simnibs.msh.ElementData

class simnibs.msh.ElementData(value, name='', mesh=None)

Bases: simnibs.msh.mesh_io.Data

Data (scalar, vector or tensor) defined in mesh elements.

Parameters
  • value (ndarray) –

    Value of field in elements. Should have the shape
    • (n_elm,) or (n_elm, 1) for scalar fields

    • (n_elm, 3) for vector fields

    • (n_elm, 9) for tensors

  • field_name (str (optional)) – name of field. Default: ‘’

  • mesh (simnibs.msh.Msh (optional)) – Mesh structure where the field is defined. Required for many methods

value

Value of field in elements

Type

ndarray

field_name

name of field

Type

str

elm_number

index of elements

Type

ndarray

nr

number of data points

Type

property

nr_comp

number of dimensions per data point (1 for scalars, 3 for vectors)

Type

property

__init__(value, name='', mesh=None)

Initialize self. See help(type(self)) for accurate signature.

Methods

__init__(value[, name, mesh])

Initialize self.

append_to_mesh(fn[, mode])

Appends this ElementData fields to a file

as_nodedata()

Converts the current ElementData instance to NodaData For more information see the elm_data2node_data method

assign_triangle_values()

In-place Assigns field value at triangle as the same as the one of the tetrahedra with a similar tag to it.

calc_flux([triangles])

Calculates the flux of a vectorial field

elm_data2node_data()

Transforms an ElementData field into a NodeData field using Superconvergent patch recovery For volumetric data.

from_data_grid(mesh, data_grid, affine[, …])

Defines an ElementData field form a mesh and gridded data

get_focality([cuttofs, peak_percentile])

Caluclates field focality as the area/volume of the mesh experiencing a field norm of above (cut_off% of the field peak).

get_percentiles([percentile, roi])

Get percentiles of field (or field norm, if a vector field)

interpolate_scattered(points[, out_fill, …])

Interpolates the ElementData into the points by finding the element containing the point and assigning the value in it

interpolate_to_grid(n_voxels, affine[, …])

Interpolates the ElementData into a grid.

interpolate_to_surface(surface[, out_fill])

Interpolates the field in the nodes of a given surface The interpolation occurs in the tetrahedra!

mean_field_norm()

Calculates V*w/sum(w) Where V is the norm of the field, and w is the volume or area of the mesh where the field is defined.

norm([ord])

Calculate the norm of the field

read_hdf5_data_matrix_row(leadfield_fn, …)

Reads a row of an hdf5 data matrix and store it as Data

summary([percentiles, focality_cutoffs, units])

Creates a text summaty of the field

to_deformed_grid(warp, reference[, out, …])

Interpolates field to a grid and apply non-linear interpolation

to_nifti(n_voxels, affine[, fn, units, …])

Transforms the data in a nifti file

view_options([v_range, percentile, visible, …])

Generates a View object with visualization opions

write(fn)

Writes this ElementData fields to a file with field information only This file needs to be merged with a mesh for visualization

write_hdf5(hdf5_fn[, path])

Writes the field to an hdf5 file

Attributes

elm_number

Element numbers (1, …, nr)

indexing_nr

Same as elm_number

nr

Number of data entries

nr_comp

Number of field components

type

NodeData of ElementData

append_to_mesh(fn, mode='binary')

Appends this ElementData fields to a file

Parameters
  • fn (str) – file name

  • mode (binary or ascii) – mode in which to write

as_nodedata()

Converts the current ElementData instance to NodaData For more information see the elm_data2node_data method

assign_triangle_values()

In-place Assigns field value at triangle as the same as the one of the tetrahedra with a similar tag to it.

calc_flux(triangles=None)

Calculates the flux of a vectorial field

Parameters

triangles (ndarray of ints (optional)) – Triangles where the flux should be calculated. Default: All

Returns

flux – total field crossing the surface

Return type

float

elm_data2node_data()

Transforms an ElementData field into a NodeData field using Superconvergent patch recovery For volumetric data. Will not work well for discontinuous fields (like E, if several tissues are used)

Returns

Structure with NodeData

Return type

simnibs.NodeData

References

Zienkiewicz, Olgierd Cecil, and Jian Zhong Zhu. “The superconvergent patch recovery and a posteriori error estimates. Part 1: The recovery technique.” International Journal for Numerical Methods in Engineering 33.7 (1992): 1331-1364.

elm_number

Element numbers (1, …, nr)

classmethod from_data_grid(mesh, data_grid, affine, field_name='', **kwargs)

Defines an ElementData field form a mesh and gridded data

Parameters
  • mesh (Msh()) – Mesh structure where the field is to be interpolated

  • data_grid (ndarray) – Array of 3 or 4 dimensions with data

  • affine (4x4 ndarray) – Array describing the affine transformation from the data grid to the mesh space

  • kwargs (see the scipy.ndimage.map_coordinates documentation) –

get_focality(cuttofs=[50, 70], peak_percentile=99.9)

Caluclates field focality as the area/volume of the mesh experiencing a field norm of above (cut_off% of the field peak). peak_percentile gives what is the field peak

Parameters
  • cuttofs (ndarray (optional)) – Percentage of the peak value for the cut_off, between 0 and 100. Default: [50, 70]

  • peak_percentile (float (optional)) – Percentile to be used to calculate peak value. Default: 99.9

Returns

focality – Area/volume exceeding the cuttof of the peak value

Return type

ndarray

get_percentiles(percentile=[99.9], roi=None)

Get percentiles of field (or field norm, if a vector field)

Parameters
  • percentile (ndarray (optional)) – Percentiles of interest, between 0 and 100. Defaut: 99.9

  • roi (ndarray (optinal)) – Region of interest in terms of element/node indices. Default: the whole mesh

  • Returnts

  • ----------

  • f_p (ndarray) – Field at the given percentiles

indexing_nr

Same as elm_number

interpolate_scattered(points, out_fill=nan, method='linear', continuous=False, squeeze=True)

Interpolates the ElementData into the points by finding the element containing the point and assigning the value in it

Parameters
  • points (Nx3 ndarray) – List of points where we want to interpolate

  • out_fill (float) – Value to be goven to points outside the volume, if ‘nearest’ assigns the nearest value (default: NaN)

  • method ({'assign' or 'linear'} (Optional)) – If ‘assign’, gives to each voxel the value of the element that contains it. If linear, first assign fields to nodes, and then perform baricentric interpolatiom. Default: linear

  • continuous (bool) – Wether fields is continuous across tissue boundaries. Changes the behaviour of the function only if method == ‘linear’. Default: False

  • squeeze (bool) – Wether to squeeze the output. Default: True

  • Returns

  • -------

  • f (np.ndarray) – Value of function in the points

interpolate_to_grid(n_voxels, affine, method='linear', continuous=False)
Interpolates the ElementData into a grid.

finds which tetrahedra contais the given voxel and assign the value of the tetrahedra to the voxel.

Parameters
  • n_voxels (list or tuple) – number of voxels in x, y, and z directions

  • affine (ndarray) – A 4x4 matrix specifying the transformation from voxels to xyz

  • method ({'assign' or 'linear'} (Optional)) – If ‘assign’, gives to each voxel the value of the element that contains it. If linear, first assign fields to nodes, and then perform baricentric interpolatiom. Default: linear

  • continuous (bool) – Wether fields is continuous across tissue boundaries. Changes the behaviour of the function only if method == ‘linear’. Default: False

Returns

image – An (n_voxels[0], n_voxels[1], n_voxels[2], nr_comp) matrix with interpolated values. If nr_comp == 1, the last dimension is squeezed out

Return type

ndarray

interpolate_to_surface(surface, out_fill='nearest')

Interpolates the field in the nodes of a given surface The interpolation occurs in the tetrahedra!

Parameters
  • surface (Msh) – Mesh structure with triangles only

  • out_fill (float or 'nearest' (optional)) – Value to be assigned to the points in the surface outside the volume.

Returns

node_data – Node data structure with the interpolated field

Return type

NodeData

mean_field_norm()

Calculates V*w/sum(w) Where V is the norm of the field, and w is the volume or area of the mesh where the field is defined. This can be used as a focality metric. It should give out small values when the field is focal and

Returns

eff_area – Area or volume of mesh, weighted by the field

Return type

float

norm(ord=2)

Calculate the norm of the field

Parameters

ord (float) – Order of norm. Default: 2 (euclidian norm)

Returns

norm – NodeData field with the norm the field

Return type

NodeData

nr

Number of data entries

nr_comp

Number of field components

classmethod read_hdf5_data_matrix_row(leadfield_fn, field_name, row)

Reads a row of an hdf5 data matrix and store it as Data

Parameters
  • leadfield_fn (str) – Name of file with leadfield

  • field_name (str) – name of field

  • row (int) – number of the row to be read

Returns

data – instance with the fields

Return type

Data()

summary(percentiles=(99.9, 99, 95), focality_cutoffs=(75, 50), units=None)

Creates a text summaty of the field

Parameters
  • percentiles (ndarray (optinal)) – Field percentiles to be printed. Default: (99.9, 99, 95)

  • focality_cutoffs (ndarray (optional)) – Cuttofs for focality calculations. Default: (75, 50)

  • units (str or None) – Name of field units or automatically determine from name

to_deformed_grid(warp, reference, out=None, out_original=None, tags=None, order=3, method='linear', continuous=False, inverse_warp=None, reference_original=None, binary=False)

Interpolates field to a grid and apply non-linear interpolation

We first interpolate to a grid and then apply the transformation in order to avoid problems from deformed triangles

Parameters
  • warp (str) – Name of file with the transformation. Can either be a nifti file where each voxel corresponds to coordinates (x, y, z) in the original space or an affine transformation defined from the target space to the original space. In the later case, the name must finish in “.mat”, and it will be read with the numpy loadtxt file

  • ref (str) – Name of reference file. The output will be in the same space as the reference (same affine transfomation and same dimensions)

  • out (str (optional)) – If not None, the result will be written to this file as a nifti

  • out_original (str (optional)) – If not None, the volume in the original grid be written to this file as a nifti

  • tags (list (options)) – Mesh tags to be transformed. Defaut: transform the entire mesh

  • order (int) – Interpolation order to be used

  • method ({'assign' or 'linear'} (Optional)) – Method for gridding the data. If ‘assign’, gives to each voxel the value of the element that contains it. If linear, first assign fields to nodes, and then perform baricentric interpolatiom. Only for ElementData input. Default: linear

  • continuous (bool) – Wether fields is continuous across tissue boundaries. Changes the behaviour of the function only if method == ‘linear’. Default: False

  • inverse_warp (str) – Name of nifti file with inverse the transformation. Used to rotate vectors to the target space in the case of non-liner transformations. If the transformation is linear, the inverse matrix is used.

  • reference_original (str) – Name of nifti file with reference in the original space. Used to determine the dimensions and affine transformation for the initial griding

  • Returns

  • --------

  • img (nibabel.Nifti1Pair) – Nibabel image object with tranformed field

to_nifti(n_voxels, affine, fn=None, units='mm', qform=None, method='linear', continuous=False)

Transforms the data in a nifti file

Parameters
  • n_voxels (list of ints) – Number of vexels in each dimension

  • affine (4x4 ndarray) – Transformation of voxel space into xyz. This sets the sform

  • fn (str (optional)) – String with file name to be used, if the result is to be saved

  • units (str (optional)) – Units to be set in the NifTI header. Default: mm

  • qform (4x4 ndarray (optional)) – Header qform. Default: set the same as the affine

  • method ({'assign' or 'linear'} (Optional)) – If ‘assign’, gives to each voxel the value of the element that contains it. If linear, first assign fields to nodes, and then perform baricentric interpolatiom. Only for ElementData input. Default: linear

  • continuous (bool) – Wether fields is continuous across tissue boundaries. Changes the behaviour of the function only if method == ‘linear’. Default: False

Returns

img – Image object with the field interpolated in the voxels

Return type

nibabel.Nifti1Pair

type

NodeData of ElementData

view_options(v_range='auto', percentile=False, visible=True, visible_tags=None, saturate=True, idx=None)

Generates a View object with visualization opions

Parameters
  • v_range ([min, max] or 'auto' (optional)) – Range of the values to be displayed. Defaut: will automatically try to find a good range (0.1 - 99.9% percentile for positive or vector data, symetrical for two-sided data)

  • percentile (bool (optional)) – Whether the values in v_range arre given in percentile (between 0 and 100). Default: False

  • visible (bool (optional)) – Whether to turn on visualization of this field. Default: True

  • visible_tags (list (optional)) – List of tags to be visible. Will also be used to calulate field ranges in ‘auto’ mode or if percentile=True. Default: all tags

  • saturate (bool (optional)) – Whether to saturate values. Default: true

  • idx (int (optional)) – Index of this field in the mesh

Returns

view – view object

Return type

gmsh_visualization.View

write(fn)

Writes this ElementData fields to a file with field information only This file needs to be merged with a mesh for visualization

Parameters
  • fn (str) – file name

  • mode (binary or ascii) – mode in which to write

write_hdf5(hdf5_fn, path='./')

Writes the field to an hdf5 file

Parameters
  • hdf5_fn (str) – file name of hdf5 file

  • path (str) – path in the hdf5 file where the field should be saved