Skip to content

Module dcm2bids.utils⚓︎

None

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

import csv

import json

import logging

import os

from pathlib import Path

import re

from collections import OrderedDict

import shlex

import shutil

from subprocess import check_output

class DEFAULT(object):

    """ Default values of the package"""

    # cli dcm2bids

    cliLogLevel = "INFO"

    EPILOG="Documentation at https://github.com/unfmontreal/Dcm2Bids"

    # dcm2bids.py

    outputDir = Path.cwd()

    session = ""  # also Participant object

    clobber = False

    forceDcm2niix = False

    defaceTpl = None

    logLevel = "WARNING"

    # dcm2niix.py

    dcm2niixOptions = "-b y -ba y -z y -f '%3s_%f_%p_%t'"

    dcm2niixVersion = "v1.0.20181125"

    # sidecar.py

    compKeys = ["SeriesNumber", "AcquisitionTime", "SidecarFilename"]

    searchMethod = "fnmatch"

    searchMethodChoices = ["fnmatch", "re"]

    runTpl = "_run-{:02d}"

    caseSensitive = True

    # Entity table:

    # https://bids-specification.readthedocs.io/en/v1.7.0/99-appendices/04-entity-table.html

    entityTableKeys = ["sub", "ses", "task", "acq", "ce", "rec", "dir",

                       "run", "mod", "echo", "flip", "inv", "mt", "part",

                       "recording"]

    # misc

    tmpDirName = "tmp_dcm2bids"

    helperDir = "helper"

def load_json(filename):

    """ Load a JSON file

    Args:

        filename (str): Path of a JSON file

    Return:

        Dictionnary of the JSON file

    """

    with open(filename, "r") as f:

        data = json.load(f, object_pairs_hook=OrderedDict)

    return data

def save_json(filename, data):

    with filename.open("w") as f:

        json.dump(data, f, indent=4)

def write_txt(filename, lines):

    with open(filename, "a") as f:

        for row in lines:

            f.write("%s\n" % row)

def write_participants(filename, participants):

    with open(filename, "w") as f:

        writer = csv.DictWriter(f, delimiter="\t", fieldnames=participants[0].keys())

        writer.writeheader()

        writer.writerows(participants)

def read_participants(filename):

    if not os.path.exists(filename):

        return []

    with open(filename, "r") as f:

        reader = csv.DictReader(f, delimiter="\t")

        return [row for row in reader]

def splitext_(path, extensions=None):

    """ Split the extension from a pathname

    Handle case with extensions with '.' in it

    Args:

        path (str): A path to split

        extensions (list): List of special extensions

    Returns:

        (root, ext): ext may be empty

    """

    if extensions is None:

        extensions = [".nii.gz"]

    for ext in extensions:

        if path.endswith(ext):

            return path[: -len(ext)], path[-len(ext) :]

    return os.path.splitext(path)

def run_shell_command(commandLine):

    """ Wrapper of subprocess.check_output

    Returns:

        Run command with arguments and return its output

    """

    logger = logging.getLogger(__name__)

    logger.info("Running %s", commandLine)

    return check_output(commandLine)

def valid_path(in_path, type="folder"):

    """Assert that file exists.

    Parameters

    ----------

    required_file: Path

        Path to be checked.

    """

    if isinstance(in_path, str):

        in_path = Path(in_path)

    if type == 'folder':

        if in_path.is_dir() or in_path.parent.is_dir():

            return in_path

        else:

            raise NotADirectoryError(in_path)

    elif type == "file":

        if in_path.is_file():

            return in_path

        else:

            raise FileNotFoundError(in_path)

    raise TypeError(type)

def assert_dirs_empty(parser, args, required):

    """

    Assert that all directories exist are empty.

    If dirs exist and not empty, and --force is used, delete dirs.

    Parameters

    ----------

    parser: argparse.ArgumentParser object

        Parser.

    args: argparse namespace

        Argument list.

    required: string or list of paths to files

        Required paths to be checked.

    create_dir: bool

        If true, create the directory if it does not exist.

    """

    def check(path):

        if not path.is_dir():

            return

        if not any(path.iterdir()):

            return

        if not args.overwrite:

            parser.error(

                f"Output directory {path} isn't empty, so some files "

                "could be overwritten or deleted.\nRerun the command with "

                "--force option to overwrite existing output files.")

        else:

            for the_file in path.iterdir():

                file_path = path / the_file

                try:

                    if file_path.is_file():

                        file_path.unlink()

                    elif file_path.is_dir():

                        shutil.rmtree(file_path)

                except Exception as e:

                    print(e)

    if isinstance(required, str) or isinstance(required, Path):

        required = [Path(required)]

    for cur_dir in required:

        check(cur_dir)

Functions⚓︎

assert_dirs_empty⚓︎

1
2
3
4
5
def assert_dirs_empty(
    parser,
    args,
    required
)

Assert that all directories exist are empty.

If dirs exist and not empty, and --force is used, delete dirs.

Parameters:

Name Type Description Default
parser argparse.ArgumentParser object Parser. None
args argparse namespace Argument list. None
required string or list of paths to files Required paths to be checked. None
create_dir bool If true, create the directory if it does not exist. 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
def assert_dirs_empty(parser, args, required):

    """

    Assert that all directories exist are empty.

    If dirs exist and not empty, and --force is used, delete dirs.

    Parameters

    ----------

    parser: argparse.ArgumentParser object

        Parser.

    args: argparse namespace

        Argument list.

    required: string or list of paths to files

        Required paths to be checked.

    create_dir: bool

        If true, create the directory if it does not exist.

    """

    def check(path):

        if not path.is_dir():

            return

        if not any(path.iterdir()):

            return

        if not args.overwrite:

            parser.error(

                f"Output directory {path} isn't empty, so some files "

                "could be overwritten or deleted.\nRerun the command with "

                "--force option to overwrite existing output files.")

        else:

            for the_file in path.iterdir():

                file_path = path / the_file

                try:

                    if file_path.is_file():

                        file_path.unlink()

                    elif file_path.is_dir():

                        shutil.rmtree(file_path)

                except Exception as e:

                    print(e)

    if isinstance(required, str) or isinstance(required, Path):

        required = [Path(required)]

    for cur_dir in required:

        check(cur_dir)

load_json⚓︎

1
2
3
def load_json(
    filename
)

Load a JSON file

Args: filename (str): Path of a JSON file

Return: Dictionnary of the JSON file

View Source
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
def load_json(filename):

    """ Load a JSON file

    Args:

        filename (str): Path of a JSON file

    Return:

        Dictionnary of the JSON file

    """

    with open(filename, "r") as f:

        data = json.load(f, object_pairs_hook=OrderedDict)

    return data

read_participants⚓︎

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

    if not os.path.exists(filename):

        return []

    with open(filename, "r") as f:

        reader = csv.DictReader(f, delimiter="\t")

        return [row for row in reader]

run_shell_command⚓︎

1
2
3
def run_shell_command(
    commandLine
)

Wrapper of subprocess.check_output

Returns:

Type Description
None Run command with arguments and return its output
View Source
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
def run_shell_command(commandLine):

    """ Wrapper of subprocess.check_output

    Returns:

        Run command with arguments and return its output

    """

    logger = logging.getLogger(__name__)

    logger.info("Running %s", commandLine)

    return check_output(commandLine)

save_json⚓︎

1
2
3
4
def save_json(
    filename,
    data
)
View Source
1
2
3
4
5
def save_json(filename, data):

    with filename.open("w") as f:

        json.dump(data, f, indent=4)

splitext_⚓︎

1
2
3
4
def splitext_(
    path,
    extensions=None
)

Split the extension from a pathname

Handle case with extensions with '.' in it

Parameters:

Name Type Description Default
path str A path to split None
extensions list List of special extensions None

Returns:

Type Description
None (root, ext): ext may be empty
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
def splitext_(path, extensions=None):

    """ Split the extension from a pathname

    Handle case with extensions with '.' in it

    Args:

        path (str): A path to split

        extensions (list): List of special extensions

    Returns:

        (root, ext): ext may be empty

    """

    if extensions is None:

        extensions = [".nii.gz"]

    for ext in extensions:

        if path.endswith(ext):

            return path[: -len(ext)], path[-len(ext) :]

    return os.path.splitext(path)

valid_path⚓︎

1
2
3
4
def valid_path(
    in_path,
    type='folder'
)

Assert that file exists.

Parameters:

Name Type Description Default
required_file Path Path to be checked. 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
def valid_path(in_path, type="folder"):

    """Assert that file exists.

    Parameters

    ----------

    required_file: Path

        Path to be checked.

    """

    if isinstance(in_path, str):

        in_path = Path(in_path)

    if type == 'folder':

        if in_path.is_dir() or in_path.parent.is_dir():

            return in_path

        else:

            raise NotADirectoryError(in_path)

    elif type == "file":

        if in_path.is_file():

            return in_path

        else:

            raise FileNotFoundError(in_path)

    raise TypeError(type)

write_participants⚓︎

1
2
3
4
def write_participants(
    filename,
    participants
)
View Source
1
2
3
4
5
6
7
8
9
def write_participants(filename, participants):

    with open(filename, "w") as f:

        writer = csv.DictWriter(f, delimiter="\t", fieldnames=participants[0].keys())

        writer.writeheader()

        writer.writerows(participants)

write_txt⚓︎

1
2
3
4
def write_txt(
    filename,
    lines
)
View Source
1
2
3
4
5
6
7
def write_txt(filename, lines):

    with open(filename, "a") as f:

        for row in lines:

            f.write("%s\n" % row)

Classes⚓︎

DEFAULT⚓︎

1
2
3
4
5
class DEFAULT(
    /,
    *args,
    **kwargs
)
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
class DEFAULT(object):

    """ Default values of the package"""

    # cli dcm2bids

    cliLogLevel = "INFO"

    EPILOG="Documentation at https://github.com/unfmontreal/Dcm2Bids"

    # dcm2bids.py

    outputDir = Path.cwd()

    session = ""  # also Participant object

    clobber = False

    forceDcm2niix = False

    defaceTpl = None

    logLevel = "WARNING"

    # dcm2niix.py

    dcm2niixOptions = "-b y -ba y -z y -f '%3s_%f_%p_%t'"

    dcm2niixVersion = "v1.0.20181125"

    # sidecar.py

    compKeys = ["SeriesNumber", "AcquisitionTime", "SidecarFilename"]

    searchMethod = "fnmatch"

    searchMethodChoices = ["fnmatch", "re"]

    runTpl = "_run-{:02d}"

    caseSensitive = True

    # Entity table:

    # https://bids-specification.readthedocs.io/en/v1.7.0/99-appendices/04-entity-table.html

    entityTableKeys = ["sub", "ses", "task", "acq", "ce", "rec", "dir",

                       "run", "mod", "echo", "flip", "inv", "mt", "part",

                       "recording"]

    # misc

    tmpDirName = "tmp_dcm2bids"

    helperDir = "helper"

Class variables⚓︎

1
EPILOG
1
caseSensitive
1
cliLogLevel
1
clobber
1
compKeys
1
dcm2niixOptions
1
dcm2niixVersion
1
defaceTpl
1
entityTableKeys
1
forceDcm2niix
1
helperDir
1
logLevel
1
outputDir
1
runTpl
1
searchMethod
1
searchMethodChoices
1
session
1
tmpDirName

Last update: 2022-06-17
Back to top