KIT general pipeline: environment setup and running
Author: Hadi Zaatiti <hadi.zaatiti@nyu.edu>
This is the starting page to setup the NeuroWaves KIT general pipeline. After collecting data and correctly naming them according to the BIDS-convention, the starting point is to setup your configuration file. The config file is a YAML file with .yml extension, it specifies where your data can be found, which subjects are included, what runs, what processing steps to perform and so on. You might want to have several configuration files for a same project.
The config file is an input to run a number of scripts found under
pipeline/mne_pipelines/kit_general_pipelines/.
This page explains how to create the Python environment, how to run each stage, and where the outputs land. The following pages describe the individual stages in detail, one page per stage, in the order they run (the source analysis stages 13 to 19 share one page).
Preparing the BIDS dataset and its YAML config is described in
Starting a project with the general MNE-KIT pipeline. The KidLang study is the worked
example used throughout (pipeline_config_files/kidlang_config.yml).
Important
Everything in this section is derived from the scripts currently in the
repository. If a command here disagrees with --help of a script, trust
the script and open an issue.
What the pipeline does
Each numbered script is one stage; the number is the order in which the
stages run and the prefix of the folder they write under derivatives/.
Stages 1 to 9 operate on the MEG recordings, stage 10 reconstructs the
anatomy with FreeSurfer and builds the scalp surface, stage 11 puts every
reconstruction in front of a reviewer, stage 12 performs the manual MEG-MRI
coregistration, and stages 13 to 19 take the analysis into source space and
to the group level.
The stages were renumbered on 2026-10-20: the lettered scripts (2-a,
2-b, 3-a, 3-b, 5-a, 7-a, 8-a) became plain numbers,
the automatic CON-to-FIF conversion was removed (stage 2 is the manual GUI
only), and the stages after it shifted accordingly. Derivatives folders
written with the old names are still read. Migrate a dataset in one go with
python pipeline/mne_pipelines/kit_general_pipelines/rename_legacy_derivatives.py
-c <config.yml> (dry run, prints the plan) then --apply: it renames the
folders and rewrites the old folder names inside the summary tables,
provenance sidecars, logs and config snapshots, which store absolute paths
(stage 7 compares them before reusing a filtered FIF, stage 9 and the source
stages open them). A folder that Box Drive or a running process refuses to
rename is left in place and reported; rerun later. Stop the report watcher
before migrating.
# |
Script |
Reads |
Writes (under |
|---|---|---|---|
0 |
|
raw |
the CALM recording in the dataset, next to the original:
|
1 |
|
raw |
|
2 |
|
|
|
3 |
|
stage-2 |
|
4 |
|
stage-2 summary (marker pairs), |
|
5 |
|
stage-2 |
|
6 |
|
stage-2 |
|
7 |
|
stage-2 |
|
8 |
|
raw |
|
9 |
|
stage-7 |
|
10 |
|
|
|
11 |
|
stage-10 reconstructions |
MNE scalp surfaces |
12 |
|
stage-2 |
manual GUI; |
13 |
|
stage-2 |
automatic template coregistration for subjects without a complete
stage-12 transform: |
14 |
|
stage-12 (or 13) transform + its anatomy, stage-9 |
|
15 |
|
stage-9 |
|
16 |
|
stage-15 estimates |
|
17 |
|
stage-9 evoked (sensor), stage-15/16 estimates (source) |
|
18 |
|
stage-15/16 estimates or stage-9 evoked (RSA), stage-9 epochs (decoding) |
|
19 |
|
stage-15 estimates (individual), stage-16 averages and contrasts (group) |
|
20 |
|
stage-9 evoked, stage-15 covariance, stage-12/13 transform, stage-14 BEM |
|
21 |
|
stage-7 filtered FIF of |
|
22 |
|
stage-9 epochs |
|
Run stages 1 to 9 in order against the same YAML. For the anatomy run 10,
then 11, then 12: coregistration needs the reconstruction and its scalp
surface, and stage 12 uses an individual MRI only after a pass or
pass_with_note verdict in 11. Stage 12 falls back to the fsaverage
template for subjects without a T1w image (or with a use_fsaverage
verdict). The anatomy stages only depend on stage 2 (the digitisation in the
FIF), so stage 10 can run on a compute node while stages 3 to 9 run on the
workstation. After every successful stage the pipeline re-renders an
incremental Quarto report under
<bids_root>/derivatives/pipeline_report/_output/report.html.
Stages 13 to 19 take the analysis into source space and to the group level: automatic template coregistration (13), forward model (14), inverse solution and source estimates (15), group averages and contrasts (16), spatio-temporal cluster permutation tests (17), representational similarity and decoding (18), movies of the source estimates at the individual and group level (19), dipole fits of the evoked components (20) and spectra of the long recordings (21). They are described in KIT general pipeline: source analysis, statistics and multivariate.
Page per stage:
Stage 0: CALM noise reduction in MEG160 (stage 0)
Stage 1: trigger count sanity check (single and multi channel) (stage 1, single and multi channel)
Stage 2: KIT .con to .fif (stage 2) and the GUI walkthrough Kit2Fiff and coregistration GUIs: manual walkthrough
Stage 4: Head movement between marker measurements (stage 4)
Stage 5: Bad channel detection (stage 5)
Stage 6: ICA artefact decomposition (stage 6)
Stage 7: Apply filters (stage 7)
Stage 8: build MNE events from the triggers (stage 8, three variants)
Stage 9: Epochs and evoked responses (stage 9)
Stage 11: FreeSurfer reconstruction quality control (stage 11)
Stage 12: Manual MEG-MRI coregistration (stage 12)
KIT general pipeline: source analysis, statistics and multivariate (stages 13 to 21)
Two conventions hold across the stages:
Human decisions flow downstream, they are never recomputed. Stage 5 decides the bad channels and stage 6 the ICA components, both with a reviewer; stage 7 applies them (
info['bads']set, excluded components removed before filtering) and records them in a.jsonsidecar next to each filtered FIF; stage 9 epochs only filtered FIFs that stage 7 lists as valid and copies the applied bad channels and ICA into its own records. Changing a review invalidates the downstream outputs: stage 7 reportsexisting_output_unverifiedand stage 9blocked_unverified_filteruntil stage 7 is rerun with--overwrite.Summary tables add up. Every stage keeps one
<stage>_summary.csvwith one row per recording (per event code for stage 9). A run on some subjects (subjects.include,bids_selection) replaces only the rows of the recordings it processed and keeps the others, so the cohort can be processed subject by subject; a recording whose existing output was left alone keeps the row that describes how that output was made. Later stages and the report only accept the outputs listed in these tables.
Prerequisites
Git and access to the private repository (neurowaves-lab-documentation). Email
nyuad.meg@nyu.eduto request access.Conda. If you do not have one, install Miniforge (conda-forge first, all platforms). Check with
conda --version.A desktop session with working OpenGL for the GUIs (stages 2, 5, 6, 11 and 12) and the 3-D plots of stage 3.
Disk space: several GB for the environment plus space for the datasets, their
derivatives/and FreeSurfer outputs.
Create the neurowaves environment
The dependency recipe is
pipeline/mne_pipelines/kit_general_pipelines/environment.yml. It is the
only environment file you need for the pipeline. (The environment.yml at
the repository root is the Windows export used to build this documentation
site and does not contain the MEG stack.)
From the repository root:
conda env create -f pipeline/mne_pipelines/kit_general_pipelines/environment.yml
conda activate neurowaves
The recipe installs, from conda-forge only:
Layer |
Packages |
|---|---|
Interpreter |
Python 3.11 or 3.12 (KIT GUI 2.x needs 3.11+) |
MEG / BIDS |
|
Numerics |
|
GUIs and plots |
|
Config and tables |
|
Reports |
Quarto CLI (bundles Pandoc), |
The environment also sets QT_API=pyside6 on activation so MNE and the KIT
GUI pick the installed Qt binding.
To update an existing environment after the recipe changed:
conda env update -f pipeline/mne_pipelines/kit_general_pipelines/environment.yml --prune
--prune removes packages that are no longer in the recipe, so keep this
environment dedicated to the pipeline. Before updating an environment that was
used for a published analysis, record it with
conda env export -n neurowaves > neurowaves-resolved.yml.
Verify the installation
With neurowaves activated, from the repository root:
# (1) Python dependencies import
python -c "import mne, mne_bids, mne_kit_gui, nibabel, pandas, pyvista, pyvistaqt, qtpy, yaml, joblib, tabulate, IPython, ipykernel, nbclient, nbformat; print('Python deps OK'); mne.sys_info()"
# (2) Quarto is on PATH (1.4 or newer)
quarto --version
# (3) Quarto finds the Python kernel
quarto check jupyter
The report is HTML only: one self-contained report.html (figures and
the source movies embedded), so no LaTeX is needed. pdf in the
reports.formats of an older config is ignored with a notice.
Optional: FreeSurfer for stage 10
FreeSurfer is not installed by Conda. Install it on the Linux host that will run
recon-all (Linux workstation, HPC node, or WSL Ubuntu-22.04 on Windows),
following FreeSurfer on WSL,
and provide its license (FS_LICENSE or freesurfer.license_file in the
YAML).
On Windows, 10-freesurfer_reconstruction.py is launched with the
Windows neurowaves interpreter and forwards the work into WSL, where
python3 and PyYAML must exist:
# inside the WSL distribution
sudo apt update && sudo apt install python3 python3-yaml
python3 -c "import sys, yaml; print(sys.version)"
Set FREESURFER_WSL_DISTRO before starting VS Code if FreeSurfer lives in a
distribution other than Ubuntu-22.04. The distribution’s files are
reachable from the Windows explorer at \\wsl$\<distribution>.
Stage 10 runs recon-all for every selected subject, plans jobs and threads
from the available CPUs and RAM, resumes incomplete subjects, creates the
scalp surface with mkheadsurf and records an audit CSV. freeview (part of
FreeSurfer) can be opened from the stage 11 review window through WSLg.
IDE setup
In VS Code select the neurowaves interpreter with Python: Select
Interpreter. The repository ships .vscode/launch.json entries for every
stage (including the KidLang-specific ones) and .vscode/tasks.json tasks
that refresh the Quarto report. All launch entries set
PYTHONPATH=${workspaceFolder} so the pipeline package is importable.
The pipeline console
pipeline_console.py (launch entry “(Kidlang) Pipeline console (GUI)”, or
python pipeline/mne_pipelines/kit_general_pipelines/pipeline_console.py -c
<config.yml>) is one window for the whole pipeline. It reads the summary
tables the stages write and shows, per recording (stages 1 to 9, 14 and
15), per subject (10 to 13) and for the group stages (16 to 19), what is
done, what a person still has to review, what carries a warning and what
failed; double-clicking a cell
opens the summary rows behind it. The Run a stage panel runs the chosen
stage with its options as a separate process (the command line is shown and
can be copied) and streams the output into the Log tab; a stage that opens
windows runs in its own process, so its crash never closes the console. The
Markers tab previews the marker pairing of a subject and writes the
scans.tsv draft (see the KIT-to-FIF page). The toolbar opens the config,
the derivatives folder and the rendered report. The console never computes
anything itself: every value on screen comes from the files the stages
produce, and every button runs a script a person could run by hand.
Run the stages
Every stage takes the dataset’s YAML config with -c / --config (see
Starting a project with the general MNE-KIT pipeline for creating it).
Run the scripts as modules from the repository root so that the local
pipeline package is importable (no pip install of the repository is
required):
conda activate neurowaves
MODULE=pipeline.mne_pipelines.kit_general_pipelines
CONFIG=pipeline/mne_pipelines/kit_general_pipelines/pipeline_config_files/kidlang_config.yml
python -m $MODULE.0-kit_meg160_calm_noise_reduction -c $CONFIG # Windows (MEG160)
python -m $MODULE.1-kit_count_sanity_check_single_channel -c $CONFIG
python -m $MODULE.2-kit_con_to_fif -c $CONFIG
python -m $MODULE.3-kit_fif_plot_headshape_sensor_alignment -c $CONFIG
python -m $MODULE.4-kit_head_movement -c $CONFIG
python -m $MODULE.5-kit_detect_bad_channels -c $CONFIG
python -m $MODULE.6-kit_ica -c $CONFIG
python -m $MODULE.7-kit_apply_filters -c $CONFIG
python -m $MODULE.8-kit_compute_events_STI014 -c $CONFIG
python -m $MODULE.9-kit_evoked_response_single_channel -c $CONFIG
# Anatomy (Linux/WSL/HPC), reconstruction QC, manual MEG-MRI coregistration
python -m $MODULE.10-freesurfer_reconstruction -c $CONFIG
python -m $MODULE.11-freesurfer_qc -c $CONFIG
python -m $MODULE.12-kit_mri_coreg -c $CONFIG
The variable assignments are Bash syntax; in PowerShell spell out the module
and config paths. Running a script by file path also works when
PYTHONPATH contains the repository root (this is what the VS Code launch
entries do).
Common options:
--overwrite(stages 2, 5, 6, 7, 9): rebuild outputs that already exist. Without it, existing outputs are skipped and reported as such. Stage 3 redraws a picture by itself when its FIF changed; stage 4 rebuilds its tables on every run.--write-scans-draft(stage 2): write a draftscans.tsvwith the marker pairing per subject and session, to review and copy next to the data.--no-plots(stage 4): tables only.--desc <label>(stage 8 variants): overrideevents.desc.--show(stage 3): open the interactive 3-D alignment plots instead of only saving PNGs.--no-gui,--review-all,--reset-review,--overwrite,--no-plots,--save-cleaned(stage 6): fit and propose without reviewing, redo or discard reviews, refit, skip figures, also write the cleaned recording. Details on the ICA page.--no-gui(stage 5): compute the automatic candidates only and label nothing (review_status: pending); the default run opens the inspection and confirmation browsers for every recording not yet reviewed.--review-allredoes the review of reviewed recordings,--reset-reviewdiscards the saved reviews,--no-plotsskips the audit figures. Rerunning stage 5 with unchanged input and detection settings reuses the saved metrics. Details on the bad channel page.--dry-run,--force,--jobs,--threads(stage 10).--no-gui,--review-all,--reset-review,--overwrite,--no-plots(stage 11): as in stage 5;--no-guicomputes metrics, flags and figures and leaves the verdictspending.--redo,--qa-only,--no-plots(stage 12): reopen the GUI for verified transforms, or only recompute the distance QA.
Each Python stage writes a timestamped copy of the YAML it used into
<stage>/configs/config_<timestamp>.yml (the report reads the newest one
to show the parameters of the run; copies that older runs left in the stage
root are moved into configs/ on the next run).
The KidLang configuration
kidlang_config.yml differs from the template in a few deliberate ways:
kit2fiff.slope: "+"(triggers are 0 to 5 V peaks). Stage 2 opens the KIT-to-FIFF GUI once per recording so the head-shape alignment is checked by eye; there is no automatic mode.Events come from the STI 014 channel, so the stage-8 variant is
8-kit_compute_events_STI014.pywithevents.desc: sti014,events.source: sti014andevents.find_eventskwargs (stim_channel: "STI 014",shortest_event: 1,min_duration: 0.002).freesurfer.auto_cw256: trueretries subjects whose field of view exceeds 256 with-cw256(stage 11 checks the crop);missing_anat: fsaveragelets stage 12 use the template for subjects without a T1w.reports.formats: ["html"](the only format).There is no
filtersorepochingblock, so stages 7 and 9 use their built-in defaults (notch at 50 Hz harmonics, band-pass 1 to 40 Hz, epochs from -0.2 s to 0.8 s with a baseline of -0.2 to 0 s). Add those blocks to the config to change them.
Where the outputs land
The scripts write only under <bids_root>/derivatives/, with one exception:
stage 0 saves each noise-reduced recording in the dataset itself, next to its
raw file, as ..._proc-CALMnoisereduction_..._meg.con (the raw file is not
changed). The source tree is never modified.
<bids_root>/derivatives/
0-kit_meg160_calm_noise_reduction/
calm_summary.csv
sub-*/[ses-*/]sub-*_..._proc-CALMnoisereduction_..._meg_calm.json # provenance
sub-*/[ses-*/]sub-*_..._proc-CALMnoisereduction_..._meg_calmweights.txt
1-kit_count_sanity_check_single_channel/
sanity_check_overview.csv
sub-*/sub-*_..._desc-sanitycheck_log.txt
2-kit_con_to_fif/
kit2fiff_summary.csv
sub-*/[ses-*/]
sub-*_..._desc-rawkit_raw.fif
sub-*_..._desc-rawkit_raw_marker_selection.json # GUI marker selection
*_edited.txt # digitizer points without the last 3 columns
kit2fiff_log.txt
3-kit_fif_plot_headshape_sensor_alignment/
alignment_summary.csv
sub-*/...png (+ .json)
4-kit_head_movement/
head_movement_summary.csv, head_movement_markers.csv
sub-*/[ses-*/]sub-*_desc-headmovement.png
5-kit_detect_bad_channels/
bad_channels_summary.csv
sub-*/sub-*_..._desc-badchannels.json # final bad-channel list + settings
sub-*/sub-*_..._desc-badchannels_metrics.tsv # one row per channel
sub-*/figures/*.png # PSD, metrics, sensor map, traces
6-kit_ica/
ica_summary.csv
sub-*/sub-*_..._desc-ica_ica.fif # ICA solution incl. reviewed exclusions
sub-*/sub-*_..._desc-ica.json # proposals, review, settings
sub-*/sub-*_..._desc-ica_scores.tsv # one row per component
sub-*/figures/*.png # components, scores, properties, overlays
7-kit_apply_filters/
filter_summary.csv # bad_channels, ica_excluded columns
sub-*/sub-*_..._desc-filtered_raw.fif (+ .json provenance; info['bads'] from 5, ICA from 6 applied)
8-kit_compute_events_STI014/ # or 8-kit_compute_events_<mode>/
events_summary.csv # auto_events_index.csv for the analog variants
sub-*/sub-*_..._desc-sti014_events.eve
sub-*/sub-*_..._desc-sti014_events_detail.tsv
9-kit_evoked_response_single_channel/
epochs_evoked_summary.csv
sub-*/sub-*_..._desc-epo_raw_ev<code>_epo.fif # one epochs file per event code
sub-*/sub-*_..._desc-evk_raw_ave.fif # all evoked responses of the recording
10-freesurfer_reconstruction/
subjects/sub-*/ # SUBJECTS_DIR (surf/lh.seghead, bem/*-head-*.fif)
freesurfer_summary.csv
runs/<run-id>/{freesurfer_summary.csv, run_metadata.txt, config.yml, logs/}
11-freesurfer_qc/
freesurfer_qc_summary.csv
freesurfer_qc_metrics.tsv
sub-*/sub-*_desc-reconqc.json # metrics, flags, verdict
sub-*/figures/*.png
12-kit_mri_coreg/
coreg_summary.csv
sub-*/sub-*-trans.fif # saved from the GUI
sub-*/sub-*-trans.json # provenance and QA distances
subjects/fsaverage/ # template copy when needed
pipeline_report/
_output/report.html # + source/report.qmd, _quarto.yml
logs/render_log_<timestamp>.txt # newest 30 kept
state/render.lock, report_refresh.json
staging/ # transient, empty between renders
Report
The report (report_generation/report.qmd) is rendered with Quarto after
each stage when reports.enabled: true. Quarto is found on PATH, through
reports.quarto_path, or via conda run -n <reports.quarto_env>. To
re-render without re-running any processing (for example after pulling a new
report template, or on a workstation after stage 10 ran on a compute node):
python -m pipeline.mne_pipelines.kit_general_pipelines.report_generation.refresh --config $CONFIG
# keep watching the inputs and refresh on change
python -m pipeline.mne_pipelines.kit_general_pipelines.report_generation.refresh --watch
Only one render runs per report at a time. A stage that finds another render
in progress (for example the VS Code task Watch Quarto reports, which
starts with the workspace) waits at most reports.lock_wait_s seconds
(default 30), then continues without waiting: the running render re-checks
the inputs when it finishes and renders again if the stage added outputs. A
render that runs longer than reports.render_timeout_s seconds (default
600) is killed, the previous report is kept, and the next stage or the
watcher renders again. A stage whose outputs were already rendered by the
watcher reports report already up to date and skips.
Troubleshooting
Symptom |
Cause |
Fix |
|---|---|---|
|
Script launched without the repository on the import path |
Run with |
|
Dataset parent folder unknown |
Export |
|
Backslash in a double-quoted Windows path |
Use forward slashes or single quotes |
Quarto cannot be found |
Not on PATH and not in the configured Conda env |
|
GUI cannot initialise Qt / OpenGL |
No desktop session or wrong interpreter |
Select the |
Stage 10 cannot import |
PyYAML installed on Windows only |
|
Stage 7 reports |
Input, settings, bad channels or ICA exclusions changed since the FIF was filtered |
Rerun stage 7 with |
Stage 9 reports |
The stage-7 FIF is outdated (see above) or was never made |
Rerun stage 7 ( |
Report shows old data |
Not refreshed after the inputs changed |
Run the |
|
The watcher task or another stage holds the render lock |
Nothing to do; that render includes this stage’s outputs |
|
Quarto or its Jupyter kernel hung, often on a slow or syncing drive |
Check the latest |
If a render fails, the Quarto stderr is in
<bids_root>/derivatives/pipeline_report/logs/render_log_<timestamp>.txt. The
stages continue after a failed render unless reports.fail_on_error: true.
Further reading in the repository
pipeline/mne_pipelines/kit_general_pipelines/README.md: stage-by-stage behaviour, manual coregistration details, FreeSurfer resource planning.pipeline/mne_pipelines/kit_general_pipelines/SETUP.md: the installation walkthrough this page summarises.pipeline/mne_pipelines/kit_general_pipelines/report_generation/README.md: how the Quarto report is built and refreshed.