Skip to content

Commit

Permalink
Merge pull request #248 from UNFmontreal/add_option_for_nifti_only
Browse files Browse the repository at this point in the history
Add option to skip_dcm2niix and reorganize NIFTI and JSON files
  • Loading branch information
arnaudbore authored Aug 10, 2023
2 parents 22a9851 + 7517099 commit 25eb307
Show file tree
Hide file tree
Showing 10 changed files with 71 additions and 43 deletions.
2 changes: 1 addition & 1 deletion containers/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ RUN apt-get -y install wget build-essential cmake git pigz \
RUN pip3 install dcm2bids

# Install dcm2niix from github
ENV DCM2NIIX_VERSION="v1.0.20201102"
ENV DCM2NIIX_VERSION="v1.0.20230411"

WORKDIR /usr/local/src
RUN git clone https://github.com/rordenlab/dcm2niix.git
Expand Down
11 changes: 8 additions & 3 deletions dcm2bids/cli/dcm2bids.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,10 +59,15 @@ def _build_arg_parser():
"\nbids-validator needs to be installed check: "
f"{DEFAULT.link_bids_validator}")

p.add_argument("--force_dcm2niix",
p.add_argument("--force_dcm2bids",
action="store_true",
help="Overwrite previous temporary dcm2niix "
"output if it exists.")
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",
Expand Down
2 changes: 1 addition & 1 deletion dcm2bids/cli/dcm2bids_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ def _build_arg_parser():
"Defaults to DICOM_DIR if no name is provided.\n"
"(Default: [%(default)s])")

p.add_argument('--force', '--force_dcm2niix',
p.add_argument('--force', '--force_dcm2bids',
dest='overwrite', action='store_true',
help='Force command to overwrite existing output files.')

Expand Down
13 changes: 8 additions & 5 deletions dcm2bids/dcm2bids_gen.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ class Dcm2BidsGen(object):
output_dir (path): Path to the BIDS base folder
session (str): Optional label of a session
clobber (boolean): Overwrite file if already in BIDS folder
force_dcm2niix (boolean): Forces a cleaning of a previous execution of
dcm2niix
force_dcm2bids (boolean): Forces a cleaning of a previous execution of
dcm2bids
log_level (str): logging level
"""

Expand All @@ -41,7 +41,8 @@ def __init__(
auto_extract_entities=False,
session=DEFAULT.session,
clobber=DEFAULT.clobber,
force_dcm2niix=DEFAULT.force_dcm2niix,
force_dcm2bids=DEFAULT.force_dcm2bids,
skip_dcm2niix=DEFAULT.skip_dcm2niix,
log_level=DEFAULT.logLevel,
**_
):
Expand All @@ -53,7 +54,8 @@ def __init__(
self.clobber = clobber
self.bids_validate = bids_validate
self.auto_extract_entities = auto_extract_entities
self.force_dcm2niix = force_dcm2niix
self.force_dcm2bids = force_dcm2bids
self.skip_dcm2niix = skip_dcm2niix
self.logLevel = log_level
self.logger = logging.getLogger(__name__)

Expand All @@ -77,10 +79,11 @@ def run(self):
self.dicom_dirs,
self.bids_dir,
self.participant,
self.skip_dcm2niix,
self.config.get("dcm2niixOptions", DEFAULT.dcm2niixOptions),
)

dcm2niix.run(self.force_dcm2niix)
dcm2niix.run(self.force_dcm2bids)

sidecars = []
for filename in dcm2niix.sidecarFiles:
Expand Down
45 changes: 28 additions & 17 deletions dcm2bids/dcm2niix_gen.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ class Dcm2niixGen(object):
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:
Expand All @@ -29,6 +30,7 @@ def __init__(
dicom_dirs,
bids_dir,
participant=None,
skip_dcm2niix=DEFAULT.skip_dcm2niix,
options=DEFAULT.dcm2niixOptions,
helper=False
):
Expand All @@ -37,6 +39,7 @@ def __init__(
self.dicom_dirs = dicom_dirs
self.bids_dir = bids_dir
self.participant = participant
self.skip_dcm2niix = skip_dcm2niix
self.options = options
self.helper = helper

Expand All @@ -52,7 +55,7 @@ def output_dir(self):
tmpDir = self.bids_dir
return tmpDir

def run(self, force=False, helper=False):
def run(self, force=False):
""" Run dcm2niix if necessary
Args:
Expand All @@ -68,10 +71,10 @@ def run(self, force=False, helper=False):
oldOutput = False

if oldOutput and force:
self.logger.warning("Previous dcm2niix directory output found:")
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 dcm2niix")
self.logger.warning("Cleaning the previous directory and running dcm2bids")

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

Expand All @@ -81,9 +84,9 @@ def run(self, force=False, helper=False):
self.execute()

elif oldOutput:
self.logger.warning("Previous dcm2niix directory output found:")
self.logger.warning("Previous dcm2bids temporary directory output found:")
self.logger.warning(self.output_dir)
self.logger.warning("Use --force_dcm2niix to rerun dcm2niix\n")
self.logger.warning("Use --force_dcm2bids to rerun dcm2bids\n")

else:
if not os.path.exists(self.output_dir):
Expand All @@ -96,15 +99,23 @@ def run(self, force=False, helper=False):
def execute(self):
""" Execute dcm2niix for each directory in dicom_dirs
"""
for dicomDir in self.dicom_dirs:
cmd = ['dcm2niix', *shlex.split(self.options),
'-o', self.output_dir, dicomDir]
output = run_shell_command(cmd)

try:
output = output.decode()
except Exception:
pass

self.logger.debug(f"\n{output}")
self.logger.info("Check log file for dcm2niix output\n")
if not self.skip_dcm2niix:
for dicomDir in self.dicom_dirs:
cmd = ['dcm2niix', *shlex.split(self.options),
'-o', self.output_dir, dicomDir]
output = run_shell_command(cmd)

try:
output = output.decode()
except Exception:
pass

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")
3 changes: 2 additions & 1 deletion dcm2bids/utils/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ class DEFAULT(object):
bids_validate = False
auto_extract_entities = False
clobber = False
force_dcm2niix = False
force_dcm2bids = False
post_op = []
logLevel = "WARNING"

Expand All @@ -41,6 +41,7 @@ class DEFAULT(object):

# 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]+)"],
Expand Down
7 changes: 4 additions & 3 deletions docs/get-started/install.md
Original file line number Diff line number Diff line change
Expand Up @@ -344,8 +344,8 @@ dcm2bids command such as `dcm2bids --help`:
```bash hl_lines="1"
(dcm2bids) sam:~/dcm2bids-proj$ dcm2bids --help
usage: dcm2bids [-h] -d DICOM_DIR [DICOM_DIR ...] -p PARTICIPANT [-s SESSION] -c
CONFIG [-o OUTPUT_DIR] [--forceDcm2niix] [--clobber]
[-l {DEBUG,INFO,WARNING,ERROR,CRITICAL}] [-a]
CONFIG [-o OUTPUT_DIR] [--force_dcm2bids] [--skip_dcm2niix]
[--clobber] [-l {DEBUG,INFO,WARNING,ERROR,CRITICAL}] [-a]
Reorganising NIfTI files from dcm2niix into the Brain Imaging Data Structure
dcm2bids 2.1.7
Expand All @@ -363,7 +363,8 @@ options:
-o OUTPUT_DIR, --output_dir OUTPUT_DIR
Output BIDS directory, Default: current directory
(/home/sam/dcm2bids-proj)
--forceDcm2niix Overwrite previous temporary dcm2niix output if it exists
--force_dcm2bids Overwrite previous temporary dcm2bids output if it exists
--skip_dcm2niix Skip dcm2niix conversion. Option -d should contains NIFTI and json files.
--clobber Overwrite output if it exists
-l {DEBUG,INFO,WARNING,ERROR,CRITICAL}, --log_level {DEBUG,INFO,WARNING,ERROR,CRITICAL}
Set logging level
Expand Down
2 changes: 1 addition & 1 deletion docs/how-to/create-config-file.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
}
},
{
"id": "task-rest",
"id": "task_rest",
"datatype": "func",
"suffix": "bold",
"custom_entities": "task-rest",
Expand Down
12 changes: 9 additions & 3 deletions docs/how-to/use-advanced-commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ command.
```sh hl_lines="2-3"
(dcm2bids) sam:~/dcm2bids-tutorial/bids_project$ dcm2bids --help
usage: dcm2bids [-h] -d DICOM_DIR [DICOM_DIR ...] -p PARTICIPANT [-s SESSION] -c CONFIG [-o OUTPUT_DIR]
[--auto_extract_entities] [--bids_validate] [--forceDcm2niix] [--clobber]
[--auto_extract_entities] [--bids_validate] [--force_dcm2bids] [--skip_dcm2niix] [--clobber]
[-l {DEBUG,INFO,WARNING,ERROR,CRITICAL}] [-a]

Reorganising NIfTI files from dcm2niix into the Brain Imaging Data Structure
Expand All @@ -238,8 +238,9 @@ command.
depending on the suffix and datatype. [False]
--bids_validate If set, once your conversion is done it will check if your output folder is BIDS valid. [False]
bids-validator needs to be installed check: https://github.com/bids-standard/bids-validator#quickstart
--force_dcm2niix Overwrite previous temporary dcm2niix output if it exists
--clobber Overwrite output if it exists
--force_dcm2bids Overwrite previous temporary dcm2bids output if it exists.
--skip_dcm2niix Skip dcm2niix conversion. Option -d should contains NIFTI and json files.
--clobber Overwrite output if it exists.
-l {DEBUG,INFO,WARNING,ERROR,CRITICAL}, --log_level {DEBUG,INFO,WARNING,ERROR,CRITICAL}
Set logging level

Expand Down Expand Up @@ -318,3 +319,8 @@ By default, dcm2bids will not validate your final BIDS structure. If needed, you
can install
[bids-validator](https://github.com/bids-standard/bids-validator#quickstart) and
activate this option.

### `--skip_dcm2niix`

If you don't have access to original dicom files you can still use dcm2bids to reorganise your data into a BIDS structure.
Using the option --skip_dcm2niix you will skip the conversion step.
17 changes: 9 additions & 8 deletions docs/tutorial/first-steps.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ You can test it with any command but a safe way is to use the `--help` command.
(dcm2bids) sam:~$ dcm2bids --help
usage: dcm2bids [-h] -d DICOM_DIR [DICOM_DIR ...] -p PARTICIPANT [-s SESSION] -c
CONFIG [-o OUTPUT_DIR][--auto_extract_entities] [--bids_validate]
[--forceDcm2niix] [--clobber]
[--force_dcm2bids] [--skip_dcm2niix] [--clobber]
[-l {DEBUG,INFO,WARNING,ERROR,CRITICAL}] [-a]

Reorganising NIfTI files from dcm2niix into the Brain Imaging Data Structure
Expand All @@ -104,8 +104,9 @@ You can test it with any command but a safe way is to use the `--help` command.
If set, it will automatically try to extract entityinformation [task, dir, echo] based on the suffix and datatype. [False]
--bids_validate If set, once your conversion is done it will check if your output folder is BIDS valid. [False]
bids-validator needs to be installed check: https://github.com/bids-standard/bids-validator#quickstart
--forceDcm2niix Overwrite previous temporary dcm2niix output if it exists
--clobber Overwrite output if it exists
--force_dcm2bids Overwrite previous temporary dcm2bids output if it exists.
--skip_dcm2niix Skip dcm2niix conversion. Option -d should contains NIFTI and json files.
--clobber Overwrite output if it exists.
-l {DEBUG,INFO,WARNING,ERROR,CRITICAL}, --log_level {DEBUG,INFO,WARNING,ERROR,CRITICAL}
Set logging level
-a, --anonymizer This option no longer exists from the script in this
Expand Down Expand Up @@ -501,7 +502,7 @@ As usual the first command will be to request the help info.
to make a config file due to slight variations in MRI acquisitions.
Defaults to DICOM_DIR if no name is provided.
(Default: [False])
--force, --force_dcm2niix
--force, --force_dcm2bids
Force command to overwrite existing output files.
-l {DEBUG,INFO,WARNING,ERROR,CRITICAL}, --log_level {DEBUG,INFO,WARNING,ERROR,CRITICAL}
Set logging level to the console. [INFO]
Expand Down Expand Up @@ -1069,7 +1070,7 @@ command.
```sh hl_lines="2-3"
(dcm2bids) sam:~/dcm2bids-tutorial/bids_project$ dcm2bids --help
usage: dcm2bids [-h] -d DICOM_DIR [DICOM_DIR ...] -p PARTICIPANT [-s SESSION] -c CONFIG [-o OUTPUT_DIR]
[--auto_extract_entities] [--bids_validate] [--forceDcm2niix] [--clobber]
[--auto_extract_entities] [--bids_validate] [--force_dcm2bids] [--skip_dcm2niix] [--clobber]
[-l {DEBUG,INFO,WARNING,ERROR,CRITICAL}] [-a]

Reorganising NIfTI files from dcm2niix into the Brain Imaging Data Structure
Expand All @@ -1091,9 +1092,9 @@ command.
If set, it will automatically try to extract entityinformation [task, dir, echo] based on the suffix and datatype. [False]
--bids_validate If set, once your conversion is done it will check if your output folder is BIDS valid. [False]
bids-validator needs to be installed check: https://github.com/bids-standard/bids-validator#quickstart

--forceDcm2niix Overwrite previous temporary dcm2niix output if it exists
--clobber Overwrite output if it exists
--force_dcm2bids Overwrite previous temporary dcm2bids output if it exists.
--skip_dcm2niix Skip dcm2niix conversion. Option -d should contains NIFTI and json files.
--clobber Overwrite output if it exists.
-l {DEBUG,INFO,WARNING,ERROR,CRITICAL}, --log_level {DEBUG,INFO,WARNING,ERROR,CRITICAL}
Set logging level
-a, --anonymizer This option no longer exists from the script in this release. See:https://github.com/unfmontreal/Dcm2Bids/blob/master/README.md#defaceTpl
Expand Down

0 comments on commit 25eb307

Please sign in to comment.