Source code for dolfinx.fem.element

# Copyright (C) 2024-2026 Garth N. Wells, Paul T. Kühner and
# Jørgen S. Dokken
#
# This file is part of DOLFINx (https://www.fenicsproject.org)
#
# SPDX-License-Identifier:    LGPL-3.0-or-later
"""Finite elements."""

from functools import singledispatch
from typing import ClassVar, Generic, cast

import numpy as np
import numpy.typing as npt

import basix
import basix._basixcpp
import basix.ufl
from dolfinx import cpp as _cpp
from dolfinx.typing import Real


[docs] class ElementDofLayout: """Layout of the degrees-of-freedom on a cell. Describes which degrees-of-freedom of a cell are associated with each sub-entity (vertex, edge, face, cell) of the cell. """ _cpp_object: _cpp.fem.ElementDofLayout def __init__(self, dof_layout: _cpp.fem.ElementDofLayout): """Initialize a dof layout from a C++ ElementDofLayout. Note: Dof layouts are obtained from :attr:`DofMap.dof_layout <dolfinx.fem.DofMap.dof_layout>` or :meth:`CoordinateElement.create_dof_layout`, and not created using this initialiser. Args: dof_layout: The C++ dof layout object. """ self._cpp_object = dof_layout def __eq__(self, other: object) -> bool: """Check that two wrappers hold the same dof layout.""" if not isinstance(other, ElementDofLayout): return NotImplemented return self._cpp_object == other._cpp_object def __hash__(self) -> int: """Hash of the wrapped dof layout.""" return hash(self._cpp_object) @property def num_dofs(self) -> int: """Number of degrees-of-freedom on the cell.""" return self._cpp_object.num_dofs @property def block_size(self) -> int: """Block size of the layout.""" return self._cpp_object.block_size
[docs] def entity_dofs(self, dim: int, entity_index: int) -> list[int]: """Degrees-of-freedom associated with a sub-entity of the cell. Args: dim: Topological dimension of the sub-entity. entity_index: Local index of the sub-entity. Returns: Cell-local degrees-of-freedom on the sub-entity, excluding those on its boundary. """ return self._cpp_object.entity_dofs(dim, entity_index)
[docs] def entity_closure_dofs(self, dim: int, entity_index: int) -> list[int]: """Degrees-of-freedom on the closure of a sub-entity. Args: dim: Topological dimension of the sub-entity. entity_index: Local index of the sub-entity. Returns: Cell-local degrees-of-freedom on the sub-entity and on its boundary. """ return self._cpp_object.entity_closure_dofs(dim, entity_index)
[docs] class CoordinateElement(Generic[Real]): """Coordinate element describing the geometry map for mesh cells.""" # Built-in geometry types. Public: extend with additional geometry # dtypes as needed. cpp_types: ClassVar[dict] = { np.dtype(np.float32): _cpp.fem.CoordinateElement_float32, np.dtype(np.float64): _cpp.fem.CoordinateElement_float64, } _cpp_object: _cpp.fem.CoordinateElement_float32 | _cpp.fem.CoordinateElement_float64 def __init__( self, cmap: _cpp.fem.CoordinateElement_float32 | _cpp.fem.CoordinateElement_float64 ): """Create a coordinate map element. Note: This initialiser is for internal use and not normally called in user code. Use :func:`coordinate_element` to create a CoordinateElement. Args: cmap: A C++ CoordinateElement. """ assert isinstance( cmap, _cpp.fem.CoordinateElement_float32 | _cpp.fem.CoordinateElement_float64 ) self._cpp_object = cmap @property def dtype(self) -> np.dtype: """Scalar type for the coordinate element.""" return np.dtype(self._cpp_object.dtype) @property def dim(self) -> int: """Dimension of the coordinate element space. This is number of basis functions that span the coordinate space, e.g., for a linear triangle cell the dimension will be 3. """ return self._cpp_object.dim
[docs] def hash(self) -> int: """Hash identifier of the coordinate element.""" return self._cpp_object.hash()
[docs] def create_dof_layout(self) -> ElementDofLayout: """Compute and return the dof layout.""" return ElementDofLayout(self._cpp_object.create_dof_layout())
[docs] def push_forward( self, X: npt.NDArray[Real], cell_geometry: npt.NDArray[Real] ) -> npt.NDArray[Real]: """Push points on the reference cell forward to the physical cell. Args: X: Coordinates of points on the reference cell, ``shape=(num_points, topological_dimension)``. cell_geometry: Coordinate 'degrees-of-freedom' (nodes) of the cell, ``shape=(num_geometry_basis_functions, geometrical_dimension)``. Can be created by accessing ``geometry.x[geometry.dofmaps[0].cell_dofs(i)]``, Returns: Physical coordinates of the points reference points ``X``. """ return self._cpp_object.push_forward(X, cell_geometry) # type: ignore[arg-type,return-value]
[docs] def pull_back( self, x: npt.NDArray[Real], cell_geometry: npt.NDArray[Real], *, tol: float | None = None, maxit: int = 15, working_array: npt.NDArray[Real] | None = None, ) -> npt.NDArray[Real]: """Pull points on the physical cell back to the reference cell. For non-affine cells, the pull-back is a nonlinear operation. Args: x: Physical coordinates to pull back to the reference cells, ``shape=(num_points, geometrical_dimension)``. cell_geometry: Physical coordinates describing the cell, shape ``(num_of_geometry_basis_functions, geometrical_dimension)``. They can be created by accessing ``geometry.x[geometry.dofmaps[0].cell_dofs(i)]``, tol: Tolerance for convergence in Newton method for nonaffine pullbacks. If not provided, it is set from the square root of the machine epsilon of ``x``'s dtype, since a fixed value tuned for ``float64`` is often unreachable in ``float32`` arithmetic. maxit: Maximum number of Newton iterations for nonaffine pullbacks. working_array: Working memory for the pull-back operation. If not provided, a new array will be allocated. The size of the working array can be computed using :func:`pull_back_working_size`. Returns: Reference coordinates of the physical points ``x``. """ if tol is None: tol = float(np.sqrt(np.finfo(x.dtype).eps)) if working_array is None: working_array = np.zeros(self.pull_back_working_size(x.shape[1]), dtype=x.dtype) return self._cpp_object.pull_back(x, cell_geometry, tol, maxit, working_array) # type: ignore[arg-type,return-value]
@property def variant(self) -> int: """Lagrange variant of the coordinate element. Note: The return type is an integer. A Basix enum can be created using ``basix.LagrangeVariant(value)``. """ return self._cpp_object.variant @property def degree(self) -> int: """Polynomial degree of the coordinate element.""" return self._cpp_object.degree @property def is_discontinuous(self) -> bool: """Whether the element is the discontinuous version of the element. A discontinuous coordinate element associates all of its degrees-of-freedom with the cell, so coordinate nodes are not shared between cells and the geometry may be discontinuous across cell facets. """ return self._cpp_object.is_discontinuous
[docs] def pull_back_working_size(self, gdim: int) -> int: """Compute the working array size required for pull back. Args: gdim: Geometrical dimension of input points Returns: Number of elements required in the working array for pull back. """ return self._cpp_object.pull_back_working_size(gdim)
[docs] @singledispatch def coordinate_element( celltype: _cpp.mesh.CellType | basix.finite_element.FiniteElement, degree: int, variant: int = int(basix.LagrangeVariant.unset), dtype: npt.DTypeLike = np.float64, discontinuous: bool = False, ) -> CoordinateElement: """Create a Lagrange CoordinateElement from element metadata. Coordinate elements are typically used to create meshes. Args: celltype: Cell shape degree: Polynomial degree of the coordinate element map. variant: Basix Lagrange variant (affects node placement). dtype: Scalar type for the coordinate element. discontinuous: Continuity of the coordinate element. Returns: A coordinate element. """ cpp_type = CoordinateElement.cpp_types[np.dtype(dtype)] return CoordinateElement(cpp_type(celltype, degree, variant, discontinuous))
@coordinate_element.register(basix.finite_element.FiniteElement) def _coordinate_element_from_basix(e: basix.finite_element.FiniteElement) -> CoordinateElement: """Create a Lagrange CoordinateElement from a Basix finite element. Coordinate elements are typically used when creating meshes. Args: e: Basix finite element. Returns: A coordinate element. """ cpp_type = CoordinateElement.cpp_types[e.dtype] return CoordinateElement(cpp_type(e._e))
[docs] class FiniteElement(Generic[Real]): """A finite element.""" # Built-in geometry types. Public: extend with additional geometry # dtypes as needed. cpp_types: ClassVar[dict] = { np.dtype(np.float32): _cpp.fem.FiniteElement_float32, np.dtype(np.float64): _cpp.fem.FiniteElement_float64, } _cpp_object: _cpp.fem.FiniteElement_float32 | _cpp.fem.FiniteElement_float64 def __init__( self, cpp_object: _cpp.fem.FiniteElement_float32 | _cpp.fem.FiniteElement_float64, ): """Creates a Python wrapper for the exported finite element class. Note: Do not use this constructor directly. Instead use :func:`finiteelement`. Args: cpp_object: Underlying cpp instance that this object will wrap. """ self._cpp_object = cpp_object def __eq__(self, other: object) -> bool: """Check equality with another finite element.""" if not isinstance(other, FiniteElement): return NotImplemented return self._cpp_object == other._cpp_object @property def dtype(self) -> np.dtype: """Geometry type of the mesh that the space is defined on.""" return np.dtype(self._cpp_object.dtype) @property def basix_element( self, ) -> basix._basixcpp.FiniteElement_float32 | basix._basixcpp.FiniteElement_float64: """Return underlying Basix C++ element (if it exists). Raises: RuntimeError: If a Basix element does not exist. """ return cast( "basix._basixcpp.FiniteElement_float32 | basix._basixcpp.FiniteElement_float64", self._cpp_object.basix_element, ) @property def num_sub_elements(self) -> int: """Number of sub elements (for a mixed or blocked element).""" return self._cpp_object.num_sub_elements @property def physical_base_value_size(self) -> int: """Number of physical components in one block of the field. A blocked element repeats a scalar base element {py:attr}<FiniteElement.block_size> times, so one block of its field is a single scalar and this is 1. A non-blocked element has a single block, so this is {py:attr}<FiniteElement.value_size>. This is the size of the push-forward of one (non-blocked) basis function, and hence the extent a buffer needs when it holds physical values one block at a time. It is the physical counterpart of {py:attr}<FiniteElement.reference_value_size>, and equals it unless the element is Piola mapped on a manifold, where it is `gdim` rather than `tdim`. """ return self._cpp_object.physical_base_value_size @property def value_shape(self) -> npt.NDArray[np.integer]: """Value shape of the finite element field in physical space. The value shape describes the shape of the finite element field after the basis has been pushed forward to a physical cell, e.g. ``()`` for a scalar, ``(2,)`` for a vector in 2D, ``(3, 3)`` for a rank-2 tensor in 3D. It always agrees with ``FunctionSpace.value_shape``, which UFL derives from the element's pullback and the geometric dimension. It differs from :attr:`reference_value_shape` for blocked and quadrature elements, and for a Piola-mapped element on a manifold: Raviart-Thomas on a triangle embedded in 3D has value shape ``(3,)`` and reference value shape ``(2,)``. """ return self._cpp_object.value_shape @property def reference_value_shape(self) -> npt.NDArray[np.integer]: """Value shape of the base element on the reference cell. This is the shape Basix tabulates in, with any blocking removed, so it is ``()`` for blocked and quadrature elements. Use :attr:`value_shape` for anything user-facing; this is for code that works with tabulated reference data. """ return self._cpp_object.reference_value_shape @property def interpolation_points(self) -> npt.NDArray[Real]: """Points at which to evaluate the function to be interpolated. Interpolation point coordinates on the reference cell, returning the coordinates data (row-major) storage with shape ``(num_points, tdim)``. Note: For Lagrange elements the points will just be the nodal positions. For other elements the points will typically be the quadrature points used to evaluate moment degrees of freedom. """ return self._cpp_object.interpolation_points() # type: ignore[return-value] @property def interpolation_ident(self) -> bool: """Check if interpolation into space is the identity. True if interpolation into the finite element space is an identity operation given the evaluation on an expression at specific points, i.e. the degree-of-freedom are equal to point evaluations. The function will return `true` for Lagrange elements. """ return self._cpp_object.interpolation_ident @property def space_dimension(self) -> int: """Dimension of the finite element function space. This is the number of degrees-of-freedom for the element. For 'blocked' elements, this function returns the dimension of the full element rather than the dimension of the base element. """ return self._cpp_object.space_dimension @property def needs_dof_transformations(self) -> bool: """Check if DOF transformations are needed for this element. DOF transformations will be needed for elements which might not be continuous when two neighbouring cells disagree on the orientation of a shared sub-entity, and when this cannot be corrected for by permuting the DOF numbering in the dofmap. For example, Raviart-Thomas elements will need DOF transformations, as the neighbouring cells may disagree on the orientation of a basis function, and this orientation cannot be corrected for by permuting the DOF numbers on each cell. """ return self._cpp_object.needs_dof_transformations @property def signature(self) -> str: """String identifying the finite element.""" return self._cpp_object.signature
[docs] def T_apply( self, x: npt.NDArray[Real], cell_permutations: npt.NDArray[np.uint32], dim: int ) -> None: """Transform basis from reference to physical ordering/orientation. Transform basis functions from the reference element ordering and orientation to the globally consistent physical element ordering and orientation. Args: x: Data to transform (in place). The shape is ``(num_cells, n, dim)``, where ``n`` is the number degrees- of-freedom and the data is flattened (row-major). cell_permutations: Permutation data for the cell. dim: Number of columns in ``data``. Note: Exposed for testing. Function is not vectorised across multiple cells. Please see `basix.numba_helpers` for performant versions. """ self._cpp_object.T_apply(x, cell_permutations, dim) # type: ignore[arg-type]
[docs] def Tt_apply( self, x: npt.NDArray[Real], cell_permutations: npt.NDArray[np.uint32], dim: int ) -> None: """Apply the transpose of the operator applied by T_apply(). Args: x: Data to transform (in place). The shape is ``(num_cells, n, dim)``, where ``n`` is the number degrees- of-freedom and the data is flattened (row-major). cell_permutations: Permutation data for the cells dim: Number of columns in ``data``. """ self._cpp_object.Tt_apply(x, cell_permutations, dim) # type: ignore[arg-type]
[docs] def Tt_inv_apply( self, x: npt.NDArray[Real], cell_permutations: npt.NDArray[np.uint32], dim: int ) -> None: """Apply the inverse transpose of T_apply(). Args: x: Data to transform (in place). The shape is ``(num_cells, n, dim)``, where ``n`` is the number degrees- of-freedom and the data is flattened (row-major). cell_permutations: Permutation data for the cells dim: Number of columns in ``data``. """ self._cpp_object.Tt_inv_apply(x, cell_permutations, dim) # type: ignore[arg-type]
[docs] def finiteelement( cell_type: _cpp.mesh.CellType, ufl_e: basix.ufl._ElementBase, FiniteElement_dtype: npt.DTypeLike, gdim: int, ) -> FiniteElement: """Create a DOLFINx element from a basix.ufl element. Args: cell_type: Element cell type, see ``mesh.CellType`` ufl_e: UFL element, holding quadrature rule and other properties of the selected element. FiniteElement_dtype: Geometry type of the element. gdim: Geometric dimension of the mesh the element will be used on. A Piola-mapped basis is pushed forward with a Jacobian of shape ``(gdim, tdim)``, so on a manifold the element's value shape in physical space is not its reference value shape. """ CppElement = FiniteElement.cpp_types[np.dtype(FiniteElement_dtype)] if ufl_e.is_mixed: elements = [ finiteelement( cell_type, cast(basix.ufl._ElementBase, e), FiniteElement_dtype, gdim )._cpp_object for e in ufl_e.sub_elements ] return FiniteElement(CppElement(elements)) elif ufl_e.is_quadrature: # Quadrature elements are identity mapped, so the reference # value shape is also the physical value shape. return FiniteElement( CppElement( cell_type, ufl_e.custom_quadrature()[0], ufl_e.reference_value_shape, ufl_e.is_symmetric, ) ) else: basix_e = ufl_e.basix_element._e block_shape = ufl_e.reference_value_shape if ufl_e.block_size > 1 else None return FiniteElement(CppElement(basix_e, gdim, block_shape, ufl_e.is_symmetric))