lameg package#
Submodules#
lameg.invert module#
Laminar source inversion and MEG-MRI coregistration tools using SPM.
This module provides a high-level Python interface for performing source reconstruction and forward modeling of MEG data via the SPM standalone engine. It supports both Empirical Bayesian Beamformer (EBB) and Multiple Sparse Priors (MSP) algorithms, as well as utilities for working with inversion outputs.
Main functionalities#
Coregistration: Aligns MEG sensor data with anatomical MRI and surface meshes, and constructs a forward model using the Nolte single-shell approximation.
Empirical Bayesian Beamformer (EBB): Performs source inversion using empirical Bayesian beamforming with cross-validation.
Multiple Sparse Priors (MSP): Performs sparse Bayesian inversion with optional vertex-level priors to constrain source localization.
Sliding-window inversion: Applies MSP within time windows to obtain time-resolved estimates of free energy (model evidence).
Reconstruction utilities: - Load source-space time series from precomputed inversions or lead field matrices. - Verify the existence of inversion structures in SPM data files. - Extract cortical mesh vertex coordinates from forward models.
Notes
All inversion and coregistration routines depend on a valid SPM standalone installation accessible via the spm_context interface.
Meshes must be provided through a LayerSurfaceSet object, typically containing pial, white, and intermediate laminar surfaces.
This module supports both MATLAB v7.3+ (HDF5) and pre-v7.3 file formats for SPM data.
- lameg.invert.check_inversion_exists(data_file)#
Verify the presence of source inversion data within an SPM M/EEG dataset file.
This function checks whether an SPM-compatible M/EEG .mat file (either v7.3+ HDF5 or pre-v7.3 MATLAB format) contains the required inversion structure (D.other.inv), indicating that a source reconstruction has been performed.
- Parameters:
data_file (str) – Path to the SPM M/EEG .mat file.
- Returns:
True if an inversion structure is present in the file.
- Return type:
bool
- Raises:
KeyError – If the inversion structure is missing, indicating that source inversion has not been run on the dataset.
Notes
Supports both MATLAB v7.3+ (HDF5) and older pre-v7.3 formats.
Used internally by reconstruction utilities such as load_source_time_series().
- lameg.invert.coregister(fid_coords, data_fname, surf_set, layer_name=None, stage='ds', orientation='link_vector', fixed=True, fid_labels=('nas', 'lpa', 'rpa'), iskull_fname=None, oskull_fname=None, scalp_fname=None, forward_model_type='Single Shell', viz=True, spm_instance=None)#
Perform MEG-MRI coregistration and compute the forward model using the Nolte single-shell method.
This function uses SPM’s standalone interface to coregister MEG sensor data to the subject’s anatomy. It constructs a forward model based on a specified laminar surface mesh (from a LayerSurfaceSet) and fiducial-based alignment between headshape and MRI coordinates. The laminar surface is selected by layer name, processing stage, and orientation parameters. The forward model type can be chosen from several SPM-compatible MEG models.
- Parameters:
fid_coords (dict) – Dictionary of fiducial landmark coordinates, e.g.:
{'nas': [x, y, z], 'lpa': [x, y, z], 'rpa': [x, y, z]}Values must be expressed in MEG headspace coordinates (millimeters).data_fname (str) – Path to the MEG dataset (SPM-compatible format).
surf_set (LayerSurfaceSet) – The subject’s surface set containing laminar meshes.
layer_name (str or None, optional) – Layer surface to use for forward modeling (e.g., ‘pial’, ‘white’, or fractional layer). If None, the multilayer combined surface is used.
stage (str, optional) – Processing stage of the surface mesh (default: ‘ds’).
orientation (str, optional) – Orientation model used for dipole alignment (default: ‘link_vector’).
fixed (bool, optional) – Whether to use fixed dipole orientations across layers (default: True).
fid_labels (sequence of str, optional) – Labels for fiducial points, typically (‘nas’, ‘lpa’, ‘rpa’).
iskull_fname (str or None, optional) – Path to the inner-skull surface. If None, an empty string is passed to SPM.
oskull_fname (str or None, optional) – Path to the outer-skull surface. If None, an empty string is passed to SPM.
scalp_fname (str or None, optional) – Path to the scalp/outer-skin surface. If None, an empty string is passed to SPM.
forward_model_type ({'Single Sphere', 'MEG Local Spheres', 'Single Shell',) –
BEM'} ('MEG OpenMEEG) – MEG forward model to use. Defaults to ‘Single Shell’.
optional – MEG forward model to use. Defaults to ‘Single Shell’.
viz (bool, optional) – Whether to display SPM’s coregistration and forward model visualization (default: True).
spm_instance (spm_standalone, optional) – Active standalone SPM instance. If None, a temporary instance is created and closed after execution.
Notes
The function constructs and executes an SPM batch job using the provided fiducials and mesh information.
The forward model uses the Nolte single-shell MEG head model.
The mesh is derived from the LayerSurfaceSet and passed to SPM as a custom cortical surface.
- lameg.invert.get_lead_field_rms_diff(data_file, surf_set)#
Compute vertex-wise RMS difference of lead field vectors across cortical depths relative to the superficial (pial) layer.
This function loads the forward model (gain matrix) generated by SPM and quantifies how the lead field topographies change with cortical depth. For each vertex, it computes the root-mean-square (RMS) difference between the superficial (layer 1) lead field and the corresponding lead fields at deeper layers, returning the RMS difference for the deepest layer.
- Parameters:
data_file (str or pathlib.Path) – Path to the SPM-compatible MEG dataset (.mat) for which the inversion was run. The corresponding gain matrix file (e.g.,
SPMgainmatrix_<data_base>_1.mat) is expected in the same directory.surf_set (LayerSurfaceSet) – The subject’s laminar surface set used for forward modeling. Provides the number of layers and vertices per layer.
- Returns:
rms_dff – Vertex-wise RMS difference between the deepest and superficial layer lead fields. Values reflect how much lead field topography changes with depth.
- Return type:
numpy.ndarray, shape (n_vertices,)
Notes
The gain matrix (‘G’) is assumed to be depth-ordered, with all vertices from layer 1 first, followed by subsequent layers.
RMSE is computed as the Euclidean distance between lead field vectors, averaged across sensors.
The function requires a valid SPM inversion; otherwise, it will not execute.
Useful for assessing layer-wise forward model sensitivity and laminar discriminability.
- lameg.invert.invert_ebb(data_fname, surf_set, layer_name=None, stage='ds', orientation='link_vector', fixed=True, patch_size=5, n_temp_modes=4, n_spatial_modes=None, foi=None, woi=None, hann_windowing=False, n_folds=1, ideal_pc_test=0, viz=True, return_mu_matrix=False, spm_instance=None)#
Perform Empirical Bayesian Beamformer (EBB) source inversion on MEG data.
This function runs the SPM EBB source reconstruction pipeline on MEG data that has already been coregistered with an anatomical mesh. It first smooths the specified cortical or laminar mesh, then prepares spatial and temporal modes, and finally computes source inversion using SPM’s EBB algorithm. Optionally, it returns the full projection matrix used to reconstruct source activity.
- Parameters:
data_fname (str) – Path to the MEG dataset (SPM-compatible .mat file).
surf_set (LayerSurfaceSet) – The subject’s surface set containing laminar meshes.
layer_name (str or None, optional) – Surface layer to use for inversion (e.g., ‘pial’, ‘white’, or a fractional layer). If None, the full multilayer surface is used.
stage (str, optional) – Processing stage of the surface mesh (default: ‘ds’).
orientation (str, optional) – Orientation model used for dipoles (default: ‘link_vector’).
fixed (bool, optional) – Whether to use fixed dipole orientations across layers (default: True).
patch_size (float, optional) – Full-width at half-maximum (FWHM) of cortical patch smoothing in millimeters (default: 5).
n_temp_modes (int, optional) – Number of temporal modes for dimensionality reduction (default: 4).
n_spatial_modes (int or None, optional) – Number of spatial modes for data reduction. If None, all channels are used.
foi (list of float, optional) – Frequency range of interest [low, high] in Hz (default: [0, 256]).
woi (list of float, optional) – Time window of interest [start, end] in ms (default: full epoch).
hann_windowing (bool, optional) – Whether to apply Hann windowing to data before inversion (default: False).
n_folds (int, optional) – Number of cross-validation folds for spatial mode testing (default: 1).
ideal_pc_test (float, optional) – Fraction of channels to leave out during cross-validation (default: 0).
viz (bool, optional) – Whether to display SPM’s inversion progress and diagnostic plots (default: True).
return_mu_matrix (bool, optional) – If True, return the full source reconstruction matrix (default: False).
spm_instance (spm_standalone, optional) – Active standalone SPM instance. If None, a temporary instance is created and closed after execution.
- Returns:
results – A list containing: - free_energy : float
Model evidence (free energy) from the inversion.
- cv_errfloat
Cross-validation error across data folds.
- mu_matrixscipy.sparse.csc_matrix, optional
Source reconstruction matrix (returned only if return_mu_matrix=True).
- Return type:
list
Notes
The forward model must be precomputed via coregister() before calling this function.
Mesh smoothing uses spm_eeg_smoothmesh_multilayer_mm.
Spatial mode preparation and cross-validation use spm_eeg_inv_prep_modes_xval.
- lameg.invert.invert_msp(data_fname, surf_set, layer_name=None, stage='ds', orientation='link_vector', fixed=True, priors=None, patch_size=5, n_temp_modes=4, n_spatial_modes=None, foi=None, woi=None, hann_windowing=False, n_folds=1, ideal_pc_test=0, viz=True, return_mu_matrix=False, spm_instance=None)#
Perform Multiple Sparse Priors (MSP) source inversion on MEG data.
This function runs SPM’s MSP source reconstruction pipeline using a specified cortical or laminar surface mesh. The procedure includes mesh smoothing, spatial mode preparation, and inversion using MSP. Optional vertex-level priors can be provided to constrain the inversion to specific cortical patches. The MEG dataset must already be coregistered with the provided surface mesh.
- Parameters:
data_fname (str) – Path to the MEG dataset (SPM-compatible .mat file).
surf_set (LayerSurfaceSet) – The subject’s surface set containing laminar meshes.
layer_name (str or None, optional) – Surface layer to use for inversion (e.g., ‘pial’, ‘white’, or a fractional layer). If None, the full multilayer surface is used.
stage (str, optional) – Processing stage of the surface mesh (default: ‘ds’).
orientation (str, optional) – Orientation model used for dipoles (default: ‘link_vector’).
fixed (bool, optional) – Whether to use fixed dipole orientations across layers (default: True).
priors (list of int, optional) – List of vertex indices to be used as MSP priors (0-based Python indexing). If None or empty, random patches are used as priors.
patch_size (float, optional) – Full-width at half-maximum (FWHM) of cortical patch smoothing in millimeters (default: 5).
n_temp_modes (int, optional) – Number of temporal modes for dimensionality reduction (default: 4).
n_spatial_modes (int or None, optional) – Number of spatial modes for data reduction. If None, all channels are used.
foi (list of float, optional) – Frequency range of interest [low, high] in Hz (default: [0, 256]).
woi (list of float, optional) – Time window of interest [start, end] in ms (default: full epoch).
hann_windowing (bool, optional) – Whether to apply Hann windowing to data before inversion (default: False).
n_folds (int, optional) – Number of cross-validation folds for spatial mode testing (default: 1).
ideal_pc_test (float, optional) – Fraction of channels to leave out during cross-validation (default: 0).
viz (bool, optional) – Whether to display SPM’s inversion progress and diagnostic plots (default: True).
return_mu_matrix (bool, optional) – If True, return the full source reconstruction matrix (default: False).
spm_instance (spm_standalone, optional) – Active standalone SPM instance. If None, a temporary instance is created and closed after execution.
- Returns:
results – A list containing: - free_energy : float
Model evidence (free energy) from the inversion.
- cv_errfloat
Cross-validation error across data folds.
- mu_matrixscipy.sparse.csc_matrix, optional
Source reconstruction matrix (returned only if return_mu_matrix=True).
- Return type:
list
Notes
The forward model must be precomputed via coregister() before calling this function.
If priors are provided, they are converted to 1-based indices to match MATLAB conventions.
Mesh smoothing uses spm_eeg_smoothmesh_multilayer_mm.
Spatial mode preparation and cross-validation use spm_eeg_inv_prep_modes_xval.
- lameg.invert.invert_sliding_window(prior, data_fname, surf_set, layer_name=None, stage='ds', orientation='link_vector', fixed=True, patch_size=5, n_temp_modes=1, n_spatial_modes=None, win_size=50, win_overlap=True, foi=None, hann_windowing=True, viz=True, spm_instance=None)#
Perform Multiple Sparse Priors (MSP) source inversion over sliding time windows.
This function applies SPM’s MSP source reconstruction algorithm within successive overlapping or non-overlapping time windows, enabling time-resolved estimation of source model evidence (free energy). It smooths the surface mesh, prepares spatial modes, and repeatedly inverts the MEG data across windows using a fixed spatial prior centered on a specified vertex. The MEG dataset must already be coregistered with the surface mesh.
- Parameters:
prior (int) – Index of the vertex to be used as the MSP prior (0-based Python indexing).
data_fname (str) – Path to the MEG dataset (SPM-compatible .mat file).
surf_set (LayerSurfaceSet) – The subject’s surface set containing laminar meshes.
layer_name (str or None, optional) – Surface layer to use for inversion (e.g., ‘pial’, ‘white’, or a fractional layer). If None, the full multilayer surface is used.
stage (str, optional) – Processing stage of the surface mesh (default: ‘ds’).
orientation (str, optional) – Orientation model used for dipoles (default: ‘link_vector’).
fixed (bool, optional) – Whether to use fixed dipole orientations across layers (default: True).
patch_size (float, optional) – Full-width at half-maximum (FWHM) of cortical patch smoothing in millimeters (default: 5).
n_temp_modes (int, optional) – Number of temporal modes for dimensionality reduction (default: 1).
n_spatial_modes (int or None, optional) – Number of spatial modes for data reduction. If None, all channels are used.
win_size (float, optional) – Duration of each sliding window in milliseconds (default: 50).
win_overlap (bool, optional) – Whether consecutive windows overlap (default: True).
foi (list of float, optional) – Frequency range of interest [low, high] in Hz (default: [0, 256]).
hann_windowing (bool, optional) – Whether to apply Hann windowing to each window before inversion (default: True).
viz (bool, optional) – Whether to display SPM’s inversion progress and diagnostic plots (default: True).
spm_instance (spm_standalone, optional) – Active standalone SPM instance. If None, a temporary instance is created and closed after execution.
- Returns:
results – A list containing: - free_energy : ndarray
Array of model evidence (free energy) values across time windows.
- woisndarray, shape (n_windows, 2)
Time windows of interest in milliseconds.
- Return type:
list
Notes
The forward model must be precomputed via coregister() before calling this function.
The prior index is internally converted to 1-based indexing for MATLAB compatibility.
Mesh smoothing uses spm_eeg_smoothmesh_multilayer_mm.
Spatial mode preparation uses spm_eeg_inv_prep_modes_xval.
Each windowed inversion uses the Multiple Sparse Priors (MSP) algorithm in SPM.
- lameg.invert.load_forward_model_vertices(data_file)#
Load the vertex coordinates from the forward model stored in an SPM M/EEG dataset.
This function extracts the cortical mesh vertices used in the forward model from an SPM-compatible .mat file, supporting both MATLAB v7.3+ (HDF5) and legacy pre-v7.3 formats. The returned array contains the vertex coordinates in MNI space.
- Parameters:
data_file (str) – Path to the SPM M/EEG .mat file containing the forward model.
- Returns:
Array of vertex coordinates (n_vertices × 3) in MNI space.
- Return type:
numpy.ndarray
- Raises:
TypeError – If the file cannot be read as a valid MATLAB file.
KeyError – If the forward model or vertex data is missing from the file.
Notes
For MATLAB v7.3+ files, the function reads directly from the HDF5 hierarchy: D/other/inv/mesh/tess_mni/vert.
For older MATLAB formats, it accesses the corresponding nested struct fields.
Typically used after source inversion to recover the 3D cortical geometry associated with the lead field model.
- lameg.invert.load_source_time_series(data_fname, mu_matrix=None, inv_fname=None, vertices=None)#
Load or compute source-space time series from MEG data.
This function reconstructs source-level activity either from precomputed inverse solutions (stored in the MEG data file or an external inversion file) or directly from a provided forward/inverse matrix (mu_matrix). Optionally, the reconstruction can be restricted to a subset of vertices.
- Parameters:
data_fname (str) – Path to the MEG dataset (SPM-compatible .mat file).
mu_matrix (np.ndarray or scipy.sparse matrix, optional) – Precomputed source reconstruction matrix (sources × sensors). If provided, this matrix is used directly to compute source time series. Default is None.
inv_fname (str, optional) – Path to a file containing the precomputed inverse solution. If None, the inversion stored within data_fname is used. Default is None.
vertices (list of int, optional) – List of vertex indices to extract source time series from. If None, all vertices are used.
- Returns:
source_ts (np.ndarray) – Source-space time series (sources × time × trial).
time (np.ndarray) – Time vector in milliseconds.
mu_matrix (np.ndarray or scipy.sparse matrix) – Matrix used to reconstruct source activity from sensor data.
Notes
If both mu_matrix and inv_fname are None, the function attempts to load the inverse solution embedded in data_fname.
When vertices is specified, only the corresponding subset of the inverse matrix is used.
Supports both single-trial and multi-trial MEG data structures.
lameg.laminar module#
Laminar analysis tools for MEG source reconstruction and depth-resolved model comparison.
This module provides functions for performing and evaluating laminar source reconstructions of MEG data using SPM. It integrates surface-based forward models, inversion algorithms, and analytical tools for quantifying laminar-specific neural activity. The main focus is on comparing model evidence across cortical depths, estimating current source density profiles, and identifying regions of interest showing laminar modulation in power.
Key functionalities#
Model comparison: Run Empirical Bayesian Beamformer (EBB) or Multiple Sparse Priors (MSP) inversions across cortical layers and compare model fits using free energy or cross-validation.
Sliding-window inversions: Estimate time-resolved laminar model evidence to capture dynamic changes in cortical processing.
Current source density (CSD): Compute laminar CSD profiles using the StandardCSD method from the elephant library, with optional layer-wise interpolation.
ROI analysis: Identify regions of interest based on layer-specific power modulations between task and baseline periods.
Notes
All inversion routines depend on SPM’s standalone interface for forward modeling and source reconstruction.
Surface geometry and layer definitions are handled through LayerSurfaceSet objects.
- lameg.laminar.compute_csd(signal, thickness, sfreq, method='KCSD1D', smoothing=None, **kwargs)#
Compute laminar current source density (CSD) from multi-layer neural signals.
This function estimates the CSD profile across cortical depth using methods from the elephant.current_source_density module (typically StandardCSD or KCSD1D). The input should be a laminar time series (layers × time) spanning a known cortical thickness. Optionally, a smoothed, interpolated CSD can be computed across layers.
- Parameters:
signal (ndarray, shape (n_layers, n_times)) – Laminar signal (e.g., LFP or current) with layers along the first axis and time along the second.
thickness (float) – Cortical thickness in millimeters.
sfreq (float) – Sampling frequency of the signal in Hertz.
method ({'StandardCSD', 'KCSD1D'}, optional) – The method used for CSD estimation. Default is ‘KCSD1D’.
smoothing ({'linear', 'cubic', 'quadratic'} or None, optional) – Interpolation method for across-layer smoothing. If None, no smoothing is applied. Only applies to StandardCSD
**kwargs – Additional arguments passed to the underlying CSD method (e.g., lambdas, Rs for KCSD1D).
- Returns:
ret_vals – Contains one or two elements: - csd : ndarray, shape (n_layers, n_times)
The estimated current source density.
- smoothed_csdndarray, shape (500, n_times), optional
Layer-interpolated CSD if smoothing is specified (StandardCSD only).
- Return type:
list
Notes
Smoothing uses scipy.interpolate.interp1d independently at each time point.
For KCSD1D, the signal is internally converted to microvolts before CSD estimation.
Ensure signals are continuous and layer-aligned with uniform spacing.
- lameg.laminar.model_comparison(fid_coords, data_fname, surf_set, stage='ds', orientation='link_vector', fixed=True, method='EBB', viz=True, spm_instance=None, coregister_kwargs=None, invert_kwargs=None)#
Perform laminar model comparison by evaluating free energy and/or cross-validation error across cortical surfaces.
This function coregisters MEG data to a subject’s anatomical MRI and performs source reconstruction separately on each layer within a LayerSurfaceSet, using either the Empirical Bayesian Beamformer (EBB) or Multiple Sparse Priors (MSP) algorithm. It returns the free energy and cross-validation error for each layer, enabling laminar model comparison based on model evidence.
- Parameters:
fid_coords (dict) – Dictionary of fiducial landmark coordinates, e.g.:
{'nas': [x, y, z], 'lpa': [x, y, z], 'rpa': [x, y, z]}Values must be expressed in MEG headspace coordinates (millimeters).data_fname (str) – Path to the MEG dataset (SPM-compatible .mat file).
surf_set (LayerSurfaceSet) – The subject’s surface set containing laminar meshes (e.g., pial, white, intermediate).
stage (str, optional) – Surface mesh processing stage (default: ‘ds’).
orientation (str, optional) – Dipole orientation model used for inversion (default: ‘link_vector’).
fixed (bool, optional) – Whether to use fixed dipole orientations across layers (default: True).
method ({'EBB', 'MSP'}, optional) – Source reconstruction method to use (default: ‘EBB’).
viz (bool, optional) – Whether to display SPM visualizations during coregistration and inversion (default: True).
spm_instance (spm_standalone, optional) – Active standalone SPM instance. If None, a temporary instance is created and closed after execution.
coregister_kwargs (dict, optional) – Additional keyword arguments passed to the coregister() function.
invert_kwargs (dict, optional) – Additional keyword arguments passed to the selected inversion function (invert_ebb() or invert_msp()).
- Returns:
f_vals (np.ndarray) – Array of free energy values (one per layer), representing model evidence.
cv_errs (np.ndarray) – Array of cross-validation errors corresponding to each layer.
Notes
The function iterates over all layer surfaces defined in surf_set.
Free energy serves as a quantitative parametric model comparison metric, with higher values indicating better model evidence.
Cross-validation serves as a quantitative nonparameteric model comparison metric, with lower values indicating better model evidence.
Requires prior generation of laminar surfaces and preprocessing of MEG data into SPM-compatible format.
Uses the Nolte single-shell MEG forward model as defined in SPM.
- lameg.laminar.roi_power_comparison(data_fname, woi, baseline_woi, perc_thresh, surf_set, stage='ds', orientation='link_vector', fixed=True, mu_matrix=None, chunk_size=1000, roi_idx=None)#
Compute laminar power changes and identify or reuse regions of interest (ROIs) based on layer-specific modulation.
This function quantifies power changes between a window of interest (WOI) and a baseline window in both pial and white matter layers. If no ROI indices are provided, it identifies spatial regions showing significant power modulation relative to baseline by applying a percentile threshold to vertex-wise t-statistics. If roi_idx is provided, only those vertices are loaded and processed, bypassing ROI computation.
- Parameters:
data_fname (str) – Path to the MEG dataset (SPM-compatible .mat file) containing source time series.
woi (tuple of float) – Window of interest in milliseconds, specified as (start, end).
baseline_woi (tuple of float) – Baseline window in milliseconds, specified as (start, end), used for power normalization.
perc_thresh (float) – Percentile threshold (0-100) for defining significant power changes when roi_idx is None.
surf_set (LayerSurfaceSet) – Subject’s laminar surface set containing pial and white matter meshes.
stage (str, optional) – Surface mesh processing stage (default: ‘ds’).
orientation (str, optional) – Dipole orientation model used for inversion (default: ‘link_vector’).
fixed (bool, optional) – Whether to use fixed dipole orientations across layers (default: True).
mu_matrix (np.ndarray or None, optional) – Precomputed source reconstruction matrix. If None, it is derived automatically from inversion data (default: None).
chunk_size (int, optional) – Number of vertices processed per iteration to optimize memory usage (default: 1000).
roi_idx (array_like or None, optional) – Indices of vertices defining a precomputed ROI. If provided, only those vertices are loaded and analyzed; otherwise, ROIs are computed from all vertices based on perc_thresh.
- Returns:
laminar_t_statistic (np.ndarray) – Paired-sample t-statistic comparing absolute power modulation between pial and white matter layers within the ROI.
laminar_p_value (np.ndarray) – Corresponding p-value of the laminar t-test.
deg_of_freedom (int) – Degrees of freedom for the laminar comparison.
roi_idx (np.ndarray) – Indices of vertices defining the analyzed ROI (either computed or provided).
Notes
Power is computed as the variance of source time series within the specified time windows.
Relative power change is calculated as (WOI - baseline) / baseline per trial and vertex.
If roi_idx is None, the function computes vertex-wise t-statistics between WOI and baseline power, then selects vertices exceeding the given percentile threshold.
If roi_idx is provided, only those vertices are loaded and processed, greatly improving performance for small ROIs.
The resulting laminar statistics quantify whether activation is preferentially expressed in superficial (pial) or deep (white matter) layers within the ROI.
- lameg.laminar.sliding_window_model_comparison(prior, fid_coords, data_fname, surf_set, stage='ds', orientation='link_vector', fixed=True, viz=True, spm_instance=None, coregister_kwargs=None, invert_kwargs=None)#
Perform laminar model comparison over time using sliding-window MSP inversions.
This function performs time-resolved source reconstruction across multiple laminar surfaces using the Multiple Sparse Priors (MSP) algorithm within sliding time windows. For each layer in a LayerSurfaceSet, the function coregisters MEG data to the MRI, performs MSP inversion over successive windows, and computes the corresponding free energy values. The result is a layer-by-time representation of model evidence, suitable for laminar model comparison.
- Parameters:
prior (int) – Index of the vertex to be used as the MSP prior (0-based Python indexing).
fid_coords (dict) – Dictionary of fiducial landmark coordinates, e.g.:
{'nas': [x, y, z], 'lpa': [x, y, z], 'rpa': [x, y, z]}Values must be expressed in MEG headspace coordinates (millimeters).data_fname (str) – Path to the MEG dataset (SPM-compatible .mat file).
surf_set (LayerSurfaceSet) – The subject’s surface set containing laminar meshes (e.g., pial, white, intermediate).
stage (str, optional) – Surface mesh processing stage (default: ‘ds’).
orientation (str, optional) – Dipole orientation model used for inversion (default: ‘link_vector’).
fixed (bool, optional) – Whether to use fixed dipole orientations across layers (default: True).
viz (bool, optional) – Whether to display SPM visualizations during coregistration and inversion (default: True).
spm_instance (spm_standalone, optional) – Active standalone SPM instance. If None, a temporary instance is created and closed after execution.
coregister_kwargs (dict, optional) – Additional keyword arguments passed to the coregister() function.
invert_kwargs (dict, optional) – Additional keyword arguments passed to the invert_sliding_window() function.
- Returns:
f_vals (np.ndarray, shape (n_layers, n_windows)) – Free energy values for each layer and time window.
wois (np.ndarray, shape (n_windows, 2)) – Time windows of interest in milliseconds.
Notes
This function applies the Multiple Sparse Priors (MSP) algorithm within sliding time windows, providing dynamic estimates of model evidence.
Free energy serves as a model comparison metric across both depth and time; higher values indicate better model evidence.
The prior index is internally adjusted to match MATLAB’s 1-based indexing convention.
Requires prior MEG-MRI coregistration via coregister().
Typically used to examine how laminar model evidence evolves during task-related dynamics.
lameg.postinstall module#
laMEG Post-installation Script#
This module performs all post-installation setup tasks for the laMEG package. It installs the DANC SPM Python interface, configures Jupyter notebook extensions (e.g., k3d), and creates a marker file in the user’s home directory (~/.lameg_postinstall) indicating that setup has been completed.
Typical usage (after pip install lameg):
$ lameg-postinstall
If laMEG is installed inside a conda environment, users should deactivate and reactivate the environment after running this script so that any new environment variables take effect:
conda deactivate conda activate <env_name>
- lameg.postinstall.clone_and_install_spm()#
Clones the SPM repository and installs it.
- lameg.postinstall.run_postinstall()#
Run all laMEG post-installation setup tasks.
- lameg.postinstall.setup_jupyter_extensions()#
Sets up Jupyter notebook extensions.
This method creates a script to install and enable the Jupyter k3d extension for the environment. The script will be executed when the environment is activated.
lameg.simulate module#
Simulation tools for MEG data generation using SPM.
This module provides functions for generating synthetic MEG datasets based on user-specified source parameters and an existing SPM forward model. It enables controlled simulations of both current density fields and discrete dipoles, with configurable spatial, temporal, and noise properties. These simulations are intended for testing source reconstruction pipelines, validating laminar inversion methods, and assessing model sensitivity under known ground truth conditions.
Key functionalities#
Current density simulations: Generate distributed cortical activity from one or more vertices with specified dipole moments, patch sizes, and time series, projected through the SPM forward model.
Dipole simulations: Create focal dipolar sources with defined orientations, amplitudes, and spatial extents, optionally unique across trials.
Noise control: Inject Gaussian sensor noise to achieve a user-defined signal-to-noise ratio (SNR).
Trial averaging: Automatically perform trial-level averaging via SPM’s spm_eeg_averaging.
Notes
All simulations require a valid SPM M/EEG dataset containing a forward model.
Both single- and multi-source simulations are supported.
The generated data can be used to benchmark inversion algorithms (e.g., EBB, MSP), estimate laminar sensitivity, or evaluate spatial leakage and depth bias.
Simulations are executed via SPM’s spm_eeg_simulate interface, which ensures biophysically realistic projection of cortical activity to MEG sensors.
- lameg.simulate.run_current_density_simulation(data_file, prefix, sim_vertices, sim_signals, dipole_moments, sim_patch_sizes, snr, sim_woi=None, average_trials=False, spm_instance=None)#
Simulate laminar current density data using SPM’s MEG forward model.
This function generates synthetic MEG datasets by projecting user-defined source time series (signals) from specified cortical vertices through an existing SPM forward model. Each simulated source is defined by its vertex location, dipole moment, and patch extent. Gaussian noise is added at the sensor level to achieve the desired signal-to-noise ratio (SNR), and the simulated data can optionally be averaged across trials.
- Parameters:
data_file (str) – Path to an existing SPM M/EEG .mat file containing a valid forward model, used as the simulation template.
prefix (str) – Prefix for the output simulated dataset (e.g., ‘sim_’).
sim_vertices (int or list of int) – Indices of source vertices (0-based) defining the locations of simulated current sources.
sim_signals (np.ndarray, shape (n_sources, n_times)) – Time series of the simulated source activity for each vertex.
dipole_moments (float or list of float) – Dipole moments (in nA·m) associated with each simulated source.
sim_patch_sizes (float or list of float) – Patch sizes (in mm) around each vertex that define spatial spread of the simulated sources.
snr (float) – Desired signal-to-noise ratio at the sensor level (in dB).
sim_woi (list of float, optional) – Window of interest for the simulation, specified as [start, end] in milliseconds. Default is [-np.inf, np.inf].
average_trials (bool, optional) – Whether to average across simulated trials (default: False).
spm_instance (spm_standalone, optional) – Active standalone SPM instance. If None, a temporary instance is created and closed after execution.
- Returns:
sim_fname – Full path to the generated simulated MEG dataset (.mat file).
- Return type:
str
Notes
Uses SPM’s spm_eeg_simulate function to project source-level activity through the forward model and add Gaussian noise.
Supports both single and multiple simulated sources with different dipole moments or spatial extents.
The forward model (lead field) must be precomputed and stored within data_file.
If average_trials=True, the simulated data are averaged using SPM’s spm_eeg_averaging routine and saved with prefix ‘m’.
This function is useful for validating inversion methods, testing model recovery, and quantifying depth sensitivity under controlled SNR conditions.
- lameg.simulate.run_dipole_simulation(data_file, prefix, sim_vertices, sim_signals, dipole_orientations, dipole_moments, sim_patch_sizes, snr, sim_woi=None, average_trials=False, spm_instance=None)#
Simulate dipole-level MEG data using SPM’s forward model.
This function generates synthetic MEG datasets by projecting source-level dipole activity through an existing SPM forward model. Each dipole is defined by its cortical vertex location, orientation, moment, and patch extent. The resulting MEG data are corrupted with Gaussian noise at the sensor level to achieve a specified signal-to-noise ratio (SNR), and can optionally be averaged across trials.
- Parameters:
data_file (str) – Path to an existing SPM M/EEG .mat file containing a valid forward model, used as the simulation template.
prefix (str) – Prefix for the output simulated dataset (e.g., ‘sim_’).
sim_vertices (int or list of int) – Indices of source vertices (0-based) where dipoles are positioned.
sim_signals (np.ndarray) – Array of simulated dipole time courses, either shaped (n_dipoles × n_times) or (n_dipoles × n_times × n_trials).
dipole_orientations (np.ndarray, shape (n_dipoles, 3)) – Array specifying the 3D orientation vector for each dipole in head coordinates.
dipole_moments (float or list of float) – Dipole moments (in nA·m) for each simulated source.
sim_patch_sizes (float or list of float) – Spatial extent of the simulated dipole patch (in mm).
snr (float) – Desired signal-to-noise ratio at the sensor level (in dB).
sim_woi (list of float, optional) – Simulation window of interest, specified as [start, end] in milliseconds. Default is [-np.inf, np.inf].
average_trials (bool, optional) – Whether to average the simulated data over trials (default: False).
spm_instance (spm_standalone, optional) – Active standalone SPM instance. If None, a temporary instance is created and closed after execution.
- Returns:
sim_fname – Full path to the generated simulated MEG dataset (.mat file).
- Return type:
str
Notes
Uses SPM’s spm_eeg_simulate function to generate sensor-level data from specified dipole configurations.
Supports multiple dipoles with distinct orientations, moments, or spatial extents.
The forward model (lead field) must already exist in data_file.
If average_trials=True, trial-averaged data are computed via SPM’s spm_eeg_averaging and saved with the ‘m’ prefix.
This function is primarily used for testing inversion accuracy, source localization performance, and evaluating laminar sensitivity under controlled SNR conditions.
- lameg.simulate.setup_opm_simulation(data_file, surf_set, s_rate=1000, wholehead=True, sensor_spacing=35, sensor_offset=6.5, n_samples=1000, n_trials=1, density_checks=40, axes=1, sensor_positions_file=None, iskull_fname=None, oskull_fname=None, scalp_fname=None, spm_instance=None)#
Configure and setup an SPM OPM (Optically Pumped Magnetometer) data file.
This function wraps the MATLAB routine
spm_opm_sim()to generate synthetic MEG data using user-specified anatomical meshes, sensor geometry, and simulation parameters. It prepares the required input structure, and executes the SPM simulation within the provided SPM standalone context.- Parameters:
data_file (str) – Path to the intended output data file (used to determine simulation name and destination).
surf_set (LayerSurfaceSet) – Surface set object providing the cortical mesh and MRI reference. The pial surface from
surf_setis used as the cortical source model.s_rate (int, optional) – Sampling frequency in Hz (default: 1000).
wholehead (bool, optional) – If True, sensor array covers the entire scalp; otherwise, sensors are restricted to the upper hemisphere (default: True).
sensor_spacing (float, optional) – Inter-sensor spacing in millimeters (default: 35 mm).
sensor_offset (float, optional) – Distance between scalp and sensor array in millimeters (default: 6.5 mm).
n_samples (int, optional) – Number of time samples per trial (default: 1000).
n_trials (int, optional) – Number of trials to simulate (default: 1).
density_checks (int, optional) – Number of density optimization iterations for sensor packing (default: 40).
axes ({1, 2, 3}, optional) – Number of orthogonal measurement axes per sensor (default: 1).
sensor_positions_file (str, optional) – Path to a .tsv file containing custom sensor positions and orientations. If None, sensors are automatically generated on the scalp surface.
iskull_fname (str, optional) – Optional custom inner skull, outer skull, and scalp surface files (GIFTI format). If omitted, default meshes from SPM segmentation are used.
oskull_fname (str, optional) – Optional custom inner skull, outer skull, and scalp surface files (GIFTI format). If omitted, default meshes from SPM segmentation are used.
scalp_fname (str, optional) – Optional custom inner skull, outer skull, and scalp surface files (GIFTI format). If omitted, default meshes from SPM segmentation are used.
spm_instance (spm_standalone, optional) – Active SPM standalone context for calling
spm_opm_sim(). If None, a temporary instance is created and destroyed automatically.
- Returns:
Absolute path to the generated SPM MEEG .mat file containing the simulated dataset.
- Return type:
str
Notes
The simulation generates .mat and .dat files containing a valid SPM MEEG object.
Meshes must be in scanner RAS coordinates and compatible with the subject’s MRI.
Examples
>>> sim_file = setup_opm_simulation( ... data_file='/home/user/sim/test_sim.mat', ... surf_set=surf_set, ... srate=1000, ... sensor_spacing=30, ... wholehead=False ... )
lameg.surf module#
Tools for generating, managing, and postprocessing laminar cortical surfaces.
This module implements a complete workflow for constructing, manipulating, and visualizing laminar surface meshes derived from FreeSurfer reconstructions. It provides a high-level API for end-to-end postprocessing, including coordinate transformations, hemisphere merging, downsampling, and computation of laminar dipole orientations.
Public API#
Classes#
- LayerSurfaceSet
High-level interface for organizing, validating, and manipulating laminar surface hierarchies.
Functions#
- interpolate_data
Interpolate scalar or vector data between aligned surface meshes.
- convert_fsaverage_to_native
Convert vertices from the fsaverage template space into the subject’s native surface space.
- convert_native_to_fsaverage
Convert vertices from a subject’s native space to the fsaverage template.
Internal utilities handle surface file I/O, mesh decimation, transformation tracking, and FreeSurfer compatibility.
- class lameg.surf.LayerSurfaceSet(subj_id, n_layers, subjects_dir=None)#
Bases:
objectObject-oriented interface for managing subject-specific laminar cortical surfaces.
This class provides standardized access to the laminar surface hierarchy generated from FreeSurfer reconstructions, stored under:
$SUBJECTS_DIR/<subj_id>/surf/laminar
It handles file naming, metadata sidecars, validation, and mappings between processing stages (e.g., ‘converted’ -> ‘nodeep’ -> ‘combined’ -> ‘ds’). The class also provides convenience functions for loading, saving, and verifying consistency across layers and hemispheres.
- Parameters:
subj_id (str) – Subject identifier corresponding to the FreeSurfer reconstruction directory.
n_layers (int) – Number of cortical layers (including white and pial surfaces).
subjects_dir (str, optional) – Path to the FreeSurfer SUBJECTS_DIR. If None, it is read from the environment variable.
- subj_id#
The subject identifier.
- Type:
str
- n_layers#
Number of layers managed by this surface set.
- Type:
int
- layer_spacing#
Proportional thickness values between 0 (white matter) and 1 (pial).
- Type:
np.ndarray
- subjects_dir#
Path to the FreeSurfer subjects directory.
- Type:
str
- subj_dir#
Path to the subject’s directory within SUBJECTS_DIR.
- Type:
str
- mri_file#
Path to the subject’s mri/orig.nii, converted from mri/orig.mgz
- Type:
str
- surf_dir#
Path to the subject’s FreeSurfer surface directory.
- Type:
str
- laminar_surf_dir#
Path to the laminar surface output directory.
- Type:
str
Notes
- File naming follows the convention:
<hemi>.<layer>.<stage>[.<orientation>[.<fixed>]].gii
where each stage represents a processing step (e.g., ‘raw’, ‘converted’, ‘nodeep’, ‘combined’, ‘ds’).
JSON sidecars store transformation matrices, removed vertices, and other metadata.
The class provides validation and mapping functions to ensure geometric and topological consistency across all processing stages.
- __init__(subj_id, n_layers, subjects_dir=None)#
Initialize a LayerSurfaceSet instance for a given subject.
This constructor sets up paths and metadata for managing laminar surface files derived from a FreeSurfer reconstruction. It verifies the existence of the subject directory and defines the expected hierarchy under $SUBJECTS_DIR/<subj_id>/surf/laminar.
- Parameters:
subj_id (str) – Subject identifier corresponding to the FreeSurfer reconstruction directory.
n_layers (int) – Number of cortical layers (including pial and white matter surfaces).
subjects_dir (str, optional) – Path to the FreeSurfer SUBJECTS_DIR. If not provided, the environment variable SUBJECTS_DIR is used.
- Raises:
EnvironmentError – If neither subjects_dir is provided nor the environment variable SUBJECTS_DIR is set.
FileNotFoundError – If the subject directory does not exist or if FreeSurfer reconstruction outputs are missing.
Notes
- The laminar surface directory is assumed to be located at:
$SUBJECTS_DIR/<subj_id>/surf/laminar
The cortical layer spacing is defined linearly from white matter (0.0) to pial (1.0).
- compute_dipole_orientations(method, fixed=True)#
Compute vertex-wise dipole orientation vectors for all cortical layers.
This function estimates dipole orientations using one of several geometric methods applied to the laminar surface set. Depending on the method, orientations may be derived from vertex correspondence between pial and white surfaces or from local surface normals. Optionally, orientations can be fixed across layers, ensuring consistent directionality between homologous vertices.
- Parameters:
method ({'link_vector', 'ds_surf_norm', 'orig_surf_norm', 'cps'}) –
- Algorithm used to compute dipole orientations:
’link_vector’ - vectors connecting pial and white vertices.
’ds_surf_norm’ - surface normals computed from the downsampled surfaces.
’orig_surf_norm’ - normals from original (combined) surfaces, mapped to the downsampled meshes.
’cps’ - cortical patch statistics; averages of original-surface normals for vertices mapped to each downsampled vertex.
fixed (bool, optional) – If True (default), the orientation vectors from the pial surface are reused for all layers, ensuring layer-consistent directionality. If False, orientations are computed separately for each layer.
- Returns:
orientations – Array of shape (n_layers, n_vertices, 3) containing normalized dipole orientation vectors.
- Return type:
np.ndarray
- Raises:
ValueError – If the pial and white surfaces have mismatched vertex counts when using the ‘link_vector’ method.
Notes
All orientation vectors are normalized to unit length.
For ‘orig_surf_norm’ and ‘cps’, geometric mapping between stages is computed using nearest-neighbour search.
- create(ds_factor=0.1, orientation='link_vector', fix_orientation=True, n_jobs=-1, spm_instance=None, **scalp_kwargs)#
Postprocess and combine FreeSurfer cortical surface meshes for laminar analysis.
This function reconstructs a complete laminar surface hierarchy for a given FreeSurfer subject. It generates intermediate cortical layers between the pial and white matter surfaces, converts all surfaces to GIFTI format, aligns them to scanner RAS coordinates, removes deep-cut vertices, combines hemispheres, performs mesh decimation, and computes dipole orientation vectors. The resulting downsampled, orientation-annotated multilayer surfaces are stored in:
$SUBJECTS_DIR/<subj_id>/surf/laminar- Parameters:
ds_factor (float, optional) – Fraction of vertices to retain during mesh decimation (default: 0.1).
orientation ({'link_vector', 'ds_surf_norm', 'orig_surf_norm', 'cps'}, optional) –
- Method used to compute dipole orientations:
'link_vector': vectors connecting pial - white vertices.'ds_surf_norm': surface normals from downsampled meshes.'orig_surf_norm': surface normals from original combined meshes.'cps': cortical patch statistics (mean local normals).
Default is
'link_vector'.fix_orientation (bool, optional) – If True, enforces consistent orientation across layers by copying pial-layer normals to all other layers (default: True).
n_jobs (int, optional) – Number of parallel jobs used when generating intermediate surfaces (default: -1 for all cores).
spm_instance (spm_standalone, optional) – Active standalone SPM instance. If None, a temporary instance is created and closed after execution.
**scalp_kwargs (optional) –
Additional keyword arguments passed to
mne.bem.make_scalp_surfaces(). Commonly used options include: -threshold(int): Intensity threshold for scalp segmentation (default: 20). -mri(str): MRI volume to use (default: ‘T1.mgz’).Examples
To adjust scalp generation parameters: >>> surf_set.create(threshold=30, mri=’brain.mgz’)
To use default settings: >>> surf_set.create()
- Raises:
EnvironmentError – If required FreeSurfer binaries (
mris_convert,mris_inflate,mri_info) are not found in the system PATH.FileNotFoundError – If the subject directory or expected FreeSurfer files are missing.
ValueError – If validation fails due to vertex count mismatches across layers or hemispheres.
Notes
Requires that FreeSurfer’s
$SUBJECTS_DIRenvironment variable is set andrecon-allhas completed successfully forsubj_id.Surface metadata JSON files record coordinate transformations, removed vertices, downsampling ratios, and orientation method parameters.
Downsampling and orientation computation are applied identically across all layers to preserve laminar alignment.
In some cases,
mne.make_scalp_surfaces()may fail if the MRI lacks sufficient contrast between scalp and background (e.g., overly skull-stripped images). When this occurs, a warning is printed and execution continues without creating a scalp surface.To improve robustness, try: >>> surf_set.create(threshold=15, mri=’orig.mgz’)
- downsample(ds_factor, spm_instance=None)#
Downsample all combined cortical surface meshes
This function applies geometric mesh reduction to each combined surface (including all laminar layers and the inflated mesh) using Matlan’s reducepatch algorithm. The first surface in the sequence defines the downsampling vertex mapping, which is then applied to all other surfaces to ensure topological and vertex-wise correspondence across layers.
- Parameters:
ds_factor (float) – Fraction of vertices to retain during decimation (e.g., 0.1 retains 10% of vertices).
spm_instance (spm_standalone, optional) – Active standalone SPM instance. If None, a temporary instance is created and closed after execution.
Notes
The vertex mapping from the first (reference) surface is reused for all other layers to maintain laminar alignment.
Downsampling removes redundant vertices while preserving overall cortical geometry.
If vertex normals are present in the input GIFTI files, they are resampled and stored in the output surfaces.
- Metadata for each surface includes:
‘ds_factor’ - the applied decimation ratio.
‘ds_removed_vertices’ - indices of removed vertices in the original mesh.
Downsampled surfaces are saved under the ‘ds’ stage within the laminar directory.
See also
_iterative_downsample_single_surfacePerforms per-surface iterative decimation.
_fix_non_manifold_edgesRepairs topological defects introduced by downsampling.
_create_surf_giftiCreates a valid GIFTI surface from vertices and faces.
Examples
>>> surf_set = LayerSurfaceSet('sub-01', n_layers=11) >>> surf_set.downsample(0.1)
- get_bigbrain_layer_boundaries(subj_coord=None)#
Map BigBrain proportional layer boundaries into the subject’s downsampled surface space.
This function retrieves the laminar boundary proportions defined in the BigBrain histological atlas and projects them into the subject’s cortical geometry by mapping through fsaverage correspondence. It returns the proportional depth boundaries (0-1 range) of the six cortical layers for each vertex in the subject’s surface space.
- Parameters:
subj_coord (array-like or None, optional) – Optional array of vertex coordinates (n_vertices × 3) in the subject’s native space. If None, mapping is performed for all vertices of the subject’s pial surface.
- Returns:
layer_boundaries – Array of proportional cortical layer boundaries per vertex, shape (n_layers, n_vertices). If both hemispheres are processed, returns an array of shape (n_layers, n_total_vertices) with hemisphere stacking.
- Return type:
np.ndarray
Notes
Uses convert_native_to_fsaverage to identify corresponding fsaverage vertices for the subject.
Retrieves laminar proportion data from big_brain_proportional_layer_boundaries().
The returned values represent depth fractions (0 at white matter, 1 at pial surface) that can be used for aligning laminar CSD or source estimates across subjects.
- get_cortical_thickness(stage='ds', hemi=None)#
Compute vertex-wise cortical thickness from pial and white matter surfaces.
This method loads the pial and white matter meshes at the specified processing stage and hemisphere, then computes cortical thickness as the Euclidean distance between corresponding vertices on the two surfaces. Vertex correspondence is maintained across layers, allowing accurate per-vertex thickness estimation.
- Parameters:
stage (str, optional) – Surface processing stage to use (e.g., ‘converted’, ‘nodeep’, ‘combined’, ‘ds’). Default is ‘ds’.
hemi ({'lh', 'rh', None}, optional) – Hemisphere to process (‘lh’ or ‘rh’). If None, the combined surface is used (default: None).
- Returns:
thickness – Vertex-wise cortical thickness values (in millimeters).
- Return type:
numpy.ndarray, shape (n_vertices,)
Notes
Thickness is computed as the Euclidean distance between corresponding pial and white matter vertices.
Requires vertex correspondence between surfaces, as guaranteed by LayerSurfaceSet.
Can be used to assess local cortical geometry or normalize laminar profiles.
- get_distance_to_scalp(layer_name='pial', stage='ds', hemi=None)#
Compute the minimum Euclidean distance from each cortical vertex to the scalp surface.
This method loads the cortical surface (e.g., pial or white matter) and computes, for each vertex, the shortest distance to the nearest point on the scalp mesh. The scalp surface is expected to be stored as origscalp_2562.surf.gii in the subject’s MRI directory.
- Parameters:
layer_name (str, optional) – Cortical surface layer to use (e.g., ‘pial’, ‘white’, or fractional depth). Default is ‘pial’.
stage (str, optional) – Processing stage of the surface mesh (e.g., ‘converted’, ‘nodeep’, ‘combined’, ‘ds’). Default is ‘ds’.
hemi ({'lh', 'rh', None}, optional) – Hemisphere to process (‘lh’ or ‘rh’). If None, the combined surface is used (default: None).
- Returns:
distances – Euclidean distance (in millimeters) from each cortical vertex to the nearest scalp vertex.
- Return type:
numpy.ndarray, shape (n_vertices,)
Notes
The scalp surface is expected at: <SUBJECTS_DIR>/<subject>/mri/origscalp_2562.surf.gii.
Uses a KD-tree search for efficient nearest-neighbor computation.
Useful for evaluating cortical depth relative to scalp or for spatial normalization of MEG sensitivity profiles.
- get_interlayer_distance(vertex, orientation='link_vector', fixed=True)#
Compute Euclidean distances between corresponding vertices across cortical layers.
This function calculates the physical (3D) distances between adjacent layer surfaces for a given cortical column, providing an estimate of local cortical thickness and its distribution across layers.
- Parameters:
vertex (int) – Vertex index on the reference (superficial) layer for which interlayer distances are computed.
orientation ({'link_vector', 'normal_vector'}, optional) – Orientation model defining how dipole orientations are computed. Default is ‘link_vector’.
fixed (bool, optional) – Whether to use fixed dipole orientations across layers (default: True).
- Returns:
layer_dists – Euclidean distances (in millimeters) between consecutive layers along the specified cortical column.
- Return type:
ndarray of float, shape (n_layers - 1,)
Notes
Distances are computed from the downsampled (‘ds’) multilayer mesh.
The result reflects local layer spacing and may vary across cortical regions.
- get_layer_names()#
Return the list of cortical layer identifiers for this subject.
This function generates the ordered list of surface layer names corresponding to the proportional spacing defined in self.layer_spacing. The first and last layers are labeled as ‘pial’ and ‘white’, respectively, while intermediate layers are represented by fractional depth values between 0 and 1.
- Returns:
Ordered list of layer identifiers (e.g., [‘pial’, ‘0.900’, ‘0.800’, …, ‘white’]).
- Return type:
list of str
- get_layer_vertices(vertex, orientation='link_vector', fixed=True)#
Retrieve the vertex indices corresponding to a single cortical column across all layers.
This function maps a vertex index from the superficial (reference) layer to its corresponding vertices in deeper layers, ensuring layer-wise alignment according to the mesh organization defined by orientation and fixed parameters.
- Parameters:
vertex (int) – Vertex index on the reference (superficial) layer for which layer correspondences are desired.
orientation ({'link_vector', 'normal_vector'}, optional) – Orientation model defining how dipole orientations are computed. Default is ‘link_vector’.
fixed (bool, optional) – Whether to use fixed dipole orientations across layers (default: True).
- Returns:
layer_verts – Array of vertex indices corresponding to the same cortical column across all layers, ordered from superficial to deep.
- Return type:
ndarray of int, shape (n_layers,)
Notes
This function uses get_multilayer_vertex() to compute per-layer indices.
The mapping assumes consistent vertex ordering across layers within the LayerSurfaceSet.
- get_mesh_path(layer_name=None, stage='ds', hemi=None, orientation='link_vector', fixed=True)#
Return the full path to a single-layer or multilayer surface mesh file.
This function constructs the absolute path to a laminar surface file for a given layer, processing stage, hemisphere, and orientation configuration. If no layer name is provided, it returns the path to the combined multilayer surface.
- Parameters:
layer_name (str or None, optional) – Name of the cortical layer (e.g., ‘white’, ‘pial’, or an intermediate layer label such as ‘0.333’). If None, the function returns the path to the combined multilayer surface (e.g., ‘multilayer.<n_layers>’).
stage (str, optional) – Processing stage of the surface (e.g., ‘raw’, ‘converted’, ‘nodeep’, ‘combined’, ‘ds’). Default is ‘ds’.
hemi ({'lh', 'rh'}, optional) – Hemisphere identifier. Required for hemisphere-specific stages (‘raw’, ‘converted’, ‘nodeep’).
orientation (str, optional) – Orientation method (e.g., ‘link_vector’, ‘ds_surf_norm’, ‘orig_surf_norm’, ‘cps’). Used only for downsampled surfaces. Default is ‘link_vector’.
fixed (bool, optional) – Whether the surface uses fixed dipole orientations. If True, ‘fixed’ is appended to the filename. Default is True.
- Returns:
Absolute path to the requested surface mesh file.
- Return type:
str
- get_multilayer_vertex(layer, layer_vertex, orientation='link_vector', fixed=True)#
Compute the global vertex index within the concatenated multilayer surface mesh.
This function converts a vertex index belonging to a specific cortical layer into its corresponding global index in the multilayer surface representation, where vertices from all layers are stored contiguously.
- Parameters:
layer (int or str) – Layer identifier. If an integer, it is treated as a zero-based layer index. If a string, it must match one of the layer names in self.get_layer_names().
layer_vertex (int) – Vertex index within the specified layer.
orientation ({'link_vector', 'surface_normal'}, optional) – Dipole orientation model used to determine vertex ordering. Default is ‘link_vector’.
fixed (bool, optional) – Whether to use the fixed-orientation surface set. Default is True.
- Returns:
global_vertex – The global vertex index corresponding to the given layer and local vertex index.
- Return type:
int
Notes
Vertices across layers are assumed to be stored in sequential order (i.e., all vertices from layer 0 precede those from layer 1, etc.).
Useful for indexing vertex-wise quantities defined over the full multilayer mesh.
- get_radiality_to_scalp(layer_name='pial', orientation='link_vector', fixed=True)#
Compute the radiality of cortical dipole orientations relative to the scalp surface.
This function quantifies the degree to which each cortical orientation vector (e.g., dipole or column direction) is aligned with the local scalp normal. The result is a vertex-wise cosine similarity (absolute dot product) between dipole orientation and scalp normal vectors, indicating radial alignment.
- Parameters:
layer_name (str, optional) – Cortical surface layer to analyze (e.g., ‘pial’, ‘white’, or fractional depth). Default is ‘pial’.
orientation (str, optional) – Dipole orientation model used in the surface reconstruction (e.g., ‘link_vector’, ‘ds_surf_norm’, ‘orig_surf_norm’, ‘cps’). Default is ‘link_vector’.
fixed (bool, optional) – Whether fixed dipole orientations were used during inversion. Default is True.
- Returns:
radiality – Absolute cosine similarity between cortical dipole vectors and local scalp normals. Values range from 0 (tangential) to 1 (perfectly radial).
- Return type:
numpy.ndarray, shape (n_vertices,)
Notes
Higher values indicate more radial orientations (dipoles pointing toward the scalp).
Scalp geometry is loaded from <SUBJECTS_DIR>/<subject>/mri/origscalp_2562.surf.gii.
Surface normals are estimated per face and averaged across connected vertices.
Useful for assessing source sensitivity, forward-model biases, or validating laminar orientation models.
- get_vertices_per_layer(orientation='link_vector', fixed=True)#
Return the number of vertices per cortical layer in the downsampled multilayer mesh.
This method loads the multilayer surface (spanning all cortical depths) and computes how many vertices correspond to a single layer by dividing the total vertex count by the number of layers in the surface set.
- Parameters:
orientation (str, optional) – Dipole orientation model used in the laminar surface reconstruction (e.g., ‘link_vector’, ‘ds_surf_norm’, ‘orig_surf_norm’, ‘cps’). Default is ‘link_vector’.
fixed (bool, optional) – Whether fixed dipole orientations were used across layers. Default is True.
- Returns:
n_vertices – Number of vertices per cortical layer in the downsampled (stage=’ds’) mesh.
- Return type:
int
- interpolate_layer_data(layer_name, data, from_stage='ds', to_stage='combined', k_neighbors=5)#
Interpolate vertex-wise data from a downsampled layer mesh to the original high-resolution surface.
This function projects data values defined on a downsampled surface (e.g., ‘ds’ stage) onto the corresponding vertices of the full-resolution mesh (e.g., ‘combined’ stage). Interpolation is performed using a nearest-neighbour scheme with optional local averaging over connected vertices.
- Parameters:
layer_name (str) – Name of the cortical layer to interpolate (e.g., ‘pial’, ‘white’, ‘0.333’).
data (array-like, shape (n_vertices_ds,)) – Vertex-wise data associated with the downsampled mesh.
from_stage (str, optional) – Source mesh stage for interpolation (default: ‘ds’).
to_stage (str, optional) – Target mesh stage to which data are interpolated (default: ‘combined’).
k_neighbors (int, optional) – Number of nearest neighbours to use for smoothing interpolation (default: 5).
- Returns:
interpolated_data – Array of interpolated vertex values in the target mesh space.
- Return type:
np.ndarray
Notes
The interpolation preserves the laminar correspondence between meshes by using vertex adjacency and spatial proximity.
This function is typically used to project laminar or orientation data back to the original-resolution FreeSurfer space after downsampling.
Internally calls interpolate_data() to perform weighted vertex interpolation.
- load(layer_name=None, stage='raw', hemi=None, orientation=None, fixed=None)#
Load a GIFTI surface mesh for a specified cortical layer and processing stage.
This function retrieves and loads a surface file corresponding to a given layer, hemisphere, and processing stage. If layer_name is None, the multilayer combined surface (e.g., ‘multilayer.<n_layers>’) is loaded. Optionally, orientation and fixation metadata can be specified to load downsampled or orientation-specific variants. Combined surfaces (both hemispheres) are loaded when hemi is None.
- Parameters:
layer_name (str, optional) – Name of the cortical layer (e.g., ‘pial’, ‘white’, intermediate label such as ‘0.333’, or None to load the multilayer combined surface).
stage (str, optional) – Processing stage of the surface (e.g., ‘raw’, ‘converted’, ‘nodeep’, ‘combined’, ‘ds’). Default is ‘raw’.
hemi ({'lh', 'rh'}, optional) – Hemisphere identifier. If None, the function loads the combined surface file.
orientation ({'link_vector', 'ds_surf_norm', 'orig_surf_norm', 'cps'}, optional) – Orientation method used for dipole estimation (applies only to downsampled surfaces).
fixed (bool, optional) – Whether a fixed-orientation variant of the surface should be loaded.
- Returns:
The loaded GIFTI surface object.
- Return type:
nib.GiftiImage
- Raises:
FileNotFoundError – If the requested surface file does not exist.
- load_head_mesh(mesh_type='scalp')#
Load a head-related surface mesh (scalp, inner skull, or outer skull).
- Parameters:
mesh_type ({'scalp', 'iskull', 'oskull'}) – Type of head surface to load.
- Returns:
mesh – Loaded surface mesh in GIFTI format.
- Return type:
nib.GiftiImage
- Raises:
ValueError – If mesh_type is not one of ‘scalp’, ‘iskull’, or ‘oskull’.
FileNotFoundError – If the requested mesh is not found and prerequisite processing steps (e.g., scalp generation or SPM segmentation) have not been completed.
- load_meta(layer_name=None, stage='raw', hemi=None, orientation=None, fixed=None)#
Load metadata associated with a laminar surface file.
This function retrieves the JSON sidecar metadata corresponding to a surface mesh at a specified processing stage, hemisphere, and orientation configuration. If the metadata file does not exist, an empty dictionary is returned.
- Parameters:
layer_name (str, optional) – Name of the cortical layer (e.g., ‘pial’, ‘white’, or an intermediate layer label such as ‘0.333’). If None, the function attempts to load metadata for the multilayer combined surface.
stage (str, optional) – Processing stage of the surface (e.g., ‘raw’, ‘converted’, ‘nodeep’, ‘combined’, ‘ds’). Default is ‘raw’.
hemi ({'lh', 'rh'}, optional) – Hemisphere identifier. Required for hemisphere-specific stages (‘raw’, ‘converted’, ‘nodeep’). If None, loads metadata for the combined surface.
orientation (str, optional) – Orientation method (e.g., ‘link_vector’, ‘ds_surf_norm’, ‘orig_surf_norm’, ‘cps’). Used only for downsampled surfaces.
fixed (bool, optional) – Whether the surface uses fixed dipole orientations. If True, loads metadata from the corresponding ‘fixed’ file variant.
- Returns:
Dictionary containing the surface metadata. Returns an empty dictionary if no metadata file is found.
- Return type:
dict
- map_between_stages(layer_name, from_stage='ds', from_hemi=None, to_stage='converted', to_hemi=None)#
Map vertex indices between different surface processing stages.
This function computes vertex correspondences between surfaces at different stages of the laminar processing pipeline (e.g., ‘converted’, ‘nodeep’, ‘combined’, ‘ds’). It handles stage-specific transformations such as vertex removal, hemisphere concatenation/splitting, and geometric downsampling. The mapping is returned as an integer index array that maps vertices in the from_stage surface to their nearest counterparts in the to_stage surface.
- Parameters:
layer_name (str) – Name of the cortical layer (e.g., ‘pial’, ‘white’, or intermediate layer such as ‘0.333’).
from_stage (str, optional) – Source processing stage from which vertices are mapped (e.g., ‘converted’, ‘nodeep’, ‘combined’, ‘ds’). Default is ‘ds’.
from_hemi ({'lh', 'rh'}, optional) – Hemisphere for the source surface. Must be specified when mapping from per-hemisphere stages (‘converted’ or ‘nodeep’).
to_stage (str, optional) – Target processing stage to which vertices are mapped (e.g., ‘converted’, ‘nodeep’, ‘combined’, ‘ds’). Default is ‘converted’.
to_hemi ({'lh', 'rh'}, optional) – Hemisphere for the target surface. Must be specified when mapping to per-hemisphere stages (‘converted’ or ‘nodeep’).
- Returns:
idx – Integer array mapping vertex indices from from_stage to to_stage.
- Return type:
np.ndarray
- Raises:
ValueError – If invalid hemisphere combinations are specified or if mapping across hemispheres is attempted.
FileNotFoundError – If one of the required surface files does not exist.
Notes
- Stage-specific mappings are handled as follows:
‘converted’ -> ‘nodeep’ - applies vertex removal based on metadata.
‘nodeep’ -> ‘combined’ - concatenates hemispheres and offsets right-hemisphere indices.
‘combined’ -> ‘nodeep’ - splits the combined mesh into hemispheres.
‘combined’ -> ‘ds’ - maps vertices geometrically via nearest-neighbour search.
All other transitions fall back to geometric nearest-neighbour mapping.
- save(gifti_obj, layer_name=None, stage='raw', hemi=None, orientation=None, fixed=None, meta=None)#
Save a GIFTI surface mesh and its associated metadata.
This function saves a GIFTI surface object to the laminar surface directory using the standardized naming convention defined by the layer, stage, hemisphere, and orientation. A corresponding JSON sidecar file is also written, containing metadata and a timestamp of the last modification. If no metadata is provided, a minimal file with a modification timestamp is created.
- Parameters:
gifti_obj (nib.GiftiImage) – The GIFTI surface object to save.
layer_name (str, optional) – Name of the cortical layer (e.g., ‘pial’, ‘white’, ‘0.333’, or None for multilayer surfaces).
stage (str, optional) – Processing stage of the surface (e.g., ‘raw’, ‘converted’, ‘nodeep’, ‘combined’, ‘ds’). Default is ‘raw’.
hemi ({'lh', 'rh'}, optional) – Hemisphere identifier. If None, saves the combined surface.
orientation ({'link_vector', 'ds_surf_norm', 'orig_surf_norm', 'cps'}, optional) – Orientation method, if applicable (used for downsampled surfaces).
fixed (bool, optional) – Whether a fixed-orientation variant should be saved.
meta (dict, optional) – Optional metadata dictionary to be saved alongside the surface as a JSON file. If None, only a timestamp entry is written.
Notes
The GIFTI file is saved in the laminar surface directory for the subject.
Metadata is stored in a .json sidecar file with the same base name as the surface file.
The metadata file always includes a modified_at timestamp field.
- update_meta(layer_name=None, stage='raw', hemi=None, orientation=None, fixed=None, updates=None)#
Update or create the metadata JSON sidecar for a surface file.
This function loads the existing metadata for a given surface, applies updates from a provided dictionary, and writes the modified metadata back to disk. If the metadata file does not exist, it is created automatically. The modification timestamp is always updated.
- Parameters:
layer_name (str, optional) – Name of the cortical layer (e.g., ‘pial’, ‘white’, or intermediate layer label such as ‘0.333’). If None, the function targets the combined multilayer surface.
stage (str, optional) – Processing stage of the surface (e.g., ‘raw’, ‘converted’, ‘nodeep’, ‘combined’, ‘ds’). Default is ‘raw’.
hemi ({'lh', 'rh'}, optional) – Hemisphere identifier. Required for hemisphere-specific stages (‘raw’, ‘converted’, ‘nodeep’).
orientation (str, optional) – Orientation method (e.g., ‘link_vector’, ‘ds_surf_norm’, ‘orig_surf_norm’, ‘cps’). Used only for downsampled surfaces.
fixed (bool, optional) – Whether the surface uses fixed dipole orientations. If True, updates metadata for the corresponding ‘fixed’ file variant.
updates (dict, optional) – Dictionary of key-value pairs to add or modify in the metadata. If None, no update is performed.
Notes
A timestamp field (‘modified_at’) is automatically added or updated.
The directory structure for the metadata file is created if it does not exist.
- validate(required_stages=('raw', 'converted', 'nodeep', 'combined', 'ds'), hemis=('lh', 'rh'), orientations=None, fixed=None)#
Validate the completeness and internal consistency of surface files across layers, hemispheres, and stages.
This function checks that all expected surface files are present for the specified processing stages and verifies vertex count consistency across layers within each stage. For downsampled surfaces, optional validation of orientation and fixed-orientation variants is supported. The function raises descriptive errors for missing files or mismatched vertex counts, ensuring structural integrity of the laminar surface set before further processing.
- Parameters:
required_stages (sequence of str, optional) – List of processing stages to validate (e.g., ‘raw’, ‘converted’, ‘nodeep’, ‘combined’, ‘ds’). Default includes all standard stages.
hemis (sequence of {'lh', 'rh'}, optional) – Hemispheres to check for per-hemisphere stages (default: both).
orientations (sequence of str or None, optional) – Orientation methods to validate for the downsampled stage (e.g., [‘link_vector’]). Ignored for other stages.
fixed (bool or None, optional) – Whether to restrict validation to fixed-orientation variants. If None, both fixed and non-fixed variants are checked.
- Raises:
FileNotFoundError – If any expected surface files are missing from the directory structure.
ValueError – If vertex counts are inconsistent across layers within a hemisphere or combined mesh.
Notes
For ‘raw’, ‘converted’, and ‘nodeep’ stages, each hemisphere is validated separately.
For ‘combined’ surfaces, vertex counts are checked across layers for the merged hemispheres.
For ‘ds’ (downsampled) surfaces, each orientation and fixedness combination is validated independently.
This validation step is typically run at the end of create to ensure consistency before dipole orientation computation or laminar combination.
- lameg.surf.convert_fsaverage_to_native(surf_set, layer_name, hemi, vert_idx=None)#
Map vertex indices from fsaverage spherical registration space to a subject’s native, downsampled surface space.
This function maps vertices defined on the fsaverage template to their corresponding locations on an individual subject’s cortical surface. It first identifies the subject’s corresponding vertex in spherical registration space (?h.sphere.reg) via nearest-neighbour search, then maps those vertices to the subject’s downsampled surface for use in laminar or source-space analyses.
- Parameters:
surf_set (LayerSurfaceSet) – Subject’s surface set instance containing paths and metadata for all cortical layers.
layer_name (str) – Name of the surface layer to use for mapping (e.g., ‘pial’, ‘white’, or a fractional layer).
hemi ({'lh', 'rh'}) – Hemisphere to convert.
vert_idx (int | array-like of int | None, optional) – Vertex index or array of vertex indices on the fsaverage surface. If None, all fsaverage vertices are mapped.
- Returns:
subj_v_idx – Corresponding vertex index (or array of indices) on the subject’s downsampled surface.
- Return type:
int or np.ndarray
Notes
- The mapping is performed in two stages:
Spherical registration mapping: fsaverage vertices are mapped to the subject’s ?h.sphere.reg using nearest-neighbour search in spherical space.
Downsampling alignment: the subject’s full-resolution surface vertices are mapped onto the downsampled mesh via spatial proximity.
Assumes that the downsampled surface is a vertex subset of the full-resolution mesh.
This provides a lightweight geometric approximation to FreeSurfer’s surface morph, suitable for vertex-level correspondence in laminar analyses.
Examples
>>> subj_v_idx = convert_fsaverage_to_native(surf_set, 'pial', 'lh', vert_idx=[100, 200, 300]) >>> subj_v_idx.shape (3,)
- lameg.surf.convert_native_to_fsaverage(surf_set, layer_name, subj_coord=None)#
Map coordinates from a subject’s native surface space to fsaverage spherical registration space.
This function maps vertices or coordinates defined in a subject’s native surface (typically downsampled pial or white matter surfaces) to their corresponding vertices on the fsaverage template. It uses the spherical registration surfaces (?h.sphere.reg) to establish vertex- level correspondence via nearest-neighbour matching in spherical space.
- Parameters:
surf_set (LayerSurfaceSet) – Subject’’s surface set instance containing paths and metadata for cortical layers.
layer_name (str) – Surface layer to use for mapping (e.g., ‘pial’, ‘white’, or a fractional layer).
subj_coord (array-like of shape (3,) or (N, 3), optional) – Vertex coordinate(s) in the subject’s downsampled surface space. If None, all downsampled vertices are mapped.
- Returns:
hemis (str or list of str) – Hemisphere label(s) for each vertex (‘lh’ or ‘rh’).
fsave_v_idx (int or list of int) – Corresponding vertex index (or list of indices) on the fsaverage spherical surface.
Notes
- The mapping proceeds in three stages:
Downsampled -> full-resolution mapping: Each downsampled vertex is matched to the nearest vertex in the subject’s full-resolution left and right hemisphere meshes.
Hemisphere assignment: Vertices are assigned to the hemisphere with the smallest Euclidean distance.
Spherical registration mapping: The corresponding vertex on the subject’s ?h.sphere.reg surface is matched to fsaverage using nearest-neighbour search in spherical space.
This procedure approximates FreeSurfer’s spherical morph alignment geometrically and is suitable for mapping subject-specific data into fsaverage space for group-level laminar or source-space analyses.
Examples
>>> hemis, fsave_idx = convert_native_to_fsaverage(surf_set, 'pial') >>> len(fsave_idx) 81924 >>> hemis[0], fsave_idx[0] ('lh', 10234)
- lameg.surf.interpolate_data(original_mesh, downsampled_mesh, downsampled_data, adjacency_matrix=None, k_neighbors=5)#
Interpolate vertex-wise data from a downsampled mesh back to the original high-resolution mesh.
This function reconstructs vertex data on the full-resolution surface by weighted averaging of the k nearest downsampled vertices in Euclidean space. It then performs a refinement pass for vertices that were part of the downsampled mesh, averaging their values with adjacent vertices to enforce local smoothness.
- Parameters:
original_mesh (nibabel.gifti.GiftiImage) – Original high-resolution cortical mesh (GIFTI format).
downsampled_mesh (nibabel.gifti.GiftiImage) – Downsampled version of the mesh corresponding to the provided data.
downsampled_data (np.ndarray) – Vertex-wise data array from the downsampled mesh.
adjacency_matrix (scipy.sparse matrix, optional) – Vertex adjacency matrix for the original mesh. If None, it is computed internally.
k_neighbors (int, optional) – Number of nearest downsampled vertices used for interpolation (default: 5).
- Returns:
vertex_data – Interpolated vertex-wise data for the original high-resolution mesh.
- Return type:
np.ndarray
Notes
The first interpolation pass uses inverse-distance weighting based on k-nearest neighbors in Euclidean space between meshes.
The second pass refines vertices present in the downsampled mesh using weighted neighborhood averaging based on surface adjacency.
This method preserves spatial smoothness while minimizing interpolation bias near downsampled vertices.
Examples
>>> vertex_data = interpolate_data(orig_gii, ds_gii, ds_data, k_neighbors=5) >>> vertex_data.shape (163842,)
lameg.util module#
Utility functions for SPM, MEG sensor data management, and neuroanatomical processing.
This module provides a suite of high-level tools to interface with SPM (Statistical Parametric Mapping), MNE-Python, and FreeSurfer environments. It facilitates batch execution, data format conversion, sensor-level data handling, and laminar or anatomical computations relevant to MEG/EEG analysis pipelines. Many functions integrate seamlessly with standalone SPM sessions and FreeSurfer-derived cortical surfaces.
Core functionalities#
SPM interfacing and batch execution - Context-managed lifecycle for standalone SPM instances (spm_context). - Automated batch execution of MATLAB-based neuroimaging workflows (batch). - Conversion of CTF MEG data from MNE .fif to SPM .mat format (ctf_fif_spm_conversion).
File and directory utilities - Structured recursive file and directory retrieval (get_files, get_directories). - Directory creation with automatic parent handling (make_directory). - Flexible substring matching (check_many).
Statistical and numerical utilities - Corrected paired-sample t-tests with NaN handling (ttest_rel_corrected). - Conversion of absolute layer thicknesses to proportional coordinates (calc_prop).
Anatomical and laminar processing - Derivation of normalized laminar boundaries from the fsaverage BigBrain atlas
(big_brain_proportional_layer_boundaries).
Coregistration and fiducial handling - Extraction of subject-specific fiducial coordinates from TSV metadata files
(get_fiducial_coords).
Coregistration of 3D facial scans to FreeSurfer MRI via fiducial and ICP alignment (coregister_3d_scan_mri).
Notes
The module assumes correctly configured environments for SPM standalone, MNE-Python, and FreeSurfer.
Designed for reproducible neuroimaging workflows combining MATLAB-based and Python-based tools.
File operations are implemented with explicit error handling for compatibility across platforms.
The laminar utilities rely on fsaverage-space anatomical templates distributed with laMEG.
- lameg.util.batch(cfg, viz=True, spm_instance=None) None#
Execute an SPM batch job within a managed standalone MATLAB session.
This function runs an arbitrary SPM batch configuration (matlabbatch) by writing it to a temporary MATLAB file and executing it within an SPM standalone environment. It supports both interactive (visual) and non-interactive (headless) execution, automatically handling session setup and cleanup.
- Parameters:
cfg (dict) – Dictionary defining the SPM batch configuration, following the standard matlabbatch format (e.g., as used in spm_jobman).
viz (bool, optional) – Whether to display the SPM GUI during execution (True) or run in command-line mode (False). Default is True.
spm_instance (spm_standalone, optional) – Active standalone SPM instance. If None, a temporary instance is created and closed after execution.
Notes
The function automatically wraps cfg into a valid matlabbatch structure and saves it to a temporary .mat file before execution.
Temporary files are created using the system’s default temp directory and deleted after the job completes.
Runs all standard SPM batch modules, including EEG/MEG preprocessing, coregistration, inversion, and statistical analyses.
When viz=False, spm_get_defaults(‘cmdline’, 1) is used to suppress GUI output, making the function suitable for automated pipelines and HPC execution.
- lameg.util.big_brain_proportional_layer_boundaries(overwrite=False)#
Retrieve proportional cortical layer boundary coordinates from the fsaverage-converted BigBrain atlas included in laMEG.
This function computes normalized laminar depth coordinates (ranging from 0 to 1) for each cortical vertex using the fsaverage-mapped BigBrain histological atlas. The proportional layer boundaries (layers 1-6) are derived from absolute thickness values and cached as a NumPy dictionary to improve subsequent loading speed.
- Parameters:
overwrite (bool, optional) – If True, recomputes proportional boundaries and overwrites the existing cached file. Default is False.
- Returns:
bb_data – Dictionary containing normalized layer boundaries for each hemisphere: - “lh”: left hemisphere vertex-wise boundary array (shape: 6 × n_vertices) - “rh”: right hemisphere vertex-wise boundary array (shape: 6 × n_vertices)
- Return type:
dict
Notes
The proportional boundaries represent cumulative thickness proportions from layer 1 (pial) to layer 6 (white matter).
Cached results are stored as proportional_layer_boundaries.npy in the module’s assets directory.
Uses calc_prop() internally to normalize absolute thickness values per vertex.
This dataset provides a standard laminar coordinate reference compatible with fsaverage- registered MEG/EEG source models.
- lameg.util.calc_prop(vec)#
Compute cumulative proportional values from a vector while preserving zero-sum cases.
This function converts an array of independent thickness or weight values into cumulative proportions that sum to one. If the total sum of the input is zero, the function returns the original vector unchanged to avoid division by zero.
- Parameters:
vec (array_like) – Input array of non-negative values (e.g., layer thicknesses or weights).
- Returns:
vec – Cumulative proportion vector, normalized by the total sum. If the input sum is zero, returns the original vector unchanged.
- Return type:
np.ndarray
Notes
The result ranges from 0 to 1, representing the normalized cumulative distribution.
Useful for converting laminar thickness values into depth proportion coordinates.
- lameg.util.check_freesurfer_setup()#
Verify that essential FreeSurfer command-line tools are available in the environment.
This function checks whether the required FreeSurfer binaries (mris_convert and mri_info) can be found in the system’s PATH. If one or more binaries are missing, it raises an EnvironmentError with detailed setup instructions for sourcing the FreeSurfer environment.
- Raises:
EnvironmentError – If one or more required FreeSurfer binaries are not found in the system PATH.
Notes
- This check ensures that FreeSurfer has been properly installed and initialized via:
export FREESURFER_HOME=/path/to/freesurfer source $FREESURFER_HOME/SetUpFreeSurfer.sh
Typically called before surface conversion or reconstruction routines that depend on FreeSurfer utilities.
- lameg.util.check_many(multiple, target, func=None)#
Evaluate whether multiple substrings occur within a target string.
This utility checks whether all or any of a list of substrings are present in a given target string. It is designed for use in conditional logic (e.g., list comprehensions or filtering routines) where flexible substring matching is required.
- Parameters:
multiple (list of str) – Substrings to search for within the target string.
target (str) – String in which to search for the specified substrings.
func ({'all', 'any'}) – Search mode: ‘all’ returns True only if all substrings are found, ‘any’ returns True if at least one substring is found.
- Returns:
True if the condition specified by func is satisfied; False otherwise.
- Return type:
bool
- Raises:
ValueError – If func is not ‘all’ or ‘any’.
Notes
Useful for concise logical checks in comprehensions or filters.
Matching is case-sensitive and does not support regular expressions.
- lameg.util.coregister_3d_scan_mri(subject_id, lpa, rpa, nas, dig_face_fname, dig_units='mm', out_dir=None)#
Coregister a 3D facial surface scan to a FreeSurfer MRI using fiducial- and ICP-based alignment.
This function aligns a subject’s 3D facial mesh (e.g., STL scan) to their FreeSurfer MRI space. It first performs a fiducial-based rigid alignment using the NAS, LPA, and RPA landmarks, then refines the fit using iterative closest point (ICP) optimization on dense head-surface points. The resulting transformation is applied to the fiducials, returning their coordinates in FreeSurfer MRI voxel space (scanner RAS + CRAS offset).
- Parameters:
subject_id (str) – Name of the FreeSurfer subject (must exist in $SUBJECTS_DIR).
lpa (array_like, shape (3,)) – Left preauricular fiducial in millimeters (3D scan coordinate frame).
rpa (array_like, shape (3,)) – Right preauricular fiducial in millimeters (3D scan coordinate frame).
nas (array_like, shape (3,)) – Nasion fiducial in millimeters (3D scan coordinate frame).
dig_face_fname (str or pathlib.Path) – Path to the subject’s 3D facial mesh (e.g., .stl) containing head-surface points.
dig_units ({'m', 'mm'}, optional) – Units of the 3D facial scan coordinates. Default is ‘mm’.
out_dir (str or None, optional) – Directory where visualization screenshots of the alignment stages will be saved. If None, no figures are written.
- Returns:
lpa_t (np.ndarray, shape (3,)) – Transformed LPA coordinate in FreeSurfer MRI voxel space (mm).
rpa_t (np.ndarray, shape (3,)) – Transformed RPA coordinate in FreeSurfer MRI voxel space (mm).
nas_t (np.ndarray, shape (3,)) – Transformed NAS coordinate in FreeSurfer MRI voxel space (mm).
Notes
Requires FreeSurfer to be installed and $SUBJECTS_DIR to be set.
Uses MNE-Python’s Coregistration and plot_alignment utilities for alignment and visualization.
Fiducial alignment is refined using ICP on dense surface points but excludes fiducial weighting during ICP iterations.
The returned coordinates are in scanner RAS + CRAS space (voxel-aligned), not FreeSurfer surface RAS.
If out_dir is provided, three screenshots are saved: coreg-initial.png, coreg-fit_fiducials.png, and coreg-fit_icp.png.
This workflow is useful for aligning 3D optical scans or digitized head shapes to MRI space prior to MEG/EEG forward modeling.
- lameg.util.ctf_fif_spm_conversion(mne_file, res4_file, output_path, epoched, prefix='spm_', spm_instance=None)#
Convert MEG data from CTF .fif format to SPM-compatible .mat format.
This function converts raw or epoched MEG data acquired from a CTF scanner (in .fif format) into SPM’s M/EEG format using the standalone SPM interface. It requires the corresponding CTF .res4 file for sensor geometry and saves the converted dataset to the specified output directory with a customizable prefix.
- Parameters:
mne_file (str or pathlib.Path) – Path to the MNE .fif file containing MEG data (either *-raw.fif or *-epo.fif).
res4_file (str or pathlib.Path) – Path to the CTF .res4 file containing sensor position and geometry information.
output_path (str or pathlib.Path) – Destination directory for the converted SPM dataset.
epoched (bool) – Whether the input data are epoched (True) or continuous (False).
prefix (str, optional) – Prefix to prepend to the converted dataset filename (default: “spm_”).
spm_instance (spm_standalone, optional) – Active standalone SPM instance. If None, a temporary instance is created and closed after execution.
Notes
If spm_instance is not provided, a new standalone SPM session is automatically launched and terminated after completion.
The resulting .mat file is compatible with all SPM EEG/MEG preprocessing, inversion, and model comparison pipelines.
Both paths (mne_file and res4_file) must be valid and refer to files from the same acquisition session.
- lameg.util.get_directories(target_path, strings='', check='all', depth='all')#
Retrieve directories within a path that contain specified substrings in their names.
This function searches a target directory (optionally recursively) for subdirectories whose names match one or more specified substrings. It supports both shallow and recursive search modes and flexible matching logic (“all” or “any”) for substring inclusion.
- Parameters:
target_path (str or pathlib.Path) – Root directory in which to search for subdirectories.
strings (list of str, optional) – Substrings to be matched within each directory path or name. Default is an empty string.
check ({'all', 'any'}, optional) – Search mode: ‘all’ requires all substrings in strings to be present; ‘any’ requires at least one. Default is ‘all’.
depth ({'all', 'one'}, optional) – Search depth: ‘all’ performs a recursive search through subdirectories, ‘one’ limits the search to the top-level directory. Default is ‘all’.
- Returns:
subdirs – Sorted list of paths to directories matching the specified criteria.
- Return type:
list of pathlib.Path
Notes
Matching is case-sensitive and performed using check_many().
The returned list is sorted lexicographically by directory path.
Useful for structured directory traversal and dataset organization tasks.
- lameg.util.get_fiducial_coords(subj_id, fname, col_delimiter='\t', subject_column='subj_id', nas_column='nas', lpa_column='lpa', rpa_column='rpa', val_delimiter=',')#
Retrieve fiducial landmark coordinates (NAS, LPA, RPA) for a specified subject from a TSV file.
This function reads a tab- or comma-delimited text file containing subject-specific fiducial landmarks and returns the NASion (NAS), Left Preauricular (LPA), and Right Preauricular (RPA) coordinates for the requested subject. Each coordinate entry should contain three comma-separated values representing the x, y, and z positions (in millimeters, unless otherwise specified).
- Parameters:
subj_id (str) – Subject identifier used to locate the corresponding row in the file.
fname (str or pathlib.Path) – Path to the TSV file containing fiducial coordinates.
col_delimiter (str, optional) – Character delimiting columns in the file (default: ‘t’).
subject_column (str, optional) – Column name containing subject identifiers (default: ‘subj_id’).
nas_column (str, optional) – Column name for NASion coordinates (default: ‘nas’).
lpa_column (str, optional) – Column name for Left Preauricular coordinates (default: ‘lpa’).
rpa_column (str, optional) – Column name for Right Preauricular coordinates (default: ‘rpa’).
val_delimiter (str, optional) – Character delimiting coordinate values within each cell (default: ‘,’).
- Returns:
fid_coords – Dictionary containing fiducial coordinates:
{'nas': [x, y, z], 'lpa': [x, y, z], 'rpa': [x, y, z]}. ReturnsNoneif the subject is not found in the file.- Return type:
dict or None
- Raises:
ValueError – If a matching subject is found but one or more fiducial columns are missing or malformed.
Notes
The file must contain a header row with named columns.
Coordinates are typically in head or MRI space, depending on acquisition convention.
Commonly used to initialize coregistration in MEG/EEG preprocessing pipelines (e.g., for SPM, MNE, or hpMEG analyses).
- lameg.util.get_files(target_path, suffix, strings='', prefix=None, check='all', depth='all')#
Retrieve files from a directory matching specified criteria (suffix, prefix, and substrings).
This function searches a target directory (optionally recursively) for files with a given extension and filters them by filename content and prefix. It supports flexible substring matching via “all” or “any” logic, making it suitable for controlled file selection in large datasets.
- Parameters:
target_path (str or pathlib.Path) – Root directory in which to search for files.
suffix (str) – File extension to match, in the form ‘.ext’ (e.g., ‘.mat’ or ‘*.fif’).
strings (list of str, optional) – Substrings to be matched within each filename. Default is an empty string.
prefix (str, optional) – Restrict results to filenames beginning with this prefix. Default is None.
check ({'all', 'any'}, optional) – Search mode: ‘all’ requires all substrings in strings to be present; ‘any’ requires at least one. Default is ‘all’.
depth ({'all', 'one'}, optional) – Search depth: ‘all’ performs a recursive search through subdirectories, ‘one’ limits the search to the top-level directory. Default is ‘all’.
- Returns:
files – Sorted list of paths to files matching the specified criteria.
- Return type:
list of pathlib.Path
Notes
Matching is case-sensitive and exact (no regular expressions).
The function internally uses check_many() for substring evaluation.
Useful for structured data pipelines where file inclusion depends on both naming and hierarchical constraints.
- lameg.util.load_meg_sensor_data(data_fname)#
Load MEG sensor-level data and metadata from an SPM M/EEG dataset.
This function extracts MEG channel data, timestamps, and channel labels from an SPM-format dataset, supporting both HDF5-based (v7.3+) and older MATLAB .mat file structures. It filters out non-MEG and bad channels, reconstructs the binary data matrix, and returns it in sensor × time × trial format (if applicable).
- Parameters:
data_fname (str) – Path to the SPM M/EEG .mat file containing metadata and reference to the binary data file.
- Returns:
sensor_data (np.ndarray) – MEG sensor data (channels × time [× trials]) extracted from the referenced binary file.
time (np.ndarray) – Time vector in milliseconds.
ch_names (list of str) – Names of the valid MEG channels included in the output.
- Raises:
FileNotFoundError – If the binary data file specified in the .mat structure cannot be found.
OSError – If the .mat file cannot be opened as an HDF5 dataset.
KeyError – If required fields are missing from the file.
Notes
Supports both MATLAB v7.3 (HDF5) and earlier formats.
Only MEG channels marked as ‘good’ (not bad) are retained.
Binary data are read directly from the file specified in D.data.fname using Fortran-order reshaping to match SPM’s internal data layout.
The returned time vector is derived from timeOnset, Fsample, and Nsamples fields within the dataset.
Non-MEG modalities (e.g., EEG, EOG, EMG) are excluded automatically.
- lameg.util.make_directory(root_path, extended_dir)#
Create a directory (and all necessary parent directories) within a specified root path.
This function ensures that the full directory path exists, creating intermediate directories as needed. It supports both single directory names and nested paths provided as lists.
- Parameters:
root_path (str or pathlib.Path) – The root directory in which to create the new directory or directories.
extended_dir (str or list of str) – Subdirectory (or sequence of nested subdirectories) to be created within root_path.
- Returns:
root_path – Path object representing the created directory.
- Return type:
pathlib.Path
Notes
Existing directories are preserved (exist_ok=True).
Intermediate directories are automatically created (parents=True).
Useful for ensuring consistent directory structure in data processing pipelines.
- lameg.util.spm_context(spm=None, n_jobs=4)#
Context manager for safe initialization and termination of standalone SPM sessions.
This utility ensures proper lifecycle management of SPM standalone instances when executing MATLAB-based analyses (e.g., source reconstruction or simulation). It supports both user-supplied SPM sessions and automatic instantiation of temporary ones with optional parallelization.
- Parameters:
spm (spm_standalone, optional) – Existing SPM standalone instance. If None, a new instance is launched and automatically terminated upon context exit (default: None).
n_jobs (int, optional) – Number of MATLAB parallel workers to initialize via parpool. Default is 4.
- Yields:
spm (spm_standalone) – Active standalone SPM instance usable within the context.
Notes
Designed for use within a with block to ensure safe cleanup of MATLAB processes.
If spm is None, a new standalone SPM session is created with a parallel pool of size n_jobs, and both are terminated automatically upon exit.
If an existing spm instance is provided, it is reused and not terminated at the end of the context.
The default setting (n_jobs=4) is suitable for standard workstations; higher values may be beneficial on high-performance computing (HPC) systems.
Ensures robustness against MATLAB errors when initializing or closing parpool.
- lameg.util.ttest_rel_corrected(data, correction=0, tail=0, axis=0)#
Perform a corrected paired-sample t-test with NaN handling and variance stabilization.
This function computes a t-statistic, degrees of freedom, and p-value for paired data while accounting for potential missing values (NaNs) and small-sample variance instabilities. A correction term is applied to the variance to prevent division by zero or underflow when the variance is near zero.
- Parameters:
data (array_like) – Input data array (typically representing paired differences), where the t-test is computed along the specified axis. NaN values are ignored in statistical computations.
correction (float, optional) – Variance correction term. If 0 (default), an adaptive correction of 0.01 * max(variance) is applied automatically.
tail ({0, 1, -1}, optional) – Specifies the type of test: - 0: two-tailed test (default) - 1: right-tailed test - -1: left-tailed test
axis (int, optional) – Axis along which the t-test is performed. Default is 0.
- Returns:
tval (float or ndarray) – Computed t-statistic(s).
deg_of_freedom (int or ndarray) – Degrees of freedom associated with each test.
p_val (float or ndarray) – Corresponding p-value(s).
Notes
Missing values (NaNs) are excluded from mean and variance computations.
The standard error includes the correction term to ensure numerical stability.
For two-tailed tests, p = 2 * t.sf(|tval|, df); for one-tailed, p = t.sf(-tval, df) or p = t.cdf(tval, df) depending on direction.
This test is useful for robust paired-sample comparisons when small variance or missing data may otherwise bias standard t-test results.
lameg.viz module#
Visualization and color mapping utilities for laminar and cortical surface data.
This module provides a set of functions for visualizing laminar MEG and cortical data, including color mapping utilities, 3D surface rendering, and Current Source Density (CSD) plotting. It integrates seamlessly with FreeSurfer surfaces, laMEG outputs, and matplotlib-based plotting pipelines.
Main Features#
Color Mapping: - Convert numerical data into RGB, RGBA, or hexadecimal color representations. - Support for diverging, linear, and logarithmic normalization schemes. - Utilities for encoding RGB triplets as 32-bit integers for compact graphical representation.
Surface Visualization: - Render 3D cortical surfaces using the k3d engine. - Overlay vertex-wise statistical maps, curvature-based shading, and anatomical markers. - Interactive camera controls and scene export support.
Laminar Data Visualization: - Visualization of Current Source Density (CSD) profiles across cortical layers. - Optional display of laminar boundaries and custom color scaling.
Functions#
- data_to_rgb(data, n_bins, cmap, vmin, vmax, vcenter=0.0, ret_map=False, norm=’TS’)
Map numerical data to RGBA colors using matplotlib colormaps with specified normalization.
- rgbtoint(rgb)
Convert an RGB color triplet to a 32-bit integer color code.
- color_map(data, cmap, vmin, vmax, n_bins=1000, vcenter=0, norm=’TS’)
Map numerical data to hexadecimal color codes suitable for visualization.
- show_surface(surf_set, layer_name=’inflated’, stage=’combined’, …)
Render a cortical or laminar surface with optional curvature, color, and marker overlays.
- plot_csd(csd, times, axis, colorbar=True, cmap=’RdBu_r’, …)
Plot a 2D laminar Current Source Density (CSD) profile over time.
Notes
All functions are designed to integrate with laMEG’s surface and layer representations.
Surface visualization relies on k3d for GPU-accelerated rendering.
The module assumes FreeSurfer-compatible surface files and curvature data.
- lameg.viz.color_map(data, cmap, vmin, vmax, n_bins=1000, vcenter=0, norm='TS')#
Map numerical data to hexadecimal color codes using a specified matplotlib colormap.
This function normalizes numerical data using a chosen normalization scheme, maps values to RGB colors via a matplotlib colormap, and converts them to hexadecimal format suitable for visualization (e.g., in surface plots or colorbar annotations).
- Parameters:
data (array_like, shape (n,)) – One-dimensional array of numerical values to be color-mapped.
cmap (str) – Name of the matplotlib colormap (e.g., ‘viridis’, ‘RdBu_r’).
vmin (float) – Minimum data value for normalization.
vmax (float) – Maximum data value for normalization.
n_bins (int, optional) – Number of histogram bins used to discretize the data range. Default is 1000.
vcenter (float, optional) – Center value for diverging normalization (norm=’TS’). Default is 0.
norm ({'TS', 'N', 'LOG'}, optional) – Type of normalization: - ‘TS’: Two-slope (diverging) normalization. - ‘N’: Linear normalization. - ‘LOG’: Logarithmic normalization. Default is ‘TS’.
- Returns:
map_colors (ndarray, shape (n,)) – Array of hexadecimal color codes corresponding to the input data values.
cmap (matplotlib.colors.Colormap) – The matplotlib colormap object used for mapping.
Notes
Internally uses data_to_rgb() to compute RGBA values, which are then scaled and converted to hexadecimal color codes.
The ‘TS’ normalization is suited for data centered around a neutral reference (e.g., zero).
Useful for generating vertex-wise color encodings or colorbars consistent with matplotlib colormaps.
- lameg.viz.data_to_rgb(data, n_bins, cmap, vmin, vmax, vcenter=0.0, ret_map=False, norm='TS')#
Map numerical data values to RGB colors using a specified matplotlib colormap.
This function normalizes input data according to a chosen scaling mode (two-slope, linear, or logarithmic), bins the data into a specified number of intervals, and maps each bin to an RGB color value. It optionally returns the colormap object for use in associated plots (e.g., colorbars).
- Parameters:
data (array_like, shape (n,)) – One-dimensional array of numerical values to be color-mapped.
n_bins (int) – Number of histogram bins used to discretize the data range.
cmap (str) – Name of the matplotlib colormap (e.g., ‘viridis’, ‘RdBu_r’).
vmin (float) – Minimum data value for normalization.
vmax (float) – Maximum data value for normalization.
vcenter (float, optional) – Center value for the colormap when using two-slope normalization (norm=”TS”). Default is 0.0.
ret_map (bool, optional) – If True, return the matplotlib ScalarMappable object along with the mapped RGB values. Default is False.
norm ({'TS', 'N', 'LOG'}, optional) – Normalization type: - ‘TS’: Two-slope normalization (diverging colormap, zero-centered) - ‘N’: Linear normalization - ‘LOG’: Logarithmic normalization Default is ‘TS’.
- Returns:
color_mapped (ndarray, shape (n, 4)) – Array of RGBA color values corresponding to each input datum.
scalar_map (matplotlib.cm.ScalarMappable, optional) – The colormap object used for mapping (returned only if ret_map=True).
- Raises:
ValueError – If norm is not one of ‘TS’, ‘N’, or ‘LOG’.
Notes
The function assigns each data point the color of its corresponding histogram bin.
The ‘TS’ normalization is best suited for data centered around a neutral reference value (e.g., 0), producing balanced diverging colormaps.
The returned colors can be directly used for visualizing scalar data distributions or as vertex colors in surface plots.
- lameg.viz.plot_csd(csd, times, axis, colorbar=True, cmap='RdBu_r', vmin_vmax=None, n_layers=11, layer_boundaries=None)#
Visualize a laminar Current Source Density (CSD) profile over time.
This function plots a 2D representation of CSD data (layers × time) using a diverging colormap to indicate current sources and sinks. It supports automatic or user-defined color scaling, customizable colormaps, and optional display of laminar boundaries.
- Parameters:
csd (np.ndarray, shape (n_layers, n_times)) – CSD matrix to plot, where each row corresponds to a cortical layer and each column to a time point.
times (np.ndarray, shape (n_times,)) – Time vector corresponding to the CSD data columns (in ms).
axis (matplotlib.axes.Axes) – Matplotlib axes on which to draw the CSD plot.
colorbar (bool, optional) – If True, adds a colorbar indicating CSD amplitude (source/sink polarity). Default is True.
cmap (str, optional) – Colormap name (e.g., ‘RdBu_r’, ‘viridis’). Default is ‘RdBu_r’.
vmin_vmax (tuple of float or {'norm', None}, optional) – Color normalization limits: - (vmin, vmax): explicit color scale limits, - ‘norm’: symmetric normalization based on maximum absolute CSD value, - None: uses full data range. Default is None.
n_layers (int, optional) – Number of cortical layers represented in the CSD matrix. Default is 11.
layer_boundaries (array_like, optional) – Optional array of y-axis positions marking laminar boundaries. Default is None.
- Returns:
im (matplotlib.image.AxesImage) – The plotted image object.
cb (matplotlib.colorbar.Colorbar or None) – The colorbar object, if colorbar=True, otherwise None.
Notes
Assumes CSD is in units of current per unit area (e.g., uA/mm²).
Negative values (blue) typically represent current sinks; positive values (red) represent sources.
If layer_boundaries is provided, horizontal lines are drawn at those positions.
Suitable for visualizing laminar profiles from simulations, hpMEG reconstructions, or LFP-derived CSD estimates.
- lameg.viz.rgbtoint(rgb)#
Convert an RGB triplet to a 32-bit integer color representation.
This function encodes red, green, and blue components (0-255) into a single 32-bit integer, enabling compact storage or low-level graphical interfacing. The resulting integer can be decoded back into RGB components via bitwise operations.
- Parameters:
rgb (array_like of int, shape (3,)) – RGB color triplet with values in the range [0, 255].
- Returns:
color – 32-bit integer encoding of the input RGB color.
- Return type:
int
- Raises:
AssertionError – If any RGB component is outside the valid range [0, 255].
Notes
Values are packed in big-endian order: R << 16 | G << 8 | B.
Useful for transferring color information to graphics libraries that use integer encoding.
- lameg.viz.show_surface(surf_set, layer_name='inflated', stage='ds', hemi=None, orientation=None, fixed=None, color=None, grid=False, menu=False, vertex_colors=None, info=False, camera_view=None, height=512, opacity=1.0, marker_coords=None, marker_vertices=None, marker_size=1, marker_color=None, plot_curvature=True)#
Render a 3D cortical surface with optional curvature, vertex-wise data, and marker overlays.
This function visualizes a laminar or pial surface loaded from a LayerSurfaceSet object using the k3d rendering backend. It supports curvature shading, vertex-specific color mapping, and visualization of fiducial or region markers, providing a flexible interactive 3D view of laminar or anatomical surfaces.
- Parameters:
surf_set (LayerSurfaceSet) – Layer surface container providing access to laminar or pial surfaces.
layer_name (str, optional) – Name of the layer to render (e.g., ‘pial’, ‘white’, ‘inflated’). Default is ‘inflated’.
stage ({'combined', 'ds'}, optional) – Rendering stage: ‘combined’ for merged hemispheres, ‘ds’ for downsampled single surfaces. Default is ‘combined’.
hemi ({'lh', 'rh'}, optional) – Hemisphere to render. Required if stage=’ds’. Default is None.
orientation (str or None, optional) – Downsampling orientation identifier used when stage=’ds’. Ignored otherwise.
fixed (bool or None, optional) – Whether to load fixed or adaptive orientation surfaces when stage=’ds’. Default is None.
color (array_like of int, shape (3,), optional) – Base RGB color of the surface (0-255). Default is [166, 166, 166].
grid (bool, optional) – Display background grid. Default is False.
menu (bool, optional) – Display interactive visualization menu. Default is False.
vertex_colors (array_like, optional) – Vertex-wise colors specified as either RGB(A) values or packed 32-bit integers. Default is None.
info (bool, optional) – If True, prints surface metadata (e.g., vertex count). Default is False.
camera_view (array_like, optional) – Predefined camera position and orientation. If None, automatic camera fitting is used. Default is None.
height (int, optional) – Plot height in pixels. Default is 512.
opacity (float, optional) – Surface opacity (0 = transparent, 1 = opaque). Default is 1.0.
marker_coords (array_like, optional) – Marker coordinates (n × 3) in the same space as the surface vertices.
marker_vertices (array_like of int, optional) – Vertex indices to highlight as markers (used instead of explicit coordinates if provided).
marker_size (float or sequence, optional) – Size (radius) of marker spheres. Default is 1.0.
marker_color (array_like, shape (3,) or (n, 3), optional) – RGB color(s) of marker spheres (0-255). Default is [255, 0, 0].
plot_curvature (bool, optional) – If True, overlays sulcal curvature shading derived from FreeSurfer .curv files. Default is True.
- Returns:
plot – Interactive k3d plot object containing the rendered surface and optional overlays.
- Return type:
k3d.plot.Plot
Notes
Supports both per-vertex color overlays (e.g., statistical maps) and curvature-based shading.
Vertex colors with an alpha channel (RGBA) use transparency to blend with curvature shading.
Curvature values are mapped to grayscale for sulcal and gyral regions.
If both marker_vertices and marker_coords are provided, the function prioritizes marker_vertices.
Compatible with fsaverage-aligned surfaces and laminar surface sets generated by laMEG.
- lameg.viz.verify_coregistration(fid_coords, surf_set)#
Visualize MEG-MRI coregistration by plotting the scalp, skull, and cortical surfaces along with fiducial landmarks.
This function provides a 3D visualization of the subject’s head geometry and fiducial points (nasion, left and right preauricular) to verify whether MEG-MRI coregistration was successful. It loads the pial, scalp, inner skull, and outer skull surfaces from the subject’s directory and displays them using a k3d interactive plot.
- Parameters:
fid_coords (dict) – Dictionary of fiducial coordinates in MEG headspace, e.g.:
{'nas': [x, y, z], 'lpa': [x, y, z], 'rpa': [x, y, z]}.surf_set (LayerSurfaceSet) – Subject’s surface set containing paths and metadata for cortical and head meshes.
- Returns:
plot – Interactive 3D plot displaying cortical and head surfaces with fiducial markers.
- Return type:
k3d.plot.Plot
- Raises:
FileNotFoundError – If one or more head surface meshes are missing, indicating that coregistration or segmentation has not yet been completed.
Notes
- The following meshes are required:
<subject>/mri/origscalp_2562.surf.gii
<subject>/mri/origiskull_2562.surf.gii
<subject>/mri/origoskull_2562.surf.gii
- Fiducial markers are displayed as colored spheres:
Nasion: blue
LPA: red
RPA: green
Intended as a visual diagnostic tool; does not modify or compute transformations.