lameg package#

Submodules#

lameg.invert module#

lameg.laminar module#

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#

lameg.surf module#

lameg.util module#

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.

Module contents#