Skip to content

Module dcm2bids.cli.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
 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
#!/usr/bin/env python3

# -*- coding: utf-8 -*-

"""

Reorganising NIfTI files from dcm2niix into the Brain Imaging Data Structure

"""

import argparse

import logging

import platform

import sys

import os

from pathlib import Path

from datetime import datetime

from dcm2bids.dcm2bids_gen import Dcm2BidsGen

from dcm2bids.utils.utils import DEFAULT

from dcm2bids.utils.tools import dcm2niix_version, check_latest

from dcm2bids.utils.schema import load_schema

from dcm2bids.participant import Participant

from dcm2bids.utils.logger import setup_logging

from dcm2bids.version import __version__

def _build_arg_parser():

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

                                formatter_class=argparse.RawTextHelpFormatter)

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

                   required=True, nargs="+",

                   help="Path to one or more directories or archives"

                        f" ({DEFAULT.arch_extensions}) containing the DICOM files for a"

                        " single participant and session to be converted to BIDS."

                    )

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

                   required=True,

                   help="Participant ID to be used in the BIDS dataset filenames"

                        " (e.g. sub-<PARTICIPANT>)."

    )

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

                   required=False,

                   default=DEFAULT.cli_session,

                   help="Session ID to be used in the BIDS dataset filenames"

                        " (e.g. ses-<SESSION>). If not provided, no session"

                        " entity will be added to the BIDS filenames."

                   )

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

                   required=True,

                   help="JSON configuration that specifies additional parameters for"

                        " BIDS conversion. See the documentation for more information:"

                        f" \nhttps://unfmontreal.github.io/Dcm2Bids/{__version__}/how-to/create-config-file/"  # noqa: E501

                )

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

                   required=False,

                   default=DEFAULT.output_dir,

                   help="Output BIDS directory. Defaults to the current working directory."

                )

    g = p.add_mutually_exclusive_group()

    g.add_argument("--auto_extract_entities",

                   action='store_true',

                   help="If set, it will automatically try to extract entity "

                   "information [task, dir, echo] based on the suffix and datatype."

                   " Default is [%(default)s]")

    g.add_argument("--do_not_reorder_entities",

                   action='store_true',

                   help="If set, it will not reorder entities according to the relative "

                        "ordering indicated in the BIDS specification and use the "

                        "order defined in custom_entities by the user.\n"

                        "Cannot be used with --auto_extract_entities. "

                        " Default is [%(default)s]")

    p.add_argument("-b", "--bids_version",

                   default=None,

                   help=(

            "Set the BIDS specification version to follow (e.g. 'v1.11.1', 'stable', 'latest' or 'default')."

            "\nThis controls which BIDS schema and rules dcm2bids uses for automatic entity extraction and ordering."

            "\nIf not provided, dcm2bids uses the 'default' BIDS spec for reproducible, offline-friendly behavior."

            "\nFor long-running or shared pipelines, consider pinning a specific tag (e.g. 'v1.11.1')."

            "\nWhen internet is available, it will check once whether the remote 'stable' is newer and, if so, \n"

            "suggest updating to that specific version tag."

            ),

        )

    p.add_argument("--bids_validate",

                   action='store_true',

                   help="If set, once your conversion is done it "

                        "will check if your output folder is BIDS valid. [%(default)s]"

                        "\nbids-validator needs to be installed check: "

                        f"{DEFAULT.link_bids_validator}")

    p.add_argument("--force_dcm2bids",

                   action="store_true",

                   help="Overwrite previous temporary dcm2bids "

                        "output if it exists.")

    p.add_argument("--skip_dcm2niix",

                   action="store_true",

                   help="Skip dcm2niix conversion. "

                        "Option -d should contains NIFTI and json files.")

    p.add_argument("--clobber",

                   action="store_true",

                   help="Overwrite output if it exists.")

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

                   required=False,

                   default=DEFAULT.cli_log_level,

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

                   help="Set logging level to the console."

                        " The default level is [%(default)s]"

                )

    p.add_argument("-v", "--version",

                   action="version",

                   # This uses version.__BIDSversion__, which reflects the bundled schema version.

                   version=(

                        f"dcm2bids version:\t{__version__}\n"

                        f"default BIDS version:\t{DEFAULT.bids_version} "

                        "unless overridden by --bids_version."

                    ),

                   help="Report dcm2bids version and the default BIDS specification version it follows by default."

                   )

    return p

def main():

    parser = _build_arg_parser()

    args = parser.parse_args()

    participant = Participant(args.participant, args.session)

    log_dir = Path(args.output_dir) / DEFAULT.tmp_dir_name / "log"

    log_file = (log_dir /

                f"{participant.prefix}_{datetime.now().strftime('%Y%m%d-%H%M%S')}.log")

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

    setup_logging(args.log_level, log_file)

    logger = logging.getLogger(__name__)

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

    logger.info("Running the following command: " + " ".join(sys.argv))

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

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

    logger.info(f"dcm2bids version: {__version__}")

    logger.info(f"dcm2niix version: {dcm2niix_version()}")

    logger.info("Checking for software update")

    check_latest("dcm2bids", log_dir=log_dir)

    if not args.skip_dcm2niix:

        check_latest("dcm2niix", log_dir=log_dir)

    schema, derived_entities = load_schema(args.bids_version, log_dir=log_dir)

    # Update the DEFAULT based on the requested version directly, otherwise uses default values

    if args.bids_version is not None:

        DEFAULT.bids_version = schema["bids_version"]

        DEFAULT.entityTableKeys = derived_entities.get("entity_table_keys",

                                              DEFAULT.entityTableKeys)

        DEFAULT.auto_entities = derived_entities.get("auto_entities",

                                                DEFAULT.auto_entities)

    logger.info(f"participant: {participant.name}")

    if participant.session:

        logger.info(f"session: {participant.session}")

    logger.info(f"config: {os.path.realpath(args.config)}")

    logger.info(f"BIDS directory: {os.path.realpath(args.output_dir)}")

    logger.info(f"Auto extract entities: {args.auto_extract_entities}")

    logger.info(f"Reorder entities: {not args.do_not_reorder_entities}")

    logger.info(f"Validate BIDS: {args.bids_validate}\n")

    app = Dcm2BidsGen(**vars(args)).run()

    logger.info(f"Logs saved in {log_file}")

    logger.info("--- dcm2bids end ---")

    return app

if __name__ == "__main__":

    main()

Functions⚓︎

main⚓︎

1
2
3
def main(

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

    parser = _build_arg_parser()

    args = parser.parse_args()

    participant = Participant(args.participant, args.session)

    log_dir = Path(args.output_dir) / DEFAULT.tmp_dir_name / "log"

    log_file = (log_dir /

                f"{participant.prefix}_{datetime.now().strftime('%Y%m%d-%H%M%S')}.log")

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

    setup_logging(args.log_level, log_file)

    logger = logging.getLogger(__name__)

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

    logger.info("Running the following command: " + " ".join(sys.argv))

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

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

    logger.info(f"dcm2bids version: {__version__}")

    logger.info(f"dcm2niix version: {dcm2niix_version()}")

    logger.info("Checking for software update")

    check_latest("dcm2bids", log_dir=log_dir)

    if not args.skip_dcm2niix:

        check_latest("dcm2niix", log_dir=log_dir)

    schema, derived_entities = load_schema(args.bids_version, log_dir=log_dir)

    # Update the DEFAULT based on the requested version directly, otherwise uses default values

    if args.bids_version is not None:

        DEFAULT.bids_version = schema["bids_version"]

        DEFAULT.entityTableKeys = derived_entities.get("entity_table_keys",

                                              DEFAULT.entityTableKeys)

        DEFAULT.auto_entities = derived_entities.get("auto_entities",

                                                DEFAULT.auto_entities)

    logger.info(f"participant: {participant.name}")

    if participant.session:

        logger.info(f"session: {participant.session}")

    logger.info(f"config: {os.path.realpath(args.config)}")

    logger.info(f"BIDS directory: {os.path.realpath(args.output_dir)}")

    logger.info(f"Auto extract entities: {args.auto_extract_entities}")

    logger.info(f"Reorder entities: {not args.do_not_reorder_entities}")

    logger.info(f"Validate BIDS: {args.bids_validate}\n")

    app = Dcm2BidsGen(**vars(args)).run()

    logger.info(f"Logs saved in {log_file}")

    logger.info("--- dcm2bids end ---")

    return app