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 | # -*- coding: utf-8 -*-
import csv
import logging
import os
from pathlib import Path
from subprocess import check_output
class DEFAULT(object):
""" Default values of the package"""
doc = "Documentation at https://unfmontreal.github.io/Dcm2Bids/"
link_bids_validator = "https://github.com/bids-standard/bids-validator#quickstart"
link_doc_intended_for = "https://unfmontreal.github.io/Dcm2Bids/docs/tutorial/first-steps/#populating-the-config-file"
# cli dcm2bids
cli_session = ""
cli_log_level = "INFO"
# Archives
arch_extensions = "tar, tar.bz2, tar.gz or zip"
# dcm2bids.py
output_dir = Path.cwd()
session = "" # also Participant object
bids_validate = False
auto_extract_entities = False
clobber = False
force_dcm2bids = False
post_op = []
logLevel = "WARNING"
entity_dir = {"j-": "AP",
"j": "PA",
"i-": "LR",
"i": "RL",
"AP": "AP",
"PA": "PA",
"LR": "LR",
"RL": "RL"}
# dcm2niix.py
dcm2niixOptions = "-b y -ba y -z y -f '%3s_%f_%p_%t'"
skip_dcm2niix = False
# sidecar.py
auto_extractors = {'SeriesDescription': ["task-(?P<task>[a-zA-Z0-9]+)"],
'PhaseEncodingDirection': ["(?P<dir>(j|i)-?)"],
'EchoNumber': ["(?P<echo>[0-9])"]}
extractors = {}
auto_entities = {"anat_MEGRE": ["echo"],
"anat_MESE": ["echo"],
"func_cbv": ["task"],
"func_bold": ["task"],
"func_sbref": ["task"],
"fmap_epi": ["dir"]}
compKeys = ["SeriesNumber", "AcquisitionTime", "SidecarFilename"]
search_methodChoices = ["fnmatch", "re"]
search_method = "fnmatch"
dup_method_choices = ["dup", "run"]
dup_method = "run"
runTpl = "_run-{:02d}"
dupTpl = "_dup-{:02d}"
case_sensitive = 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"]
keyWithPathsidecar_changes = ['IntendedFor', 'Sources']
# misc
tmp_dir_name = "tmp_dcm2bids"
helper_dir = "helper"
# BIDS version
bids_version = "v1.8.0"
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, log=True):
""" Wrapper of subprocess.check_output
Returns:
Run command with arguments and return its output
"""
if log:
logger = logging.getLogger(__name__)
logger.info("Running: %s", " ".join(str(item) for item in commandLine))
return check_output(commandLine)
def convert_dir(dir):
""" Convert Direction
Args:
dir (str): direction - dcm format
Returns:
str: direction - bids format
"""
return DEFAULT.entity_dir[dir]
class TreePrinter:
"""
Generates and prints a tree representation of a given a directory.
"""
BRANCH = "│"
LAST = "└──"
JUNCTION = "├──"
BRANCH_PREFIX = "│ "
SPACE = " "
def __init__(self, root_dir):
self.root_dir = Path(root_dir)
def print_tree(self):
"""
Prints the tree representation of the root directory and
its subdirectories and files.
"""
tree = self._generate_tree(self.root_dir)
logger = logging.getLogger(__name__)
logger.info(f"Tree representation of {self.root_dir}{os.sep}")
logger.info(f"{self.root_dir}{os.sep}")
for item in tree:
logger.info(item)
def _generate_tree(self, directory, prefix=""):
"""
Generates the tree representation of the <directory> recursively.
Parameters:
- directory: Path
The directory for which a tree representation is needed.
- prefix: str
The prefix to be added to each entry in the tree.
Returns a list of strings representing the tree.
"""
tree = []
entries = sorted(directory.iterdir(), key=lambda path: str(path).lower())
entries = sorted(entries, key=lambda entry: entry.is_file())
entries_count = len(entries)
for index, entry in enumerate(entries):
connector = self.LAST if index == entries_count - 1 else self.JUNCTION
if entry.is_dir():
sub_tree = self._generate_tree(
entry,
prefix=prefix
+ (
self.BRANCH_PREFIX if index != entries_count - 1 else self.SPACE
),
)
tree.append(f"{prefix}{connector} {entry.name}{os.sep}")
tree.extend(sub_tree)
else:
tree.append(f"{prefix}{connector} {entry.name}")
return tree
|