Z03-heuristics/heuristic.py
Michał Szczepanik 0eb9d67c8d Rename extra_data to uncategorized
In a conversation with FW and MH we agreed that "extra_data" may
suggest some acquisitions done in addition to the standard protocol,
while "uncategorized" sounds more appropriate for dicom series which
were not categorized into any expected categories by the heuristic.

This catch-all folder will include misnomers (name did not match any
criteria), repetitions (a series got replaced by repeating the
protocol with the same name) and incomplete functional runs (number of
volumes not matching expectations).
2024-09-24 13:35:17 +02:00

205 lines
7.2 KiB
Python

from __future__ import annotations
import logging
import os
from pathlib import Path
from typing import Optional
from heudiconv.utils import SeqInfo
# set up custom logging to stdout
lgr = logging.getLogger("heudiconv.heuristic")
formatter = logging.Formatter(fmt="%(levelname)s: %(message)s")
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
lgr.addHandler(stream_handler)
lgr.setLevel("INFO")
# additional logging to file, if BIDS_LOG_FILE env var is defined
# the file will be created on 1st message but we'll create parent dir upfront
if (log_file := os.environ.get("BIDS_LOG_FILE")) is not None:
log_fp = Path(log_file)
if not log_fp.parent.is_dir():
log_fp.parent.mkdir(parents=True)
file_handler = logging.FileHandler(log_fp, delay=True, mode="w")
file_handler.setFormatter(formatter)
file_handler.setLevel("WARNING")
lgr.addHandler(file_handler)
def create_key(
template: Optional[str],
outtype: tuple[str, ...] = ("nii.gz",),
annotation_classes: None = None,
) -> tuple[str, tuple[str, ...], None]:
if template is None or not template:
raise ValueError("Template must be a valid format string")
return (template, outtype, annotation_classes)
def _place(si: SeqInfo, target: list, elsewhere: list, n: Optional[list] = None):
"""Place a sequence id into the right list
This works on the assumption that we do not have runs, so anything
that comes later (and passes the length criterion, if given) goes
into `target` replacing the session which came earlier. IDs of any
rejected series (either mismatched length or superseded) go into
`elsewhere` and a warning is logged.
"""
if n is not None and si.series_files != n:
# disqualified by number of volumes
elsewhere.append(si.series_id)
lgr.warning(
f"Ignoring {si.series_id}: expected 740 dicoms, found {si.series_files}"
)
elif len(target) > 0:
# we go in order, so this is a replacement - put existing aside
assert len(target) == 1 # there should be just one, assert to make sure
old_id = target.pop()
target.append(si.series_id)
elsewhere.append(old_id)
lgr.warning(
f"Series {old_id} got supersided by {si.series_id}, which came later"
)
else:
target.append(si.series_id)
def infotodict(
seqinfo: list[SeqInfo],
) -> dict[tuple[str, tuple[str, ...], None], list[str]]:
"""Heuristic evaluator for determining which runs belong where
allowed template fields - follow python string module:
item: index within category
subject: participant id
seqitem: run number during scanning
subindex: sub index within group
"""
t1w = create_key(
"{bids_subject_session_dir}/anat/{bids_subject_session_prefix}_T1w"
)
t2w = create_key(
"{bids_subject_session_dir}/anat/{bids_subject_session_prefix}_T2w"
)
flair = create_key(
"{bids_subject_session_dir}/anat/{bids_subject_session_prefix}_FLAIR"
)
rest = create_key(
"{bids_subject_session_dir}/func/{bids_subject_session_prefix}_task-rest_dir-AP_bold"
)
tapp = create_key(
"{bids_subject_session_dir}/func/{bids_subject_session_prefix}_task-fingertapping_dir-AP_bold"
)
dwi98 = create_key(
"{bids_subject_session_dir}/dwi/{bids_subject_session_prefix}_acq-98dir_dir-AP_dwi"
)
dwi99 = create_key(
"{bids_subject_session_dir}/dwi/{bids_subject_session_prefix}_acq-99dir_dir-AP_dwi"
)
dwi_sl = create_key(
"{bids_subject_session_dir}/dwi/{bids_subject_session_prefix}_acq-slice_dir-AP_dwi"
)
fm_rest = create_key(
"{bids_subject_session_dir}/fmap/{bids_subject_session_prefix}_acq-FID_dir-PA_run-1_epi"
)
fm_tapp = create_key(
"{bids_subject_session_dir}/fmap/{bids_subject_session_prefix}_acq-FID_dir-PA_run-2_epi"
)
dwi_b0_ap = create_key(
"{bids_subject_session_dir}/fmap/{bids_subject_session_prefix}_acq-SE_dir-AP_run-1_epi"
)
dwi_b0_pa = create_key(
"{bids_subject_session_dir}/fmap/{bids_subject_session_prefix}_acq-SE_dir-PA_run-1_epi"
)
info: dict[tuple[str, tuple[str, ...], None], list[str]] = {
t1w: [],
t2w: [],
flair: [],
rest: [],
tapp: [],
dwi98: [],
dwi99: [],
dwi_sl: [],
fm_rest: [],
fm_tapp: [],
dwi_b0_ap: [],
dwi_b0_pa: [],
}
protocols_to_skip = {"localizer", "Phoenix Document"}
skipped_series = []
uncategorized_series = []
for s in seqinfo:
"""
The namedtuple `s` contains the following fields:
* total_files_till_now
* example_dcm_file
* series_id
* dcm_dir_name
* unspecified2
* unspecified3
* dim1
* dim2
* dim3
* dim4
* TR
* TE
* protocol_name
* is_motion_corrected
* is_derived
* patient_id
* study_description
* referring_physician_name
* series_description
* image_type
"""
if s.protocol_name.startswith("t1_mprage_0.9mm"):
_place(s, info[t1w], uncategorized_series)
elif s.protocol_name.startswith("t2w_space_0.9mm"):
_place(s, info[t2w], uncategorized_series)
elif s.protocol_name.startswith("Axial T2-FLAIR"):
_place(s, info[flair], uncategorized_series)
elif s.protocol_name.startswith("rfMRI_resting_AP"):
_place(s, info[rest], uncategorized_series, n=740)
elif s.protocol_name.startswith("rfMRI_resting_PA"):
_place(s, info[fm_rest], uncategorized_series, n=10)
elif s.protocol_name.startswith("tfMRI_tapping_AP"):
_place(s, info[tapp], uncategorized_series, n=417)
elif s.protocol_name.startswith("tfMRI_tapping_PA"):
_place(s, info[fm_tapp], uncategorized_series, n=10)
elif s.protocol_name.startswith("ep2d_diff_dir98_AP"):
_place(s, info[dwi98], uncategorized_series)
elif s.protocol_name.startswith("ep2d_diff_dir99_AP"):
_place(s, info[dwi99], uncategorized_series)
elif s.protocol_name.startswith("ep2d_diff_b=0_AP"):
_place(s, info[dwi_b0_ap], uncategorized_series)
elif s.protocol_name.startswith("ep2d_diff_b=0_PA"):
_place(s, info[dwi_b0_pa], uncategorized_series)
elif s.protocol_name.startswith("ep2d_diff_slice"):
_place(s, info[dwi_sl], uncategorized_series)
elif s.protocol_name in protocols_to_skip:
skipped_series.append(s.series_id)
else:
lgr.warning("Don't know where to stick %s", s.series_id)
uncategorized_series.append(s.series_id)
# put series rejected due to repetition under uncategorized (to be .bidsignore'd)
# use session id as file name
for sid in uncategorized_series:
info[create_key(f"{{bids_subject_session_dir}}/uncategorized/{sid}")] = [sid]
# screen for missing acquisitions
for key, series_ids in info.items():
if len(series_ids) == 0:
lgr.warning(f"Found no dicom series to populate {key[0]}")
return info