Finite element model from labels

The main problems in shamo depend on a finite element model to serve as a support for the computation. Generating such a model can be achieved in a few lines of code.

To start, we import the FEM class and initialize a model with a name and a parent directory.

[ ]:
from shamo import FEM

model = FEM("fem_from_labels", "../../derivatives")
[ ]:
import logging
import sys

logger = logging.getLogger("shamo")
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(logging.Formatter("[{levelname}] {message}", style="{"))

Mesh generation

Several methods can be used ot generate the mesh:

  • mesh_from_array()

  • mesh_from_nii()

  • mesh_from_masks()

  • mesh_from_niis()

All those methods skip the step of generating surfaces and allow us to directly produce a high definition mesh from the segmented image. Here, we start from a labelled volume created from the well known Suzanne model from Blender.


Several parameters can be used to refine the mesh. Make sure to tweak them to obtain the mesh you want.

[ ]:
from pathlib import Path

data_path = Path("../../rawdata/suzanne")
    data_path / "suzanne_labels.nii",
    ["wm", "gm", "scalp"],

After this first step, a mesh built of triangles and tetrahedra and annotated with the name of the tissues is saved to the directory of the object.

Sensors additions

Sensors can be added to the mesh with the following methods:

  • add_point_sensor() and the partials add_point_sensor_on() and add_point_sensor_in()

  • add_point_sensors() and the partials add_point_sensors_on() and add_point_sensors_in()

  • add_point_sensors_from_tsv() and the partials add_point_sensors_from_tsv_on() and add_point_sensors_from_tsv_in()

In the case of Suzanne, the electrodes are defined in a TSV file with the format:

Electrodes TSV file









[ ]:
import numpy as np
from pathlib import Path

model.add_point_sensors_from_tsv(data_path / "suzanne_sensors.tsv", "scalp", 2)

Now the model also includes the sensors modelled as points.

Field addition

Scalar, vector and tensor fields can be required to model some properties of the model. Such fields can be added to the mesh with the methods:

  • field_from_elems()

  • field_from_array()

  • field_from_nii()

For Suzanne, a fake anisotropy tensor for the white matter is stored in a NIFTI file as a 4 dimensional volume.

[ ]:
model.field_from_nii("dti", data_path / "suzanne_dti.nii.gz", "wm", fill_val=[1, 0, 0, 0, 1, 0, 0, 0, 1], formula="{sigma[wm]}", nearest=False, resize=False)

The model for Suzanne is now up and ready to get used in a problem.