Skip to content

Module dcm2bids⚓︎

dcm2bids


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
# -*- coding: utf-8 -*-

"""

dcm2bids

--------

Reorganising NIfTI files from dcm2niix into the Brain Imaging Data Structure

"""

from .dcm2bids import Dcm2bids

from .scaffold import scaffold

from .version import __version__

__all__ = ["__version__", "Dcm2bids", "scaffold"]

Sub-modules⚓︎

Variables⚓︎

1
__version__

Functions⚓︎

scaffold⚓︎

1
2
3
def scaffold(
    output_dir_override: Optional[str] = None
)

scaffold entry point

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
def scaffold(output_dir_override: Optional[str] = None):

    """scaffold entry point"""

    args = _get_arguments()

    output_dir_ = output_dir_override if output_dir_override is not None else args.output_dir

    for _ in ["code", "derivatives", "sourcedata"]:

        os.makedirs(os.path.join(output_dir_, _), exist_ok=True)

    for _ in [

        "dataset_description.json",

        "participants.json",

        "participants.tsv",

        "README",

    ]:

        dest = os.path.join(output_dir_, _)

        with resources.path(__name__, _) as src:

            shutil.copyfile(src, dest)

    with resources.path(__name__, "CHANGES") as changes_template:

        with open(changes_template) as _:

            data = _.read().format(datetime.date.today().strftime("%Y-%m-%d"))

        write_txt(

            os.path.join(output_dir_, "CHANGES"),

            data.split("\n")[:-1],

    )

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-06-17
Back to top