lameg package#

Submodules#

lameg.invert module#

This module provides tools for the coregistration, and source reconstruction of MEG data using SPM (Statistical Parametric Mapping). Key operations include:

  • Coregistration of MRI and surface meshes with MEG data.

  • Empirical Bayesian Beamformer (EBB) and Multiple Sparse Priors (MSP) source reconstruction algorithms.

  • Sliding time window source reconstruction using MSP

  • Utility function for loading source data after source reconstruction.

lameg.invert.coregister(nas, lpa, rpa, mri_fname, mesh_fname, data_fname, fid_labels=('nas', 'lpa', 'rpa'), viz=True, spm_instance=None) None#

Run head coregistration.

This function performs head coregistration on MEG data using an MRI and mesh, and computes a forward model using the Nolte single shell model.

Parameters:
  • nas (list) – NASion fiducial coordinates.

  • lpa (list) – Left PreAuricular fiducial coordinates.

  • rpa (list) – Right PreAuricular fiducial coordinates.

  • mri_fname (str) – Filename of the MRI data.

  • mesh_fname (str) – Filename of the mesh data.

  • data_fname (str) – Filename of the MEG data.

  • fid_labels (list, optional) – Fiducial coordinate labels. Default is [‘nas’, ‘lpa’, ‘rpa’].

  • viz (bool, optional) – Whether or not to show SPM visualization. Default is True.

  • spm_instance (spm_standalone, optional) – Instance of standalone SPM. Default is None.

Notes

If spm_instance is not provided, the function will start a new standalone SPM instance. The function will automatically close the standalone SPM instance if it was started within the function.

lameg.invert.invert_ebb(mesh_fname, data_fname, n_layers, patch_size=5, n_temp_modes=4, foi=None, woi=None, hann_windowing=False, n_folds=1, ideal_pc_test=0, viz=True, return_mu_matrix=False, spm_instance=None)#

Run the Empirical Bayesian Beamformer (EBB) source reconstruction algorithm.

This function performs EBB source reconstruction on MEG data. It involves mesh smoothing and running the EBB algorithm. The MEG data must already be coregistered with the given mesh.

Parameters:
  • mesh_fname (str) – Filename of the mesh data.

  • data_fname (str) – Filename of the MEG data.

  • n_layers (int) – Number of layers in the mesh.

  • patch_size (int, optional) – Patch size for mesh smoothing. Default is 5.

  • n_temp_modes (int, optional) – Number of temporal modes for the beamformer. Default is 4.

  • foi (list, optional) – Frequency of interest range as [low, high]. Default is [0, 256].

  • woi (list, optional) – Window of interest as [start, end]. Default is [-np.inf, np.inf].

  • hann_windowing (int, optional) – Whether or not to perform Hann windowing. Default is False.

  • n_folds (int) – Number of cross-validation folds. Must be >1 for cross-validation error.

  • ideal_pc_test (float) – Percentage of channels to leave out (ideal because it needs an integer number of channels).

  • viz (bool, optional) – Whether or not to show SPM visualization. Default is True.

  • return_mu_matrix (bool, optional) – Whether or not to return the matrix needed to reconstruct source activity. Default is False.

  • spm_instance (spm_standalone, optional) – Instance of standalone SPM. Default is None.

Returns:

A list containing the free energy, cross-validation error (cv_err), and the matrix needed to reconstruct source activity (mu_matrix; if return_mu_matrix is True).

Return type:

list

Notes

  • If spm_instance is not provided, the function will start a new standalone SPM instance.

  • The function will automatically close the standalone SPM instance if it was started within the function.

lameg.invert.invert_msp(mesh_fname, data_fname, n_layers, priors=None, patch_size=5, n_temp_modes=4, foi=None, woi=None, hann_windowing=False, n_folds=1, ideal_pc_test=0, viz=True, return_mu_matrix=False, spm_instance=None)#

Run the Multiple Sparse Priors (MSP) source reconstruction algorithm.

This function performs MSP source reconstruction on MEG data. It involves mesh smoothing and running the MSP algorithm. The MEG data must already be coregistered with the given mesh.

Parameters:
  • mesh_fname (str) – Filename of the mesh data.

  • data_fname (str) – Filename of the MEG data.

  • n_layers (int) – Number of layers in the mesh.

  • priors (list, optional) – Indices of vertices to be used as priors. Default is an empty list.

  • patch_size (int, optional) – Patch size for mesh smoothing. Default is 5.

  • n_temp_modes (int, optional) – Number of temporal modes for the beamformer. Default is 4.

  • foi (list, optional) – Frequency of interest range as [low, high]. Default is [0, 256].

  • woi (list, optional) – Window of interest as [start, end]. Default is [-np.inf, np.inf].

  • hann_windowing (int, optional) – Whether or not to perform Hann windowing. Default is False.

  • n_folds (int) – Number of cross-validation folds. Must be >1 for cross-validation error.

  • ideal_pc_test (float) – Percentage of channels to leave out (ideal because it needs an integer number of channels).

  • viz (bool, optional) – Whether or not to show SPM visualization. Default is True.

  • return_mu_matrix (bool, optional) – Whether or not to return the matrix needed to reconstruct source activity. Default is False.

  • spm_instance (spm_standalone, optional) – Instance of standalone SPM. Default is None.

Returns:

A list containing the free energy, cross-validation error (cv_err), and the matrix needed to reconstruct source activity (mu_matrix; if return_mu_matrix is True).

Return type:

list

Notes

  • If spm_instance is not provided, the function will start a new standalone SPM instance.

  • The function will automatically close the standalone SPM instance if it was started within the function.

  • Priors are adjusted by adding 1 to each index to align with MATLAB’s 1-based indexing.

lameg.invert.invert_sliding_window(prior, mesh_fname, data_fname, n_layers, patch_size=5, n_temp_modes=1, win_size=16, win_overlap=True, foi=None, hann_windowing=True, viz=True, spm_instance=None)#

Run the Multiple Sparse Priors (MSP) source reconstruction algorithm in a sliding time window.

This function performs MSP source reconstruction on MEG data within sliding time windows. It involves mesh smoothing and running the MSP algorithm. The MEG data must already be coregistered with the given mesh.

Parameters:
  • prior (float) – Index of the vertex to be used as a prior.

  • mesh_fname (str) – Filename of the mesh data.

  • data_fname (str) – Filename of the MEG data.

  • n_layers (int) – Number of layers in the mesh.

  • patch_size (int, optional) – Patch size for mesh smoothing. Default is 5.

  • n_temp_modes (int, optional) – Number of temporal modes for the beamformer. Default is 1.

  • win_size (float, optional) – Size of the sliding window in ms. Default is 16. If you increase win_size, you may need to increase n_temp_modes.

  • win_overlap (bool, optional) – Whether the windows should overlap. Default is True.

  • foi (list, optional) – Frequency of interest range as [low, high]. Default is [0, 256].

  • hann_windowing (bool, optional) – Whether or not to use Hann windowing. Default is True.

  • viz (bool, optional) – Whether or not to show SPM visualization. Default is True.

  • spm_instance (spm_standalone, optional) – Instance of standalone SPM. Default is None.

Returns:

A list containing the free energy time series (free_energy), and the windows of interest (wois).

Return type:

list

Notes

  • If spm_instance is not provided, the function will start a new standalone SPM instance.

  • The function will automatically close the standalone SPM instance if it was started within the function.

  • The prior index is adjusted by adding 1 to align with MATLAB’s 1-based indexing.

lameg.invert.load_source_time_series(data_fname, mu_matrix=None, inv_fname=None, vertices=None)#

Load source time series data from specified vertices using precomputed inverse solutions or a lead field matrix.

This function extracts time series data from specific vertices, based on precomputed inverse solutions, or computes the source time series using a provided lead field matrix.

Parameters:
  • data_fname (str) – Filename or path of the MEG data file.

  • mu_matrix (ndarray, optional) – Lead field matrix (source x sensor). Default is None.

  • inv_fname (str, optional) – Filename or path of the file containing the inverse solutions. Default is None.

  • vertices (list of int, optional) – List of vertex indices from which to extract time series data. Default is None, which implies all vertices will be used.

Returns:

  • source_ts (np.array) – An array containing the extracted source time series data (sources x time x trial).

  • time (np.array) – An array containing the timestamps.

  • mu_matrix (np.array) – The matrix needed to reconstruct source activity from sensor signals.

Notes

  • If inv_fname is not provided, and mu_matrix is None, the inverse solution from the MEG data file specified by data_fname will be used.

  • If mu_matrix is provided, the function will compute the source time series directly using the lead field matrix, without the need for precomputed inverse solutions.

lameg.laminar module#

This module provides tools for performing laminar analysis of MEG signals. It integrates functionalities for performing source reconstruction using different methods (Empirical Bayesian Beamformer and Multiple Sparse Priors), and assessing model fit via free energy and cross validation error. It also includes capabilities for analyzing laminar current source density and comparing regional brain activity across different conditions or layers.

Key functionalities include: - Source reconstruction with options to choose between different methods and evaluate model fits. - Calculation of current source density from laminar neural signals. - Comparison of power changes across different regions and layers to identify areas of interest.

lameg.laminar.compute_csd(signal, thickness, sfreq, smoothing=None)#

Compute the laminar Current Source Density (CSD) from a given signal.

This function calculates CSD using the Standard CSD method. It takes a multi-layered neural signal, and computes the CSD. An optional smoothing step can be applied to the CSD output.

Parameters:
  • signal (numpy.ndarray) – The neural signal matrix, where rows correspond to different layers and columns to time points.

  • thickness (float) – The laminar thickness of the cortex from which the signal was recorded, in millimeters.

  • sfreq (float) – Sampling frequency of the signal in Hertz.

  • smoothing (str, optional) – Specifies the kind of smoothing to apply to the CSD. Acceptable values are those compatible with scipy.interpolate.interp1d, such as ‘linear’, ‘nearest’, ‘zero’, ‘slinear’, ‘quadratic’, ‘cubic’, etc. If None, no smoothing is applied. Default is None.

Returns:

ret_vals – A list containing the CSD matrix as the first element. If smoothing is applied, the second element is the smoothed CSD matrix. The CSD matrix dimensions are layers x time points.

Return type:

list

Notes

  • The function requires the ‘neo’, ‘quantities’ (pq), ‘numpy’ (np), ‘elephant’, and ‘scipy.interpolate.interp1d’ libraries.

  • The CSD is calculated using the Standard CSD method provided by the ‘elephant’ package.

  • Smoothing is applied across layers and is independent for each time point.

  • The returned CSD matrix has the same number of time points as the input signal but can have a different number of layers if smoothing is applied.

lameg.laminar.model_comparison(nas, lpa, rpa, mri_fname, mesh_fnames, data_fname, method='EBB', viz=True, spm_instance=None, coregister_kwargs=None, invert_kwargs=None)#

Compare model fits using different meshes by computing the free energy.

This function runs source reconstruction algorithms (either Empirical Bayesian Beamformer or Multiple Sparse Priors) on a set of meshes and compares their model fits using the free energy and cross-validation error metrics.

Parameters:
  • nas (list) – NASion fiducial coordinates.

  • lpa (list) – Left PreAuricular fiducial coordinates.

  • rpa (list) – Right PreAuricular fiducial coordinates.

  • mri_fname (str) – Filename of the MRI data.

  • mesh_fnames (list) – List of filenames for different meshes.

  • data_fname (str) – Filename of the MEG data.

  • method (str, optional) – Source reconstruction method, either ‘EBB’ or ‘MSP’. Default is ‘EBB’.

  • viz (bool, optional) – Whether to display SPM visualizations. Default is True.

  • spm_instance (spm_standalone, optional) – Instance of standalone SPM software. Default is None.

  • coregister_kwargs (dict, optional) – Keyword arguments specifically for the coregister function.

  • invert_kwargs (dict, optional) – Keyword arguments specifically for the invert function.

Returns:

  • f_vals (np.array) – Free energy values for each mesh.

  • cv_errs (np.array) – The cross-validation error for each mesh.

Notes

  • If spm_instance is not provided, the function will start a new standalone SPM instance.

  • The function will automatically close the standalone SPM instance if it was started within the function.

  • Free energy is used as a measure of model fit, with higher values indicating better fit.

lameg.laminar.roi_power_comparison(data_fname, woi, baseline_woi, mesh, n_layers, perc_thresh, mu_matrix=None, chunk_size=None)#

Computes and compares power changes in pial and white matter layers to define regions of interest (ROI) based on significant power shifts.

This function calculates power changes in the pial and white matter layers during a specified window of interest (WOI) and a baseline window. It identifies ROIs by comparing these changes against a percentile threshold and performs a relative comparison of power changes between the layers to assess laminar differences.

Parameters:
  • data_fname (str) – Filename of the data file containing source time series.

  • woi (tuple) – Window of interest, specified as a start and end time (in milliseconds).

  • baseline_woi (tuple) – Baseline window of interest for comparison, specified as start and end time (in milliseconds).

  • mesh (nibabel.gifti.GiftiImage) – Gifti surface mesh.

  • n_layers (int) – Number of layers in the cortical model.

  • perc_thresh (float) – Percentile threshold for determining significant changes in power.

  • mu_matrix (ndarray, optional) – Lead field matrix (source x sensor). Default is None.

  • chunk_size (int, optional) – Number of vertices to load source time series from at once. If None, will load all at the same time. Default is None.

Returns:

  • laminar_t_statistic (float) – The t-statistic for laminar power comparison.

  • laminar_p_value (float) – The p-value associated with the laminar power comparison.

  • deg_of_freedom (int) – Degrees of freedom for the statistical test.

  • roi_idx (list of int) – Indices of vertices considered as ROIs.

lameg.laminar.sliding_window_model_comparison(prior, nas, lpa, rpa, mri_fname, mesh_fnames, data_fname, viz=True, spm_instance=None, coregister_kwargs=None, invert_kwargs=None)#

Compare model fits across different meshes using a sliding window approach.

This function runs source reconstruction using the Multiple Sparse Priors (MSP) method in sliding time windows on a set of meshes. It compares the model fits for each mesh by computing the free energy in each window.

Parameters:
  • prior (float) – Index of the vertex to be used as a prior.

  • nas (list) – NASion fiducial coordinates.

  • lpa (list) – Left PreAuricular fiducial coordinates.

  • rpa (list) – Right PreAuricular fiducial coordinates.

  • mri_fname (str) – Filename of the MRI data.

  • mesh_fnames (list) – List of filenames for different meshes.

  • data_fname (str) – Filename of the MEG data.

  • viz (bool, optional) – Whether or not to show SPM visualization. Default is True.

  • spm_instance (spm_standalone, optional) – Instance of standalone SPM. Default is None.

  • coregister_kwargs (dict, optional) – Keyword arguments specifically for the coregister function.

  • invert_kwargs (dict, optional) – Keyword arguments specifically for the invert_sliding_window function.

Returns:

  • f_vals (list) – Free energy values for each mesh.

  • wois (list) – Windows of interest.

Notes

  • If spm_instance is not provided, the function will start a new standalone SPM instance.

  • The function will automatically close the standalone SPM instance if it was started within the function.

  • Free energy is used as a measure of model fit, with higher values indicating better fit.

  • The prior index is adjusted by adding 1 to align with MATLAB’s 1-based indexing.

lameg.simulate module#

This module facilitates the simulation of MEG data using the Statistical Parametric Mapping (SPM) toolbox. It provides functionalities to simulate both current density and dipole-based MEG data under varying conditions and configurations.

Key Features:

  • Current Density Simulation: Allows for the simulation of current density data based on user-defined parameters such as vertices, signals, dipole moments, and patch sizes. Includes the ability to specify the signal-to-noise ratio and window of interest for the simulations.

  • Dipole Simulation: Facilitates the simulation of dipole-based data, providing options to configure dipole orientations, moments, and noise levels. It supports the simulation of unique signals per trial and can average data across trials if needed.

Examples of use:

  • Simulating data with specific noise levels and analyzing the impact of noise on signal processing algorithms.

  • Generating datasets with known properties to test the efficacy of dipole fitting routines or source localization methods.

lameg.simulate.check_inversion_exists(file)#

Check if inversion data exists in the loaded HDF5 file.

Parameters:

file (h5py.File) – The loaded HDF5 file object. The expected structure is file[‘D’][‘other’][‘inv’].

Returns:

Returns True if inversion data exists in the file.

Return type:

bool

Raises:
  • ValueError – If the inversion data is missing or not found in the expected structure.

  • KeyError – If the required keys are missing from the file structure.

lameg.simulate.load_vertices(file)#

Load vertices from the HDF5 file based on the file version.

Parameters:

file (h5py.File) – The loaded HDF5 file object. The function expects the structure file[‘D’][‘other’][‘inv’][0][0][‘mesh’][‘tess_mni’][‘vert’].

Returns:

A NumPy array containing the vertices loaded from the file.

Return type:

numpy.ndarray

Raises:
  • TypeError – If the file is not saved in a format compatible with MATLAB v7.3 or later.

  • KeyError – If the required keys are missing from the file structure.

lameg.simulate.run_current_density_simulation(data_file, prefix, sim_vertices, sim_signals, dipole_moments, sim_patch_sizes, snr, sim_woi=None, spm_instance=None)#

Simulate current density data based on specified parameters.

This function generates simulated MEG data based on specified vertices, signals, dipole moments, and patch sizes, incorporating a defined signal-to-noise ratio (SNR). White noise is added at the sensor level to yield the given SNR.

Parameters:
  • data_file (str) – Filename or path of the MEG data file used as a template for simulation.

  • prefix (str) – Prefix for the output simulated data filename.

  • sim_vertices (list or int) – Indices of vertices where simulations are centered. Can be a single integer or a list.

  • sim_signals (ndarray) – Array of simulated signals.

  • dipole_moments (list or float) – Dipole moments for the simulation. Can be a single float or a list.

  • sim_patch_sizes (list or int) – Sizes of patches around each vertex for the simulation. Can be a single integer or a list.

  • snr (float) – Signal-to-noise ratio for the simulation.

  • sim_woi (list, optional) – Window of interest for the simulation as [start, end]. Default is [-np.inf, np.inf].

  • spm_instance (spm_standalone, optional) – Instance of standalone SPM. Default is None.

Returns:

sim_fname – Filename of the generated simulated data.

Return type:

str

Notes

  • If spm_instance is not provided, the function will start a new standalone SPM instance.

  • The function will automatically close the standalone SPM instance if it was started within the function.

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-based MEG data based on specified parameters.

This function generates simulated MEG data with specific dipole configurations. It creates simulations based on specified vertices, signals, dipole orientations, moments, and patch sizes, incorporating a defined signal-to-noise ratio (SNR). White noise is added at the sensor level to yield the given SNR.

Parameters:
  • data_file (str) – Filename or path of the MEG data file used as a template for simulation.

  • prefix (str) – Prefix for the output simulated data filename.

  • sim_vertices (list or int) – Indices of vertices where simulations are centered. Can be a single integer or a list.

  • sim_signals (ndarray) – Array of simulated signals. Either dipoles x time (signal will be used for each trial), or dipoles x time x trials (unique signal for each trial).

  • dipole_orientations (ndarray) – Array of dipole orientations for the simulation.

  • dipole_moments (list or float) – Dipole moments for the simulation. Can be a single float or a list.

  • sim_patch_sizes (list or int) – Sizes of patches around each vertex for the simulation. Can be a single integer or a list.

  • snr (float) – Signal-to-noise ratio for the simulation.

  • sim_woi (list, optional) – Window of interest for the simulation as [start, end]. Default is [-np.inf, np.inf].

  • average_trials (bool, optional) – Whether to average the simulated data over trials. Default is False.

  • spm_instance (spm_standalone, optional) – Instance of standalone SPM. Default is None.

Returns:

sim_fname – Filename of the generated simulated data.

Return type:

str

Notes

  • If spm_instance is not provided, the function will start a new standalone SPM instance.

  • The function will automatically close the standalone SPM instance if it was started within the function.

lameg.surf module#

This module provides a set of tools for handling and manipulating surface mesh data. The functionalities include computing mesh normals, interpolating mesh data, handling non-manifold edges, creating and manipulating GIFTI surface files, and downsampling meshes using the VTK library.

Key functionalities include: - Normalization of vectors to unit length. - Calculation of normals for mesh surfaces using both Delaunay triangulation and custom methods. - Creation of GIFTI images from mesh data. - Removal of specified vertices from a mesh and updating the mesh topology accordingly. - Identification and handling of non-manifold edges to ensure mesh manifoldness. - Interpolation of data from a downsampled mesh back to its original high-resolution mesh. - Downsampling of meshes using VTK’s decimation algorithms. - Combination and adjustment of multiple surface meshes into a single mesh.

lameg.surf.combine_surfaces(surfaces)#

Combine multiple surface meshes into a single surface mesh.

This function takes a list of Gifti surface meshes and combines them into a single surface mesh. It concatenates the vertices, faces, and normals (if present) from each surface. The faces are re-indexed appropriately to maintain the correct references to the combined vertex array.

Parameters:

surfaces (list of nibabel.gifti.GiftiImage) – List of Gifti surface meshes to be combined.

Returns:

combined_surf – A single combined Gifti surface mesh.

Return type:

nibabel.gifti.GiftiImage

Notes

  • The vertices, faces, and normals (if present) from each surface are concatenated.

  • The faces are re-indexed to reference the correct vertices in the combined vertex array.

  • If normals are present in any of the input surfaces, they are also combined.

Raises:

ValueError – If the vertex or face arrays do not have the expected dimensions.

Example

>>> import nibabel as nib
>>> surfaces = [nib.load('path/to/surface1.gii'), nib.load('path/to/surface2.gii')]
>>> combined_surf = combine_surfaces(surfaces)
>>> nib.save(combined_surf, 'path/to/combined_surface.gii')
lameg.surf.compute_dipole_orientations(method, layer_names, surf_dir, fixed=True)#

Compute dipole orientations for cortical layers using different methods.

Parameters:
  • method (str) – Method for computing dipole orientations (‘link_vector’, ‘ds_surf_norm’, ‘orig_surf_norm’, or ‘cps’). link_vector: Vectors connecting pial vertices to corresponding white matter vertices. ds_surf_norm: Surface normal vectors computed from the downsampled surface. orig_surf_norm: Surface normal vectors computed from the original (non-downsampled) surface. cps: Cortical patch statistics - mean surface normal vectors from connected vertices in the original (non-downsampled) surface.

  • layer_names (list) – Names of the cortical layers.

  • surf_dir (str) – Directory where the surface files are stored.

  • fixed (bool, optional) – Flag to ensure that orientation of corresponding vertices across layers is the same (True by default). If True, for ‘ds_surf_norm’, ‘orig_surf_norm’, and ‘cps’, orientations computed from the pial surface are used for all layers.

Returns:

orientations – An array of dipole orientations for each vertex in each layer.

Return type:

np.ndarray

Raises:

ValueError – If the number of vertices in pial and white matter surfaces do not match.

lameg.surf.create_layer_mesh(layer, hemispheres, fs_subject_dir) None#

Create or retrieve a specified cortical layer mesh file name or path based on the provided layer proportional thickness or identifier.

Parameters:
  • layer (float or int) – Specifies the cortical layer. The value 1 corresponds to the ‘pial’ surface, values between 0 and 1 (exclusive) correspond to intermediate layers (specified as a decimal), and the value 0 corresponds to the ‘white matter’ surface.

  • hemispheres (list of str) – A list of hemisphere identifiers (e.g., [‘lh’, ‘rh’]) for which meshes should be created or retrieved.

  • fs_subject_dir (str) – Path to the subject directory within the FreeSurfer environment. This directory should include a ‘surf’ directory where mesh files are stored.

Returns:

layer_name – Returns a string representing the mesh layer (‘pial’, ‘white’, or a specific intermediate layer as a formatted string). Returns None if the input layer does not match any recognized pattern (e.g., a negative number or a number greater than 1).

Return type:

str or None

Notes

For intermediate layers (0 < layer < 1), the function will check for the existence of the mesh file corresponding to each hemisphere. If it does not exist, it uses ‘mris_expand’ to generate it using the white matter surface file. If the layer exactly matches 0 or 1, it returns the corresponding standard FreeSurfer mesh identifier (‘white’ or ‘pial’).

lameg.surf.create_surf_gifti(vertices, faces, normals=None)#

Create a Gifti image object from surface mesh data.

This function creates a GiftiImage object from the provided vertices, faces, and optional normals. The vertices and faces are required, while normals are optional. If normals are provided, they are added to the Gifti image. The function returns the GiftiImage object.

Parameters:
  • vertices (numpy.ndarray) – Array of vertices. Each row represents a vertex with its x, y, z coordinates.

  • faces (numpy.ndarray) – Array of faces. Each row represents a face with three integers corresponding to vertex indices.

  • normals (numpy.ndarray, optional) – Array of vertex normals. Each row represents a normal vector corresponding to a vertex.

Returns:

new_gifti – The GiftiImage object created from the provided mesh data.

Return type:

nibabel.gifti.GiftiImage

Notes

  • Vertex, face, and normal arrays should be NumPy arrays.

  • Vertices and normals should be in float32 format, and faces should be in int32 format.

Example

>>> import numpy as np
>>> import nibabel as nib
>>> vertices = np.array([[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0]])
>>> faces = np.array([[0, 1, 2], [0, 2, 3]])
>>> normals = np.array([[0, 0, 1], [0, 0, 1], [0, 0, 1], [0, 0, 1]])
>>> gifti_img = create_surf_gifti(vertices, faces, normals)
lameg.surf.downsample_multiple_surfaces(in_surfs, ds_factor)#

Downsample multiple surface meshes using the VTK decimation algorithm.

This function takes a list of input surface meshes (in Gifti format) and applies a downsampling process to each surface. The downsampling is performed using VTK’s vtkDecimatePro algorithm. The first surface in the list is downsampled, and its vertex mapping is then applied to all other surfaces in the list. The function returns a list of downsampled surface meshes.

Parameters:
  • in_surfs (list of nibabel.gifti.GiftiImage) – Input Gifti surface meshes to be downsampled.

  • ratio (float) – The reduction ratio for the downsampling process. For example, a ratio of 0.1 implies that the mesh will be reduced to 90% of its original size.

Returns:

out_surfs – List of downsampled Gifti surface meshes.

Return type:

list of nibabel.gifti.GiftiImage

Notes

  • The function prints the percentage of vertices retained in the first surface after downsampling.

  • If normals are present in the input surfaces, they are also downsampled and mapped to the new surfaces.

  • The resulting surfaces maintain the original topology and are suitable for visualization and further processing.

Example

>>> import nibabel as nib
>>> in_surfs = [nib.load('path/to/input_surf1.gii'), nib.load('path/to/input_surf2.gii')]
>>> ratio = 0.1
>>> out_surfs = downsample_multiple_surfaces(in_surfs, ratio)
>>> for i, ds_surf in enumerate(out_surfs):
...     nib.save(ds_surf, f'path/to/output_surf{i+1}.gii')
lameg.surf.downsample_single_surface(gifti_surf, ds_factor=0.1)#

Downsample a Gifti surface using the VTK library.

This function takes a Gifti surface defined by its vertices and faces, and downsamples it using VTK’s vtkDecimatePro algorithm. The reduction ratio determines the degree of downsampling. The function returns the downsampled Gifti surface.

Parameters:
  • gifti_surf (nibabel.gifti.GiftiImage) – The Gifti surface object to be downsampled.

  • reduction_ratio (float) – The proportion of the mesh to remove. For example, a reduction ratio of 0.1 retains 90% of the original mesh.

Returns:

new_gifti_surf – A new GiftiImage object with the downsampled surface.

Return type:

nibabel.gifti.GiftiImage

Notes

  • The input faces array should be triangulated, i.e., each face should consist of exactly three vertex indices.

  • The VTK library is used for mesh decimation, which must be installed and properly configured.

  • The returned GiftiImage object is a new object; the original gifti_surf object is not modified in place.

Example

>>> import numpy as np
>>> gifti_surf = nib.load('path_to_gifti_file.gii')
>>> new_gifti_surf = downsample_single_surface(gifti_surf, 0.1)
lameg.surf.find_non_manifold_edges(faces)#

Identify non-manifold edges in a given mesh represented by its faces.

A non-manifold edge is defined as an edge that is shared by more than two faces. This function processes an array of faces, each face represented by a tuple of vertex indices, and identifies edges that meet the non-manifold criteria.

Parameters:

faces (np.ndarray) – An array where each row represents a face as a tuple of three vertex indices.

Returns:

non_manifold_edges – A dictionary where keys are tuples representing non-manifold edges (vertex indices are sorted), and values are lists of face indices that share the edge.

Return type:

dict

Notes

The function uses a defaultdict to collect face indices for each edge encountered in the mesh. It then filters out edges that are associated with more than two faces, identifying them as non-manifold.

lameg.surf.fix_non_manifold_edges(vertices, faces)#

Remove faces associated with non-manifold edges from a mesh defined by vertices and faces.

Non-manifold edges are edges that are shared by more than two faces, which can cause issues in various mesh processing tasks such as mesh simplification, smoothing, or 3D printing. This function identifies such edges and removes all faces associated with them to ensure manifoldness of the mesh.

Parameters:
  • vertices (np.ndarray) – An array of vertices, where each row represents a vertex as [x, y, z] coordinates.

  • faces (np.ndarray) – An array of faces, where each row represents a face as indices into the vertices array.

Returns:

  • vertices (np.ndarray) – The unchanged array of vertices.

  • new_faces (np.ndarray) – The modified array of faces, with faces associated with non-manifold edges removed.

Examples

>>> vertices = np.array([[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0]])
>>> faces = np.array([[0, 1, 2], [0, 2, 3], [1, 2, 3]])
>>> new_vertices, new_faces = fix_non_manifold_edges(vertices, faces)
>>> new_faces
array([[0, 1, 2], [0, 2, 3]])  # Assuming face [1, 2, 3] was associated with a non-manifold
edge.
lameg.surf.interpolate_data(original_mesh, downsampled_mesh, downsampled_data, adjacency_matrix=None, max_iterations=10)#

Interpolate vertex data from a downsampled mesh back to the original mesh using nearest neighbor matching and optional smoothing based on an adjacency matrix. Both meshes are expected to be nibabel Gifti objects.

Parameters:
  • original_mesh (nibabel.gifti.GiftiImage) – The original high-resolution mesh as a nibabel Gifti object from which ‘downsampled_mesh’ is derived.

  • downsampled_mesh (nibabel.gifti.GiftiImage) – The downsampled version of the original mesh as a nibabel Gifti object.

  • downsampled_data (array) – Data associated with the vertices of ‘downsampled_mesh’.

  • adjacency_matrix (sparse matrix, optional) – A vertex-by-vertex adjacency matrix of the original mesh. If None, it will be computed from the ‘original_mesh’.

  • max_iterations (int, optional) – The maximum number of iterations to perform for smoothing the interpolated data.

Returns:

vertex_data – An array of interpolated data for each vertex in the ‘original_mesh’. The data is initially interpolated using nearest neighbors and can be further refined through iterative smoothing.

Return type:

np.ndarray

Notes

The function first finds the nearest vertex in the ‘downsampled_mesh’ for each vertex in the ‘original_mesh’ using a KD-tree. It directly assigns corresponding data values where a close match is found. The function iteratively adjusts data values at vertices without direct matches by averaging over neighbors.

lameg.surf.iterative_downsample_single_surface(gifti_surf, ds_factor=0.1)#

Iteratively downsample a single surface mesh to a target number of vertices.

This function reduces the number of vertices in a surface mesh (in GIFTI format) to a specified fraction of its original size. Downsampling is performed iteratively until the target number of vertices is reached or closely approximated.

Parameters:
  • gifti_surf (nibabel.gifti.GiftiImage) – The surface mesh to be downsampled, provided as a GIFTI image object.

  • ds_factor (float, optional) – The downsampling factor representing the target fraction of the original number of vertices. Default is 0.1.

Returns:

current_surf – The downsampled surface mesh as a GIFTI image object.

Return type:

nibabel.gifti.GiftiImage

Notes

  • The downsampling process is iterative. In each iteration, the mesh is downsampled by a factor calculated to approach the target number of vertices.

  • If the calculated downsampling factor in an iteration equals or exceeds 1, the process is terminated to prevent upsampling or infinite loops.

lameg.surf.mesh_adjacency(faces)#

Compute the adjacency matrix of a triangle mesh.

Parameters:

faces (np.array, shape (f, 3)) – The mesh faces, where f is the number of faces, and each face is represented by a tuple of three vertex indices.

Returns:

adjacency – The adjacency matrix of the mesh, where v is the number of vertices. Each entry (i, j) indicates whether vertices i and j are connected by an edge.

Return type:

np.array, shape (v, v)

lameg.surf.mesh_normals(vertices, faces, unit=False)#

Normalize a numpy array of vectors.

This function normalizes each row in the array of vectors to have unit length. If the length of a vector is below a certain threshold (machine epsilon), it is set to 1 to avoid division by zero.

Parameters:

vectors (ndarray) – Array of vectors to be normalized. Each row represents a vector.

Returns:

Normalized array of vectors where each row has unit length.

Return type:

ndarray

lameg.surf.postprocess_freesurfer_surfaces(subj_id, out_dir, out_fname, n_surfaces=11, ds_factor=0.1, orientation='link_vector', fix_orientation=True, remove_deep=True, n_jobs=-1)#

Process and combine FreeSurfer surface meshes for a subject.

This function processes FreeSurfer surface meshes for a given subject by creating intermediate surfaces, adjusting for RAS offset, removing deep vertices, combining hemispheres, downsampling, and computing link vectors. The resulting surfaces are combined and saved to a specified output file.

Parameters:
  • subj_id (str) – Subject ID corresponding to the FreeSurfer subject directory.

  • out_dir (str) – Output directory where the processed files will be saved.

  • out_fname (str) – Filename for the final combined surface mesh.

  • n_surfaces (int, optional) – Number of intermediate surfaces to create between white and pial surfaces.

  • ds_factor (float, optional) – Downsampling factor for surface decimation.

  • orientation (str, optional) – Method to compute orientation vectors (‘link_vector’ for pial-white link, ‘ds_surf_norm’ for downsampled surface normals, ‘orig_surf_norm’ for original surface normals, and ‘cps’ for cortical patch statistics).

  • fix_orientation (bool, optional) – Flag to ensure that orientation of corresponding vertices across layers is the same (True by default).

  • remove_deep (bool, optional) – Flag to remove vertices located in deep regions (labeled as ‘unknown’).

  • n_jobs (int, optional) – Number of parallel processes to run. -1 for all available cores (default is -1).

Notes

  • This function assumes the FreeSurfer ‘SUBJECTS_DIR’ environment variable is set.

  • Surfaces are processed in Gifti format and combined into a single surface mesh.

Example

>>> postprocess_freesurfer_surfaces('subject1', '/path/to/output', 'combined_surface.gii')
lameg.surf.remove_unconnected_vertices(gifti_surf)#

Remove vertices that are not connected to any faces from a Gifti surface object.

Parameters:

gifti_surf (nibabel.gifti.GiftiImage) – The Gifti surface object to be processed.

Returns:

cleaned_gifti_surf – A new GiftiImage object with unconnected vertices removed.

Return type:

nibabel.gifti.GiftiImage

lameg.surf.remove_vertices(gifti_surf, vertices_to_remove)#

Remove specified vertices from a Gifti surface and update the faces accordingly.

This function modifies a Gifti surface by removing the specified vertices. It also updates the faces of the surface so that they only reference the remaining vertices. If normals are present in the surface, they are also updated to correspond to the new set of vertices.

Parameters:
  • gifti_surf (nibabel.gifti.GiftiImage) – The Gifti surface object from which vertices will be removed.

  • vertices_to_remove (array_like) – An array of vertex indices to be removed from the surface.

Returns:

new_gifti – A new GiftiImage object with the specified vertices removed and faces updated.

Return type:

nibabel.gifti.GiftiImage

Notes

  • The function assumes that the GiftiImage object contains at least two data arrays: one for vertices and one for faces. If normals are present, they are also updated.

  • Vertex indices in vertices_to_remove should be zero-based (following Python’s indexing convention).

  • The returned GiftiImage object is a new object; the original gifti_surf object is not modified in place.

Example

>>> import nibabel as nib
>>> gifti_surf = nib.load('path_to_gifti_file.gii')
>>> vertices_to_remove = np.array([0, 2, 5])  # Indices of vertices to remove
>>> new_gifti_surf = remove_vertices(gifti_surf, vertices_to_remove)
lameg.surf.split_fv(faces, vertices)#

Split faces and vertices into connected pieces based on the connectivity of the faces.

Parameters:
  • faces (np.ndarray) – A 2D numpy array of faces, where each row represents a face and each element is an index to a vertex in vertices.

  • vertices (np.ndarray) – A 2D numpy array of vertices, where each row represents a vertex.

Returns:

fv_out – A list where each element is a dictionary with keys ‘faces’ and ‘vertices’. Each dictionary represents a separately connected patch of the mesh.

Return type:

list of dict

Examples

>>> faces = np.array([[1, 2, 3], [1, 3, 4], [5, 6, 1], [7, 8, 9], [11, 10, 4]])
>>> vertices = np.array([[2, 4], [2, 8], [8, 4], [8, 0], [0, 4], [2, 6], [2, 2], [4, 2],
>>>                      [4, 0], [5, 2], [5, 0]])
>>> split_patches = split_fv(faces, vertices)

Notes

Faces and vertices should be defined such that faces sharing a vertex reference the same vertex number. This function does not explicitly test for duplicate vertices at the same location.

lameg.util module#

This module provides tools for interfacing with SPM (Statistical Parametric Mapping) software, managing MEG sensor data, and working with neuroimaging data in various formats such as NIfTI, GIFTI, and MATLAB files. It includes functions for batch processing in SPM, converting data formats, loading and processing sensor data, and working with anatomical structures through cortical mesh analysis.

Key functionalities:

  • Context management for SPM operations.

  • Batch processing for neuroimaging tasks.

  • Loading MEG sensor data and managing related file operations.

  • Utility functions for anatomical and spatial data transformations.

lameg.util.batch(cfg, viz=True, spm_instance=None) None#

Execute a batch processing job in SPM (Statistical Parametric Mapping) using MATLAB.

This function prepares a configuration for an SPM batch job, saves it to a temporary MATLAB file, and executes it within an SPM instance. The function is capable of running any batch configuration passed to it, as long as it adheres to SPM’s batch configuration structure. After processing, it cleans up by deleting the temporary file used for the job.

Parameters:
  • cfg (dict) – A dictionary containing the configuration settings for the SPM job. The dictionary should follow the structure required by SPM’s matlabbatch system.

  • viz (bool, optional) – If True, the SPM GUI will display progress and results, allowing user interaction. If False, the process runs entirely in the background. Defaults to True.

  • spm_instance (optional) – An instance of an SPM session. If None, a new SPM session is created and used for the job. Defaults to None.

Examples

To run an SPM job with a given configuration, you might call the function as follows:

>>> cfg = {
>>>     'spm.stats.fmri_spec.dir': ['/path/to/output'],
>>>     'spm.stats.fmri_spec.timing.units': 'secs',
>>>     'spm.stats.fmri_spec.sess': {
>>>         'scans': ['scan1.nii', 'scan2.nii'],
>>>         'cond': {
>>>             'name': 'ExampleCondition',
>>>             'onset': [10, 30],
>>>             'duration': [1, 1],
>>>         },
>>>         'multi': {'regress': {'name': 'movement', 'val': [1, 0, 1, 0]}}
>>>     }
>>> }
>>> batch(cfg, viz=False)

Notes

  • The temporary MATLAB file is created in the system’s default temp directory.

  • This function assumes that an SPM and MATLAB environment is properly set up and accessible through the provided spm_instance or through a default SPM environment.

lameg.util.big_brain_proportional_layer_boundaries(overwrite=False)#

Get the proportional layer boundaries (6 values between 0 and 1) from the fsaverage-converted Big Brain atlas included in laMEG.

This function uses the fsaverage-converted Big Brain cortical thickness atlas to calculate normalized distances between cortical layer boundaries (from layer 1 to layer 6) with values between 0 and 1. To speed up computation, the results are stored in a NumPy dictionary.

Parameters:

overwrite (bool) – Whether to overwrite the existing file.

Returns:

bb_data – Dictionary with keys “lh” (left hemisphere) and “rh” (right hemisphere) containing arrays with layer boundaries for each vertex in the hemisphere.

Return type:

dict

lameg.util.calc_prop(vec)#

Convert independent thickness values to cumulative proportions, while respecting zeros.

This function calculates the cumulative sum of the input vector and normalizes it by the total sum of the vector. If the total sum is zero, the original vector is returned.

Parameters:

vec (array-like) – Input array of thickness values.

Returns:

vec – The cumulative proportion of the input values, normalized by the total sum. If the sum of the input values is zero, the original vector is returned.

Return type:

array-like

lameg.util.check_many(multiple, target, func=None)#

Check for the presence of strings in a target string.

Parameters:
  • multiple (list) – List of strings to be found in the target string.

  • target (str) – The target string in which to search for the specified strings.

  • func (str) – Specifies the search mode: “all” to check if all strings are present, or “any” to check if any string is present.

Notes

  • This function works well with if statements in list comprehensions.

lameg.util.convert_fsaverage_to_native(subj_id, hemi, vert_idx)#

Convert a vertex index from fsaverage to a subject’s native surface space.

This function takes a vertex index from the fsaverage template surface and finds the corresponding vertex index in a subject’s native surface space. It loads the fsaverage spherical surface, identifies the coordinates of the given vertex index, and then finds the nearest corresponding vertex on the subject’s registered spherical surface. If the hemisphere is right, it adjusts the index by adding the number of vertices in the left hemisphere pial surface so that it matches the combined hemisphere mesh. It returns the adjusted vertex index in the subject’s native space.

Parameters:
  • subj_id (str) – The subject identifier for which the conversion is being performed.

  • hemi (str) – Hemisphere specifier (‘lh’ for left hemisphere, ‘rh’ for right hemisphere).

  • vert_idx (int) – Index of the vertex in the fsaverage surface to be converted.

Returns:

subj_v_idx – Index of the vertex on the subject’s native surface that corresponds to the input vertex index.

Return type:

int

lameg.util.convert_native_to_fsaverage(subj_id, subj_surf_dir, subj_coord)#

Convert coordinates from a subject’s native surface space to the fsaverage surface space.

This function maps a vertex coordinate from a subject’s native combined pial surface to the corresponding vertex index in the fsaverage template space. It determines which hemisphere the vertex belongs to based on the closest match in the left and right hemispheres’ pial surfaces. It then finds the nearest vertex in the subject’s registered spherical surface, maps this to the nearest vertex in the fsaverage spherical surface, and returns the index of this fsaverage vertex.

Parameters:
  • subj_id (str) – The subject identifier for which the conversion is being performed.

  • subj_surf_dir (str) – The path containing the laMEG-processed subject surfaces.

  • subj_coord (array-like) – The x, y, z coordinates on the subject’s combined hemisphere pial surface to be converted.

Returns:

  • hemi (str) – The hemisphere the vertex is found in (‘lh’ for left hemisphere, ‘rh’ for right hemisphere).

  • fsave_v_idx (int) – Index of the vertex on the fsaverage spherical surface that corresponds to the input coordinates.

lameg.util.ctf_fif_spm_conversion(mne_file, res4_file, output_path, epoched, prefix='spm_', spm_instance=None)#

Convert a *.fif file containing data from a CTF scanner to SPM data format.

Parameters:
  • mne_file (str or pathlib.Path or os.Path) – Path to the “*-raw.fif” or “*-epo.fif” file.

  • res4_file (str or pathlib.Path or os.Path) – Location of the sensor position data (*.res4 for CTF).

  • output_path (str or pathlib.Path or os.Path) – Location of the converted file.

  • epoched (bool) – Specify if the data is epoched (True) or not (False).

  • prefix (str) – A string appended to the output file name after conversion. Default: "spm_".

  • spm_instance (spm_standalone, optional) – Instance of standalone SPM. Default is None.

Notes

  • If spm_instance is not provided, the function will start a new standalone SPM instance.

  • The function will automatically close the standalone SPM instance if it was started within the function.

lameg.util.get_bigbrain_layer_boundaries(subj_id, subj_surf_dir, subj_coord)#

Get the cortical layer boundaries based on Big Brain atlas for a specified coordinate in the subject’s downsampled combined space.

This function maps a vertex coordinate from a subject’s native combined pial surface to the corresponding vertex index in the fsaverage template space for a specific hemisphere. Then, the proportional layer boundaries (6 values between 0 and 1) from the fsaverage-converted Big Brain atlas are returned (from layer 1 to layer 6). To get the subject’s proportional values, these values must be multiplied by the observed cortical thickness.

Parameters:
  • subj_id (str) – The subject identifier for which the conversion is being performed.

  • subj_surf_dir (str) – The path containing the laMEG-processed subject surfaces.

  • subj_coord (array-like) – The x, y, z coordinates on the subject’s combined hemisphere pial surface to be converted.

Returns:

vert_bb_prop – Proportional layer boundaries (6 values between 0 and 1) from the fsaverage-converted Big Brain atlas.

Return type:

array-like

lameg.util.get_directories(target_path, strings='', check='all', depth='all')#

Return a list of directories in the path (or all subdirectories) containing specified strings.

Parameters:
  • target_path (str or pathlib.Path or os.Path) – The most shallow searched directory.

  • depth (str) – Specifies the depth of the search: “all” for recursive search, “one” for shallow search.

Returns:

subdirs – List of pathlib.Path objects representing the found directories.

Return type:

list

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=',')#

Fetch fiducial coordinates from a tab-separated values (TSV) file for a given subject ID.

Parameters:
  • subj_id (str) – The subject ID to search for in the TSV file.

  • fname (str) – Path to the TSV file.

  • col_delimiter (str, optional) – Column delimiter when reading file. Default is .

  • subject_column (str, optional) – Column name for subject. Default is subj_id.

  • nas_column (str, optional) – Column name for nas coordinate. Default is nas.

  • lpa_column (str, optional) – Column name for lpa coordinate. Default is lpa.

  • rpa_column (str, optional) – Column name for rpa coordinate. Default is rpa.

  • val_delimiter (str, optional) – Value delimiter when reading file. Default is ,.

Returns:

  • NAS (list) – List of floats representing the NASion fiducial coordinates.

  • LPA (list) – List of floats representing the Left Preauricular fiducial coordinates.

  • RPA (list) – List of floats representing the Right Preauricular fiducial coordinates.

lameg.util.get_files(target_path, suffix, strings='', prefix=None, check='all', depth='all')#

Return a list of files with a specific extension, prefix, and name containing specific strings.

Searches either all files in the target directory or within a specified directory.

Parameters:
  • target_path (str or pathlib.Path or os.Path) – The most shallow searched directory.

  • suffix (str) – File extension in “*.ext” format.

  • strings (list of str) – List of strings to search for in the file name.

  • prefix (str) – Limits the output list to file names starting with this prefix.

  • check (str) – Specifies the search mode: “all” to check if all strings are present, or “any” to check if any string is present.

  • depth (str) – Specifies the depth of the search: “all” for recursive search, “one” for shallow search.

Returns:

subdirs – List of pathlib.Path objects representing the found files.

Return type:

list

lameg.util.get_surface_names(n_layers, surf_path, orientation_method)#

Generate a list of filenames for each mesh layer in a multi-layer mesh setup.

Parameters:
  • n_layers (int) – The number of layers in the mesh.

  • surf_path (str) – The file path where the mesh files are located.

  • orientation_method (str) – The method used for orientation in the naming of mesh files.

Returns:

layer_fnames – A list of strings, where each string is the full file path to a mesh layer file. The list order corresponds to the layers’ order, starting from the outermost layer (pial surface) to the innermost layer (white matter surface).

Return type:

list

Notes

This function assumes a specific naming convention for the mesh files. The outermost layer is named as ‘pial’, the innermost as ‘white’, and the intermediate layers are named based on their relative position between 1 (pial) and 0 (white), with the position formatted to three decimal places. Each filename also includes an orientation method specifier.

lameg.util.load_meg_sensor_data(data_fname)#

Load sensor data from a MEG dataset.

Parameters:

data_fname (str) – Filename or path of the MEG data file.

Returns:

  • sensor_data (ndarray) – An array containing the MEG sensor data (channels x time x trial).

  • time (ndarray) – An array containing the MEG data timestamps.

  • ch_names (list) – A list of channel names.

lameg.util.make_directory(root_path, extended_dir)#

Create a directory along with intermediate directories.

Parameters:
  • root_path (str or pathlib.Path or os.Path) – The root directory.

  • extended_dir (str or list) – Directory or directories to create within root_path.

Returns:

root_path – The updated root directory.

Return type:

str or pathlib.Path or os.Path

lameg.util.spm_context(spm=None)#

Context manager for handling standalone SPM instances.

Parameters:

spm (spm_standalone, optional) – An existing standalone instance. Default is None.

Yields:

spm (spm_standalone) – A standalone SPM instance for use within the context.

Notes

  • If spm is None, the function starts a new standalone SPM instance.

  • The new standalone SPM instance will be closed automatically upon exiting the context.

  • If spm is provided, it will be used as is and not closed automatically.

  • This function is intended for use in a with statement to ensure proper management of standalone SPM resources.

lameg.util.ttest_rel_corrected(data, correction=0, tail=0, axis=0)#

Perform a corrected paired t-test on a sample of data.

This function handles missing data (NaNs) and applies a variance correction to the t-test calculation. It computes the t-statistic and corresponding p-value for the hypothesis test.

Parameters:
  • data (array_like) – A 2-D array containing the sample data. NaN values are allowed and are handled appropriately.

  • correction (float, optional) – The correction value to be added to the variance to avoid division by zero issues. If set to 0 (default), an automatic correction of 0.01 * max(variance) is applied.

  • tail (int, optional) – Specifies the type of t-test to be performed: - 0 for a two-tailed test (default), - 1 for a right one-tailed test, - -1 for a left one-tailed test.

  • axis (int, optional) – Axis along which to perform the t-test. Default is 0.

Returns:

  • t-statistic (float) – The computed t-statistic for the test.

  • degrees_of_freedom (int) – The degrees of freedom for the t-test.

  • p-value (float) – The p-value for the test.

Notes

  • The function handles NaNs by computing the sample size, mean, and variance while ignoring NaNs.

  • The degrees of freedom for the t-test are computed as max(sample size - 1, 0).

  • The standard error of the mean is adjusted with the variance correction.

  • The p-value is computed based on the specified tail type of the t-test.

lameg.viz module#

This module provides tools for converting and visualizing data. It includes functions for mapping data to RGB and hexadecimal color values, performing color normalization, and rendering 3D surface visualizations using K3D. Additional utilities are included for plotting Current Source Density (CSD) data and handling color transformations.

Functions:#

  • data_to_rgb: Converts numerical data into RGB or RGBA color arrays based on a specified colormap and normalization.

  • rgbtoint: Converts RGB color lists to a single 32-bit integer color representation.

  • color_map: Maps numerical data to hexadecimal color values suitable for use in visualizations.

  • show_surface: Renders 3D surfaces with optional vertex coloring and interactive features using K3D.

  • plot_csd: Plots Current Source Density (CSD) data as a 2D image over a specified time range.

Utilities:#

  • The module supports various color normalizations including linear, logarithmic, and diverging scales.

  • Includes handling of edge cases and data-specific adjustments to enhance the quality of visual outputs.

lameg.viz.color_map(data, cmap, vmin, vmax, n_bins=1000, vcenter=0, norm='TS')#

Return data mapped to the colormap in hexadecimal format, and a colormap for use, e.g., with a colorbar.

Parameters:
  • data (iterable) – 1D numerical data.

  • n_bins (int) – Number of bins in the histogram.

  • vmin (float) – Lowest value on the histogram range.

  • vmax (float) – Highest value on the histogram range.

  • vcenter (float, optional) – Center of the histogram range (default is 0 for zero-centered color mapping).

  • norm (str) – Type of normalization (“TS”, “N”, “LOG”).

Returns:

  • map_colors (array-like) – Data mapped to the colormap in hexadecimal format.

  • cmap (matplotlib.colors.Colormap) – The colormap object for use with visualizations like colorbars.

Notes

  • The function creates normalization based on the “norm” argument.

  • It generates a suitable colormap and maps data values based on histogram bins.

  • Returns RGB values for each data point, converts percent-based RGB to decimal, and then converts RGB to hexadecimal in a format appropriate for visualization functions.

lameg.viz.data_to_rgb(data, n_bins, cmap, vmin, vmax, vcenter=0.0, ret_map=False, norm='TS')#

Return RGB values of data mapped to the normalized matplotlib colormap. Optionally, return a colormap for use, e.g., with a colorbar.

Parameters:
  • data (iterable) – 1D numerical data.

  • n_bins (int) – Number of bins in the histogram.

  • vmin (float) – Lowest value on the histogram range.

  • vmax (float) – Highest value on the histogram range.

  • vcenter (float, optional) – Center of the histogram range (default is 0 for zero-centered color mapping).

  • ret_map (bool, optional) – Whether to return a colormap object.

  • norm (str) – Type of normalization (“TS”, “N”, “LOG”).

Returns:

  • color_mapped (array-like) – RGB values mapped to the colormap for each data point.

  • scalar_map (matplotlib.colors.ScalarMappable, optional) – The colormap object if ret_map is True.

Notes

  • The function creates normalization based on the “norm” argument.

  • It generates a suitable colormap and maps data values based on histogram bins.

  • It returns RGB values for each data point.

lameg.viz.plot_csd(csd, times, axis, colorbar=True, cmap='RdBu_r', vmin_vmax=None, n_layers=11)#

Plot the computed Current Source Density (CSD) data.

This function takes a CSD matrix and plots it over a specified time range. It offers options for color normalization, colormap selection, and including a colorbar. Optionally, it can return plot details.

Parameters:
  • csd (numpy.ndarray) – The CSD matrix to be plotted, with dimensions corresponding to layers x time points.

  • times (numpy.ndarray) – A 1D array of time points corresponding to the columns of the CSD matrix.

  • ax (matplotlib.axes.Axes) – The matplotlib axes object where the CSD data will be plotted.

  • colorbar (bool, optional) – Flag to indicate whether a colorbar should be added to the plot. Default is True.

  • cmap (str, optional) – The colormap used for plotting the CSD data. Default is “RdBu_r”.

  • vmin_vmax (tuple or str, optional) – A tuple specifying the (vmin, vmax) range for color normalization. If “norm”, a standard normalization is used. If None, the range is set to the maximum absolute value in the CSD matrix. Default is None.

  • n_layers (int) – Number of layers in the CSD.

Returns:

csd_imshow – The imshow object of the plot.

Return type:

matplotlib.image.AxesImage

Notes

  • This function requires the ‘numpy’, ‘matplotlib.colors’, and ‘matplotlib.pyplot’ libraries.

  • The ‘TwoSlopeNorm’ from ‘matplotlib.colors’ is used for diverging color normalization.

  • The aspect ratio of the plot is automatically set to ‘auto’ for appropriate time-layer representation.

  • Layer labels are set from 1 to n_layers

lameg.viz.rgbtoint(rgb)#

Return a 32-bit representation of the color as an integer.

Parameters:

rgb (array-like) – An integer array [R, G, B] representing the red, green, and blue color components.

Returns:

color – The 32-bit integer representation of the color.

Return type:

int

Notes

  • The function requires integer RGB values (0-255).

lameg.viz.show_surface(surface, color=None, grid=False, menu=False, vertex_colors=None, info=False, camera_view=None, height=512, opacity=1.0, coords=None, coord_size=1, coord_color=None)#

Render a 3D surface with optional data overlay. The rendering is persistent and does not require an active kernel.

Parameters:
  • surface (nibabel.gifti.GiftiImage) – The Gifti surface mesh to be rendered.

  • color (array, optional) – Basic color of the surface in the absence of data, specified as a decimal RGB array. Default is [166, 166, 166].

  • grid (bool, optional) – Toggles the rendering of a grid. Default is False.

  • menu (bool, optional) – Toggles the display of a menu with options such as lighting adjustments. Default is False.

  • vertex_colors (array, optional) – An array of vertex colors specified as hexadecimal 32-bit color values. Each color corresponds to a vertex on the surface. Default is None.

  • info (bool, optional) – If True, prints information about the surface, such as the number of vertices. Default is False.

  • camera_view (array, optional) – Specifies a camera view for the rendering. If None, an automatic camera view is set. Default is None.

  • height (int, optional) – Height of the widget in pixels. Default is 512.

  • opacity (float, optional) – Sets the opacity of the surface, with 1.0 being fully opaque and 0.0 being fully transparent. Default is 1.0.

Returns:

plot – A k3d plot object containing the rendered surface.

Return type:

k3d.plot.Plot

Notes

This function utilizes the k3d library for rendering the surface. It supports customization of surface color, opacity, and additional features like grid and menu display. The vertex_colors parameter allows for vertex-level color customization.

Module contents#