Using a precomputed MEG forward#

Pass the same forward_operator to a direct inversion, a sliding-window inversion, or a layer comparison. It holds one gain row per named MEG channel and one signed column per vertex, grouped by layer. Each analysis writes to its SPM inversion slot. For comparisons between solvers, give each run its own writable copy of the same recording in a separate directory.

MNE BEM and native single-shell on the same vertices#

If you have an MNE BEM solution, use compute_mne_forward to solve on the original laMEG surfaces. After coregistering the SPM reference to the multilayer mesh, pass the BEM solution, acquisition Info and MNE head/MRI transform as in Tutorial 10. If you already have a forward for each layer, use prepare_mne_forward with a dictionary of layer names to MNE Forward objects or FIF paths, as in the example below. Both functions check the registered source positions and prepare a surface set containing the anatomical locations retained at every depth. For example, if MNE excludes a pial vertex outside the inner skull, its matching white vertex is also omitted from the prepared surfaces. Use those surfaces for both solvers. For coincident positions that make matching ambiguous when importing existing forwards, supply the source-space and vertex IDs via vertices.

The example compares seeded MSP across layers and time windows for a CTF recording. reference is an SPM dataset already coregistered to the original multilayer mesh. info is the original MNE acquisition Info, including the reference channels used to compute the compensated forwards.

from lameg.forward import prepare_mne_forward
from lameg.laminar import sliding_window_model_comparison

def compare_solver_windows(forwards, surfaces, reference, info, output_dir,
                           bem_copy, native_copy, fids, vertex, spm):
    # Take the intersection across layers once. Both solvers will then use the same
    # cortical locations, even if the BEM excluded a vertex from only one layer.
    prepared = prepare_mne_forward(
        forwards, surfaces, output_dir, reference=reference, info=info,
        ignore_ref=False, allow_nominal_ctf_coils=True,
    )
    options = dict(
        spm_instance=spm, viz=False,
        invert_kwargs=dict(wois=[[-50, -25], [-25, 0], [0, 25]], patch_size=5),
    )
    # vertex is the original within-layer ID. Each call maps it to the kept
    # vertex before running MSP in the specified windows.
    bem = sliding_window_model_comparison(
        vertex, fids, bem_copy, prepared.surfaces,
        forward_operator=prepared.operator, **options,
    )
    # Use SPM's native gain on the same prepared surfaces and an independent copy
    # of the recording so that this run preserves the BEM inversion on bem_copy.
    single_shell = sliding_window_model_comparison(
        vertex, fids, native_copy, prepared.surfaces, **options,
    )
    return bem, single_shell, prepared.manifest

Each result is a pair containing the layer-by-window free energies and the window bounds in milliseconds. Rows follow surfaces.get_layer_names(). Supply the seed using its zero-based within-layer vertex ID on the original mesh. If the seed is excluded, laMEG raises an error. It maps a retained seed to the corresponding row on the prepared mesh automatically. Direct inversions on the combined mesh accept MSP priors in original layer-major order. Use prepared.support.original_vertices to map compact source rows within each layer back to anatomical vertex IDs. The JSON file at prepared.manifest records the vertex correspondence and exclusions.

For this example the SPM recipient uses CTF head coordinates. Preparation reads the MRI registration and channel units from the SPM header, and obtains the MNE-to-CTF head transform from the acquisition Info. For other coordinate frames, supply the measured transform explicitly. The example enables nominal CTF coil matching because MNE uses nominal pickup positions and this SPM file has measured positions for the same recording. Strict sensor matching is the default. With this option, each nominal pickup must match a unique group of measured coils within 0.15 mm. Each channel’s signed response, including its reference weights, is compared at each group with absolute tolerance 1e-9 and relative tolerance 1e-5. For compensated CTF acquisitions, ignore_ref=False must match the setting used to compute the forward.

Direct inversions#

Direct inversions require a working dataset registered to the mesh you will invert, including any vertex exclusions. The example below registers prepared.surfaces in the working dataset before fitting EBBlayer. The default layer_name=None selects the combined multilayer mesh. For an individual layer, pass the same layer name and inversion slot to both registration and inversion. The layer-comparison functions perform this step internally for each candidate layer.

from lameg.invert import coregister, invert_ebb_layer

def fit_multilayer_ebb(working_copy, prepared, fids, spm):
    # Register the combined mesh to this recording before fitting across layers.
    coregister(fids, working_copy, prepared.surfaces, spm_instance=spm, viz=False)
    # Rows of the returned reconstruction matrix follow the kept vertices of
    # each layer in order. prepared.manifest records their original IDs.
    return invert_ebb_layer(
        working_copy, prepared.surfaces, forward_operator=prepared.operator,
        woi=[-25, 25], spm_instance=spm, return_mu_matrix=True, viz=False,
    )

The call returns free energy, cross-validation error, and the source reconstruction matrix. To identify an original cortical location from row r of the combined matrix, set ids = prepared.support.original_vertices and compute layer_index, i = divmod(r, len(ids)). The anatomical vertex is ids[i] on prepared.surfaces.get_layer_names()[layer_index]. Keep source_support.json with results exported for later analysis.

The same forward_operator keyword works with invert_ebb, invert_ebb_layer, invert_msp, and their three invert_sliding_window_* counterparts. A supplied operator is installed before spatial-mode preparation and is used for all time windows in that inversion. SPM keeps the attached gain in that slot. Keep its lameg_gain_*.mat cache beside the dataset.

Native SPM round trip#

This example takes a donor SPM dataset with a previously computed multilayer gain and an independent working copy of the same recording. Both must use the same head registration, sensor response and good MEG channels. Keep the donor’s gain cache beside its header.

from lameg.forward import ForwardOperator
from lameg.laminar import model_comparison

def compare_saved_forward(donor, working_copy, surfaces, fids, vertex, spm):
    # Read the gain referenced by the donor, including its channel order and
    # dipole signs, before selecting the matching layer for each inversion.
    operator = ForwardOperator.from_spm(
        donor, surfaces.get_mesh_path(), surfaces.get_layer_names()
    )
    return model_comparison(
        fids, working_copy, surfaces, method='MSP', spm_instance=spm,
        forward_operator=operator, viz=False,
        invert_kwargs=dict(priors=[vertex], patch_size=5, woi=[-25, 25]),
    )

Archived gains may contain nonzero columns at vertices with a missing dipole direction. For a numerical round trip, allow_undefined_gain=True explicitly preserves those columns. Use operator.layer(name).orientation_defined when selecting sites for oriented-source comparisons, including the vertices in a patch.

Importing MNE forwards with known vertex correspondence#

Use ForwardOperator.from_mne directly when all requested vertices are present and the correspondence is already known. Each row of vertices gives the MNE source-space index and vertex ID for one vertex in single-layer GIfTI order. For example, (1, 42) identifies vertex 42 in the second source space. Supply a single array if the mapping is identical across layers, or a dictionary keyed by layer name if it differs. Pass the recording’s good MEG channel names and physical units as an ordered mapping. The importer projects free-orientation gains onto the signed dipole directions in the GIfTI and scales each channel to its recorded unit per nA m.

Both coordinate transforms take and return points in millimetres. mri_to_head_mm maps native GIfTI MRI coordinates into the recipient SPM head frame. mne_head_to_head_mm maps MNE head coordinates into the same frame. A coregistered native operator provides native.mri_to_head_mm and dict(zip(native.channel_names, native.channel_units)).

DUNEuro FEM on the same cortical layers#

Tutorial 10 uses the subject’s CHARM mesh to simulate each cortical depth with FEM. Install the Gmsh reader with pip install -e '.[fem]' from the laMEG checkout. Build the DUNEuro Python bindings with tetrahedral continuous Galerkin support for the Python interpreter running the notebook. Verify that import duneuropy succeeds in that environment. For an MPI-enabled DUNE build, initialize its matching MPI runtime first (e.g., from mpi4py import MPI). Serial builds can run directly. Whole-head calculations need memory for the volume solver and its transfer matrix, which stores one double per active pickup and FEM degree of freedom. laMEG assembles each pickup’s flux integral on demand. By default, one worker solves all pickups and reuses the same FEM grid and solver. SPM performs the simulations and inversions.

Pass the coregistered SPM recording as reference. This supplies the MRI-to-head transform, physical coil geometry and channel weights. The LayerSurfaceSet supplies the positions and signed dipole directions. The solver uses the CHARM tetrahedra and the SimNIBS isotropic tissue conductivities. Supply a tag-to-conductivity mapping in S/m to override them. If CHARM’s T1 and the laMEG GIfTIs use different scanner coordinates, supply their measured rigid registration in millimetres as mri_to_fem_mm.

from lameg.forward import compute_duneuro_forward
from lameg.invert import coregister

# Run coregister once for this recording if it has not yet been registered.
coregister(fid_coords, base_fname, surf_set, iskull_fname=skull_fname, spm_instance=spm)
prepared = compute_duneuro_forward(
    surf_set, charm_fname, reference=base_fname, output_dir=tmp_dir, verbose=True
)
fem = prepared.operator
surfaces = prepared.surfaces

verbose=True reports which stage is running. If your allocation has spare cores and memory, try n_jobs=2 to solve two groups of pickups concurrently. Each worker needs memory for its own grid and solver. Parallel runs also write temporary pickup fields under output_dir. Choose a disk-backed directory with eight bytes per active pickup per evaluated dipole for these fields, plus space for shared inputs. With an MPI-enabled DUNE build, launch multiple workers from a standalone Python or Jupyter process.

The fitted patch-based St. Venant model uses the signed cortical link vectors. DUNEuro currently marks this source model experimental. Before computing any pickup transfer matrices, laMEG locates the cortical positions in CHARM gray matter (tissue tag 2). It checks candidate dipoles with DUNEuro’s own element search on a separate copy of the grid. On a nonconvex mesh this search can fail even for a position inside a gray-matter tetrahedron. laMEG releases the search grid before building the forward solver.

A column must pass the checks at every requested depth and belong to a surviving cortical triangle. This can remove substantial portions of the cortex at the pial or white boundary. The file at prepared.manifest lists original vertex IDs by depth. excluded_by_tissue records the anatomical tissue exclusions. excluded_by_native_search records positions where DUNEuro could not confirm gray matter. vertices_without_faces lists remaining vertices that lost all their triangles. The simulator and all three inversions in Tutorial 10 use the same retained cortical columns.

External solvers#

Construct ForwardOperator directly with a physical gain in each channel’s recorded unit per nA m. Preserve signed dipole and sensor orientations. Supply the sensor coils in head metres and the channel-by-coil transfer matrix, including reference compensation. Supply both the original MRI surface coordinates (mm) and the effective head coordinates (mm) used by the solver. This allows a solver to shift a source while preserving its anatomical vertex index and patch membership. Patch smoothing uses the requested layer surface. The comparison checks layer names, vertex order, connectivity and orientations before processing the first layer. It checks the recipient’s sensor response and reads the installed gain back through SPM before inversion.

class lameg.forward.ForwardOperator(gain: ndarray, channel_names: tuple, channel_units: tuple, layer_names: tuple, requested_mri_mm: ndarray, effective_head_mm: ndarray, orientations_head: ndarray, mri_to_head_mm: ndarray, faces: ndarray, sensor_geometry: dict, provenance: str, allow_undefined_gain: bool = False, allow_nominal_ctf_coils: bool = False)#

Bases: object

Unprojected channels × sources gain in each channel’s physical units per nA m.

Columns follow consecutive layer blocks in layer_names, each in the original GIfTI vertex order. requested_mri_mm is the native GIfTI point set. mri_to_head_mm maps its coordinates into the MEG head frame, where effective_head_mm records the actual solver positions and orientations_head gives the signed fixed current directions. Positions and directions have shape (n_sources, 3). faces is a single layer’s zero-based triangle array.

sensor_geometry contains coil positions coilpos (head metres), signed unit vectors coilori, and the channel-by-coil transfer matrix tra, including reference compensation. The transfer rows follow channel_names. provenance identifies the solver and input.

A zero direction means undefined. Set allow_undefined_gain=True explicitly to preserve legacy nonzero gain columns with missing directions. orientation_defined identifies sources usable for oriented-source comparisons. Input arrays are shared; treat them as immutable for the lifetime of this operator and its layer views. allow_nominal_ctf_coils opts into matching nominal CTF pickup coils to measured coils from the same acquisition when attaching to SPM.

__init__(gain: ndarray, channel_names: tuple, channel_units: tuple, layer_names: tuple, requested_mri_mm: ndarray, effective_head_mm: ndarray, orientations_head: ndarray, mri_to_head_mm: ndarray, faces: ndarray, sensor_geometry: dict, provenance: str, allow_undefined_gain: bool = False, allow_nominal_ctf_coils: bool = False) → None#
allow_nominal_ctf_coils: bool = False#
allow_undefined_gain: bool = False#
channel_names: tuple#
channel_units: tuple#
effective_head_mm: ndarray#
faces: ndarray#
classmethod from_mne(forwards, mesh_fname, *, vertices, channel_units, mri_to_head_mm, mne_head_to_head_mm, info=None, ignore_ref=None, allow_nominal_ctf_coils=False)#

Import precomputed MNE-Python MEG forwards on an oriented laMEG GIfTI.

forwards maps layer names in GIfTI block order to MNE Forward objects or FIF paths. vertices maps each within-layer GIfTI vertex to an integer (MNE source-space index, vertex ID) pair. Pass a single (n_columns, 2) array or one array per layer keyed by name. Every requested position must be present; extra MNE sources may be omitted.

channel_units maps the recipient’s good MEG labels to physical units in the desired row order. For compensated forwards supply the complete acquisition info and explicitly confirm the original solve used ignore_ref=False. The FIF does not record this setting. Free-orientation gains are projected onto the signed GIfTI directions. Fixed-orientation gains require collinear dipoles at defined vertices.

Supply the GIfTI MRI-to-recipient-head affine and the rigid MNE-head- to-recipient-head transform explicitly. Both map millimetres to millimetres. The latter applies to both sources and sensor coils. For matching CTF acquisitions, allow_nominal_ctf_coils=True permits small differences between nominal and measured coil geometry during SPM attachment (see the precomputed forwards guide).

classmethod from_spm(data_fname, mesh_fname, layer_names, inversion_idx=0, gain_fname=None, allow_undefined_gain=False)#

Read a saved SPM v7.3 MEG forward and its referenced gain file.

This importer supports one MEG modality, SPM’s SI-aware forward path, and an explicitly oriented laMEG GIfTI. It reads only the header and gain cache. inversion_idx is zero-based. Supply the original source mesh; if moved, gain_fname can locate the original cache by its saved basename. The header’s scale is undone once. SPM gain files contain channel labels and gain values; source correspondence depends on using the dataset’s original cache. Relocated sources require the actual original GIfTI. For native single-shell and sphere models, the saved source positions provide an additional independent check of MRI coordinates.

gain: ndarray#
layer(name)#

Return a single-layer operator retaining its explicit vertex order.

layer_names: tuple#
mri_to_head_mm: ndarray#
property n_columns#

Number of within-surface vertex indices.

property orientation_defined#

Boolean mask of sources with a defined signed current direction.

orientations_head: ndarray#
provenance: str#
requested_mri_mm: ndarray#
sensor_geometry: dict#
validate_mesh(layer_name, path)#

Require matching vertices, connectivity and signed orientations for a laMEG mesh.

Pass None for the combined mesh, or a layer name and its individual GIfTI. Effective source displacement is allowed and is recorded in head coordinates separately from the original MRI points.