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_retainedis a share of the recording’s duration. It isthe same number for every channel set, so it stays on the whole-file section alone (see
_WHOLE_FILE_KEYS); repeating it under_longwould 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#
Map each BIDS run label to its derivatives: |
|
Pull the BIDS entities back out of a run label, for the columns a database wants. |
|
The run label a record is named for: the inverse of |
|
Each channel’s variance carried by its fitted short-channel part, over the frames the fit kept. |
|
The raw-family scalars a quality verdict is read off, as one flat dict. |
|
The record with every |
|
The three views of the original recording, as |
|
One haemoglobin file measured over every channel, the long ones, the short ones. |
|
The whole motion family, from the optical density either side of the correction. |
|
One entry per annotated condition, sliced from |
|
Every SQM section for one run, keyed by section name, plus |
|
The on-disk record: provenance keys wrapped around the sections themselves. |
|
Write |
|
Write |
|
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.snirfbecomes{"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"
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)
designis the GLM step’s design table (censored= 1 marks a frame left out),betasitsdesc-glm_nirsmaptable,haemothe 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
_longsection 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
_longsection 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 onraw_long_cv_meanwould 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_longis skipped when the long set is the whole montage, since it would repeatraw;raw_shortis skipped when there is no short channel. Both missing is therefore ambiguous on its own, which is whatn_long_channelsandn_short_channelsonraware 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_scoresis 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_freqis 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.computemaps 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, andmotion_post*is the corrected file measured again on the keysraw*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 theraw*section’s GVTD cutoff for the matching channel set, so before and after are counted against one yardstick. See_motion_post_section().rejectedis the run’s rejected channels, which the GVTD ofmotion_post*leaves out as theraw*GVTD does.before_odNone 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 getsmotion_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
windowedand recomputed on a crop.Written whenever the recording carries conditions:
--by-conditiondecides 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_rootis where to look for the original recording when the path its sidecar recorded no longer resolves; without it a moved tree loses theraw*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.jsonand its tables, provenance keys included.The provenance lives in the same file rather than a sidecar beside it: a sidecar for
x.jsonwould resolve tox.jsonitself. A top-levelstepis 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.tsvfrom 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.labelsrestricts 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_rootrescues theraw*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_bandshas 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*_longand*_shortmetric describes a channel set the run did not use.