# dolfinx.fem

Tools for assembling and manipulating finite element forms.

Functions

`apply_lifting`(b, a, bcs[, x0, alpha, ...]) | Modify right-hand side vector `b` for lifting of Dirichlet boundary conditions.
`assemble_matrix`(-> ~dolfinx.la.MatrixCSR) | Assemble bilinear form into a matrix.
`assemble_scalar`(M[, constants, coeffs]) | Assemble functional.
`assemble_vector`(...) |
`bcs_by_block`(spaces, bcs) | Arrange Dirichlet boundary conditions by the function space that they constrain.
`compile_form`(comm, form, ...) | Compile UFL form without associated DOLFINx data.
`compute_integration_domains`(integral_type, ...) | Given an integral type and a set of entities 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, function_spaces, msh, ...) | Create a Form object from a data-independent compiled form.
`create_interpolation_data`(V_to, V_from, cells) | Generate data needed to interpolate discrete functions across different meshes.
`create_matrix`(a[, block_mode]) | Create a sparse matrix that is compatible with a given 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]) | Create a representation of Dirichlet boundary condition which is imposed on a linear system.
`discrete_curl`(V0, V1) | Assemble a discrete curl operator.
`discrete_gradient`(space0, space1) | Assemble a discrete gradient operator.
`extract_function_spaces`(forms[, index]) | Extract common function spaces from an array of forms.
`finiteelement`(cell_type, ufl_e, ...) | Create a DOLFINx element from a basix.ufl element.
`form`(form, dtype, form_compiler_options, ...) | Create a Form or list of Forms.
`form_cpp_class`(dtype) | Return the wrapped C++ class of a variational form of a specific scalar type.
`functionspace`(mesh, element) | Create a finite element function space.
`locate_dofs_geometrical`(V, marker) | Locate degrees-of-freedom geometrically using a marker function.
`locate_dofs_topological`(V, entity_dim, entities) | Locate degrees-of-freedom belonging to mesh entities topologically.
`mixed_topology_form`(forms, dtype, ...) | Create a mixed-topology from from an array of Forms.
`pack_coefficients`(form) | Pack form coefficients for use in assembly.
`pack_constants`(form) | Pack form constants for use in assembly.
`set_bc`(b, bcs[, x0, alpha]) | Insert boundary condition values into vector.

Classes

`Constant`(domain, c) | A constant with respect to a domain.
`CoordinateElement`(cmap) | Coordinate element describing the geometry map for mesh cells.
`DirichletBC`(bc) | Representation of Dirichlet boundary condition which is imposed on a linear system.
`DofMap`(dofmap) | Degree-of-freedom map.
`ElementMetaData`(family, degree[, shape, ...]) | Data for representing a finite element
`Expression`(e, X[, comm, ...]) | Create a DOLFINx Expression.
`FiniteElement`(cpp_object) | Creates a Python wrapper for the exported finite element class.
`Form`(form[, ufcx_form, code, module]) | A finite element form.
`Function`(*args, **kw) | A finite element function that is represented by a function space (domain, element and dofmap) and a vector holding the degrees-of-freedom.
`FunctionSpace`(mesh, element, cppV) | A space on which Functions (fields) can be defined.
`IntegralType` |

class dolfinx.fem.Constant(domain, c: float | floating | complex | complexfloating | Sequence | ndarray)

  Bases: `Constant`

  A constant with respect to a domain.

  Parameters:

    - domain – DOLFINx or UFL mesh

    - c – Value of the constant.

  property dtype: dtype
  property value

    The value of the constant

class dolfinx.fem.CoordinateElement(cmap: CoordinateElement_float32 | CoordinateElement_float64)

  Bases: `object`

  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.

  create_dof_layout() → ElementDofLayout

    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

    Hash identifier of the coordinate element.

  pull_back(x: ndarray[tuple[Any, ...], dtype[float32]] | ndarray[tuple[Any, ...], dtype[float64]], cell_geometry: ndarray[tuple[Any, ...], dtype[float32]] | ndarray[tuple[Any, ...], dtype[float64]]) → ndarray[tuple[Any, ...], dtype[float32]] | ndarray[tuple[Any, ...], dtype[float64]]

    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.dofmap.cell_dofs(i)]`,

    Returns:

      Reference coordinates of the physical points `x`.

  push_forward(X: ndarray[tuple[Any, ...], dtype[float32]] | ndarray[tuple[Any, ...], dtype[float64]], cell_geometry: ndarray[tuple[Any, ...], dtype[float32]] | ndarray[tuple[Any, ...], dtype[float64]]) → ndarray[tuple[Any, ...], dtype[float32]] | ndarray[tuple[Any, ...], dtype[float64]]

    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.dofmap.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)

  Bases: `object`

  Representation of Dirichlet boundary condition which is imposed on a linear system.

  Note

  Dirichlet boundary conditions should normally be constructed using `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:

    - value – Lifted boundary values function.

    - dofs – Local indices of degrees of freedom in function space to which boundary condition applies. Expects array of size (number of dofs, 2) if function space of the problem, `V` is passed. 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.

  dof_indices() → tuple[ndarray[tuple[Any, ...], dtype[int32]], int]

    Access dof indices (local indices, unrolled), including ghosts, to which a Dirichlet condition is applied, and the index to the first non-owned (ghost) index. The array of indices is sorted.

    Note

    The returned array is read-only.

    Returns:

      Sorted array of dof indices (unrolled) and 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

    The function space on which the boundary condition is defined

  property g: Function | Constant | ndarray

    The boundary condition value(s)

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

    Set entries in an array that are constrained by Dirichlet boundary conditions.

    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.

    If x includes ghosted entries (entries available on the calling rank but owned by another rank), ghosted entries constrained by a Dirichlet condition will also be set.

    Parameters:

      - x – Array to modify for Dirichlet boundary conditions.

      - x0 – Optional array used in computing the value to set. If not provided it is treated as zero.

      - alpha – Scaling factor.

class dolfinx.fem.DofMap(dofmap: DofMap)

  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.

  property bs

    Block size of the dofmap.

  cell_dofs(cell_index: int)

    Cell local-global dof map

    Parameters:

      cell – The cell index.

    Returns:

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

  property dof_layout

    Layout of dofs on an element.

  property index_map

    Index map that described the parallel distribution of the dofmap.

  property index_map_bs

    Block size of the index map.

  property list

    Adjacency list with dof indices for each cell.

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

  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)

  Bases: `object`

  Create a DOLFINx Expression.

  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.

  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.

  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

    Evaluation points on the reference cell

  property argument_space: FunctionSpace | None

    Argument function space if Expression has argument.

  property code: str

    C code strings.

  property dtype: dtype
  eval(mesh: Mesh, entities: np.ndarray, values: np.ndarray | None = None) → np.ndarray

    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

    The compiled ufcx_expression object.

  property ufl_expression

    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)

  Bases: `object`

  Creates a Python wrapper for the exported finite element class.

  Note

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

  Parameters:

    wrap. (The underlying cpp instance that this object will)

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

    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[floating]], cell_permutations: ndarray[tuple[Any, ...], dtype[uint32]], dim: int) → None

    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[floating]], cell_permutations: ndarray[tuple[Any, ...], dtype[uint32]], dim: int) → None

    Apply the inverse 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`.

  property basix_element: FiniteElement

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

    Raises:

      Runtime error if Basix element does not exist. –

  property dtype: dtype

    Geometry type of the Mesh that the FunctionSpace is defined on.

  property interpolation_ident: bool

    Check 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[floating]]

    Points on the reference cell at which an expression needs to be evaluated in order to interpolate the expression in the finite element space.

    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 signature: str

    String identifying the finite element.

  property space_dimension: int

    Dimension of the finite element function space (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.

    The value shape describes the shape of the finite element field, e.g. `{}` for a scalar, `{2}` for a vector in 2D, `{3, 3}` for a rank-2 tensor in 3D, etc.

class dolfinx.fem.Form(form: Form_complex64 | Form_complex128 | Form_float32 | Form_float64, ufcx_form=None, code: str | list[str] | None = None, module: ModuleType | list[ModuleType] | None = None)

  Bases: `object`

  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.

    - ufcx_form – UFCx form.

    - code – Form C++ code.

    - module – CFFI module.

  property code: str | list[str] | None

    C code strings.

  property dtype: dtype

    Scalar type of this form.

  property function_spaces: list[FunctionSpace]

    Function spaces on which this form is defined.

  property integral_types

    Integral types in the form.

  property mesh: Mesh_float32 | Mesh_float64

    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

    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
  property ufcx_form

    The compiled ufcx_form object.

class dolfinx.fem.Function(*args, **kw)

  Bases: `Coefficient`

  A finite element function that 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
  copy() → Function

    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.

  property dtype: dtype
  eval(x: ArrayLike, cells: ArrayLike, u=None) → ndarray

    Evaluate Function at points x.

    Points where x has shape (num_points, 3), and cells has shape (num_points,) and cell[i] is the index of the cell containing point x[i]. If the cell index is negative the point is ignored.

  property function_space: FunctionSpace

    The FunctionSpace that the Function is defined on.

  interpolate(u0: Callable | Expression | Function, cells0: ndarray | None = None, cells1: ndarray | None = None) → None

    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`, then it must have the same length as `cells0`.

  interpolate_nonmatching(u0: Function, cells: ndarray[tuple[Any, ...], dtype[int32]], interpolation_data: PointOwnershipData) → None

    Interpolate a Function defined on one mesh to a function defined on a different mesh.

    Parameters:

      - u0 – The 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()`.

  property name: str

    Name of the Function.

  split() → tuple[Function, ...]

    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

    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

    Vector holding the degrees-of-freedom.

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

  Bases: `FunctionSpace`

  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

    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, ndarray]

    Collapse a subspace and return a new function space and a map from new to old dofs.

    Returns:

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

  component()

    Return the component relative to the parent space.

  contains(V) → bool

    Check if a space is contained in, or is the same as (identity), 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.

  property dofmap: DofMap

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

  dofmaps(idx: int) → DofMap
  property element: FiniteElement

    Function space finite element.

  property mesh: Mesh

    Mesh on which the function space is defined.

  property num_sub_spaces: int

    Number of sub spaces.

  sub(i: int) → FunctionSpace

    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[float64]]

    Tabulate the coordinates of the degrees-of-freedom in the function space.

    Returns:

      Coordinates of the degrees-of-freedom.

    Note

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

  ufl_function_space() → FunctionSpace

    UFL function space.

dolfinx.fem.IntegralType

  alias of `_IntegralType`

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: ndarray[tuple[Any, ...], dtype[_ScalarT]] | None = None, coeffs: dict[tuple[_IntegralType, int], ndarray[tuple[Any, ...], dtype[_ScalarT]]] | None = None) → None

  Modify right-hand side vector `b` for lifting of Dirichlet boundary 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`.

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
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 on the matrix diagonal.

    - diagonal – 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.

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

  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
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]]

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

  Arrange Dirichlet boundary conditions by the function 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.compile_form(comm: Intracomm, form: Form, form_compiler_options: dict | None = {'scalar_type': <class 'numpy.float64'>}, jit_options: dict | None = None) → CompiledForm

  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: ndarray)

  Given an integral type and a set of entities 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, degree: int, variant=0, dtype: DTypeLike = <class 'numpy.float64'>)
dolfinx.fem.coordinate_element(e: FiniteElement)

  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.

  Returns:

    A coordinate element.

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

  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, function_spaces: 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

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

  Parameters:

    - form – Compiled ufl form function_spaces: List of function spaces

    - the (associated with) – form. Should match the number of arguments in the form.

    - msh – Mesh to associate form with. subdomains: A map from

    - pairs (integral type to a list of) – each pair corresponds to a subdomain id and the set of of integration entities to integrate over. Can be computed with {py:func}`dolfinx.fem.compute_integration_domains`.

    - where – each pair corresponds to a subdomain id and the set of 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) → PointOwnershipData

  Generate data needed to interpolate discrete functions across 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 of bounding boxes of all entities on mesh_to

  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

  Create a sparse matrix that is compatible with a given 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: Form)

  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 `assemble` on the sparsity pattern.

dolfinx.fem.create_vector(V: FunctionSpace, dtype: DTypeLike = <class 'numpy.float64'>) → Vector

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

  Parameters:

    V – A function space.

  Returns:

    A vector compatible with the function space.

dolfinx.fem.dirichletbc(value: Function | Constant | ndarray, dofs: ndarray[tuple[Any, ...], dtype[int32]], V: FunctionSpace | None = None) → DirichletBC

  Create a representation of Dirichlet boundary condition which is imposed on a linear system.

  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. Expects array of size (number of dofs, 2) if function space of the problem, `V`, is passed. 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

  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

  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 | Sequence[Form] | Sequence[Sequence[Form]], index: int = 0) → FunctionSpace | list[None | FunctionSpace]

  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 – Index of the function space to extract. If `index=0`, the test function spaces are extracted, if `index=1` the trial function spaces are extracted.

  Returns:

    List of function spaces.

dolfinx.fem.finiteelement(cell_type: CellType, ufl_e: _ElementBase, FiniteElement_dtype: dtype) → FiniteElement

  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.

dolfinx.fem.form(form: ufl.Form | Sequence[ufl.Form] | Sequence[Sequence[ufl.Form]], dtype: npt.DTypeLike = <class 'numpy.float64'>, form_compiler_options: dict | None = None, jit_options: dict | None = None, entity_maps: Sequence[_EntityMap] | None = None)

  Create a Form or list of Forms.

  Parameters:

    - form – A UFL form or iterable of UFL forms.

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

    - form_compiler_options – See `ffcx_jit`

    - jit_options – See `ffcx_jit`.

    - 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: DTypeLike) → Form_float32 | Form_float64 | Form_complex64 | Form_complex128

  Return the wrapped C++ class of a variational form of a specific scalar type.

  Parameters:

    dtype – Scalar type of the required form class.

  Returns:

    Wrapped C++ form class of the requested type.

  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

  Create a finite element function space.

  Parameters:

    - mesh – Mesh that space is defined on.

    - element – Finite element description.

  Returns:

    A function space.

dolfinx.fem.locate_dofs_geometrical(V: FunctionSpace | Iterable[FunctionSpace], marker: Callable) → 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 a list of two function spaces, then a 2-D array of shape (number of dofs, 2) is returned.

    Returned degree-of-freedom indices are unique and ordered by the first column.

dolfinx.fem.locate_dofs_topological(V: FunctionSpace | Iterable[FunctionSpace], entity_dim: int, entities: ndarray[tuple[Any, ...], dtype[int32]], remote: bool = True) → 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 a list of two function spaces, then a 2-D array of shape (number of dofs, 2) is returned.

    Returned degree-of-freedom indices are unique and ordered by the first column.

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, entity_maps: Sequence[_EntityMap] | None = None)

  Create a mixed-topology from 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:

    - form – 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`.

    - 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 | Sequence[Form]) → dict[tuple[_IntegralType, int], ndarray[tuple[Any, ...], dtype[_ScalarT]]] | 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: Form | Sequence[Form]) → ndarray[tuple[Any, ...], dtype[_ScalarT]] | Sequence[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(b: ndarray[tuple[Any, ...], dtype[_ScalarT]], bcs: Sequence[DirichletBC], x0: ndarray[tuple[Any, ...], dtype[_ScalarT]] | None = None, alpha: float = 1) → None

  Insert boundary condition values into vector.

  Note

  This function is deprecated.

  Only local (owned) entries are set, hence communication after calling this function is not required unless ghost entries need to be updated to the boundary condition value.