Skip to content

Module dcm2bids.dcm2bids⚓︎

Reorganising NIfTI files from dcm2niix into the Brain Imaging Data Structure

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
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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
# -*- coding: utf-8 -*-

"""

Reorganising NIfTI files from dcm2niix into the Brain Imaging Data Structure

"""

import argparse

import logging

import os

from pathlib import Path

import platform

import sys

from datetime import datetime

from glob import glob

from dcm2bids.dcm2niix import Dcm2niix

from dcm2bids.logger import setup_logging

from dcm2bids.sidecar import Sidecar, SidecarPairing

from dcm2bids.structure import Participant

from dcm2bids.utils import (DEFAULT, load_json, save_json,

                            splitext_, run_shell_command, valid_path)

from dcm2bids.version import __version__, check_latest, dcm2niix_version

class Dcm2bids(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

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

                                 dcm2niix

        log_level (str): logging level

    """

    def __init__(

        self,

        dicom_dir,

        participant,

        config,

        output_dir=DEFAULT.outputDir,

        session=DEFAULT.session,

        clobber=DEFAULT.clobber,

        forceDcm2niix=DEFAULT.forceDcm2niix,

        log_level=DEFAULT.logLevel,

        **_

    ):

        self._dicomDirs = []

        self.dicomDirs = dicom_dir

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

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

        self.participant = Participant(participant, session)

        self.clobber = clobber

        self.forceDcm2niix = forceDcm2niix

        self.logLevel = log_level

        # logging setup

        self.set_logger()

        self.logger.info("--- dcm2bids start ---")

        self.logger.info("OS:version: %s", platform.platform())

        self.logger.info("python:version: %s", sys.version.replace("\n", ""))

        self.logger.info("dcm2bids:version: %s", __version__)

        self.logger.info("dcm2niix:version: %s", dcm2niix_version())

        self.logger.info("participant: %s", self.participant.name)

        self.logger.info("session: %s", self.participant.session)

        self.logger.info("config: %s", os.path.realpath(config))

        self.logger.info("BIDS directory: %s", os.path.realpath(output_dir))

    @property

    def dicomDirs(self):

        """List of DICOMs directories"""

        return self._dicomDirs

    @dicomDirs.setter

    def dicomDirs(self, value):

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

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

        self._dicomDirs = valid_dirs

    def set_logger(self):

        """ Set a basic logger"""

        logDir = self.bidsDir / DEFAULT.tmpDirName / "log"

        logFile = logDir / f"{self.participant.prefix}_{datetime.now().isoformat().replace(':', '')}.log"

        logDir.mkdir(parents=True, exist_ok=True)

        setup_logging(self.logLevel, logFile)

        self.logger = logging.getLogger(__name__)

    def run(self):

        """Run dcm2bids"""

        dcm2niix = Dcm2niix(

            self.dicomDirs,

            self.bidsDir,

            self.participant,

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

        )

        check_latest()

        check_latest("dcm2niix")

        dcm2niix.run(self.forceDcm2niix)

        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("searchMethod", DEFAULT.searchMethod),

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

        )

        parser.build_graph()

        parser.build_acquisitions(self.participant)

        parser.find_runs()

        self.logger.info("moving acquisitions into BIDS folder")

        intendedForList = [[] for i in range(len(parser.descriptions))]

        for acq in parser.acquisitions:

            acq.setDstFile()

            intendedForList = self.move(acq, intendedForList)

    def move(self, acquisition, intendedForList):

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

        for srcFile in glob(acquisition.srcRoot + ".*"):

            ext = Path(srcFile).suffixes

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

                                                                '.json',

                                                                '.bval','.bvec']]

            dstFile = (self.bidsDir / acquisition.dstRoot).with_suffix("".join(ext))

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

            # checking if destination file exists

            if dstFile.exists():

                self.logger.info("'%s' already exists", dstFile)

                if self.clobber:

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

                else:

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

                    continue

            # it's an anat nifti file and the user using a deface script

            if (

                self.config.get("defaceTpl")

                and acquisition.dataType == "func"

                and ".nii" in ext

                ):

                try:

                    os.remove(dstFile)

                except FileNotFoundError:

                    pass

                defaceTpl = self.config.get("defaceTpl")

                cmd = [w.replace('srcFile', srcFile) for w in defaceTpl]

                cmd = [w.replace('dstFile', dstFile) for w in defaceTpl]

                run_shell_command(cmd)

                intendedForList[acquisition.indexSidecar].append(acquisition.dstIntendedFor + "".join(ext))

            elif ".json" in ext:

                data = acquisition.dstSidecarData(self.config["descriptions"],

                                                  intendedForList)

                save_json(dstFile, data)

                os.remove(srcFile)

            # just move

            else:

                os.rename(srcFile, dstFile)

            intendedFile = acquisition.dstIntendedFor + ".nii.gz"

            if intendedFile not in intendedForList[acquisition.indexSidecar]:

                intendedForList[acquisition.indexSidecar].append(intendedFile)

        return intendedForList

def _build_arg_parser():

    p = argparse.ArgumentParser(description=__doc__, epilog=DEFAULT.EPILOG,

                                formatter_class=argparse.RawTextHelpFormatter)

    p.add_argument("-d", "--dicom_dir",

                   type=Path, required=True, nargs="+",

                   help="DICOM directory(ies).")

    p.add_argument("-p", "--participant",

                   required=True,

                   help="Participant ID.")

    p.add_argument("-s", "--session",

                   required=False,

                   default="",

                   help="Session ID.")

    p.add_argument("-c", "--config",

                   type=Path,

                   required=True,

                   help="JSON configuration file (see example/config.json).")

    p.add_argument("-o", "--output_dir",

                   required=False,

                   type=Path,

                   default=Path.cwd(),

                   help="Output BIDS directory. (Default: %(default)s)")

    p.add_argument("--forceDcm2niix",

                   action="store_true",

                   help="Overwrite previous temporary dcm2niix "

                        "output if it exists.")

    p.add_argument("--clobber",

                   action="store_true",

                   help="Overwrite output if it exists.")

    p.add_argument("-l", "--log_level",

                   required=False,

                   default=DEFAULT.cliLogLevel,

                   choices=["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"],

                   help="Set logging level. [%(default)s]")

    return p

def main():

    """Let's go"""

    parser = _build_arg_parser()

    args = parser.parse_args()

    app = Dcm2bids(**vars(args))

    return app.run()

if __name__ == "__main__":

    sys.exit(main())

Functions⚓︎

main⚓︎

1
2
3
def main(

)

Let's go

View Source
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
def main():

    """Let's go"""

    parser = _build_arg_parser()

    args = parser.parse_args()

    app = Dcm2bids(**vars(args))

    return app.run()

Classes⚓︎

Dcm2bids⚓︎

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Dcm2bids(
    dicom_dir,
    participant,
    config,
    output_dir=PosixPath('/home/runner/work/Dcm2Bids/Dcm2Bids'),
    session='',
    clobber=False,
    forceDcm2niix=False,
    log_level='WARNING',
    **_
)

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
forceDcm2niix boolean Forces a cleaning of a previous execution of
dcm2niix 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
class Dcm2bids(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

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

                                 dcm2niix

        log_level (str): logging level

    """

    def __init__(

        self,

        dicom_dir,

        participant,

        config,

        output_dir=DEFAULT.outputDir,

        session=DEFAULT.session,

        clobber=DEFAULT.clobber,

        forceDcm2niix=DEFAULT.forceDcm2niix,

        log_level=DEFAULT.logLevel,

        **_

    ):

        self._dicomDirs = []

        self.dicomDirs = dicom_dir

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

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

        self.participant = Participant(participant, session)

        self.clobber = clobber

        self.forceDcm2niix = forceDcm2niix

        self.logLevel = log_level

        # logging setup

        self.set_logger()

        self.logger.info("--- dcm2bids start ---")

        self.logger.info("OS:version: %s", platform.platform())

        self.logger.info("python:version: %s", sys.version.replace("\n", ""))

        self.logger.info("dcm2bids:version: %s", __version__)

        self.logger.info("dcm2niix:version: %s", dcm2niix_version())

        self.logger.info("participant: %s", self.participant.name)

        self.logger.info("session: %s", self.participant.session)

        self.logger.info("config: %s", os.path.realpath(config))

        self.logger.info("BIDS directory: %s", os.path.realpath(output_dir))

    @property

    def dicomDirs(self):

        """List of DICOMs directories"""

        return self._dicomDirs

    @dicomDirs.setter

    def dicomDirs(self, value):

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

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

        self._dicomDirs = valid_dirs

    def set_logger(self):

        """ Set a basic logger"""

        logDir = self.bidsDir / DEFAULT.tmpDirName / "log"

        logFile = logDir / f"{self.participant.prefix}_{datetime.now().isoformat().replace(':', '')}.log"

        logDir.mkdir(parents=True, exist_ok=True)

        setup_logging(self.logLevel, logFile)

        self.logger = logging.getLogger(__name__)

    def run(self):

        """Run dcm2bids"""

        dcm2niix = Dcm2niix(

            self.dicomDirs,

            self.bidsDir,

            self.participant,

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

        )

        check_latest()

        check_latest("dcm2niix")

        dcm2niix.run(self.forceDcm2niix)

        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("searchMethod", DEFAULT.searchMethod),

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

        )

        parser.build_graph()

        parser.build_acquisitions(self.participant)

        parser.find_runs()

        self.logger.info("moving acquisitions into BIDS folder")

        intendedForList = [[] for i in range(len(parser.descriptions))]

        for acq in parser.acquisitions:

            acq.setDstFile()

            intendedForList = self.move(acq, intendedForList)

    def move(self, acquisition, intendedForList):

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

        for srcFile in glob(acquisition.srcRoot + ".*"):

            ext = Path(srcFile).suffixes

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

                                                                '.json',

                                                                '.bval','.bvec']]

            dstFile = (self.bidsDir / acquisition.dstRoot).with_suffix("".join(ext))

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

            # checking if destination file exists

            if dstFile.exists():

                self.logger.info("'%s' already exists", dstFile)

                if self.clobber:

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

                else:

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

                    continue

            # it's an anat nifti file and the user using a deface script

            if (

                self.config.get("defaceTpl")

                and acquisition.dataType == "func"

                and ".nii" in ext

                ):

                try:

                    os.remove(dstFile)

                except FileNotFoundError:

                    pass

                defaceTpl = self.config.get("defaceTpl")

                cmd = [w.replace('srcFile', srcFile) for w in defaceTpl]

                cmd = [w.replace('dstFile', dstFile) for w in defaceTpl]

                run_shell_command(cmd)

                intendedForList[acquisition.indexSidecar].append(acquisition.dstIntendedFor + "".join(ext))

            elif ".json" in ext:

                data = acquisition.dstSidecarData(self.config["descriptions"],

                                                  intendedForList)

                save_json(dstFile, data)

                os.remove(srcFile)

            # just move

            else:

                os.rename(srcFile, dstFile)

            intendedFile = acquisition.dstIntendedFor + ".nii.gz"

            if intendedFile not in intendedForList[acquisition.indexSidecar]:

                intendedForList[acquisition.indexSidecar].append(intendedFile)

        return intendedForList

Instance variables⚓︎

1
dicomDirs

List of DICOMs directories

Methods⚓︎

move⚓︎

1
2
3
4
5
def move(
    self,
    acquisition,
    intendedForList
)

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
    def move(self, acquisition, intendedForList):

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

        for srcFile in glob(acquisition.srcRoot + ".*"):

            ext = Path(srcFile).suffixes

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

                                                                '.json',

                                                                '.bval','.bvec']]

            dstFile = (self.bidsDir / acquisition.dstRoot).with_suffix("".join(ext))

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

            # checking if destination file exists

            if dstFile.exists():

                self.logger.info("'%s' already exists", dstFile)

                if self.clobber:

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

                else:

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

                    continue

            # it's an anat nifti file and the user using a deface script

            if (

                self.config.get("defaceTpl")

                and acquisition.dataType == "func"

                and ".nii" in ext

                ):

                try:

                    os.remove(dstFile)

                except FileNotFoundError:

                    pass

                defaceTpl = self.config.get("defaceTpl")

                cmd = [w.replace('srcFile', srcFile) for w in defaceTpl]

                cmd = [w.replace('dstFile', dstFile) for w in defaceTpl]

                run_shell_command(cmd)

                intendedForList[acquisition.indexSidecar].append(acquisition.dstIntendedFor + "".join(ext))

            elif ".json" in ext:

                data = acquisition.dstSidecarData(self.config["descriptions"],

                                                  intendedForList)

                save_json(dstFile, data)

                os.remove(srcFile)

            # just move

            else:

                os.rename(srcFile, dstFile)

            intendedFile = acquisition.dstIntendedFor + ".nii.gz"

            if intendedFile not in intendedForList[acquisition.indexSidecar]:

                intendedForList[acquisition.indexSidecar].append(intendedFile)

        return intendedForList

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
    def run(self):

        """Run dcm2bids"""

        dcm2niix = Dcm2niix(

            self.dicomDirs,

            self.bidsDir,

            self.participant,

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

        )

        check_latest()

        check_latest("dcm2niix")

        dcm2niix.run(self.forceDcm2niix)

        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("searchMethod", DEFAULT.searchMethod),

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

        )

        parser.build_graph()

        parser.build_acquisitions(self.participant)

        parser.find_runs()

        self.logger.info("moving acquisitions into BIDS folder")

        intendedForList = [[] for i in range(len(parser.descriptions))]

        for acq in parser.acquisitions:

            acq.setDstFile()

            intendedForList = self.move(acq, intendedForList)

set_logger⚓︎

1
2
3
def set_logger(
    self
)

Set a basic logger

View Source
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
    def set_logger(self):

        """ Set a basic logger"""

        logDir = self.bidsDir / DEFAULT.tmpDirName / "log"

        logFile = logDir / f"{self.participant.prefix}_{datetime.now().isoformat().replace(':', '')}.log"

        logDir.mkdir(parents=True, exist_ok=True)

        setup_logging(self.logLevel, logFile)

        self.logger = logging.getLogger(__name__)

Last update: 2022-09-30
Back to top