### Install and run dcm2bids binary on Ubuntu Source: https://unfmontreal.github.io/Dcm2Bids/latest/get-started/install Example commands to download, extract, and execute the dcm2bids binary on a Linux system. ```bash sam:~/software$ curl -fLO https://github.com/unfmontreal/dcm2bids/releases/latest/download/dcm2bids_debian-based_3.0.rc1.tar.gz sam:~/software$ tar -xvf dcm2bids_debian-based*.tar.gz sam:~/software$ cd ../data sam:~/data$ ~/software/dcm2bids_scaffold -o new-bids-project ``` ```text sam:~/software$ curl -fLO https://github.com/unfmontreal/dcm2bids/releases/latest/download/dcm2bids_debian-based_3.0.0rc1.tar.gz % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0 100 40.6M 100 40.6M 0 0 23.2M 0 0:00:01 0:00:01 --:--:-- 36.4M sam:~/software$ tar -xvf dcm2bids_debian-based*.tar.gz dcm2bids dcm2bids_helper dcm2bids_scaffold sam:~/software$ cd ../data sam:~/data$ ~/software/dcm2bids_scaffold -o new-bids-project INFO | --- dcm2bids_scaffold start --- INFO | Running the following command: /home/sam/software/dcm2bids_scaffold -o new-bids-project INFO | OS version: Linux-5.15.0-76-generic-x86_64-with-glibc2.31 INFO | Python version: 3.10.12 | packaged by conda-forge | (main, Jun 23 2023, 22:40:32) [GCC 12.3.0] INFO | dcm2bids version: 3.0.rc1 INFO | Checking for software update INFO | Currently using the latest version of dcm2bids. INFO | The files used to create your BIDS directory were taken from https://github.com/bids-standard/bids-starter-kit. INFO | Tree representation of new-bids-project/ INFO | new-bids-project/ INFO | ├── code/ INFO | ├── derivatives/ INFO | ├── sourcedata/ INFO | ├── tmp_dcm2bids/ INFO | │ └── log/ INFO | │ └── scaffold_20230716-122220.log INFO | ├── .bidsignore INFO | ├── CHANGES INFO | ├── dataset_description INFO | ├── participants.json INFO | ├── participants.tsv INFO | └── README INFO | Log file saved at new-bids-project/tmp_dcm2bids/log/scaffold_20230716-122220.log INFO | --- dcm2bids_scaffold end --- ``` -------------------------------- ### Full dcm2bids configuration example Source: https://unfmontreal.github.io/Dcm2Bids/latest/how-to/use-advanced-commands A comprehensive example showing the structure of a dcm2bids configuration file, including extractors, search methods, and post-processing operations. ```json { "extractors": { "SeriesDescription": [ "run-(?P[0-9]+)", "task-(?P[0-9]+)" ], "BodyPartExamined": [ "(?P[a-zA-Z]+)" ] }, "search_method": "fnmatch", "case_sensitive": true, "dup_method": "dup", "post_op": [ { "cmd": "pydeface --outfile dst_file src_file", "datatype": "anat", "suffix": [ "T1w", "MP2RAGE" ], "custom_entities": "rec-defaced" } ], "descriptions": [ { "datatype": "anat", "suffix": "T2w", "custom_entities": [ "acq-highres", "bodypart", "run", "task" ], "criteria": ... } ] } ``` -------------------------------- ### Example command and output format Source: https://unfmontreal.github.io/Dcm2Bids/latest/tutorial/first-steps Demonstrates the structure of command and output tabs used throughout the tutorial. ```bash echo "Hello, World!" ``` ```bash sam:~/$ echo "Hello, World!" Hello, World! ``` -------------------------------- ### Python version output examples Source: https://unfmontreal.github.io/Dcm2Bids/latest/get-started/install Example terminal outputs when checking Python version and starting the interactive shell. ```text sam:~$ python --version Python 3.10.4 ``` ```text sam:~$ python Python 3.10.4 | packaged by conda-forge | (main, Mar 24 2022, 17:39:04) [GCC 10.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> exit() ``` -------------------------------- ### Verify dcm2bids installation Source: https://unfmontreal.github.io/Dcm2Bids/latest/get-started/install Run the help command to confirm that the dcm2bids package is correctly installed and accessible. ```bash (dcm2bids) sam:~/dcm2bids-proj$ dcm2bids --help usage: dcm2bids [-h] -d DICOM_DIR [DICOM_DIR ...] -p PARTICIPANT [-s SESSION] -c CONFIG [-o OUTPUT_DIR] [--auto_extract_entities | --do_not_reorder_entities] [-b BIDS_VERSION] [--bids_validate] [--force_dcm2bids] [--skip_dcm2niix] [--clobber] [-l {DEBUG,INFO,WARNING,ERROR,CRITICAL}] [-v] Reorganising NIfTI files from dcm2niix into the Brain Imaging Data Structure options: -h, --help show this help message and exit -d DICOM_DIR [DICOM_DIR ...], --dicom_dir DICOM_DIR [DICOM_DIR ...] Path to one or more directories or archives (tar, tar.bz2, tar.gz or zip) containing the DICOM files for a single participant and session to be converted to BIDS. -p PARTICIPANT, --participant PARTICIPANT Participant ID to be used in the BIDS dataset filenames (e.g. sub-). -s SESSION, --session SESSION Session ID to be used in the BIDS dataset filenames (e.g. ses-). If not provided, no session entity will be added to the BIDS filenames. -c CONFIG, --config CONFIG JSON configuration that specifies additional parameters for BIDS conversion. See the documentation for more information: https://unfmontreal.github.io/Dcm2Bids/3.3.0.rc1/how-to/create-config-file/ -o OUTPUT_DIR, --output_dir OUTPUT_DIR Output BIDS directory. Defaults to the current working directory. --auto_extract_entities If set, it will automatically try to extract entity information [task, dir, echo] based on the suffix and datatype. Default is [False] --do_not_reorder_entities If set, it will not reorder entities according to the relative ordering indicated in the BIDS specification and use the order defined in custom_entities by the user. Cannot be used with --auto_extract_entities. Default is [False] -b BIDS_VERSION, --bids_version BIDS_VERSION Set the BIDS specification version to follow (e.g. 'v1.11.1', 'stable', 'latest' or 'default'). This controls which BIDS schema and rules dcm2bids uses for automatic entity extraction and ordering. If not provided, dcm2bids uses the 'default' BIDS spec for reproducible, offline-friendly behavior. For long-running or shared pipelines, consider pinning a specific tag (e.g. 'v1.11.1'). When internet is available, it will check once whether the remote 'stable' is newer and, if so, suggest updating to that specific version tag. --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_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 to the console. The default level is [INFO] -v, --version Report dcm2bids version and the default BIDS specification version it follows by default. Documentation at https://unfmontreal.github.io/Dcm2Bids/ ``` -------------------------------- ### Example terminal output for environment creation Source: https://unfmontreal.github.io/Dcm2Bids/latest/get-started/install Sample terminal session showing the creation of the environment using the configuration file. ```bash sam:~/dcm2bids-proj$ nano environment.yml sam:~/dcm2bids-proj$ conda env create --file environment.yml Collecting package metadata (repodata.json): done Solving environment: |done Downloading and Extracting Packages future-0.18.2 | 738 KB | ########################################## | 100% Preparing transaction: done Verifying transaction: done Executing transaction: done # ``` -------------------------------- ### Example output of dcm2bids_scaffold Source: https://unfmontreal.github.io/Dcm2Bids/latest/tutorial/parallel This shows the console output and the resulting directory tree after running the scaffold command. ```text (dcm2bids) sam:~$ dcm2bids_scaffold -o tuto-parallel INFO | --- dcm2bids_scaffold start --- INFO | Running the following command: /home/sam/miniconda3/envs/dcm2bids/bin/dcm2bids_scaffold -o tuto-parallel INFO | OS version: Linux-5.15.0-83-generic-x86_64-with-glibc2.31 INFO | Python version: 3.10.4 | packaged by conda-forge | (main, Mar 24 2022, 17:39:04) [GCC 10.3.0] INFO | dcm2bids version: 3.1.0 INFO | Checking for software update INFO | Currently using the latest version of dcm2bids. INFO | The files used to create your BIDS directory were taken from https://github.com/bids-standard/bids-starter-kit. INFO | Tree representation of tuto-parallel/ INFO | tuto-parallel/ INFO | ├── code/ INFO | ├── derivatives/ INFO | ├── sourcedata/ INFO | ├── tmp_dcm2bids/ INFO | │ └── log/ INFO | │ └── scaffold_20230913-095334.log INFO | ├── .bidsignore INFO | ├── CHANGES INFO | ├── dataset_description.json INFO | ├── participants.json INFO | ├── participants.tsv INFO | └── README INFO | Log file saved at tuto-parallel/tmp_dcm2bids/log/scaffold_20230913-095334.log INFO | --- dcm2bids_scaffold end --- ``` -------------------------------- ### Test the dcm2bids container Source: https://unfmontreal.github.io/Dcm2Bids/latest/how-to/container Verify the container installation by displaying the help message. ```bash docker run --rm -it unfmontreal/dcm2bids:${VERSION} --help ``` ```bash apptainer run -e --containall dcm2bids.sif --help ``` -------------------------------- ### Install dcm2bids via package managers Source: https://unfmontreal.github.io/Dcm2Bids/latest/get-started Use these commands to install dcm2bids within a dedicated project environment. ```bash conda install -c conda-forge dcm2bids ``` ```bash pip install dcm2bids ``` -------------------------------- ### Example dcm2bids configuration file Source: https://unfmontreal.github.io/Dcm2Bids/latest/tutorial/first-steps A sample JSON configuration file defining task and fieldmap matching criteria. ```json { "descriptions": [ { "id": "id_task-rest", "datatype": "func", "suffix": "bold", "custom_entities": "task-rest", "criteria": { "SeriesDescription": "Axial EPI-FMRI (Interleaved I to S)*" }, "sidecar_changes": { "TaskName": "rest" } }, { "datatype": "fmap", "suffix": "epi", "custom_entities": "dir", "criteria": { "SeriesDescription": "EPI PE=*" }, "sidecar_changes": { "intendedFor": ["id_task-rest"] } } ] } ``` -------------------------------- ### Parallel Execution Example Source: https://unfmontreal.github.io/Dcm2Bids/latest/tutorial/parallel Demonstrates using GNU parallel to iterate over a list of files and execute a command for each. ```bash ls PATH/TO/YOUR/SOURCE/DATA | parallel echo "This is the command for subject {}" ``` ```bash (dcm2bids) sam:~/tuto-parallel$ ls sourcedata/punk_proj | parallel echo "This is the command for subject {}" This is the command for subject PUNK041.tar.bz2 This is the command for subject PUNK042.tar.bz2 This is the command for subject PUNK043.tar.bz2 This is the command for subject PUNK044.tar.bz2 This is the command for subject PUNK045.tar.bz2 This is the command for subject PUNK046.tar.bz2 This is the command for subject PUNK047.tar.bz2 This is the command for subject PUNK048.tar.bz2 This is the command for subject PUNK049.tar.bz2 This is the command for subject PUNK050.tar.bz2 This is the command for subject PUNK051.tar.bz2 ``` -------------------------------- ### Schema Loading Logic Source: https://unfmontreal.github.io/Dcm2Bids/latest/dcm2bids/utils/schema Example of resolving the BIDS version label and loading the corresponding schema. ```python actual_label = _resolve_bids_version_label(args_bids_version, log_dir) schema = get_schema(schema_version=actual_label, log_dir=log_dir) _abort_if_schema_missing(actual_label, schema) derived = derive_entities_from_schema(schema) return schema, derived ``` -------------------------------- ### Activate dcm2bids environment Source: https://unfmontreal.github.io/Dcm2Bids/latest/get-started/install Use this command to activate the environment after installation. ```bash conda activate dcm2bids ``` -------------------------------- ### dcm2niix_version(name='dcm2niix') Source: https://unfmontreal.github.io/Dcm2Bids/latest/dcm2bids/utils/tools Verifies if dcm2niix is installed and returns its version string. ```APIDOC ### Function: dcm2niix_version #### Description Checks and raises an error if dcm2niix is not in the system PATH. Then checks for the version installed. #### Parameters - **name** (str) - Optional - Name of the tool. Default is 'dcm2niix'. #### Returns - **str** - The version string of the dcm2niix installation on the system. ``` -------------------------------- ### Install dcm2bids and dcm2niix via conda Source: https://unfmontreal.github.io/Dcm2Bids/latest/get-started/install Installs the required software packages from the conda-forge channel. ```bash conda install -c conda-forge dcm2bids conda install -c conda-forge dcm2niix ``` -------------------------------- ### Verify dcm2bids and GNU parallel installation Source: https://unfmontreal.github.io/Dcm2Bids/latest/tutorial/parallel Check the installed versions of dcm2bids and GNU parallel to ensure they are correctly configured in your environment. ```bash dcm2bids -v parallel --version ``` -------------------------------- ### Example dry-run output Source: https://unfmontreal.github.io/Dcm2Bids/latest/tutorial/parallel A demonstration of the output generated by a dry-run command. ```bash (dcm2bids) sam:~/tuto-parallel$ parallel --dry-run --plus dcm2bids --auto_extract_entities -c code/config_dcm2bids_t1w.json -d {} -p "{= s/.*\\/PUNK//; s/.tar.*// =}" ::: sourcedata/punk_proj/* dcm2bids --auto_extract_entities -c code/config_dcm2bids_t1w.json -d sourcedata/punk_proj/PUNK041.tar.bz2 -p 041 dcm2bids --auto_extract_entities -c code/config_dcm2bids_t1w.json -d sourcedata/punk_proj/PUNK042.tar.bz2 -p 042 dcm2bids --auto_extract_entities -c code/config_dcm2bids_t1w.json -d sourcedata/punk_proj/PUNK043.tar.bz2 -p 043 dcm2bids --auto_extract_entities -c code/config_dcm2bids_t1w.json -d sourcedata/punk_proj/PUNK044.tar.bz2 -p 044 dcm2bids --auto_extract_entities -c code/config_dcm2bids_t1w.json -d sourcedata/punk_proj/PUNK045.tar.bz2 -p 045 dcm2bids --auto_extract_entities -c code/config_dcm2bids_t1w.json -d sourcedata/punk_proj/PUNK046.tar.bz2 -p 046 dcm2bids --auto_extract_entities -c code/config_dcm2bids_t1w.json -d sourcedata/punk_proj/PUNK047.tar.bz2 -p 047 dcm2bids --auto_extract_entities -c code/config_dcm2bids_t1w.json -d sourcedata/punk_proj/PUNK048.tar.bz2 -p 048 dcm2bids --auto_extract_entities -c code/config_dcm2bids_t1w.json -d sourcedata/punk_proj/PUNK049.tar.bz2 -p 049 dcm2bids --auto_extract_entities -c code/config_dcm2bids_t1w.json -d sourcedata/punk_proj/PUNK050.tar.bz2 -p 050 dcm2bids --auto_extract_entities -c code/config_dcm2bids_t1w.json -d sourcedata/punk_proj/PUNK051.tar.bz2 -p 051 ``` -------------------------------- ### Define instance variables Source: https://unfmontreal.github.io/Dcm2Bids/latest/dcm2bids/dcm2bids_gen Example of an instance variable definition for DICOM directories. ```text 1 ``` ```text dicom_dirs ``` -------------------------------- ### Scaffolding Output Examples Source: https://unfmontreal.github.io/Dcm2Bids/latest/tutorial/first-steps Console output when running the scaffold command with default settings versus a specified output directory. ```bash (dcm2bids) sam:~/dcm2bids-tutorial$ dcm2bids_scaffold INFO | --- dcm2bids_scaffold start --- INFO | Running the following command: /home/sam/miniconda3/envs/dcm2bids-env/bin/dcm2bids_scaffold INFO | OS version: Linux-5.19.0-45-generic-x86_64-with-glibc2.35 INFO | Python version: 3.10.4 (main, May 29 2023, 11:10:38) [GCC 11.3.0] INFO | dcm2bids version: 3.0.0 INFO | Checking for software update INFO | Currently using the latest version of dcm2bids. INFO | The files used to create your BIDS directory were taken from https://github.com/bids-standard/bids-starter-kit. INFO | Tree representation of /home/sam/dcm2bids-tutorials/ INFO | /home/sam/dcm2bids-tutorials/ INFO | ├── code/ INFO | ├── derivatives/ INFO | ├── sourcedata/ INFO | ├── tmp_dcm2bids/ INFO | │ └── log/ INFO | │ └── scaffold_20230703-163905.log INFO | ├── .bidsignore INFO | ├── CHANGES INFO | ├── dataset_description INFO | ├── participants.json INFO | ├── participants.tsv INFO | └── README INFO | Log file saved at /home/sam/dcm2bids-tutorials/tmp_dcm2bids/log/scaffold_20230703-163905.log INFO | --- dcm2bids_scaffold end --- (dcm2bids) sam:~/dcm2bids-tutorial$ ls -a .bidsignore CHANGES dataset_description.json participants.json README code derivatives participants.tsv sourcedata ``` ```bash (dcm2bids) sam:~/dcm2bids-tutorial$ dcm2bids_scaffold -o bids_project INFO | --- dcm2bids_scaffold start --- INFO | Running the following command: /home/sam/miniconda3/envs/dcm2bids-env/bin/dcm2bids_scaffold -o bids_project INFO | OS version: Linux-5.19.0-45-generic-x86_64-with-glibc2.35 INFO | Python version: 3.10.4 (main, May 29 2023, 11:10:38) [GCC 11.3.0] INFO | dcm2bids version: 3.0.dev INFO | Checking for software update INFO | Currently using the latest version of dcm2bids. INFO | The files used to create your BIDS directory were taken from https://github.com/bids-standard/bids-starter-kit. ``` -------------------------------- ### Implement main function logic Source: https://unfmontreal.github.io/Dcm2Bids/latest/dcm2bids/cli/dcm2bids_helper The full implementation of the main function, handling argument parsing, logging setup, and the Dcm2niixGen execution. ```python def main(): """Let's go""" parser = _build_arg_parser() args = parser.parse_args() out_dir = Path(args.output_dir) if args.output_dir != parser.get_default('output_dir'): out_dir = (Path(args.output_dir) / DEFAULT.tmp_dir_name / DEFAULT.helper_dir) log_file = (Path(args.output_dir) / DEFAULT.tmp_dir_name / "log" / f"helper_{datetime.now().strftime('%Y%m%d-%H%M%S')}.log") else: log_file = (Path(DEFAULT.output_dir) / DEFAULT.tmp_dir_name / "log" / f"helper_{datetime.now().strftime('%Y%m%d-%H%M%S')}.log") if args.nest: if isinstance(args.nest, str): log_file = Path( str(log_file).replace("helper_", f"helper_{args.nest.replace(os.path.sep, '-')}_")) out_dir = out_dir / args.nest else: log_file = Path(str(log_file).replace( "helper_", f"helper_{args.dicom_dir[0].replace(os.path.sep, '-')}_" ) out_dir = out_dir / args.dicom_dir[0] log_file.parent.mkdir(parents=True, exist_ok=True) setup_logging(args.log_level, log_file) logger = logging.getLogger(__name__) logger.info("--- dcm2bids_helper start ---") logger.info("Running the following command: " + " ".join(sys.argv)) logger.info("OS version: %s", platform.platform()) logger.info("Python version: %s", sys.version.replace("\n", "")) logger.info(f"dcm2bids version: {__version__}") logger.info(f"dcm2niix version: {dcm2niix_version()}") logger.info("Checking for software update") log_dir = log_file.parent check_latest("dcm2bids", log_dir=log_dir) check_latest("dcm2niix", log_dir=log_dir) app = Dcm2niixGen(dicom_dirs=args.dicom_dir, bids_dir=out_dir, helper=True) rsl = app.run(force=args.overwrite) logger.info(f"Helper files in: {out_dir}\n") logger.info(f"Log file saved at {log_file}") logger.info("--- dcm2bids_helper end ---") return rsl ``` -------------------------------- ### Verify dcm2niix installation and version Source: https://unfmontreal.github.io/Dcm2Bids/latest/dcm2bids/utils/tools Checks if dcm2niix is available in the system PATH and retrieves its version string. ```python def dcm2niix_version(name="dcm2niix"): """ Check and raises an error if dcm2niix is not in PATH. Then check for the version installed. Returns: A string of the version of dcm2niix install on the system """ if not is_tool(name): logger.error(f"{name} is not in your PATH or not installed.") logger.error("https://github.com/rordenlab/dcm2niix to troubleshoot.") raise FileNotFoundError(f"{name} is not in your PATH or not installed." " -> https://github.com/rordenlab/dcm2niix" " to troubleshoot.") try: output = getoutput("dcm2niix --version") except Exception: logger.exception("Checking dcm2niix version", exc_info=False) return else: return output.split()[-1] ``` -------------------------------- ### dcm2niix_version(name='dcm2niix') Source: https://unfmontreal.github.io/Dcm2Bids/latest/dcm2bids/utils/tools Checks if the specified tool is available in the system PATH and retrieves its installed version. ```APIDOC ## dcm2niix_version(name='dcm2niix') ### Description Checks if the dcm2niix tool is present in the system PATH and returns the installed version string. If the tool is not found, it raises a FileNotFoundError. ### Parameters - **name** (string) - Optional - The name of the tool to check, defaults to 'dcm2niix'. ### Returns - **version** (string) - The version string of the installed dcm2niix tool. ``` -------------------------------- ### Configure post-processing operations Source: https://unfmontreal.github.io/Dcm2Bids/latest/how-to/use-advanced-commands Example of using the post_op key to run external commands like pydeface on specific data types and suffixes. ```json "post_op": [ { "cmd": "pydeface --outfile dst_file src_file", "datatype": "anat", "suffix": [ "T1w", "MP2RAGE" ], "custom_entities": "rec-defaced" } ], ``` -------------------------------- ### Define dcm2bids configuration structure Source: https://unfmontreal.github.io/Dcm2Bids/latest/tutorial/first-steps Example JSON structure for mapping acquisitions to BIDS format, including sidecar modifications. ```json { "descriptions": [ { "datatype": "func", "suffix": "bold", "custom_entities": "task-rest", "criteria": { "SeriesDescription": "Axial EPI-FMRI (Interleaved I to S)*" }, "sidecar_changes": { "TaskName": "rest" } } ] } ``` -------------------------------- ### Inspect dcm2bids helper JSON output Source: https://unfmontreal.github.io/Dcm2Bids/latest/tutorial/first-steps Example of a JSON sidecar file generated in the tmp_dcm2bids/helper directory, showing metadata parameters for MRI acquisition. ```json "SliceThickness": 3, "SliceThickness": 3, "SpacingBetweenSlices": 12, "SpacingBetweenSlices": 12, "SAR": 0.00556578, "SAR": 0.00556578, "EchoTime": 0.05, "EchoTime": 0.05, "RepetitionTime": 2.43537, "RepetitionTime": 2.43537, "FlipAngle": 75, "FlipAngle": 75, "PartialFourier": 1, "PartialFourier": 1, "BaseResolution": 72, "BaseResolution": 72, "ShimSetting": [ "ShimSetting": [ -3717, -3717, 15233, 15233, -9833, -9833, -207, -207, -312, -312, -110, -110, 150, 150, 226 ], 226], "TxRefAmp": 316.97, "TxRefAmp": 316.97, "PhaseResolution": 1, "PhaseResolution": 1, "ReceiveCoilName": "Head_32", "ReceiveCoilName": "Head_32", "ReceiveCoilActiveElements": "HEA;HEP", "ReceiveCoilActiveElements": "HEA;HEP", "PulseSequenceDetails": "%CustomerSeq%\\nih_ep2d_bold "PulseSequenceDetails": "%CustomerSeq%\\nih_ep2d_bold "CoilCombinationMethod": "Sum of Squares", "CoilCombinationMethod": "Sum of Squares", "ConsistencyInfo": "N4_VE11C_LATEST_20160120", "ConsistencyInfo": "N4_VE11C_LATEST_20160120", "MatrixCoilMode": "SENSE", "MatrixCoilMode": "SENSE", "PercentPhaseFOV": 100, "PercentPhaseFOV": 100, "PercentSampling": 100, "PercentSampling": 100, "EchoTrainLength": 72, "EchoTrainLength": 72, "PhaseEncodingSteps": 72, "PhaseEncodingSteps": 72, "AcquisitionMatrixPE": 72, "AcquisitionMatrixPE": 72, "ReconMatrixPE": 72, "ReconMatrixPE": 72, "BandwidthPerPixelPhaseEncode": 27.778, "BandwidthPerPixelPhaseEncode": 27.778, "EffectiveEchoSpacing": 0.000499996, "EffectiveEchoSpacing": 0.000499996, "DerivedVendorReportedEchoSpacing": 0.000499996, "DerivedVendorReportedEchoSpacing": 0.000499996, "TotalReadoutTime": 0.0354997, "TotalReadoutTime": 0.0354997, "PixelBandwidth": 2315, "PixelBandwidth": 2315, "DwellTime": 3e-06, "DwellTime": 3e-06, "PhaseEncodingDirection": "j-", | "PhaseEncodingDirection": "j", "SliceTiming": [ "SliceTiming": [ 0, 0, 1.45, | 1.4475, 0.4825, 0.4825, 1.9325, | 1.93, 0.9675 ], | 0.965 ], "ImageOrientationPatientDICOM": [ "ImageOrientationPatientDICOM": [ 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0 ], 0 ], "ImageOrientationText": "Tra", "ImageOrientationText": "Tra", "InPlanePhaseEncodingDirectionDICOM": "COL", "InPlanePhaseEncodingDirectionDICOM": "COL", "ConversionSoftware": "dcm2niix", "ConversionSoftware": "dcm2niix", "ConversionSoftwareVersion": "v1.0.20211006" "ConversionSoftwareVersion": "v1.0.20211006" } } ``` -------------------------------- ### Create Tutorial Directory Source: https://unfmontreal.github.io/Dcm2Bids/latest/tutorial/first-steps Initialize a new directory for the tutorial project. ```bash mkdir dcm2bids-tutorial cd dcm2bids-tutorial ``` ```bash (dcm2bids) sam:~$ mkdir dcm2bids-tutorial (dcm2bids) sam:~$ cd dcm2bids-tutorial/ (dcm2bids) sam:~/dcm2bids-tutorial$ # no output is printed by mkdir and cd if when the command is successful. # You can now see that you are inside dcm2bids-tutorial directory. ``` -------------------------------- ### Initialize bids_starter_kit class Source: https://unfmontreal.github.io/Dcm2Bids/latest/dcm2bids/utils/scaffold Constructor signature for the bids_starter_kit class. ```python class bids_starter_kit( /, *args, **kwargs ) ``` -------------------------------- ### setup_logging Implementation Source: https://unfmontreal.github.io/Dcm2Bids/latest/dcm2bids/utils/logger The implementation logic for the setup_logging function. ```python def setup_logging(log_level, log_file=None): """ Setup logging configuration""" # Check level level = getattr(logging, log_level.upper(), None) if not isinstance(level, int): raise ValueError(f"Invalid log level: {log_level}") fh = logging.FileHandler(log_file) # fh.setFormatter(formatter) fh.setLevel("DEBUG") sh = logging.StreamHandler(sys.stdout) sh.setLevel(log_level) sh_fmt = CustomFormatter(fmt="%(levelname)-8s| %(message)s") sh.setFormatter(sh_fmt) # default formatting is kept for the log file" logging.basicConfig( level=logging.DEBUG, format="%(asctime)s.%(msecs)02d - %(levelname)-8s - %(module)s.%(funcName)s | " "%(message)s", datefmt="%Y-%m-%d %H:%M:%S", handlers=[fh, sh] ) ``` -------------------------------- ### Initialize configuration file Source: https://unfmontreal.github.io/Dcm2Bids/latest/tutorial/first-steps Create an empty JSON configuration file structure. ```json { "descriptions": [] } ``` -------------------------------- ### Initialize BIDS dataset structure with bids_starter_kit Source: https://unfmontreal.github.io/Dcm2Bids/latest/dcm2bids/utils/scaffold The bids_starter_kit class provides predefined string templates for essential BIDS dataset files. ```python # -*- coding: utf-8 -*- class bids_starter_kit(object): CHANGES = """Revision history for your dataset 1.0.0 DATE - Initialized study directory """ dataset_description = """{ "Name": "", "BIDSVersion": "BIDS_VERSION", "License": "", "Authors": [ "" ], "Acknowledgments": "", "HowToAcknowledge": "", "Funding": [ "" ], "ReferencesAndLinks": [ "" ], "DatasetDOI": "" } """ participants_json = """{ "age": { "LongName": "", "Description": "age of the participant", "Units": "years" }, "sex": { "LongName": "", "Description": "sex of the participant as reported by the participant", "Levels": { "M": "male", "F": "female" } }, "group": { "LongName": "", "Description": "experimental group the participant belonged to", "Levels": { "control": "control", "patient": "patient" } } } """ participants_tsv = """participant_id age sex group sub-01 34 M control sub-02 12 F control sub-03 33 F patient """ README = """# README The README is usually the starting point for researchers using your data and serves as a guidepost for users of your data. A clear and informative README makes your data much more usable. In general you can include information in the README that is not captured by some other files in the BIDS dataset (dataset_description.json, events.tsv, ...). It can also be useful to also include information that might already be present in another file of the dataset but might be important for users to be aware of before preprocessing or analysing the data. If the README gets too long you have the possibility to create a `/doc` folder and add it to the `.bidsignore` file to make sure it is ignored by the BIDS validator. More info here: https://neurostars.org/t/where-in-a-bids-dataset-should-i-put-notes-about-individual-mri-acqusitions/17315/3 """ ``` -------------------------------- ### Initialize BIDS directory structure Source: https://unfmontreal.github.io/Dcm2Bids/latest/tutorial/parallel Use this command to create a standard BIDS directory structure in the specified output folder. ```bash dcm2bids_scaffold -o name_of_your_bids_dir ``` -------------------------------- ### Full Logging Module Implementation Source: https://unfmontreal.github.io/Dcm2Bids/latest/dcm2bids/utils/logger Contains the complete setup_logging function and CustomFormatter class definition. ```python # -*- coding: utf-8 -*- """Setup logging configuration""" import logging import sys def setup_logging(log_level, log_file=None): """ Setup logging configuration""" # Check level level = getattr(logging, log_level.upper(), None) if not isinstance(level, int): raise ValueError(f"Invalid log level: {log_level}") fh = logging.FileHandler(log_file) # fh.setFormatter(formatter) fh.setLevel("DEBUG") sh = logging.StreamHandler(sys.stdout) sh.setLevel(log_level) sh_fmt = CustomFormatter(fmt="%(levelname)-8s| %(message)s") sh.setFormatter(sh_fmt) # default formatting is kept for the log file" logging.basicConfig( level=logging.DEBUG, format="%(asctime)s.%(msecs)02d - %(levelname)-8s - %(module)s.%(funcName)s | " "%(message)s", datefmt="%Y-%m-%d %H:%M:%S", handlers=[fh, sh] ) class CustomFormatter(logging.Formatter): """Logging colored formatter, adapted from https://stackoverflow.com/a/56944256/3638629""" grey = '\x1b[38;21m' blue = '\x1b[38;5;39m' yellow = '\x1b[38;5;226m' red = '\x1b[38;5;196m' bold_red = '\x1b[31;1m' reset = '\x1b[0m' def __init__(self, fmt): super().__init__() self.fmt = fmt self.FORMATS = { logging.DEBUG: self.grey + self.fmt + self.reset, logging.INFO: self.blue + self.fmt + self.reset, logging.WARNING: self.yellow + self.fmt + self.reset, logging.ERROR: self.red + self.fmt + self.reset, logging.CRITICAL: self.bold_red + self.fmt + self.reset } def format(self, record): log_fmt = self.FORMATS.get(record.levelno) formatter = logging.Formatter(log_fmt) return formatter.format(record) ``` -------------------------------- ### Display dcm2bids_helper help Source: https://unfmontreal.github.io/Dcm2Bids/latest/tutorial/first-steps View the command-line interface options and usage documentation. ```bash dcm2bids_helper --help ``` ```bash (dcm2bids) sam:~/dcm2bids-tutorial/bids_project$ dcm2bids_helper --help usage: dcm2bids_helper [-h] -d DICOM_DIR [DICOM_DIR ...] [-o OUTPUT_DIR] [-n [NEST]] [--force] [-l {DEBUG,INFO,WARNING,ERROR,CRITICAL}] Converts DICOM files to NIfTI files including their JSON sidecars in a temporary directory which can be inspected to make a dcm2bids config file. options: -h, --help show this help message and exit -d DICOM_DIR [DICOM_DIR ...], --dicom_dir DICOM_DIR [DICOM_DIR ...] DICOM directory(ies) or archive(s) (tar, tar.bz2, tar.gz or zip). -o OUTPUT_DIR, --output_dir OUTPUT_DIR Output directory. (Default: [/home/runner/work/Dcm2Bids/Dcm2Bids/tmp_dcm2bids/helper] -n [NEST], --nest [NEST] Nest a directory in . Useful if many helper runs are needed 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_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] Documentation at https://unfmontreal.github.io/Dcm2Bids/ ``` -------------------------------- ### setup_logging(log_level, log_file=None) Source: https://unfmontreal.github.io/Dcm2Bids/latest/dcm2bids/utils/logger Configures the global logging settings for the application. It sets up both a file handler and a stream handler with a custom colored formatter. ```APIDOC ## setup_logging(log_level, log_file=None) ### Description Configures the logging system. It initializes a file handler for detailed logs and a stream handler for console output with colored formatting. ### Parameters - **log_level** (str) - Required - The logging level (e.g., 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'). - **log_file** (str) - Optional - The path to the file where logs should be written. ### Exceptions - **ValueError** - Raised if the provided log_level is not a valid logging level. ``` -------------------------------- ### Verify Python version Source: https://unfmontreal.github.io/Dcm2Bids/latest/get-started/install Commands to check the installed Python version or enter an interactive shell. ```bash python --version ``` ```bash python ``` -------------------------------- ### Create configuration file via terminal Source: https://unfmontreal.github.io/Dcm2Bids/latest/tutorial/first-steps Use the nano editor to create the configuration file in the project directory. ```bash nano code/dcm2bids_config.json ``` ```bash (dcm2bids) sam:~/dcm2bids-tutorial/bids_project$ nano code/dcm2bids_config.json (dcm2bids) sam:~/dcm2bids-tutorial/bids_project$ ``` -------------------------------- ### Display Dcm2Bids help information Source: https://unfmontreal.github.io/Dcm2Bids/latest/how-to/use-main-commands Use these commands to view the complete list of available options and arguments for the CLI. ```bash dcm2bids -h ``` ```bash dcm2bids --help ``` -------------------------------- ### Run dcm2bids_scaffold Source: https://unfmontreal.github.io/Dcm2Bids/latest/how-to/container Execute the scaffold utility to initialize a BIDS directory structure. ```bash docker run --rm -it \ --entrypoint /venv/bin/dcm2bids_scaffold \ -v /path/to/bids:/bids \ unfmontreal/dcm2bids:${VERSION} -o /bids/new_scaffold ``` ```bash apptainer exec \ -e --containall \ -B /path/to/bids:/bids \ dcm2bids.sif dcm2bids_scaffold -o /bids/new_scaffold ``` -------------------------------- ### bids_starter_kit class definition Source: https://unfmontreal.github.io/Dcm2Bids/latest/dcm2bids/utils/scaffold Full class definition containing default templates for BIDS metadata files. ```python class bids_starter_kit(object): CHANGES = """Revision history for your dataset 1.0.0 DATE - Initialized study directory """ dataset_description = """{ "Name": "", "BIDSVersion": "BIDS_VERSION", "License": "", "Authors": [ "" ], "Acknowledgments": "", "HowToAcknowledge": "", "Funding": [ "" ], "ReferencesAndLinks": [ "" ], "DatasetDOI": "" } """ participants_json = """{ "age": { "LongName": "", "Description": "age of the participant", "Units": "years" }, "sex": { "LongName": "", "Description": "sex of the participant as reported by the participant", "Levels": { "M": "male", "F": "female" } }, "group": { "LongName": "", "Description": "experimental group the participant belonged to", "Levels": { "control": "control", "patient": "patient" } } } """ participants_tsv = """participant_id age sex group sub-01 34 M control sub-02 12 F control sub-03 33 F patient """ README = """# README The README is usually the starting point for researchers using your data and serves as a guidepost for users of your data. A clear and informative README makes your data much more usable. In general you can include information in the README that is not captured by some other files in the BIDS dataset (dataset_description.json, events.tsv, ...). It can also be useful to also include information that might already be present in another file of the dataset but might be important for users to be aware of before preprocessing or analysing the data. If the README gets too long you have the possibility to create a `/doc` folder and add it to the `.bidsignore` file to make sure it is ignored by the BIDS validator. More info here: https://neurostars.org/t/where-in-a-bids-dataset-should-i-put-notes-about-individual-mri-acqusitions/17315/3 """ ```