The symbolic layer#
The symbolic description of variational problems, without mesh data.
Domain: a symbolic description of a type of mesh, with named markers.Cartesian,Cylindrical,SphericalandWeighted: coordinate systems of domains, which weight their integrals, e.g. for axisymmetric or radially symmetric bodies.Field,Parameter,KnownCoefficient: the named objects residuals and functionals are written with, with units.Residual: a reusable contribution to a residual, summed with+into aResidualSum.Functional: a reusable contribution to a scalar functional, summed into aFunctionalSum, whose variation is a residual.UFLResidual: a residual from plain UFL forms, as written for DOLFINx.build_system(): turns a residual into blocked residual and Jacobian forms, optionally in dimensionless form.DirichletBC: boundary conditions by marker name.check_units(),equation_scales()andpi_groups(): dimensional analysis withufl_units, and physical constants such asBOLTZMANN,FARADAYandGAS_CONSTANT, andboltzmann_constant()for forms.
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
Domainare 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.
Cylindricalfor an axisymmetric body. Defaults toCartesian.
- 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.
- property coordinates: CoordinateSystem#
The coordinate system, which weights the integrals.
- 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:
- 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.
- 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 shortcutsdomain.dx("Electrode")anddomain.ds("Inlet"). Entity types that coincide share their markers, seemarker_ids(): on a triangle meshdr("A")anddP("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:
- dx(*markers, degree=None, metadata=None)#
Cell measure over the domain, or over the named cell markers.
- Parameters:
- Return type:
- ds(*markers, degree=None, metadata=None)#
Exterior facet measure, optionally restricted to named facet markers.
- Parameters:
- Return type:
- dS(*markers, degree=None, metadata=None)#
Interior facet measure, optionally restricted to named facet markers.
- Parameters:
- Return type:
- dr(*markers, degree=None, metadata=None)#
Ridge measure (codimension 2), optionally restricted to named ridges.
- Parameters:
- Return type:
- dP(*markers, degree=None, metadata=None)#
Vertex measure, optionally restricted to named vertex markers.
- Parameters:
- Return type:
- 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.
- interface(first, second, marker, degree=None, metadata=None)[source]#
Interior facet measure of an interface between two subdomains.
Its
"+"side is always infirstand its"-"side insecond, so the functions of each subdomain can be restricted to their own side, e.g.u_0("+")andu_1("-")for an exchange flux between two materials.- Parameters:
- Raises:
ComponentError – If a subdomain is not a subdomain of cells of this domain.
- Return type:
- interface_sides(marker)[source]#
The subdomains and facet marker of an interface measure’s marker.
See
interface().Noneif the marker is not an interface.
- interfaces_of(measure)[source]#
The interfaces an interior facet measure of this domain covers.
See
interface()andinterface_sides().
- 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.
dxintegrates over the subdomain,dsover its boundary anddSover its interior facets. Markers are named after the parent’s: those ofdxare parent markers of the subdomain’s dimension, and those ofdsanddSparent 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 - 1for 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 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 fordsanddS, and vertex markers fordr.
- dx(*markers, degree=None, metadata=None)#
Cell measure of this domain, optionally restricted to named parts.
- Parameters:
- Return type:
- ds(*markers, degree=None, metadata=None)#
Measure of this domain’s boundary, optionally of named parts of it.
- Parameters:
- Return type:
- dS(*markers, degree=None, metadata=None)#
Measure of this domain’s interior facets, optionally of named ones.
- Parameters:
- Return type:
- dr(*markers, degree=None, metadata=None)#
Ridge measure of this domain, optionally restricted to named ridges.
- Parameters:
- Return type:
- dP(*markers, degree=None, metadata=None)#
Vertex measure of this domain, optionally restricted to named vertices.
- Parameters:
- Return type:
- 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, seeDomain.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:
- 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), seeCylindrical.lift(), and say whether it supports vector-valued unknowns with the class attributevectors. Without them, integrands are kept as they are and only scalar unknowns are supported, seelift()andsupports_vectors().- check(gdim)[source]#
Check that a domain of geometric dimension
gdimcan 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.
- 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, withx[1] = zon a 2D mesh. On a 1D mesh inrthe 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 swirlu_thetaas its last component. Fields do not depend ontheta.- gradient(f, x)[source]#
The gradient of a scalar or a vector in
(r, z, theta).- Raises:
ComponentError – For other shapes.
- Parameters:
- Return type:
- 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.- 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:
- 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-anglethetaaround its axis, in the distancex[0]from its apex. Integrands are kept as they are, so only scalar unknowns are supported.- weight_of#
The weight, as a function of the spatial coordinate.
- Type:
Callable[[ufl.core.expr.Expr], ufl.core.expr.Expr | float]
- 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 aDomainare 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 valuektime steps back.
Models that write terms with the same
field.vcontribute 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.
Nonemeans 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=Falsewith an element mapped by a Piola transformation.
- property element: AbstractFiniteElement#
Finite element of the field.
- 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 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.
- 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_unitsquantity, 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.
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 tounit. A scalar sets every component of a vector or tensor parameter.unit (Unit | None) – Unit of the value, a sympy unit expression.
Nonemeans 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:
- property default: ndarray[tuple[Any, ...], dtype[Any]] | None#
Default value, or
Noneif the value must be set explicitly.
- 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_unitsquantity, 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.
Nonemeans 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 element: AbstractFiniteElement#
Finite element of the data.
- sumfem.symbolic.as_expr(value)[source]#
Convert a component input to a UFL expression.
UFL expressions, including a
Field,ParameterandKnownCoefficient, are returned unchanged. Numbers and nested sequences of numbers become UFL literals.
- 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:
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>".
- 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.
- 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:
- 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
valueis given, it is converted withas_expr(). Passing aFieldcouples this component to the field. Otherwise a placeholder named"<component>.<name>"is created: aKnownCoefficientwhenelementis given, else aParameterof the givenshape.unitapplies to either,scaleto a known coefficient anddefaultto a parameter.- Parameters:
name (str)
value (Expr | Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str] | None)
domain (Domain)
element (AbstractFiniteElement | str | tuple | None)
default (Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str] | None)
unit (Expr | None)
scale (float)
doc (str)
- Return type:
- 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(), orNonefor the parameter.domain (Domain) – The domain 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:
- 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 namedname, 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
unitor a quantity with units;Nonefor a parameter without a default.domain (Domain) – The domain 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:
- 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 functionsfield.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.vand contain no trial functions. A contribution that is zero, e.g. for some inputs, isufl.ZeroBaseForm((field.v,)): UFL drops the test function from a form whose terms vanish.- Return type:
- jacobian()[source]#
Return a hand-written linearization of
residual(), orNone.A
Jacobian, or a form withfield.duas trial functions. Blocks for unknowns it does not mention are zero. WithNone, the Jacobian is derived automatically.
- preconditioner()[source]#
Return this component’s contribution to a preconditioner, or
None.If any summand provides a preconditioner, summands without one contribute their Jacobian.
- 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 equations: tuple[Field, ...]#
Fields the component writes equation terms for, in creation order.
- property known_coefficients: Mapping[str, KnownCoefficient]#
Known coefficients used by the component, by name.
- 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.
- 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.
- 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.
- 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:
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) + canda + (b + c)both have the summands(a, b, c). Usea + borsum([a, b, c])rather than constructing this class directly.- Parameters:
- Raises:
ComponentError – If the same component appears twice.
- 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 functionsfield.vand trial functionsfield.du. Jacobians sum with+into aJacobianSum, and a residual takes one as its Jacobian or preconditioner withResidual.with_jacobian()orResidual.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.
- property form: Form | ZeroBaseForm[source]#
The bilinear form, built on first access and then cached.
- property known_coefficients: Mapping[str, KnownCoefficient]#
Known coefficients used by the form, by name.
- 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:
- Return type:
- class sumfem.symbolic.JacobianSum(components, name=None)[source]#
The sum of several Jacobians, flattened like a
ResidualSum.- Parameters:
- Raises:
ComponentError – If the same component appears twice.
- 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 aFunctionalSum. The form may be assembled, e.g. withassemble_scalar(), andto_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.
- property components: tuple[Functional, ...]#
The summands. A single component is its own summand.
- property known_coefficients: Mapping[str, KnownCoefficient]#
Known coefficients used by the functional, by name.
- class sumfem.symbolic.FunctionalSum(components, name=None)[source]#
The sum of several functionals, flattened like a
ResidualSum.- Parameters:
- Raises:
ComponentError – If the same component appears twice.
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
terminalsorprevious, 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 aSubdomainfor a submesh. Other meshes take the domain of theirterminals, 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"}}fords(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 becomeprevious()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.
- residual()[source]#
Return this component’s contribution to the residual.
The form must be linear in test functions
field.vand contain no trial functions. A contribution that is zero, e.g. for some inputs, isufl.ZeroBaseForm((field.v,)): UFL drops the test function from a form whose terms vanish.- Return type:
- jacobian()[source]#
Return a hand-written linearization of
residual(), orNone.A
Jacobian, or a form withfield.duas trial functions. Blocks for unknowns it does not mention are zero. WithNone, the Jacobian is derived automatically.- 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.MixedFunctionSpaceof 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
Nonefor zero blocks. Each integral is weighted by the coordinate system of its domain, seecoordinates.- component#
The residual.
- field_order#
Block order, a permutation of the unknowns given as fields or names.
Noneorders 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:
- equation_scales#
The size each equation is divided by, in SI base units, by the name of its unknown. Empty for dimensional equations.
- Raises:
SystemBuildError – If the component has no equations, if
field_orderis 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, ifequation_scalesdoes 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 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 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 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.
- 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 functionfield.vof its unknown. The unknowns keep their SI values.System.equation_scalesrecords 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_orderis 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:
- 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
Systemone 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. ATransferis 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.
Time#
- class sumfem.symbolic.Clock(domain, t0=0.0, dt=None, name='clock')[source]#
The current time
tand the time stepdtas parameters.Both are
Parameterobjects, so models can use them in expressions, for instance a time-dependent sourceufl.sin(clock.t).- Parameters:
- 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 momentumH * uof the shallow water equations, it is aTimeDerivative, which a time-stepping scheme replaces by a difference of the whole expression over time steps. That keeps conserved quantities conserved, which the chain ruleu * Dt(H) + H * Dt(u)would not.
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
Discretizationturns it into adolfinx.fem.DirichletBCon the mesh of the field’s domain.- Parameters:
field (Field)
value (Value | ufl.core.expr.Expr)
entity_type (EntityType)
- marker#
Name of the marker on the field’s mesh, e.g.
"Inlet", or several names.
- 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
Valueis 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
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 aSequentialsequence, 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 source: Field | KnownCoefficient#
The field or known coefficient to read.
- property target: Field | KnownCoefficient#
The known coefficient or field to write.
- 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 fractiong, clipped to[0, 1], between solves for the temperatureT.- Parameters:
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.
- 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:
- 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.
- sumfem.symbolic.equation_dimensions(system, time_scale=1.0)[source]#
The dimension of each equation of a system, by field name.
- 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.
- 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
repeatingquantities, 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
Domainfor itslength_scale, aFieldfor itsscale, aParameterorKnownCoefficientfor its value, or a symbol, such as"t_ref"fortime_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:
Example
In heat conduction
-div(kappa grad(T)) = qondomain, the length scale of the domain, the scale ofTand 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.
- expression#
The group as a product of powers of quantity symbols.
- Type:
- 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 hasBOLTZMANNas default. The same parameter is returned for every call with a domain.
- 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.