The symbolic layer

Contents

The symbolic layer#

The symbolic description of variational problems, without mesh data.

Domains and coordinate systems#

class sumfem.symbolic.Domain(name, cell, gdim=None, degree=1, length_scale=1.0, lagrange_variant=None, coordinates=None)[source]#

A symbolic description of a type of mesh.

A domain has a name, a cell type and named markers, but does not store any data.

A domain is named independently of the models that use it, and is shared between models by identity. Several models written on the same Domain are discretized on the same mesh.

Subdomains are referred to by marker names, see measure(). The discretization later maps the names to the tags of an actual mesh.

Parameters:
  • name (str) – Name of the domain, used to pair it with a mesh.

  • cell (CellType) – Cell type, e.g. "triangle" or "hexahedron".

  • gdim (int | None) – Geometric dimension. Defaults to the topological dimension.

  • degree (int) – Degree of the coordinate element.

  • length_scale (float) – Typical length of the domain in metres, used as reference length in dimensional analysis. Mesh coordinates are in metres.

  • lagrange_variant (basix.LagrangeVariant | str | None) – Lagrange variant of the coordinate element. It must match the mesh, e.g. "equispaced" for meshes read from gmsh. from_mesh() takes it from a mesh.

  • coordinates (CoordinateSystem | None) – The coordinate system, which weights the integrals over the domain, e.g. Cylindrical for an axisymmetric body. Defaults to Cartesian.

Raises:

ComponentError – For a name that is not an identifier, a length scale that is not positive, or a coordinate system the geometric dimension does not fit.

classmethod from_mesh(name, mesh, length_scale=1.0, coordinates=None)[source]#

A domain whose coordinate element matches an existing mesh.

Parameters:
  • name (str) – Name of the domain.

  • mesh (Mesh) – The mesh, which provides cell type, geometric dimension, coordinate degree and Lagrange variant.

  • length_scale (float) – See Domain.

  • coordinates (CoordinateSystem | None) – See Domain.

Return type:

Domain

property name: str#

Name of the domain.

property cell_name: str#

Name of the cell type, e.g. "triangle".

property length_scale: float#

Typical length of the domain in metres, for dimensional analysis.

property coordinates: CoordinateSystem#

The coordinate system, which weights the integrals.

property tdim: int#

Topological dimension.

property gdim: int#

Geometric dimension.

entity_dimension(entity_type)[source]#

Topological dimension of an entity type on this domain.

Raises:

ComponentError – If the entity type does not exist on this domain, for instance a ridge on an interval mesh.

Parameters:

entity_type (Literal['cell', 'facet', 'ridge', 'peak', 'vertex'])

Return type:

int

marker_ids(markers, entity_type)[source]#

Return the integer ids of named markers, assigning ids to new names.

The ids are numbered separately per entity dimension, so entity types that coincide share their markers: on a triangle mesh a ridge is a vertex, and "A" has the same id for both.

Parameters:
  • markers (str | Sequence[str]) – Name of a subdomain, e.g. "Electrode", or a sequence of names.

  • entity_type (Literal['cell', 'facet', 'ridge', 'peak', 'vertex']) – The entities the markers refer to.

Returns:

One id per marker, in the given order.

Return type:

tuple[int, …]

property markers: dict[int, dict[str, int]]#

Copy of the marker name to integer id maps, per entity dimension.

measure(integral_type, *markers, degree=None, metadata=None)[source]#

Create a measure over the whole domain or over named subdomains.

Subdomains are referred to by marker name, e.g. domain.measure("dx", "Electrode"), or with the shortcuts domain.dx("Electrode") and domain.ds("Inlet"). Entity types that coincide share their markers, see marker_ids(): on a triangle mesh dr("A") and dP("A") refer to the same vertices.

Parameters:
  • integral_type (Literal['dx', 'ds', 'dS', 'dr', 'dP']) – One of "dx", "ds", "dS", "dr" or "dP".

  • markers (str) – Names of the subdomains to integrate over. With no names, the measure covers the whole domain.

  • degree (int | None) – Quadrature degree. Shorthand for metadata={"quadrature_degree": degree}.

  • metadata (dict | None) – Form compiler metadata for the measure.

Return type:

Measure

dx(*markers, degree=None, metadata=None)#

Cell measure over the domain, or over the named cell markers.

Parameters:
  • markers (str)

  • degree (int | None)

  • metadata (dict | None)

Return type:

ufl.Measure

ds(*markers, degree=None, metadata=None)#

Exterior facet measure, optionally restricted to named facet markers.

Parameters:
  • markers (str)

  • degree (int | None)

  • metadata (dict | None)

Return type:

ufl.Measure

dS(*markers, degree=None, metadata=None)#

Interior facet measure, optionally restricted to named facet markers.

Parameters:
  • markers (str)

  • degree (int | None)

  • metadata (dict | None)

Return type:

ufl.Measure

dr(*markers, degree=None, metadata=None)#

Ridge measure (codimension 2), optionally restricted to named ridges.

Parameters:
  • markers (str)

  • degree (int | None)

  • metadata (dict | None)

Return type:

ufl.Measure

dP(*markers, degree=None, metadata=None)#

Vertex measure, optionally restricted to named vertex markers.

Parameters:
  • markers (str)

  • degree (int | None)

  • metadata (dict | None)

Return type:

ufl.Measure

one_sided(marker)[source]#

The subdomain a facet marker sees its facets from, if one-sided.

Facet integrals of a subdomain of cells move to its parent as integrals over facets seen from the subdomain’s side, see Subdomain.on_parent(), under markers named "<subdomain>.<marker>". Inside the parent, such facets may have cells on several sides, e.g. at the joint of a branching surface.

Returns:

The subdomain and its own facet marker, None for its whole boundary, or None if the marker is not one-sided.

Parameters:

marker (str)

Return type:

tuple[Subdomain, str | None] | None

interface(first, second, marker, degree=None, metadata=None)[source]#

Interior facet measure of an interface between two subdomains.

Its "+" side is always in first and its "-" side in second, so the functions of each subdomain can be restricted to their own side, e.g. u_0("+") and u_1("-") for an exchange flux between two materials.

Parameters:
  • first (Subdomain) – The subdomain of cells on the "+" side.

  • second (Subdomain) – The subdomain of cells on the "-" side.

  • marker (str) – This domain’s facet marker of the interface.

  • degree (int | None) – Quadrature degree, see measure().

  • metadata (dict | None) – Form compiler metadata, see measure().

Raises:

ComponentError – If a subdomain is not a subdomain of cells of this domain.

Return type:

Measure

interface_sides(marker)[source]#

The subdomains and facet marker of an interface measure’s marker.

See interface(). None if the marker is not an interface.

Parameters:

marker (str)

Return type:

tuple[Subdomain, Subdomain, str] | None

interfaces_of(measure)[source]#

The interfaces an interior facet measure of this domain covers.

See interface() and interface_sides().

Parameters:

measure (Measure) – An interior facet measure.

Returns:

The two subdomains and the facet marker of each interface the measure covers, "+" side first. Empty if it covers any facets that are not an interface, e.g. those of a plain measure(), or if it is not this domain’s.

Return type:

tuple[tuple[Subdomain, Subdomain, str], …]

class sumfem.symbolic.Subdomain(name, parent, dim, marker, length_scale=None)[source]#

Marked entities of a domain, as a domain of their own.

Fields on a subdomain live on a submesh of a subset of the parent’s mesh entities, those with the subdomain’s marker. These are cells, e.g. the electrolyte of a cell, or facets, e.g. the concentration of a species on a surface, or the unknown of a PDE on a manifold. dx integrates over the subdomain, ds over its boundary and dS over its interior facets. Markers are named after the parent’s: those of dx are parent markers of the subdomain’s dimension, and those of ds and dS parent markers of one dimension lower. For a surface of a 3D domain, these are facet and ridge markers. Its coordinates are the parent’s, and so is its coordinate system.

Whether a form is integrated on the submesh or on the parent is decided per form, see place_subdomain_integrals().

Parameters:
  • name (str) – Name of the domain.

  • parent (Domain) – The domain the entities belong to.

  • dim (int) – Topological dimension of the entities, e.g. parent.tdim - 1 for facets.

  • marker (str) – The parent’s marker of the entities, e.g. "Membrane".

  • length_scale (float | None) – See Domain. Defaults to the parent’s.

property parent: Domain#

The domain the entities belong to.

property marker: str#

The parent’s marker of the entities.

property codim: int#

Codimension of the subdomain in its parent.

property coordinates: CoordinateSystem#

The parent’s coordinate system, since the coordinates are the same.

measure(integral_type, *markers, degree=None, metadata=None)[source]#

A measure of this domain, as Domain.measure().

The markers are the parent’s markers of the measure’s entities, which have the same dimension in the parent: e.g. for a surface of a 3D domain, facet markers for dx, ridge markers for ds and dS, and vertex markers for dr.

Parameters:
  • integral_type (Literal['dx', 'ds', 'dS', 'dr', 'dP'])

  • markers (str)

  • degree (int | None)

  • metadata (dict | None)

Return type:

Measure

dx(*markers, degree=None, metadata=None)#

Cell measure of this domain, optionally restricted to named parts.

Parameters:
  • markers (str)

  • degree (int | None)

  • metadata (dict | None)

Return type:

ufl.Measure

ds(*markers, degree=None, metadata=None)#

Measure of this domain’s boundary, optionally of named parts of it.

Parameters:
  • markers (str)

  • degree (int | None)

  • metadata (dict | None)

Return type:

ufl.Measure

dS(*markers, degree=None, metadata=None)#

Measure of this domain’s interior facets, optionally of named ones.

Parameters:
  • markers (str)

  • degree (int | None)

  • metadata (dict | None)

Return type:

ufl.Measure

dr(*markers, degree=None, metadata=None)#

Ridge measure of this domain, optionally restricted to named ridges.

Parameters:
  • markers (str)

  • degree (int | None)

  • metadata (dict | None)

Return type:

ufl.Measure

dP(*markers, degree=None, metadata=None)#

Vertex measure of this domain, optionally restricted to named vertices.

Parameters:
  • markers (str)

  • degree (int | None)

  • metadata (dict | None)

Return type:

ufl.Measure

on_parent(integral)[source]#

An integral of this domain, as one on the parent’s entities.

A cell integral moves to the parent’s cells for a subdomain of cells, and to its exterior facets for a subdomain of facets. For a subdomain of facets between two subdomains of cells, an interface of the parent, see Domain.interface(), an integral over the whole subdomain moves to the interior facets of the interface, on its "+" side, which holds the same values of the facets’ functions as the other. An exterior facet integral of a subdomain of cells moves to the parent’s facets seen from the subdomain’s side, under a one-sided marker, see Domain.one_sided(): e.g. the joint of a branching surface, seen from one branch. The functions and the geometry of the submesh in it, e.g. its spatial coordinate, are mapped by the entity map, and its facet normal is the parent’s.

Raises:

ComponentError – For other integrals, or subdomains of codimension above one.

Parameters:

integral (Integral)

Return type:

Integral

class sumfem.symbolic.CoordinateSystem(*args, **kwargs)[source]#

How the integrals over a domain are weighted.

A coordinate system may also write the vectors of integrands in its basis, with the method lift(integrand, x), see Cylindrical.lift(), and say whether it supports vector-valued unknowns with the class attribute vectors. Without them, integrands are kept as they are and only scalar unknowns are supported, see lift() and supports_vectors().

weight(x)[source]#

The weight of an integral.

Parameters:

x (Expr) – The spatial coordinate of the domain.

Return type:

Expr

check(gdim)[source]#

Check that a domain of geometric dimension gdim can use it.

Raises:

ComponentError – If it cannot.

Parameters:

gdim (int)

Return type:

None

class sumfem.symbolic.Cartesian[source]#

Integrals without a weight, the default of every domain.

The weight is the integer one, which UFL drops from products, and integrands are kept as they are, so forms keep their integrands.

check(gdim)[source]#

Any geometric dimension.

Parameters:

gdim (int)

Return type:

None

class sumfem.symbolic.Cylindrical[source]#

An axisymmetric body, with the weight 2 pi r.

The mesh lies in the half-plane x[0] = r >= 0, with x[1] = z on a 2D mesh. On a 1D mesh in r the integrals are per unit length of an infinite cylinder. On the axis the weight vanishes, so the symmetry condition of scalars there is the natural one. A vector’s radial component vanishes on the axis, which is a Dirichlet condition.

Vectors are written in the basis (r, z, theta): a field of shape (gdim,) has no swirl, and one of shape (3,) has the swirl u_theta as its last component. Fields do not depend on theta.

lift(integrand, x)[source]#

See _Lift.

Parameters:
Return type:

Expr

gradient(f, x)[source]#

The gradient of a scalar or a vector in (r, z, theta).

Raises:

ComponentError – For other shapes.

Parameters:
Return type:

Expr

divergence(f, x)[source]#

The divergence of a vector or a tensor in (r, z, theta).

Raises:

ComponentError – For other shapes.

Parameters:
Return type:

Expr

class sumfem.symbolic.Spherical[source]#

A radially symmetric body, with the weight 4 pi r^2.

The mesh is an interval in x[0] = r >= 0. Vectors are written in the basis (r, theta, phi), and only have a radial component.

lift(integrand, x)[source]#

See _Lift.

Parameters:
Return type:

Expr

gradient(f, x)[source]#

The gradient of a scalar or a radial vector in (r, theta, phi).

Raises:

ComponentError – For other shapes.

Parameters:
Return type:

Expr

divergence(f, x)[source]#

The divergence of a radial vector or a diagonal tensor.

Raises:

ComponentError – For other shapes.

Parameters:
Return type:

Expr

class sumfem.symbolic.Weighted(weight_of)[source]#

Integrals with any weight of the spatial coordinate.

E.g. Weighted(lambda x: 2 * pi * (1 - cos(theta)) * x[0] ** 2) for a cone of half-angle theta around its axis, in the distance x[0] from its apex. Integrands are kept as they are, so only scalar unknowns are supported.

Parameters:

weight_of (Callable[[Expr], Expr | float])

weight_of#

The weight, as a function of the spatial coordinate.

Type:

Callable[[ufl.core.expr.Expr], ufl.core.expr.Expr | float]

check(gdim)[source]#

Any geometric dimension.

Parameters:

gdim (int)

Return type:

None

sumfem.symbolic.apply_coordinates(form: ufl.Form) → ufl.Form[source]#
sumfem.symbolic.apply_coordinates(form: ufl.ZeroBaseForm) → ufl.ZeroBaseForm

A form with each integral in its domain’s coordinate system.

Each integrand is lifted, see CoordinateSystem.lift(), and weighted. Integrals over a mesh that is not a Domain are Cartesian. On interior facets the weight is taken from the "+" side.

Fields, parameters and known coefficients#

class sumfem.symbolic.Field(*args, **kw)[source]#

An unknown of a variational problem.

A field is the coefficient holding the solution, so models use it directly in expressions, e.g. ufl.grad(c). It also owns:

  • v: the test function of its equation,

  • du: the trial function, for hand-written Jacobians,

  • dot: a placeholder for its time derivative,

  • previous(k): its value k time steps back.

Models that write terms with the same field.v contribute to the same equation when they are summed. A model that uses the field without writing an equation for it is coupled to whichever model does.

The name must be passed positionally: ufl.Coefficient.__new__ reads the first positional argument.

Parameters:
  • name (str) – Unique name of the field.

  • domain (Domain) – The domain the field lives on.

  • element (ElementSpec) – The finite element, see ElementSpec.

  • unit (Unit | None) – Unit of the field, a sympy unit expression. None means dimensionless. Values given for the field, such as initial and boundary values, are in this unit. The discretization stores them in SI base units.

  • scale (float) – Typical magnitude of the field in its unit, used as reference value in dimensional analysis.

  • spatial (bool) – Whether the components of a vector-valued field are those of a vector in physical space, which change with the basis of the coordinates, e.g. a velocity or a displacement, or independent scalars, which do not, e.g. the concentrations of several species. The two differ only on domains whose coordinate system has a curved basis, e.g. Cylindrical: there a vector in space gains components in the angular directions, and its gradient the terms of the Christoffel symbols. In Cartesian coordinates, and with a weight alone, they are the same. Elements mapped by a Piola transformation, e.g. Raviart-Thomas or Nedelec, are always vectors in space.

Raises:

ComponentError – For spatial=False with an element mapped by a Piola transformation.

property name: str#

Name of the field.

property spatial: bool#

Whether the components are those of a vector in physical space.

property domain: Domain#

Domain the field lives on.

property element: AbstractFiniteElement#

Finite element of the field.

property unit: Expr#

Unit of the field, 1 if dimensionless.

property scale: float#

Typical magnitude of the field in its unit, for dimensional analysis.

property v: Argument[source]#

The test function of this field’s equation.

Its part number is the field’s count, unique among all fields.

property du: Argument[source]#

The trial function, for hand-written Jacobians.

property dot: FieldTerminal[source]#

Placeholder for the time derivative of the field.

A time-stepping scheme replaces it, for instance by a backward difference of the field and its previous() values.

previous(k=1)[source]#

The value of the field k time steps back.

Parameters:

k (int)

Return type:

FieldTerminal

class sumfem.symbolic.Parameter(*args, **kw)[source]#

A named value that is constant in space, with a unit.

The value lives on a Real function space, a single global degree of freedom per component. This means a residual can be differentiated with respect to a parameter, as needed for sensitivities and optimal control. The discretization owns the degree of freedom on one process and keeps all processes in sync.

A parameter is also a ufl_units quantity, so dimensional analysis finds it in forms. Its scale for that analysis is the largest magnitude of its default, or 1 without a non-zero default.

Parameters:
  • name (str) – Unique name. Parameters created through parameter() are named "<component>.<name>".

  • domain (Domain) – The domain the parameter is defined on.

  • shape (tuple[int, ...]) – Value shape, () for a scalar.

  • default (npt.ArrayLike | sympy.Expr | None) – Default value in unit, used when no other value is set, or a sympy quantity carrying its own units, e.g. 0.5 * syu.millimeter, converted to unit. A scalar sets every component of a vector or tensor parameter.

  • unit (Unit | None) – Unit of the value, a sympy unit expression. None means dimensionless. The discretization stores values in SI base units.

  • doc (str) – Description, shown in documentation and archived metadata.

The name must be passed positionally: ufl.Coefficient.__new__ reads the first positional argument.

Raises:

ValueError – If a default with units does not have the dimension of unit.

Parameters:
  • name (str)

  • domain (Domain)

  • shape (tuple[int, ...])

  • default (npt.ArrayLike | sympy.Expr | None)

  • unit (Unit | None)

  • doc (str)

property name: str#

Unique name.

property shape: tuple[int, ...]#

Value shape.

property default: ndarray[tuple[Any, ...], dtype[Any]] | None#

Default value, or None if the value must be set explicitly.

property default_si: ndarray[tuple[Any, ...], dtype[Any]] | None#

Default value in SI base units, as the discretization stores it, or None without a default.

property doc: str#

Description of the parameter.

class sumfem.symbolic.KnownCoefficient(*args, **kw)[source]#

Named, spatially varying data that a model reads but does not solve for.

It is also a ufl_units quantity, so dimensional analysis finds it in forms, with its typical magnitude as scale.

Parameters:
  • name (str) – Unique name. Known coefficients created through known_coefficient() are named "<component>.<name>".

  • domain (Domain) – The domain the data is defined on.

  • element (ElementSpec) – The finite element, see ElementSpec.

  • unit (Unit | None) – Unit of the data, a sympy unit expression. None means dimensionless. The discretization stores values in SI base units.

  • scale (float) – Typical magnitude of the data in its unit, for dimensional analysis.

  • doc (str) – Description of the data.

The name must be passed positionally: ufl.Coefficient.__new__ reads the first positional argument.

property name: str#

Unique name.

property element: AbstractFiniteElement#

Finite element of the data.

property doc: str#

Description of the data.

sumfem.symbolic.as_expr(value)[source]#

Convert a component input to a UFL expression.

UFL expressions, including a Field, Parameter and KnownCoefficient, are returned unchanged. Numbers and nested sequences of numbers become UFL literals.

Parameters:

value (Expr | Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str])

Return type:

Expr

sumfem.symbolic.value_at_defaults(expr)[source]#

The value of an expression of parameters at their defaults, in SI units.

Use it for a value that follows from the parameters of a model before anything is discretized, e.g. the permeability of an electrode or the pressure drop of a flow, as the scale of a field.

Parameters:

expr (Expr) – An expression of parameters and numbers.

Raises:

ComponentError – If the expression depends on anything but parameters with defaults, e.g. a field or the spatial coordinate.

Return type:

float | ndarray[tuple[Any, …], dtype[float64]]

Example

The scale of a pressure from a viscosity, a velocity, a length and a permeability, all parameters:

p = Field("p", domain, ("Lagrange", 1), unit=syu.pascal,
          scale=value_at_defaults(mu * v * L / K))

Components#

class sumfem.symbolic.Component(name)[source]#

What residuals and functionals share: a name, and named inputs.

Parameters:

name (str) – Unique name of the component. It prefixes the names of parameters and known coefficients the component creates, as "<name>.<parameter>".

property name: str#

Name of the component.

parameter(name, domain, shape=(), default=None, unit=None, doc='')[source]#

Return the parameter "<component>.<name>", creating it on first call.

Calling this again with the same name returns the same object, so it is safe to call while building a form.

Parameters:
Return type:

Parameter

known_coefficient(name, domain, element, unit=None, scale=1.0, doc='')[source]#

Return the known coefficient "<component>.<name>", made on first call.

Parameters:
Return type:

KnownCoefficient

input(name, value=None, *, domain, element=None, shape=(), default=None, unit=None, scale=1.0, doc='')[source]#

Resolve an input given to the constructor.

If value is given, it is converted with as_expr(). Passing a Field couples this component to the field. Otherwise a placeholder named "<component>.<name>" is created: a KnownCoefficient when element is given, else a Parameter of the given shape. unit applies to either, scale to a known coefficient and default to a parameter.

Parameters:
Return type:

Expr

property components: tuple[Component, ...]#

The summands. A single component is its own summand.

sumfem.symbolic.input_or_parameter(name, value, domain, *, shape=(), default=None, unit=None, doc='')[source]#

An input given as a value, or else a new parameter named name.

As Component.input(), for code that is not a component and names its parameters itself, such as a sum of components under one name, whose summands share its parameters, or a container of the parameters of several models.

Parameters:
  • name (str) – The full name of the parameter, e.g. "<model>.<input>".

  • value (Expr | Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str] | None) – The value, converted with as_expr(), or None for the parameter.

  • domain (Domain) – The domain of the parameter.

  • shape (tuple[int, ...]) – The shape of the parameter.

  • default (Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str] | None) – The default value of the parameter.

  • unit (Expr | None) – The unit of the parameter.

  • doc (str) – A description of the parameter.

Return type:

Expr

sumfem.symbolic.expression_or_parameter(name, value, domain, *, shape=(), unit=None, doc='')[source]#

An expression, or else a new parameter with a value as its default.

Unlike input_or_parameter(), which turns a number into a constant, a number here becomes the default of a parameter named name, so that it has a unit and can be changed on a discretization. An expression, e.g. a parameter shared with another model or a field, is used as given.

Parameters:
  • name (str) – The full name of the parameter, e.g. "<model>.<property>".

  • value (Expr | Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str] | Expr | None) – An expression, used as given, or the default of the parameter, in unit or a quantity with units; None for a parameter without a default.

  • domain (Domain) – The domain of the parameter.

  • shape (tuple[int, ...]) – The shape of the parameter.

  • unit (Expr | None) – The unit of the parameter.

  • doc (str) – A description of the parameter.

Returns:

The expression or the parameter.

Return type:

Expr

sumfem.symbolic.ExpressionOrValue = ufl.core.expr.Expr | collections.abc.Buffer | numpy._typing._array_like._SupportsArray[numpy.dtype[typing.Any]] | numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[typing.Any]]] | complex | bytes | str | numpy._typing._nested_sequence._NestedSequence[complex | bytes | str] | None#

Represent a union type

E.g. for int | str

sumfem.symbolic.ExpressionOrDefault = ufl.core.expr.Expr | collections.abc.Buffer | numpy._typing._array_like._SupportsArray[numpy.dtype[typing.Any]] | numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[typing.Any]]] | complex | bytes | str | numpy._typing._nested_sequence._NestedSequence[complex | bytes | str] | sympy.core.expr.Expr | None#

Represent a union type

E.g. for int | str

class sumfem.symbolic.Residual(name)[source]#

Base class for a reusable contribution to a residual.

Subclasses override residual() and write it with the fields they act on and their test functions field.v. Everything the residual uses is discovered from the form, so there is no registration of unknowns, parameters or known coefficients. A subclass that overrides one term only changes that term.

The residual is built on first use and then cached, so a component should be fully configured before it is summed or turned into a system.

Parameters:

name (str) – Unique name of the component. It prefixes the names of parameters and known coefficients the component creates, as "<name>.<parameter>".

residual()[source]#

Return this component’s contribution to the residual.

The form must be linear in test functions field.v and contain no trial functions. A contribution that is zero, e.g. for some inputs, is ufl.ZeroBaseForm((field.v,)): UFL drops the test function from a form whose terms vanish.

Return type:

Form | ZeroBaseForm

jacobian()[source]#

Return a hand-written linearization of residual(), or None.

A Jacobian, or a form with field.du as trial functions. Blocks for unknowns it does not mention are zero. With None, the Jacobian is derived automatically.

Return type:

Jacobian | Form | None

preconditioner()[source]#

Return this component’s contribution to a preconditioner, or None.

If any summand provides a preconditioner, summands without one contribute their Jacobian.

Return type:

Jacobian | Form | None

property components: tuple[Residual, ...]#

The summands. A single component is its own summand.

property form: Form | ZeroBaseForm[source]#

The residual, built on first access and then cached.

property jacobian_term: Jacobian | None[source]#

The hand-written Jacobian, if any, built on first access.

property preconditioner_term: Jacobian | None[source]#

The preconditioner contribution, if any, built on first access.

property inventory: Inventory[source]#

The named objects used by this component, validated.

property fields: tuple[Field, ...]#

Every field the component uses, in creation order.

property equations: tuple[Field, ...]#

Fields the component writes equation terms for, in creation order.

property parameters: Mapping[str, Parameter]#

Parameters used by the component, by name.

property known_coefficients: Mapping[str, KnownCoefficient]#

Known coefficients used by the component, by name.

property domains: tuple[Domain, ...]#

Domains used by the component.

to_jacobian(fields=None, name=None)[source]#

The derived linearization sum_f derivative(F, f, f.du).

It is derived after the substitutions of the system it is used in, e.g. of a time-stepping scheme, so the terms of time derivatives are linearized too.

Parameters:
  • fields (Sequence[Field] | None) – The fields to linearize in. Defaults to the unknowns of the system it is used in, or, on its own, the fields this residual writes equations for.

  • name (str | None) – Name of the Jacobian. Defaults to the residual’s name.

Return type:

Jacobian

with_jacobian(jacobian)[source]#

This residual, linearized by the given Jacobian.

It replaces the whole Jacobian of this residual: of every summand of a sum, hand-written or derived. To replace the Jacobian of one summand only, attach it to that summand before summing.

Parameters:

jacobian (Jacobian)

Return type:

Residual

with_preconditioner(preconditioner)[source]#

This residual, with the given preconditioner.

It replaces the whole preconditioner of this residual. Its Jacobian is unchanged, including hand-written Jacobians of its summands.

Parameters:

preconditioner (Jacobian)

Return type:

Residual

copy(suffix)[source]#

Return a copy of this component that solves for new fields.

Each field the component writes an equation for is replaced by a new field named "<name><suffix>", with the same domain, element, unit and scale. Its test and trial functions, time derivative and previous values are replaced too. The new fields have their own UFL counts, so the copy can be summed with the original.

Each summand is copied as "<name><suffix>", together with the parameters and known coefficients it created. They keep their defaults, units and docs, under the new name. Everything else the component uses is shared with the original, such as fields it has no equation for and inputs given to its constructor.

The copy has the original’s forms with these replacements. It is not an instance of the original’s class, so attributes set by the original’s constructor are not available on it.

Parameters:

suffix (str) – Appended to the names of the copied fields, components, parameters and known coefficients, e.g. "_pos".

Raises:

ComponentError – If the suffix is empty.

Return type:

Residual

Example

The positive half-cell of a flow battery has the same equations as the negative one:

positive = negative.copy("_pos")
cell = negative + positive
class sumfem.symbolic.ResidualSum(components, name=None)[source]#

The sum of several residuals.

Sums are flattened, so (a + b) + c and a + (b + c) both have the summands (a, b, c). Use a + b or sum([a, b, c]) rather than constructing this class directly.

Parameters:
  • components (Sequence[_C]) – The components to sum.

  • name (str | None) – Name of the sum. Defaults to the summand names joined by +.

Raises:

ComponentError – If the same component appears twice.

residual()[source]#

Sum of the summands’ residuals.

Return type:

Form | ZeroBaseForm

class sumfem.symbolic.Jacobian(name)[source]#

Base class for a reusable bilinear form: a linearization or preconditioner.

Subclasses override jacobian() with a form in the test functions field.v and trial functions field.du. Jacobians sum with + into a JacobianSum, and a residual takes one as its Jacobian or preconditioner with Residual.with_jacobian() or Residual.with_preconditioner(), or from its hooks.

Parameters:

name (str) – Unique name of the component. It prefixes the names of parameters and known coefficients the component creates.

jacobian()[source]#

Return this component’s bilinear form.

Return type:

Form | ZeroBaseForm

property components: tuple[Jacobian, ...]#

The summands. A single component is its own summand.

property form: Form | ZeroBaseForm[source]#

The bilinear form, built on first access and then cached.

property inventory: Inventory[source]#

The named objects used by this component, validated.

property fields: tuple[Field, ...]#

Every field the form uses, in creation order.

property parameters: Mapping[str, Parameter]#

Parameters used by the form, by name.

property known_coefficients: Mapping[str, KnownCoefficient]#

Known coefficients used by the form, by name.

property domains: tuple[Domain, ...]#

Domains used by the form.

linearized(unknowns)[source]#

The form in a system with these unknowns.

Derived linearizations, of Residual.to_jacobian() without fields, are taken with respect to the unknowns.

Parameters:

unknowns (Sequence[Field])

Return type:

Form | ZeroBaseForm

replaced(mapping)[source]#

This Jacobian with terminals replaced, derivatives left unevaluated.

See replace().

Parameters:

mapping (Mapping[Any, Expr])

Return type:

Jacobian

class sumfem.symbolic.JacobianSum(components, name=None)[source]#

The sum of several Jacobians, flattened like a ResidualSum.

Parameters:
  • components (Sequence[_C]) – The components to sum.

  • name (str | None) – Name of the sum. Defaults to the summand names joined by +.

Raises:

ComponentError – If the same component appears twice.

jacobian()[source]#

Sum of the summands’ forms.

Return type:

Form | ZeroBaseForm

class sumfem.symbolic.Functional(name)[source]#

Base class for a reusable contribution to a scalar functional.

Subclasses override functional() with a form of rank zero, e.g. an energy, an objective or a quantity of interest. Functionals sum with + into a FunctionalSum. The form may be assembled, e.g. with assemble_scalar(), and to_residual() gives the residual of its stationary point.

Parameters:

name (str) – Unique name of the component. It prefixes the names of parameters and known coefficients the component creates.

functional()[source]#

Return this component’s contribution to the functional.

Return type:

Form

property components: tuple[Functional, ...]#

The summands. A single component is its own summand.

property form: Form[source]#

The functional, built on first access and then cached.

property inventory: Inventory[source]#

The named objects used by this component, validated.

property fields: tuple[Field, ...]#

Every field the functional uses, in creation order.

property parameters: Mapping[str, Parameter]#

Parameters used by the functional, by name.

property known_coefficients: Mapping[str, KnownCoefficient]#

Known coefficients used by the functional, by name.

property domains: tuple[Domain, ...]#

Domains used by the functional.

to_residual(fields=None, name=None)[source]#

The residual of the functional’s stationary point.

Its residual is sum_f derivative(J, f, f.v) over the given fields, so each field gets the equation of the functional’s variation in it.

Parameters:
  • fields (Sequence[Field] | None) – The fields to vary, e.g. the unknowns of one stage. Defaults to every field of the functional.

  • name (str | None) – Name of the residual. Defaults to the functional’s name.

Return type:

Residual

class sumfem.symbolic.FunctionalSum(components, name=None)[source]#

The sum of several functionals, flattened like a ResidualSum.

Parameters:
  • components (Sequence[_C]) – The components to sum.

  • name (str | None) – Name of the sum. Defaults to the summand names joined by +.

Raises:

ComponentError – If the same component appears twice.

functional()[source]#

Sum of the summands’ functionals.

Return type:

Form

Models from plain UFL#

class sumfem.symbolic.UFLResidual(name, residual, unknown, jacobian=None, preconditioner=None, *, names=None, domains=None, markers=None, terminals=None, previous=())[source]#

A residual based on plain UFL forms (with no data attached), as done in DOLFINx C++ API.

For example, Poisson’s equation:

u = ufl.Coefficient(V)
v = ufl.TestFunction(V)
F = kappa * ufl.inner(ufl.grad(u), ufl.grad(v)) * ufl.dx - f * v * ufl.dx
poisson = UFLResidual("poisson", F, u, names={"kappa": kappa, "f": f})

and a linear problem a(u, v) = L(v):

UFLResidual("linear", ufl.action(a, u) - L, u, jacobian=a)

Several unknowns are written on a ufl.MixedFunctionSpace, e.g. Stokes flow:

W = ufl.MixedFunctionSpace(V, Q)
u, p = ufl.Coefficient(V), ufl.Coefficient(Q)
v, q = ufl.TestFunctions(W)
F = (inner(grad(u), grad(v)) - p * div(v) - div(u) * q) * ufl.dx
stokes = UFLResidual("stokes", F, [u, p], names={"u": u, "p": p})

The constants and coefficients of the forms become parameters and known coefficients of this component, set when it is discretized, and the unknowns become its fields, unknowns.

Parameters:
  • name (str) – Name of the component. Its parameters and known coefficients are named "<name>.<variable>", e.g. "poisson.kappa".

  • residual (ufl.Form) – The residual, linear in test functions on the space of unknown, or on the sub-spaces of a mixed space.

  • unknown (ufl.Coefficient | Sequence[ufl.Coefficient]) – The coefficient to solve for, or one per sub-space of a mixed space, in its order.

  • jacobian (ufl.Form | None) – The linearization, bilinear on the same spaces. Derived from the residual if not given.

  • preconditioner (ufl.Form | None) – A form to precondition the Jacobian with, bilinear on the same spaces.

  • names (Mapping[str, Any] | None) – The variable name of the forms’ meshes, coefficients and constants. Needed for each coefficient and constant not given in terminals or previous, except the unknowns, which default to "u", or "u0", "u1", … Meshes default to "mesh0", "mesh1", …

  • domains (Mapping[ufl.Mesh, Domain] | None) – The domain of a mesh, e.g. from from_mesh(), or a Subdomain for a submesh. Other meshes take the domain of their terminals, or one created from their coordinate element.

  • markers (Mapping[str, Mapping[int, str]] | None) – The marker name of each integer subdomain id, by measure, e.g. {"ds": {1: "Dirichlet"}} for ds(1). A tuple of ids, ds((1, 2)), needs a name for each, and each id its own name.

  • terminals (Mapping[Any, Any] | None) – What replaces a coefficient or constant of the forms that is defined elsewhere: the field of an unknown, or any UFL expression of the same shape, e.g. the field of another component, {T: heat.field}, an expression of it, {b: -ufl.grad(T)}, or a time step, {dt: clock.dt}.

  • previous (ufl.Coefficient | Sequence[ufl.Coefficient] | Mapping[ufl.Coefficient, ufl.Coefficient | Sequence[ufl.Coefficient]]) – The unknown one, two, … steps back, e.g. (u_n, u_nn), for a time discretization written out, or, for several unknowns, those of each, e.g. {u: (u_n,)}. A single step may be given alone, u_n. They become previous() of its field.

Raises:

ComponentError – If a form has other arguments than described above, a coefficient, constant or subdomain id has no name, or a terminal or earlier step has another element or shape.

property field: Field#

The unknown, if there is one.

Raises:

ComponentError – If there are several, see unknowns.

property unknowns: tuple[Field, ...]#

The unknowns, in the order given.

residual()[source]#

Return this component’s contribution to the residual.

The form must be linear in test functions field.v and contain no trial functions. A contribution that is zero, e.g. for some inputs, is ufl.ZeroBaseForm((field.v,)): UFL drops the test function from a form whose terms vanish.

Return type:

Form

jacobian()[source]#

Return a hand-written linearization of residual(), or None.

A Jacobian, or a form with field.du as trial functions. Blocks for unknowns it does not mention are zero. With None, the Jacobian is derived automatically.

Return type:

Form | None

preconditioner()[source]#

Return this component’s contribution to a preconditioner, or None.

If any summand provides a preconditioner, summands without one contribute their Jacobian.

Return type:

Form | None

Systems and sequences#

class sumfem.symbolic.System(component, field_order=None, substitutions=mappingproxy({}), equation_scales=mappingproxy({}))[source]#

The equations of a residual, in a fixed block order.

A system is given by its component, the block order, substitutions and equation scales. Everything else is derived from these on first use. The unknowns are the fields the component writes equations for, its data are the other terminals of its forms, and its forms are blocked over a ufl.MixedFunctionSpace of the unknowns. build_system() creates systems, and also checks units and computes equation scales.

With one unknown the residual and Jacobian are single forms. With several unknowns the residual is a tuple with one form per unknown, and the Jacobian a tuple of rows with None for zero blocks. Each integral is weighted by the coordinate system of its domain, see coordinates.

component#

The residual.

Type:

sumfem.symbolic.components.Residual

field_order#

Block order, a permutation of the unknowns given as fields or names. None orders them by creation.

Type:

Sequence[sumfem.symbolic.terminals.Field | str] | None

substitutions#

Replacements in every form before the Jacobian is derived, such as those of a time-stepping scheme. Objects they introduce become part of the system.

Type:

Mapping[ufl.coefficient.Coefficient, ufl.core.expr.Expr]

equation_scales#

The size each equation is divided by, in SI base units, by the name of its unknown. Empty for dimensional equations.

Type:

Mapping[str, float]

Raises:

SystemBuildError – If the component has no equations, if field_order is not a permutation of the unknowns, if a hand-written Jacobian or preconditioner uses the trial function of a field that is not an unknown, if equation_scales does not give one positive scale per unknown, if a vector in space is an unknown on a domain whose coordinate system supports scalar unknowns only, or if a tensor-valued unknown lies on a domain whose coordinate system is not Cartesian.

Parameters:
property inventory: Inventory[source]#

The named objects of the component’s forms, after substitution.

property unknowns: tuple[Field, ...][source]#

The fields the component writes equations for, in block order.

property parameters: Mapping[str, Parameter]#

Parameters used by the system, by name.

property known_coefficients: Mapping[str, KnownCoefficient | Field][source]#

The data of the system, by name.

These are its known coefficients, and the fields it uses but does not solve for, such as fields solved for in another stage.

property domains: tuple[Domain, ...]#

Domains used by the system.

property test_functions: tuple[Argument, ...][source]#

The test function of each block, as used in the residual.

property trial_functions: tuple[Argument, ...][source]#

The trial function of each block, as used in the Jacobian.

property residual: Form | tuple[Form, ...]#

Residual form, or one form per unknown.

property jacobian: Form | tuple[tuple[Form | None, ...], ...]#

Jacobian form, or blocks J[i][j] = dF_i/du_j.

property preconditioner: Form | tuple[tuple[Form | None, ...], ...] | None#

Preconditioner form or blocks, or None.

property blocked: bool#

Whether the system has more than one unknown.

index(field)[source]#

Block index of an unknown, given as a field or by name.

Parameters:

field (Field | str)

Return type:

int

derivative(wrt)[source]#

Derivative of the residual with respect to a parameter or data.

The result is linear in a trial function on the space of wrt, giving the sensitivity forms dF_i/dm used by adjoint gradients.

Parameters:

wrt (Parameter | KnownCoefficient | Field | str) – A parameter or a known coefficient of this system, given as the object or by name.

Returns:

One form, or one form per unknown with None where the residual block does not depend on wrt.

Return type:

Form | tuple[Form | None, …] | None

sumfem.symbolic.build_system(component, field_order=None, substitutions=None, check_units=False, factorize_equations=False, time_scale=1.0)[source]#

Build the system of equations for a residual.

The component is not modified.

Parameters:
  • component (Residual) – A residual, or a sum of residuals. The unknowns are the fields it writes an equation for, with a term in field.v. Other fields used by the component are known coefficients of the system, as in a stage of a sequence.

  • field_order (Sequence[Field | str] | None) – Block order, a permutation of the unknowns, as objects or names. Defaults to field creation order.

  • substitutions (Mapping[Coefficient, Expr] | None) – Coefficients to replace in every form before the Jacobian is derived, such as {c.dot: (c - c.previous()) / dt} from a time-stepping scheme. Objects introduced by a substitution become part of the system.

  • check_units (bool) – Check that every equation is dimensionally consistent, see check_units().

  • factorize_equations (bool) – Make the equations dimensionless. Each equation is divided by its typical size, see equation_scales(), by dividing the test function field.v of its unknown. The unknowns keep their SI values. System.equation_scales records the sizes. This checks units too, since the sizes are only meaningful for consistent equations.

  • time_scale (float) – Reference time in seconds for time derivatives, used by the unit check and the equation sizes.

Raises:
  • SystemBuildError – If the component has no equations, if a hand-written Jacobian uses the trial function of a field that is not an unknown, if field_order is not a permutation of the unknowns, if a vector in space is an unknown on a domain whose coordinate system supports scalar unknowns only, or if a tensor-valued unknown lies on a domain whose coordinate system is not Cartesian.

  • UnitError – If units are checked, or equations factorized, and an equation is dimensionally inconsistent.

Return type:

System

class sumfem.symbolic.Sequential(stages, max_iterations=1, tol=None)[source]#

Solve stages one after another, each with the latest values of the others.

A model is a stage that solves for every field it writes an equation for, and a System one built with options of its own, e.g. a time-stepping scheme’s substitutions. The other fields a stage uses are data, taken from the stages that solve for them. A Transfer is a stage too, which writes data from one field to another, e.g. a velocity solved on one mesh into a known coefficient of another.

By default the sequence runs once, which is weak coupling. With a tolerance it is repeated until the solution stops changing, which is strong coupling.

A stage may itself be a sequence, which runs to its own tolerance whenever the outer sequence reaches it, e.g. the iterations of an enthalpy method inside a pass that then solves for the flow.

Parameters:
  • stages (Sequence[Stage | Sequential]) – The models, systems, transfers and nested sequences, in the order they run.

  • max_iterations (int) – Number of passes through the stages without a tolerance, or the maximum number with one.

  • tol (float | None) – Relative change of the unknowns of its stages between two passes below which strong coupling has converged.

Raises:
  • ValueError – For an empty sequence, a non-positive number of iterations, or a non-positive tolerance.

  • TypeError – If a stage is not a model, a system, a transfer or a sequence.

property stages: tuple[Residual | System | Transfer | Sequential, ...]#

The stages and nested sequences, in the order they run.

property max_iterations: int#

Number of passes, or maximum number of passes with a tolerance.

property tol: float | None#

Tolerance of the relative change for strong coupling, if any.

leaves()[source]#

The stages of this and the nested sequences, in order.

Return type:

tuple[Residual | System | Transfer, …]

map(function)[source]#

The same sequence, with each stage replaced by function(stage).

Parameters:

function (Callable[[Residual | System | Transfer], Residual | System | Transfer])

Return type:

Sequential

description()[source]#

The structure of the sequence by stage names, e.g. for metadata.

Return type:

dict[str, Any]

Time#

class sumfem.symbolic.Clock(domain, t0=0.0, dt=None, name='clock')[source]#

The current time t and the time step dt as parameters.

Both are Parameter objects, so models can use them in expressions, for instance a time-dependent source ufl.sin(clock.t).

Parameters:
  • domain (Domain) – The domain the parameters are defined on.

  • t0 (float) – Initial time.

  • dt (float | None) – Default time step size.

  • name (str) – Prefix of the parameter names, "<name>.t" and "<name>.dt".

property t: Parameter#

Current time.

property dt: Parameter#

Time step size.

sumfem.symbolic.Dt(expression)[source]#

The time derivative of an expression of fields.

For a field this is field.dot. For any other expression, such as the momentum H * u of the shallow water equations, it is a TimeDerivative, which a time-stepping scheme replaces by a difference of the whole expression over time steps. That keeps conserved quantities conserved, which the chain rule u * Dt(H) + H * Dt(u) would not.

Parameters:

expression (Expr)

Return type:

Expr

Boundary conditions#

class sumfem.symbolic.DirichletBC(field, marker, value, entity_type='facet')[source]#

A Dirichlet condition on a field, on the entities of a named marker.

The condition is symbolic: a Discretization turns it into a dolfinx.fem.DirichletBC on the mesh of the field’s domain.

Parameters:
field#

The field the condition applies to.

Type:

Field

marker#

Name of the marker on the field’s mesh, e.g. "Inlet", or several names.

Type:

str | tuple[str, …]

value#

The prescribed value. A UFL expression written with parameters, fields and the coordinates of the domain is evaluated at runtime, before every solve and every Newton iteration, so it follows time and other changing values. It is evaluated in SI base units. Any other Value is evaluated once, in the field’s unit.

Type:

Value | ufl.core.expr.Expr

entity_type#

The entities the marker refers to, facets by default.

Type:

EntityType

property markers: tuple[str, ...]#

The marker names, as a tuple.

Transfers#

class sumfem.symbolic.Transfer(name, source, target)[source]#

A stage that writes a field or known coefficient from another one.

Transfers couple by data, not by summing forms: for instance between non-matching meshes, where no form can hold both, see Interpolation. A transfer is a stage of a Sequential sequence, or is applied by hand: disc[transfer].apply(). It only describes what is transferred. How is up to its discrete counterpart: register one for a new kind of transfer, e.g. a projection, with @counterpart.register.

Parameters:
  • name (str) – Name of the transfer, unique among the stages it runs with.

  • source (Transferable) – The field or known coefficient to read.

  • target (Transferable) – The known coefficient or field to write, usually on another domain. A stage may solve for it, starting from the transferred values, e.g. a correction or an initial guess.

Raises:

ComponentError – If the source and the target differ in shape or in the dimension of their units, or are the same.

property name: str#

Name of the transfer.

property source: Field | KnownCoefficient#

The field or known coefficient to read.

property target: Field | KnownCoefficient#

The known coefficient or field to write.

property target_domain: Domain#

The domain of the target.

class sumfem.symbolic.Assignment(name, target, expression)[source]#

Write an expression of fields into the target, point by point.

The expression is evaluated at the target’s interpolation points, so it may only use terminals on the target’s domain. It may use the target itself, e.g. the update g + lambda (T - T_m) of a liquid fraction g, clipped to [0, 1], between solves for the temperature T.

Parameters:
  • name (str) – See Transfer.

  • target (Transferable) – See Transfer.

  • expression (ufl.core.expr.Expr) – The expression, of the target’s shape. Values are in SI base units, as every symbolic expression’s.

Raises:

ComponentError – If the expression and the target differ in shape.

property source: Expr#

The expression written into the target.

class sumfem.symbolic.Interpolation(name, source, target, markers=())[source]#

Interpolate into the target, from a source on any mesh.

The meshes need not match or be nested. The discrete layer locates the target’s interpolation points in the source mesh once, and evaluates the source there at every transfer, see Interpolation.

Parameters:
  • name (str) – See Transfer.

  • source (Transferable) – See Transfer.

  • target (Transferable) – See Transfer.

  • markers (Sequence[str]) – Cell markers of the target’s domain to interpolate on. Empty for all its cells.

property markers: tuple[str, ...]#

Cell markers of the target’s domain to interpolate on.

sumfem.symbolic.transfer.Transferable = sumfem.symbolic.terminals.Field | sumfem.symbolic.terminals.KnownCoefficient#

The terminals a transfer reads from and writes to.

Units and dimensional analysis#

sumfem.symbolic.check_units(system, time_scale=1.0)[source]#

Check that every term of every equation has the same dimension.

Parameters:
  • system (System) – The system.

  • time_scale (float) – Reference time in seconds, for time derivatives.

Raises:

UnitError – Naming the first dimensionally inconsistent equation.

Return type:

None

sumfem.symbolic.equation_dimensions(system, time_scale=1.0)[source]#

The dimension of each equation of a system, by field name.

Parameters:
  • system (System) – The system.

  • time_scale (float) – Reference time in seconds, for time derivatives.

Raises:

UnitError – If an equation is dimensionally inconsistent.

Return type:

dict[str, Expr]

sumfem.symbolic.equation_scales(system, time_scale=1.0)[source]#

The typical size of each equation of a system, by field name.

Each term of an equation gets a typical size from the scales of the quantities in it. The size of the equation is that of its largest term, in SI base units. Dividing the equation by it makes its dominant terms of order one: the normalization by the dominant term of Habera and Zilian, 2026, Section 3.5.

Parameters:
  • system (System) – The system.

  • time_scale (float) – Reference time in seconds, for time derivatives.

Raises:

UnitError – If an equation is dimensionally inconsistent.

Return type:

dict[str, float]

sumfem.symbolic.pi_groups(system, time_scale=1.0, repeating=())[source]#

The dimensionless groups of a system, by Buckingham Pi analysis.

Any product of powers of dimensionless groups is one too, so the groups are not unique (Habera and Zilian, 2026, Section 2.3). By default, they are a basis of the null space of the dimension matrix, whose form depends on the order in which the quantities appear in the forms (Section 4.1 of the paper). With repeating quantities, they are those of the method of repeating variables (Çengel and Cimbala, Fluid Mechanics: Fundamentals and Applications, 2nd ed., McGraw-Hill, 2010, Section 7.4): one group for every other quantity, that quantity times powers of the repeating ones.

Parameters:
  • system (System) – The system.

  • time_scale (float) – Reference time in seconds, for time derivatives.

  • repeating (Sequence[Field | Domain | Parameter | KnownCoefficient | str]) – The quantities to build every group from, given by the objects whose scales the analysis uses: a Domain for its length_scale, a Field for its scale, a Parameter or KnownCoefficient for its value, or a symbol, such as "t_ref" for time_scale. Choose one for each base dimension of the problem, e.g. the length, the scale of the unknown and a material coefficient: they must be dimensionally independent, and their dimensions must make up those of every other quantity.

Raises:

ComponentError – If a repeating quantity is not one of the system, or the repeating quantities are not dimensionally independent, or do not make up the dimensions of the others.

Return type:

list[PiGroup]

Example

In heat conduction -div(kappa grad(T)) = q on domain, the length scale of the domain, the scale of T and the conductivity make up the dimensions of the source, in which mass and time only appear together, as kg/s^3. They give one group, of the source:

pi_groups(system, repeating=[domain, T, kappa])
# [PiGroup(expression=L_domain**2*q/(T_ref*kappa), value=...)]
class sumfem.symbolic.PiGroup(expression, value)[source]#

A dimensionless group of the quantities of a system.

Parameters:
expression#

The group as a product of powers of quantity symbols.

Type:

sympy.core.expr.Expr

value#

Its value for the scales of the quantities.

Type:

float

exception sumfem.symbolic.UnitError[source]#

Raised when an equation is dimensionally inconsistent.

sumfem.symbolic.constants.BOLTZMANN: Expr = 1380649*joule/(100000000000000000000000000000*kelvin)#

The Boltzmann constant k_B = 1.380649e-23 J/K, exact by the definition of the SI, as a sympy quantity. boltzmann_constant() gives it on a domain, for forms.

sumfem.symbolic.constants.FARADAY: Expr = 120606665154137523*coulomb/(1250000000000*mole)#

Faraday’s constant F = N_A e, about 96485.33 C/mol, exact by the definition of the SI, as a sympy quantity.

sumfem.symbolic.constants.GAS_CONSTANT: Expr = 207861565453831*joule/(25000000000000*kelvin*mole)#

The gas constant R = N_A k_B, about 8.314 J/(mol K), exact by the definition of the SI, as a sympy quantity.

sumfem.symbolic.boltzmann_constant(domain)[source]#

The Boltzmann constant on a domain, a parameter in J/K.

The parameter is named "<domain>.k_B", so that a model over several domains has one of each, and has BOLTZMANN as default. The same parameter is returned for every call with a domain.

Parameters:

domain (Domain) – The domain of the forms that use it.

Return type:

Parameter

sumfem.symbolic.si.CONCENTRATION = mole/meter**3#

Unit of concentrations.

sumfem.symbolic.si.DENSITY = kilogram/meter**3#

Unit of densities.

sumfem.symbolic.si.DIFFUSIVITY = meter**2/second#

Unit of diffusivities.

sumfem.symbolic.si.PERMEABILITY = meter**2#

Unit of permeabilities.

sumfem.symbolic.si.VISCOSITY = pascal*second#

Unit of dynamic viscosities.

Errors#

exception sumfem.symbolic.ComponentError[source]#

Raised when a component, or a sum of components, is defined inconsistently.

exception sumfem.symbolic.SystemBuildError[source]#

Raised when a residual cannot be turned into a system of equations.