The Mesh class#

class pylife.mesh.Mesh(pandas_obj)[source]#

Access connected finite-element mesh data.

A connected mesh stores one row per node occurrence in an element. The DataFrame must have coordinate columns x and y in mm and may have z for three-dimensional meshes. Its index must contain the levels element_id and node_id; together they identify a unique row.

Signal contract:

  • element_id : Index level identifying the finite element.

  • node_id : Index level identifying the node used by the element.

  • x : Coordinate in mm along the global x-axis.

  • y : Coordinate in mm along the global y-axis.

  • z : Optional coordinate in mm along the global z-axis.

Parameters:

pandas_obj (pandas.DataFrame) – DataFrame with a pandas.MultiIndex containing element_id and node_id and with coordinate columns in mm.

Raises:
  • AttributeError – If at least one of the columns x or y is missing.

  • AttributeError – If the index of the DataFrame does not contain the levels node_id and element_id.

See also

pylife.mesh.meshsignal.PlainMesh

Access meshes without connectivity information.

pandas.api.extensions.register_dataframe_accessor

Register pandas DataFrame accessors.

Notes

A node can occur in several elements, and each element contains several nodes. The combination of element_id and node_id is expected to be unique. pyLife functions preserve this full mesh index unless a method explicitly returns node-averaged data indexed only by node_id.

Examples

>>> import pandas as pd
>>> index = pd.MultiIndex.from_tuples(
...     [(1, 10), (1, 11), (1, 12)], names=["element_id", "node_id"]
... )
>>> mesh = pd.DataFrame({"x": [0.0, 1.0, 0.0], "y": [0.0, 0.0, 1.0]}, index=index)
>>> mesh.mesh.connectivity.loc[1].tolist()
[10, 11, 12]
broadcast(parameter, droplevel=None)#

Broadcast the parameter to the object of self.

Parameters:
  • parameter (scalar, numpy.ndarray, pandas.Series or pandas.DataFrame) – The operand to align with the object of self.

  • droplevel (list of str, optional) – Names of index levels that are dropped from the returned parameter before it is returned. Use it when a parameter must not be resolved along those levels, e.g. when a material parameter is constant over all load steps. Default is None, which keeps all levels.

Returns:

  • parameter (scalar, pandas.Series or pandas.DataFrame) – The broadcast operand, index aligned with obj.

  • obj (pandas.Series or pandas.DataFrame) – The broadcast object of self, index aligned with parameter.

Examples

The behavior of the Broadcaster is best illustrated by examples:

  • Broadcasting pandas.Series to a scalar results in a scalar and a pandas.Series.

    obj = pd.Series([1.0, 2.0], index=pd.Index(['foo', 'bar'], name='idx'))
    obj
    
    idx
    foo    1.0
    bar    2.0
    dtype: float64
    
    parameter, obj = Broadcaster(obj).broadcast(5.0)
    
    parameter
    
    array(5.)
    
    obj
    
    idx
    foo    1.0
    bar    2.0
    dtype: float64
    
  • Broadcasting pandas.DataFrame to a scalar results in a pandas.DataFrame and a pandas.Series.

    obj = pd.DataFrame({
        'foo': [1.0, 2.0],
        'bar': [3.0, 4.0]
    }, index=pd.Index([1, 2], name='idx'))
    obj
    
    foo bar
    idx
    1 1.0 3.0
    2 2.0 4.0
    parameter, obj = Broadcaster(obj).broadcast(5.0)
    
    parameter
    
    idx
    1    5.0
    2    5.0
    dtype: float64
    
    obj
    
    foo bar
    idx
    1 1.0 3.0
    2 2.0 4.0
  • Broadcasting pandas.DataFrame to a a pandas.Series results in a pandas.DataFrame and a pandas.Series, if and only if the index name of the object is None.

    obj = pd.Series([1.0, 2.0], index=pd.Index(['tau', 'chi']))
    obj
    
    tau    1.0
    chi    2.0
    dtype: float64
    
    parameter = pd.Series([3.0, 4.0], index=pd.Index(['foo', 'bar'], name='idx'))
    parameter
    
    idx
    foo    3.0
    bar    4.0
    dtype: float64
    
    parameter, obj = Broadcaster(obj).broadcast(parameter)
    
    parameter
    
    idx
    foo    3.0
    bar    4.0
    dtype: float64
    
    obj
    
    tau chi
    idx
    foo 1.0 2.0
    bar 1.0 2.0
property connectivity#

Return the node connectivity of each element.

Returns:

Series indexed by element_id. Each value is a numpy.ndarray with the node_id values that define the element connectivity.

Return type:

pandas.Series

property coordinates#

Return the coordinate columns of the accessed DataFrame.

Returns:

Coordinate columns x and y and, for three-dimensional meshes, z. Values are coordinates in mm and the returned DataFrame carries the same index as the accessed object.

Return type:

pandas.DataFrame

property dimensions#

Return the spatial dimension of the mesh.

Returns:

Spatial dimension, either 2 for a planar mesh or 3 for a mesh with varying z coordinates. Coordinates are interpreted in mm.

Return type:

int

Notes

If column z is missing or all values in column z are equal, the mesh is considered two-dimensional.

fail_if_key_missing(keys_to_check, msg=None)#

Raise an exception if any key is missing in the signal.

Parameters:
  • keys_to_check (list of str) – The keys that need to be available in the signal.

  • msg (str, optional) – A printf style format string for the error message taking two %s arguments: the expected keys and the missing keys. By default a message naming the signal class is generated.

Raises:

AttributeError – If the underlying object is neither a pandas.DataFrame nor a pandas.Series, or if any of keys_to_check is not provided by the signal.

See also

get_missing_keys

Return the missing keys instead of raising.

Notes

This is the canonical way to assert a signal contract in the _validate() implementation of a derived class.

classmethod from_parameters(**kwargs)#

Make a signal instance from a parameter set.

This is a convenience function to instantiate a signal from individual parameters rather than from a pandas object.

Parameters:

**kwargs (scalar or array_like) – The signal keys and their values. If more than one value is given and the values are iterable, a pandas.DataFrame backed signal is created, otherwise a pandas.Series backed one.

Returns:

An instance of the signal class the method is called on.

Return type:

PylifeSignal

Examples

For a signal class like

@pd.api.extensions.register_dataframe_accessor('foo_signal')
class FooSignal(PylifeSignal):
    pass

the following two expressions are equivalent

pd.Series({'foo': 1.0, 'bar': 2.0}).foo_signal
FooSignal.from_parameters(foo=1.0, bar=2.0)
get_missing_keys(keys_to_check)#

Get a list of keys that are missing in the signal.

Parameters:

keys_to_check (list of str) – The keys that need to be available in the signal.

Returns:

The keys of keys_to_check that the signal does not provide, in the order in which they were given. An empty list means that the signal is complete.

Return type:

list of str

Raises:

AttributeError – If the underlying object is neither a pandas.DataFrame nor a pandas.Series.

See also

fail_if_key_missing

Raise instead of returning the missing keys.

Notes

This method is meant to be used in the _validate() implementation of a derived class when a missing key is not necessarily an error, e.g. when a default value can be derived.

keys()#

Get the keys the signal provides.

Returns:

The keys of the underlying pandas object.

Return type:

pandas.Index

Raises:

AttributeError – If the underlying object is neither a pandas.DataFrame nor a pandas.Series.

Notes

For a pandas.DataFrame backed signal the columns are returned, for a pandas.Series backed one the index.

to_pandas()#

Expose the pandas object of the signal.

Returns:

The pandas object representing the signal.

Return type:

pandas.DataFrame or pandas.Series

Notes

The default implementation just returns the object given when instantiating the signal class. Derived classes may return a modified or augmented object, if they store some extra information.

By default the object is not copied. So make a copy yourself, if you intend to modify it.

vtk_data()[source]#

Create VTK arrays for plotting the mesh with pyVista.

Returns:

  • cells (numpy.ndarray) – The location of the cells describing the points in a way pyVista.UnstructuredGrid expects it.

  • cell_types (numpy.ndarray) – The VTK element type codes for the cells.

  • points (numpy.ndarray) – Coordinates in mm of the cell points. Rows are sorted by node_id and columns are x, y and, for 3D meshes, z.

Notes

This is a convenience method for visualization. It prepares data that can be passed as pv.UnstructuredGrid(*mesh.mesh.vtk_data()). For quadratic elements, only the first-order corner nodes are used because the VTK element codes selected here describe first-order geometry.

Examples

>>> import pandas as pd
>>> index = pd.MultiIndex.from_tuples(
...     [(1, 10), (1, 11), (1, 12)], names=["element_id", "node_id"]
... )
>>> mesh = pd.DataFrame({"x": [0.0, 1.0, 0.0], "y": [0.0, 0.0, 1.0]}, index=index)
>>> cells, cell_types, points = mesh.mesh.vtk_data()
>>> cells.tolist()
[3, 0, 1, 2]
>>> cell_types.tolist()
[5]
>>> points.tolist()
[[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]