Skip to content

Module dcm2bids.dcm2niix_gen⚓︎

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

"""Dcm2niix class"""

import logging

import os

import shlex

import shutil

import tarfile

import zipfile

from glob import glob

from dcm2bids.utils.io import valid_path

from dcm2bids.utils.utils import DEFAULT, run_shell_command

class Dcm2niixGen(object):

    """ Object to handle dcm2niix execution

    Args:

        dicom_dirs (list): A list of folder with dicoms to convert

        bids_dir (str): A path to the root BIDS directory

        participant: Optional Participant object

        skip_dcm2niix: Optional if input only NIFTI and JSON files

        options (str): Optional arguments for dcm2niix

    Properties:

        sidecars (list): A list of sidecar path created by dcm2niix

    """

    def __init__(

        self,

        dicom_dirs,

        bids_dir,

        participant=None,

        skip_dcm2niix=DEFAULT.skip_dcm2niix,

        options=DEFAULT.dcm2niixOptions,

        helper=False

    ):

        self.logger = logging.getLogger(__name__)

        self.sidecarsFiles = []

        self.dicom_dirs = dicom_dirs

        self.bids_dir = bids_dir

        self.participant = participant

        self.skip_dcm2niix = skip_dcm2niix

        self.options = options

        self.helper = helper

        self.rm_tmp_dir = False

    @property

    def output_dir(self):

        """

        Returns:

            A directory to save all the output files of dcm2niix

        """

        tmpDir = self.participant.prefix if self.participant else DEFAULT.helper_dir

        tmpDir = self.bids_dir / DEFAULT.tmp_dir_name / tmpDir

        if self.helper:

            tmpDir = self.bids_dir

        return tmpDir

    def run(self, force=False):

        """ Run dcm2niix if necessary

        Args:

            force (boolean): Forces a cleaning of a previous execution of

                             dcm2niix

        Sets:

            sidecarsFiles (list): A list of sidecar path created by dcm2niix

        """

        try:

            oldOutput = os.listdir(self.output_dir) != []

        except Exception:

            oldOutput = False

        if oldOutput and force:

            self.logger.warning("Previous dcm2bids temporary directory output found:")

            self.logger.warning(self.output_dir)

            self.logger.warning("'force' argument is set to True")

            self.logger.warning("Cleaning the previous directory and running dcm2bids")

            shutil.rmtree(self.output_dir, ignore_errors=True)

            if not os.path.exists(self.output_dir):

                os.makedirs(self.output_dir)

            self.execute()

        elif oldOutput:

            self.logger.warning("Previous dcm2bids temporary directory output found:")

            self.logger.warning(self.output_dir)

            self.logger.warning("Use --force_dcm2bids to rerun dcm2bids\n")

        else:

            if not os.path.exists(self.output_dir):

                os.makedirs(self.output_dir)

            self.execute()

        self.sidecarFiles = glob(os.path.join(self.output_dir, "*.json"))

    def execute(self):

        """ Execute dcm2niix for each directory in dicom_dirs

        """

        if not self.skip_dcm2niix:

            for dicomDir in self.dicom_dirs:

                if os.path.isfile(dicomDir):

                    tmp_dcm_name = os.path.join(self.output_dir.parent,

                                                self.output_dir.name + '_tmp')

                    self.rm_tmp_dir = valid_path(tmp_dcm_name, type="folder")

                    if tarfile.is_tarfile(dicomDir):

                        self.logger.info(f"Extracting archive {dicomDir} to temporary "

                                         f"dicom directory {self.rm_tmp_dir}.")

                        with tarfile.open(dicomDir) as archive:

                            archive.extractall(self.rm_tmp_dir)

                    elif zipfile.is_zipfile(dicomDir):

                        self.logger.info(f"Extracting archive {dicomDir} to temporary "

                                         f"dicom directory {self.rm_tmp_dir}.")

                        with zipfile.ZipFile(dicomDir, 'r') as zip_ref:

                            zip_ref.extractall(self.rm_tmp_dir)

                    else:

                        self.logger.error(f"\n{dicomDir} is not a supported file" +

                                          " extension." +

                                          DEFAULT.arch_extensions + " are supported.")

                    dicomDir = self.rm_tmp_dir

                cmd = ['dcm2niix', *shlex.split(self.options),

                       '-o', self.output_dir, dicomDir]

                output = run_shell_command(cmd)

                try:

                    output = output.decode()

                except Exception:

                    pass

                if self.rm_tmp_dir:

                    shutil.rmtree(self.rm_tmp_dir)

                    self.logger.info("Temporary dicom directory removed.")

                self.logger.debug(f"\n{output}")

                self.logger.info("Check log file for dcm2niix output\n")

        else:

            for dicomDir in self.dicom_dirs:

                shutil.copytree(dicomDir, self.output_dir, dirs_exist_ok=True)

                cmd = ['cp', '-r', dicomDir, self.output_dir]

                self.logger.info("Running: %s", " ".join(str(item) for item in cmd))

            self.logger.info("Not running dcm2niix\n")

Classes⚓︎

Dcm2niixGen⚓︎

1
2
3
4
5
6
7
8
class Dcm2niixGen(
    dicom_dirs,
    bids_dir,
    participant=None,
    skip_dcm2niix=False,
    options="-b y -ba y -z y -f '%3s_%f_%p_%t'",
    helper=False
)

Object to handle dcm2niix execution

Attributes⚓︎

Name Type Description Default
dicom_dirs list A list of folder with dicoms to convert None
bids_dir str A path to the root BIDS directory None
participant None Optional Participant object None
skip_dcm2niix None Optional if input only NIFTI and JSON files None
options str Optional arguments for dcm2niix 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
class Dcm2niixGen(object):

    """ Object to handle dcm2niix execution

    Args:

        dicom_dirs (list): A list of folder with dicoms to convert

        bids_dir (str): A path to the root BIDS directory

        participant: Optional Participant object

        skip_dcm2niix: Optional if input only NIFTI and JSON files

        options (str): Optional arguments for dcm2niix

    Properties:

        sidecars (list): A list of sidecar path created by dcm2niix

    """

    def __init__(

        self,

        dicom_dirs,

        bids_dir,

        participant=None,

        skip_dcm2niix=DEFAULT.skip_dcm2niix,

        options=DEFAULT.dcm2niixOptions,

        helper=False

    ):

        self.logger = logging.getLogger(__name__)

        self.sidecarsFiles = []

        self.dicom_dirs = dicom_dirs

        self.bids_dir = bids_dir

        self.participant = participant

        self.skip_dcm2niix = skip_dcm2niix

        self.options = options

        self.helper = helper

        self.rm_tmp_dir = False

    @property

    def output_dir(self):

        """

        Returns:

            A directory to save all the output files of dcm2niix

        """

        tmpDir = self.participant.prefix if self.participant else DEFAULT.helper_dir

        tmpDir = self.bids_dir / DEFAULT.tmp_dir_name / tmpDir

        if self.helper:

            tmpDir = self.bids_dir

        return tmpDir

    def run(self, force=False):

        """ Run dcm2niix if necessary

        Args:

            force (boolean): Forces a cleaning of a previous execution of

                             dcm2niix

        Sets:

            sidecarsFiles (list): A list of sidecar path created by dcm2niix

        """

        try:

            oldOutput = os.listdir(self.output_dir) != []

        except Exception:

            oldOutput = False

        if oldOutput and force:

            self.logger.warning("Previous dcm2bids temporary directory output found:")

            self.logger.warning(self.output_dir)

            self.logger.warning("'force' argument is set to True")

            self.logger.warning("Cleaning the previous directory and running dcm2bids")

            shutil.rmtree(self.output_dir, ignore_errors=True)

            if not os.path.exists(self.output_dir):

                os.makedirs(self.output_dir)

            self.execute()

        elif oldOutput:

            self.logger.warning("Previous dcm2bids temporary directory output found:")

            self.logger.warning(self.output_dir)

            self.logger.warning("Use --force_dcm2bids to rerun dcm2bids\n")

        else:

            if not os.path.exists(self.output_dir):

                os.makedirs(self.output_dir)

            self.execute()

        self.sidecarFiles = glob(os.path.join(self.output_dir, "*.json"))

    def execute(self):

        """ Execute dcm2niix for each directory in dicom_dirs

        """

        if not self.skip_dcm2niix:

            for dicomDir in self.dicom_dirs:

                if os.path.isfile(dicomDir):

                    tmp_dcm_name = os.path.join(self.output_dir.parent,

                                                self.output_dir.name + '_tmp')

                    self.rm_tmp_dir = valid_path(tmp_dcm_name, type="folder")

                    if tarfile.is_tarfile(dicomDir):

                        self.logger.info(f"Extracting archive {dicomDir} to temporary "

                                         f"dicom directory {self.rm_tmp_dir}.")

                        with tarfile.open(dicomDir) as archive:

                            archive.extractall(self.rm_tmp_dir)

                    elif zipfile.is_zipfile(dicomDir):

                        self.logger.info(f"Extracting archive {dicomDir} to temporary "

                                         f"dicom directory {self.rm_tmp_dir}.")

                        with zipfile.ZipFile(dicomDir, 'r') as zip_ref:

                            zip_ref.extractall(self.rm_tmp_dir)

                    else:

                        self.logger.error(f"\n{dicomDir} is not a supported file" +

                                          " extension." +

                                          DEFAULT.arch_extensions + " are supported.")

                    dicomDir = self.rm_tmp_dir

                cmd = ['dcm2niix', *shlex.split(self.options),

                       '-o', self.output_dir, dicomDir]

                output = run_shell_command(cmd)

                try:

                    output = output.decode()

                except Exception:

                    pass

                if self.rm_tmp_dir:

                    shutil.rmtree(self.rm_tmp_dir)

                    self.logger.info("Temporary dicom directory removed.")

                self.logger.debug(f"\n{output}")

                self.logger.info("Check log file for dcm2niix output\n")

        else:

            for dicomDir in self.dicom_dirs:

                shutil.copytree(dicomDir, self.output_dir, dirs_exist_ok=True)

                cmd = ['cp', '-r', dicomDir, self.output_dir]

                self.logger.info("Running: %s", " ".join(str(item) for item in cmd))

            self.logger.info("Not running dcm2niix\n")

Instance variables⚓︎

1
output_dir

Methods⚓︎

execute⚓︎

1
2
3
def execute(
    self
)

Execute dcm2niix for each directory in dicom_dirs

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

        """ Execute dcm2niix for each directory in dicom_dirs

        """

        if not self.skip_dcm2niix:

            for dicomDir in self.dicom_dirs:

                if os.path.isfile(dicomDir):

                    tmp_dcm_name = os.path.join(self.output_dir.parent,

                                                self.output_dir.name + '_tmp')

                    self.rm_tmp_dir = valid_path(tmp_dcm_name, type="folder")

                    if tarfile.is_tarfile(dicomDir):

                        self.logger.info(f"Extracting archive {dicomDir} to temporary "

                                         f"dicom directory {self.rm_tmp_dir}.")

                        with tarfile.open(dicomDir) as archive:

                            archive.extractall(self.rm_tmp_dir)

                    elif zipfile.is_zipfile(dicomDir):

                        self.logger.info(f"Extracting archive {dicomDir} to temporary "

                                         f"dicom directory {self.rm_tmp_dir}.")

                        with zipfile.ZipFile(dicomDir, 'r') as zip_ref:

                            zip_ref.extractall(self.rm_tmp_dir)

                    else:

                        self.logger.error(f"\n{dicomDir} is not a supported file" +

                                          " extension." +

                                          DEFAULT.arch_extensions + " are supported.")

                    dicomDir = self.rm_tmp_dir

                cmd = ['dcm2niix', *shlex.split(self.options),

                       '-o', self.output_dir, dicomDir]

                output = run_shell_command(cmd)

                try:

                    output = output.decode()

                except Exception:

                    pass

                if self.rm_tmp_dir:

                    shutil.rmtree(self.rm_tmp_dir)

                    self.logger.info("Temporary dicom directory removed.")

                self.logger.debug(f"\n{output}")

                self.logger.info("Check log file for dcm2niix output\n")

        else:

            for dicomDir in self.dicom_dirs:

                shutil.copytree(dicomDir, self.output_dir, dirs_exist_ok=True)

                cmd = ['cp', '-r', dicomDir, self.output_dir]

                self.logger.info("Running: %s", " ".join(str(item) for item in cmd))

            self.logger.info("Not running dcm2niix\n")

run⚓︎

1
2
3
4
def run(
    self,
    force=False
)

Run dcm2niix if necessary

Parameters:

Name Type Description Default
force boolean Forces a cleaning of a previous execution of
dcm2niix
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
    def run(self, force=False):

        """ Run dcm2niix if necessary

        Args:

            force (boolean): Forces a cleaning of a previous execution of

                             dcm2niix

        Sets:

            sidecarsFiles (list): A list of sidecar path created by dcm2niix

        """

        try:

            oldOutput = os.listdir(self.output_dir) != []

        except Exception:

            oldOutput = False

        if oldOutput and force:

            self.logger.warning("Previous dcm2bids temporary directory output found:")

            self.logger.warning(self.output_dir)

            self.logger.warning("'force' argument is set to True")

            self.logger.warning("Cleaning the previous directory and running dcm2bids")

            shutil.rmtree(self.output_dir, ignore_errors=True)

            if not os.path.exists(self.output_dir):

                os.makedirs(self.output_dir)

            self.execute()

        elif oldOutput:

            self.logger.warning("Previous dcm2bids temporary directory output found:")

            self.logger.warning(self.output_dir)

            self.logger.warning("Use --force_dcm2bids to rerun dcm2bids\n")

        else:

            if not os.path.exists(self.output_dir):

                os.makedirs(self.output_dir)

            self.execute()

        self.sidecarFiles = glob(os.path.join(self.output_dir, "*.json"))

Last update: 2024-07-23
Created: 2024-07-23