nirspipe.qc.common.channel_table#

Per-channel QC rows, assembled once for every view that prints them.

The subject report, the raw viewer and the GUI all answer the same question channel by channel: what did this channel score, was it kept, and which separation block is it in. Assembled here once, so the three cannot read different halves of the record and disagree.

Everything here reads an SQM record and returns plain dicts. Nothing computes a metric and nothing renders: the record is the single measurement, and a view that wants a number it does not carry is asking for a metric that was never stored.

Module Contents#

Functions#

uncorrected_view

record as raw QC reads it: channel_rows() takes the correlation before the correction.

channel_rows

One row per channel: its scores, its verdict, and which separation block it is in.

channel_order

A sort key: source, then detector number, then wavelength.

pair_wavelengths

The wavelengths behind the rows, in the order pair_rows() keeps them.

pair_rows

The same rows collapsed to one per source-detector pair.

separation_blocks

Rows grouped by separation, long first, empty blocks dropped.

heatmap_args

Arguments for channel_quality_heatmap(), ordered the way a table reads.

template_note

The note a child or adolescent run on the adult template gets, or None.

bad_count

The summary box’s count, total, share in percent and badge colour.

summary_cells

The run summary’s printed cells, formatted here once so both reports round a half alike.

heart_rate_note

What to say when the heart rate lies outside the cardiac band, or None.

placement_note

What to say when no reading placed the optodes on their template, read as the brain views read it.

roi_overlap_note

What to say when a channel sits in two ROIs, or None. One wording for both reports.

separation_notes

What to say when the montage could not be split the way the metrics assume it was.

channel_columns

CHANNEL_COLUMNS without the columns a view does not print.

measured_columns

The columns at least one channel set has a value for.

split_table

One recording measured over several channel sets, as a table ready to print.

metric_set_table

A run’s metrics as one table: a metric per row, a channel set per column.

format_rows

Rows with the numbers already formatted and the cells already classed.

pair_status

Each source-detector pair a run’s channel table lists, in its order, with its separation and whether either wavelength was rejected.

long_kept_pairs

The long pairs pair_status() rows list as kept; a pair with no separation counts as long.

region_coverage

Each --roi-mapping region’s long channels in one recording, and which were rejected.

region_table

A run’s region coverage from its channel_rows(): {"rows", "not_counted"}, empty without a map.

optode_rejections

Each source’s and detector’s long pairs as (rejected, listed), from pair_status() rows.

save_channel_csv

Per-channel metrics for one run. The name carries the run’s entities, or a subject with several tasks would keep only whichever ran last.

Data#

API#

nirspipe.qc.common.channel_table.logger = 'get_logger(...)'#
nirspipe.qc.common.channel_table.uncorrected_view(record: dict) → dict#

record as raw QC reads it: channel_rows() takes the correlation before the correction.

nirspipe.qc.common.channel_table.channel_rows(record: dict, sci_scores: dict[str, float], bad_channels: collections.abc.Iterable[str]) → list[dict[str, Any]]#

One row per channel: its scores, its verdict, and which separation block it is in.

Rows go by source then detector number, a pair’s wavelengths side by side (channel_order()), and every value is read from the record rather than recomputed, so a table and the stored numbers cannot disagree.

A short channel’s scores come from raw_short and a long channel’s from the long sections, because the two are measured separately: averaging a short channel’s coupling in with the long ones lifts every score, and reading a short channel’s row off the long section would leave it blank. A channel in neither range falls back to the whole-montage raw section, which measured it even though no split claimed it; its scores are the same per-channel numbers either way, and only the scalar means they feed differ. corr is the exception and comes from the whole-file preproc section, so it is filled for short channels too. Raw QC’s views leave preproc out, through uncorrected_view(), and read rawhaemo, the uncorrected side. corr_post is the same correlation on the regression residual (errts), None where the record has none.

nirspipe.qc.common.channel_table.channel_order(ch: str) → tuple#

A sort key: source, then detector number, then wavelength.

[“S2_D1 850”, “S10_D1 760”, “S2_D1 760”] -> [“S2_D1 760”, “S2_D1 850”, “S10_D1 760”]

nirspipe.qc.common.channel_table.WAVELENGTH_COLUMNS = ('snr', 'cv', 'spike', 'saturated')#
nirspipe.qc.common.channel_table.pair_wavelengths(rows: list[dict]) → list[str]#

The wavelengths behind the rows, in the order pair_rows() keeps them.

[“S1_D1 850”, “S1_D1 760”] -> [“760”, “850”]

nirspipe.qc.common.channel_table.pair_rows(rows: list[dict], pairs: list[str] | None = None, *, by_wavelength: bool = False) → list[dict[str, Any]]#

The same rows collapsed to one per source-detector pair.

Raw intensity carries two channels per pair, one per wavelength, and SCI is a property of the pair rather than of either wavelength. A view that lists pairs (the channel decisions tables) needs one row each:

rows for "S1_D1 760" and "S1_D1 850"  ->  one row, pair "S1_D1"

pairs fixes the membership when the caller already has a pair list from the haemoglobin file; either way the pairs come out by source then detector number. A pair with no row is still returned, empty, so the caller’s list stays intact.

by_wavelength keeps both values of each WAVELENGTH_COLUMNS column as a tuple in pair_wavelengths() order, snr: (23.7, 13.7), instead of the first.

nirspipe.qc.common.channel_table.separation_blocks(rows: list[dict], sep_bands=None) → list[tuple[str, list[dict]]]#

Rows grouped by separation, long first, empty blocks dropped.

A single block back means the montage is of one kind (or was never split), which is the case where a view prints one plain table with no group headers.

nirspipe.qc.common.channel_table.heatmap_args(rows: list[dict]) → dict[str, Any]#

Arguments for channel_quality_heatmap(), ordered the way a table reads.

Long block first so the grid and the table above it list channels in the same order, with a stable sort so channel_rows()’ order survives inside each block. split_at is the divider between long and short, and it names its two sides, so it is only set when there are exactly two: a montage with channels in neither range has three blocks, and the table is where those get named.

nirspipe.qc.common.channel_table.template_note(population: str | None, template: str | None) → str | None#

The note a child or adolescent run on the adult template gets, or None.

nirspipe.qc.common.channel_table.bad_count(bad: list[str], n_total: int) → tuple[int, int, float, str]#

The summary box’s count, total, share in percent and badge colour.

nirspipe.qc.common.channel_table.summary_cells(n_bad: int, n_total: int, good_frac: float | None, heart_rate: float | None, duration_s: float | None) → dict#

The run summary’s printed cells, formatted here once so both reports round a half alike.

(5, 40, 0.85, 1.2, 391.4) -> {"bad": "5/40 (12%)", "frac": "85% of windows",
                              "heart_rate": "1.20 Hz (72 bpm)", "duration": "391 s"}
nirspipe.qc.common.channel_table.heart_rate_note(heart_rate: float | None, cardiac: tuple[float, float]) → str | None#

What to say when the heart rate lies outside the cardiac band, or None.

nirspipe.qc.common.channel_table.placement_note(raw) → str | None#

What to say when no reading placed the optodes on their template, read as the brain views read it.

None for a placed run, and for one with no positions at all, which the separation notes already name. One wording for both views, as the separation notes are.

nirspipe.qc.common.channel_table.roi_overlap_note(roi_map: dict[str, list[str]] | None) → str | None#

What to say when a channel sits in two ROIs, or None. One wording for both reports.

nirspipe.qc.common.channel_table.separation_notes(scalars: dict, rows: list[dict], short_channel_requested: bool = False, sep_bands=None, orphan_mm: dict[str, float] | None = None) → list[str]#

What to say when the montage could not be split the way the metrics assume it was.

Three cases, and they are worth telling apart. No channel in either range means the recording carries no registered optode positions, so every distance reads as zero and the metrics fall back to the whole montage. Channels in neither range is a real montage with real positions that happens to use separations the two ranges leave out; those channels are screened and scored like any other but sit in none of the split scalars. The third is a run that asked for short-channel regression and had every short channel rejected, which the pipeline treats as a warning and carries on past.

orphan_mm is separation_orphans()’ output, name -> mm. Given, the second note also says where those channels actually sit and which bound would take them in.

Returns the notes in the order they should be printed, empty when the split was clean. The caller decides where they go: the subject report files them as run notes, the raw views print them under the table.

nirspipe.qc.common.channel_table.CHANNEL_COLUMNS = (('name', 'Channel'), ('region', 'Region (aparc)'), ('status', 'Status'), ('sci_win',), ('sci_whole'...#
nirspipe.qc.common.channel_table.channel_columns(drop: Sequence[str] = ()) → list[tuple[str, str]]#

CHANNEL_COLUMNS without the columns a view does not print.

channel_columns((“corr”, “separation”)) -> [(“name”, “Channel”), …, (“spike”, …)]

A view drops a column rather than listing the ones it wants, so a new column reaches it by default and the lists cannot silently fall out of step.

nirspipe.qc.common.channel_table.CSV_FIELDS = ()#
nirspipe.qc.common.channel_table.RAW_CSV_FIELDS = 'tuple(...)'#
nirspipe.qc.common.channel_table.OD_SPLIT_COLUMNS = 'tuple(...)'#
nirspipe.qc.common.channel_table.MOTION_SPLIT_COLUMNS = 'tuple(...)'#
nirspipe.qc.common.channel_table.OD_LOOSE_KEYS = ('cp_mean', 'n_flat_channels')#
nirspipe.qc.common.channel_table.COUNT_BESIDE = None#
nirspipe.qc.common.channel_table.HAEMO_SPLIT_COLUMNS = (('hbo_hbr_corr_mean', 'HbO–HbR corr'),)#
nirspipe.qc.common.channel_table.WHOLE_RUN_ONLY_COLUMNS = 'frozenset(...)'#
nirspipe.qc.common.channel_table.CONDITION_OD_SPLIT_COLUMNS = 'tuple(...)'#
nirspipe.qc.common.channel_table.measured_columns(columns: Sequence[tuple[str, str]], *scalar_sets: dict) → tuple[tuple[str, str], ...]#

The columns at least one channel set has a value for.

measured_columns([("gvtd_mean", "GVTD"), ("motion_corrected_frac_mean", "Corrected")],
                 {"gvtd_mean": 0.004}, {"gvtd_mean": 0.009})
-> (("gvtd_mean", "GVTD"),)

A column nothing measured is dropped rather than printed as a row of dashes: the correction footprint is there only when a correction ran.

nirspipe.qc.common.channel_table.split_table(channel_sets: list[tuple[str, Any, dict, bool]], columns: Sequence[tuple[str, str]] = OD_SPLIT_COLUMNS, *, fold_counts: bool = False) → dict[str, Any]#

One recording measured over several channel sets, as a table ready to print.

channel_sets is [(name, n_channels, scalars, colour), ...] -- normally All, Long and Short. colour says whether that row’s cells carry a verdict: only the long channels get one, because a short channel’s coupling is high by construction and the cutoffs do not apply to it:

split_table([("Long", 40, {"sci_mean": 0.81}, True)], [("sci_mean", "Mean SCI")])
-> columns: [{"key": "sci_mean", "label": "Mean SCI", ...}]
   rows:    [{"name": "Long", "n": 40, "cells": [{"value": "0.810", "cls": "qm-ok"}]}]

fold_counts prints each COUNT_BESIDE count inside its share’s cell and drops the count’s own column.

nirspipe.qc.common.channel_table.metric_set_table(sets: list[tuple[str, Any]], groups: list[tuple[str, dict, list[dict]]]) → dict[str, Any]#

A run’s metrics as one table: a metric per row, a channel set per column.

sets is [(name, n_channels), ...] in column order. groups is [(title, split, loose), ...]: split a split_table() result (empty when the montage did not split), loose rows from metric_rows that belong to no channel set, printed in the first column with the others blank. A share and its count print in one cell, 7.8% (34330), whether they arrive as two loose rows or as two columns of a split that was not folded:

metric_set_table([("All", 52), ("Long", 44)],
                 [("Optical density", split, [{"key": "cp_mean", ...}])])
-> {"sets": ["All", "Long"], "counts": [52, 44],
    "groups": [{"title": "Optical density",
                "rows": [{"label": "Mean SCI (10 s)", "cells": [{...}, {...}]}, ...]}]}
nirspipe.qc.common.channel_table.format_rows(rows: list[dict], sci_threshold: float | None, *, name_key: str = 'name', psp_threshold: float | None = None, regions: dict[str, str] | None = None) → list[dict[str, Any]]#

Rows with the numbers already formatted and the cells already classed.

format_rows([{"name": "S1_D1 760", "sci_win": 0.412, "corr": None, "is_bad": True, ...}], 0.8)
-> [{"name": "S1_D1 760", "status": "BAD", "status_cls": "bad",
     "sci_win": "0.412", "sci_win_cls": "bad", "corr": "—", "corr_cls": "", ...}]

Formatting lives here rather than in each renderer because the raw viewer prints in JavaScript and cannot use the Python registry, so it gets its strings from here instead of reimplementing the formats and the SCI cutoff. Classes are the subject report’s .qm-table names (bad/good for status, bad for a below-threshold SCI, neg/pos for the correlation’s sign), so one stylesheet rule covers both views.

sci_threshold is the run’s own --sci-threshold, not the registry’s cutoff for the SCI mean: this column marks the channels that were actually pruned, so colouring it against anything else would show a verdict the run did not reach. psp_threshold is the run’s other line, and is here for the same reason: the reason printed beside a rejected channel is re-derived from its scores, so a run that moved the PSP line has to hand that line over or the reason comes out naming the wrong criterion. sci_threshold None means no line was recorded, and the SCI cell stays uncoloured. name_key is "pair" for rows that came through pair_rows(). regions is recorded_regions(), pair -> region, for the Region column.

Status is BAD for a channel rejected on its passing-window share, the reason every table’s note states once, and BAD (manual) for one rejected by hand. reason keeps the full list for the channel TSV.

nirspipe.qc.common.channel_table.CHANNEL_METRICS_SUFFIX = '_desc-channel_qc.tsv'#
nirspipe.qc.common.channel_table.RAW_CHANNEL_METRICS_SUFFIX = '_desc-rawchannel_qc.tsv'#
nirspipe.qc.common.channel_table.CHANNEL_METRICS_SUFFIXES = ()#
nirspipe.qc.common.channel_table.pair_status(path: pathlib.Path) → dict[str, dict[str, Any]]#

Each source-detector pair a run’s channel table lists, in its order, with its separation and whether either wavelength was rejected.

nirspipe.qc.common.channel_table.long_kept_pairs(pairs: dict[str, dict[str, Any]]) → set[str]#

The long pairs pair_status() rows list as kept; a pair with no separation counts as long.

nirspipe.qc.common.channel_table.region_coverage(pairs: dict[str, dict[str, Any]], roi_map: dict[str, list[str]]) → list[dict[str, Any]]#

Each --roi-mapping region’s long channels in one recording, and which were rejected.

region_coverage({"S1_D1": {"separation": "long", "is_bad": False},
                 "S1_D2": {"separation": "long", "is_bad": True},
                 "S1_D9": {"separation": "short", "is_bad": False}},
                {"L": ["S1_D1", "S1_D2 hbo", "S1_D9", "S7_D7"]})
-> [{"region": "L", "listed": 2, "kept": 1, "rejected": ["S1_D2"],
     "not_counted": {"S1_D9": "short", "S7_D7": "not in the recording"}}]

pairs is pair_status()-shaped. A listed pair that is not a long channel of this recording is named under not_counted rather than counted, since no region output averages it.

nirspipe.qc.common.channel_table.region_table(rows: list[dict], roi_map: dict[str, list[str]] | None) → dict[str, Any]#

A run’s region coverage from its channel_rows(): {"rows", "not_counted"}, empty without a map.

not_counted names every listed pair no region counted, with why, in one line.

nirspipe.qc.common.channel_table.optode_rejections(pairs: dict[str, dict[str, Any]]) → dict[str, tuple[int, int]]#

Each source’s and detector’s long pairs as (rejected, listed), from pair_status() rows.

{"S1_D1": {"separation": "long", "is_bad": True},
 "S1_D2": {"separation": "long", "is_bad": False},
 "S1_D9": {"separation": "short", "is_bad": True}}
-> {"S1": (1, 2), "D1": (1, 1), "D2": (0, 1)}

Short pairs are left out, so an optode that only short pairs use has no entry. A pair with no separation at all (a montage that never split, n/a in the channel table) counts as long, as the tables block it.

nirspipe.qc.common.channel_table.save_channel_csv(rows: list[dict], label: str, out_dir: pathlib.Path, sci_threshold: float | None, psp_threshold: float | None = None, suffix: str = CHANNEL_METRICS_SUFFIX, fields: Sequence[str] = CSV_FIELDS) → None#

Per-channel metrics for one run. The name carries the run’s entities, or a subject with several tasks would keep only whichever ran last.

reason names the criterion a rejected channel failed, so the CSV answers “why did this channel go” without the reader re-deriving it from the score columns.