pyoomph.generic.codegen module
- class pyoomph.generic.codegen.BaseEquations(*args: Any, **kwargs: Any)[source]
Bases:
EquationsThese are the parent class for both
ODEEquationsandEquations. You will rarely have to use this base class directly.- add_dweak_dt(a, b, *, dimensional_dx=False, lagrangian=False, coordsys=None, destination=None, scheme='BDF1', apply_on_others=True)[source]
Adds d/dt of the weak contribution
(a, b), i.e. the time derivative of the whole integral, so that the change of the integration domain of a moving mesh is taken into account as well.- Parameters:
apply_on_others (
bool) – Whether the history terms also take the normal, the Eulerian element sizes and the Eulerian spatial derivatives in grad/div from the mesh of the corresponding history step. Defaults to True, since each history term belongs to the configuration the element had then. Has no effect unless the mesh moves.
- add_functional_minimization(F, with_respect_to=None, *, dimensional_dx=False, dimensional_testfunctions=True, lagrangian=False, coordsys=None, destination=None)[source]
Adds the weak form of the functional minimization of W=integral(F dOmega) to the equations.
- Parameters:
F (
Expression|GiNaC_GlobalParam|int|float) – Integrand of the functional.with_respect_to (
Expression|list[Expression] |None) – Optionally only derive with respect to all shape functions appearing in the listed expressions. Defaults to None, meaning all shape functions in F.dimensional_dx (
bool) – Consider spatial scaling in the weak form integral. Defaults to False.dimensional_testfunctions (
bool) – Expand by dimensional testfunctions. Defaults to True.lagrangian (
bool) – Weak formulation is integrated over the Lagrangian domain. Defaults to False.coordsys (
CustomCoordinateSystem|None) – Optional coordinate system. Defaults to the equations’ coordinate system, then parent equations and eventually the problem coordinate system. Defaults to None. The former namecoordinate_systemis deprecated, but still accepted.destination (
str|None) – Residual destination identifier. Defaults to None.
- Returns:
Returns self for chaining.
- Return type:
- add_interior_facet_residual(expr, *, destination=None)[source]
Same as
add_residual(), but the added residuals are evaluated and considered at the interior facet domain. This is only used for DG methods and requires the propertyrequires_interior_facet_termsto be set in the constructor of the equations.- Parameters:
expr (
Expression|GiNaC_GlobalParam|int|float) – Expression to add to the residualsdestination (
str|None) – Optional residual destination for multiple residuals. Defaults toNone.
- add_local_function(name, expr)[source]
Adds a local function for the output. This are not degrees of freedom but only calculated node-wise on output. The same can be achieved by using LocalExpressions(…) instead.
- Parameters:
name (
str) – name of the local expressionsexpr (
Expression|GiNaC_GlobalParam|int|float|Callable[[],Expression|GiNaC_GlobalParam|int|float]) – Expression to be evaluated on the nodes on output.
- Returns:
If the expression is a vector, it just returns the vector component names and 0. For a tensor, it returns the tensor components and the dimension of the tensor.
- Return type:
tuple[list[str],int]
- add_residual(expr, *, destination=None)[source]
Adds a residual contribution to this equations.
- Parameters:
expr (
Expression|GiNaC_GlobalParam|int|float|str) – The expression or number to be added as a residual.destination (
str|None) – The destination of the residual. Defaults toNone, can be used to specify different residuals.
- add_weak(a, b, *, dimensional_dx=False, lagrangian=False, coordsys=None, destination=None)[source]
Adds the weak contribution
(a, b)(i.e. the integral ofatimes the test functionb) to the residuals.- Parameters:
a (
Expression|GiNaC_GlobalParam|int|float) – Expression to be tested.b (
str|Expression|GiNaC_GlobalParam|int|float) – Test function, either passed directly or as the name of the field to test.dimensional_dx (
bool) – Whether to use the dimensional (as opposed to the nondimensional) integration measure.lagrangian (
bool) – Whether to integrate over the Lagrangian (undeformed) instead of the Eulerian domain.coordsys (
CustomCoordinateSystem|None) – Optional coordinate system override for the integration. The former namecoordinate_systemis deprecated, but still accepted.destination (
str|None) – Optional residual destination for multiple residuals. Defaults toNone.
- Returns:
self, to allow chaining further
add_weak/add_residualcalls.
- after_transient_solve()[source]
Called once per accepted timestep, at the end of
solve()with a time step.Unlike
after_newton_solve(), this does not fire for stationary solves, for arclength continuation steps, for the Newton solves a temporal-adaptivity retry discards, or for the intermediate solves of spatial adaptation. Anything that must advance exactly once per step in time - tracer particle advection, say - belongs here.
- before_assigning_equations_postorder(mesh)[source]
This function is called whenever the equations are numbered. The equation tree is traversed and this function is called after applying it on all of the children of this domain.
Override this method to e.g. pin redundant (overconstraining) Lagrange multipliers with the
InterfaceEquations.pin_redundant_lagrange_multipliers()method.- Parameters:
mesh (AnyMesh) – The mesh corresponding to the this domain.
- before_assigning_equations_preorder(mesh)[source]
This function is called whenever the equations are numbered. The equation tree is traversed and this function is called before applying it on all of the children of this domain.
Override this method to e.g. pin redundant (overconstraining) Lagrange multipliers with the
InterfaceEquations.pin_redundant_lagrange_multipliers()method.- Parameters:
mesh (AnyMesh) – The mesh corresponding to the this domain.
- define_fields()[source]
Inherit and specify to define fields (dependent variables), either by using
ODEEquations.define_ode_variable()(ODEs inherited fromODEEquations) orEquations.define_scalar_field()/Equations.define_vector_field()(PDEs inherited fromEquations)
- define_residuals()[source]
Inherit and specify to define residuals for the equations, using
add_residual()oradd_weak()Any returned expression will be also added to the residuals- Return type:
Expression|None
- get_azimuthal_r0_info()[source]
Returns a dict [0,1,2]-> Set[str] with the names of the fields that are pinned at r=0 for azimuthal symmetry. Entry 0 contains the names of the fields that are pinned to zero at r=0 for normal (axisymmetric solves). This pinning is strongly enforced. Entry 1 contains the names of the fields that are pinned at r=0 for azimuthal eigensolves with m=1. This pinning is implemented by modifying the eigenproblem matrices. Entry 2 contains the names of the fields that are pinned at r=0 for azimuthal eigensolves with m>=2. This pinning is implemented by modifying the eigenproblem matrices.
- get_element_dimension()[source]
Returns the element dimension of the domain where the equations are defined.
- get_nodal_dimension()[source]
Returns the nodal (Eulerian) dimension of the domain where the equations are defined.
- get_normal()[source]
Returns the normal of this domain. This is only possible if the domain is either a boundary or a bulk domain with co-dimension 1.
Note that
var("normal")is essentially the same.
- get_parent_domain()[source]
If this domain is a subdomain of another domain, i.e. a boundary, this function returns the parent domain. Otherwise, it returns None.
- Return type:
FiniteElementCodeGenerator|None
- requires_interior_facet_terms: bool
Set this to true if you require internal facet contributions for DG methods, at best in the constructor
- set_facet_recovery(fieldname, expr, at_internal_facets=False)[source]
Defines how a discontinuous (
DLorD0) field of this domain is filled on elements that are created by a spatial adaptation or a remeshing and therefore receive no values from the old mesh.This is meant for fields on the interior-facet skeleton (
"_internal_facets_"): when the bulk is refined, facets appear inside the former elements, and no amount of interpolation from the old skeleton can produce a value there - the old skeleton has nothing at that position. For an HDG-style trace the right answer comes from the bulk instead, e.g.:class MyFacetEqs(Equations): def define_fields(self): self.define_scalar_field("lam","DL") def define_residuals(self): lam,lamtest=var_and_test("lam") self.add_residual(weak(lam-avg(var("u")),lamtest)) self.set_facet_recovery("lam",avg(var("u")))
Without it, such facets keep the zero they were allocated with (and a one-time warning is printed); they are corrected by the next solve, which is why zero remains the default.
The expression is evaluated on the new element, i.e. on the CURRENT state only, and least-squares fitted onto the field’s own space (for
D0: averaged). The result is written to every stored time level, so that a facet which just came into existence does not produce a spurious time derivative. Elements that DO get values from the old mesh are untouched by it, and so are fields without a recovery expression - if any field of the domain lacks one, the element still counts as unrestored and shows up inmesh.get_discontinuous_unrestored_elements().- Parameters:
fieldname (
str) – name of theDL/D0field to recover.expr (
Expression|GiNaC_GlobalParam|int|float) – expression evaluated on the new element, e.g.avg(var("u")).at_internal_facets (
bool) – register this on the"_internal_facets_"child of this domain instead of on this domain itself, so that a bulk equation class can declare the recovery of a skeleton field it declared withat_internal_facets=True. ReturnsNonein that case, since the local function is only created on replay.
- class pyoomph.generic.codegen.EquationTree(eqs=None, parent=None)[source]
Bases:
EquationsOne domain of the equation tree, and at the same time the equation object of that domain.
Being an Equations is what lets a node carry the state its equations share - scalings, fields defined by substitution, initial and Dirichlet conditions - and be the single object the code generator is given, without a separate combining equation class in between.
- get_compilation_flags(problem)[source]
The code generation flags in effect on this domain.
Any
EquationCompilationFlagsadded here wins, all settings it leaves atNoneare inherited from the parent domain and eventually fromequation_compilation_flags.- Return type:
- get_equation_of_type(typ, *, exact_type=False, always_as_list=False)[source]
Search this domain’s equations. The node itself is never a candidate.
- Return type:
list[BaseEquations] |BaseEquations|None
- with_exception_info: bool = False
Nodes are created in bulk (one per path component, per clone, per glob match) and BaseEquations.__new__ walks the interpreter stack for each one, which reads source files.
- class pyoomph.generic.codegen.Equations(*args: Any, **kwargs: Any)[source]
Bases:
BaseEquationsEquations to be solved on a domain, i.e. including spatial coordinates. Add unknown fields by overriding the
define_fields()method and residuals by overriding thedefine_residuals()method.See
BaseEquationsfor further methods.- activate_coordinates_as_dofs(coordinate_space=None)[source]
Activates the coordinates as degrees of freedom (dofs) for a moving mesh. You must then add residuals in the define_residuals method for the field “mesh”, e.g.
- def define_residuals(self):
x,xtest=var_and_test(“mesh”) X=var(“lagrangian”) self.add_weak(grad(x-X,lagrangian=True),grad(xtest,lagrangian=True),lagrangian=True)
for a Laplace-smoothed mesh
- Parameters:
coordinate_space (
str|None) – The coordinate space to be set as the coordinate space for the element. Valid options are “C2TB”, “C2”, “C1TB”, or “C1”. If not provided, the coordinate space will not be set.- Raises:
ValueError – If the provided coordinate space is not one of the valid options.
- Return type:
None- Returns:
None
- define_scalar_field(name, space, scale=None, testscale=None, discontinuous_refinement_exponent=None, allow_scales_with_fields=False, at_internal_facets=False)[source]
Define a scalar field on this domain. Must be called within the specified implementation of the method
define_fields().- Parameters:
name (
str|list[str]) – The name of the vector field.space (
Literal['C1','C1TB','C2','C2TB','D1','D1TB','D2','D2TB','DL','D0']) – The finite element space on which the vector field is defined.scale (
Expression|GiNaC_GlobalParam|int|float|str|None) – The scale for the vector field for nondimensionalization. Defaults to None.testscale (
Expression|GiNaC_GlobalParam|int|float|str|None) – The scale for the test function of the vector field for nondimensionalization. Defaults to None.discontinuous_refinement_exponent (
float|None) – The exponent for the discontinuous refinement. Defaults to None.allow_scales_with_fields (
bool) – Whether to allow scales/testscales with fields included. Defaults to False.at_internal_facets (
bool) – Define the field on the"_internal_facets_"skeleton of this domain instead of on this domain itself. The space must then be discontinuous (D0,DL,D1,D1TB,D2,D2TB) and the domain must have a skeleton, i.e.self.requires_interior_facet_termsmust be set in__init__. Defaults to False.
- define_vector_field(name, space, dim=None, scale=None, testscale=None, allow_scales_with_fields=False, at_internal_facets=False)[source]
Define a vector field on this domain. Must be called within the specified implementation of the method
define_fields().- Parameters:
name (
str) – The name of the vector field.space (
Literal['C1','C1TB','C2','C2TB','D1','D1TB','D2','D2TB','DL','D0']) – The finite element space on which the vector field is defined.dim (
int|None) – The dimension of the vector field. If not provided, it defaults to the nodal dimension.scale (
Expression|GiNaC_GlobalParam|int|float|None) – The scale for the vector field for nondimensionalization. Defaults to None.testscale (
Expression|GiNaC_GlobalParam|int|float|None) – The scale for the test function of the vector field for nondimensionalization. Defaults to None.at_internal_facets (
bool) – Define the field on the"_internal_facets_"skeleton of this domain instead of on this domain itself. Seedefine_scalar_field(). Defaults to False.
- get_opposite_parent_domain(raise_error_if_none=True)[source]
Returns the bulk domain at the opposite side of this interface.
- Parameters:
raise_error_if_none (
bool) – If there is no opposite side set, raise an error. Otherwise, justNoneis returned.- Return type:
FiniteElementCodeGenerator|None- Returns:
The bulk domain at the opposite side.
- get_opposite_side_of_interface(raise_error_if_none=True)[source]
Returns the interface domain at the opposite side of this interface.
- Parameters:
raise_error_if_none (
bool) – If there is no opposite side set, raise an error. Otherwise, justNoneis returned.- Return type:
FiniteElementCodeGenerator|None- Returns:
The interface domain at the opposite side.
- get_weak_dirichlet_terms_for_DG(fieldname, value)[source]
Returns the weak Dirichlet terms for a discontinuous Galerkin (DG) formulation. When using a
DirichletBCwithprefer_weak_for_DG, this method is called. If it returns notNone, theDirichletBCis not enforced strongly, but on the basis of the given interface residuals.- Parameters:
fieldname (
str) – Name of the field for which the weak Dirichlet terms are to be returned.value (
Expression|GiNaC_GlobalParam|int|float) – The desired Dirichlet condition.
- Return type:
Expression|GiNaC_GlobalParam|int|float|None
- class pyoomph.generic.codegen.InterfaceEquations(*args: Any, **kwargs: Any)[source]
Bases:
EquationsSame as normal
Equationsbut with some extra functions for equations defined on interfaces.- get_opposite_parent_equations(of_type=None)[source]
Returns the
Equationsin the parent bulk domain at the opposite side of this interface. When setting the attributerequired_opposite_parent_type,of_typecan be omitted to get the expected parent equations.This method is useful to e.g. get the mass density from a Navier-Stokes equation in the opposite bulk domain, e.g. for mass transfer processes at the interface.
- Parameters:
of_type (
type[Equations] |None) – The type of the equations to be returned. If not provided, therequired_opposite_parent_typehas to be set.
- get_parent_equations(of_type=None)[source]
Returns the
Equationsin the parent bulk domain of a given type. When setting the attributerequired_parent_type,of_typecan be omitted to get the expected parent equations.This method is useful to e.g. get the mass density from a Navier-Stokes equation in the bulk domain, e.g. for mass transfer processes at the interface.
- Parameters:
of_type (
type[Equations] |None) – The type of the equations to be returned. If not provided, therequired_parent_typehas to be set.
- pin_redundant_lagrange_multipliers(mesh, lagr, depvars, opposite_interface=[])[source]
Allows to pin redundant (overconstraining) Lagrange multipliers. A field of Lagrange multipliers usually enforces some constraint depending on
depvars(and poentially degrees at theopposite_interface). If all these degrres are pinned, the Lagrange multiplierlagris pinned and set to zero as well.- Parameters:
mesh (
InterfaceMesh) – The current mesh must be passedlagr (
str|list[str] |tuple[str,...]) – Name of the Lagrange multiplier field to be automatically pinned if necessary. Several names may be given, e.g. the components of a vector-valued multiplier.depvars (
str|list[str] |tuple[str,...]) – Single or multiple variables that occur in the constraint.opposite_interface (
str|list[str] |tuple[str,...]) – Optional dependencies on the opposite side of the interface.
- class pyoomph.generic.codegen.ODEEquations(*args: Any, **kwargs: Any)[source]
Bases:
BaseEquationsClass representing a set of ordinary differential equations (ODEs). Add unknowns by overriding the
define_fields()method and residuals by overriding thedefine_residuals()method.See
BaseEquationsfor further methods.- __init__()[source]
Call this method to initialize the ODE equations, e.g. usually you pass parameters here which can be then used in the equations within the define_residuals method. Also, you must call super().__init__() in the derived class before anything else.
- define_ode_variable(*names, scale=None, testscale=None)[source]
Defines the ODE variables.
- Parameters:
*names (
str) – Variable length argument representing the names of the ODE variable(s).scale (
Expression|GiNaC_GlobalParam|int|float|None) – Optional scaling factor for the ODE variable(s).testscale (
Expression|GiNaC_GlobalParam|int|float|None) – Optional scaling factor for the test functions associated with the ODE variable(s).
- Return type:
None
- get_coordinate_system()[source]
Returns the base coordinate system.
- Returns:
The base coordinate system.
- Return type:
BaseCoordinateSystem
- get_parent_domain()[source]
Returns the parent domain.
- Returns:
The parent domain.
- Return type:
None
- on_apply_boundary_conditions(mesh)[source]
Applies boundary conditions to the ODEs.
- Parameters:
mesh (AnyMesh) – The mesh to which the boundary conditions are applied.
- pyoomph.generic.codegen.sorted_field_kwargs(kwargs)[source]
Return keyword arguments naming fields in a fixed (alphabetical) order.
Equations that take their fields as
**kwargsget whatever order the caller’s dict happens to have. That is the literal source order when the call is written out by hand, but a random one, differing from process to process, as soon as the caller builds the arguments from a set:DirichletBC(**{"massfrac_"+c:True for c in mixture.required_adv_diff_fields})
Python randomizes the iteration order of a set of strings per process (PYTHONHASHSEED), so without this the conditions would be stated - and the generated code written - in a different order on every run. Normalizing here fixes that for every caller at once.
Only for equations whose kwargs order is not otherwise observable. Classes that DEFINE fields from their kwargs (
ODEEquations,ProjectExpression, the Lagrange multiplier constraints) must NOT use this: there the order sets the dof numbering, so sorting would renumber the dofs of every existing script and invalidate the state files those scripts have already written. The same holds for the observable classes, whose kwargs order is the column order of their output files. Callers of those must sort their own arguments if they build them from a set.- Return type:
dict[str,TypeVar(_KwargValue)]