Pipelines Overview
Different pipelines can be built with the software available at the NYUAD MEG Lab, tailored to best answer your research questions.
Important
The pipelines are provided for use with the understanding that bugs may exist. The pipelines provided by the MEG lab can never be tested for all situations and cases. It is therefore the project owner’s responsibility to check whether the output of any pipeline they use is correct. Pipeline users should report any suspicious output, or suggest test cases that would make the test benchmarks more robust, by raising an issue on the repository.
Software stack and installation
The following software and libraries are available for MEG/EEG data analysis:
MNE Python library
FieldTrip
BESA
Sample pipelines are provided for each of them.
MNE Python
Installation
The MNE-based pipelines in this repository run in a dedicated Conda environment
named neurowaves, defined by
pipeline/mne_pipelines/kit_general_pipelines/environment.yml. Creating,
verifying and updating it is described on
KIT general pipeline: environment setup and running. The MNE standalone
installer is no longer the recommended way to run the lab pipelines: it lacks
some of the pipeline’s dependencies and its versions cannot be pinned by the
repository.
FreeSurfer for source localisation
Source localisation with MNE needs a FreeSurfer reconstruction of each participant’s T1w MRI. FreeSurfer runs on Linux (on Windows, inside WSL2), and stage 13 of the KIT general pipeline runs it for a whole BIDS dataset, and stage 14 has every reconstruction checked by a reviewer before the MEG-MRI coregistration (stage 15) uses it. Its installation is described on Optional: FreeSurfer for stage 13.
Starting a project with the general MNE-KIT pipeline
You have acquired MEG-KIT data at NYUAD, organised it in BIDS following the
lab’s naming convention (see Data Naming and Storing: directory structure, entity
order, and the naming rules for .con, .mrk, laser-scan head shape and
empty-room files), and want to start pre-processing. The pipeline finds every
file through these BIDS names, so a dataset that does not follow the convention
will be partly or entirely skipped. The layout it expects is:
<datasets parent>/ # value of MEG_DATA or project.root_override
<project name>/ # project.name: the BIDS root
dataset_description.json
participants.tsv
sub-001/
anat/sub-001_T1w.nii.gz # only needed for stage 13
ses-01/ # only if the subject has several sessions
meg/
sub-001_ses-01_task-<task>_run-01_meg.con
sub-001_ses-01_task-<task>_run-01_proc-CALMnoisereduction_meg.con
sub-001_ses-01_task-rest_acq-<N>_space-ALS_markers.mrk
sub-001_ses-01_acq-head_headshape.txt
sub-001_ses-01_acq-points_headshape.txt
derivatives/ # created by the pipeline, one folder per stage
The KIT general pipeline is a sequence of numbered scripts driven by one YAML
config per dataset, passed to every stage with -c / --config. Before
running any stage, create a preliminary config for your project as follows.
Copy the template and name it after your project:
cd pipeline/mne_pipelines/kit_general_pipelines/pipeline_config_files cp config_template.yml <project>_config.yml
Relative paths written inside the YAML are resolved from the folder that contains the YAML, not from the folder you launch the scripts from.
Point it at your dataset (
projectblock). The pipeline builds the BIDS root as<parent>/<project.name>:name: the exact name of your BIDS root folder (case-sensitive on Linux), for example"kidlang".root_env/root_override: where<parent>comes from. Either keeproot_override: nulland set the environment variable named byroot_env(defaultMEG_DATA) to the parent folder in the shell that runs the stages (or before starting VS Code):export MEG_DATA=/path/to/datasets_parent # Linux / macOS $env:MEG_DATA = "D:\MEG_Data" # Windows PowerShell
or write the parent folder directly in
root_override. On Windows use forward slashes, single quotes or doubled backslashes ("D:/MEG_Data",'D:\MEG_Data'or"D:\\MEG_Data"): a single backslash inside double quotes breaks the YAML.
Choose the subjects (
subjectsblock). Labels are written without thesub-prefix.include: []processes everysub-*folder found in the BIDS root;excludealways skips the listed labels (pilots, unusable subjects). For a first run, restrictincludeto one or two subjects, for exampleinclude: ["001"].Choose the recordings (
bids_selectionblock). Every filter left as[]means “all”. Values are the labels as they appear in the file names, without the entity prefix ("01", not"ses-01"). Set at least:tasks: your task label(s) if the dataset holds more than one task.processings: whether to process the raw or the CALM noise-reduced.confiles.[null]selects raw files only (noproc-entity),[CALMnoisereduction]the CALM files only, and[]processes both as separate recordings.
The other filters (
sessions,acquisitions,runs,splits,recordings,spaces,descriptions) can stay empty unless you want to process a subset. The nestedexcludeblock removes matches, for exampleexclude: {tasks: [rest]}.Reports (
reportsblock). The report is HTML only (formats: ["html"]).Leave every other block at its template value for now (
kit2fiff,bad_channels,filters,events,epoching,plots,freesurfer). Do not delete them: they are read by later stages.
The keys changed in a typical preliminary config are therefore only:
project:
name: "myproject"
root_env: "MEG_DATA"
root_override: null
subjects:
include: ["001"]
exclude: []
bids_selection:
tasks: ["mytask"]
processings: [null]
reports:
formats: ["html"]
Every stage prints the BIDS root it resolved when it starts. On your first run,
check that this path is your dataset folder; if it is not, fix project.name
or the parent folder before going further.
The settings that are specific to each processing step are described on the page of that step below, and you complete the same YAML as you progress:
calm(stage 0): the MEG160 executable, the outputproclabel and optional overrides of the Noise Reduction dialog (nullkeeps MEG160’s pre-filled values).kit2fiff(stage 2): trigger decoding (stim,slope,stimthresh,stim_code). The conversion always goes through the KIT-to-FIFF GUI; stage 5 has no settings of its own.head_movement(stage 6):warn_mmand the figure switches.events.multi_channel.max_onset_skew_ms(stages 1 and 3): grouping of binary-coded triggers.bad_channels(stage 7): segment plan, detector thresholds (flat/peak, variance, PSD, line noise, LOF, Maxwell), decision rule (decision.min_detectors), per-subjectmanualandignore_detectedlists, and the review browser settings.filters(stage 9): notch and band-pass. When the block is absent, stage 9 applies a notch at the 50 Hz harmonics and a 1 to 40 Hz band-pass.eventsandplots(stage 3): thedesclabel written by stage 3 and read by stage 10, thesourcebranch used by stage 10,find_eventskwargs for the STI 014 variant, and the stim-channel plots.epoching(stage 10): globaltmin,tmaxandbaselineplus per-event-codewindows.freesurfer(stage 13):missing_anat: fsaverage | error, resource planning (jobs,threads_per_subject),auto_cw256and themkheadsurfscalp surface (scalp_surface,scalp_threshold).freesurfer_qc(stage 14): flag thresholds, figures, freeview button and YAML verdict overrides.coregistration(stage 15):require_mri_qcand the QA figures.reports(all stages): per-script switches,quarto_envandoutput_dir.
The commented config_template.yml remains the reference for every key, and
kidlang_config.yml is a complete worked example.
Order of pages for the general MNE-KIT pipeline
Read the setup page first, then the stage pages in the order of the stages. Every stage has its own page; the page number is the stage number.
Environment setup and running: create the
neurowavesenvironment, run the stages, find the outputs and the auto-generated report.Stage 1, trigger count sanity check (single-channel and binary-coded trigger modes): verify that no triggers were lost and that they are detected in the right order. Recommended before any analysis of analog-trigger datasets.
Stage 2, KIT to FIFF: convert the raw
.confiles (with and without CALM noise reduction) to.fifwith head shape and markers, through the KIT-to-FIFF GUI, one window per recording. The GUI walkthrough page shows the controls of this GUI and of the coregistration GUI of stage 15.Stage 3, compute events: write the
.evefiles from the analog trigger lines or from theSTI 014channel; stage 10 epochs from them.Stage 4, photodiode timing (experiments with a photodiode): measure the delay between each trigger and the light of the screen and move the visual events to the time the participant saw them.
Stage 5, head shape and sensor alignment plots: a picture of the alignment accepted in stage 2 for every FIF, the QC of the conversion.
Stage 6, head movement between marker measurements: a timeline per session of the HPI coil positions and of the displacement attributed to each recording, from the marker files only.
Stage 7, bad channel detection: human-in-the-loop audit of the 207 KIT gradiometers (inspection in MNE’s browser, automatic candidates, confirmation); the resulting list is applied by stage 9 and inherited by every later stage.
Stage 8, ICA: COGNESTIC-style ICA (fit on a 1 Hz high-passed copy, ECG/EOG proposals, review in MNE’s source browser); stage 9 applies the reviewed exclusions to the unfiltered data before filtering.
Stage 9, apply filters: write the cleaned continuous recording (bad channels marked, ICA applied, notch and band-pass) with its provenance.
Stage 10, epochs and evoked responses: one epochs file and one evoked response per event code, from the stage-9 FIF and the stage-3 events, with the sensor-level figures (joint plot, single epochs, drop log) and peaks.
Stages 11 and 12, time-frequency and spectra: time-frequency power and inter-trial coherence of the epochs; spectra and band powers over time for long recordings without events (sleep, rest).
Stage 13, FreeSurfer reconstruction:
recon-alland the scalp surface for every subject with a T1w (Linux, HPC or WSL).Stage 14, FreeSurfer QC: metrics, flags, figures and a reviewer’s verdict on every reconstruction before it is used.
Stage 15, manual MEG-MRI coregistration: the MNE coregistration GUI per subject, on the approved reconstruction or on
fsaverage, with QA distances.Stages 16 to 24, source analysis, statistics and multivariate: automatic template coregistration (16), forward model (17), inverse solution (18), band-limited power in source space for oscillations that are not phase-locked to the event (19), equivalent current dipole fits of the evoked components, with the variance they explain and the field topographies (20), group averages and contrasts (21), cluster permutation tests (22), RSA and decoding (23), and movies of the source estimates, individual and group (24).
The results in Python: every figure and table of the report carries the code that reproduces it (
results.py); see the last page below.
FieldTrip
Download and install FieldTrip by following the instructions at https://www.fieldtriptoolbox.org/download/.
FieldTrip coregistration with OPM data
You need the headshape.pos file, which contains the head shape grid and 3 fiducials: the nasion, the LPA and the RPA
(these three fiducials are at the end of the .pos file).
As a reminder, the laser scanner generates a basic_surface.txt file, which contains the head points,
and a stylus.txt file, which contains 8 reference points, of which the first three are needed
(see the laser scan steps of the Operational Protocol).
Use ft_read_headshape to read the .pos file and the fiducials.
Information on head coordinate systems is available at https://www.fieldtriptoolbox.org/faq/coordsys/.
Beamforming, source reconstruction
A beamformer measures the contribution of each sensor to a source signal (a weighting of the sensors with respect to a specific source):
where \(S\) is the source estimate, \(W\) holds the beamformer weights (3 columns, for the 3 orientations of each dipole) and \(b\) is the channel measurement.
The question is to find the right \(W\) among the many possible ones. Adding constraints reduces the ill-posedness of the problem:
forward model constraints, from physiological data
inverse problem constraints
Spatial filtering assumes that there is only one source and estimates its activity independently from the other sources (the estimate is the product of the weight matrix and the channel measurements); this is repeated over all the sources.
Under a simple assumption, the lead field matrix \(L\) is the inverse of the weight matrix \(W\). An additional constraint takes the neighbouring sources into account: the weights \(W\) at a source \(r\) should not give a high gain for another source \(q\) located at a certain distance from \(r\) (\(q\) not being a direct neighbour). For direct neighbours, the gain is only slightly reduced rather than set to 0. The variance is therefore minimised, which ensures smoothness and a reduced gain in the neighbours: this is the Linearly Constrained Minimum Variance (LCMV) beamformer.
\(W\) and \(S\) are both unknown, and minimising \(\operatorname{var}(S)\) requires knowing \(W\). However, there is a relationship between \(W\), \(L\) and \(C\), the covariance matrix of the measured data (how dependent each measurement is on the others). In FieldTrip, the configuration selects the LCMV algorithm, or DICS for frequency analysis, to use this beamformer.
Computing the inverse of \(C\), which is needed for the solution, requires that \(C\) is not rank deficient (rank deficiency reflects dependencies between its rows or columns). A short time window, or having applied ICA, can make \(C\) rank deficient.
Continuous stimulus
A dissimilarity matrix is a comparison measure between different stimuli: its values are low when the stimuli are similar. Computed at each time point, both at the level of the stimulus and at the level of the brain response, it is a way of measuring brain activity for time-continuous stimuli (video, speech, etc.).
BESA Software
The following are the main steps for processing MEG data with the BESA MRI and BESA Research suite. Most of this section is a collection of notes taken during BESA training sessions.
BESA installation
Download BESA from https://www.besa.de/.
The BESA license available at the NYUAD MEG lab will soon be hosted on a server; instructions to use it will then be made available on this page.
MRI segmentation and coregistration
If you have MRI data of your participant:
Open BESA MRI, start a new segmentation project, check all the segmentation options (especially BEM and FEM), pick the landmarks for the segmentation and start the process. Once done, BESA saves the segmentation and the BEM and FEM model outputs.
In BESA MRI, start a new coregistration project.
Open BESA Research and load your MEG data in
.fifformat. To get a.fiffile from the.conand.mrkfiles, use MNE kit2fiff, then open the.fifin BESA.
Notes:
Choosing the AC: start with the sagittal view and pick the end of the white matter fibers, then go to the coronal view and pick the point where the white matter fibers link the left and right hemispheres (above the black point).
Set the nasion on the surface of the skin, because the digitization is performed on the skin.
The coregistration files are saved under
C:\Users\Public\Documents\BESA MRI\Projects\(for example inAS-oddball-task_19010101).
Inspecting the data
Use Open file and clear DB to erase the previous settings.
To quickly inspect the data and view the field at a specific time on a template head, with the sensor layout loaded from the
.fif, enable Options -> Mapping -> Enable direct mapping by double clicking. Then double-click at a specific time to see the field on the template head.Radial activity within the brain can only be picked up partially by the SQUIDs.
BESA ships with an examples folder containing different datasets.
In artifact rejection, the Low signal criterion is used to cut flat signals (signals that are saturated with noise).
A BESA project directory contains, among others:
.pdg: the paradigm file (triggers, conditions, groups).fsg: the averaged trials (trials and averages)
Source localization
The algorithms available for source localization include sLORETA, LORETA (named CLARA in BESA, where it is applied recursively), dSPM, the Equivalent Current Dipole (well suited when the phenomenon is triggered by one area of the brain and not by multiple areas at once) and beamformers.
Steps:
After the coregistration, make sure that the coregistration file is checked in BESA Research (File > Coregistration).
Define your trials and average them, then pick a time window, right-click and choose Source analysis.
Pick BEM or FEM as the conducting model (the spherical model is only a template and is not used for source localization).
Choose a window in the top left panel, then pick CLARA or another algorithm.
Things to keep in mind:
In source analysis, never forget to set the baseline properly, on a period before the stimulus where there is not much activity.
After the source localization, use the up and down arrows to change the sensitivity of the heatmap.
If the source analysis crashes when using CLARA, reduce the voxel size.
CLARA goes through each time point, computes the inverse solution for each of them, then shows the average over the time region of activation.
PCA can indicate how many sources are needed: if there are 3 components with high activity, 3 dipoles are needed. Right-click a PCA component and add it to the solution to see where the dipole for that component is located.
Use Residual to see which part of the data is not explained. You can uncheck the data, keep the residual, and fit again for the residual part only.
The confidence level indicates how well the dipole explains the data (but it is not a validation).
The regularization parameter is very important for all methods. For the beamformer in the oddball task, the best value was 0.01 (the parameter is accessed from Image Settings).
The beamformer did not work well in the oddball task because the noise level was high (the artifacts were fine). The result can be improved by choosing a baseline with lower noise (-300 to -200).
SESAME uses Bayesian statistics to estimate the number of sources.
Cortical LORETA is LORETA applied not to the MRI volume but to the reconstructed brain model (inflated or not).
When to use CLARA, a beamformer or SESAME:
Clinically, CLARA (a distributed model, in which each voxel has an activity) and dipole fitting are the approved methods.
For MEG, a beamformer is a good choice, because MEG has a better spatial separation than EEG.
SESAME uses a dipole model and does not assume that each voxel has an activity.
CLARA followed by SESAME: CLARA shows the regions of activity, and SESAME can then use dipoles in these regions as a prior. This should give a more accurate, more focal result. Click Weight By Image to use the output of CLARA as the input (prior) of SESAME.
Frequency analysis in BESA
Time-frequency analysis is currently not possible with sLORETA or CLARA. A workaround is to apply high-pass and low-pass filters around the band of interest, then run a time-locked analysis with CLARA/LORETA.
A frequency analysis of the source time series obtained with CLARA (tried on the oddball task) is not directly possible: the orientations of the sources can be very different, in which case the oscillation effect can double the frequency power.
In resting state, after computing an FFT, you can define your own frequency band in Options (Band Name and Width); you must be in source space (SRC) first. We ran a beamformer in the time domain, defined a source on the maximum obtained, and looked at the estimated time series at that maximum.
Connectivity analysis
Some regions can be activated at the same time; in other situations, one region fires and then triggers other regions. Identifying which region initiates the activity is an unsolved question.
A source montage is the definition of the sources.
In epilepsy, one region or several regions can be activated at the same time. In another kind of epilepsy, the whole brain is activated; in yet another, the right hemisphere is activated and then the left hemisphere.
Batch processing
Batch processing is the automation workflow of BESA, used to run similar steps multiple times. Open it with Shift+R, or with Process -> Batch Processing. A Pause step stops the batch after a step so that the user can check things or take a screenshot; the batch then continues.
Exporting the source-localized activity to NIfTI
Solution 1: use MIND.
Solution 2: export a
.vmrfile (BrainVoyager) and use NeuroElf (a free MATLAB toolbox) to import the MRI from the.vmrfile, then import the analysis.Solution 3: after the source analysis, export and choose
ACPC.nii(this setting only appears when the coregistration is set).Solution 4 (longer term): find the transformation parameters in the project file, use them to get to ACPC coordinates and apply them to the DICOM. The exported
.niiactivity image (in ACPC) should then match the anatomical image.
Open questions and to-do list
The number of digitized head points, and the alignment during coregistration
How BESA picks up the triggers of the oddball experiment
Identify the metrics used to compute the artifact rejection heatmap (and see whether different metrics can be used)
The time axis of the PCA components
Save solution works for dipoles but not for CLARA
Saving the activity coregistered with the T1 MRI
How the USB license can be hosted on a server
Frequency analysis of the difference between eyes closed and eyes open, in sensor space and in source space
OPM coregistration: how the pink points and the sensors are connected
OPM trigger processing: show the amplitude value of the codes
Ask FieldLine about the fiducials that are automatically added to the
.fiffile without a digitized headReport to BESA: on
MISC_002, one trigger is up and one is down, whereas both should be up
Already covered: the MATLAB import from BESA, seeding a dipole, and CLARA followed by SESAME.
General analysis concepts
Denoising
There are many sources of noise to be aware of:
noise related to the site in which the MEG system is installed
noise related to conditions that occur from time to time (for example, a parking garage nearby)
Once the causes are understood, the pattern produced by each noise source can be identified.
With training data covering the different possible noise sources, it is quite possible to train a neural classifier that identifies the noise coming from each source and removes it from the MEG data.
Independent component analysis
Independent component analysis (ICA) is commonly used to derive a set of signals that are assumed to be independent from a given set of correlated signals.
The signals produced by MEG are highly correlated, so ICA is well suited to separating them. Given a set of MEG signals \(X(t)\), ICA learns a matrix \(W\) and the output signals \(S(t)\) such that
ICA performs well at identifying noise signals that have a long-lasting, continuous pattern in time, but it is less efficient when the noise is a single event happening at irregular intervals.
projs, raw.info['projs'] = raw.info['projs'], []
ica.fit(raw)
raw.info['projs'] = projs
Frequency Analysis
Fast-oscillating signals correspond to high frequencies, and slow oscillations to low frequencies. In Fourier space (the signal represented by its Fourier transform), we can see the frequency components that constitute the signal. The FFT (Fast Fourier Transform) algorithm is commonly used to identify these frequency components.
Research has shown that signals at different frequencies have different functions at different locations in the brain. In other words, in a given region of the brain, signals at 8 Hz reflect an activity that is very different from that of signals at 20 Hz.
Brain Source Estimate
When neurons become active, they do so in large groups.