nirspipe.qc.subject.sqm_record#

Per-run SQM record: one JSON per BIDS run, assembled after the pipeline has finished.

The pipeline writes each stage to disk; this reads those files back and computes every metric once, at one named stage, through one writer. It works on any tree a past run left behind.

Sections name the input a metric family was measured on. The metric names inside a section are the names the metric functions return:

raw every channel of the original recording, the archival view raw_long the same recording, long channels only raw_short the same recording, short channels only: are the regressors trustworthy motion what the motion correction repaired, from the OD either side of it preproc Beer-Lambert output, before any filtering filtered the same signal after the bandpass resampled the same signal after the resample, when one ran errts the confound-regression residual, the last denoising step there is

Every family is written three times, over every channel, the long ones and the short ones: raw / raw_long / raw_short, preproc / preproc_long / preproc_short, and so on for each stage. One file seen through three channel sets, so the only thing that differs within a trio is source-detector separation, and a _long number is only ever compared against another _long one.

Split a new metric three ways unless it cannot be. A short channel sees scalp rather than cortex, so an average over both sets describes neither. A metric taken across channels splits too: GVTD, the spike counts and the correction footprint are each a measurement of the set they are given, “at least a tenth of these channels” being a different question per set, and spike_count is printed beside its set’s channel count. One kind of metric is the exception:

not channel-based pct_data_retained is a share of the recording’s duration. It is

the same number for every channel set, so it stays on the whole-file section alone (see _WHOLE_FILE_KEYS); repeating it under _long would name a quantity that does not exist.

Anything else, split it.

Bad channels: the Beer-Lambert conversion is the dividing line, never the section.

raw / raw_long / raw_short / motion intensity and OD, include them preproc / filtered / resampled / errts haemoglobin, exclude them

A rejected channel is still part of what the machine recorded, so everything measured before Beer-Lambert describes the recording as it arrived; after it the channel is out of the analysis, and those metrics go through mne.pick_types, which drops bads by default. Excluding them earlier would make sci_mean circular, taken over channels selected for good SCI. channel_retention_rate is what says how many were dropped. errts also drops the short channels its regressor spanned, whose residual is float noise, as the GLM tables, ALFF and FC do: its sidecar names them and read_snirf marks them.

GVTD is the exception, in every section: it asks how much the analysed data moved, so it is taken over the kept channels, as --gvtd-censor takes it, and rejecting a channel moves it.

Per-channel values live under per_channel so the sections stay scalar. Those are always complete, every channel, whichever section they sit under.

Module Contents#

Functions#

scan_runs

Map each BIDS run label to its derivatives: {label: {desc: path}}.

entities_of

Pull the BIDS entities back out of a run label, for the columns a database wants.

record_path

record_label

The run label a record is named for: the inverse of record_path().

short_regression_shares

Each channel’s variance carried by its fitted short-channel part, over the frames the fit kept.

raw_verdict_view

The raw-family scalars a quality verdict is read off, as one flat dict.

fill_skipped_long_sections

The record with every _long section an all-long montage skipped filled back in.

raw_sections

The three views of the original recording, as (sections, per_channel).

haemo_sections

One haemoglobin file measured over every channel, the long ones, the short ones.

motion_sections

The whole motion family, from the optical density either side of the correction.

condition_sections

One entry per annotated condition, sliced from windowed and recomputed on a crop.

compute_run_sections

Every SQM section for one run, keyed by section name, plus per_channel.

sqm_record_dict

The on-disk record: provenance keys wrapped around the sections themselves.

write_run_sqm

Write <label>_desc-sqm_qc.json and its tables, provenance keys included.

write_channel_table

Write <label>_desc-channel_qc.tsv from the record and the sci sidecar, report or not.

build_sqm_records

Write one SQM record per run found under nirs_dir. Band edges default to the values the run’s own sidecars recorded, so a past tree needs no arguments.

Data#

API#

nirspipe.qc.subject.sqm_record.logger = 'get_logger(...)'#
nirspipe.qc.subject.sqm_record.PRE_BANDPASS_HAEMO_STAGE = 'preproc'#
nirspipe.qc.subject.sqm_record.POST_BANDPASS_HAEMO_STAGES = None#
nirspipe.qc.subject.sqm_record.SECTIONS = ('raw', 'raw_long', 'raw_short', 'motion', 'motion_long', 'motion_short', 'motion_post', 'motion_pos...#
nirspipe.qc.subject.sqm_record.SQM_DESCS = ('sqm', 'sqmraw')#
nirspipe.qc.subject.sqm_record.OPTIONAL_SECTIONS = ('censor', 'imu', 'whitening', 'short_regression', 'rawhaemo', 'rawhaemo_long', 'rawhaemo_short')#
nirspipe.qc.subject.sqm_record.scan_runs(nirs_dir: pathlib.Path) → dict[str, dict[str, pathlib.Path]]#

Map each BIDS run label to its derivatives: {label: {desc: path}}.

sub-01_task-tapping_desc-preproc_nirs.snirf becomes {"sub-01_task-tapping": {"preproc": <path>}}, so a subject holding three tasks yields three runs rather than one that silently keeps the last.

nirspipe.qc.subject.sqm_record.entities_of(label: str) → dict[str, str | None]#

Pull the BIDS entities back out of a run label, for the columns a database wants.

nirspipe.qc.subject.sqm_record.RECORD_SUFFIXES = None#
nirspipe.qc.subject.sqm_record.RECORD_SUFFIX = None#
nirspipe.qc.subject.sqm_record.record_path(nirs_dir: pathlib.Path, label: str) → pathlib.Path#
nirspipe.qc.subject.sqm_record.record_label(path: Path | str) → str#

The run label a record is named for: the inverse of record_path().

"sub-01_task-rest_desc-sqm_qc.json" -> "sub-01_task-rest"

nirspipe.qc.subject.sqm_record.short_regression_shares(design: pandas.DataFrame, betas: pandas.DataFrame, haemo: mne.io.BaseRaw) → dict[str, float]#

Each channel’s variance carried by its fitted short-channel part, over the frames the fit kept.

share = var(X_short @ theta_short) / var(y)

design is the GLM step’s design table (censored = 1 marks a frame left out), betas its desc-glm_nirsmap table, haemo the series it was fitted on. A channel whose short-channel betas are blank, fitted against itself, has no entry.

nirspipe.qc.subject.sqm_record.raw_verdict_view(record: dict) → dict#

The raw-family scalars a quality verdict is read off, as one flat dict.

raw_verdict_view({"raw": {"sci_mean": 0.71, "duration_s": 600},
                  "raw_long": {"sci_mean": 0.86}})
-> {"sci_mean": 0.86, "duration_s": 600}

The long-channel split sits on top of the whole-file section rather than replacing it, because the split carries only what a channel set can be measured on and the run-level numbers (montage counts, duration) live underneath.

One function because three readers need the same answer: the subject report, the dyad raw report and the dyad analysis.

nirspipe.qc.subject.sqm_record.fill_skipped_long_sections(record: dict) → dict#

The record with every _long section an all-long montage skipped filled back in.

fill_skipped_long_sections({“raw”: {“cv_mean”: 0.02, “n_long_channels”: 40}}) -> {“raw”: {…}, “raw_long”: {“cv_mean”: 0.02, “n_long_channels”: 40}}

A _long section is not written when the long set is the whole file, because it would repeat the section above it. That is a storage rule and not a measurement one: on such a montage the whole-file section is the long-channel one. A reader comparing a cohort on raw_long_cv_mean would otherwise drop every all-long run rather than compare it, and drop it silently, since an absent section and a failed one look the same from outside. raw_verdict_view() is the same rule for one section at a time.

Absence plus a positive long count is what identifies the case, and it is exact: a montage whose long channels are only part of it has the section written, and one with no long channels at all has nothing to fill from. The per-channel dicts are filled with it, so a filled record stays readable by everything that reads an unfilled one.

nirspipe.qc.subject.sqm_record.raw_sections(raw_intensity: mne.io.Raw, sci_scores: dict[str, float], bad_channels: list[str], cardiac_l_freq: float, cardiac_h_freq: float, sep_bands=None, good_frac_scores: dict[str, float] | None = None, resp_h_freq: float | None = None) → tuple[dict[str, Any], dict[str, Any]]#

The three views of the original recording, as (sections, per_channel).

One file measured over every channel, over the long ones, and over the short ones. Every writer of a run record goes through here, so a tree holds one record shape whichever command produced it and the group table needs no per-writer special case.

raw_long is skipped when the long set is the whole montage, since it would repeat raw; raw_short is skipped when there is no short channel. Both missing is therefore ambiguous on its own, which is what n_long_channels and n_short_channels on raw are for: two zeros means no registered optode positions, and any other pair means a montage of one kind.

The separations that produced the split are stamped beside those counts, since the defaults can move and a reader of an old record cannot otherwise recover them.

good_frac_scores is the passing-window share the screening already counted, passed in rather than recounted: it is two windowed passes over the recording, and a caller that screened has it. None leaves the entry empty rather than paying for it again.

resp_h_freq is where each set’s heart rate is looked for from; a heart rate outside the cardiac band is warned about in the log. None measures no heart rate.

nirspipe.qc.subject.sqm_record.haemo_sections(name: str, raw_haemo: mne.io.Raw, compute, sep_bands=None) → tuple[dict[str, Any], dict[str, Any]]#

One haemoglobin file measured over every channel, the long ones, the short ones.

The same three-way split as raw_sections(), and for the same reason: a short channel sees scalp, so a mean taken over both sets describes neither.

compute maps a Raw to a flat metric dict, which is what lets the unfiltered stage (band power and drift included) and the filtered ones share this.

A subset that turns out to be the whole file is skipped rather than written twice.

nirspipe.qc.subject.sqm_record.motion_sections(before_od: mne.io.Raw | None, after_od: mne.io.Raw, section, windowed: dict[str, Any], raw_thresh, cardiac_l_freq: float, cardiac_h_freq: float, sep_bands=None, rejected: list[str] | None = None) → None#

The whole motion family, from the optical density either side of the correction.

Two groups. motion* is the correction’s footprint, how much of the recording it touched, and motion_post* is the corrected file measured again on the keys raw* already carries, so a pair subtracts. Both split by separation, because the footprint’s frame counts ask how many channels were corrected at once and that is a different measurement per set rather than the same one regrouped.

raw_thresh(name) returns the raw* section’s GVTD cutoff for the matching channel set, so before and after are counted against one yardstick. See _motion_post_section().

rejected is the run’s rejected channels, which the GVTD of motion_post* leaves out as the raw* GVTD does.

before_od None leaves the footprint half out and keeps the rest: measuring what the correction touched needs both sides, measuring the corrected file needs only the one. A tree carrying a corrected file but no pre-correction one still gets motion_post*.

Written in place through section, the same writer the rest of the record uses, so a family that fails costs that family alone. One function because two callers assemble it: the pipeline’s record reads the two files off disk, and raw QC (nirspipe-qc) corrects a copy in memory and never writes it.

nirspipe.qc.subject.sqm_record.condition_sections(sections: dict[str, Any], raw_intensity: mne.io.Raw, stages: dict[str, pathlib.Path], *, cardiac_l_freq: float, cardiac_h_freq: float, resp_l_freq: float, resp_h_freq: float, sep_bands=None, imu: dict | None = None) → dict[str, Any]#

One entry per annotated condition, sliced from windowed and recomputed on a crop.

Written whenever the recording carries conditions: --by-condition decides what a report shows, not what the record measures. Anything deriving a scale from the recording it is handed (the filtered GVTD trace, per-channel z-scores, a threshold off a distribution) stays whole-run and is absent here. {} when no annotation holds two screening windows.

nirspipe.qc.subject.sqm_record.compute_run_sections(stages: dict[str, pathlib.Path], *, cardiac_l_freq: float, cardiac_h_freq: float, resp_l_freq: float, resp_h_freq: float, qc_window_s: float = 10.0, bids_root: pathlib.Path | None = None, sep_bands=None) → dict[str, Any]#

Every SQM section for one run, keyed by section name, plus per_channel.

bids_root is where to look for the original recording when the path its sidecar recorded no longer resolves; without it a moved tree loses the raw* sections.

nirspipe.qc.subject.sqm_record.sqm_record_dict(sections: dict[str, Any], sources: list[str]) → dict[str, Any]#

The on-disk record: provenance keys wrapped around the sections themselves.

Shared by both writers so a record is the same shape whichever command made it. The provenance table lists a record’s metric names prefixed the way the group table names its columns, so the two read as one vocabulary.

nirspipe.qc.subject.sqm_record.write_run_sqm(nirs_dir: pathlib.Path, label: str, stages: dict[str, pathlib.Path], sections: dict[str, Any], bids_root: pathlib.Path | None = None) → pathlib.Path#

Write <label>_desc-sqm_qc.json and its tables, provenance keys included.

The provenance lives in the same file rather than a sidecar beside it: a sidecar for x.json would resolve to x.json itself. A top-level step is all the provenance graph needs to pick the file up.

nirspipe.qc.subject.sqm_record.write_channel_table(nirs_dir: pathlib.Path, label: str, stages: dict[str, pathlib.Path], sections: dict[str, Any]) → None#

Write <label>_desc-channel_qc.tsv from the record and the sci sidecar, report or not.

nirspipe.qc.subject.sqm_record.build_sqm_records(nirs_dir: pathlib.Path, *, cardiac_l_freq: float | None = None, cardiac_h_freq: float | None = None, resp_l_freq: float | None = None, resp_h_freq: float | None = None, qc_window_s: float | None = None, bids_root: pathlib.Path | None = None, labels: set[str] | None = None, sep_bands=None, failures: dict[str, str] | None = None) → list[pathlib.Path]#

Write one SQM record per run found under nirs_dir. Band edges default to the values the run’s own sidecars recorded, so a past tree needs no arguments.

failures, when given, receives each run whose record could not be written, keyed by its stem, with the first line of the reason, so the run’s report can say why.

labels restricts the work to those BIDS run stems, which is what a --task-label run wants: the tasks it did not touch keep the records they already had, computed with the settings they were computed under. Omit it to rebuild every run in the directory.

bids_root rescues the raw* sections when the tree has been moved since the run: the sidecars name the original recording by an absolute path that no longer resolves, but the filename is still correct, so it is searched for there.

sep_bands has to be the run’s own, unlike the band edges above: nothing on disk records them, so left out they fall back to the package defaults and every *_long and *_short metric describes a channel set the run did not use.