dolfinx.fem#

Tools for assembling and manipulating finite element forms.

Note

dolfinx.fem.petsc and dolfinx.fem.problems require optional dependencies and must be explicitly imported.

Functions

apply_lifting(b, a, bcs[, x0, alpha, ...])

Modify right-hand side for lifting of Dirichlet conditions.

assemble_matrix(-> ~dolfinx.la.MatrixCSR)

Assemble bilinear form into a matrix.

assemble_matrix_fn(fn, a[, bcs])

Assemble a bilinear form, inserting element matrices via fn.

assemble_scalar(M[, constants, coeffs])

Assemble functional.

assemble_vector(...)

Assemble linear form into a vector.

bcs_by_block(spaces, bcs)

Arrange boundary conditions by the space that they constrain.

build_sparsity_pattern(pattern, a)

Build a sparsity pattern from a bilinear form.

compile_form(comm, form[, ...])

Compile UFL form without associated DOLFINx data.

compute_integration_domains(integral_type, ...)

Determine compute integration entities.

coordinate_element(...)

Create a Lagrange CoordinateElement from element metadata.

create_dofmaps(comm, topology, elements)

Create degree-of-freedom maps on a given topology.

create_form(form, V, msh, subdomains, ...[, ...])

Create a Form object from a data-independent compiled form.

create_interpolation_data(V_to, V_from, cells)

Generate data for interpolating functions on different meshes.

create_matrix(a[, block_mode])

Create a sparse matrix that is compatible with a bilinear form.

create_sparsity_pattern(a)

Create a sparsity pattern from a bilinear form.

create_vector(V, dtype, ...)

Create a Vector that is compatible with the given function space.

dirichletbc(value, dofs[, V])

Representation of Dirichlet boundary condition.

discrete_curl(V0, V1)

Assemble a discrete curl operator.

discrete_gradient(space0, space1)

Assemble a discrete gradient operator.

extract_function_spaces(...)

Extract common function spaces from an array of forms.

finiteelement(cell_type, ufl_e, ...)

Create a DOLFINx element from a basix.ufl element.

form(...)

Create a Form or list of Forms.

form_cpp_class(dtype)

Look up the wrapped C++ Form class for a given scalar type.

functionspace(mesh, element)

Create a finite element function space.

interpolate_geometry(msh, cmap)

From a mesh create a mesh with geometry interpolated into cmap.

interpolation_matrix(space0, space1)

Create interpolation matrix between spaces on the same mesh.

locate_dofs_geometrical(-> ~numpy.ndarray)

Locate degrees-of-freedom geometrically using a marker function.

locate_dofs_topological(-> ~numpy.ndarray)

Locate degrees-of-freedom belonging to mesh entities topologically.

mixed_topology_form(forms, dtype, ...)

Create a mixed-topology from an array of Forms.

pack_coefficients(...)

Pack form coefficients for use in assembly.

pack_constants(...)

Pack form constants for use in assembly.

set_bc_diagonal(A, V, bcs[, diagonal])

Set a value on the diagonal for Dirichlet boundary condition rows.

set_diagonal(A, rows[, diagonal, insert_mode])

Set or add values on the diagonal for given rows of a matrix.

transpose_dofmap(dofmap, num_cells)

Build the index to (cell, local index) map from a dofmap.

Classes

Constant(domain, c)

A constant with respect to a domain.

CoordinateElement(cmap)

Coordinate element describing the geometry map for mesh cells.

DirichletBC(bc, V, g)

Representation of Dirichlet boundary conditions.

DofMap(dofmap)

Degree-of-freedom map.

ElementDofLayout(dof_layout)

Layout of the degrees-of-freedom on a cell.

ElementMetaData(family, degree[, shape, ...])

Data for representing a finite element.

Expression(e, X[, comm, ...])

An object for evaluating functions of finite element functions.

FiniteElement(cpp_object)

A finite element.

Form(form, msh, spaces[, ufcx_form, code, ...])

A finite element form.

Function(*args, **kw)

A finite element function.

FunctionSpace(mesh, element, cppV)

A space on which Functions (fields) can be defined.

IntegralType(*values)

class dolfinx.fem.Constant(domain: Mesh | ufl.Mesh, c: float | np.floating | complex | np.complexfloating | Sequence | np.ndarray)[source]#

Bases: Constant, Generic[Scalar]

A constant with respect to a domain.

Create a Constant.

Parameters:
  • domain – DOLFINx or UFL mesh

  • c – Value of the constant.

cpp_types: ClassVar[dict] = {dtype('float32'): <class 'dolfinx.cpp.fem.Constant_float32'>, dtype('float64'): <class 'dolfinx.cpp.fem.Constant_float64'>, dtype('complex64'): <class 'dolfinx.cpp.fem.Constant_complex64'>, dtype('complex128'): <class 'dolfinx.cpp.fem.Constant_complex128'>}#
property dtype: type[Any] | dtype[Any] | _SupportsDType[dtype[Any]] | tuple[Any, Any] | list[Any] | _DTypeDict | str | None#

Value dtype of the constant.

property value: ndarray[tuple[Any, ...], dtype[_ScalarT]]#

The value of the constant.

class dolfinx.fem.CoordinateElement(cmap: CoordinateElement_float32 | CoordinateElement_float64)[source]#

Bases: Generic[Real]

Coordinate element describing the geometry map for mesh cells.

Create a coordinate map element.

Note

This initialiser is for internal use and not normally called in user code. Use coordinate_element() to create a CoordinateElement.

Parameters:

cmap – A C++ CoordinateElement.

cpp_types: ClassVar[dict] = {dtype('float32'): <class 'dolfinx.cpp.fem.CoordinateElement_float32'>, dtype('float64'): <class 'dolfinx.cpp.fem.CoordinateElement_float64'>}#
create_dof_layout() → ElementDofLayout[source]#

Compute and return the dof layout.

property degree: int#

Polynomial degree of the coordinate element.

property dim: 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.

property dtype: dtype#

Scalar type for the coordinate element.

hash() → int[source]#

Hash identifier of the coordinate element.

property is_discontinuous: 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.

pull_back(x: ndarray[tuple[Any, ...], dtype[Real]], cell_geometry: ndarray[tuple[Any, ...], dtype[Real]], *, tol: float | None = None, maxit: int = 15, working_array: ndarray[tuple[Any, ...], dtype[Real]] | None = None) → ndarray[tuple[Any, ...], dtype[Real]][source]#

Pull points on the physical cell back to the reference cell.

For non-affine cells, the pull-back is a nonlinear operation.

Parameters:
  • 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 pull_back_working_size().

Returns:

Reference coordinates of the physical points x.

pull_back_working_size(gdim: int) → int[source]#

Compute the working array size required for pull back.

Parameters:

gdim – Geometrical dimension of input points

Returns:

Number of elements required in the working array for pull back.

push_forward(X: ndarray[tuple[Any, ...], dtype[Real]], cell_geometry: ndarray[tuple[Any, ...], dtype[Real]]) → ndarray[tuple[Any, ...], dtype[Real]][source]#

Push points on the reference cell forward to the physical cell.

Parameters:
  • 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.

property variant: int#

Lagrange variant of the coordinate element.

Note

The return type is an integer. A Basix enum can be created using basix.LagrangeVariant(value).

class dolfinx.fem.DirichletBC(bc: DirichletBC_complex64 | DirichletBC_complex128 | DirichletBC_float32 | DirichletBC_float64, V: FunctionSpace, g: Function | Constant)[source]#

Bases: Generic[Scalar]

Representation of Dirichlet boundary conditions.

The conditions are imposed on a linear system.

Initialise a Dirichlet boundary condition.

Note

Dirichlet boundary conditions should normally be constructed using dolfinx.fem.dirichletbc() and not using this class initialiser. This class is combined with different base classes that depend on the scalar type of the boundary condition.

Parameters:
  • bc – C++ wrapped Dirichlet condition.

  • V – Function space on which the boundary condition is defined.

  • g – The boundary condition value(s).

cpp_types: ClassVar[dict] = {(dtype('float32'), dtype('float32')): <class 'dolfinx.cpp.fem.DirichletBC_float32'>, (dtype('float64'), dtype('float64')): <class 'dolfinx.cpp.fem.DirichletBC_float64'>, (dtype('complex64'), dtype('float32')): <class 'dolfinx.cpp.fem.DirichletBC_complex64'>, (dtype('complex128'), dtype('float64')): <class 'dolfinx.cpp.fem.DirichletBC_complex128'>}#
dof_indices() → tuple[ndarray[tuple[Any, ...], dtype[int32]], int][source]#

Dof indices to which a Dirichlet condition is applied.

Note

Returned array is read-only.

Returns:

(i) Sorted array of dof indices (unrolled) and (ii) index to the first entry in the dof index array that is not owned. Entries dofs[:pos] are owned and entries dofs[pos:] are ghosts.

property function_space: FunctionSpace#

Function space on which the boundary condition is defined.

property g: Function | Constant#

The boundary condition value(s).

set(x: ndarray[tuple[Any, ...], dtype[Scalar]], x0: ndarray[tuple[Any, ...], dtype[Scalar]] | None = None, alpha: float = 1) → None[source]#

Set array entries that are constrained by a Dirichlet condition.

Entries in x that are constrained by a Dirichlet boundary conditions are set to alpha * (x_bc - x0), where x_bc is the (interpolated) boundary condition value.

For elements with point-wise evaluated degrees-of-freedom, e.g. Lagrange elements, x_bc is the value of the boundary condition at the degree-of-freedom. For elements with moment degrees-of-freedom, x_bc is the value of the boundary condition interpolated into the finite element space.

x may be sized to hold only owned entries or to also include ghost entries (entries available on the calling rank but owned by another rank); a constrained degree-of-freedom beyond the end of x is silently skipped. Passing an owned-only array therefore sets only owned entries, while an array that also includes ghosts (e.g. the full array of a Vector) additionally sets ghost entries constrained by the condition.

Parameters:
  • x – Array to modify for Dirichlet boundary conditions. May include ghost entries.

  • x0 – Optional array used in computing the value to set. If not provided it is treated as zero. Must be at least as long as x (checked only in Developer builds).

  • alpha – Scaling factor.

class dolfinx.fem.DofMap(dofmap: DofMap)[source]#

Bases: object

Degree-of-freedom map.

This class handles the mapping of degrees of freedom. It builds a dof map based on a FiniteElement on a specific mesh.

Initialise a degree-of-freedom map.

property bs: int#

Block size of the dofmap.

cell_dofs(cell_index: int) → ndarray[tuple[Any, ...], dtype[int32]][source]#

Cell local-global dof map.

Parameters:

cell_index – The cell index.

Returns:

Local-global dof map for the cell (using process-local indices).

property dof_layout: ElementDofLayout[source]#

Layout of dofs on an element.

Note

This is a cached property. The wrapper is built on first access and the same object is returned thereafter.

property index_map: IndexMap[source]#

Index map describing parallel distribution of the dofmap.

Note

This is a cached property. The wrapper is built on first access and the same object is returned thereafter.

property index_map_bs: int#

Block size of the index map.

property list: ndarray[tuple[Any, ...], dtype[int32]]#

Adjacency list with dof indices for each cell.

class dolfinx.fem.ElementDofLayout(dof_layout: ElementDofLayout)[source]#

Bases: object

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.

Initialize a dof layout from a C++ ElementDofLayout.

Note

Dof layouts are obtained from DofMap.dof_layout or CoordinateElement.create_dof_layout(), and not created using this initialiser.

Parameters:

dof_layout – The C++ dof layout object.

property block_size: int#

Block size of the layout.

entity_closure_dofs(dim: int, entity_index: int) → list[int][source]#

Degrees-of-freedom on the closure of a sub-entity.

Parameters:
  • 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.

entity_dofs(dim: int, entity_index: int) → list[int][source]#

Degrees-of-freedom associated with a sub-entity of the cell.

Parameters:
  • 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.

property num_dofs: int#

Number of degrees-of-freedom on the cell.

class dolfinx.fem.ElementMetaData(family: str, degree: int, shape: tuple[int, ...] | None = None, symmetry: bool | None = None)[source]#

Bases: NamedTuple

Data for representing a finite element.

Parameters:
  • family – Element type.

  • degree – Polynomial degree of the element.

  • shape – Shape for vector/tensor valued elements that are constructed from blocked scalar elements (e.g., Lagrange).

  • symmetry – Symmetry option for blocked tensor elements.

Create new instance of ElementMetaData(family, degree, shape, symmetry)

degree: int#

Alias for field number 1

family: str#

Alias for field number 0

shape: tuple[int, ...] | None#

Alias for field number 2

symmetry: bool | None#

Alias for field number 3

class dolfinx.fem.Expression(e: ufl.core.expr.Expr, X: np.ndarray, comm: _MPI.Comm | None = None, form_compiler_options: dict | None = None, jit_options: dict | None = None, dtype: npt.DTypeLike | None = None, entity_maps: list[_EntityMap] | None = None)[source]#

Bases: Generic[Scalar]

An object for evaluating functions of finite element functions.

Represents a mathematical expression evaluated at a pre-defined set of points on the reference cell. This class closely follows the concept of a UFC Expression.

This functionality can be used to evaluate a gradient of a Function at the quadrature points in all cells. This evaluated gradient can then be used as input to a non-FEniCS function that calculates a material constitutive model.

Create an Expression.

Parameters:
  • e – UFL expression.

  • X – Array of points of shape (num_points, tdim) on the reference element.

  • comm – Communicator that the Expression is defined on.

  • form_compiler_options – Options used in FFCx compilation of this Expression. Run ffcx --help in the commandline to see all available options.

  • jit_options – Options controlling JIT compilation of C code.

  • dtype – Type of the Expression values. If None, the dtype is deduced from the UFL expression.

  • entity_maps – Maps between different meshes.

Note

This wrapper is responsible for the FFCx compilation of the UFL Expr and attaching the correct data to the underlying C++ Expression.

X() → ndarray[tuple[Any, ...], dtype[_ScalarT]][source]#

Evaluation points on the reference cell.

property argument_space: FunctionSpace | None#

Argument function space if Expression has argument.

property code: str#

C code strings.

cpp_types: ClassVar[dict] = {(dtype('float32'), dtype('float32')): <nanobind.nb_func object>, (dtype('float64'), dtype('float64')): <nanobind.nb_func object>, (dtype('complex64'), dtype('float32')): <nanobind.nb_func object>, (dtype('complex128'), dtype('float64')): <nanobind.nb_func object>}#
property dtype: type[Any] | dtype[Any] | _SupportsDType[dtype[Any]] | tuple[Any, Any] | list[Any] | _DTypeDict | str | None#

Expression value dtype.

eval(mesh: Mesh, entities: npt.NDArray[np.int32], values: npt.NDArray[Scalar] | None = None) → npt.NDArray[Scalar][source]#

Evaluate Expression on entities.

Parameters:
  • mesh – Mesh to evaluate Expression on.

  • entities – Entities to evaluate the Expression over. For cells, it is a list of cell indices. For facets, it is a 2D array of (cell index, local facet index).

  • values – Array to fill with evaluated values. If None, storage will be allocated. Otherwise it must have shape (entities.shape[0], num_points, *value_shape) if there is not argument function and shape (entities.shape[0], num_points, *value_shape, argument_space_dim) if the Expression does have an argument function.

Returns:

Expression evaluated at points for entities. Shape is (entities.shape[0], num_points, *value_shape) if there is no argument function, or shape is (entities.shape[0], num_points, *value_shape, argument_space_dim) if the Expression does have an argument function.

property ufcx_expression: Any#

The compiled ufcx_expression object.

property ufl_expression: Expr#

Original UFL Expression.

property value_shape: ndarray#

Value shape of the Expression.

property value_size: int#

Value size of the expression.

class dolfinx.fem.FiniteElement(cpp_object: FiniteElement_float32 | FiniteElement_float64)[source]#

Bases: Generic[Real]

A finite element.

Creates a Python wrapper for the exported finite element class.

Note

Do not use this constructor directly. Instead use finiteelement().

Parameters:

cpp_object – Underlying cpp instance that this object will wrap.

T_apply(x: ndarray[tuple[Any, ...], dtype[Real]], cell_permutations: ndarray[tuple[Any, ...], dtype[uint32]], dim: int) → None[source]#

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.

Parameters:
  • 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.

Tt_apply(x: ndarray[tuple[Any, ...], dtype[Real]], cell_permutations: ndarray[tuple[Any, ...], dtype[uint32]], dim: int) → None[source]#

Apply the transpose of the operator applied by T_apply().

Parameters:
  • 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.

Tt_inv_apply(x: ndarray[tuple[Any, ...], dtype[Real]], cell_permutations: ndarray[tuple[Any, ...], dtype[uint32]], dim: int) → None[source]#

Apply the inverse transpose of T_apply().

Parameters:
  • 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.

property basix_element: FiniteElement_float32 | FiniteElement_float64#

Return underlying Basix C++ element (if it exists).

Raises:

RuntimeError – If a Basix element does not exist.

cpp_types: ClassVar[dict] = {dtype('float32'): <class 'dolfinx.cpp.fem.FiniteElement_float32'>, dtype('float64'): <class 'dolfinx.cpp.fem.FiniteElement_float64'>}#
property dtype: dtype#

Geometry type of the mesh that the space is defined on.

property interpolation_ident: 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.

property interpolation_points: ndarray[tuple[Any, ...], dtype[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.

property needs_dof_transformations: 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.

property num_sub_elements: int#

Number of sub elements (for a mixed or blocked element).

property physical_base_value_size: 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.

property reference_value_shape: ndarray[tuple[Any, ...], dtype[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 value_shape for anything user-facing; this is for code that works with tabulated reference data.

property signature: str#

String identifying the finite element.

property space_dimension: 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.

property value_shape: ndarray[tuple[Any, ...], dtype[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 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,).

class dolfinx.fem.Form(form: _cpp.fem.Form_complex64 | _cpp.fem.Form_complex128 | _cpp.fem.Form_float32 | _cpp.fem.Form_float64, msh: Mesh, spaces: list[FunctionSpace], ufcx_form: Any = None, code: str | list[str] | None = None, module: types.ModuleType | list[types.ModuleType] | None = None)[source]#

Bases: Generic[Scalar]

A finite element form.

Initialize a finite element form.

Note

Forms should normally be constructed using form() and not using this class initialiser. This class is combined with different base classes that depend on the scalar type used in the Form.

Parameters:
  • form – Compiled form object.

  • msh – Mesh that form is defined on.

  • spaces – Function spaces that the form arguments are defined on, one per argument.

  • ufcx_form – UFCx form.

  • code – Form C++ code.

  • module – CFFI module.

property code: str | list[str] | None#

C code strings.

cpp_types: ClassVar[dict[tuple[np.dtype, np.dtype], type[_cpp.fem.Form_float32] | type[_cpp.fem.Form_float64] | type[_cpp.fem.Form_complex64] | type[_cpp.fem.Form_complex128]]] = {(dtype('float32'), dtype('float32')): <class 'dolfinx.cpp.fem.Form_float32'>, (dtype('float64'), dtype('float64')): <class 'dolfinx.cpp.fem.Form_float64'>, (dtype('complex64'), dtype('float32')): <class 'dolfinx.cpp.fem.Form_complex64'>, (dtype('complex128'), dtype('float64')): <class 'dolfinx.cpp.fem.Form_complex128'>}#
property dtype: dtype#

Scalar type of this form.

property function_spaces: tuple[FunctionSpace, ...]#

Function spaces on which this form is defined.

property integral_types: set[IntegralType]#

Integral types in the form.

property mesh: Mesh#

Mesh on which this form is defined.

property module: ModuleType | list[ModuleType] | None#

The CFFI module.

num_integrals(integral_type: IntegralType, kernel_index: int) → int[source]#

Number of integrals of a given type for a specific cell type.

Parameters:
  • integral_type – The type of integral to count.

  • kernel_index – In the case of mixed topology, we have a kernel per cell type. For single-cell type meshes, this is zero.

property rank: int#

Rank of this form.

property ufcx_form: Any#

The compiled ufcx_form object.

class dolfinx.fem.Function(*args, **kw)[source]#

Bases: Coefficient, Generic[Scalar]

A finite element function.

A finite element function is represented by a function space (domain, element and dofmap) and a vector holding the degrees-of-freedom.

Initialize a finite element Function.

Parameters:
  • V – The function space that the Function is defined on.

  • x – Function degree-of-freedom vector. Typically required only when reading a saved Function from file.

  • name – Function name.

  • dtype – Scalar type. Is not set, the DOLFINx default scalar type is used.

collapse() → Function[Scalar][source]#

Create a collapsed version of this Function.

copy() → Function[Scalar][source]#

Create a copy of the Function.

The function space is shared and the degree-of-freedom vector is copied.

Returns:

A new Function with a copy of the degree-of-freedom vector.

cpp_types: ClassVar[dict] = {(dtype('float32'), dtype('float32')): <class 'dolfinx.cpp.fem.Function_float32'>, (dtype('float64'), dtype('float64')): <class 'dolfinx.cpp.fem.Function_float64'>, (dtype('complex64'), dtype('float32')): <class 'dolfinx.cpp.fem.Function_complex64'>, (dtype('complex128'), dtype('float64')): <class 'dolfinx.cpp.fem.Function_complex128'>}#
property dtype: type[Any] | dtype[Any] | _SupportsDType[dtype[Any]] | tuple[Any, Any] | list[Any] | _DTypeDict | str | None#

Function value dtype.

eval(x: Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str], cells: ndarray[tuple[Any, ...], dtype[int32]], u: ndarray[tuple[Any, ...], dtype[Scalar]] | None = None, tol: float = 1e-06, maxit: int = 15) → ndarray[tuple[Any, ...], dtype[Scalar]][source]#

Evaluate Function at points x.

Parameters:
  • x – Points with shape (num_points, 3)

  • cells – Array with cell indices, with shape (num_points,), where cell[i] is the index of the cell containing point x[i]. If the cell index is negative the point is ignored.

  • u – Array to put evaluated data in.

  • tol – Tolerance for convergence in Newton method for nonaffine pullbacks.

  • maxit – Maximum number of Newton iterations for nonaffine pullbacks.

property function_space: FunctionSpace#

FunctionSpace that the Function is defined on.

interpolate(u0: Callable | Expression[Scalar] | Function[Scalar], cells0: ndarray[tuple[Any, ...], dtype[int32]] | None = None, cells1: ndarray[tuple[Any, ...], dtype[int32]] | None = None) → None[source]#

Interpolate an expression.

Parameters:
  • u0 – Callable function, Expression or Function to interpolate.

  • cells0 – Cells in mesh associated with u0 to interpolate over. If None then all cells are interpolated over.

  • cells1 – Cells in the mesh associated with self to interpolate over. If None, then taken to be the same cells as cells0. If cells1 is not None it must have the same length as cells0.

interpolate_nonmatching(u0: Function[Scalar], cells: ndarray[tuple[Any, ...], dtype[int32]], interpolation_data: PointOwnershipData, tol: float = 1e-06, maxit: int = 15) → None[source]#

Interpolate a Function on a non-matching mesh.

Parameters:
  • u0 – Function to interpolate.

  • cells – The cells to interpolate over. If None then all cells are interpolated over.

  • interpolation_data – Data needed to interpolate functions defined on other meshes. Created by dolfinx.fem.create_interpolation_data().

  • tol – Tolerance for convergence in Newton method for nonaffine pullbacks. Ignored if mesh geometry is affine.

  • maxit – Maximum number of iterations for nonaffine pullback. Ignored if mesh geometry is affine.

property name: str#

Name of the Function.

split() → tuple[Function[Scalar], ...][source]#

Extract (any) sub-functions.

A sub-function can be extracted from a discrete function that is in a mixed, vector, or tensor FunctionSpace. The sub-function resides in the subspace of the mixed space.

Returns:

First level of subspaces of the function space.

sub(i: int) → Function[Scalar][source]#

Return a sub-function (a view into the Function).

Sub-functions are indexed i = 0, ..., N-1, where N is the number of sub-spaces.

Parameters:

i – Index of the sub-function to extract.

Returns:

A view into the parent Function.

Note

If the sub-Function is re-used, for performance reasons the returned Function should be stored by the caller to avoid repeated re-computation of the subspace.

property x: Vector[Scalar]#

Vector holding the degrees-of-freedom.

class dolfinx.fem.FunctionSpace(mesh: Mesh[Real], element: ufl.finiteelement.AbstractFiniteElement, cppV: _cpp.fem.FunctionSpace_float32 | _cpp.fem.FunctionSpace_float64)[source]#

Bases: FunctionSpace, Generic[Real]

A space on which Functions (fields) can be defined.

Create a finite element function space.

Note

This initialiser is for internal use and not normally called in user code. Use functionspace() to create a function space.

Parameters:
  • mesh – Mesh that space is defined on.

  • element – UFL finite element.

  • cppV – Compiled C++ function space.

clone() → FunctionSpace[Real][source]#

Create a FunctionSpace which shares data with this space.

The new space has a different unique integer ID.

Create a new FunctionSpace \(W\) which shares data with this FunctionSpace \(V\), but with a different unique integer ID.

This function is helpful for defining mixed problems and using blocked linear algebra. For example, a matrix block defined on the spaces \(V \times W\) where, \(V\) and \(W\) are defined on the same finite element and mesh can be identified as an off-diagonal block whereas the \(V \times V\) and \(V \times V\) matrices can be identified as diagonal blocks. This is relevant for the handling of boundary conditions.

Returns:

A new function space that shares data

collapse() → tuple[FunctionSpace[Real], list[ndarray[tuple[Any, ...], dtype[int32]]]][source]#

Create a new function space by collapsing a subspace.

Returns:

A new function space and the map from new to old degrees-of-freedom.

component() → list[int][source]#

Return the component relative to the parent space.

contains(V: FunctionSpace) → bool[source]#

Check if a space is contained in, or is the same as, this space.

Parameters:

V – The space to check to for inclusion.

Returns:

`` True`` if V is contained in, or is the same as, this space.

cpp_types: ClassVar[dict] = {dtype('float32'): <class 'dolfinx.cpp.fem.FunctionSpace_float32'>, dtype('float64'): <class 'dolfinx.cpp.fem.FunctionSpace_float64'>}#
property dofmap: DofMap[source]#

Degree-of-freedom map associated with the function space.

property dofmaps: tuple[DofMap, ...][source]#

The function space dofmaps, one per cell type.

property element: FiniteElement[Real][source]#

Function space finite element.

property mesh: Mesh[Real]#

Mesh on which the function space is defined.

property num_sub_spaces: int#

Number of sub spaces.

sub(i: int) → FunctionSpace[Real][source]#

Return the i-th sub space.

Parameters:

i – Index of the subspace to extract.

Returns:

A subspace.

Note

If the subspace is re-used, for performance reasons the returned subspace should be stored by the caller to avoid repeated re-computation of the subspace.

tabulate_dof_coordinates() → ndarray[tuple[Any, ...], dtype[Real]][source]#

Tabulate coordinates of function space degrees-of-freedom.

Returns:

Coordinates of the degrees-of-freedom.

Note

This method is only for elements with point evaluation degrees-of-freedom.

ufl_function_space() → Self[source]#

UFL function space.

class dolfinx.fem.IntegralType(*values)#

Bases: Enum

cell = 0#
exterior_facet = 1#
interior_facet = 2#
ridge = 4#
vertex = 3#
dolfinx.fem.apply_lifting(b: ndarray[tuple[Any, ...], dtype[_ScalarT]], a: Sequence[Form], bcs: Sequence[Sequence[DirichletBC]], x0: Sequence[ndarray[tuple[Any, ...], dtype[_ScalarT]]] | None = None, alpha: float = 1, constants: Sequence[ndarray[tuple[Any, ...], dtype[_ScalarT]]] | None = None, coeffs: Sequence[dict[tuple[IntegralType, int], ndarray[tuple[Any, ...], dtype[_ScalarT]]]] | None = None) → None[source]#

Modify right-hand side for lifting of Dirichlet conditions.

Consider the discrete algebraic system:

\[\begin{split}\begin{bmatrix} A_{0} & A_{1} \end{bmatrix} \begin{bmatrix}u_{0} \\ u_{1}\end{bmatrix} = b,\end{split}\]

where \(A_{i}\) is a matrix. Partitioning each vector \(u_{i}\) into ‘unknown’ (\(u_{i}^{(0)}\)) and prescribed (\(u_{i}^{(1)}\)) groups,

\[\begin{split}\begin{bmatrix} A_{0}^{(0)} & A_{0}^{(1)} & A_{1}^{(0)} & A_{1}^{(1)} \end{bmatrix} \begin{bmatrix} u_{0}^{(0)} \\ u_{0}^{(1)} \\ u_{1}^{(0)} \\ u_{1}^{(1)} \end{bmatrix} = b.\end{split}\]

If \(u_{i}^{(1)} = \alpha(g_{i} - x_{i})\), where \(g_{i}\) is the Dirichlet boundary condition value, \(x_{i}\) is provided and \(\alpha\) is a constant, then

\[\begin{split}\begin{bmatrix} A_{0}^{(0)} & A_{0}^{(1)} & A_{1}^{(0)} & A_{1}^{(1)} \end{bmatrix} \begin{bmatrix}u_{0}^{(0)} \\ \alpha(g_{0} - x_{0}) \\ u_{1}^{(0)} \\ \alpha(g_{1} - x_{1})\end{bmatrix} = b.\end{split}\]

Rearranging,

\[\begin{split}\begin{bmatrix}A_{0}^{(0)} & A_{1}^{(0)}\end{bmatrix} \begin{bmatrix}u_{0}^{(0)} \\ u_{1}^{(0)}\end{bmatrix} = b - \alpha A_{0}^{(1)} (g_{0} - x_{0}) - \alpha A_{1}^{(1)} (g_{1} - x_{1}).\end{split}\]

The modified \(b\) vector is

\[b \leftarrow b - \alpha A_{0}^{(1)} (g_{0} - x_{0}) - \alpha A_{1}^{(1)} (g_{1} - x_{1})\]

More generally,

\[b \leftarrow b - \alpha A_{i}^{(1)} (g_{i} - x_{i}).\]
Parameters:
  • b – The array to modify inplace.

  • a – List of bilinear forms, where a[i] is the form that generates the matrix :math”A_{i}. All forms in a must share the same test function space. The trial function spaces can differ.

  • bcs –

    Boundary conditions that provide the \(g_{i}\) values. bcs1[i] is the sequence of boundary conditions on \(u_{i}\). Helper functions exist to build a list-of-lists of DirichletBC from a list of forms a and a flat list of DirichletBC objects bcs:

    bcs1 = fem.bcs_by_block(
        fem.extract_function_spaces([a], 1),
        bcs
    )
    

  • x0 – The array \(x_{i}\) above. If None it is set to zero.

  • alpha – Scalar used in the modification of b.

  • constants – Packed constant data appearing in the forms a. If None, the constant data will be packed by the function.

  • coeffs – Packed coefficient data appearing in the forms a. If None, the coefficient data will be packed by the function.

Note

Ghost contributions are not accumulated (not sent to owner). Caller is responsible for reverse-scatter to update the ghosts.

Note

Boundary condition values are not set in b by this function. Use dolfinx.fem.DirichletBC.set() to set values in b.

Note

Convenience function for callers that have boundary conditions. It rebuilds the constrained dof markers and values on every call, and should not be called internally by the library.

dolfinx.fem.assemble_matrix(a: Any, bcs: Sequence[DirichletBC] | None = None, diag: float = 1.0, constants: ndarray[tuple[Any, ...], dtype[_ScalarT]] | None = None, coeffs: dict[tuple[IntegralType, int], ndarray[tuple[Any, ...], dtype[_ScalarT]]] | None = None, block_mode: BlockMode | None = None) → MatrixCSR[source]#
dolfinx.fem.assemble_matrix(A: MatrixCSR, a: Form, bcs: Sequence[DirichletBC] | None = None, diag: float = 1.0, constants: ndarray[tuple[Any, ...], dtype[_ScalarT]] | None = None, coeffs: dict[tuple[IntegralType, int], ndarray[tuple[Any, ...], dtype[_ScalarT]]] | None = None) → MatrixCSR

Assemble bilinear form into a matrix.

Parameters:
  • a – The bilinear form assemble.

  • bcs – Boundary conditions that affect the assembled matrix. Degrees-of-freedom constrained by a boundary condition will have their rows/columns zeroed and the value diagonal set on the matrix diagonal.

  • diag – Value to set on the matrix diagonal for Dirichlet boundary condition constrained degrees-of-freedom belonging to the same trial and test space.

  • constants – Constants that appear in the form. If None, any required constants will be computed.

  • coeffs – Coefficients that appear in the form. If not provided, any required coefficients will be computed.

  • block_mode – Block size mode for the returned space matrix. If None, default is used.

Returns:

Matrix representation of the bilinear form a.

Note

The returned matrix is not finalised, i.e. ghost values are not accumulated.

Note

Convenience function for callers that have boundary conditions. It rebuilds the constrained dof markers on every call, and should not be called internally by the library.

dolfinx.fem.assemble_matrix_fn(fn: Callable[[ndarray[tuple[Any, ...], dtype[int32]], ndarray[tuple[Any, ...], dtype[int32]], ndarray[tuple[Any, ...], dtype[_ScalarT]]], int], a: Form, bcs: Sequence[DirichletBC] | None = None) → None[source]#

Assemble a bilinear form, inserting element matrices via fn.

Rather than assembling into a MatrixCSR or a PETSc matrix, fn is called once per cell/facet contribution with the local-to-global row indices, column indices, and the element matrix values, and is responsible for inserting them into a caller-owned matrix representation.

Parameters:
  • fn – Called as fn(rows, cols, vals) for each contribution, where vals has shape (len(rows), len(cols)). Return 0 on success.

  • a – Bilinear form to assemble.

  • bcs – Boundary conditions that affect the assembled matrix. Rows and columns constrained by a boundary condition are zeroed.

Note

Convenience function for callers that have boundary conditions. It rebuilds the constrained dof markers on every call, and should not be called internally by the library.

dolfinx.fem.assemble_scalar(M: Form, constants: ndarray[tuple[Any, ...], dtype[_ScalarT]] | None = None, coeffs: dict[tuple[IntegralType, int], ndarray[tuple[Any, ...], dtype[_ScalarT]]] | None = None) → float | complex[source]#

Assemble functional.

The returned value is local and not accumulated across processes.

Parameters:
  • M – The functional to compute.

  • constants – Constants that appear in the form. If None, any required constants will be computed.

  • coeffs – Coefficients that appear in the form. If not provided, any required coefficients will be computed.

Returns:

The computed scalar on the calling rank.

Note

Passing constants and coefficients is a performance optimisation for when a form is assembled multiple times and when (some) constants and coefficients are unchanged.

To compute the functional value on the whole domain, the output of this function is typically summed across all MPI ranks.

dolfinx.fem.assemble_vector(L: Any, constants: ndarray[tuple[Any, ...], dtype[_ScalarT]] | None = None, coeffs: dict[tuple[IntegralType, int], ndarray[tuple[Any, ...], dtype[_ScalarT]]] | None = None) → Vector[source]#
dolfinx.fem.assemble_vector(L: Form, constants: ndarray[tuple[Any, ...], dtype[_ScalarT]] | None = None, coeffs: dict[tuple[IntegralType, int], ndarray[tuple[Any, ...], dtype[_ScalarT]]] | None = None) → Vector
dolfinx.fem.assemble_vector(b: ndarray[tuple[Any, ...], dtype[_ScalarT]], L: Form, constants: ndarray[tuple[Any, ...], dtype[_ScalarT]] | None = None, coeffs: dict[tuple[IntegralType, int], ndarray[tuple[Any, ...], dtype[_ScalarT]]] | None = None) → ndarray[tuple[Any, ...], dtype[_ScalarT]]

Assemble linear form into a vector.

dolfinx.fem.bcs_by_block(spaces: Iterable[FunctionSpace | None], bcs: Iterable[DirichletBC[Scalar]]) → list[list[DirichletBC[Scalar]]][source]#

Arrange boundary conditions by the space that they constrain.

Given a sequence of function spaces spaces and a sequence of DirichletBC objects bcs, return a list where the ith entry is the list of DirichletBC objects whose space is contained in space[i].

dolfinx.fem.build_sparsity_pattern(pattern: dolfinx.la.SparsityPattern, a: dolfinx.fem.forms.Form) → None[source]#

Build a sparsity pattern from a bilinear form.

Parameters:
  • pattern – The sparsity pattern to add to

  • a – Bilinear form to build a sparsity pattern for.

Note

The pattern is not finalised, i.e. the caller is responsible for calling SparsityPattern.finalize.

dolfinx.fem.compile_form(comm: Intracomm, form: Form, form_compiler_options: dict | None = None, jit_options: dict | None = None) → CompiledForm[source]#

Compile UFL form without associated DOLFINx data.

Parameters:
  • comm – The MPI communicator used when compiling the form

  • form – The UFL form to compile

  • form_compiler_options – See ffcx_jit

  • jit_options – See ffcx_jit.

dolfinx.fem.compute_integration_domains(integral_type: IntegralType, topology: dolfinx.mesh.Topology, entities: np.ndarray) → npt.NDArray[np.int32][source]#

Determine compute integration entities.

This function returns a list [(id, entities)]. For cell integrals entities are the cell indices. For exterior facet integrals, entities is a list of (cell_index, local_facet_index) pairs. For interior facet integrals, entities is a list of (cell_index0, local_facet_index0, cell_index1, local_facet_index1). id refers to the subdomain id used in the definition of the integration measures of the variational form.

Note

Owned mesh entities only are returned. Ghost entities are not included.

Note

For facet integrals, the topology facet-to-cell and cell-to-facet connectivity must be computed before calling this function.

Parameters:
  • integral_type – Integral type.

  • topology – Mesh topology.

  • entities – List of mesh entities. For integral_type==IntegralType.cell, entities should be cell indices. For other IntegralType``s, ``entities should be facet indices.

Returns:

List of integration entities.

dolfinx.fem.coordinate_element(celltype: CellType | FiniteElement, degree: int, variant: int = 0, dtype: type[~typing.Any] | ~numpy.dtype[~typing.Any] | ~numpy._typing._dtype_like._SupportsDType[~numpy.dtype[~typing.Any]] | tuple[~typing.Any, ~typing.Any] | list[~typing.Any] | ~numpy._typing._dtype_like._DTypeDict | str | None=<class 'numpy.float64'>, discontinuous: bool = False) → CoordinateElement[source]#
dolfinx.fem.coordinate_element(e: FiniteElement) → CoordinateElement

Create a Lagrange CoordinateElement from element metadata.

Coordinate elements are typically used to create meshes.

Parameters:
  • 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.

dolfinx.fem.create_dofmaps(comm: Comm, topology: dolfinx.mesh.Topology, elements: Sequence[FiniteElement]) → list[DofMap][source]#

Create degree-of-freedom maps on a given topology.

Parameters:
  • comm – MPI communicator

  • topology – Mesh topology

  • elements – Sequence of elements

Returns:

List of degree-of-freedom maps where the i-th map is the map for elements[i].

dolfinx.fem.create_form(form: CompiledForm, V: list[FunctionSpace], msh: Mesh, subdomains: dict[IntegralType, list[tuple[int, np.ndarray]]], coefficient_map: dict[ufl.Coefficient, Function], constant_map: dict[ufl.Constant, Constant], entity_maps: Sequence[_EntityMap] | None = None) → Form[source]#

Create a Form object from a data-independent compiled form.

Parameters:
  • form – Compiled ufl form,

  • V – List of function spaces associated with the form. Should match the number of arguments in the form.

  • msh – Mesh to associate form with.

  • subdomains – A map from integral type to a list of pairs, where each pair corresponds to a subdomain id and the set of integration entities to integrate over. Can be computed with {py:func}`dolfinx.fem.compute_integration_domains`.

  • coefficient_map – Map from UFL coefficient to function with data.

  • constant_map – Map from UFL constant to constant with data. to the integration domain msh. The value of the map is an array of integers, where the i-th entry is the entity in the key mesh.

  • entity_maps – Entity maps to support cases where forms involve sub-meshes.

Returns:

A Form object.

dolfinx.fem.create_interpolation_data(V_to: FunctionSpace, V_from: FunctionSpace, cells: ndarray[tuple[Any, ...], dtype[int32]], padding: float = 1e-14, allow_extrapolation: bool = True) → PointOwnershipData[source]#

Generate data for interpolating functions on different meshes.

Parameters:
  • V_to – Function space to interpolate into.

  • V_from – Function space to interpolate from.

  • cells – Indices of the cells associated with V_to on which to interpolate into.

  • padding – Absolute padding applied to the bounding box of each cell in V_from’s mesh before searching for candidate cells. Increasing padding increases the number of cells considered as candidates for an interpolation point; it does not by itself decide whether a point with no actually-containing cell is assigned an owner, which is controlled by allow_extrapolation.

  • allow_extrapolation – If True (default), a point from V_to’s mesh not actually contained in any candidate cell of V_from’s mesh is instead assigned the candidate cell closest to it (relevant e.g. if the two meshes do not fully overlap). If False, such points are left unowned.

Returns:

Data needed to interpolation functions defined on function spaces on the meshes.

dolfinx.fem.create_matrix(a: Form, block_mode: BlockMode | None = None) → MatrixCSR[source]#

Create a sparse matrix that is compatible with a bilinear form.

Parameters:
  • a – Bilinear form.

  • block_mode – Block mode of the CSR matrix. If None, default is used.

Returns:

A sparse matrix that the form can be assembled into.

dolfinx.fem.create_sparsity_pattern(a: dolfinx.fem.forms.Form) → dolfinx.la.SparsityPattern[source]#

Create a sparsity pattern from a bilinear form.

Parameters:

a – Bilinear form to build a sparsity pattern for.

Returns:

Sparsity pattern for the form a.

Note

The pattern is not finalised, i.e. the caller is responsible for calling SparsityPattern.finalize.

dolfinx.fem.create_vector(V: FunctionSpace, dtype: type[~typing.Any] | ~numpy.dtype[~typing.Any] | ~numpy._typing._dtype_like._SupportsDType[~numpy.dtype[~typing.Any]] | tuple[~typing.Any, ~typing.Any] | list[~typing.Any] | ~numpy._typing._dtype_like._DTypeDict | str | None=<class 'numpy.float64'>) → Vector[source]#

Create a Vector that is compatible with the given function space.

Parameters:
  • V – A function space.

  • dtype – Data type of the vector.

Returns:

A vector compatible with the function space.

dolfinx.fem.dirichletbc(value: Function | Constant | ndarray[tuple[Any, ...], dtype[Scalar]] | floating | complexfloating | float | complex, dofs: ndarray[tuple[Any, ...], dtype[int32]] | Sequence[ndarray[tuple[Any, ...], dtype[int32]]], V: FunctionSpace | None = None) → DirichletBC[Scalar][source]#

Representation of Dirichlet boundary condition.

Parameters:
  • value – Lifted boundary values function. It must have a dtype property.

  • dofs – Local indices of degrees of freedom in function space to which boundary condition applies. When V is a sub-space and value’s function space is a different (e.g. collapsed) space, this is a pair of arrays – dof indices in V and the matching dof indices in value’s function space – as returned by locate_dofs_topological() or locate_dofs_geometrical() when passed a pair of spaces. Otherwise assumes function space of the problem is the same of function space of boundary values function.

  • V – Function space of a problem to which boundary conditions are applied.

Returns:

A representation of the boundary condition for modifying linear systems.

dolfinx.fem.discrete_curl(V0: FunctionSpace, V1: FunctionSpace) → MatrixCSR[source]#

Assemble a discrete curl operator.

The discrete curl operator interpolates the curl of H(curl) finite element function into a H(div) space.

Parameters:
  • V0 – H1(curl) space to interpolate the curl from.

  • V1 – H(div) space to interpolate into.

Returns:

Discrete curl operator.

dolfinx.fem.discrete_gradient(space0: FunctionSpace, space1: FunctionSpace) → MatrixCSR[source]#

Assemble a discrete gradient operator.

The discrete gradient operator interpolates the gradient of a H1 finite element function into a H(curl) space. It is assumed that the H1 space uses an identity map and the H(curl) space uses a covariant Piola map.

Parameters:
  • space0 – H1 space to interpolate the gradient from.

  • space1 – H(curl) space to interpolate into.

Returns:

Discrete gradient operator.

dolfinx.fem.extract_function_spaces(forms: Form, index: None = None) → FunctionSpace | None[source]#
dolfinx.fem.extract_function_spaces(forms: Sequence[Form | None], index: None = None) → list[FunctionSpace | None]
dolfinx.fem.extract_function_spaces(forms: Sequence[Sequence[Form | None]], index: int = 0) → list[FunctionSpace | None]

Extract common function spaces from an array of forms.

If forms is a list of linear forms, this function returns of list of the corresponding test function spaces. If forms is a 2D array of bilinear forms, for index=0 the list of common test function spaces for each row is returned, and if index=1 the common trial function spaces for each column are returned.

Parameters:
  • forms – A list of forms or a 2D array of forms.

  • index – For a 2D array of bilinear forms, selects whether the common test function space of each row (index=0) or the common trial function space of each column (index=1) is extracted. Must be None (the default) for a single form or a 1D sequence of linear forms.

Returns:

List of function spaces.

dolfinx.fem.finiteelement(cell_type: CellType, ufl_e: _ElementBase, FiniteElement_dtype: type[Any] | dtype[Any] | _SupportsDType[dtype[Any]] | tuple[Any, Any] | list[Any] | _DTypeDict | str | None, gdim: int) → FiniteElement[source]#

Create a DOLFINx element from a basix.ufl element.

Parameters:
  • 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.

dolfinx.fem.form(form: None, dtype: type[Any] | dtype[Any] | _SupportsDType[dtype[Any]] | tuple[Any, Any] | list[Any] | _DTypeDict | str | None = default_scalar_type, form_compiler_options: dict | None = None, jit_options: dict | None = None, jit_comm: Intracomm | None = None, entity_maps: Sequence[_EntityMap] | None = None) → None[source]#
dolfinx.fem.form(form: Form, dtype: type[Any] | dtype[Any] | _SupportsDType[dtype[Any]] | tuple[Any, Any] | list[Any] | _DTypeDict | str | None = default_scalar_type, form_compiler_options: dict | None = None, jit_options: dict | None = None, jit_comm: Intracomm | None = None, entity_maps: Sequence[_EntityMap] | None = None) → Form
dolfinx.fem.form(form: Sequence[Form | None], dtype: type[Any] | dtype[Any] | _SupportsDType[dtype[Any]] | tuple[Any, Any] | list[Any] | _DTypeDict | str | None = default_scalar_type, form_compiler_options: dict | None = None, jit_options: dict | None = None, jit_comm: Intracomm | None = None, entity_maps: Sequence[_EntityMap] | None = None) → list[Form | None]
dolfinx.fem.form(form: Sequence[Sequence[Form | None]], dtype: type[Any] | dtype[Any] | _SupportsDType[dtype[Any]] | tuple[Any, Any] | list[Any] | _DTypeDict | str | None = default_scalar_type, form_compiler_options: dict | None = None, jit_options: dict | None = None, jit_comm: Intracomm | None = None, entity_maps: Sequence[_EntityMap] | None = None) → list[list[Form | None]]

Create a Form or list of Forms.

Parameters:
  • form – A UFL form, or a nested sequence of UFL forms (e.g. for a block form). Any entry may be None, e.g. to indicate a zero block in a block form; each None entry is returned as None in the corresponding position of the result, rather than being compiled.

  • dtype – Scalar type to use for the compiled form.

  • form_compiler_options – See ffcx_jit

  • jit_options – See ffcx_jit.

  • jit_comm – MPI communicator used when compiling the form. If None, then form.mesh.comm.

  • entity_maps – If any trial functions, test functions, or coefficients in the form are not defined over the same mesh as the integration domain (the domain associated with the measure), entity_maps must be supplied. For each mesh in the form, there should be an entity map relating entities in that mesh to the integration domain mesh.

Returns:

Compiled finite element Form.

Note

This function is responsible for the compilation of a UFL form (using FFCx) and attaching coefficients and domains specific data to the underlying C++ form. It dynamically create a Form instance with an appropriate base class for the scalar type, e.g. _cpp.fem.Form_float64().

dolfinx.fem.form_cpp_class(dtype: type[Any] | dtype[Any] | _SupportsDType[dtype[Any]] | tuple[Any, Any] | list[Any] | _DTypeDict | str | None) → type[Form_float32] | type[Form_float64] | type[Form_complex64] | type[Form_complex128][source]#

Look up the wrapped C++ Form class for a given scalar type.

DOLFINx’s C++ Form is templated on the scalar type and, for complex scalars, on the geometry (coordinate) type. This resolves dtype to the matching entry in Form.cpp_types, using matched precision between the scalar and geometry types, e.g. np.complex64 maps to the class with np.float32 geometry and np.complex128 to the class with np.float64 geometry.

Parameters:

dtype – Scalar type of the required form class, e.g. np.float64 or np.complex128.

Returns:

Wrapped C++ form class matching dtype.

Raises:

KeyError – If dtype is not one of the supported scalar types (np.float32, np.float64, np.complex64, np.complex128).

Note

This function is for advanced usage, typically when writing custom kernels using Numba or C.

dolfinx.fem.functionspace(mesh: Mesh, element: ufl.finiteelement.AbstractFiniteElement | ElementMetaData | tuple[str, int] | tuple[str, int, tuple] | tuple[str, int, tuple, bool]) → FunctionSpace[source]#

Create a finite element function space.

Parameters:
  • mesh – Mesh that space is defined on.

  • element – Finite element description.

Returns:

A function space.

dolfinx.fem.interpolate_geometry(msh: dolfinx.mesh.Mesh, cmap: CoordinateElement) → dolfinx.mesh.Mesh[source]#

From a mesh create a mesh with geometry interpolated into cmap.

Useful for creating a higher-order mesh from a lower-order one for computation, or vice-versa, for IO.

If cmap is discontinuous, the new geometry is discontinuous: each cell has its own coordinate nodes, which are not shared with neighbouring cells, so cell geometries can be moved independently of each other. This is required, e.g., for periodic meshes.

Note

The topology is shared between msh and the returned mesh.

Note

A discontinuous geometry has no coordinate degrees-of-freedom associated with the sub-entities of a cell, so functions that extract the geometry of a sub-entity, e.g. dolfinx.mesh.entities_to_geometry(), do not support it.

Parameters:
  • msh – Input mesh.

  • cmap – Coordinate element for the new geometry.

Returns:

A new mesh with geometry in cmap.

dolfinx.fem.interpolation_matrix(space0: FunctionSpace, space1: FunctionSpace) → MatrixCSR[source]#

Create interpolation matrix between spaces on the same mesh.

Parameters:
  • space0 – space to interpolate from.

  • space1 – space to interpolate into.

Returns:

Interpolation matrix.

Note

The returned matrix is not finalised, i.e. ghost values are not accumulated.

dolfinx.fem.locate_dofs_geometrical(V: FunctionSpace, marker: Callable) → ndarray[source]#
dolfinx.fem.locate_dofs_geometrical(V: Iterable[FunctionSpace], marker: Callable) → list[ndarray]

Locate degrees-of-freedom geometrically using a marker function.

Parameters:
  • V – Function space(s) in which to search for degree-of-freedom indices.

  • marker – A function that takes an array of points x with shape (gdim, num_points) and returns an array of booleans of length num_points, evaluating to True for entities whose degree-of-freedom should be returned.

Returns:

An array of degree-of-freedom indices (local to the process) for degrees-of-freedom whose coordinate evaluates to True for the marker function.

If V is an iterable of function spaces, a list with one such array per space is returned instead, in the same order as V.

dolfinx.fem.locate_dofs_topological(V: FunctionSpace, entity_dim: int, entities: ndarray[tuple[Any, ...], dtype[int32]], remote: bool = True) → ndarray[source]#
dolfinx.fem.locate_dofs_topological(V: Iterable[FunctionSpace], entity_dim: int, entities: ndarray[tuple[Any, ...], dtype[int32]], remote: bool = True) → list[ndarray]

Locate degrees-of-freedom belonging to mesh entities topologically.

Parameters:
  • V – Function space(s) in which to search for degree-of-freedom indices.

  • entity_dim – Topological dimension of entities where degrees-of-freedom are located.

  • entities – Indices of mesh entities of dimension entity_dim where degrees-of-freedom are located.

  • remote – True to return also “remotely located” degree-of-freedom indices.

Returns:

An array of degree-of-freedom indices (local to the process) for degrees-of-freedom topologically belonging to mesh entities.

If V is an iterable of function spaces, a list with one such array per space is returned instead, in the same order as V.

dolfinx.fem.mixed_topology_form(forms: Sequence[ufl.Form], dtype: npt.DTypeLike = <class 'numpy.float64'>, form_compiler_options: dict | None = None, jit_options: dict | None = None, jit_comm: MPI.Intracomm | None = None, entity_maps: Sequence[_EntityMap] | None = None) → Form[source]#

Create a mixed-topology from an array of Forms.

# FIXME: This function is a temporary hack for mixed-topology meshes. # It is needed because UFL does not know about mixed-topology meshes, # so we need to pass a list of forms for each cell type.

Parameters:
  • forms – A list of UFL forms. Each form should be the same, just defined on different cell types.

  • dtype – Scalar type to use for the compiled form.

  • form_compiler_options – See ffcx_jit

  • jit_options – See ffcx_jit.

  • jit_comm – MPI communicator used when compiling the form. If None, then form.mesh.comm.

  • entity_maps – If any trial functions, test functions, or coefficients in the form are not defined over the same mesh as the integration domain (the domain associated with the measure), entity_maps must be supplied. For each mesh in the form, there should be an entity map relating entities in that mesh to the integration domain mesh.

Returns:

Compiled finite element Form.

dolfinx.fem.pack_coefficients(form: Form | None) → dict[tuple[IntegralType, int], ndarray[tuple[Any, ...], dtype[_ScalarT]]][source]#
dolfinx.fem.pack_coefficients(form: Sequence[Form | None]) → list[dict[tuple[IntegralType, int], ndarray[tuple[Any, ...], dtype[_ScalarT]]]]

Pack form coefficients for use in assembly.

Pack the coefficients that appear in forms. The packed coefficients can be passed to an assembler. This is a performance optimisation for cases where a form is assembled multiple times and (some) coefficients do not change.

If form is an array of forms, this function returns an array of form coefficients with the same shape as form.

Parameters:
  • form – A form or a sequence of forms to pack the coefficients

  • for.

Returns:

Coefficients for each form.

dolfinx.fem.pack_constants(form: None) → None[source]#
dolfinx.fem.pack_constants(form: Form) → ndarray[tuple[Any, ...], dtype[_ScalarT]]
dolfinx.fem.pack_constants(form: Sequence[Form | None]) → list[ndarray[tuple[Any, ...], dtype[_ScalarT]]]

Pack form constants for use in assembly.

Pack the ‘constants’ that appear in forms. The packed constants can then be passed to an assembler. This is a performance optimisation for cases where a form is assembled multiple times and (some) constants do not change.

If form is a sequence of forms, this function returns an array of form constants with the same shape as form.

Parameters:

form – Single form or sequence of forms to pack the constants for.

Returns:

A constant array for each form.

dolfinx.fem.set_bc_diagonal(A: MatrixCSR[Scalar], V: FunctionSpace, bcs: Sequence[DirichletBC[Scalar]] | None, diagonal: Scalar | float | complex = 1.0) → None[source]#

Set a value on the diagonal for Dirichlet boundary condition rows.

Note

Convenience interface for callers holding V and bcs rather than the row list, which it rebuilds on every call. Library code passes the rows to set_diagonal() instead.

Parameters:
  • A – Matrix to modify. Must be associated with V on both its row and column function spaces.

  • V – Function space that the rows/columns of A are associated with.

  • bcs – Boundary conditions that identify the diagonal rows to set. If None, no rows are set.

  • diagonal – Value to set on the diagonal.

dolfinx.fem.set_diagonal(A: MatrixCSR[Scalar], rows: ndarray[tuple[Any, ...], dtype[int32]], diagonal: Scalar | float | complex | ndarray[tuple[Any, ...], dtype[Scalar]] = 1.0, insert_mode: InsertMode = InsertMode.insert) → None[source]#

Set or add values on the diagonal for given rows of a matrix.

Parameters:
  • A – Matrix to modify.

  • rows – Rows to set the diagonal value for.

  • diagonal – Value to set on the diagonal, either a single value for all rows or an array with diagonal[i] the value for rows[i]. An array must have the same length as rows.

  • insert_mode – la.InsertMode.insert to set the diagonal entries, or la.InsertMode.add to add to them.

dolfinx.fem.transpose_dofmap(dofmap: ndarray[tuple[Any, ...], dtype[int32]], num_cells: int) → AdjacencyList[int32][source]#

Build the index to (cell, local index) map from a dofmap.

Parameters:
  • dofmap – Dofmap (cell, local index) -> index, with shape (num_cells, dofs_per_cell).

  • num_cells – Number of cells in dofmap to consider. Cells beyond num_cells are ignored.

Returns:

Adjacency list where node i holds the positions in the flattened dofmap at which index i appears.