Skip to content

Module dcm2bids.dcm2bids_gen⚓︎

Reorganising NIfTI files from dcm2niix into the Brain Imaging Data Structure

View Source
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
# -*- coding: utf-8 -*-

"""

Reorganising NIfTI files from dcm2niix into the Brain Imaging Data Structure

"""

import logging

import os

from pathlib import Path

from glob import glob

import shutil

from dcm2bids.dcm2niix_gen import Dcm2niixGen

from dcm2bids.sidecar import Sidecar, SidecarPairing

from dcm2bids.participant import Participant

from dcm2bids.utils.utils import DEFAULT, run_shell_command

from dcm2bids.utils.io import load_json, save_json, valid_path

class Dcm2BidsGen(object):

    """ Object to handle dcm2bids execution steps

    Args:

        dicom_dir (str or list): A list of folder with dicoms to convert

        participant (str): Label of your participant

        config (path): Path to a dcm2bids configuration file

        output_dir (path): Path to the BIDS base folder

        session (str): Optional label of a session

        clobber (boolean): Overwrite file if already in BIDS folder

        force_dcm2bids (boolean): Forces a cleaning of a previous execution of

                                 dcm2bids

        log_level (str): logging level

    """

    def __init__(

        self,

        dicom_dir,

        participant,

        config,

        output_dir=DEFAULT.output_dir,

        bids_validate=DEFAULT.bids_validate,

        auto_extract_entities=False,

        session=DEFAULT.session,

        clobber=DEFAULT.clobber,

        force_dcm2bids=DEFAULT.force_dcm2bids,

        skip_dcm2niix=DEFAULT.skip_dcm2niix,

        log_level=DEFAULT.logLevel,

        **_

    ):

        self._dicom_dirs = []

        self.dicom_dirs = dicom_dir

        self.bids_dir = valid_path(output_dir, type="folder")

        self.config = load_json(valid_path(config, type="file"))

        self.participant = Participant(participant, session)

        self.clobber = clobber

        self.bids_validate = bids_validate

        self.auto_extract_entities = auto_extract_entities

        self.force_dcm2bids = force_dcm2bids

        self.skip_dcm2niix = skip_dcm2niix

        self.logLevel = log_level

        self.logger = logging.getLogger(__name__)

    @property

    def dicom_dirs(self):

        """List of DICOMs directories"""

        return self._dicom_dirs

    @dicom_dirs.setter

    def dicom_dirs(self, value):

        dicom_dirs = value if isinstance(value, list) else [value]

        valid_dirs = [valid_path(_dir, "folder") for _dir in dicom_dirs]

        self._dicom_dirs = valid_dirs

    def run(self):

        """Run dcm2bids"""

        dcm2niix = Dcm2niixGen(

            self.dicom_dirs,

            self.bids_dir,

            self.participant,

            self.skip_dcm2niix,

            self.config.get("dcm2niixOptions", DEFAULT.dcm2niixOptions),

        )

        dcm2niix.run(self.force_dcm2bids)

        sidecars = []

        for filename in dcm2niix.sidecarFiles:

            sidecars.append(

                Sidecar(filename, self.config.get("compKeys", DEFAULT.compKeys))

            )

        sidecars = sorted(sidecars)

        parser = SidecarPairing(

            sidecars,

            self.config["descriptions"],

            self.config.get("extractors", {}),

            self.auto_extract_entities,

            self.config.get("search_method", DEFAULT.search_method),

            self.config.get("case_sensitive", DEFAULT.case_sensitive),

            self.config.get("dup_method", DEFAULT.dup_method),

            self.config.get("post_op",  DEFAULT.post_op)

        )

        parser.build_graph()

        parser.build_acquisitions(self.participant)

        parser.find_runs()

        output_dir = os.path.join(self.bids_dir, self.participant.directory)

        if parser.acquisitions:

            self.logger.info("Moving acquisitions into BIDS "

                             f"folder \"{output_dir}\".\n")

        else:

            self.logger.warning("No pairing was found. "

                                f"BIDS folder \"{output_dir}\" won't be created. "

                                "Check your config file.\n".upper())

        idList = {}

        for acq in parser.acquisitions:

            idList = self.move(acq, idList, parser.post_op)

        if self.bids_validate:

            try:

                self.logger.info(f"Validate if {self.output_dir} is BIDS valid.")

                self.logger.info("Use bids-validator version: ")

                run_shell_command(['bids-validator', '-v'])

                run_shell_command(['bids-validator', self.bids_dir])

            except Exception:

                self.logger.error("The bids-validator does not seem to work properly. "

                                  "The bids-validator may not be installed on your "

                                  "computer. Please check: "

                                  "https://github.com/bids-standard/bids-validator.")

    def move(self, acq, idList, post_op):

        """Move an acquisition to BIDS format"""

        for srcFile in sorted(glob(f"{acq.srcRoot}.*"), reverse=True):

            ext = Path(srcFile).suffixes

            ext = [curr_ext for curr_ext in ext if curr_ext in ['.nii', '.gz',

                                                                '.json',

                                                                '.bval', '.bvec']]

            dstFile = (self.bids_dir / acq.dstRoot).with_suffix("".join(ext))

            dstFile.parent.mkdir(parents=True, exist_ok=True)

            # checking if destination file exists

            if dstFile.exists():

                self.logger.info(f"'{dstFile}' already exists")

                if self.clobber:

                    self.logger.info("Overwriting because of --clobber option")

                else:

                    self.logger.info("Use --clobber option to overwrite")

                    continue

            # Populate idList

            if '.nii' in ext:

                if acq.id in idList:

                    idList[acq.id].append(os.path.join(acq.participant.name,

                                                       acq.dstId + "".join(ext)))

                else:

                    idList[acq.id] = [os.path.join(acq.participant.name,

                                                   acq.dstId + "".join(ext))]

                for curr_post_op in post_op:

                    if acq.datatype in curr_post_op['datatype'] or 'any' in curr_post_op['datatype']:

                        if acq.suffix in curr_post_op['suffix'] or '_any' in curr_post_op['suffix']:

                            cmd = curr_post_op['cmd'].replace('src_file', str(srcFile))

                            # If custom entities it means that the user

                            # wants to have both versions

                            # before and after post_op

                            if 'custom_entities' in curr_post_op:

                                acq.setExtraDstFile(curr_post_op["custom_entities"])

                                extraDstFile = self.bids_dir / acq.extraDstFile

                                # Copy json file with this new set of custom entities.

                                shutil.copy(

                                    str(srcFile).replace("".join(ext), ".json"),

                                    f"{str(extraDstFile)}.json",

                                )

                                cmd = cmd.replace('dst_file',

                                                  str(extraDstFile) + ''.join(ext))

                            else:

                                cmd = cmd.replace('dst_file', str(dstFile))

                            run_shell_command(cmd.split())

                            continue

            if ".json" in ext:

                data = acq.dstSidecarData(idList)

                save_json(dstFile, data)

                os.remove(srcFile)

            # just move

            elif not os.path.exists(dstFile):

                os.rename(srcFile, dstFile)

        return idList

Classes⚓︎

Dcm2BidsGen⚓︎

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Dcm2BidsGen(
    dicom_dir,
    participant,
    config,
    output_dir=PosixPath('/home/runner/work/Dcm2Bids/Dcm2Bids'),
    bids_validate=False,
    auto_extract_entities=False,
    session='',
    clobber=False,
    force_dcm2bids=False,
    skip_dcm2niix=False,
    log_level='WARNING',
    **_
)

Object to handle dcm2bids execution steps

Attributes⚓︎

Name Type Description Default
dicom_dir str or list A list of folder with dicoms to convert None
participant str Label of your participant None
config path Path to a dcm2bids configuration file None
output_dir path Path to the BIDS base folder None
session str Optional label of a session None
clobber boolean Overwrite file if already in BIDS folder None
force_dcm2bids boolean Forces a cleaning of a previous execution of
dcm2bids
None
log_level str logging level None
View Source
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
class Dcm2BidsGen(object):

    """ Object to handle dcm2bids execution steps

    Args:

        dicom_dir (str or list): A list of folder with dicoms to convert

        participant (str): Label of your participant

        config (path): Path to a dcm2bids configuration file

        output_dir (path): Path to the BIDS base folder

        session (str): Optional label of a session

        clobber (boolean): Overwrite file if already in BIDS folder

        force_dcm2bids (boolean): Forces a cleaning of a previous execution of

                                 dcm2bids

        log_level (str): logging level

    """

    def __init__(

        self,

        dicom_dir,

        participant,

        config,

        output_dir=DEFAULT.output_dir,

        bids_validate=DEFAULT.bids_validate,

        auto_extract_entities=False,

        session=DEFAULT.session,

        clobber=DEFAULT.clobber,

        force_dcm2bids=DEFAULT.force_dcm2bids,

        skip_dcm2niix=DEFAULT.skip_dcm2niix,

        log_level=DEFAULT.logLevel,

        **_

    ):

        self._dicom_dirs = []

        self.dicom_dirs = dicom_dir

        self.bids_dir = valid_path(output_dir, type="folder")

        self.config = load_json(valid_path(config, type="file"))

        self.participant = Participant(participant, session)

        self.clobber = clobber

        self.bids_validate = bids_validate

        self.auto_extract_entities = auto_extract_entities

        self.force_dcm2bids = force_dcm2bids

        self.skip_dcm2niix = skip_dcm2niix

        self.logLevel = log_level

        self.logger = logging.getLogger(__name__)

    @property

    def dicom_dirs(self):

        """List of DICOMs directories"""

        return self._dicom_dirs

    @dicom_dirs.setter

    def dicom_dirs(self, value):

        dicom_dirs = value if isinstance(value, list) else [value]

        valid_dirs = [valid_path(_dir, "folder") for _dir in dicom_dirs]

        self._dicom_dirs = valid_dirs

    def run(self):

        """Run dcm2bids"""

        dcm2niix = Dcm2niixGen(

            self.dicom_dirs,

            self.bids_dir,

            self.participant,

            self.skip_dcm2niix,

            self.config.get("dcm2niixOptions", DEFAULT.dcm2niixOptions),

        )

        dcm2niix.run(self.force_dcm2bids)

        sidecars = []

        for filename in dcm2niix.sidecarFiles:

            sidecars.append(

                Sidecar(filename, self.config.get("compKeys", DEFAULT.compKeys))

            )

        sidecars = sorted(sidecars)

        parser = SidecarPairing(

            sidecars,

            self.config["descriptions"],

            self.config.get("extractors", {}),

            self.auto_extract_entities,

            self.config.get("search_method", DEFAULT.search_method),

            self.config.get("case_sensitive", DEFAULT.case_sensitive),

            self.config.get("dup_method", DEFAULT.dup_method),

            self.config.get("post_op",  DEFAULT.post_op)

        )

        parser.build_graph()

        parser.build_acquisitions(self.participant)

        parser.find_runs()

        output_dir = os.path.join(self.bids_dir, self.participant.directory)

        if parser.acquisitions:

            self.logger.info("Moving acquisitions into BIDS "

                             f"folder \"{output_dir}\".\n")

        else:

            self.logger.warning("No pairing was found. "

                                f"BIDS folder \"{output_dir}\" won't be created. "

                                "Check your config file.\n".upper())

        idList = {}

        for acq in parser.acquisitions:

            idList = self.move(acq, idList, parser.post_op)

        if self.bids_validate:

            try:

                self.logger.info(f"Validate if {self.output_dir} is BIDS valid.")

                self.logger.info("Use bids-validator version: ")

                run_shell_command(['bids-validator', '-v'])

                run_shell_command(['bids-validator', self.bids_dir])

            except Exception:

                self.logger.error("The bids-validator does not seem to work properly. "

                                  "The bids-validator may not be installed on your "

                                  "computer. Please check: "

                                  "https://github.com/bids-standard/bids-validator.")

    def move(self, acq, idList, post_op):

        """Move an acquisition to BIDS format"""

        for srcFile in sorted(glob(f"{acq.srcRoot}.*"), reverse=True):

            ext = Path(srcFile).suffixes

            ext = [curr_ext for curr_ext in ext if curr_ext in ['.nii', '.gz',

                                                                '.json',

                                                                '.bval', '.bvec']]

            dstFile = (self.bids_dir / acq.dstRoot).with_suffix("".join(ext))

            dstFile.parent.mkdir(parents=True, exist_ok=True)

            # checking if destination file exists

            if dstFile.exists():

                self.logger.info(f"'{dstFile}' already exists")

                if self.clobber:

                    self.logger.info("Overwriting because of --clobber option")

                else:

                    self.logger.info("Use --clobber option to overwrite")

                    continue

            # Populate idList

            if '.nii' in ext:

                if acq.id in idList:

                    idList[acq.id].append(os.path.join(acq.participant.name,

                                                       acq.dstId + "".join(ext)))

                else:

                    idList[acq.id] = [os.path.join(acq.participant.name,

                                                   acq.dstId + "".join(ext))]

                for curr_post_op in post_op:

                    if acq.datatype in curr_post_op['datatype'] or 'any' in curr_post_op['datatype']:

                        if acq.suffix in curr_post_op['suffix'] or '_any' in curr_post_op['suffix']:

                            cmd = curr_post_op['cmd'].replace('src_file', str(srcFile))

                            # If custom entities it means that the user

                            # wants to have both versions

                            # before and after post_op

                            if 'custom_entities' in curr_post_op:

                                acq.setExtraDstFile(curr_post_op["custom_entities"])

                                extraDstFile = self.bids_dir / acq.extraDstFile

                                # Copy json file with this new set of custom entities.

                                shutil.copy(

                                    str(srcFile).replace("".join(ext), ".json"),

                                    f"{str(extraDstFile)}.json",

                                )

                                cmd = cmd.replace('dst_file',

                                                  str(extraDstFile) + ''.join(ext))

                            else:

                                cmd = cmd.replace('dst_file', str(dstFile))

                            run_shell_command(cmd.split())

                            continue

            if ".json" in ext:

                data = acq.dstSidecarData(idList)

                save_json(dstFile, data)

                os.remove(srcFile)

            # just move

            elif not os.path.exists(dstFile):

                os.rename(srcFile, dstFile)

        return idList

Instance variables⚓︎

1
dicom_dirs

List of DICOMs directories

Methods⚓︎

move⚓︎

1
2
3
4
5
6
def move(
    self,
    acq,
    idList,
    post_op
)

Move an acquisition to BIDS format

View Source
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
    def move(self, acq, idList, post_op):

        """Move an acquisition to BIDS format"""

        for srcFile in sorted(glob(f"{acq.srcRoot}.*"), reverse=True):

            ext = Path(srcFile).suffixes

            ext = [curr_ext for curr_ext in ext if curr_ext in ['.nii', '.gz',

                                                                '.json',

                                                                '.bval', '.bvec']]

            dstFile = (self.bids_dir / acq.dstRoot).with_suffix("".join(ext))

            dstFile.parent.mkdir(parents=True, exist_ok=True)

            # checking if destination file exists

            if dstFile.exists():

                self.logger.info(f"'{dstFile}' already exists")

                if self.clobber:

                    self.logger.info("Overwriting because of --clobber option")

                else:

                    self.logger.info("Use --clobber option to overwrite")

                    continue

            # Populate idList

            if '.nii' in ext:

                if acq.id in idList:

                    idList[acq.id].append(os.path.join(acq.participant.name,

                                                       acq.dstId + "".join(ext)))

                else:

                    idList[acq.id] = [os.path.join(acq.participant.name,

                                                   acq.dstId + "".join(ext))]

                for curr_post_op in post_op:

                    if acq.datatype in curr_post_op['datatype'] or 'any' in curr_post_op['datatype']:

                        if acq.suffix in curr_post_op['suffix'] or '_any' in curr_post_op['suffix']:

                            cmd = curr_post_op['cmd'].replace('src_file', str(srcFile))

                            # If custom entities it means that the user

                            # wants to have both versions

                            # before and after post_op

                            if 'custom_entities' in curr_post_op:

                                acq.setExtraDstFile(curr_post_op["custom_entities"])

                                extraDstFile = self.bids_dir / acq.extraDstFile

                                # Copy json file with this new set of custom entities.

                                shutil.copy(

                                    str(srcFile).replace("".join(ext), ".json"),

                                    f"{str(extraDstFile)}.json",

                                )

                                cmd = cmd.replace('dst_file',

                                                  str(extraDstFile) + ''.join(ext))

                            else:

                                cmd = cmd.replace('dst_file', str(dstFile))

                            run_shell_command(cmd.split())

                            continue

            if ".json" in ext:

                data = acq.dstSidecarData(idList)

                save_json(dstFile, data)

                os.remove(srcFile)

            # just move

            elif not os.path.exists(dstFile):

                os.rename(srcFile, dstFile)

        return idList

run⚓︎

1
2
3
def run(
    self
)

Run dcm2bids

View Source
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
    def run(self):

        """Run dcm2bids"""

        dcm2niix = Dcm2niixGen(

            self.dicom_dirs,

            self.bids_dir,

            self.participant,

            self.skip_dcm2niix,

            self.config.get("dcm2niixOptions", DEFAULT.dcm2niixOptions),

        )

        dcm2niix.run(self.force_dcm2bids)

        sidecars = []

        for filename in dcm2niix.sidecarFiles:

            sidecars.append(

                Sidecar(filename, self.config.get("compKeys", DEFAULT.compKeys))

            )

        sidecars = sorted(sidecars)

        parser = SidecarPairing(

            sidecars,

            self.config["descriptions"],

            self.config.get("extractors", {}),

            self.auto_extract_entities,

            self.config.get("search_method", DEFAULT.search_method),

            self.config.get("case_sensitive", DEFAULT.case_sensitive),

            self.config.get("dup_method", DEFAULT.dup_method),

            self.config.get("post_op",  DEFAULT.post_op)

        )

        parser.build_graph()

        parser.build_acquisitions(self.participant)

        parser.find_runs()

        output_dir = os.path.join(self.bids_dir, self.participant.directory)

        if parser.acquisitions:

            self.logger.info("Moving acquisitions into BIDS "

                             f"folder \"{output_dir}\".\n")

        else:

            self.logger.warning("No pairing was found. "

                                f"BIDS folder \"{output_dir}\" won't be created. "

                                "Check your config file.\n".upper())

        idList = {}

        for acq in parser.acquisitions:

            idList = self.move(acq, idList, parser.post_op)

        if self.bids_validate:

            try:

                self.logger.info(f"Validate if {self.output_dir} is BIDS valid.")

                self.logger.info("Use bids-validator version: ")

                run_shell_command(['bids-validator', '-v'])

                run_shell_command(['bids-validator', self.bids_dir])

            except Exception:

                self.logger.error("The bids-validator does not seem to work properly. "

                                  "The bids-validator may not be installed on your "

                                  "computer. Please check: "

                                  "https://github.com/bids-standard/bids-validator.")

Last update: 2024-07-23
Created: 2024-07-23