Stage 1: trigger count sanity check (single and multi channel)
Author: Hadi Zaatiti <hadi.zaatiti@nyu.edu>
What & why
1-kit_count_sanity_check_single_channel.py validates that the trigger
pulses recorded on the analog MISC lines of a NYUAD-KIT MEG dataset match the
event annotations in the BIDS *_events.csv / *_events.tsv table:
same number of pulses per trigger channel, same chronological order. It
detects lost, duplicated or misaligned triggers before any further processing.
The check is intended for datasets acquired in single-channel trigger mode
(each event type on its own trigger line, KIT channels 224 to 231). A
companion script, 1-kit_count_sanity_check_multi_channel.py, performs the
equivalent check for binary-coded (multi-channel) trigger mode, where one
event is encoded by several lines rising together.
Datasets whose triggers are read from the digital STI 014 channel (such as
KidLang) do not go through this check; their events are extracted in stage 3
with 3-kit_compute_events_STI014.py.
What you need to provide
MEG recordings
sub-<id>/[ses-<id>/]meg/sub-<id>[_ses-<id>]_task-<task>[_run-<n>]_meg.con
A paired events table and JSON sidecar at the same scope
..._events.csv (or .tsv) ..._events.json
The table must contain a
channelcolumn holding the KIT trigger channel number (224 to 231) of each event, in presentation order. The JSON must declare the trigger mode:{ "TriggerMode": "single_channel" }
Runs whose JSON does not declare
single_channel(case, spaces and hyphens are normalised) are reported in the summary as skipped.The same JSON can declare the timing the recording must respect (Timing constraints (both scripts)) and how long a trigger stays on (Trigger duration (both scripts)). Both are optional.
A complete example of both trigger modes is in the bids-template dataset
on NYU Box (MEG/Data/bids-template): task singlechannel (a recording
with its events table and sidecar, which passes this stage) and task
binarycoded (events table and sidecar). Its README.md describes every
column and field.
Fallback hierarchy for events files
The search goes from the most specific to the least specific level and stops at the first level that provides both files:
Exact match:
sub-<id>[_ses-<id>]_task-<task>_run-<n>_events.*Subject + task:
sub-<id>[_ses-<id>]_task-<task>_events.*Subject only:
sub-<id>[_ses-<id>]_events.*Dataset root, one task:
task-<task>_events.*next todataset_description.json(applies to every recording of that task)Dataset root:
events.csv+events.jsonnext todataset_description.json(applies to every recording)
When no level provides both, the most specific table is used with the JSON
of the closest less specific level (BIDS inheritance): a table written for
each run can share one task-<task>_events.json at the dataset root. A
JSON is never taken from a more specific level than the table, nor from
another subject, session or task. The entities are compared as written, as
BIDS labels are case-sensitive: task-MSWM and task-mswm are two
different tasks.
TriggerMode is read from the JSON of the pair. TimingConstraints and
TriggerDuration are read from that JSON when it has the field, and
otherwise from task-<task>_events.json and then events.json at the
dataset root, so values common to every run can be written once.
Stage 3 looks for the events JSON with the same order of levels (it needs no table).
Configuration file
The stage reads the shared pipeline YAML (-c / --config; default
pipeline_config_files/config_template.yml). Keys used:
project:
name: "script-testing-dataset"
root_env: "MEG_DATA" # or root_override
subjects:
include: []
exclude: []
bids_selection:
sessions: []
tasks: []
runs: []
processings: [] # [null] = unprocessed .con only
exclude: {}
events:
multi_channel:
max_onset_skew_ms: 2.0 # multi-channel variant only
trigger_timing:
enabled: true
default_tolerance_ms: 2.0 # for a constraint without ToleranceMs
on_violation: warn # warn: reported, the recording keeps its PASS; fail: the recording fails
max_listed: 10 # violations spelled out per constraint
constraints: [] # constraints added to those of the dataset
reports:
enabled: true
The pulse-detection thresholds are fixed in the script (see Tuning below); there are no YAML keys for them.
How to run
From the repository root, neurowaves environment activated:
python -m pipeline.mne_pipelines.kit_general_pipelines.1-kit_count_sanity_check_single_channel \
-c pipeline/mne_pipelines/kit_general_pipelines/pipeline_config_files/config_template.yml
# binary-coded datasets
python -m pipeline.mne_pipelines.kit_general_pipelines.1-kit_count_sanity_check_multi_channel \
-c <your_config.yml>
The VS Code launch entry KIT Sanity Check Single Channel runs the same command on the template config.
What the script does
Loads the config and resolves the BIDS root (
<parent>/<project.name>).Discovers subjects and
.conrecordings, applyingbids_selection.Resolves the events table and its JSON. A recording without any events file is reported as
no_events, one with a table and no JSON that applies to it (or a JSON and no table) asfail, and one whoseTriggerModeis notsingle_channelasskipped.Reads the KIT recording (no preload) and the events table; checks that every
channelvalue is one of the KIT trigger channels (224,KIT224and224.0are the same line). Rows whosechannelisn/acarry no trigger and are not counted.Detects pulses on each of
MISC 001toMISC 008with a robust threshold: baseline from the lower tail of the first 10 s, median + MAD threshold, hysteresis and debouncing. Spans annotated as bad are ignored without shifting sample indices.Compares detected pulses with the table: count per KIT channel and the chronological channel sequence.
Checks the timing constraints and the trigger duration (sections below).
Computes pulse statistics (amplitude and width mean/variance), writes a per-run log and the summary CSV, saves a timestamped copy of the config and requests a report refresh.
Outputs
<bids_root>/derivatives/1-kit_count_sanity_check_single_channel/
sanity_check_overview.csv one row per recording
timing_check_overview.csv one row per recording and constraint
configs/config_<timestamp>.yml
sub-<id>/[ses-<id>/]
sub-<id>[_ses-<id>]_task-<task>[_run-<n>]_desc-sanitycheck_log.txt
sub-<id>[_ses-<id>]_task-<task>[_run-<n>]_desc-timingcheck_intervals.tsv
The multi-channel variant writes to
derivatives/1-kit_count_sanity_check_multi_channel/ with the same layout
(its summary columns differ, see the multi-channel section below). Its two
per-recording files keep the _meg of the recording name:
..._meg_desc-sanitycheck_log.txt and
..._meg_desc-timingcheck_intervals.tsv.
A run on some subjects replaces their rows in the two overview tables; the rows of the other recordings are kept.
Per-run log
Raw file, events table and JSON paths,
TriggerModeThreshold per channel (
thr_hi,thr_lo, pulse count)Count comparison per KIT channel (
csv_count/detected_count/diff)Sequence check with the first mismatching position
Amplitude and width statistics
Final PASS/FAIL line (ASCII
OK/FAILon Windows consoles)
Summary CSV
sanity_check_overview.csv columns: subject, file, status,
trigger_mode, csv_events, detected_events, counts_match,
row_order_match, reference_channels_valid, pass, the timing
columns (timing_status, timing_constraints, timing_violations,
see Timing constraints (both scripts)), the trigger duration columns
(trigger_duration_status, trigger_duration_warnings, see
Trigger duration (both scripts)), log_file, comments,
mne_version.
status is one of:
|
Meaning |
|---|---|
|
Counts and order match the events table. |
|
They do not, or the table has no paired JSON. |
|
The recording has no events table and no JSON (rest, empty-room):
nothing to check, |
|
The JSON declares another |
|
A file could not be read, the table has no |
Pass/Fail criteria
A run passes only if every KIT channel count matches the table exactly and the detected chronological channel order equals the table order. The table must hold at least one event and only KIT trigger channels (224 to 231).
Timing violations are reported and leave the PASS as it is, unless the
configuration sets trigger_timing.on_violation: fail. A trigger duration
outside its tolerance is always a warning.
Tuning & interpretation
The detector is detect_pulses_on_channel in
kit_general_pipelines/utilities.py. The stage calls it with
baseline_s=(0.0, 10.0) and the function defaults:
absolute_floor = 0.3V minimum deviation from baselinemad_mult = 12.0(threshold = baseline + 12 * MAD)hysteresis_frac = 0.8(pulse ends below 80 % of the threshold)min_width_ms = 3.0,min_distance_ms = 6.0baseline_q = 0.7(baseline from the lower 70 % of samples)
Interpretation:
Stable amplitude and width across pulses: reliable triggering.
Large width variance: noisy line or timing drift; inspect the stim plots saved by stage 3.
Count mismatch on one channel: an event was dropped or doubled on that line, or the events table is wrong.
Order mismatch with equal counts: the table and the acquisition disagree about presentation order.
Troubleshooting
Run failed, “no paired scope”: the recording has an events table and no JSON at its level or above (or a JSON and no table); check the fallback hierarchy above.
Run skipped, wrong TriggerMode: the JSON declares another mode. Use the multi-channel script, or stage 3 for
STI 014datasets.“Events table is missing the required channel column”: the table needs a
channelcolumn with KIT channel numbers.Too many or too few pulses: the pulses may not start within the first 10 s used as baseline, or their amplitude may be below 0.3 V; adjust the call in the script for that dataset and document it in the config copy.
Timing constraints (both scripts)
The count check says that every trigger arrived. The timing constraints say that they arrived when they should: “the target comes 33 ms after the prime”, “a response comes at most 2.5 s after the target”, “every interval in the recording equals the interval the stimulus computer logged”.
Declare them in events.json, next to TriggerMode:
{
"TriggerMode": "single_channel",
"TimingConstraints": [
{"Name": "prime duration",
"From": "prime", "To": "target", "GroupBy": "trial_index",
"ExpectedMs": 33.3, "ToleranceMs": 2.0},
{"Name": "response window",
"From": "target", "To": "response", "GroupBy": "trial_index",
"MaxMs": 2520, "Required": false},
{"Name": "recording against the stimulus log",
"From": "*", "To": "*",
"ExpectedFromColumn": "stim_time", "ToleranceMs": 3.0}
]
}
Each constraint measures, in the recording, the time from every From event
to its To event.
Field |
Meaning |
|---|---|
|
Label used in the tables and in the report. |
|
The events that start and end the interval (selectors, below). Required. |
|
Optional column of the events table: the |
|
The interval must be this long, within |
|
The interval must equal the difference of this column between the two
rows: a time stamp logged by the stimulus computer. |
|
Allowed deviation from the expected interval. Default:
|
|
The interval must lie in this range. Either may be absent. |
|
With |
|
|
A constraint needs at least one of ExpectedMs, ExpectedFromColumn,
MinMs and MaxMs. Field names are not case-sensitive; an unknown field
makes the constraint invalid.
Selectors (From, To):
Selector |
Events it designates |
|---|---|
|
Every event. With the same selector on both sides ( |
|
Single-channel mode: the trigger line whose |
|
The events of that trigger line (single-channel mode), or the events with that code (binary-coded mode). |
|
The rows of the events table that match every column given. |
|
A list means any of its values. |
The events of the recording and the rows of the events table are paired in
order. This is meaningful only when the count check has passed, so the timing
is checked only then (timing_status is not_checked otherwise).
Results:
timing_statusof the summary:pass,violations,invalid(a constraint could not be read: the reason is incomments),not_defined(no constraint declared) ornot_checked.timing_constraintsis the number of constraints andtiming_violationsthe number of intervals outside their rule.timing_check_overview.csv: one row per recording and constraint, with the number of intervals, their mean, SD, minimum and maximum, the largest deviation and the first violations.*_desc-timingcheck_intervals.tsv: every interval measured, with its rows, expected value and deviation.
Violations are reported and the recording keeps its PASS. With
trigger_timing.on_violation: fail in the configuration, a recording with
a violation or an invalid constraint fails.
A run that was stopped before its end has a last trial without its To
event. With Required left to true this is reported as one violation
(“no To event”).
The measured times have the resolution of the recording (1 ms at 1 kHz). An interval exactly on a limit is inside it, but a tolerance below 1 ms leaves no room for the sampling. For a screen that lasts a whole number of frames, half a frame (4.2 ms at 120 Hz) separates “right” from “one frame off”.
Trigger duration (both scripts)
How long a trigger stays on (a pulse on one line, or a binary code on several) is a choice of the experiment. Both scripts measure it for every trigger of the recording, and compare it with what the dataset says. A difference is a warning: it is reported, and it never changes the PASS of the recording.
Declare the duration in events.json, as a number of frames of the display:
{
"TriggerMode": "binary_coded",
"TriggerDuration": {"Frames": 4, "FrameMs": 8.3357}
}
Frames: the number of frames the trigger stays on.FrameMs: the duration of one frame in ms (8.3333 at 120 Hz, or the value the experiment measured).The expected duration is
FramesxFrameMs, here 33.3 ms. A trigger that the script holds for “30 ms” on a 120 Hz display lasts 4 frames, so 33.3 ms: declare the frames, not the 30.ToleranceMs(optional): the allowed difference. Without it, half a frame.A trigger that is not tied to the display declares its duration directly:
"TriggerDuration": {"Ms": 30}(tolerance:ToleranceMs, elsetrigger_timing.default_tolerance_ms).
As for the timing constraints, the events.json of the recording is used
when it has the field; otherwise task-<task>_events.json and then
events.json at the dataset root, so a value common to every run is written
once.
The experiment can also log the duration of each trigger, in a
trigger_duration column of the events table (seconds). This is not the
BIDS duration column: duration is how long the event lasts (the
stimulus on screen), trigger_duration how long its trigger stayed on.
onset duration trial_type value trigger_duration ...
n/a 0.500 fixation 25 0.033
n/a 0.300 stimuli 73 0.033
Two comparisons are made, and each is one row of
timing_check_overview.csv (and of the report):
Row |
Compares the measured duration with |
Tells you |
|---|---|---|
|
|
whether every trigger lasted as long as designed |
|
the |
whether the recording matches what the stimulus computer says it sent |
A trigger that the script itself cut short, and logged as such, gives a
warning on the first row and none on the second. The declared comparison is
made on every detected trigger, whatever the count check says; the logged one
needs the rows and the triggers to be paired, so it is made only when counts
and order match. In the summary, trigger_duration_status is pass,
warning, not_declared (neither the field nor the column) or
invalid (the field could not be read), and trigger_duration_warnings
is the number of triggers outside the tolerance. The first ones are spelled
out in comments and in the log (event number, time, measured and expected
duration).
The measured duration is the time the line stays above the detection threshold, at 1 kHz. In a trigger test with one-frame pulses (8.3 ms declared), the 230 pulses measured 5 to 9 ms, 7.5 ms on average. For a binary code it runs from the first line that rises to the last line that falls.
The logged duration is as good as the time stamps of the stimulus computer.
A flip time stamp that is a few ms off gives a trigger duration (logged)
warning while the declared comparison passes: the trigger was right and the
log was not.
The detector has its own fixed floor, which no dataset can change: a pulse shorter than 3 ms is not counted, in both scripts.
Multi-channel (binary-coded) variant
1-kit_count_sanity_check_multi_channel.py is the same check for datasets
acquired in binary-coded trigger mode: one event is encoded as a
combination of the eight trigger lines rising together, and the code is the
sum of the bit weights of the lines that are high (KIT channel 224 = bit 0,
weight 1; 225 = bit 1, weight 2; … 231 = bit 7, weight 128). Where the
single-channel script counts pulses per line, this one groups the rising
edges of all lines into events, so one event is one full code and not one
pulse. It then compares the events with the rows of the events table (one
row per event): their number, the count of every code, and the code of each
row against the event detected at that position.
Inputs and selection are the same as above. The run is skipped unless the
events JSON declares a multi-channel TriggerMode; the accepted spellings
are multi_channel, multi_channel_trigger_mode, multiple_channels,
binary_coded, binary_coded_trigger_mode and their variants without
underscores (case and punctuation are ignored). The events table needs no
channel column.
The code of each row is read from the value column of the events table
(the lab convention), or else from the first of code, trigger and
event_id that the table has. Every row must hold a whole number between
1 and 255, with the bit weights given above. Names for the codes are taken
from the trial_type column when there is one.
onset duration trial_type value trigger_duration ...
n/a 0.500 fixation 25 0.033
n/a 0.300 stimuli 73 0.033
n/a 0.050 mask 49 0.033
Without such a column the codes cannot be compared: only the number of
events is checked, and a warning in comments and in the log says so. A
code column in which a row holds something else (empty, n/a, text, 0, a
number above 255) is a FAIL: the table declares codes that cannot be
checked, and comments names the first such row.
Configuration:
events:
multi_channel:
max_onset_skew_ms: 2.0 # lines rising within this delay belong to the same event
What the script does, per recording:
Detects the high intervals of every trigger line (
MISC 001toMISC 008) with the same robust threshold as the single-channel script (baseline from the first 10 s, median + MAD, hysteresis, minimum width 3 ms). A missing line is kept as an empty slot so that the bit weights stay tied to the KIT channel numbers.Builds the code at every sample from the lines that are high and splits the occupied stretches into events: every rising edge that comes more than
max_onset_skew_msafter the first rising edge of the current event starts a new event, even if other lines are still high; rising edges within the delay are the same event (the lines of one code never rise on exactly the same sample). A falling edge never starts an event. A gap of up to 2 ms where every line is low is tolerated inside an event. The lines of one code do not fall on exactly the same sample either: a line that falls withinmax_onset_skew_msof the end of the event is part of the normal end of the code.Records, per event, the onset sample and time, the width, the code, the number of active lines, whether an earlier line was still high at the onset (
held_channels_at_onset), whether the grouped lines were ever high together (grouped_bits_never_coactive) and whether the code changed without a new rising edge, earlier thanmax_onset_skew_msbefore the end of the event (late_falling_code_transitions).Compares the number of events with the number of table rows.
Compares the codes, when the table has a usable code column:
count per code: for every code present in the table or in the recording, the number of rows against the number of detected events;
order: when the two totals are equal, the code of row i against the code of the i-th detected event.
Checks the timing constraints of the events JSON (rows and events are paired only when the totals are equal and no row has a code that differs from its event), and writes the log and the summary row.
PASS requires all of: at least one table row and one detected event, equal counts, where the codes were compared the same count for every code and the same code on every row, all eight trigger lines present, no non-finite samples, no event starting while another line was held high, no grouped code whose lines were never simultaneously high, and no late code transition. Any of these produces a warning in the log and FAIL. A recording in which every event has a single active line (only the codes 1, 2, 4, 8, 16, 32, 64 and 128) is taken for a single-channel dataset labelled as multi-channel and fails, unless the codes were compared with the events table and match: a design that uses these codes on purpose passes.
Timing violations and trigger durations are handled as in the single-channel
script: reported, without changing the PASS (unless
trigger_timing.on_violation: fail).
A table without a code column does not prevent a PASS: the recording is then validated on the number of events only, with the warning described above. A code column that cannot be read does.
The summary sanity_check_overview.csv of this variant has the columns
subject, file, trigger_mode, expected_events,
detected_events, max_onset_skew_ms, held_onset_events,
noncoactive_event_codes, late_falling_code_transitions,
count_match, code_column, code_counts_match,
code_order_match, pass, the timing columns, the trigger duration
columns (see Trigger duration (both scripts)), warnings,
comments, log_file and mne_version. code_column is the column
the codes were read from; code_counts_match and code_order_match are
empty when the codes were not compared (no code column, or one that cannot
be read), and code_order_match is also empty when the totals differ. For a failed recording comments names each
code whose count differs (code 25 (fixation): 60 expected, 59 detected)
and the first row whose code differs from its event.
The per-run log lists the threshold per line, the count of every code in the table and in the recording, the rows whose code differs from the detected event (row number, expected code, detected code and its time in the recording), and every detected event with its code.
Interpretation:
One code short and another code, absent from the table, detected instead (
code 25: 2 expected, 1 detectedwithcode 24: 0 expected, 1 detected): the event arrived with a line missing or added. The two codes differ by the weight of that line (here 1, KIT channel 224); check that trigger line and the pixel value the script sends for the event.Count per code matches but the order does not: the events arrived in another order than the table lists them, or two events were sent with each other’s code. The log gives the rows concerned.
One code short and nothing in its place: that event never arrived.
Fewer events than rows with
held_onset_eventsabove zero: two stimuli were presented while the lines of the first were still high; the second was absorbed. Check the stimulus script’s pulse duration.late_falling_code_transitionsabove zero, with counts and codes that match: a line of a code fell more thanmax_onset_skew_msbefore the others (a difference of one or two samples is tolerated). A falling edge never starts an event, so the number of events and their codes are not affected, but the recording fails: the trigger was cut on that line, or two codes followed each other without a return to zero. Look at the events concerned in the log ([Detected combined events]).grouped_bits_never_coactive: lines grouped into one event never overlapped in time, so the code is a guess; the onset delay between the lines is longer than their pulses.
Stage 3’s 3-kit_compute_events_multi_channel.py uses the same grouping
rule and the same max_onset_skew_ms, so a PASS here means stage 3 will
produce one event per table row, with the code of that row when the codes
were compared.
Summary
Run this stage immediately after BIDS conversion of a single-channel dataset. It confirms that the analog trigger stream and the event annotations agree, and its summary table becomes the first section of the pipeline report.