pymeshtool
- create_image(shape, itk_dtype, *, num_comp=1, origin=None, voxel_size=None)
Create an empty image with a given shape and type.
- Parameters:
shape (tuple[int, int, int]) – Size in the X, Y, and Z directions.
itk_dtype (int) – Image data type.
num_comp (int, optional, default=1) – Number of components per pixel (max: 4).
origin (tuple[float, float, float], optional, default=None) – The X, Y, and Z coordinates of the image origin.
voxel_size (tuple[float, float, float], optional, default=None) – Voxel size in the X, Y, and Z directions.
- Returns:
The generated image object.
- Return type:
Image
- Raises:
TypeError – If the shape object is None.
PyMeshToolError – If the shape object cannot be converted to the correct C++ container.
ValueError – If the shape object has negative entries.
ValueError – If the data type is unknown.
PyMeshToolError – If the origin object cannot be converted to the correct C++ container.
PyMeshToolError – If the voxel size object cannot be converted to the correct C++ container.
ValueError – If the voxel size object has negative entries.
See also
# create the image img = pymeshtool.create_image((10, 10, 10), pymeshtool.ImageDType.int8, origin=(-5.0, -5.0, -5.0), voxel_size=(1.0, 1.0, 1.0)) # set voxel data img.voxels[:,:,5] = 17 img.voxels[0,0,0] = 1 img.voxels[1:3,0,0] = 2 img.voxels[0,1:3,0] = 3 img.voxels[0,0,1:3] = 4 # save image img.save('image.nrrd')
- create_mesh(points, elem2node_dsp, elem2node_con, elem_types, *, elem_tags=None, num_fibers=1, refine_uniform=0)
Create a mesh from a point cloud and an element-to-node graph. The element-to- node graph is defined by the displacement array, elem2node_dsp, and the connectivity array, elem2node_con. The connectivity array contains the indices of the points that span each element, while the displacement array specifies the start index in the connectivity array.
- Parameters:
points (ndarray[float]) – Nx3 points array.
elem2node_dsp (ndarray[int]) – Element-to-node displacement array.
elem2node_con (ndarray[int]) – Element-to-node connectivity array.
elem_types (ndarray[int]) – Element type array.
elem_tags (ndarray[int], optional, default=None) – Element tag array.
num_fibers (int, optional, default=1) – Number of fibers per element, either 1 or 2.
refine_uniform (int, optional, default=0) – Number of uniform refinement iterations.
- Returns:
The generated mesh object.
- Return type:
Mesh
- Raises:
ValueError – If the points array is empty or has the wrong shape.
ValueError – If the element-to-node displacement array is empty.
ValueError – If the element-to-node connectivity array is empty.
ValueError – If the element type array is empty.
PyMeshToolError – If the points array cannot be converted to the correct C++ container.
PyMeshToolError – If the element-to-node displacement array cannot be converted to the correct C++ container.
PyMeshToolError – If the element-to-node connectivity array cannot be converted to the correct C++ container.
PyMeshToolError – If the element type array cannot be converted to the correct C++ container.
PyMeshToolError – If the element tags array cannot be converted to the correct C++ container.
ValueError – If the element arrays are not consistent.
# define 4 points in 3D points = [[0, 0, 0], [1, 0, 0], [0, 1, 0], [1, 1, 0]] # define triangle connectivity array # T0 = (0, 1, 2) # T1 = (1, 3, 2) e2ncon = [0, 1, 2, 1, 3, 2] # start indices in the `e2ncon` array # T0 starts at 0 # T1 starts at 3 # followed by the total number of # indices in the `e2ncon` array e2ndsp = [0, 3, 6] # the element types (2 triangles) etypes = [pymeshtool.ElementType.tri, pymeshtool.ElementType.tri] # create the mesh mesh = pymeshtool.create_mesh(points, e2ndsp, e2ncon, etypes)
- get_max_par_threads()
Get the maximum number of parallel OpenMP threads.
- Returns:
Maximum number of OpenMP threads.
- Return type:
int
- get_meshtool_git_info()
Get Git information about MeshTool.
- Returns:
The Git hash, branch, and commit date of MeshTool.
- Return type:
tuple[str, str, str]
- get_num_par_threads()
Get the number of parallel OpenMP threads in use.
- Returns:
Number of OpenMP threads used
- Return type:
int
- load_fibers(filename)
Read fibers from a CARP fiber file. Can be a text file (*.lon) or a binary file (*.blon).
- Parameters:
filename (str) – Path to the fiber file.
- Returns:
None - If the loaded data is empty or has the wrong dimensions.
ndarray[float] - The fibers array.
- Return type:
None or ndarray[float]
- Raises:
FileNotFoundError – If the file does not exist.
ValueError – If the format is neither a lon nor a blon file.
IOError – If an error occurrs while reading the file.
PyMeshToolError – If the data cannot be converted to a NumPy array.
- load_points(filename)
Read points from a CARP point file. Can be a text file (*.pts) or a binary file (*.bpts).
- Parameters:
filename (str) – Path to the point file.
- Returns:
None - If the loaded data is empty.
ndarray[float] - The points array.
- Return type:
None or ndarray[float]
- Raises:
FileNotFoundError – If the file does not exist.
ValueError – If the format is neither a pts nor a bpts file.
PyMeshToolError – If the data cannot be converted to a NumPy array.
- load_vtx(filename)
Read vertex indices from a CARP vtx file.
- Parameters:
filename (str) – Path to the vertex file.
- Returns:
None - If the loaded data is empty.
tuple[ndarray[int], str] - The vertex indices and the domain the vertices are defined for.
- Return type:
None or tuple[ndarray[int], str]
- Raises:
FileNotFoundError – If the file does not exist.
ValueError – If the format is not a vtx file.
IOError – If an error occurred while reading the file.
PyMeshToolError – If the data cannot be converted to a NumPy array.
- save_fibers(fibers, filename)
Save fibers to a CARP fiber file. Can be a text file (*.lon) or a binary file (*.blon).
- Parameters:
fibers (ndarray[float]) – The fibers to save.
filename (str) – Path to the fibers file.
- Return type:
None
- Raises:
ValueError – If the format is neither a lon nor a blon file.
PyMeshToolError – If the data cannot be converted to the correct C++ container.
- save_points(pnts, filename)
Save points to a CARP points file. Can be a text file (*.pts) or a binary file (*.bpts).
- Parameters:
pnts (ndarray[float]) – The points array.
filename (str) – Path to the points file.
- Return type:
None
- Raises:
ValueError – If the format is neither a pts nor a bpts file.
PyMeshToolError – If the data cannot be converted to the correct C++ container.
- save_vtx(vtxdata, filename, *, domain='intra')
Write vertex indices to a CARP vtx file.
- Parameters:
vtxdata (ndarray[int]) – The vertex data to write.
filename (str) – Path to the vertex file.
domain (str, optional, default='intra') – The domain the vertices are defined on. Choices are:
intra: intracallular domain,extra: extracellular domain
- Return type:
None
- Raises:
ValueError – If the format is not a vtx file.
IOError – If an error occurred while writing the file.
PyMeshToolError – If the data cannot be converted to the correct C++ container.
- set_num_par_threads(np)
Set the number of parallel OpenMP threads to be used.
- Parameters:
np (int) – Number of parallel threads.
- Return type:
None
- class Mesh
PyMeshTool Mesh object. Wrapper class for the meshtool mt_meshdata structure.
Class Attributes
- element_tags
Set or get the element tags in the mesh.
- Type:
ndarray[int] - The new element tags of the same size.
- Returns:
Array of the element tags in the mesh.
- Return type:
ndarray[int]
- Raises:
RuntimeError – If the mesh object has not been initialized correctly.
PyMeshToolError – If the tag data cannot be converted to a NumPy array.
PyMeshToolError – If the new tag data cannot be converted to the correct C++ container.
ValueError – If the new tag data array has the wrong shape.
Attention
The attribute returns a NumPy array that provides access to the existing tag data of the underlying mesh structure without owning the data. This means that the mesh object is not deleted as long as there are NumPy arrays referencing the tag data.
- elements
Get the element-to-node graph of the mesh.
- Returns:
Tuple holding the element-to-node (e2n) graph. The first array holds the number of nodes per element (e2n_cnt), the second array holds the offset in the connectivity array (e2n_dsp), the third array holds the nodal connectivity (e2n_con), and the fourth array holds the element types.
- Return type:
tuple[ndarray[int], ndarray[int], ndarray[int], ndarray[int]]
- Raises:
RuntimeError – If the mesh object has not been initialized correctly.
PyMeshToolError – If the e2n_cnt data cannot be converted to a NumPy array.
PyMeshToolError – If the e2n_dsp data cannot be converted to a NumPy array.
PyMeshToolError – If the e2n_con data cannot be converted to a NumPy array.
PyMeshToolError – If the etypes data cannot be converted to a NumPy array.
# load mesh from file mesh = pymeshtool.Mesh('mesh', format='carp_txt') # get mesh elements elements = mesh.elements # get element-to-node (e2n) graph components e2ncnt, e2ndsp, e2ncon, etypes = elements for i in range(len(e2ncnt)): cnt, dsp = e2ncnt[i], e2ndsp[i] con = e2ncon[dsp:dsp+cnt] print(con, etypes[i])
Attention
The attribute returns a tuple of NumPy arrays that provides access to the existing graph data of the underlying mesh structure without owning the data. This means that the mesh object is not deleted as long as there are NumPy arrays referencing the graph data.
- fibers
Set or get the fibers in the mesh.
- Type:
ndarray[float] - The new fiber data of the same size.
- Returns:
Array of the fibers in the mesh.
- Return type:
ndarray[float]
- Raises:
RuntimeError – If the mesh object has not been initialized correctly.
PyMeshToolError – If the fiber data cannot be converted to a NumPy array.
PyMeshToolError – If the new fiber data cannot be converted to the correct C++ container.
ValueError – If the new fiber data array has the wrong shape.
Attention
The attribute returns a NumPy array that provides access to the existing fiber data of the underlying mesh structure without owning the data. This means that the mesh object is not deleted as long as there are NumPy arrays referencing the fiber data.
- n2e_graph
Get the node-to-element graph of the mesh.
- Returns:
None - If the node-to-element graph is empty.
tuple[ndarray[int], ndarray[int], ndarray[int]] - Tuple holding the node-to-element (n2e) graph. The first array holds the number of attached elements (n2e_cnt), the second array holds the offset in the connectivity array (n2e_dsp), and the third array holds the connectivity (n2e_con).
- Return type:
None or tuple[ndarray[int], ndarray[int], ndarray[int]]
- Raises:
RuntimeError – If the mesh object has not been initialized correctly.
PyMeshToolError – If the n2e_cnt data cannot be converted to a NumPy array.
PyMeshToolError – If the n2e_dsp data cannot be converted to a NumPy array.
PyMeshToolError – If the n2e_con data cannot be converted to a NumPy array.
See also
# load mesh from file mesh = pymeshtool.Mesh('mesh', format='carp_txt', compute_connectivity=True) # get mesh node-to-element (n2e) graph n2egraph = mesh.n2e_graph # get node-to-element (n2e) graph components n2ecnt, n2edsp, n2econ = n2egraph for i in range(len(n2ecnt)): cnt, dsp = n2ecnt[i], n2edsp[i] con = n2econ[dsp:dsp+cnt] print(con)
Attention
The attribute returns a tuple of NumPy arrays that provides access to the existing graph data of the underlying mesh structure without owning the data. This means that the mesh object is not deleted as long as there are NumPy arrays referencing the graph data.
- n2n_graph
Get the node-to-node graph of the mesh. The nodal connectivity is defined by the elements. This means that two nodes are connected if they are attached to the same element.
- Returns:
None - If the node-to-node graph is empty.
tuple[ndarray[int], ndarray[int], ndarray[int]] - Tuple holding the node-to-node (n2n) graph. The first array holds the number of neighboring nodes (n2n_cnt), the second array holds the offset in the connectivity array (n2n_dsp), and the third array holds the nodal connectivity (n2n_con).
- Return type:
None or tuple[ndarray[int], ndarray[int], ndarray[int]]
- Raises:
RuntimeError – If the mesh object has not been initialized correctly.
PyMeshToolError – If the n2n_cnt data cannot be converted to a NumPy array.
PyMeshToolError – If the n2n_dsp data cannot be converted to a NumPy array.
PyMeshToolError – If the n2n_con data cannot be converted to a NumPy array.
See also
# load mesh from file mesh = pymeshtool.Mesh('mesh', format='carp_txt', compute_connectivity=True) # get mesh node-to-node (n2n) graph n2ngraph = mesh.n2n_graph # get node-to-node (n2n) graph components n2ncnt, n2ndsp, n2ncon = n2ngraph for i in range(len(n2ncnt)): cnt, dsp = n2ncnt[i], n2ndsp[i] con = n2ncon[dsp:dsp+cnt] print(con)
Attention
The attribute returns a tuple of NumPy arrays that provides access to the existing graph data of the underlying mesh structure without owning the data. This means that the mesh object is not deleted as long as there are NumPy arrays referencing the graph data.
- num_elements
Get the number of elements in the mesh.
- Returns:
The number of elements in the mesh.
- Return type:
int
- Raises:
RuntimeError – If the mesh object has not been initialized correctly.
- num_fibers
Get the number of fibers in the mesh. The value should be one of {0, 1, 2}.
- Returns:
The number of fibers in the mesh.
- Return type:
int
- Raises:
RuntimeError – If the mesh object has not been initialized correctly.
RuntimeError – If the fibers array has an invalid shape.
- num_points
Get the number of points in the mesh.
- Returns:
The number of points in the mesh.
- Return type:
int
- Raises:
RuntimeError – If the mesh object has not been initialized correctly.
RuntimeError – If the points array has an invalid shape.
- points
Get or set the points of the mesh.
- Type:
ndarray[float] - The new point data of the same size.
- Returns:
Array of the points in the mesh.
- Return type:
ndarray[float]
- Raises:
RuntimeError – If the mesh object has not been initialized correctly.
PyMeshToolError – If the point data cannot be converted to a NumPy array.
PyMeshToolError – If the new point data cannot be converted to the correct C++ container.
ValueError – If the new point data array has the wrong shape.
# load mesh from file mesh = pymeshtool.Mesh('mesh', format='carp_txt') # get mesh points pnts = mesh.points # scale mesh points mesh.points *= 1000.0
Attention
The attribute returns a NumPy array that provides access to the existing point data of the underlying mesh structure without owning the data. This means that the mesh object is not deleted as long as there are NumPy arrays referencing the point data.
Class Functions
- __deepcopy__()
Deep-copy operator. This function is triggered by the copy.deepcopy() function.
- Returns:
A deep copy of the mesh.
- Return type:
Mesh
- Raises:
RuntimeError – If the mesh object has not been initialized correctly.
- __getitem__(i)
Get the i-th element of the mesh. This function is triggered by the subscription operator self[i].
- Parameters:
i (int) – The index of the element.
- Returns:
Tuple holding the nodal connectivity, the element type, and the element tag.
- Return type:
tuple[ndarray[int], int, int]
- Raises:
PyExc_IndexError – If the index is out of range.
See also
# load torso model tor_mesh = pymeshtool.Mesh("torso_mesh.elem") # iterate over elements for i in range(len(tor_mesh)): e2ncon, elmtype, elmtag = tor_mesh[i] print(e2ncon, elmtype, elmtag)
- __init__(basename, *, format='carp_txt', compute_connectivity=True, num_fibers=0)
Create a new mesh object by loading it from a file.
- Parameters:
basename (str) – Basename of the file from which the mesh should be loaded.
format (str, optional, default='carp_txt') – Format of the mesh file. Choices are:
carp_txt: CARP text format,carp_bin: CARP binary format,vtk: VTK text format,vtk_bin: VTK binary format,vtu: VTU format,mmg: MMG format,neu: EnSight format,obj: object format,off: off format,gmsh: Gmsh format,stellar: Stellar format,purk: Purkinje format,vcflow: vcflow formatcompute_connectivity (bool, optional, default=True) – If True, the full mesh connectivity is computed after the mesh has been loaded.
num_fibers (int, optional, default=0) – Should be a value in {0, 1, 2}. Change the number of fibers in the mesh. If num_fibers =0, the number of fibers will not be changed. If num_fibers =1 and the number of fibers in the mesh is 2, then the sheet fibers are removed. If num_fibers =2 and the number of fibers in the mesh is 1, then sheet fibers are added and longitudinal-orthogonal fibers are assigned.
- Returns:
The new mesh object loaded from basename.
- Return type:
Mesh
- Raises:
RuntimeError – If the mesh object has not been initialized correctly.
ValueError – If the mesh format is unknown.
ValueError – If the number of fibers is not valid.
RuntimeError – If changing the fiber number fails.
See also
- __len__()
Get the number of elements in the mesh. This function is triggered by the len() function.
- Returns:
The number of elements in the mesh.
- Return type:
int
- apply_split(splitop, *, return_mapping=False)
Apply a split to a given mesh that is defined by the split operation splitop. The format of the split operations is: tagA1,tagA2,..:tagB1,../tagA1,..:tagB1../.. where ‘,’ separates tags, ‘:’ separates tag groups to split, ‘/’ separates split operations. The splitting is applied to the elements defined by the ‘tagA’ tags, so these must not repeat between several split operations!
- Parameters:
splitop (str) – String defining the split operation.
return_mapping (bool, optional, default=False) – If True, the mapping object is returned.
- Returns:
None - If splitop generates an empty split-list.
Mesh - The split mesh.
tuple[Mesh, Mapping] - If return_mapping is True, the split mesh and the corresponding mapping object.
- Return type:
None or Mesh or tuple[Mesh, Mapping]
- Raises:
RuntimeError – If the mesh object has not been initialized correctly.
ValueError – If the split operation is empty or the parsing fails.
- clean_topology(*, threshold=None)
Clean the mesh of invalid topology definitions. This includes removing duplicate points and elements, as well as removing tetrahedra with zero volume and/or triangles with zero area.
- Parameters:
threshold (float, optional, default=None) – Distance threshold when checking co-location of vertices.
- Returns:
The cleaned mesh or the mesh itself.
- Return type:
Mesh
- Raises:
RuntimeError – If the mesh object has not been initialized correctly.
- clear_full_connectivity()
Clear the node-to-element and the node-to-node connectivity graphs.
- Return type:
None
- Raises:
RuntimeError – If the mesh object has not been initialized correctly.
- compute_full_connectivity()
Compute the node-to-element (n2e) and the node-to-node (n2n) connectivity graphs of the mesh.
- Return type:
None
- Raises:
RuntimeError – If the mesh object has not been initialized correctly.
- connected_vtx_components(selection)
Split a vertex selection into its connected components. Two components are connected if they share at least one common vertex. If a connected component cannot be converted to a NumPy array, None is inserted in the tuple instead.
- Parameters:
selection (ndarray[int]) – List of selected vertices.
- Returns:
None - If no connected components were found.
tuple[ndarray[int], …] - Tuple of the connected vertex selections.
- Return type:
None or tuple[ndarray[int], …]
- Raises:
RuntimeError – If the mesh object has not been initialized correctly.
PyMeshToolError – If the selection data cannot be converted to the correct C++ container.
- correspondence(mesh, *, nodal=True)
Compute nodal or element correcpondence between two meshes.
- Parameters:
mesh (Mesh) – Mesh to generate the correspondence for.
nodal (bool, optional, default=True) – If True, the nodal correspondence will be generated, otherwise, the element-wise correspondence with respect to their center points.
- Returns:
Index of the corresponding entity in mesh and the Euclidean distance.
- Return type:
tuple[ndarray[int], ndarray[float]]
- Raises:
RuntimeError – If the mesh object has not been initialized correctly.
PyMeshToolError – If the index array cannot be converted to a NumPy array.
PyMeshToolError – If the distance array cannot be converted to a NumPy array.
- extract_element_nodes()
Get a list of all nodes to which an element is attached.
- Returns:
None - If the list of nodes is empty.
ndarray[int] - List of all nodes to which an element is attached.
- Return type:
None or ndarray[int]
- Raises:
RuntimeError – If the mesh object has not been initialized correctly.
PyMeshToolError – If the node data cannot be converted to a NumPy array.
- extract_elements(indices, *, compute_connectivity=True, return_mapping=False)
Extract a sub-mesh defined by a list of element indices.
- Parameters:
indices (int | ndarray[int]) – List of element indices to extract from the mesh.
compute_connectivity (bool, optional, default=True) – If True, the full mesh connectivity is computed after the mesh was extracted.
return_mapping (bool, optional, default=False) – If True, the mapping object is returned.
- Returns:
None - If no element indices are in the mesh or the entire mesh would be extracted.
Mesh - If a sub-mesh was extracted and return_mapping is False.
tuple[Mesh, Mapping] - If a sub-mesh was extracted and return_mapping is True.
- Return type:
None or Mesh or tuple[Mesh, Mapping]
- Raises:
RuntimeError – If the mesh object has not been initialized correctly.
PyMeshToolError – If the tags object cannot be converted to an integer nor to the correct C++ container.
ValueError – If the tags array is empty.
See also
- extract_gradient(data, *, nodal_input=True, return_nodal=False, normalize=False, norm_threshold=0.0)
Compute gradient and its magnitude of a scalar function given for the mesh.
- Parameters:
data (ndarray[float]) – Scalar input data.
nodal_input (bool, optional, default=True) – True if data is defined on the points, False if defined on the elements.
return_nodal (bool, optional, default=False) – True if nodal data should be returned, False for element data.
normalize (bool, optional, default=False) – If True, the gradient vectors get normalized.
norm_threshold (float, optional, default=0.0) – Threshold value for vector normalization.
- Returns:
Magnitude of the gradient vectors and the gradient vectors.
- Return type:
tuple[ndarray[float], ndarray[float]]
- Raises:
RuntimeError – If the mesh object has not been initialized correctly.
PyMeshToolError – If the input data cannot be converted to the correct C++ container.
PyMeshToolError – If the output data cannot be converted to a NumPy array.
- extract_mesh(tags, *, compute_connectivity=True, return_mapping=False)
Extract a sub-mesh defined by a list of element tags from a given mesh.
- Parameters:
tags (int | ndarray[int]) – List of element tags defining the sub-mesh.
compute_connectivity (bool, optional, default=True) – If True, the full mesh connectivity is computed after the mesh was extracted.
return_mapping (bool, optional, default=False) – If True, the mapping object is returned.
- Returns:
None - If no region tag was found in the mesh or the entire mesh would be extracted.
Mesh - If a sub-mesh was extracted and return_mapping is False.
tuple[Mesh, Mapping] - If a sub-mesh was extracted and return_mapping is True.
- Return type:
None or Mesh or tuple[Mesh, Mapping]
- Raises:
RuntimeError – If the mesh object has not been initialized correctly.
PyMeshToolError – If the tags object cannot be converted to an integer nor to the correct C++ container.
ValueError – If the tags array is empty.
See also
- extract_myocard(*, threshold=0.0, compute_connectivity=True, return_mapping=False)
Extract the myocardial sub-mesh. All elements with non-zero fibers are considered to be myocardial tissue.
- Parameters:
threshold (float, optional, default=0.0) – Fibers with a length greater than the threshold value are considered as myocardium.
compute_connectivity (bool, optional, default=True) – If True, the full mesh connectivity is computed after the mesh was extracted.
return_mapping (bool, optional, default=False) – If True, the mapping object is returned.
- Returns:
None - If no fibers are defined or no myocardial region was found in the mesh or the entire mesh defines the myocardial sub-mesh.
Mesh - If a myocardial region was extracted and return_mapping is False.
tuple[Mesh, Mapping] - If a myocardial region was extracted and return_mapping is True.
- Return type:
None or Mesh or tuple[Mesh, Mapping]
- Raises:
RuntimeError – If the mesh object has not been initialized correctly.
ValueError – If the threshold value is negative.
See also
- extract_surface(*, setops='', coords=None, edge_threshold=0.0, angle_threshold=0.0, distance=0.0, lower_distance=0.0, hybrid_meshes=True, flip_normals=False, reindex_nodes=True, return_mapping=False)
Extract a sequence of surfaces defined by set operations on element tags. The format of the operations is: tagA1,tagA2,[surfA1,surfA2..]..[+-:]tagB1,tagB2,[surfB1,surfB2..].. where tag regions separated by ‘,’ will be unified into sub-meshes and their surface is computed. Alternatively, surfaces can be provided directly by *.surf files (only basename, no extension). If two surfaces are separated by ‘-’, the rhs surface will be removed from the lhs surface (set difference). Similarly, using ‘+’ will compute the surface union and if the sub-meshes are separated by ‘:’, the set intersection of the two sub-mesh surfaces will be computed. Individual operations are separated by ‘;’. An empty set operation will extract the entire surface. If coordinates are provided by the coords argument, the extracted surfaces will be further restricted to those elements reachable by surface edge- traversal starting from the surface vertices closest to the given points. Blocking edges can be defined by setting the edge_threshold value. If angle_threshold is specified, vertices are blocked where the angle between the normal vector and the normal vector of the start vertex is greater than the threshold value. To restrict the size of the surface edge-traversal, the arguments distance and lower_distance can be specified.
- Parameters:
setops (str, optional, default='') – Set operations defining the surfaces.
coords (ndarray[float], optional, default=None) – Start points for the surface edge-traversal.
edge_threshold (float, optional, default=0.0) – Sharp edge angle blocking surface edge-traversal.
angle_threshold (float, optional, default=0.0) – Normal vector angle blocking surface edge-traversal.
distance (float, optional, default=0.0) – Edge-traversal upper distance.
lower_distance (float, optional, default=0.0) – Edge-traversal lower distance.
hybrid_meshes (bool, optional, default=True) – If False, hybrid surfaces are converted to triangular surfaces.
flip_normals (bool, optional, default=False) – If True, ordering is changed to flip the normal vectors.
reindex_nodes (bool, optional, default=True) – If True, nodes in the surface meshes are reindexed and their point arrays are restricted.
return_mapping (bool, optional, default=False) – If True, the mapping object is returned.
- Returns:
None - If no surface was extracted.
tuple[Mesh, …] - Tuple of the extracted surface meshes.
tuple[tuple[Mesh, Mapping], …] - If return_mapping is True, a tuple of pairs with the extracted surface meshes and the corresponding mapping objects is returned.
- Return type:
None or tuple[Mesh, …] or tuple[tuple[Mesh, Mapping], …]
- Raises:
RuntimeError – If the mesh object has not been initialized correctly.
PyMeshToolError – If the coordinates cannot be converted to the correct C++ container.
- extract_unreachable(*, mode, compute_connectivity=True, return_mapping=False)
Extract unreachable sub-meshes. A sub-mesh is considered unreachable if it has no common nodes with other sub-meshes.
- Parameters:
mode (int) – Extraction mode. Choices are:
<0: extract smallest unreachable sub-mesh,>0: extract largest unreachable sub-mesh,=0: extract all unreachable sub-meshescompute_connectivity (bool, optional, default=True) – If True, the full mesh connectivity is computed after the mesh was extracted.
return_mapping (bool, optional, default=False) – If True, the mapping object is returned.
- Returns:
None - If no unreachable sub-mesh was found.
Mesh - If mode is not equal to zero and return_mapping is False.
tuple[Mesh, Mapping] - If mode is not equal to zero and return_mapping is True.
tuple[Mesh, …] - If mode is equal to zero and return_mapping is False.
tuple[tuple[Mesh, Mapping], …] - If mode is equal to zero and return_mapping is True.
- Return type:
None or Mesh or tuple[Mesh, Mapping] or tuple[Mesh, …] or tuple[tuple[Mesh, Mapping], …]
- Raises:
RuntimeError – If the mesh object has not been initialized correctly.
RuntimeError – If the sub-mesh extraction fails.
See also
- extract_vtx(tags)
Extract all vertices from a region defined by a list of element tags and return a list of their indices.
- Parameters:
tags (int | ndarray[int]) – List of element tags from which the vertices should be extracted.
- Returns:
None - If no vertices were extracted.
ndarray[int] - Array of vertex indices.
- Return type:
None or ndarray[int]
- Raises:
RuntimeError – If the mesh object has not been initialized correctly.
PyMeshToolError – If the tags data cannot be converted to an integer nor to the correct C++ container.
PyMeshToolError – If the selection data cannot be converted to a NumPy array.
- extract_vtxhalo(block)
Extract connected components from a vertex selection that is given as the halo of the provided vertex block.
- Parameters:
block (ndarray[int]) – Indices defining the vertex block.
- Returns:
None - If no components were found.
tuple[ndarray[int], …] - Tuple of arrays holding the node indices of the connected halo components.
- Return type:
None or tuple[ndarray[int], …]
- Raises:
RuntimeError – If the mesh object has not been initialized correctly.
PyMeshToolError – If the block object cannot be converted to the correct C++ container.
- generate_distancefield(start_vtx, *, end_vtx=None)
Generate a distance field. If only start_vtx is given, the shortest topological distance between each mesh point and the points defined by start_vtx is computed. If end_vtx is also specified, the relative distance to both sets is computed. Points in the set defined by start_vtx have a value of 0, all points in the set defined by end_vtx have a value of 1, and all remaining points have a value between these two.
- Parameters:
start_vtx (ndarray[int]) – Start vertices of the distance field.
end_vtx (ndarray[int], optional, default=None) – End vertices of the distance field.
- Returns:
The nodal values of the computed distance field.
- Return type:
ndarray[float]
- Raises:
RuntimeError – If the mesh object has not been initialized correctly.
PyMeshToolError – If the mesh has not only tetrahedral, triangular, or line elements.
PyMeshToolError – If the vertex array cannot be converted to the correct C++ container.
PyMeshToolError – If the distance field cannot be converted to a NumPy array.
- generate_fibers(*, bath_tags=None)
Generate default fibers for a given mesh. The optional element tags identify bath regions to which zero fibers are assigned.
- Parameters:
bath_tags (ndarray[int], optional, default=None) – Bath region tags.
- Returns:
The modified input mesh with generated fibers.
- Return type:
Mesh
- Raises:
RuntimeError – If the mesh object has not been initialized correctly.
ValueError – If the fiber dimension in the mesh is not supported.
PyMeshToolError – If the bath tags cannot be converted to the correct C++ container.
- generate_split(splitop)
Generate a split-list for a given mesh defined by the split operation splitop. The format of the split operations is: tagA1,tagA2,..:tagB1,../tagA1,..:tagB1../.. where ‘,’ separates tags, ‘:’ separates tag groups to split, ‘/’ separates split operations. The splitting is applied to the elements defined by the ‘tagA’ tags, so these must not repeat between several split operations!
- Parameters:
splitop (str) – String defining the split operation.
- Returns:
The split-list defined by splitop. The dimension is (N, 3) where the first column holds the element index, the second column the old node index, and the third column the new node index.
- Return type:
ndarray[int]
- Raises:
RuntimeError – If the mesh object has not been initialized correctly.
ValueError – If the split operation is empty or the parsing fails.
PyMeshToolError – If the split-list cannot be converted to a NumPy array.
- get_element_sizes()
Get the size of all the elements, for 1D elements the length is returned, for 2D elements the area is returned, and for 3D elements the volume is returned.
- Returns:
List of the sizes of the elements.
- Return type:
ndarray[float]
- Raises:
RuntimeError – If the mesh object has not been initialized correctly.
PyMeshToolError – If the size data cannot be converted to a NumPy array.
- get_elements_in_selection(selection)
Get a list of indices of all the elements for which all nodes are in the provided nodal selection.
- Parameters:
selection (ndarray[int]) – The nodal selection.
- Returns:
None - If the list of selected elements is empty.
ndarray[int] - List of all elements within the nodal selection.
- Return type:
None or ndarray[int]
- Raises:
RuntimeError – If the mesh object has not been initialized correctly.
PyMeshToolError – If the selection data cannot be converted to a NumPy array.
PyMeshToolError – If the index data cannot be converted to a NumPy array.
- has_full_connectivity()
Check if the node-to-element and the node-to-node connectivity graphs of the mesh are computed.
- Returns:
True if the graphs are computed, False otherwise.
- Return type:
bool
- Raises:
RuntimeError – If the mesh object has not been initialized correctly.
- interpolate_clouddata(points, data, *, mode=2)
Interpolate data from a point cloud onto the mesh using radial basis function interpolation.
- Parameters:
points (ndarray[float]) – Coordinates of the point cloud.
data (ndarray[float]) – Input data.
mode (int, optional, default=2) – Choose between different interpolation modes. Choices are:
0: localized Shepard,1: global Shepard,2: RBF interpolation
- Returns:
The interpolated data on the mesh.
- Return type:
ndarray[float]
- Raises:
RuntimeError – If the mesh object has not been initialized correctly.
ValueError – If the interpolation mode is not supported.
PyMeshToolError – If the input points cannot be converted to the correct C++ container.
PyMeshToolError – If the input data cannot be converted to the correct C++ container.
ValueError – If the input data has the wrong shape.
RuntimeError – If the interpolation failed.
PyMeshToolError – If the interpolated data cannot be converted to a NumPy array.
See also
ClouddataInterpolation
- interpolate_elem2node(data, *, normalize=False)
Interpolate data from elements onto nodes.
- Parameters:
data (ndarray[float]) – Input data array of certain shape. Choices are:
(N): for scalar data,(N,3): for vector data,(N,9): and (N,3,3) for tensor/matrix datanormalize (bool, optional, default=False) – If True, vector data is normalized.
- Returns:
The interpolated data on the nodes.
- Return type:
ndarray[float]
- Raises:
RuntimeError – If the mesh object has not been initialized correctly.
PyMeshToolError – If the input data cannot be converted to the correct C++ container.
ValueError – If the input data has the wrong shape.
PyMeshToolError – If the interpolated data cannot be converted to a NumPy array.
- interpolate_node2elem(data, *, normalize=False)
Interpolate data from nodes onto elements.
- Parameters:
data (ndarray[float]) – Input data array of certain shape. Choices are:
(N): for scalar data,(N,3): for vector data,(N,9): and (N,3,3) for tensor/matrix datanormalize (bool, optional, default=False) – If True, vector data is normalized.
- Returns:
The interpolated data on the elements.
- Return type:
ndarray[float]
- Raises:
RuntimeError – If the mesh object has not been initialized correctly.
PyMeshToolError – If the input data cannot be converted to the correct C++ container.
ValueError – If the input data has the wrong shape.
PyMeshToolError – If the interpolated data cannot be converted to a NumPy array.
- interpolate_nodes(data, omesh, *, norm=False)
Interpolate nodal data from one mesh onto another.
- Parameters:
data (ndarray[float]) – Input data array of certain shape. Choices are:
(N): for scalar data,(N,3): for vector data,(N,9): and (N,3,3) for tensor/matrix dataomesh (Mesh) – Mesh we interpolate to.
norm (bool, optional, default=False) – If True, vector data is normalized.
- Returns:
The interpolated data on the target mesh.
- Return type:
ndarray[float]
- Raises:
RuntimeError – If the mesh object has not been initialized correctly.
PyMeshToolError – If the input data cannot be converted to the correct C++ container.
ValueError – If the input data has the wrong shape.
PyMeshToolError – If the interpolated data cannot be converted to a NumPy array.
- is_surface_mesh()
Check whether the mesh is a surface mesh.
- Returns:
True if mesh is a surface mesh, False otherwise.
- Return type:
bool
- Raises:
RuntimeError – If the mesh object has not been initialized correctly.
- merge(mesh, *, ignore_empty_interface=True)
Merge the mesh with another mesh.
- Parameters:
mesh (Mesh) – The mesh that gets merged into.
ignore_empty_interface (bool, optional, default=True) – If False, an error is raised if the interface is empty.
- Returns:
None - If the mesh to be combined does not contain any elements.
Mesh - The combined mesh.
- Return type:
None or Mesh
- Raises:
RuntimeError – If the mesh object has not been initialized correctly.
RuntimeError – If the interface is empty and an empty interface is not ignored.
- query_bbox()
Get the box bounding the mesh in X, Y, and Z direction.
- Returns:
Tuple holding the XYZ-coordinates of the point defining the lower-left-back corner of the box, the XYZ-coordinates of the point defining the upper-right-front corner of the box, the sizes of the bounding box in the X, Y, and Z direction and the length of the diagonal.
- Return type:
tuple[tuple[float, float, float], tuple[float, float, float], tuple[float, float, float], float]
- Raises:
RuntimeError – If the mesh object has not been initialized correctly.
- query_curvature(radius)
Calculate the curvature of the surface mesh.
- Parameters:
radius (float) – Radius parameter influencing the curvature calculation.
- Returns:
The computed curvature values.
- Return type:
ndarray[float]
- Raises:
RuntimeError – If the mesh object has not been initialized correctly.
TypeError – If the mesh is not a surface mesh.
PyMeshToolError – If the output data cannot be converted to a NumPy array.
- query_edges(*, tags=None)
Get statistical parameters related to the edges in the given mesh or in a specified sub-region.
- Parameters:
tags (int | ndarray[int], optional, default=None) – Restrict query to elements of a certain tag region.
- Returns:
None - If no edges are in the restricted region.
tuple[float, float, float] - The minimum, maximum and average edge lengths.
- Return type:
None or tuple[float, float, float]
- Raises:
RuntimeError – If the mesh object has not been initialized correctly.
PyMeshToolError – If the tags object cannot be converted to an integer nor to the correct C++ container.
- query_idx(coord, *, threshold=0.0, vertices=None)
Get indices in proximity to a given coordinate. If the threshold value is less than or equal to zero, the closest vertex is returned.
- Parameters:
coord (ndarray[float]) – XYZ-coordinates of the point for which the nearest vertex is to be found.
threshold (float, optional, default=0.0) – Sets the proximity threshold for the coordinates.
vertices (ndarray[int], optional, default=None) – Node indices for additional filtering.
- Returns:
None - If no point was found in proximity to the given coordinates.
int - If only one index was found.
ndarray[int] - List of indices in proximity to the given coordinates.
- Return type:
None or int or ndarray[int]
- Raises:
RuntimeError – If the mesh object has not been initialized correctly.
PyMeshToolError – If the coordinate cannot be converted to the correct C++ container.
PyMeshToolError – If the restricting vertex data cannot be converted to the correct C++ container.
PyMeshToolError – If the queried index list cannot be converted to a NumPy array.
- query_idxlist(coords, *, threshold=0.0, vertices=None)
Get indices in proximity for all provided coordinates. If the threshold value is less than or equal to zero, the closest vertex is returned. If an index list cannot be converted to a NumPy array, None is inserted in the returned tuple instead. If threshold is not greater than zero, the index of the closest point in the mesh is returned.
- Parameters:
coords (ndarray[float]) – List of the XYZ-coordinates of the points for which the nearest vertex is to be found.
threshold (float | ndarray[float], optional, default=0.0) – Proximity threshold for each coordinate.
vertices (ndarray[float], optional, default=None) – Restricts query to indices of specific vertices.
- Returns:
None - If the queried index list is empty.
tuple[None | int | ndarray[int], …] - Tuple containing None if no points were found within the defined radius, the index if only one point was found, or an array of indices if multiple points lie within the defined radius.
- Return type:
None or tuple[None | int | ndarray[int], …]
- Raises:
RuntimeError – If the mesh object has not been initialized correctly.
PyMeshToolError – If the coordinates cannot be converted to the correct C++ container.
ValueError – If the coordinates have the wrong shape.
PyMeshToolError – If the threshold values cannot be converted to the correct C++ container.
PyMeshToolError – If the restricting vertex data cannot be converted to the correct C++ container.
ValueError – If the threshold values have a wrong size.
- query_quality()
Get the quality of the mesh elements. Only the quality of the tetrahedral and triangular elements is calculated; all other elements are assigned a value of 0.
- Returns:
Array holding the quality for each element in the mesh.
- Return type:
ndarray[float]
- Raises:
RuntimeError – If the mesh object has not been initialized correctly.
PyMeshToolError – If the quality data cannot be converted to a NumPy array.
- query_tags(*, vtx=None, tolerance=0.01)
Get information about the tags in the myocardial and non-myocardial regions, as well as the corresponding number of elements with those tags.
- Parameters:
vtx (None | ndarray[int], optional, default=None) – Restrict query to elements connected to the vertices in the list.
tolerance (float, optional, default=0.01) – Fibers with a length greater than this value are considered as myocardial tissue.
- Returns:
Tuple, where the first entry is a dictionary mapping myocardial tags to the corresponding number of elements, the second entry is a dictionary mapping bath tags to the corresponding number of elements, and the third entry is the number of elements considered.
- Return type:
tuple[dict[int, int], dict[int, int], int]
- Raises:
RuntimeError – If the mesh object has not been initialized correctly.
PyMeshToolError – If the vtx object cannot be converted to the correct C++ container.
ValueError – If the fiber tolerance is negative.
- refine_uniformly(num_it)
Uniformly refine the mesh.
- Parameters:
num_it (int) – Number of refinement iterations.
- Returns:
The refined mesh.
- Return type:
Mesh
- Raises:
RuntimeError – If the mesh object has not been initialized correctly.
ValueError – If the number of iterations is less than one.
- rotate(axis, angle, *, ignore_fibers=False)
Rotate the mesh around a given vector by a given angle. If ignore_fibers is False, the fibers are not rotated.
- Parameters:
axis (ndarray[float]) – Axis vector around which the mesh is rotated.
angle (float) – Rotation angle.
ignore_fibers (bool, optional, default=False) – If False, the fibers are not rotated.
- Return type:
None
- Raises:
RuntimeError – If the mesh object has not been initialized correctly.
PyMeshToolError – If the axis vector cannot be converted to the correct C++ container.
ValueError – If the axis vector is zero.
RuntimeError – If the fiber data has the wrong shape.
- save(basename, *, format='carp_txt')
Write the mesh to a file.
- Parameters:
basename (str) – Basename of the file to which the mesh should be written to.
format (str, optional, default='carp_txt') – Format of the mesh file. Choices are:
carp_txt: CARP text format,carp_bin: CARP binary format,vtk: VTK text format,vtk_bin: VTK binary format,vtu: VTU format,vtk_polydata: VTK polydata format,mmg: MMG format,neu: EnSight format,obj: object format,off: off format,stellar: Stellar format,vcflow: vcflow format
- Return type:
None
- Raises:
RuntimeError – If the mesh object has not been initialized correctly.
IOError – If the mesh format is unknown.
See also
- scale(scaling_factor)
Scale the mesh by a single scaling factor or scale each axis separately using a vector valued scaling factor. A negative scaling factor corresponds to mirroring of the mesh.
- Parameters:
scaling_factor (float | tuple[float, float, float]) – The factor by which the mesh is scaled. Either a single scaling factor or a list of factors for the X, Y, and Z coordinate.
- Return type:
None
- Raises:
RuntimeError – If the mesh object has not been initialized correctly.
PyMeshToolError – If the scaling factor cannot be converted to a double nor to the correct C++ container.
ValueError – If a scaling factor is zero.
- smooth_mesh(tags, *, num_iterations=100, smoothing_coeff=0.15, num_laplace_levels=1, edge_threshold=0, max_quality_threshold=0.95)
Smooth surfaces and volume of a mesh.
- Parameters:
tags (Iterable[int | Iterable[int]]) – List of tag sets. The tags in one set have a common surface. Surfaces between different tag sets will be smoothed.
num_iterations (int, optional, default=100) – Number of smoothing iterations.
smoothing_coeff (float, optional, default=0.15) – Smoothing coefficient.
num_laplace_levels (int, optional, default=1) – Number of Laplace levels used.
edge_threshold (float, optional, default=0) – Normal vector angle difference defining a sharp edge. If set to 0, edge detection is turned off. Negative values let meshtool skip edge vertices.
max_quality_threshold (float, optional, default=0.95) – Maximum allowed element quality metric. Set to 0 to disable quality checking.
- Return type:
None
- Raises:
RuntimeError – If the mesh object has not been initialized correctly.
ValueError – If the tags object could not be iterated.
TypeError – If the tags cannot be converted to an integer value.
- translate(displacement)
Translate the mesh by a given displacement vector.
- Parameters:
displacement (ndarray[float]) – Displacement vector in X, Y, and Z directions.
- Return type:
None
- Raises:
RuntimeError – If the mesh object has not been initialized correctly.
PyMeshToolError – If the displacement vector cannot be converted to the correct C++ container.
- class Mapping
PyMeshTool Mapping object. Helper class for mapping data between mesh and sub-mesh.
Class Attributes
- element_map
Get the element-wise submesh-to-mesh index map.
- Returns:
None - If the element index map is empty.
ndarray[int] - The element-wise submesh-to-mesh index map.
- Return type:
None or ndarray[int]
- Raises:
RuntimeError – If the mapping object has not been initialized correctly.
PyMeshToolError – If the index map cannot be converted to a NumPy array.
Attention
The attribute returns a NumPy array that provides access to the existing mapping data of the underlying mapping structure without owning the data. This means that the mapping object is not deleted as long as there are NumPy arrays referencing the mapping data.
- mesh
Get the mesh object the mapping object was created with.
- Returns:
None - If no mesh is defined.
Mesh - The mesh to the mapping object.
- Return type:
None or Mesh
- node_map
Get the nodal submesh-to-mesh index map.
- Returns:
None - If the node index map is empty.
ndarray[int] - The nodal submesh-to-mesh index map.
- Return type:
None or ndarray[int]
- Raises:
RuntimeError – If the mapping object has not been initialized correctly.
PyMeshToolError – If the index map cannot be converted to a NumPy array.
Attention
The attribute returns a NumPy array that provides access to the existing mapping data of the underlying mapping structure without owning the data. This means that the mapping object is not deleted as long as there are NumPy arrays referencing the mapping data.
- submesh
Get the sub-mesh object the mapping object was created with.
- Returns:
None - If no sub-mesh is defined.
Mesh - The sub-mesh to the mapping object.
- Return type:
None or Mesh
Class Functions
- __matmul__(other)
Create a new mapping object by concatenating two consecutive mappings.
- Parameters:
other (Mapping) – Subsequent mapping object.
- Returns:
The concatenated mapping object.
- Return type:
Mapping
- Raises:
TypeError – If either of the two objects is not a Mapping object.
ValueError – If the two mapping objects are not subsequent.
# load torso model tor_mesh = pymeshtool.Mesh("torso_mesh.elem") # extract bi-ventricular mesh and mapping object # from torso model biv_tags = [1, 2] biv_mesh, tor_biv_map = tor_mesh.extract_mesh(biv_tags, return_mapping=True) # extract left-ventricular mesh and mapping object # from bi-ventricular model lv_tag = 1 lv_mesh, biv_lv_map = biv_mesh.extract_mesh(lv_tag, return_mapping=True) # create torso <-> lv map tor_lv_map = tor_biv_map @ biv_lv_map # map data from lv to torso lv_data = numpy.ones(lv_mesh.num_points, dtype=numpy.float32) tor_data = tor_lv_map.prolongate(lv_data)
- insert_back()
Insert fiber and tag data from the sub-mesh back to the mesh.
- Return type:
None
- Raises:
RuntimeError – If the mapping object has not been initialized correctly.
- insert_data(subdata, data, *, nodal_data=True)
Insert data defined on the sub-mesh into a data array given on the mesh.
- Parameters:
subdata (ndarray[number]) – The data defined on the sub-mesh.
data (ndarray[number]) – The data defined on the mesh.
nodal_data (bool, optional, default=True) – Set to True to insert nodal data, False for element data.
- Returns:
The data array.
- Return type:
ndarray[number]
- Raises:
RuntimeError – If the mapping object has not been initialized correctly.
TypeError – If the subdata and data arrays have different underlying data types.
ValueError – If data has incorrect size or dimensions.
RuntimeError – If the mapping object is not compatible with the sub-mesh.
ValueError – If the dimensions of subdata and data are not compatible.
See also
- map_selection(idx, *, nodal_selection=True, map_forward=True)
Map nodal or element selections between the mesh and the sub-mesh.
- Parameters:
idx (ndarray[int]) – Input selection array.
nodal_selection (bool, optional, default=True) – Set True to map a nodal selection, False for an element selection.
map_forward (bool, optional, default=True) – Set to True to map from mesh to sub-mesh, False to map from sub-mesh to mesh.
- Returns:
None - If the list of the mapped selection is empty.
ndarray[int] - Mapped selection array.
- Return type:
None or ndarray[int]
- Raises:
RuntimeError – If the mapping object has not been initialized correctly.
PyMeshToolError – If input selection cannot be converted to the correct C++ container
PyMeshToolError – If input selection cannot be converted to a NumPy array.
- prolongate(data, *, default=None, nodal_data=True)
Prolongate nodal or element data from the sub-mesh to the mesh. Mesh entities that are not present in the sub-mesh are assigned the value specified by default or 0 if default is None.
- Parameters:
data (ndarray[number]) – Input data array.
default (number, optional, default=None) – Default value to use where mapping is undefined.
nodal_data (bool, optional, default=True) – Set to True to map nodal data, False for element data.
- Returns:
Mapped output data array.
- Return type:
ndarray[number]
- Raises:
RuntimeError – If the mapping object has not been initialized correctly.
ValueError – If data has incorrect size or dimensions.
RuntimeError – If the mapping object is not compatible with the sub-mesh.
RuntimeError – If the default-value object cannot be generated.
ValueError – If the default-value object has wrong shape.
RuntimeError – If the output NumPy array cannot be generated.
See also
- restrict(data, *, nodal_data=True)
Restrict nodal or element data from the mesh to the sub-mesh.
- Parameters:
data (ndarray[number]) – Input data array.
nodal_data (bool, optional, default=True) – Set to True to map nodal data, False for element data.
- Returns:
Mapped output data array.
- Return type:
ndarray[number]
- Raises:
RuntimeError – If the mapping object has not been initialized correctly.
ValueError – If data has incorrect size or dimensions.
RuntimeError – If the mapping object is not compatible with the sub-mesh.
PyMeshToolError – If the index map cannot be converted to a NumPy array.
RuntimeError – If the data restriction failed.
See also
- save(basename, *, binary=True)
Save the mapping data. For the nodal mapping, a file named basename.nod is written, for the element mapping the file basename.eidx is written.
- Parameters:
basename (str) – Basename for the output files.
binary (bool, optional, default=True) – Set to True to write binary data, False for text data.
- Return type:
None
- Raises:
RuntimeError – If the mapping object has not been initialized correctly.
- class Image
PyMeshTool Image object. Wrapper class for the meshtool itk_image structure.
Class Attributes
- data_type
Get the data type of the image.
- Returns:
The integer value representation of the image data type.
- Return type:
int
- Raises:
RuntimeError – If the image object has not been initialized correctly.
See also
- dtype
Get the NumPy data type of the image.
- Returns:
The NumPy type representation of the image data type.
- Return type:
type
- Raises:
RuntimeError – If the image object has not been initialized correctly.
ValueError – If the image data type unknown.
- origin
Set or get the origin of the image.
- Type:
tuple[float, float, float] - The X, Y, and Z position of the new origin.
- Returns:
The X, Y, and Z position of the origin.
- Return type:
tuple[float, float, float]
- Raises:
RuntimeError – If the image object has not been initialized correctly.
PyMeshToolError – If the new origin cannot be converted to the correct C++ container.
- shape
Get the shape of the image.
- Returns:
The dimension in X, Y, and Z directions and the number of components.
- Return type:
tuple[int, int, int, int]
- Raises:
RuntimeError – If the image object has not been initialized correctly.
- voxel_size
Set or get the voxel-size of the image.
- Type:
tuple[float, float, float] - The new size in X, Y, and Z direction of an image voxel.
- Returns:
The X, Y, and Z size of an image voxel.
- Return type:
tuple[float, float, float]
- Raises:
RuntimeError – If the image object has not been initialized correctly.
PyMeshToolError – If the new size cannot be converted to the correct C++ container.
- voxels
Set or get the voxels of the image.
- Type:
ndarray[number] - The new voxel data of the same shape and data type.
- Returns:
The voxel data.
- Return type:
ndarray[number]
- Raises:
RuntimeError – If the image object has not been initialized correctly.
PyMeshToolError – If the voxel data cannot be converted to a NumPy array.
BufferError – If the voxel data buffer is empty.
ValueError – If the image data type unknown.
PyMeshToolError – If the new voxel data cannot be converted to the correct C++ container.
ValueError – If the new voxel data has the wrong shape.
Attention
The attribute returns a NumPy array that provides access to the existing voxel data of the underlying image structure without owning the data. This means that the image object is not deleted as long as there are NumPy arrays referencing the voxel data.
Class Functions
- __deepcopy__()
Deep-copy operator. This function is triggered by the copy.deepcopy() function.
- Returns:
A deep copy of the image.
- Return type:
Image
- Raises:
RuntimeError – If the image object has not been initialized correctly.
- __init__(filename)
Create a new image by loading it from a file.
- Parameters:
filename (str) – Filename of the image file from which the image should be loaded.
- Returns:
The new image object loaded from filename.
- Return type:
Image
- Raises:
RuntimeError – If the image object has not been initialized correctly.
IOError – If the image format is unknown.
- change_type(new_type)
Change the image data type.
- Parameters:
new_type (int) – Index of new data type. Choices are:
1: unsigned_char,2: char,3: unsigned_short,4: short,5: unsigned_int,6: int,7: unsigned_long,8: long,9: float,10: double,11: color scalars- Returns:
The image with the new data type.
- Return type:
Image
- Raises:
RuntimeError – If the image object has not been initialized correctly.
ValueError – If the new data type is unknown.
See also
- crop()
Crop the image by removing the empty space around it.
- Returns:
The cropped image.
- Return type:
Image
- Raises:
RuntimeError – If the image object has not been initialized correctly.
- extract_mesh(*, surface_mesh=False, tetrahedralize_mesh=False, scale=1.0, compute_connectivity=True, tags=None)
Extract a mesh from the image by generating a hexahedral element for each voxel. If a list of tags is provided, only the specified sub-image is extracted. To obtain a tetrahedral mesh, set tetrahedralize_mesh to True to subdivide each hexahedral element into six tetrahedral elements.
- Parameters:
surface_mesh (bool, optional, default=False) – If True, only a surface mesh is extracted.
tetrahedralize_mesh (bool, optional, default=False) – If True, the volumetric hex elements are converted to tets.
scale (float, optional, default=1.0) – Mesh scaling factor (> 0.0).
compute_connectivity (bool, optional, default=True) – If True, the full mesh connectivity is computed after the mesh was extracted.
tags (ndarray[int], optional, default=None) – List of tags of the regions to mesh. If None, the entire image is extracted.
- Returns:
The extracted mesh.
- Return type:
Mesh
- Raises:
RuntimeError – If the image object has not been initialized correctly.
PyMeshToolError – If the tags object cannot be converted to the correct C++ container.
RuntimeError – If the mesh extraction failed.
- extrude(mode, radius, region_tag, *, new_tag=-1, tags=None)
Extrude a certain tag region in the image. If the extrusion mode is ‘inwards’, the tag region grows into itself. If the mode is set to ‘outwards’, the region grows away from itself. To grow in both directions pick extrusion mode ‘both’. The newly grown region is then assigned a new tag, which is given by new_tag or that of the region to be grown. Growh can be further restricted by providing a list of tags the reagion can grow into.
- Parameters:
mode (int) – Extrusion mode. Choices are:
<0: extrude inwards,>0: extrude outwards,=0: extrude in both directionsradius (int) – Extrusion radius (>0).
region_tag (int) – Tag of the region to extrude.
new_tag (int, optional, default=-1) – Tag of the new extruded region, if negative, region_tag is taken.
tags (ndarray[int], optional, default=None) – List of tags, the region can grow into.
- Returns:
The extruded image.
- Return type:
Image
- Raises:
RuntimeError – If the image object has not been initialized correctly.
ValueError – If the radius is not greater than zero.
PyMeshToolError – If the tags object cannot be converted to the correct C++ container.
See also
- resample(refinement_factor)
Resample the image data by refining each pixel while keeping the overall image size. In case of a single-valued refinement factor, the pixel size in each direction will be scaled by the same factor. In case of a multi-valued refinement factor, the pixel size will be scaled in X, Y, and Z directions separately.
- Parameters:
refinement_factor (float | tuple[float, float, float]) – Voxel refinement factor.
- Returns:
The resampled image.
- Return type:
Image
- Raises:
RuntimeError – If the image object has not been initialized correctly.
ValueError – If the refinement factor is not greater than zero.
PyMeshToolError – If the multi-valued refinement factor cannot be converted to the correct C++ container.
- save(filename)
Write the image to a file.
- Parameters:
filename (str) – Path to the output file. The format is specified by the file extension. Choices are:
vtk: vtk structured points format,nrrd: nearly raw raster data format,raw: raw binary format (voxels only)- Return type:
None
- Raises:
RuntimeError – If the image object has not been initialized correctly.
IOError – If the file extension is unknown.
- class PyMeshToolError
Base class for PyMeshTool related errors.
- class MeshInputFormat
Enumeration of all supported mesh input formats.
Enum Items
carp_bin: ‘carp_bin’
carp_txt: ‘carp_txt’
gmsh: ‘gmsh’
mmg: ‘mmg’
netgen: ‘neu’
obj: ‘obj’
off: ‘off’
purk: ‘purk’
stellar: ‘stellar’
vcflow: ‘vcflow’
vtk: ‘vtk’
vtk_bin: ‘vtk_bin’
vtu: ‘vtu’
- class MeshOutputFormat
Enumeration of all supported mesh output formats.
Enum Items
carp_bin: ‘carp_bin’
carp_txt: ‘carp_txt’
mmg: ‘mmg’
netgen: ‘neu’
obj: ‘obj’
off: ‘off’
stellar: ‘stellar’
vcflow: ‘vcflow’
vtk: ‘vtk’
vtk_bin: ‘vtk_bin’
vtk_polydata: ‘vtk_polydata’
vtu: ‘vtu’
- class MeshElementType
Enumeration of all mesh element types.
Enum Items
tetra: 0
hexa: 1
octa: 2
pyramid: 3
prism: 4
quad: 5
tri: 6
line: 7
node: 8
- class MeshClouddataInterpolationMode
Enumeration of available clouddata interpolation modes.
Enum Items
localized_shepard: 0
global_shepard: 1
radial_basis_function: 2
- class MeshExtractUnreachableMode
Enumeration of mesh unreachable extraction modes.
Enum Items
smallest: -1
all: 0
largest: 1
- class ImageDType
Enumeration of image voxel data types.
Enum Items
uint8: 1
int8: 2
uint16: 3
int16: 4
uint32: 5
int32: 6
uint64: 7
int64: 8
float32: 9
float64: 10
color_scalar: 11
- class ImageExtrusionMode
Enumeration of image extrusion modes.
Enum Items
inwards: -1
everywhere: 0
outwards: 1