Skip to content

Module dcm2bids.acquisition⚓︎

Participant class

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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
# -*- coding: utf-8 -*-

"""Participant class"""

import logging

from os.path import join as opj

from dcm2bids.utils.utils import DEFAULT

from dcm2bids.version import __version__

class Acquisition(object):

    """ Class representing an acquisition

    Args:

        participant (Participant): A participant object

        datatype (str): A functional group of MRI data (ex: func, anat ...)

        suffix (str): The modality of the acquisition

                (ex: T1w, T2w, bold ...)

        custom_entities (str): Optional entities (ex: task-rest)

        src_sidecar (Sidecar): Optional sidecar object

    """

    def __init__(

        self,

        participant,

        datatype,

        suffix,

        custom_entities="",

        id=None,

        src_sidecar=None,

        sidecar_changes=None,

        **kwargs

    ):

        self.logger = logging.getLogger(__name__)

        self._suffix = ""

        self._custom_entities = ""

        self._id = ""

        self.participant = participant

        self.datatype = datatype

        self.suffix = suffix

        self.custom_entities = custom_entities

        self.src_sidecar = src_sidecar

        if sidecar_changes is None:

            self.sidecar_changes = {}

        else:

            self.sidecar_changes = sidecar_changes

        if id is None:

            self.id = None

        else:

            self.id = id

        self.dstFile = ''

    def __eq__(self, other):

        return (

            self.datatype == other.datatype

            and self.participant.prefix == other.participant.prefix

            and self.build_suffix == other.build_suffix

        )

    @property

    def suffix(self):

        """

        Returns:

            A string '_<suffix>'

        """

        return self._suffix

    @suffix.setter

    def suffix(self, suffix):

        """ Prepend '_' if necessary"""

        self._suffix = self.prepend(suffix)

    @property

    def id(self):

        """

        Returns:

            A string '_<id>'

        """

        return self._id

    @id.setter

    def id(self, value):

        self._id = value

    @property

    def custom_entities(self):

        """

        Returns:

            A string '_<custom_entities>'

        """

        return self._custom_entities

    @custom_entities.setter

    def custom_entities(self, custom_entities):

        """ Prepend '_' if necessary"""

        if isinstance(custom_entities, list):

            self._custom_entities = self.prepend('_'.join(custom_entities))

        else:

            self._custom_entities = self.prepend(custom_entities)

    @property

    def build_suffix(self):

        """ The suffix to build filenames

        Returns:

            A string '_<suffix>' or '_<custom_entities>_<suffix>'

        """

        if self.custom_entities.strip() == "":

            return self.suffix

        else:

            return self.custom_entities + self.suffix

    @property

    def srcRoot(self):

        """

        Return:

            The sidecar source root to move

        """

        if self.src_sidecar:

            return self.src_sidecar.root

        else:

            return None

    @property

    def dstRoot(self):

        """

        Return:

            The destination root inside the BIDS structure

        """

        return opj(

            self.participant.directory,

            self.datatype,

            self.dstFile,

        )

    @property

    def dstId(self):

        """

        Return:

            The destination root inside the BIDS structure for description

        """

        return opj(

            self.participant.session,

            self.datatype,

            self.dstFile,

        )

    def setDstFile(self):

        """

        Return:

            The destination filename formatted following

            the v1.8.0 BIDS entity key table

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

        """

        current_name = self.participant.prefix + self.build_suffix

        new_name = ''

        current_dict = dict(x.split("-") for x in current_name.split("_") if len(x.split('-')) == 2)

        suffix_list = [x for x in current_name.split("_") if len(x.split('-')) == 1]

        for current_key in DEFAULT.entityTableKeys:

            if current_key in current_dict and new_name != '':

                new_name += f"_{current_key}-{current_dict[current_key]}"

            elif current_key in current_dict:

                new_name = f"{current_key}-{current_dict[current_key]}"

            current_dict.pop(current_key, None)

        for current_key in current_dict:

            new_name += f"_{current_key}-{current_dict[current_key]}"

        if current_dict:

            self.logger.warning(f'Entity \"{list(current_dict.keys())}\"'

                                ' is not a valid BIDS entity.')

        # Allow multiple single keys (without value)

        new_name += f"_{'_'.join(suffix_list)}"

        if len(suffix_list) != 1:

            self.logger.warning("There was more than one suffix found "

                                f"({suffix_list}). This is not BIDS "

                                "compliant. Make sure you know what "

                                "you are doing.")

        if current_name != new_name:

            self.logger.warning(

                f"""✅ Filename was reordered according to BIDS entity table order:

                from:   {current_name}

                to:     {new_name}""")

        self.dstFile = new_name

    def dstSidecarData(self, idList):

        """

        """

        data = self.src_sidecar.origData

        data["Dcm2bidsVersion"] = __version__

        # TaskName

        if 'TaskName' in self.src_sidecar.data:

            data["TaskName"] = self.src_sidecar.data["TaskName"]

        # sidecar_changes

        for key, value in self.sidecar_changes.items():

            values = []

            if not isinstance(value, list):

                value = [value]

            for val in value:

                if isinstance(val, (bool, str, int, float)):

                    if val not in idList and key in DEFAULT.keyWithPathsidecar_changes:

                        logging.warning(f"No id found for '{key}' value '{val}'.")

                        logging.warning(f"No sidecar changes for field '{key}' "

                                        f"will be made "

                                        f"for json file '{self.dstFile}.json' "

                                        "with this id.")

                    else:

                        values.append(idList.get(val, val))

                        if values[-1] != val:

                            if isinstance(values[-1], list):

                                values[-1] = "bids::" + values[-1][0]

                            else:

                                 values[-1] = "bids::" + values[-1]

            # handle if nested list vs str

            flat_value_list = []

            for item in values:

                if isinstance(item, list):

                    flat_value_list += item

                else:

                    flat_value_list.append(item)

            if len(flat_value_list) == 1:

                data[key] = flat_value_list[0]

            else:

                data[key] = flat_value_list

        return data

    @staticmethod

    def prepend(value, char="_"):

        """ Prepend `char` to `value` if necessary

        Args:

            value (str)

            char (str)

        """

        if value.strip() == "":

            return ""

        elif value.startswith(char):

            return value

        else:

            return char + value

Classes⚓︎

Acquisition⚓︎

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Acquisition(
    participant,
    datatype,
    suffix,
    custom_entities='',
    id=None,
    src_sidecar=None,
    sidecar_changes=None,
    **kwargs
)

Class representing an acquisition

Attributes⚓︎

Name Type Description Default
participant Participant A participant object None
datatype str A functional group of MRI data (ex: func, anat ...) None
suffix str The modality of the acquisition
(ex: T1w, T2w, bold ...)
None
custom_entities str Optional entities (ex: task-rest) None
src_sidecar Sidecar Optional sidecar object 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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
class Acquisition(object):

    """ Class representing an acquisition

    Args:

        participant (Participant): A participant object

        datatype (str): A functional group of MRI data (ex: func, anat ...)

        suffix (str): The modality of the acquisition

                (ex: T1w, T2w, bold ...)

        custom_entities (str): Optional entities (ex: task-rest)

        src_sidecar (Sidecar): Optional sidecar object

    """

    def __init__(

        self,

        participant,

        datatype,

        suffix,

        custom_entities="",

        id=None,

        src_sidecar=None,

        sidecar_changes=None,

        **kwargs

    ):

        self.logger = logging.getLogger(__name__)

        self._suffix = ""

        self._custom_entities = ""

        self._id = ""

        self.participant = participant

        self.datatype = datatype

        self.suffix = suffix

        self.custom_entities = custom_entities

        self.src_sidecar = src_sidecar

        if sidecar_changes is None:

            self.sidecar_changes = {}

        else:

            self.sidecar_changes = sidecar_changes

        if id is None:

            self.id = None

        else:

            self.id = id

        self.dstFile = ''

    def __eq__(self, other):

        return (

            self.datatype == other.datatype

            and self.participant.prefix == other.participant.prefix

            and self.build_suffix == other.build_suffix

        )

    @property

    def suffix(self):

        """

        Returns:

            A string '_<suffix>'

        """

        return self._suffix

    @suffix.setter

    def suffix(self, suffix):

        """ Prepend '_' if necessary"""

        self._suffix = self.prepend(suffix)

    @property

    def id(self):

        """

        Returns:

            A string '_<id>'

        """

        return self._id

    @id.setter

    def id(self, value):

        self._id = value

    @property

    def custom_entities(self):

        """

        Returns:

            A string '_<custom_entities>'

        """

        return self._custom_entities

    @custom_entities.setter

    def custom_entities(self, custom_entities):

        """ Prepend '_' if necessary"""

        if isinstance(custom_entities, list):

            self._custom_entities = self.prepend('_'.join(custom_entities))

        else:

            self._custom_entities = self.prepend(custom_entities)

    @property

    def build_suffix(self):

        """ The suffix to build filenames

        Returns:

            A string '_<suffix>' or '_<custom_entities>_<suffix>'

        """

        if self.custom_entities.strip() == "":

            return self.suffix

        else:

            return self.custom_entities + self.suffix

    @property

    def srcRoot(self):

        """

        Return:

            The sidecar source root to move

        """

        if self.src_sidecar:

            return self.src_sidecar.root

        else:

            return None

    @property

    def dstRoot(self):

        """

        Return:

            The destination root inside the BIDS structure

        """

        return opj(

            self.participant.directory,

            self.datatype,

            self.dstFile,

        )

    @property

    def dstId(self):

        """

        Return:

            The destination root inside the BIDS structure for description

        """

        return opj(

            self.participant.session,

            self.datatype,

            self.dstFile,

        )

    def setDstFile(self):

        """

        Return:

            The destination filename formatted following

            the v1.8.0 BIDS entity key table

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

        """

        current_name = self.participant.prefix + self.build_suffix

        new_name = ''

        current_dict = dict(x.split("-") for x in current_name.split("_") if len(x.split('-')) == 2)

        suffix_list = [x for x in current_name.split("_") if len(x.split('-')) == 1]

        for current_key in DEFAULT.entityTableKeys:

            if current_key in current_dict and new_name != '':

                new_name += f"_{current_key}-{current_dict[current_key]}"

            elif current_key in current_dict:

                new_name = f"{current_key}-{current_dict[current_key]}"

            current_dict.pop(current_key, None)

        for current_key in current_dict:

            new_name += f"_{current_key}-{current_dict[current_key]}"

        if current_dict:

            self.logger.warning(f'Entity \"{list(current_dict.keys())}\"'

                                ' is not a valid BIDS entity.')

        # Allow multiple single keys (without value)

        new_name += f"_{'_'.join(suffix_list)}"

        if len(suffix_list) != 1:

            self.logger.warning("There was more than one suffix found "

                                f"({suffix_list}). This is not BIDS "

                                "compliant. Make sure you know what "

                                "you are doing.")

        if current_name != new_name:

            self.logger.warning(

                f"""✅ Filename was reordered according to BIDS entity table order:

                from:   {current_name}

                to:     {new_name}""")

        self.dstFile = new_name

    def dstSidecarData(self, idList):

        """

        """

        data = self.src_sidecar.origData

        data["Dcm2bidsVersion"] = __version__

        # TaskName

        if 'TaskName' in self.src_sidecar.data:

            data["TaskName"] = self.src_sidecar.data["TaskName"]

        # sidecar_changes

        for key, value in self.sidecar_changes.items():

            values = []

            if not isinstance(value, list):

                value = [value]

            for val in value:

                if isinstance(val, (bool, str, int, float)):

                    if val not in idList and key in DEFAULT.keyWithPathsidecar_changes:

                        logging.warning(f"No id found for '{key}' value '{val}'.")

                        logging.warning(f"No sidecar changes for field '{key}' "

                                        f"will be made "

                                        f"for json file '{self.dstFile}.json' "

                                        "with this id.")

                    else:

                        values.append(idList.get(val, val))

                        if values[-1] != val:

                            if isinstance(values[-1], list):

                                values[-1] = "bids::" + values[-1][0]

                            else:

                                 values[-1] = "bids::" + values[-1]

            # handle if nested list vs str

            flat_value_list = []

            for item in values:

                if isinstance(item, list):

                    flat_value_list += item

                else:

                    flat_value_list.append(item)

            if len(flat_value_list) == 1:

                data[key] = flat_value_list[0]

            else:

                data[key] = flat_value_list

        return data

    @staticmethod

    def prepend(value, char="_"):

        """ Prepend `char` to `value` if necessary

        Args:

            value (str)

            char (str)

        """

        if value.strip() == "":

            return ""

        elif value.startswith(char):

            return value

        else:

            return char + value

Static methods⚓︎

prepend⚓︎

1
2
3
4
def prepend(
    value,
    char='_'
)

Prepend char to value if necessary

Args: value (str) char (str)

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
    @staticmethod

    def prepend(value, char="_"):

        """ Prepend `char` to `value` if necessary

        Args:

            value (str)

            char (str)

        """

        if value.strip() == "":

            return ""

        elif value.startswith(char):

            return value

        else:

            return char + value

Instance variables⚓︎

1
build_suffix

The suffix to build filenames

1
custom_entities
1
dstId

Return:

The destination root inside the BIDS structure for description

1
dstRoot

Return:

The destination root inside the BIDS structure

1
id
1
srcRoot

Return:

The sidecar source root to move

1
suffix

Methods⚓︎

dstSidecarData⚓︎

1
2
3
4
def dstSidecarData(
    self,
    idList
)
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 dstSidecarData(self, idList):

        """

        """

        data = self.src_sidecar.origData

        data["Dcm2bidsVersion"] = __version__

        # TaskName

        if 'TaskName' in self.src_sidecar.data:

            data["TaskName"] = self.src_sidecar.data["TaskName"]

        # sidecar_changes

        for key, value in self.sidecar_changes.items():

            values = []

            if not isinstance(value, list):

                value = [value]

            for val in value:

                if isinstance(val, (bool, str, int, float)):

                    if val not in idList and key in DEFAULT.keyWithPathsidecar_changes:

                        logging.warning(f"No id found for '{key}' value '{val}'.")

                        logging.warning(f"No sidecar changes for field '{key}' "

                                        f"will be made "

                                        f"for json file '{self.dstFile}.json' "

                                        "with this id.")

                    else:

                        values.append(idList.get(val, val))

                        if values[-1] != val:

                            if isinstance(values[-1], list):

                                values[-1] = "bids::" + values[-1][0]

                            else:

                                 values[-1] = "bids::" + values[-1]

            # handle if nested list vs str

            flat_value_list = []

            for item in values:

                if isinstance(item, list):

                    flat_value_list += item

                else:

                    flat_value_list.append(item)

            if len(flat_value_list) == 1:

                data[key] = flat_value_list[0]

            else:

                data[key] = flat_value_list

        return data

setDstFile⚓︎

1
2
3
def setDstFile(
    self
)

Return:

The destination filename formatted following the v1.8.0 BIDS entity key table https://bids-specification.readthedocs.io/en/v1.8.0/99-appendices/04-entity-table.html

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

        """

        Return:

            The destination filename formatted following

            the v1.8.0 BIDS entity key table

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

        """

        current_name = self.participant.prefix + self.build_suffix

        new_name = ''

        current_dict = dict(x.split("-") for x in current_name.split("_") if len(x.split('-')) == 2)

        suffix_list = [x for x in current_name.split("_") if len(x.split('-')) == 1]

        for current_key in DEFAULT.entityTableKeys:

            if current_key in current_dict and new_name != '':

                new_name += f"_{current_key}-{current_dict[current_key]}"

            elif current_key in current_dict:

                new_name = f"{current_key}-{current_dict[current_key]}"

            current_dict.pop(current_key, None)

        for current_key in current_dict:

            new_name += f"_{current_key}-{current_dict[current_key]}"

        if current_dict:

            self.logger.warning(f'Entity \"{list(current_dict.keys())}\"'

                                ' is not a valid BIDS entity.')

        # Allow multiple single keys (without value)

        new_name += f"_{'_'.join(suffix_list)}"

        if len(suffix_list) != 1:

            self.logger.warning("There was more than one suffix found "

                                f"({suffix_list}). This is not BIDS "

                                "compliant. Make sure you know what "

                                "you are doing.")

        if current_name != new_name:

            self.logger.warning(

                f"""✅ Filename was reordered according to BIDS entity table order:

                from:   {current_name}

                to:     {new_name}""")

        self.dstFile = new_name

Last update: 2023-08-31
Created: 2023-08-31