=================================================== KIT general pipeline: environment setup and running =================================================== Author: Hadi Zaatiti 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 16 to 18 and 20 to 24 share one page). Preparing the BIDS dataset and its YAML config is described in :ref:`kit_pipeline_project_config`. 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 12 operate on the MEG recordings, stage 13 reconstructs the anatomy with FreeSurfer and builds the scalp surface, stage 14 puts every reconstruction in front of a reviewer, stage 15 performs the manual MEG-MRI coregistration, and stages 16 to 24 take the analysis into source space and to the group level. The stages were renumbered twice. On 2026-10-20 the lettered scripts (``2-a``, ``2-b``, ``3-a``, ``3-b``, ``5-a``, ``7-a``, ``8-a``) became plain numbers and the automatic CON-to-FIF conversion was removed (stage 2 is the manual GUI only). On 2026-11-25 the stages were numbered in the order they run: the events (8) became stage 3 and the photodiode timing (23) stage 4, both right after the conversion because they read the raw ``.con``; sensor alignment, head movement, bad channels, ICA and filters moved from 3 to 7 to 5 to 9, epochs from 9 to 10, time-frequency and spectra from 22 and 21 to 11 and 12, the FreeSurfer and coregistration stages from 10 to 13 to 13 to 16, forward and inverse from 14 and 15 to 17 and 18, source band power from 24 to 19, and the group stages from 16 to 19 to 21 to 24 (dipole fits stay 20). The report and ``results.py`` still read derivatives folders written with the old names; the stages themselves read the folders of the earlier stages by their current names, so migrate a dataset before running a stage on it, with ``python pipeline/mne_pipelines/kit_general_pipelines/rename_legacy_derivatives.py -c `` (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 9 compares them before reusing a filtered FIF, stage 10 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. .. list-table:: :header-rows: 1 :widths: 4 36 30 30 * - # - Script - Reads - Writes (under ``/derivatives/``) * - 0 - ``0-kit_meg160_calm_noise_reduction.py`` (MEG160, Windows) - raw ``.con`` (no ``proc``) - the CALM recording **in the dataset**, next to the original: ``sub-*/[ses-*/]meg/*_proc-CALMnoisereduction_*meg.con``; under ``0-kit_meg160_calm_noise_reduction/``: ``calm_summary.csv``, per-recording ``*_calm.json`` and ``*_calmweights.txt`` * - 1 - ``1-kit_count_sanity_check_single_channel.py`` or ``1-kit_count_sanity_check_multi_channel.py`` - raw ``.con`` + paired ``*_events.csv|.tsv`` and ``*_events.json`` - ``1-kit_count_sanity_check_/sanity_check_overview.csv`` and per-run logs * - 2 - ``2-kit_con_to_fif.py`` (KIT-to-FIFF GUI, one window per recording) - ``.con``, ``.mrk``, laser head shape and digitizer points ``.txt`` - ``2-kit_con_to_fif/`` with ``sub-*/*_desc-rawkit_raw.fif`` and ``kit2fiff_summary.csv`` * - 3 - ``3-kit_compute_events_single_channel.py``, ``3-kit_compute_events_multi_channel.py`` or ``3-kit_compute_events_STI014.py`` - raw ``.con`` (single/multi channel) or stage-2 ``.fif`` (STI 014) - ``3-kit_compute_events_/sub-*/*_desc-_events.eve`` + ``*_detail.tsv``, ``auto_events_index.csv`` or ``events_summary.csv`` * - 4 - ``4-kit_photodiode_timing.py`` (datasets whose ``events.json`` declares a photodiode) - raw ``.con`` (photodiode channel) + stage-3 ``*_events_detail.tsv`` - ``4-kit_photodiode_timing/sub-*/*_desc-_events.eve`` (visual events moved to the photodiode onset), delay of every pulse, figures, ``photodiode_summary.csv``, ``photodiode_dataset_summary.csv`` * - 5 - ``5-kit_fif_plot_headshape_sensor_alignment.py`` (QC of stage 2) - stage-2 ``.fif`` - ``5-kit_fif_plot_headshape_sensor_alignment/sub-*/*.png``, ``alignment_summary.csv`` * - 6 - ``6-kit_head_movement.py`` (head movement between marker measurements) - stage-2 summary (marker pairs), ``.mrk`` files, ``scans.tsv`` or ``.con`` headers - ``6-kit_head_movement/sub-*/*_desc-headmovement.png``, ``head_movement_summary.csv``, ``head_movement_markers.csv`` * - 7 - ``7-kit_detect_bad_channels.py`` - stage-2 ``.fif`` - ``7-kit_detect_bad_channels/sub-*/*_desc-badchannels.json``, ``*_desc-badchannels_metrics.tsv``, ``figures/*.png``, ``bad_channels_summary.csv`` * - 8 - ``8-kit_ica.py`` (interactive: COGNESTIC ICA, proposals reviewed in MNE's source browser) - stage-2 ``.fif`` + stage 7 record - ``8-kit_ica/sub-*/*_desc-ica_ica.fif`` (solution incl. exclusions), ``*_desc-ica.json``, ``*_desc-ica_scores.tsv``, ``figures/*.png``, ``ica_summary.csv`` * - 9 - ``9-kit_apply_filters.py`` - stage-2 ``.fif`` + stage 7 and 8 records - ``9-kit_apply_filters/sub-*/*_desc-filtered_raw.fif`` with ``info['bads']`` set and the reviewed ICA applied (+ ``.json`` provenance), ``filter_summary.csv`` * - 10 - ``10-kit_evoked_response_single_channel.py`` - stage-9 ``.fif`` (bad channels, ICA and filters already applied; a recording without a valid one is reported, not epoched) + stage-3 ``.eve`` - ``10-kit_evoked_response_single_channel/sub-*/*_epo.fif`` (one per event code), ``*_ave.fif`` + ``*_ave.json`` (what went in, kept and dropped epochs per condition), ``epochs_evoked_summary.csv`` * - 11 - ``11-kit_time_frequency.py`` - stage-10 epochs - ``11-kit_time_frequency/sub-*/*_cond-*_desc-{power,itc}_tfr.npz``, band-power tables, figures, ``time_frequency_summary.csv`` * - 12 - ``12-kit_sleep_spectra.py`` - stage-9 filtered FIF of ``spectra.tasks`` - ``12-kit_sleep_spectra/sub-*/*_desc-psd.tsv``, band-power tables, figures, ``spectra_summary.csv`` * - 13 - ``13-freesurfer_reconstruction.py`` - ``sub-*/anat/*_T1w.nii[.gz]`` (Linux/WSL/HPC) - ``13-freesurfer_reconstruction/subjects/sub-*`` (recon-all and the ``surf/lh.seghead`` scalp from ``mkheadsurf``), ``freesurfer_summary.csv``, ``runs//`` * - 14 - ``14-freesurfer_qc.py`` - stage-13 reconstructions - MNE scalp surfaces ``bem/sub-*-head-*.fif``; ``14-freesurfer_qc/sub-*/sub-*_desc-reconqc.json`` (reviewer's verdict), figures, ``freesurfer_qc_summary.csv`` * - 15 - ``15-kit_mri_coreg.py`` - stage-2 ``.fif`` + stage-14-approved reconstruction or ``fsaverage`` - manual GUI; ``15-kit_mri_coreg/sub-*/sub-*-trans.fif`` with provenance and QA, ``coreg_summary.csv`` * - 16 - ``16-kit_auto_coreg.py`` (no GUI) - stage-2 ``.fif`` digitisation + ``fsaverage`` - automatic template coregistration for subjects without a complete stage-15 transform: ``16-kit_auto_coreg/sub-*/sub-*_trans.fif`` + ``.json``, scaled template ``subjects/sub-*``, ``auto_coreg_summary.csv`` * - 17 - ``17-kit_forward_model.py`` - stage-15 (or 16) transform + its anatomy, stage-10 ``*_ave.fif`` - ``17-kit_forward_model/sub-*/*_src.fif``, ``*_bem-sol.fif``, ``*_desc-forward_fwd.fif`` + ``.json`` per recording, ``forward_summary.csv`` * - 18 - ``18-kit_inverse_solution.py`` - stage-10 ``*_epo.fif`` + ``*_ave.fif``, stage-17 forward - ``18-kit_inverse_solution/sub-*/*_cov.fif``, ``*_inv.fif``, per condition ``*_space-fsaverage-{lh,rh}.stc`` + ROI ``*_labels.tsv``, ``*_inverse.json``, figures, ``inverse_summary.csv`` * - 19 - ``19-kit_source_band_power.py`` - stage-10 ``*_epo.fif`` + the stage-18 inverse operators - ``19-kit_source_band_power/sub-*/`` band power maps per condition, contrasts, lateralisation tables, movies, ``source_band_power_summary.csv`` * - 20 - ``20-kit_dipole_fit.py`` - stage-10 evoked, stage-18 covariance, stage-15/16 transform, stage-17 BEM - ``20-kit_dipole_fit/sub-*/*_desc-dipole.{dip,json}``, figures, ``dipole_fit_summary.csv`` * - 21 - ``21-kit_group_source.py`` - stage-18 estimates - ``21-kit_group_source/group/`` grand averages, contrasts, ROI TSVs and figures, ``subjects_manifest.json``, ``group_source_summary.csv`` * - 22 - ``22-kit_cluster_stats.py`` - stage-10 evoked (sensor), stage-18/21 estimates (source) - ``22-kit_cluster_stats/group//contrast-*/clusters.json``, ``tobs.npz``, cluster STC, figures, ``cluster_stats_summary.csv`` * - 23 - ``23-kit_rsa_decoding.py`` - stage-18/21 estimates or stage-10 evoked (RSA), stage-10 epochs (decoding) - ``23-kit_rsa_decoding/sub-*/`` RDM, RSA and decoding results and figures, ``group/``, ``rsa_decoding_summary.csv`` * - 24 - ``24-kit_source_movie.py`` - stage-18 estimates (individual), stage-21 averages and contrasts (group) - ``24-kit_source_movie/sub-*/*_movie.{gif,html,mp4}``, ``group/*``, ``source_movie_summary.csv`` Run stages 1 to 10 in order against the same YAML (stage 4 only for a dataset with a photodiode). For the anatomy run 13, then 14, then 15: coregistration needs the reconstruction and its scalp surface, and stage 15 uses an individual MRI only after a ``pass`` or ``pass_with_note`` verdict in 14. Stage 15 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 13 can run on a compute node while stages 3 to 10 run on the workstation. After every successful stage the pipeline re-renders an incremental Quarto report under ``/derivatives/pipeline_report/_output/report.html``. Stages 16 to 24 take the analysis into source space and to the group level: automatic template coregistration (16), forward model (17), inverse solution and source estimates (18), band power in source space (19), dipole fits of the evoked components (20), group averages and contrasts (21), spatio-temporal cluster permutation tests (22), representational similarity and decoding (23) and movies of the source estimates at the individual and group level (24). The spectra of the long recordings (12) are on the same page. They are described in :doc:`17-mne_pipeline_kit_source_analysis`. Page per stage: - :doc:`0-mne_pipeline_kit_meg160_calm` (stage 0) - :doc:`1-mne_pipeline_trigger_count_sanity_check` (stage 1, single and multi channel) - :doc:`2-mne_pipeline_kit2fiff` (stage 2) and the GUI walkthrough :doc:`mne_manual-usage_kit2fiff` - :doc:`3-mne_pipeline_compute-events` (stage 3, three variants) - :doc:`5-mne_pipeline_kit_sensor_alignment` (stage 5) - :doc:`6-mne_pipeline_kit_head_movement` (stage 6) - :doc:`7-mne_pipeline_kit_detect_bad_channels` (stage 7) - :doc:`8-mne_pipeline_kit_ica` (stage 8) - :doc:`9-mne_pipeline_kit_apply_filters` (stage 9) - :doc:`10-mne_pipeline_kit_evoked_responses` (stage 10) - :doc:`11-mne_pipeline_kit_time_frequency` (stage 11) - :doc:`13-mne_pipeline_freesurfer_reconstruction` (stage 13) - :doc:`14-mne_pipeline_freesurfer_qc` (stage 14) - :doc:`15-mne_pipeline_kit_mri_coreg` (stage 15) - :doc:`17-mne_pipeline_kit_source_analysis` (stages 12, 16 to 18 and 20 to 24) - :doc:`19-mne_pipeline_kit_source_band_power` (stage 19) Two conventions hold across the stages: - **Human decisions flow downstream, they are never recomputed.** Stage 7 decides the bad channels and stage 8 the ICA components, both with a reviewer; stage 9 applies them (``info['bads']`` set, excluded components removed before filtering) and records them in a ``.json`` sidecar next to each filtered FIF; stage 10 epochs only filtered FIFs that stage 9 lists as valid and copies the applied bad channels and ICA into its own records. Changing a review invalidates the downstream outputs: stage 9 reports ``existing_output_unverified`` and stage 10 ``blocked_unverified_filter`` until stage 9 is rerun with ``--overwrite``. - **Summary tables add up.** Every stage keeps one ``_summary.csv`` with one row per recording (per event code for stage 10). 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.edu`` to 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, 7, 8, 14 and 15) and the 3-D plots of stage 5. - **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: .. code-block:: bash conda env create -f pipeline/mne_pipelines/kit_general_pipelines/environment.yml conda activate neurowaves The recipe installs, from ``conda-forge`` only: .. list-table:: :header-rows: 1 :widths: 25 75 * - Layer - Packages * - Interpreter - Python 3.11 or 3.12 (KIT GUI 2.x needs 3.11+) * - MEG / BIDS - ``mne-base`` (imports as ``mne``), ``mne-bids``, ``mne-kit-gui`` 2.x, ``nibabel``, ``scikit-learn`` (optional speed-up for the coregistration GUI) * - Numerics - ``numpy``, ``scipy``, ``pandas``, ``joblib``, OpenBLAS (avoids an MKL crash on Windows while reading KIT sensor positions) * - GUIs and plots - ``pyside6``, ``qtpy``, ``mne-qt-browser``, ``matplotlib``, ``pyvista``, ``pyvistaqt``, ``vtk`` * - Config and tables - ``pyyaml``, ``tabulate`` * - Reports - Quarto CLI (bundles Pandoc), ``ipython``, ``ipykernel``, ``jupyter_client``, ``nbclient``, ``nbformat`` 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: .. code-block:: bash 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: .. code-block:: bash # (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. .. _kit_setup_freesurfer: Optional: FreeSurfer for stage 13 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 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, ``13-freesurfer_reconstruction.py`` is launched with the Windows ``neurowaves`` interpreter and forwards the work into WSL, where ``python3`` and PyYAML must exist: .. code-block:: bash # 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$\``. Stage 13 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 14 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 ``) is one window for the whole pipeline. It reads the summary tables the stages write and shows, per recording (stages 1 to 10, 17 and 18), per subject (13 to 16) and for the group stages (21 to 24), 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 :ref:`kit_pipeline_project_config` 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): .. code-block:: bash 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, 7, 8, 9, 10): rebuild outputs that already exist. Without it, existing outputs are skipped and reported as such. Stage 5 redraws a picture by itself when its FIF changed; stage 6 rebuilds its tables on every run. - ``--write-scans-draft`` (stage 2): write a draft ``scans.tsv`` with the marker pairing per subject and session, to review and copy next to the data. - ``--no-plots`` (stage 6): tables only. - ``--desc