Data structures#

Every mesh is stored in a PolyData instance, which is a subclass of LinkedDeepDict, therefore essentially being a nest of dictionaries. Every container in the nest can hold onto points and cells, data attached to either the points or the cells, or other similar containers. To store data, every container contains a data object for points, or cells, or for both. These data objects wrap themselves around instances of awkward.Record, utilizing their effective memory layout, handling of jagged data and general numba and gpu support.

class sigmaepsilon.mesh.data.CellData(*args, wrap: Array | Record | None = None, topo: ndarray | None = None, fields: dict | None = None, activity: ndarray | None = None, frames: ndarray | ReferenceFrame | None = None, areas: ndarray | float | None = None, t: ndarray | float | None = None, db: Array | Record | None = None, i: ndarray | None = None, **kwargs)[source]#

A class to handle data related to the cells of a polygonal mesh.

Technically this is a wrapper around an Awkward data object instance.

If you are not a developer, you probably don’t have to ever create any instance of this class, but since it operates in the background of every polygonal data structure, it is useful to understand how it works.

Parameters:
  • activity (numpy.ndarray, Optional) – 1d boolean array describing the activity of the elements.

  • thickness (t or) – 1d float array of thicknesses. Only for 2d cells. Default is None.

  • areas (numpy.ndarray, Optional) – 1d float array of cross sectional areas. Only for 1d cells. Default is None.

  • fields (dict, Optional) – Every value of this dictionary is added to the dataset. Default is None.

  • frames (numpy.ndarray, Optional) – Coordinate axes representing cartesian coordinate frames. Default is None.

  • topo (numpy.ndarray, Optional) – 2d integer array representing node indices. Default is None.

  • i (numpy.ndarray, Optional) – The (global) indices of the cells. Default is None.

  • **kwargs (dict, Optional) – For every key and value pair where the value is a numpy array with a matching shape (has entries for all cells), the key is considered as a field and the value is added to the database.

property A: ndarray#

Returns the thicknesses of the cells.

property activity: ndarray#

Returns a 1d boolean array of cell activity.

property db: Array | Record#

Returns the wrapped Awkward object.

property fields: Iterable[str]#

Returns the fields in the database object.

property frames: ndarray#

Returns local coordinate frames of the cells.

property id: ndarray#

Returns global indices of the cells.

property nodes: ndarray#

Returns the topology of the cells.

set_nodal_distribution_factors(factors: ndarray, key: str | None = None) None[source]#

Sets nodal distribution factors.

Parameters:
  • factors (numpy.ndarray) – A 3d float array. The length of the array must equal the number pf cells in the block.

  • key (str, Optional) – A key used to store the values in the database. This makes you able to use more nodal distribution strategies in one model. If not specified, a default key is used.

property t: ndarray#

Returns the thicknesses of the cells.

class sigmaepsilon.mesh.data.LineData(pd: PointData | PolyCell | None = None, cd: PolyCell | None = None, *args, **kwargs)[source]#

Data class for 1d cells.

plot(*args, scalars=None, backend='plotly', scalar_labels=None, **kwargs)[source]#

Plots the mesh with or without data, using multiple possible backends.

Parameters:
  • scalars (numpy.ndarray, Optional) – Stacked nodal information as an 1d or 2d NumPy array. Default is None.

  • backend (str, Optional) – The backend to use. Possible options are plotly and vtk (vtk is being managed through PyVista) at the moment. Default is ‘plotly’.

  • scalar_labels (Iterable, Optional) – Labels for the datasets provided with ‘scalars’. Default is None.

class sigmaepsilon.mesh.data.PointData(*args, points: ndarray | None = None, coords: ndarray | None = None, wrap: Record | None = None, fields: Iterable | None = None, frame: CartesianFrame | None = None, db: Record | None = None, container: PolyDataProtocol | None = None, **kwargs)[source]#

A class to handle data related to the pointcloud of a polygonal mesh.

The class is technicall a wrapper around an awkward.Record instance.

Warning

Internal variables used during calculations begin with two leading underscores. Try to avoid leading double underscores when assigning custom data to a PointData instance, unless you are sure, that it is of no importance for the correct behaviour of the class instances.

Parameters:
  • points (numpy.ndarray, Optional) – Coordinates of some points as a 2d NumPy float array. Default is None.

  • coords (numpy.ndarray, Optional) – Same as points. Default is None.

  • frame (CartesianFrame, Optional) – The coordinate frame the points are understood in. Default is None, which means the standard global frame (the ambient frame).

Example

>>> from sigmaepsilon.mesh import CartesianFrame, PointData, triangulate
>>> A = CartesianFrame(dim=3)
>>> coords = triangulate(size=(800, 600), shape=(10, 10))[0]
>>> pd = PointData(coords=coords, frame=frame)
>>> pd.activity = np.ones((len(pd)), dtype=bool)
>>> pd.id = np.arange(len(pd))
property activity: ndarray#

Returns the activity of the points as an 1d NumPy bool array.

property container: PolyDataProtocol#

Returns the container object of the block.

property frame: ReferenceFrame#

Returns the frame of the underlying pointcloud.

property has_activity: bool#

Returns True if the instance is equipped with activity information, ű False if it isn’t.

property has_id: bool#

Returns True if the points are equipped with IDs, False if they are not.

property has_x: bool#

Returns True if the instance is equipped with coordinates, False if it isn’t.

property id: ndarray#

Returns the IDs of the points as an 1d NumPy integer array.

pull(key: str, ndf: ndarray | csr_matrix | None = None) ndarray[source]#

Pulls data from the cells in the model. The pulled data is either copied or distributed according to a measure.

Parameters:
  • key (str) – A field key to identify data in the databases of the attached CellData instances of the blocks.

  • ndf (Union[numpy.ndarray, csr_matrix], Optional) – The nodal distribution factors to use. If not provided, the default factors are used. Default is None.

See also

nodal_distribution_factors(), collect_nodal_data()

property x: ndarray#

Returns the coordinates as a 2d NumPy array.

class sigmaepsilon.mesh.data.PolyCell(*args, db: CellData[MeshDataLike, PointDataLike] | None = None, pointdata: PointDataLike | None = None, container: MeshDataLike | None = None, **kwargs)[source]#

A subclass of CellData as a base class for all cell containers. The class should not be used directly, the main purpose here is encapsulation of common behaviour for all kinds of cells.

area(*args, **kwargs) float[source]#

Returns the total area of the cells in the database. Only for 2d entities.

areas(*args, **kwargs) ndarray[source]#

Returns the areas of the individuall cells in the database as a 1d float NumPy array.

Note

For 1d cells, the cross sectional areas are returned.

boundary(detach: bool = False) Tuple[ndarray][source]#

Alias for extract_surface().

centers(target: CartesianFrame | None = None) ndarray[source]#

Returns the centers of the cells of the block as a 1d float NumPy array.

Parameters:

target (CartesianFrame, Optional) – A target frame. If provided, coordinates are returned in this frame, otherwise they are returned in the global frame. Default is None.

property container: MeshDataLike#

Returns the container of the block.

coords(*args, **kwargs) ndarray[source]#

Alias for points_of_cells(), all arguments are forwarded.

property db: CellDataProtocol[MeshDataLike, PointDataLike]#

Returns the database of the block.

detach_points_cells() Tuple[ndarray][source]#

Returns the detached coordinate and topology array of the block.

extract_surface(detach: bool = False) Tuple[ndarray][source]#

Extracts the surface of the object as a 2-tuple of NumPy arrays representing the coordinates and the topology of a triangulation.

Parameters:

detach (bool, Optional) – Wether to detach the mesh or not. Default is False.

flip() PolyCell[source]#

Reverse the order of nodes of the topology.

property frames: ndarray#

Returns local coordinate frames of the cells as a 3d NumPy float array, where the first axis runs along the cells of the block.

classmethod from_parquet(path: str) PolyCell[source]#

Saves the data of the database to a parquet file.

Parameters:

path (str) – Path of the file being created.

glob_to_loc(x: Iterable | ndarray) ndarray[source]#

Returns the local coordinates of the input points for each cell in the block. The input ‘x’ can describe a single (1d array), or several positions at once (2d array).

Notes

This function is useful when detecting if two bodies touch each other or not, and if they do, where.

Parameters:

x (Iterable or numpy.ndarray) – A single point in 3d space as an 1d array, or a collection of points as a 2d array.

Returns:

A NumPy array of shape (nE, nP, nD), where nP is the number of points in ‘x’, nE is the number of cells in the block and nD is the number of spatial dimensions.

Return type:

numpy.ndarray

jacobian(*, jac: ndarray | None = None, **kwargs) float | ndarray[source]#

Returns the jacobian determinant for one or more cells.

Parameters:
  • jac (numpy.ndarray, Optional) – One or more Jacobian matrices. Default is None.

  • **kwargs (dict) – Forwarded to jacobian_matrix() if the jacobian is not provided by the parameter ‘jac’.

Returns:

Value of the Jacobian for one or more cells.

Return type:

float or numpy.ndarray

jacobian_matrix(*, pcoords: Iterable[float] | None = None, dshp: ndarray | None = None, **kwargs) ndarray[source]#

Returns the jacobian matrices of the cells in the block. The evaluation of the matrix is governed by the inputs in the following way: - if dshp is provided, it must be a matrix of shape function derivatives

evaluated at the desired locations

  • the desired locations are specified through pcoords

Parameters:
  • pcoords (Iterable[float], Optional) – Locations of the evaluation points.

  • dshp (numpy.ndarray, Optional) – 3d array of shape function derivatives for the master cell, evaluated at some points. The array must have a shape of (nG, nNE, nD), where nG, nNE and nD are the number of evaluation points, nodes per cell and spatial dimensions.

Returns:

A 4d array of shape (nE, nP, nD, nD), where nE, nP and nD are the number of elements, evaluation points and spatial dimensions. The number of evaluation points in the output is governed by the parameter ‘dshp’ or ‘pcoords’.

Return type:

numpy.ndarray

Note

For 1d cells, the returned array is also 4 dimensional, with the last two axes being dummy.

length() float[source]#

Returns the total length of the cells in the block.

lengths() ndarray[source]#

Returns the lengths as a NumPy array.

loc_to_glob(x: Iterable | ndarray, ec: ndarray | None = None) ndarray[source]#

Returns the global coordinates of the input points for each cell in the block. The input ‘x’ can describe a single (1d array), or several local positions at once (2d array).

Notes

This function is useful when detecting if two bodies touch each other or not, and if they do, where.

Parameters:
  • x (Iterable or numpy.ndarray) – A single point as an 1d array, or a collection of points as a 2d array.

  • ec (numpy.ndarray, Optional) – Element coordinates as a 3d array of shape (nE, nNE, nD). Default is None, in which case the global coordinates of the cells are used.

Returns:

A NumPy array of shape (nE, nP, nD), where nP is the number of points in ‘x’, nE is the number of cells in the block and nD is the number of spatial dimensions.

Return type:

numpy.ndarray

local_coordinates(*, target: str | CartesianFrame | None = None) ndarray[source]#

Returns local coordinates of the cells as a 3d float NumPy array. The returned array is three dimensional with a shape of (nE, nNE, 2), where nE is the number of cells in the block, nNE is the number of nodes per cell and 2 stands for the 2 spatial dimensions. The coordinates are centralized to the centers for each cell.

Parameters:

target (CartesianFrame, Optional) – A target frame. If provided, coordinates are returned in this frame, otherwise they are returned in the local frames of the cells. Default is None.

locate(x: Iterable | ndarray, lazy: bool = True, tol: float = 1e-12, k: int = 4) Tuple[ndarray][source]#

Locates a set of points inside the cells of the block.

Parameters:
  • x (Iterable or numpy.ndarray) – The coordinates of the points that we want to investigate.

  • tol (float, Optional) – Floating point tolerance for detecting boundaries. Default is 1e-12.

  • lazy (bool, Optional) – If False, the ckeck is performed for all cells in the block. If True, it is used in combination with parameter ‘k’ and the check is only performed for the k nearest neighbours of the input points. Default is True.

  • k (int, Optional) – The number of neighbours for the case when ‘lazy’ is true. Default is 4.

Returns:

  • numpy.ndarray – The indices of ‘x’ that are inside a cell of the block.

  • numpy.ndarray – The block-local indices of the cells that include the points with the returned indices.

  • numpy.ndarray – The parametric coordinates of the located points inside the including cells.

measure(*args, **kwargs) float[source]#

Returns the net generalized measure for the cells in the block. The generalized measure is length for 1d cells, area for 2d cells and volume for 3d cells.

measures(*args, **kwargs) ndarray[source]#

Returns generalized measures for each cell in the block. The generalized measure is length for 1d cells, area for 2d cells and volume for 3d cells.

normals() ndarray[source]#

Returns the normals of the cells as a 2d NumPy array.

property pd: PointDataLike#

Returns the attached point database. This is what the topology of the cells are referring to.

pip(x: Iterable | ndarray, tol: float = 1e-12, lazy: bool = True, k: int = 4) bool | ndarray[source]#

Returns an 1d boolean integer array that tells if the points specified by ‘x’ are included in any of the cells in the block.

Parameters:
  • x (Iterable or numpy.ndarray) – The coordinates of the points that we want to investigate.

  • tol (float, Optional) – Floating point tolerance for detecting boundaries. Default is 1e-12.

  • lazy (bool, Optional) – If False, the ckeck is performed for all cells in the block. If True, it is used in combination with parameter ‘k’ and the check is only performed for the k nearest neighbours of the input points. Default is True.

  • k (int, Optional) – The number of neighbours for the case when ‘lazy’ is true. Default is 4.

Returns:

A single or NumPy array of booleans for every input point.

Return type:

bool or numpy.ndarray

property pointdata: PointDataLike#

Returns the hosting point database. This is what the topology of the cells are referring to.

points_involved() PointCloud[source]#

Returns the points involved in the cells of the block.

points_of_cells(*, points: float | Iterable | None = None, cells: int | Iterable | None = None, rng: Iterable | None = None) ndarray[source]#

Returns the points of selected cells as a NumPy array. The returned array is three dimensional with a shape of (nE, nNE, nD), where nE is the number of cells in the block, nNE is the number of nodes per cell or the number of the points (if ‘points’ is specified) and nD stands for the number of spatial dimensions.

Parameters:
  • points (Optional[Union[float, Iterable, None]]) – Points defined in the domain of the master cell. If specified, global coordinates for each cell are calculated and returned for each cell. Default is None, in which case the locations of the nodes of the cells are used.

  • cells (Optional[Union[int, Iterable, None]]) – BLock-local indices of the cells of interest, or None if all of the cells in the block are of interest. Default is None.

  • rng (Optional[Union[Iterable, None]]) – For 1d cells only, it is possible to provide an iterable of length 2 as an interval (or range) in which the argument points is to be understood. Default is None, in which case the points are expected in the range [-1, 1].

pull(data: str | ndarray, ndf: ndarray | csr_matrix | None = None) ndarray[source]#

Pulls data from the attached pointdata. The pulled data is either copied or distributed according to a measure.

Parameters:

data (str or numpy.ndarray) – Either a field key to identify data in the database of the attached PointData, or a NumPy array.

rewire(imap: ndarray | MutableMapping | None = None, invert: bool | None = False) PolyCell[source]#

Rewires the topology of the block according to the mapping described by the argument imap. The mapping of the j-th node of the i-th cell happens the following way:

topology_new[i, j] = imap[topology_old[i, j]]

The object is returned for continuation.

Parameters:
  • imap (MapLike, Optional) – Mapping from old to new node indices (global to local).

  • invert (bool, Optional) – If True the argument imap describes a local to global mapping and an inversion takes place. In this case, imap must be a numpy array. Default is False.

root() MeshDataLike[source]#

Returns the top level container of the model the block is the part of.

source() MeshDataLike[source]#

Retruns the source of the cells. This is the PolyData block that stores the PointData object the topology of the cells are referring to.

source_coords() ndarray[source]#

Returns the coordinates of the hosting pointcloud.

source_frame() ReferenceFrame[source]#

Returns the frame of the hosting pointcloud.

source_points() PointCloud[source]#

Returns the hosting pointcloud.

thickness() ndarray[source]#

Returns the thicknesses of the cells. If not set, a thickness of 1.0 is returned for each cell. Only for 2d cells.

to_parquet(path: str, *args, fields: Iterable[str] | None = None, **kwargs) None[source]#

Saves the data of the database to a parquet file.

Parameters:
  • *args (tuple, Optional) – Positional arguments to specify fields.

  • path (str) – Path of the file being created.

  • fields (Iterable[str], Optional) – Valid field names to include in the parquet files.

  • **kwargs (dict, Optional) – Keyword arguments forwarded to awkward.to_parquet().

to_pv(detach: bool = False) UnstructuredGrid | PolyData[source]#

Returns the block as a PyVista object.

Parameters:

detach (bool, Optional) – Wether to detach the mesh or not. Default is False.

to_simplices() Tuple[ndarray][source]#

Returns the cells of the block, refactorized into simplices. For cells of dimension 2, the returned 2d NumPy integer array represents 3-noded triangles, for 3d cells it is a collection of 4-noded tetrahedra.

to_tetrahedra(flatten: bool | None = True) ndarray[source]#

Returns the topology as a collection of TET4 tetrahedra, represented as a 2d NumPy integer array, where the first axis runs along the tetrahedra, and the second along the nodes.

Only for 3d cells.

Parameters:

flatten (bool, Optional) – If True, the topology is returned as a 2d array. If False, the length of the first axis equals the number of cells in the block, the length of the second axis equals the number of tetrahedra per cell.

to_triangles() ndarray[source]#

Returns the topology as a collection of T3 triangles, represented as a 2d NumPy integer array, where the first axis runs along the triangles, and the second along the nodes.

Only for 2d cells.

to_vtk(detach: bool = False) Any[source]#

Returns the block as a VTK object.

Parameters:

detach (bool, Optional) – Wether to detach the mesh or not. Default is False.

topology() TopologyArray | None[source]#

Returns the numerical representation of the topology of the cells as either a TopologyArray or None if the topology is not specified yet.

unique_indices() ndarray[source]#

Returns the indices of the points involved in the cells of the block as a 1d integer NumPy array.

volume(*args, **kwargs) float[source]#

Returns the volume of the cells in the database.

volumes(*args, **kwargs) ndarray[source]#

Returns the volumes of the cells in the database.

class sigmaepsilon.mesh.data.PolyData(pd: PointData | PolyCell | None = None, cd: PolyCell | None = None, *args, **kwargs)[source]#

A class to handle complex polygonal meshes.

The PolyData class is the most important class in the library and a backbone of all mesh classes.

The implementation is based on the Awkward library, which provides memory-efficient, numba-jittable data classes to deal with dense, sparse, complete or incomplete data. These data structures are managed in pure Python by the DeepDict class.

The class accepts several kinds of inputs, allowing for a wide range of possible use cases. The fastes way to create a PolyData is from predefined PointData and CellData instances, defined separately.

Parameters:
  • pd (Union[PointData, CellData], Optional) – A PolyData or a CellData instance. Dafault is None.

  • cd (CellData, Optional) – A CellData instance, if the first argument is provided. Dafault is None.

Examples

To create a simple cube:

>>> from sigmaepsilon.mesh import PolyData, PointData
>>> from sigmaepsilon.mesh.grid import grid
>>> from sigmaepsilon.mesh.space import StandardFrame
>>> from sigmaepsilon.mesh.cells import H27
>>> size = Lx, Ly, Lz = 100, 100, 100
>>> shape = nx, ny, nz = 10, 10, 10
>>> coords, topo = grid(size=size, shape=shape, eshape='H27')
>>> frame = StandardFrame(dim=3)
>>> mesh = PolyData(pd=PointData(coords=coords, frame=frame))
>>> mesh['A']['Part1'] = PolyData(cd=H27(topo=topo[:10], frames=frame))
>>> mesh['A']['Part2'] = PolyData(cd=H27(topo=topo[10:-10], frames=frame))
>>> mesh['A']['Part3'] = PolyData(cd=H27(topo=topo[-10:], frames=frame))
>>> mesh.plot()

Load a mesh from a PyVista object:

>>> from pyvista import examples
>>> from sigmaepsilon.mesh import PolyData
>>> bunny = examples.download_bunny_coarse()
>>> mesh = PolyData.from_pv(bunny)

Read from a .vtk file:

>>> from sigmaepsilon.mesh import PolyData
>>> from sigmaepsilon.core.downloads import download_stand
>>> vtkpath = download_stand()
>>> mesh = PolyData.read(vtkpath)
area(*args, **kwargs) float[source]#

Returns the sum of areas in the model.

areas(*args, **kwargs) ndarray[source]#

Returns the areas.

blocks(*, inclusive: bool = False, blocktype: Any | None = None, deep: bool = True, **__) Collection[PolyDataLike][source]#

Returns an iterable over nested blocks.

Parameters:
  • inclusive (bool, Optional) – Whether to include the object the call was made upon. Default is False.

  • blocktype (Any, Optional) – A required type. Default is None, which means theat all subclasses of the PolyData class are accepted. Default is None.

  • deep (bool, Optional) – If True, parsing goes into deep levels. If False, only the level of the current object is handled.

Yields:

Any – A PolyData instance. The actual type depends on the ‘blocktype’ parameter.

blocks_of_cells(i: int | Iterable | None = None) dict[source]#

Returns a dictionary that maps cell indices to blocks.

bounds(*args, **kwargs) list[source]#

Returns the bounds of the mesh.

Example

>>> from sigmaepsilon.mesh.examples import download_stand
>>> pd = download_stand(read=True)
>>> pd.bounds()
property cd: PolyCellLike#

Returns the attached celldata.

property cell_fields: Iterable[str]#

Returns the fields of all the celldata of the object.

Returns:

NumPy array of data keys.

Return type:

numpy.ndarray

cell_indices() ndarray[source]#

Returns the indices of the cells along the walk.

cellblocks(*args, **kwargs) Iterable[PolyDataProtocol[PointDataLike, PolyCellLike]][source]#

Returns an iterable over blocks with CellData. All arguments are forwarded to blocks().

Yields:

Any – A CellData instance with a CellData.

See also

blocks(), CellData

property celldata: PolyCellLike#

Returns the attached celldata.

cells_around_cells(radius: float, frmt: str = 'dict') JaggedArray | csr_matrix | dict[source]#

Returns the neares cells to cells.

Parameters:
  • radius (float) – The influence radius of a point.

  • frmt (str, Optional) – A string specifying the type of the result. Valid options are ‘jagged’, ‘csr’ and ‘dict’.

See also

cells_around()

cells_at_nodes(*args, **kwargs) Iterable[source]#

Returns the neighbouring cells of nodes.

Returns:

Some kind of iterable, depending on the inputs. See the docs below for further details.

Return type:

object

See also

cells_at_nodes()

cells_coords() ndarray[source]#

Returns the coordiantes of the cells in explicit format.

center(target: ReferenceFrame | None = None) ndarray[source]#

Returns the center of the pointcloud of the mesh.

Parameters:

target (FrameLike, Optional) – The target frame in which the returned coordinates are to be understood. A None value means the frame the mesh is embedded in. Default is None.

Returns:

A one dimensional float array.

Return type:

numpy.ndarray

centers(target: ReferenceFrame | None = None) ndarray[source]#

Returns the centers of the cells.

Parameters:

target (FrameLike, Optional) – The target frame in which the returned coordinates are to be understood. A None value means the frame the mesh is embedded in. Default is None.

Returns:

A 2 dimensional float array.

Return type:

numpy.ndarray

centralize(target: ReferenceFrame | None = None, inplace: bool | None = True, axes: Iterable[int] | None = None) PolyDataLike[source]#

Moves all the meshes that belong to the same source such that the current object’s center will be at the origin of its embedding frame.

Parameters:
  • target (FrameLike, Optional) – The target frame the mesh should be central to. A None value means the frame the mesh is embedded in. Default is True.

  • inplace (bool, Optional) – If True, the transformation is done on the instance, otherwise a deep copy is created first. Default is True.

  • axes (Iterable[int], Optional) – The axes on which centralization is to be performed. A None value means all axes. For instance providing axes=[2] would only centralize coordinates in Z direction. Default is None.

Notes

This operation changes the coordinates of all blocks that belong to the same pointcloud as the object the function is called on.

property config: DeepDict#

Returns the configuration object.

Returns:

The configuration object.

Return type:

linkeddeepdict.LinkedDeepDict

Example

>>> from sigmaepsilon.mesh.examples import download_stand
>>> mesh = download_stand(read=True)

To set configuration values related to plotting with pyVista, do the following:

>>> mesh.config['pyvista', 'plot', 'color'] = 'red'
>>> mesh.config['pyvista', 'plot', 'style'] = 'wireframe'

Then, when it comes to plotting, you can specify your configuration with the config_key keyword argument:

>>> mesh.pvplot(config_key=('pyvista', 'plot'))

This way, you can store several different configurations for different scenarios.

coords(*args, return_inds: bool | None = False, from_cells: bool | None = False, **kwargs) ndarray[source]#

Returns the coordinates as an array.

Parameters:
  • return_inds (bool, Optional) – Returns the indices of the points. Default is False.

  • from_cells (bool, Optional) – If there is no pointdata attached to the current block, the points of the sublevels of the mesh can be gathered from cell information. Default is False.

Return type:

numpy.ndarray

copy() PolyDataLike[source]#

Returns a shallow copy.

deepcopy() PolyDataLike[source]#

Returns a deep copy.

detach(nummrg: bool | None = False) PolyDataLike[source]#

Returns a detached version of the mesh.

Parameters:

nummrg (bool, Optional) – If True, merges node numbering. Default is False.

property frame: ReferenceFrame#

Returns the frame of the underlying pointcloud.

classmethod from_meshio(mesh: Mesh) PolyDataLike[source]#

Returns a PolyData instance from a meshio.Mesh instance.

Note

See nschloe/meshio for formats supported by meshio. Be sure to install meshio with pip install meshio if you wish to use it.

classmethod from_pv(pvobj: PolyData | PointGrid | UnstructuredGrid) PolyDataLike[source]#

Returns a PolyData instance from a pyvista.PolyData or a pyvista.UnstructuredGrid instance.

Note

See pyvista/pyvista for more examples with pyvista. Be sure to install pyvista with pip install pyvista if you wish to use it.

Example

>>> from pyvista import examples
>>> from sigmaepsilon.mesh import PolyData
>>> bunny = examples.download_bunny_coarse()
>>> mesh = PolyData.from_pv(bunny)
index_of_closest_cell(target: Iterable) int[source]#

Returns the index of the closest cell to a target.

index_of_closest_point(target: Iterable) int[source]#

Returns the index of the closest point to a target.

index_of_furthest_cell(target: Iterable) int[source]#

Returns the index of the furthest cell to a target.

index_of_furthest_point(target: Iterable) int[source]#

Returns the index of the furthest point to a target.

is_2d_mesh() bool[source]#

Returns true if the mesh is a 2-dimensional, ie. it only contains 2 dimensional cells.

is_source(key: str | None = None) bool[source]#

Returns True, if the object is a valid source of data specified by key.

Parameters:

key (str) – A valid key to the PointData of the mesh. If not specified the key is the key used for storing coorindates.

k3dplot(*args, **kwargs) Plot[source]#

Convenience function for plotting the mesh using K3D. All arguments are forwarded to :func:~`sigmaepsilon.mesh.plotting.k3dplot.k3dplot`, refer the documentation of this function for the details.

Warning

During this call there is a UserWarning saying ‘Given trait value dtype “float32” does not match required type “float32”’. Although this is weird, plotting seems to be just fine.

Returns:

A K3D Plot Widget, which is a result of a call to k3d.plot.

Return type:

k3d.Plot

See also

to_k3d(), k3d.plot()

k_nearest_cell_neighbours(k, *args, knn_options: dict | None = None, **kwargs)[source]#

Returns the k closest neighbours of the cells of the mesh, based on the centers of each cell.

The argument knn_options is passed to the KNN search algorithm, the rest to the centers function of the mesh.

Examples

>>> from sigmaepsilon.mesh.grid import Grid
>>> from sigmaepsilon.mesh import KNN
>>> size = 80, 60, 20
>>> shape = 10, 8, 4
>>> grid = Grid(size=size, shape=shape, eshape='H8')
>>> X = grid.centers()
>>> i = KNN(X, X, k=3, max_distance=10.0)

See also

KNN()

lock(create_mappers: bool | None = False) PolyDataLike[source]#

Locks the layout. If a PolyData instance is locked, missing keys are handled the same way as they would’ve been handled if it was a dict. Also, setting or deleting items in a locked dictionary and not possible and you will experience an error upon trying.

The object is returned for continuation.

Parameters:

create_mappers (bool, Optional) – If True, some mappers are generated to speed up certain types of searches, like finding a block containing cells based on their indices.

move(v: Vector | ndarray, frame: ReferenceFrame | None = None, inplace: bool | None = True) PolyDataLike[source]#

Moves and returns the object or a deep copy of it.

Parameters:
  • v (VectorLike, Optional) – A vector describing a translation.

  • frame (FrameLike, Optional) – If v is only an array, this can be used to specify a frame in which the components should be understood.

  • inplace (bool, Optional) – If True, the transformation is done on the instance, otherwise a deep copy is created first. Default is True.

Examples

Download the Stanford bunny and move it along global X:

>>> from sigmaepsilon.mesh.examples import download_bunny
>>> import numpy as np
>>> bunny = download_bunny(tetra=False, read=True)
>>> bunny.move([0.2, 0, 0])
nodal_adjacency(*args, **kwargs) Any[source]#

Returns the nodal adjecency matrix.

Parameters:
  • frmt (str) – A string specifying the output format. Valid options are ‘jagged’, ‘csr’, ‘nx’ and ‘scipy-csr’. See below for the details on the returned object.

  • assume_regular (bool) – If the topology is regular, you can gain some speed with providing it as True. Default is False.

nodal_adjacency_matrix(assume_regular: bool | None = False) spmatrix[source]#

Returns the nodal adjecency information as a SciPy CSR matrix.

Parameters:

assume_regular (bool) –

If the topology is regular, you can gain some speed with providing it as True. Default is False.

New in version 2.3.0.

Return type:

scipy.sparse.spmatrix

nodal_distribution_factors(weights: str | ndarray | None = 'volume') ndarray | csr_matrix[source]#

Retruns nodal distribution factors for all nodes of all cells as a 2d array. The returned array has the same shape as the topology array, where the j-th factor of the i-th row is the contribution of element i to the j-th node of the cell.

Parameters:

weights (Union[str, numpy.ndarray], Optional) – The metric which is used to calculate the factors. Valid strings are ‘volume’ and ‘uniform’. If it is an array, it must be an 1d array with a length matching the number of cells. Default is ‘volume’.

Returns:

An array with the same shape as the topology.

Return type:

numpy.ndarray or sigmaepsilon.math.linalg.sparse.csr.csr_matrix

Note

For a given node, the sum of all contribution factors from all the cells that meet at that node is one.

nodal_neighbourhood_matrix() csr_matrix[source]#

Returns a sparse SciPy CSR matrix as a representation of the first order neighbourhood structure of the mesh.

The [i, j] entry of the returned matrix is 1 if points i and j are neighbours (they share a cell) 0 if they are not. Points are not considered to be neighbours of themselfes, therefore entries in the main diagonal are zero.

New in version 2.3.0.

number_of_cells() int[source]#

Returns the number of cells.

number_of_points() int[source]#

Returns the number of points.

nummrg() PolyDataLike[source]#

Merges node numbering.

property parent: PolyDataLike#

Returns the parent of the object.

property pd: PointDataLike#

Returns the attached pointdata.

plot(*, notebook: bool | None = False, backend: str | None = 'pyvista', config_key: str | None = None, **kwargs) Any[source]#

Plots the mesh using supported backends. The default backend is PyVista.

Parameters:
  • notebook (bool, Optional) – Whether to plot in an IPython notebook enviroment. This is only available for PyVista at the moment. Default is False.

  • backend (str, Optional) – The backend to use. Valid options are ‘k3d’ and ‘pyvista’. Default is ‘pyvista’.

  • config_key (str, Optional) – A configuration key if the block were configured previously. Default is None.

  • **kwargs (dict, Optional) – Extra keyword arguments forwarded to the plotter function according to the selected backend.

See also

pvplot(), k3dplot()

property point_fields: Iterable[str]#

Returns the fields of all the pointdata of the object.

Returns:

NumPy array of data keys.

Return type:

numpy.ndarray

pointblocks(*args, **kwargs) Iterable[PolyDataProtocol[PointDataLike, PolyCellLike]][source]#

Returns an iterable over blocks with PointData. All arguments are forwarded to blocks().

Yields:

Any – A PolyData instance with a PointData.

See also

blocks(), PointData

property pointdata: PointDataLike#

Returns the attached pointdata.

points(*, return_inds: bool | None = False, from_cells: bool | None = False) PointCloud[source]#

Returns the points as a PointCloud instance.

Notes

Opposed to coords(), which returns the coordiantes, it returns the points of a mesh as vectors.

See also

coords()

Return type:

PointCloud

pvplot(*args, **kwargs) None | Plotter | ndarray[source]#

Convenience function for plotting the mesh using PyVista. All arguments are forwarded to :func:~`sigmaepsilon.mesh.plotting.pvplot.pvplot`, refer the documentation of this function for the details.

Note

See pyvista/pyvista for more examples with pyvista. Be sure to install pyvista with pip install pyvista if you wish to use it.

Returns:

A PyVista plotter if return_plotter is True, a NumPy array if return_img is True, or nothing.

Return type:

Union[None, pv.Plotter, numpy.ndarray]

See also

to_pv(), to_vtk()

classmethod read(*args, **kwargs) PolyDataLike[source]#

Reads from a file using PyVista.

Example

Download a .vtk file and read it:

>>> from sigmaepsilon.mesh import PolyData
>>> from sigmaepsilon.mesh.examples import stand_vtk
>>> vtkpath = stand_vtk(read=False)
>>> mesh = PolyData.read(vtkpath)
rewire(deep: bool | None = True, imap: ndarray | None = None, invert: bool | None = False) PolyDataLike[source]#

Rewires topology according to the index mapping of the source object.

Parameters:
  • deep (bool, Optional) – If True, the action propagates down. Default is True.

  • imap (numpy.ndarray, Optional) – Index mapper. Either provided as a numpy array, or it gets fetched from the database. Default is None.

  • invert (bool, Optional) – A flag to indicate wether the provided index map should be inverted or not. Default is False.

Notes

Unless node numbering was modified, subsequent executions have no effect after once called.

Returns:

Returnes the object instance for continuitation.

Return type:

PolyData

rotate(*args, inplace: bool | None = True, **kwargs) PolyDataLike[source]#

Rotates and returns the object. Positional and keyword arguments not listed here are forwarded to sigmaepsilon.math.linalg.frame.ReferenceFrame

Parameters:

Examples

Download the Stanford bunny and rotate it about global Z with 90 degrees:

>>> from sigmaepsilon.mesh.examples import download_bunny
>>> import numpy as np
>>> bunny = download_bunny(tetra=False, read=True)
>>> bunny.rotate("Space", [0, 0, np.pi/2], "xyz")
source(key: str | None = None) PolyDataProtocol[PointDataLike, PolyCellLike] | None[source]#

Returns the closest (going upwards in the hierarchy) block that holds on to data with a certain field name. If called without arguments, it is looking for a block with a valid pointcloud, definition, otherwise the field specified by the argument key.

Parameters:

key (str) – A valid key in any of the blocks with data. Default is None.

spin(*args, inplace: bool | None = True, **kwargs) PolyDataLike[source]#

Like rotate, but rotation happens around centroidal axes. Positional and keyword arguments not listed here are forwarded to sigmaepsilon.math.linalg.frame.ReferenceFrame

Parameters:

Examples

Download the Stanford bunny and spin it about global Z with 90 degrees:

>>> from sigmaepsilon.mesh.examples import download_bunny
>>> import numpy as np
>>> bunny = download_bunny(tetra=False, read=True)
>>> bunny.spin("Space", [0, 0, np.pi/2], "xyz")
surface(mesh_class: PolyDataLike | None = None) PolyDataLike[source]#

Returns the surface of the mesh as another PolyData instance.

Parameters:

mesh_class (PolyDataLike, Optional) –

The class of the resulting mesh instance. The default is sigmaepsilon.mesh.PolyData.

New in version 2.3.0.

surface_centers(*args, **kwargs) ndarray[source]#

Retuns the surface centers as a 3d numpy array.

New in version 2.3.0.

Note

It only works in cases where the call to surface returns a mesh with a normals method, like a Trimesh instance.

surface_normals(*args, **kwargs) ndarray[source]#

Retuns the surface normals as a 2d numpy array.

New in version 2.3.0.

Note

It only works in cases where the call to surface returns a mesh with a normals method, like a Trimesh instance.

to_ak(*args, point_fields: Iterable[str] | None = None, cell_fields: Iterable[str] | None = None, **__) Tuple[Array][source]#

Returns the data contained within the mesh as a tuple of two Awkward arrays.

Parameters:
  • point_fields (Iterable[str], Optional) – A list of keys that might identify data in a database for the points in the mesh. Default is None.

  • cell_fields (Iterable[str], Optional) – A list of keys that might identify data in a database for the cells in the mesh. Default is None.

Example

>>> from sigmaepsilon.mesh.examples import stand_vtk
>>> mesh = stand_vtk(read=True)
>>> mesh.to_ak(point_fields=['x'])
to_dataframe(*args, point_fields: Iterable[str] | None = None, cell_fields: Iterable[str] | None = None, **kwargs)[source]#

Returns the data contained within the mesh to pandas dataframes.

Parameters:
  • point_fields (Iterable[str], Optional) – A list of keys that might identify data in a database for the points in the mesh. Default is None.

  • cell_fields (Iterable[str], Optional) – A list of keys that might identify data in a database for the cells in the mesh. Default is None.

Example

>>> from sigmaepsilon.mesh.examples import stand_vtk
>>> mesh = stand_vtk(read=True)
>>> mesh.to_dataframe(point_fields=['x'])
to_k3d(*args, **kwargs) Plot[source]#

Returns the mesh as a k3d mesh object. All arguments are forwarded to :func:~`sigmaepsilon.mesh.io.to_k3d.to_k3d`, refer to its documentation for the details.

:: warning:

Calling this method raises a UserWarning inside the traittypes package saying “Given trait value dtype ‘float32’ does not match required type ‘float32’.” However, plotting seems to be fine.

Returns:

A K3D Plot Widget, which is a result of a call to k3d.plot.

Return type:

k3d.Plot

to_lists(*, point_fields: Iterable[str] | None = None, cell_fields: Iterable[str] | None = None) Tuple[list][source]#

Returns data of the object as a tuple of lists. The first is a list of point-related, the other one is cell-related data. Unless specified by ‘fields’, all data is returned from the pointcloud and the related cells of the mesh.

Parameters:
  • point_fields (Iterable[str], Optional) – A list of keys that might identify data in a database for the points in the mesh. Default is None.

  • cell_fields (Iterable[str], Optional) – A list of keys that might identify data in a database for the cells in the mesh. Default is None.

Example

>>> from sigmaepsilon.mesh.examples import stand_vtk
>>> mesh = stand_vtk(read=True)
>>> mesh.to_lists(point_fields=['x'])
to_parquet(path_pd: str, path_cd: str, *args, point_fields: Iterable[str] | None = None, cell_fields: Iterable[str] | None = None, **kwargs)[source]#

Saves the data contained within the mesh to parquet files.

Parameters:
  • path_pd (str) – File path for point-related data.

  • path_cd (str) – File path for cell-related data.

  • point_fields (Iterable[str], Optional) – A list of keys that might identify data in a database for the points in the mesh. Default is None.

  • cell_fields (Iterable[str], Optional) – A list of keys that might identify data in a database for the cells in the mesh. Default is None.

Example

>>> from sigmaepsilon.mesh.examples import stand_vtk
>>> mesh = stand_vtk(read=True)
>>> mesh.to_parquet('pd.parquet', 'cd.parquet', point_fields=['x'])
to_pv(deepcopy: bool | None = False, multiblock: bool | None = False, scalars: str | ndarray | None = None) UnstructuredGrid | MultiBlock[source]#

Returns the mesh as a PyVista object, optionally set up with data.

Parameters:
  • deepcopy (bool, Optional) – Default is False.

  • multiblock (bool, Optional) – Wether to return the blocks as a vtkMultiBlockDataSet or a list of vtkUnstructuredGrid instances. Default is False.

  • scalars (str or numpy.ndarray, Optional) – A string or an array describing scalar data. Default is None.

Return type:

pyvista.UnstructuredGrid or pyvista.MultiBlock

to_standard_form(inplace: bool | None = True, default_point_fields: dict | None = None, default_cell_fields: dict | None = None) PolyDataLike[source]#

Transforms the problem to standard form, which means a centralized pointdata and regular cell indices.

Notes

Some operation might work better if the layout of the mesh admits the standard form.

Parameters:
  • inplace (bool, Optional) – Performs the operations inplace. Default is True.

  • default_point_fields (dict, Optional) – A dictionary to define default values for missing fields for point related data. If not specified, the default is numpy.nan.

  • default_cell_fields (dict, Optional) – A dictionary to define default values for missing fields for cell related data. If not specified, the default is numpy.nan.

to_vtk(deepcopy: bool | None = False, multiblock: bool | None = False) vtkUnstructuredGrid | vtkMultiBlockDataSet[source]#

Returns the mesh as a VTK object.

Parameters:
  • deepcopy (bool, Optional) – Default is False.

  • multiblock (bool, Optional) – Wether to return the blocks as a vtkMultiBlockDataSet or a list of vtkUnstructuredGrid instances. Default is False.

Return type:

vtk.vtkUnstructuredGrid or vtk.vtkMultiBlockDataSet

topology(*args, return_inds: bool | None = False, **kwargs) TopologyArray[source]#

Returns the topology.

Parameters:

return_inds (bool, Optional) – Returns the indices of the points. Default is False.

Return type:

TopologyArray

unlock() PolyDataLike[source]#

Releases the layout. If a sigmaepsilon.mesh instance is not locked, a missing key creates a new level in the layout, also setting and deleting items becomes an option. Additionally, mappers created with the call generate_cell_mappers are deleted.

The object is returned for continuation.

volume(*args, **kwargs) float[source]#

Returns the net volume of the mesh.

volumes(*args, **kwargs) ndarray[source]#

Returns the volumes of the cells.

class sigmaepsilon.mesh.data.TriMesh(pd: PointData | PolyCell | None = None, cd: PolyCell | None = None, *args, **kwargs)[source]#

A class to handle triangular meshes.

All positional and keyword arguments not listed here are forwarded to PolyData.

Besides the arguments coords and topo, this class accepts these using aliases points and triangles.

Parameters:
  • points (numpy.ndarray, Optional) – 2d numpy array of floats, describing a pointcloud. Default is None.

  • triangles (numpy.ndarray, Optional) – 2d numpy array of integers, describing the topology of a polygonal mesh. Default is None.

Notes

See the PolyData class for the rest of the possible arguments to the creator of this class. Note that, points and triangles are aliases to coords and topo, but the original terminology is still available.

Examples

Triangulate a rectangle of size 800x600 with a subdivision of 10x10 and calculate the area

>>> from sigmaepsilon.mesh import TriMesh, CartesianFrame, PointData, triangulate
>>> from sigmaepsilon.mesh.cells import T3
>>> A = CartesianFrame(dim=3)
>>> coords, topo = triangulate(size=(800, 600), shape=(10, 10))
>>> pd = PointData(coords=coords, frame=A)
>>> cd = T3(topo=topo)
>>> trimesh = TriMesh(pd, cd)
>>> trimesh.area()
480000.0

Extrude to create a tetrahedral mesh

>>> tetmesh = trimesh.extrude(h=300, N=5)
>>> tetmesh.volume()
144000000.0

Calculate normals and tell if the triangles form a planar surface or not

>>> trimesh.normals()
>>> trimesh.is_planar()
True

Create a circular disk

>>> from sigmaepsilon.mesh.recipes import circular_disk
>>> trimesh = circular_disk(120, 60, 5, 25)
axes() ndarray[source]#

Returns the normalized coordinate frames of triangles as a 3d numpy array.

edges(return_cells: bool = False) Tuple[ndarray, ndarray | None][source]#

Returns point indices of the unique edges in the model. If return_cells is True, it also returns the edge indices of the triangles, referencing the edges.

Parameters:

return_cells (bool, Optional) – If True, returns the edge indices of the triangles, that can be used to reconstruct the topology. Default is False.

Returns:

  • numpy.ndarray – Integer array of indices, representing point indices of edges.

  • numpy.ndarray, Optional – Integer array of indices, that together with the edge data reconstructs the topology.

extrude(*, h: float | None = None, N: int | None = None) PolyData[source]#

Exctrude mesh perpendicular to the plane of the triangulation. The target element type can be specified with the celltype argument.

Parameters:
  • h (float, Optional) – Size perpendicular to the plane of the surface to be extruded.

  • N (int, Optional) – Number of subdivisions along the perpendicular direction.

Returns:

A tetrahedral mesh.

Return type:

TetMesh

is_planar() bool[source]#

Returns True if the triangles form a planar surface.

normals() ndarray[source]#

Retuns the surface normals as a 2d numpy array.

to_triobj() Any[source]#

Returns a triangulation object of a specified backend. See triangulate() for the details.

Note

During the process, the 6-noded triangles of the section are converted into 3-noded ones.