The HeuDiConv heuristic.py and conversion script from SpinLab, explained line by line
SpinLab Autopilot writes two pieces of code for every study: a heuristic.py file that tells HeuDiConv how to name each series in BIDS, and a conversion script that runs HeuDiConv and the BIDS validator. This guide goes through both, section by section, using the files generated for the 7 T sample study, so that you can read, check and edit them with confidence.

Part 1: heuristic.py
1. The create_key() helper
def create_key(template, outtype=("nii.gz",), annotation_classes=None):
if template is None or not template:
raise ValueError("Template must be a valid format string")
return template, outtype, annotation_classes
HeuDiConv expects each output to be described as a tuple of template, output type and annotation classes. create_key() builds that tuple. The template is a BIDS path in which {subject} (and {session}, if used) is filled in for each participant. outtype=("nii.gz",) asks dcm2niix for compressed NIfTI files.
2. Filling IntendedFor automatically
POPULATE_INTENDED_FOR_OPTS = {
'matching_parameters': ['ImagingVolume'],
'criterion': 'First',
}
Field maps must say which images they correct, in the IntendedFor field of their JSON file. This block lets HeuDiConv fill it in: field maps are matched to images that cover the same imaging volume, and if several field maps qualify, the first is used. Autopilot chose First here because the sample headers have no acquisition times (they are anonymised); with real data it can match by the closest acquisition time instead.
3. One key per BIDS file
def infotodict(seqinfo):
"""Map each DICOM series to a BIDS file name."""
anat_mp2rage_inv1 = create_key("sub-{subject}/anat/sub-{subject}_inv-1_MP2RAGE")
anat_unit1 = create_key("sub-{subject}/anat/sub-{subject}_UNIT1")
anat_flair = create_key("sub-{subject}/anat/sub-{subject}_FLAIR")
func_bold_rest_ap = create_key("sub-{subject}/func/sub-{subject}_task-rest_dir-AP_bold")
dwi_dwi_ap = create_key("sub-{subject}/dwi/sub-{subject}_dir-AP_dwi")
perf_asl = create_key("sub-{subject}/perf/sub-{subject}_asl")
perf_m0scan = create_key("sub-{subject}/perf/sub-{subject}_m0scan")
anat_mri_23na = create_key("extra_data/sub-{subject}/sub-{subject}_acq-23Na_MRI")
...
info = {anat_mp2rage_inv1: [], anat_unit1: [], anat_flair: [], ...}
infotodict() is the function HeuDiConv calls. It first defines one key for every file that will be written. Each path follows BIDS rules: the folder (anat, func, dwi, fmap, perf), then entities such as task-rest or dir-AP, then the suffix (MP2RAGE, FLAIR, bold, dwi, asl). The sodium series goes to extra_data/ because BIDS has no suffix for X-nuclei yet. The info dictionary starts with an empty list for each key.
4. Matching rules
for s in seqinfo:
if s.series_description == "mp2rage_0.75iso_INV1": # series 3
info[anat_mp2rage_inv1].append(s.series_id)
elif s.series_description == "cmrr_mbep2d_bold_rest_1.6iso_AP": # series 12
info[func_bold_rest_ap].append(s.series_id)
elif s.series_description == "gre_field_mapping_2mm" and 'M' in s.image_type:
info[fmap_magnitude].append(s.series_id)
elif s.series_description == "gre_field_mapping_2mm" and 'P' in s.image_type:
info[fmap_phasediff].append(s.series_id)
...
return info
HeuDiConv passes a list called seqinfo, one entry per DICOM series. The loop compares each series description with the exact text read from your headers and adds the series ID to the right key. Autopilot uses exact matches (==) rather than “contains”, so that a series such as ..._AP_SBRef is not accidentally captured by the rule for ..._AP. Where two series share a description, as the magnitude and phase images of a gradient-echo field map do, the rule also checks image_type (M for magnitude, P for phase).
5. What was left out
# Left out (not converted):
# series 1 AAHead_Scout_64ch-head-coil — Planning scan
# series 13 MoCoSeries — Computed on the scanner — recompute from raw data instead
The file ends with a record of every series that was not converted and why, so a reviewer can see that nothing was silently dropped.
Part 2: the conversion script

#!/bin/bash
set -euo pipefail
DICOM_ROOT="/data/dicom" # folder that contains one sub-folder per subject
BIDS_DIR="/data/bids"
SUBJECT="01"
heudiconv \
-d "${DICOM_ROOT}/{subject}/*/*" \
-s "${SUBJECT}" \
-f "${BIDS_DIR}/code/heuristic.py" \
-c dcm2niix -b --overwrite \
-o "${BIDS_DIR}"
bids-validator "${BIDS_DIR}"
| Line | What it does |
|---|---|
set -euo pipefail | Stops the script at the first error, treats unset variables as errors and catches failures inside pipes |
-d ".../{subject}/*/*" | The DICOM file pattern. It ends in /* so that HeuDiConv receives files, not a folder; a pattern without it causes IsADirectoryError: [Errno 21] |
-s | The subject label that replaces {subject} |
-f | The heuristic file, kept in code/ inside the BIDS dataset |
-c dcm2niix -b | Convert with dcm2niix and write BIDS JSON sidecars |
--overwrite | Replace earlier outputs if you run the conversion again |
-o | The BIDS output folder |
bids-validator | Checks the result against the BIDS specification |
The script also contains a commented Docker version (nipy/heudiconv) for computers where HeuDiConv is not installed.
Running it
- Copy
heuristic.pyto/data/bids/code/. - Edit the three variables at the top of the script for your folders and subject.
- Run
bash convert_to_bids.sh. - Read the validator output; fix any errors before processing.
- For more subjects, change
SUBJECTor loop over a list of IDs.
References
- Gorgolewski KJ, Auer T, Calhoun VD, et al. The brain imaging data structure, a format for organizing and describing outputs of neuroimaging experiments. Sci Data 2016;3:160044.
- HeuDiConv documentation: heudiconv.readthedocs.io
- Li X, Morgan PS, Ashburner J, Smith J, Rorden C. The first step for neuroimaging data analysis: DICOM to NIfTI conversion. J Neurosci Methods 2016;264:47–56.
Related articles
Last reviewed: 7 November 2026. SpinLab and SpinCalc are free tools developed by MRISpin. Screenshots show the tools as they were on this date and may change as the tools are updated. Generated scripts should be checked before use on real data.



