pyoomph.equations.generic module

The physics-independent equation classes of pyoomph: the pieces that are combined with actual physics (pyoomph.equations.navier_stokes, pyoomph.equations.poisson, …) to state a problem.

Everything here is reachable from from pyoomph import *. The rarer relatives live in pyoomph.equations.additional, which has to be imported explicitly.

class pyoomph.equations.generic.AverageConstraint(*, ode_storage_domain=None, only_for_stationary_solve=False, set_zero_on_normal_mode_eigensolve=True, scaling_factor=None, **kwargs)[source]

Bases: _AverageOrIntegralConstraintBase

Enforces the value of a field to have a fixed averaged value by a global Lagrange multiplier. If you have e.g. a field "u", you can enforce the average of "u" to be 1 by adding:

AverageConstraint(u=1)

Unlike IntegralConstraint, there is no dimensional_dx: the constraint is \(\int (u-\text{target})\,\mathrm{d}x=0\), whose root a constant factor on the measure does not move.

Parameters:
  • ode_storage_domain (str | None) – The storage domain for the Lagrange multipliers. Defaults to a generated name.

  • only_for_stationary_solve (bool) – Apply the constraint during stationary solves only.

  • set_zero_on_normal_mode_eigensolve (bool) – Force the multiplier to zero in a normal mode eigensolve.

  • scaling_factor (str | Expression | GiNaC_GlobalParam | int | float | None) – Scale of the Lagrange multiplier, either an expression or the name of a scale.

  • **kwargs (Expression | GiNaC_GlobalParam | int | float) – The constraints as field_name=value pairs.

class pyoomph.equations.generic.AxisymmetryBC(verbose=True, recurse=True)[source]

Bases: InterfaceEquations

Add this to the axis of symmetry to automatically enforce the boundary condition required by symmetry. Also automatically sets the correct boundary conditions for azimuthal eigenvalue problems.

For normal solving, it sets radial (and azimuthal) components of vector fields (also mesh_x) to zero. For azimuthal eigenvalue problems, it depends on the azimuthal mode \(m\):

  • \(m=0\): as for normal solving.

  • \(|m|=1\): scalar fields and axial vector components are set to zero, radial and azimuthal components are not.

  • \(|m|\geq 2\): scalar fields and all vector components are set to zero.

If you write an equation, where you want to change this behavior, you can manually change the conditions by obtaining the (writeable) field information via get_azimuthal_r0_info() after the definition via define_scalar_field() or define_vector_field().

Must also be added to intersections of other boundaries with the axis of symmetry when those boundaries define additional fields:

bulk = NavierStokesEquations(...)
bulk += AxisymmetryBC() @ "axis"
bulk += NavierStokesFreeSurface() @ "interface"
bulk += AxisymmetryBC() @ "interface/axis"  # the free surface introduces new fields here

This is, however, done automatically as long as recurse is set.

Parameters:
  • verbose (bool) – Report which fields are pinned on the axis.

  • recurse (bool) – Also apply the condition on the intersections of this axis with other interfaces.

class pyoomph.equations.generic.ConnectFieldsAtInterface(fields, *, lagr_mult_prefix='_lagr_conn_', use_highest_space=False, check_consistent_scaling=True)[source]

Bases: InterfaceEquations

Enforces continuity of fields at the interface. The fields are connected via Lagrange multipliers. The Lagrange multipliers are automatically chosen such that the condition <inner>=<outer> is satisfied.

Parameters:
  • fields (str | dict[str, str] | list[str]) – Either a single field name or a list of field names when the fields have the same name on both sides. Alternatively, a dict mapping each inner to each outer name if the fields have different names.

  • lagr_mult_prefix (str) – Prefix for the Lagrange multipliers. Defaults to “_lagr_conn_”.

  • use_highest_space (bool) – Flag indicating whether to use the highest space for the Lagrange multipliers. If the fields have different spatial discretizations on both sides, we have to decide which space to use for the Lagrange multipliers. If this flag is set to True, the highest space will be used. Defaults to False.

  • check_consistent_scaling (bool) – Flag indicating whether to check for consistent scaling of the fields on both sides. Defaults to True.

class pyoomph.equations.generic.ConstrainFieldsToC1Space(*args, unconstrain_instead=False, where=None)[source]

Bases: Equations

Constrains a higher order field to the first order C1 space. Useful in combination with either the where parameter or (un)constrain a field e.g. a boundary

Parameters:
  • *args (str) – The names of the fields to constrain to C1 space.

  • unconstrain_instead (bool) – If set to True, the specified fields will be unconstrained from C1 space instead of being constrained. Default is False.

  • where (Callable[[list[float]], bool] | None) – An optional function to specify where the constraints should be applied. Nondimensional nodal positions are passed to this function, and it should return True for nodes where the constraint should be applied. If None, the constraint is applied to all nodes.

class pyoomph.equations.generic.DependentIntegralObservable(func, *argnames)[source]

Bases: object

An IntegralObservables entry that is computed from other observables instead of being integrated itself, e.g. U=DependentIntegralObservable(lambda U_sqr,Area: square_root(U_sqr/Area),"U_sqr","Area"). Passing a plain lambda with named arguments to IntegralObservables does the same.

Parameters:
  • func (Callable[..., Expression | GiNaC_GlobalParam | int | float]) – Called with the values of the observables named in argnames.

  • *argnames (str) – Names of the observables to feed into func.

class pyoomph.equations.generic.DirichletBC(*, prefer_weak_for_DG=True, **kwargs)[source]

Bases: BaseEquations

Class to impose one or more Dirichlet boundary condition.

Parameters:
  • prefer_weak_for_DG (bool) – Flag indicating whether to prefer weak contributions for Discontinuous Galerkin (DG) methods. If set and the bulk equations provide a specific implementation of get_weak_dirichlet_terms_for_DG(), these terms are used to enforce the condition in a weak sense. Otherwise strongly. Defaults to True.

  • **kwargs (Expression | GiNaC_GlobalParam | int | float) – Keyword arguments representing the Dirichlet conditions, where the keys are the variable names and the values are the corresponding expressions or numbers. Expressions for strong DirichletBCs may not depend on unknowns.

A vector field may be given as a whole, i.e. DirichletBC(velocity=vector(0,1)) instead of DirichletBC(velocity_x=0, velocity_y=1). The value is split component by component onto the field’s components in their own order, so this is also correct in e.g. an axisymmetric coordinate system. This includes the position fields and values that are not written as an explicit vector(...), i.e. DirichletBC(mesh=var("lagrangian")) to hold the mesh at its undeformed position. See _expand_vectorial_entries().

class pyoomph.equations.generic.ElementSpace(space)[source]

Bases: Equations

Sets the element space of the current equations. By default, pyoomph will take the highest order element space of all fields defined on the domain. With this class, you can e.g. set the element space to second order (“C2”), although you only have first-order fields (“C1”) defined.

Parameters:

space (Literal['C1', 'C1TB', 'C2', 'C2TB', 'D1', 'D1TB', 'D2', 'D2TB', 'DL', 'D0']) – Set the desired element space for the equations of the domain.

class pyoomph.equations.generic.EnforcedBC(*, only_for_stationary_solve=False, set_zero_on_normal_mode_eigensolve=False, domain=None, space=None, coordsys=None, **constraints)[source]

Bases: InterfaceEquations

Enforce rather arbitrary boundary conditions by a field of Lagrange multipliers, e.g.:

EnforcedBC(u=var("u")-var("v")) @ "boundary"

will set u=v on the boundary by adjusting u. The value must be the constraint in residual form, i.e. the expression to drive to zero - here u-v.

Parameters:
  • only_for_stationary_solve (bool) – Apply the conditions during stationary solves only. Defaults to False.

  • set_zero_on_normal_mode_eigensolve – Force the multipliers to zero in an azimuthal eigensolve. Defaults to False.

  • domain (str | None) – Domain of the adjusted field, if it is not the one this condition is added to.

  • space (Optional[Literal['C1', 'C1TB', 'C2', 'C2TB', 'D1', 'D1TB', 'D2', 'D2TB', 'DL', 'D0']]) – Space of the Lagrange multiplier field. Defaults to the space of the adjusted field.

  • coordsys (BaseCoordinateSystem | None) – Coordinate system of the constraint integral. Defaults to the one of the equations or the problem. The former name coordinate_system is deprecated, but still accepted.

  • **constraints (Expression) – Name of the field to adjust, with the constraint expression in residual form.

class pyoomph.equations.generic.EnforcedDirichlet(*, only_for_stationary_solve=False, set_zero_on_normal_mode_eigensolve=False, domain=None, space=None, coordsys=None, **constraints)[source]

Bases: EnforcedBC

Enforces a Dirichlet condition by Lagrange multipliers instead of by pinning, i.e. the value stays a degree of freedom. Unlike DirichletBC, the prescribed value may therefore depend on unknowns. The two lines:

EnforcedDirichlet(u=var("v")) @ "boundary"
EnforcedBC(u=var("u")-var("v")) @ "boundary"

are equivalent - this class only subtracts the current value for you.

Parameters:
  • only_for_stationary_solve (bool) – Apply the conditions during stationary solves only. Defaults to False.

  • set_zero_on_normal_mode_eigensolve – Force the multipliers to zero in an azimuthal eigensolve. Defaults to False.

  • domain (str | None) – Domain of the adjusted field, if it is not the one this condition is added to.

  • space (Optional[Literal['C1', 'C1TB', 'C2', 'C2TB', 'D1', 'D1TB', 'D2', 'D2TB', 'DL', 'D0']]) – Space of the Lagrange multiplier field. Defaults to the space of the adjusted field.

  • coordsys (BaseCoordinateSystem | None) – Coordinate system of the constraint integral. Defaults to the one of the equations or the problem. The former name coordinate_system is deprecated, but still accepted.

  • **constraints (Expression) – Name of the field to adjust, with the value it is enforced to.

class pyoomph.equations.generic.ExtremumObservables(*direct_vars, **named_extrema)[source]

Bases: Equations

Add these to continuum equations to find minima and maxima of given expressions. If you want to find the minimum/maximum of a scalar quantity “u”, you can add an ExtremumObservables("u") or, alternatively, give it a name like ExtremumObservables(my_name_for_u=var("u")). More than one argument can be passed to register multiple extremum observables. For e.g. the maximum of a norm of a vectorial variable v, you can add ExtremumObservables(v_norm=square_root(dot(var("v"),var("v")))).

Once registered, you can evaluate the extremum values by calling the evaluate_maximum or evaluate_minimum method of the corresponding mesh (available via problem.get_mesh(...))

Parameters:
  • *direct_vars (str) – Names of variables to monitor, e.g. "u".

  • **named_extrema (Expression | GiNaC_GlobalParam | int | float) – Expressions to monitor, keyed by the name under which the extremum is reported, e.g. u_sqr=var("u")**2.

class pyoomph.equations.generic.ForceZeroOnEigenSolve(default, *, for_nonzero_angular=None)[source]

Bases: BaseEquations

Forces the given degrees of freedom to zero in the eigenproblem only, i.e. the base solution keeps them. Required whenever a dof must not take part in a perturbation, e.g. a Lagrange multiplier that is meaningless for a nonzero azimuthal mode.

Parameters:
  • default (Iterable[str]) – Names of the fields to zero out.

  • for_nonzero_angular (Iterable[str] | None) – Names to use instead when the azimuthal mode is not zero. Defaults to default.

class pyoomph.equations.generic.GlobalLagrangeMultiplier(*args, only_for_stationary_solve=False, set_zero_on_normal_mode_eigensolve=True, **kwargs)[source]

Bases: ODEEquations

Defines global degrees of freedom, typically Lagrange multipliers enforcing a global constraint. It is just an ODEEquations with a few extras, e.g. it can be deactivated on transient solves. Each entry adds one global unknown together with the residual contribution given as its value:

problem += (GlobalLagrangeMultiplier(volume_lagr=-V0) + Scaling(volume_lagr=1*pascal)) @ "globals"

The remaining part of the constraint - here the integral over the domain - is usually added with a WeakContribution projected onto testfunction("volume_lagr", domain="globals").

Parameters:
  • *args (str) – Names of multipliers whose residual contribution is added elsewhere.

  • only_for_stationary_solve (bool) – Pin the multipliers to zero during transient solves, so the constraint acts on stationary solves only.

  • set_zero_on_normal_mode_eigensolve (bool) – Force them to zero in a normal mode eigensolve, where a global multiplier is usually meaningless. Defaults to True.

  • **kwargs (Expression | GiNaC_GlobalParam | int | float) – Multiplier name with the residual contribution added to its test function.

class pyoomph.equations.generic.InitialCondition(*, degraded_start='auto', IC_name='', **kwargs)[source]

Bases: BaseEquations

Class representing initial conditions for a set of equations. If the initial conditions depend on time, i.e. on var("time"), it will be used to initialize the history steps before the first step. Otherwise, by default, the first time step will be calculated by a first order step.

Parameters:
  • degraded_start (Union[bool, Literal['auto']]) – Flag indicating whether to use degraded start (i.e. first order time stepping in the first step) or not. Defaults to “auto”, meaning we degrade if the initial condition does not depend on time.

  • IC_name (str) – Name of the initial condition. Defaults to an empty string, which are the default initial conditions.

  • **kwargs (Expression | GiNaC_GlobalParam | int | float) – Keyword arguments representing the initial conditions for each variable.

A vector field may be given as a whole, i.e. InitialCondition(velocity=vector(0,1)) instead of InitialCondition(velocity_x=0, velocity_y=1). The value is split component by component onto the field’s components in their own order, so this is also correct in e.g. an axisymmetric coordinate system. This includes the position fields and values that are not written as an explicit vector(...), i.e. InitialCondition(mesh=var("lagrangian")). See _expand_vectorial_entries().

class pyoomph.equations.generic.IntegralConstraint(*, dimensional_dx=True, ode_storage_domain=None, only_for_stationary_solve=False, set_zero_on_normal_mode_eigensolve=True, scaling_factor=None, **kwargs)[source]

Bases: _AverageOrIntegralConstraintBase

Enforces the value of a field to have a fixed integral value by a global Lagrange multiplier. If you have e.g. a field "u", you can enforce the integral of "u" to be 1 by adding:

IntegralConstraint(u=1)
Parameters:
  • dimensional_dx (bool) – Whether the integration measure carries its physical dimension. Defaults to True.

  • ode_storage_domain (str | None) – The storage domain for the Lagrange multipliers. Defaults to a generated name.

  • only_for_stationary_solve (bool) – Apply the constraint during stationary solves only.

  • set_zero_on_normal_mode_eigensolve (bool) – Force the multiplier to zero in a normal mode eigensolve.

  • scaling_factor (str | Expression | GiNaC_GlobalParam | int | float | None) – Scale of the Lagrange multiplier, either an expression or the name of a scale.

  • **kwargs (Expression | GiNaC_GlobalParam | int | float) – The constraints as field_name=value pairs.

class pyoomph.equations.generic.IntegralObservables(coordsys=None, _lagrangian=False, **integral_observables)[source]

Bases: Equations

Integral expressions will be evaluated by spatial integration over the mesh domain, e.g.:

IntegralObservables(volume=1)

will calculate the volume by integration over the mesh domain. In e.g. axisymmetry, the factor 2*pi*r will be included. Also, the output is dimensional, i.e. if you have set the scaling to a metric quantity, you will get a result in cubic meters here. When combined with an IntegralObservableOutput object, they will be written to an output file.

You can also introduce dependent integral observables. If you have a field "u", you can calculate its average over the domain by:

IntegralObservables(_denom=1, _u_integral=var("u"), u_avg=lambda _u_integral, _denom: _u_integral/_denom)

Here, _denom is the integral over 1 and _u_integral the integral over "u", so u_avg evaluates to the average. The parameter names of the lambda must match the names of the other integral observables. The leading underscore keeps the helper observables out of the output.

Note that the integration measure of an integral observable is always the current one: the apply_on_integral_dx of evaluate_in_past() has no effect here, so an integrand evaluated in the past is still integrated over the present mesh. History evaluation of the integrand itself, including apply_on_others for the geometry entering it, does work.

Parameters:
  • coordsys (BaseCoordinateSystem | None) – The coordinate system to use. Defaults to None, i.e. the one of the equations or the problem. The former name _coordinate_system is deprecated, but still accepted. Since the observables are passed as keyword arguments, an observable cannot be named coordsys (nor _lagrangian).

  • _lagrangian (bool) – Integrate over the Lagrangian instead of the Eulerian domain. Defaults to False.

  • **integral_observables (Expression | GiNaC_GlobalParam | int | float | Callable[..., Expression | GiNaC_GlobalParam | int | float]) – The observables, either expressions to integrate or callables of other observables (see above).

class pyoomph.equations.generic.LocalExpressions(**local_expressions)[source]

Bases: Equations

Local expressions are additional expressions for output, evaluated on the nodes of the mesh. They are not solved, but only calculated for output. Since it works node-wise, it might give problems, e.g. for 1/r terms at the axis of symmetry. An alternative is ProjectExpression, which calculates such expressions by projection. However, these are degrees of freedom, i.e. it will be slower.

Parameters:

**local_expressions (Expression | GiNaC_GlobalParam | int | float) – A dict of expressions to be evaluated on the nodes of the mesh for output only.

class pyoomph.equations.generic.NeumannBC(**fluxes)[source]

Bases: InterfaceEquations

Imposes a Neumann boundary condition. What the flux means depends on the bulk equations, i.e. on how the integration by parts was performed for their weak form. For a Poisson equation implemented by the residual weak(grad(u),grad(utest)), the condition:

NeumannBC(u=1) @ "boundary"

does not mean setting u=1, but rather dot(grad(u),var("normal"))=-1, with the normal vector pointing out of the domain at the boundary.

Parameters:

**fluxes (Expression | GiNaC_GlobalParam | int | float) – The imposed fluxes as field_name=flux pairs.

class pyoomph.equations.generic.ODEObservables(**ode_observables)[source]

Bases: ODEEquations

Adds observables to ODEs. Observables are just expressions which will be also written to the output file when combined with an ODEFileOutput object. If you have e.g. a harmonic oscillator (with variable y) and want to monitor the total energy, add it as an observable:

HarmonicOscillator(...) + ODEObservables(Etot=1/2*partial_t(y)**2 + 1/2*omega**2*y**2)
Parameters:

**ode_observables (Expression | GiNaC_GlobalParam | int | float | Callable[..., Expression | GiNaC_GlobalParam | int | float]) – Observables to be added, identified by the name. Can also be a callable taking no arguments and returning an ExpressionOrNum, evaluated lazily as a dependent observable.

class pyoomph.equations.generic.PeriodicBC(other_interface, offset=None)[source]

Bases: InterfaceEquations

Introduces a periodic boundary condition between two interfaces. It will hold for all continuous fields! The mesh must be generated that way that for each node on this interface, there is a corresponding node on the other interface when adding offset to the position.

Parameters:
  • other_interface (str) – The name of the other interface to which this boundary is periodic.

  • offset (list[Expression | GiNaC_GlobalParam | int | float] | None) – Added to the position of a node here to find its counterpart on other_interface.

class pyoomph.equations.generic.PinWhere(where, **kwargs)[source]

Bases: PythonDirichletBC

Pins the given fields, but only at the nodes where where returns True, e.g. PinWhere(lambda x,y: x**2+y**2<0.25, u=0). The callback gets the nondimensional nodal coordinates. Use it for conditions that cannot be stated on a named boundary.

Parameters:
  • where (Callable[..., bool]) – Predicate on the nodal coordinates deciding where to pin.

  • **kwargs (Union[Expression, GiNaC_GlobalParam, int, float, Literal[True]]) – Fields to pin, either to a value or to True to keep the current one.

class pyoomph.equations.generic.ProjectExpression(scale=1, space='C2', destination=None, field_type='scalar', dim=None, coordsys=None, **projs)[source]

Bases: Equations

Projects an expression onto a finite element space. The projected field can be used in the equations as a variable.

Parameters:
  • scale (Expression | GiNaC_GlobalParam | int | float | str) – Scale of the projected field. A string is resolved as scale_factor(scale), i.e. it refers to a registered scale by name. Defaults to 1.

  • space (Literal['C1', 'C1TB', 'C2', 'C2TB', 'D1', 'D1TB', 'D2', 'D2TB', 'DL', 'D0']) – Finite element space to project onto. Defaults to “C2”.

  • destination (str | None) – Residual destination for the projection. Defaults to None, i.e. the default residual.

  • field_type (Literal['scalar', 'vector', 'tensor', 'symmetric_tensor']) – Type of the projected field: “scalar” (default), “vector”, “tensor” or “symmetric_tensor”. A symmetric tensor shares one test function between each pair of off-diagonal entries, so it projects the symmetric part of the expression.

  • dim (int | None) – Number of components (vector) or rows and columns (tensor) of the projected field. Defaults to the nodal dimension. In Cartesian coordinates that leaves a planar tensor without its out-of-plane entry, so pass dim=3 to project a full three-dimensional tensor on a two-dimensional mesh. Ignored for a scalar field.

  • coordsys (BaseCoordinateSystem | None) – Coordinate system for the projection. If None, the coordinate system of the domain/problem will be used. Defaults to None. The former name coordinate_system is deprecated, but still accepted.

  • **projs (Expression | GiNaC_GlobalParam | int | float) – Keyword arguments representing the expressions to project. The keys are the names of the projected fields, and the values are the expressions to project.

property coordinate_system: Any

Deprecated alias of coordsys.

class pyoomph.equations.generic.PythonDirichletBC(**kwargs)[source]

Bases: Equations

Pins (or unpins) degrees of freedom directly from Python whenever the boundary conditions are applied, i.e. for conditions that cannot be stated as an expression because they depend on the nodes themselves. Also the base class of PinWhere and UnpinDofs.

Parameters:

**kwargs (Union[Expression, GiNaC_GlobalParam, int, float, Literal[True], tuple[Callable[..., Expression | GiNaC_GlobalParam | int | float], list[int], Expression]]) – Fields to pin. The value is either the value to pin to, or True to pin each node at whatever value it currently has.

class pyoomph.equations.generic.RefineToLevel(level='max')[source]

Bases: Equations

Refine elements to a certain level. If the level is set to “max”, the elements will be refined to the maximum level set by e.g. max_refinement_level.

class pyoomph.equations.generic.RemeshMeshSize(size=None)[source]

Bases: BaseEquations

Can be added to boundaries or corners to set the local mesh size. The size can be a constant or a function of the point. If the size is a function, it must be a function of the point and return a float.

Parameters:

size (float | Callable[[RemesherPointEntry], float] | None) – The local size, i.e. the typical nondimensional length of an element here. Can be a constant or a function of the point.

class pyoomph.equations.generic.RemeshWhen(remeshing_opts=None, *, max_expansion=None, min_expansion=None, min_solves_before_remesh=0, reinit_initial_size_after_one_step=False, active=True, min_quality_decrease=None, on_invalid_triangulation=False, on_inverted_element=False)[source]

Bases: Equations

Checks whether the mesh has been deformed to much based on either the passed RemeshingOptions object or the passed parameters. If the mesh has been deformed too much, it will be marked for remeshing. The remeshing will be done after the current Newton solve, followed by a subsequent interpolation from the previous mesh.

Parameters:
  • remeshing_opts (RemeshingOptions | None) – An object containing the remeshing sensitivity.

  • max_expansion (float | None) – Maximum expansion factor of an element before remeshing is invoked.

  • min_expansion (float | None) – Minimum expansion factor of an element before remeshing is invoked.

  • min_solves_before_remesh (int | None) – Minimum number of sucessful solves before remeshing is invoked.

  • reinit_initial_size_after_one_step (bool | None) – Flag indicating whether to reinitialize the initial size after one step.

  • active (bool) – Flag indicating whether the remeshing is active.

  • min_quality_decrease (float | None) – Minimum quality decrease of an element before remeshing is invoked.

  • on_invalid_triangulation (bool) – Flag indicating whether to remesh if the triangulation is invalid.

before_finalization(codegen)[source]

Arm the inverted-element trigger, at code generation time.

Detection is a process-wide switch (BulkElementBase::detect_inverted_elements), while this equation is per domain, so arming it here turns the check on for every domain of the problem and everyone pays its ~2 % of the assembly time. That is a deliberate trade rather than an oversight - making it per-domain means threading a flag down to the element, on the hottest read there is - but it is worth knowing before switching this on.

class pyoomph.equations.generic.RemeshingOptions(max_expansion=1.75, min_expansion=0.6, min_solves_before_remesh=0, reinit_initial_size_after_one_step=False, active=True, min_quality_decrease=0.2, on_invalid_triangulation=False, on_inverted_element=False)[source]

Bases: object

A class containing the remeshing sensitivity options to be used with the RemeshWhen class.

Parameters:
  • max_expansion (float) – Maximum expansion factor of an element before remeshing is invoked.

  • min_expansion (float) – Minimum expansion factor of an element before remeshing is invoked.

  • min_solves_before_remesh (int) – Minimum number of sucessful solves before remeshing is invoked.

  • reinit_initial_size_after_one_step (bool) – Flag indicating whether to reinitialize the initial size after one step.

  • active (bool) – Flag indicating whether the remeshing is active.

  • min_quality_decrease (float) – Minimum quality decrease of an element before remeshing is invoked.

  • on_invalid_triangulation (bool) – Flag indicating whether to remesh if the triangulation is invalid.

  • on_inverted_element (bool) – Remesh when an element turns inside out. Off by default; switching it on also switches on the (global, off-by-default) inverted-element detection, since without it nothing reports an inversion in the first place.

class pyoomph.equations.generic.ScalarField(name, space, scale=None, testscale=None, residual=None)[source]

Bases: Equations

Introduces a scalar field with the given name and the given space. Residuals can be either added in the constructor or by combining with WeakContribution.

Parameters:
  • name (str) – Name of the scalar field

  • space (Literal['C1', 'C1TB', 'C2', 'C2TB', 'D1', 'D1TB', 'D2', 'D2TB', 'DL', 'D0']) – Space of the scalar field

  • scale (Expression | GiNaC_GlobalParam | int | float | None) – Optional scaling of the field. Defaults to None, i.e. the scale registered for name.

  • testscale (Expression | GiNaC_GlobalParam | int | float | None) – Optional scaling of the test function. Defaults to None, i.e. the test scale registered for name.

  • residual (Expression | GiNaC_GlobalParam | int | float | None) – Optional residual to be added. Formulate it in terms of the scalar field and its test function.

class pyoomph.equations.generic.Scaling(**kwargs)[source]

Bases: BaseEquations

Set the scales used for nondimensionalization on the equation level. It will override the scales set on the problem level by Problem.set_scaling(…=…).

Parameters:

**kwargs (Expression | GiNaC_GlobalParam | int | float | str) – Scales to use for nondimensionalization, as field_name=scale pairs. A string value refers to another scale by name.

class pyoomph.equations.generic.SpatialErrorEstimator(*fluxes, for_which='both', group='', normalize_relative=1.0, weight=1.0, **kwargs)[source]

Bases: Equations

Spatial error estimators are used to estimate where a mesh should be refined. You can either pass variable name(s) and numerical factor(s):

SpatialErrorEstimator(u=1, v=10)

In that case, the jumps of the gradients grad(u) and 10*grad(v) will be used as error estimators. Alternatively, you can also provide custom expressions as estimators, e.g. for discontinuous fields, it might be better to just add:

SpatialErrorEstimator(5*var("u"))

so that the jump in "u" is used, after weighting by the factor 5, as error estimator. Error estimator expressions must be nondimensional.

for_which controls whether these error estimators are used for the base solution, potential eigenfunctions or both.

normalize_relative selects what the resulting numbers mean, i.e. what max_permitted_error is compared against:

  • 1 (default) gives the relative error: each element’s error is divided by the recovered flux norm of the whole mesh, so it is that element’s share of this mesh’s total. Dimensionless, but blind to how well resolved the mesh is overall – a well resolved and a badly resolved domain report errors of similar magnitude, and refining the mesh does not by itself make the numbers smaller.

  • 0 gives the absolute error: the raw integrated flux jump, which really does shrink as the mesh is refined and is comparable between meshes and between adaptation steps. In exchange, its magnitude depends on the element size and on the field’s own scale, so max_permitted_error/min_permitted_error have to be chosen for the problem at hand rather than left at the defaults.

  • values in between divide by norm**normalize_relative, which is the geometric blend of the two (err/norm**p is exactly (err/norm)**p * err**(1-p)).

Note that normalize_relative is the only knob that can change the scale of the errors of a group: a common factor on the estimator expressions themselves cancels out of the relative normalisation exactly (SpatialErrorEstimator(u=2) is identical to SpatialErrorEstimator(u=1)); only the ratios between the fields within one group matter there. To scale a group against the others, use weight, which is applied after the normalisation and therefore does not cancel.

The norm being divided out is a whole-group quantity, so normalize_relative and weight belong to the group rather than to the individual expressions. That is what group is for:

eqs += SpatialErrorEstimator(u=1)                                        # group ""
eqs += SpatialErrorEstimator(Gamma=1, group="surf", normalize_relative=0, weight=3)

Each group gets its own recovered-flux norm, and the elemental error is the maximum over the groups. Two criteria in different groups can therefore neither dilute nor mask each other, and adding a group can only ever cause more refinement and less unrefinement, never the reverse – which is what makes it safe for independent pieces of a model to contribute error criteria without knowing about each other. Everything lands in the single unnamed group "" unless a group is named, which is the historical behaviour of one joint norm over all fields.

Vetoes (“refine this regardless”, “do not unrefine this”) deliberately do not live here: they would have to lower an element’s error and so break the monotonicity that makes the maximum safe. Use RefineToLevel, RefineMaxElementSize or RefineAccordingToElement for those.

Parameters:
  • *fluxes (str | Expression) – Estimators with factor 1, either an expression used as it is, e.g. 5*var("u"), or a field name, which then uses the jump of its gradient.

  • for_which (Literal['both', 'base', 'eigen']) – Whether the estimators act on the base solution, on eigenfunctions or on both.

  • group (str) – Name of the group this criterion belongs to. Each group gets its own recovered-flux norm, and the elemental error is the maximum over the groups.

  • normalize_relative (float) – Exponent of the norm divided out, see above. 1 gives the relative, 0 the absolute error.

  • weight (float) – Applied after the normalisation, i.e. it does not cancel and can scale this group against the others.

  • **kwargs (Expression | GiNaC_GlobalParam | int | float) – Field names with their numerical factors, e.g. u=1, v=10, which use the jump of the weighted gradient of that field.

class pyoomph.equations.generic.StaticCondensation(*fields, **field_specs)[source]

Bases: Equations

Declares which degrees of freedom of this domain static condensation may eliminate from the linear system. Contributes no residuals: it only states a selection, on the domain it is added to.

Experimental. Serial and distributed (--distribute) runs are both supported. Element-local unknowns - a Crouzeix-Raviart bubble velocity, the gradient modes of a discontinuous (DL) pressure, a field projected onto a D0/DG space - couple to nothing outside their own element and can be eliminated by a small dense Schur complement before the Jacobian reaches the solver, and reconstructed from the retained increment afterwards. The elimination is exact: the same solution and the same Newton iteration count as without it. On a Crouzeix-Raviart Navier-Stokes system it saves roughly half of the factorisation time.

The classical Crouzeix-Raviart elimination needs the bubble velocities and the pressure gradient modes together - neither half is invertible on its own - while the constant pressure mode has to stay a global unknown:

eqs = NavierStokesEquations(mode="CR", dynamic_viscosity=1, mass_density=100)
eqs += StaticCondensation(velocity="bubble", pressure="DL_gradients")
self.add_equations(eqs @ "domain")

"DL_gradients" is just a name for “every value of that "DL" field except the constant”, so it expands to [1,2] in 2d and [1,2,3] in 3d without the script having to know which.

Taking the constant mode along (pressure=[0,1,2]) is refused with an explanation, and so is condensing the pressure on its own - the continuity equation contains no pressure at all, so that block is structurally singular.

Without any argument, every element-private degree of freedom of this domain is selected, i.e. every element-internal Data that no other element reads. That is the convenient form for auxiliary fields projected onto a discontinuous space:

eqs += StaticCondensation()

Internal Data that some other element does adopt as external data - an interface element on a free surface, an interior-facet DG coupling - is excluded from that automatic selection, since it is not element-local at all; a field named explicitly is not filtered that way, because the elimination handles those correctly too and the user asked for them.

Switching it on and off. Adding this class anywhere in the equation tree sets problem.use_static_condensation for you. Assigning that switch explicitly always wins, in either direction, so self.use_static_condensation = False in define_problem() is a kill switch that disables the feature wholesale without touching the equations. Several instances on different domains compose - the selections are unioned - and so do rules declared at problem level with condense_dofs().

Limitations. Only Newton solves benefit: residual evaluations, eigenvalue and Hessian assemblies, and arclength continuation always see the full system. An MPI run, Jacobian reuse and the globally convergent (line search) Newton method are refused with an error rather than silently ignored. Adding it to an interface or ODE domain is an error. See dev_docs/static_condensation.md for the design and the measurements.

Parameters:
  • *fields (str) – Fields to condense entirely, e.g. StaticCondensation("my_projection_field").

  • **field_specs (str | bool | Sequence[int]) – Fields to condense in part. The value is "all" or True for the whole field, "internal" for the element-internal Data of an elemental (DL/D0/DG) field, "bubble" for the cell-interior bubble nodes of a nodal C1TB/C2TB field, "DL_gradients" for the gradient modes of a "DL" field (i.e. all of its values except the constant, resolved to [1,2] or [1,2,3] from the dimension of the domain it is added to), or an explicit list of value indices, e.g. pressure=[1,2].

class pyoomph.equations.generic.TemporalErrorEstimator(**fieldfactors)[source]

Bases: BaseEquations

Adds temporal error estimators, which drive the adaptive time stepping of run() with temporal_error=.... Each field can have a different factor. If you have e.g. fields "u" and "v", add:

TemporalErrorEstimator(u=1, v=10)

to weight the error estimator of "u" with 1 and of "v" with 10, i.e. errors in "v" count ten times as much.

Parameters:

**fieldfactors (float) – Field names with their temporal error weighting factors.

class pyoomph.equations.generic.TestScaling(**kwargs)[source]

Bases: BaseEquations

Set the scales of the test functions used for nondimensionalization on the equation level.

Parameters:

**kwargs (Expression | GiNaC_GlobalParam | int | float | str) – Test function scales, as field_name=scale pairs. A string value refers to another scale by name.

class pyoomph.equations.generic.UnconstrainFieldsFromC1Space(*args, where=None)[source]

Bases: ConstrainFieldsToC1Space

Unconstrains a higher order field from the first order C1 space. Useful in combination with either the where parameter or (un)constrain a field e.g. a boundary

Parameters:
  • *args (str) – The names of the fields to unconstrain from the C1 space.

  • where (Callable[[list[float]], bool] | None) – An optional function to specify where the unconstraining should be applied. Nondimensional nodal positions are passed to this function, and it should return True for nodes where the constraint should be applied. If None, the constraint is applied to all nodes.

class pyoomph.equations.generic.UnpinDofs(*args: Any, **kwargs: Any)[source]

Bases: PythonDirichletBC

The inverse of DirichletBC: frees the given degrees of freedom again, e.g. to release a boundary that a previously added condition has pinned.

Parameters:

**kwargs – Fields to unpin, e.g. UnpinDofs(u=True). The values are ignored.

class pyoomph.equations.generic.VectorField(name, space, scale=None, testscale=None, residual=None, dim=None)[source]

Bases: Equations

Introduces a vector field with the given name and the given space. Residuals can be either added in the constructor or by combining with WeakContribution.

Parameters:
  • name (str) – Name of the vector field

  • space (Literal['C1', 'C1TB', 'C2', 'C2TB', 'D1', 'D1TB', 'D2', 'D2TB', 'DL', 'D0']) – Space of the vector field

  • scale (Expression | GiNaC_GlobalParam | int | float | None) – Optional scaling of the field. Defaults to None, i.e. the scale registered for name.

  • testscale (Expression | GiNaC_GlobalParam | int | float | None) – Optional scaling of the test function. Defaults to None, i.e. the test scale registered for name.

  • residual (Expression | GiNaC_GlobalParam | int | float | None) – Optional residual to be added. Formulate it in terms of the vector field and its test function.

  • dim (int | None) – Vector dimension. If not set, it will be taken by the dimension of the mesh coordinates, i.e. the nodal dimension

class pyoomph.equations.generic.WeakContribution(a, b, dimensional_dx=False, lagrangian=False, coordsys=None, destination=None)[source]

Bases: BaseEquations

A class to add an arbitrary weak contribution to the equations. This is useful to add additional terms to the equations that are not covered by the standard weak formulation. Essentially, it just adds weak(a,b) to the residuals.

Parameters:
  • a (Expression | GiNaC_GlobalParam | int | float | str) – The first argument of the weak() contribution. A string is taken as a field name, i.e. "u" means var("u").

  • b (Expression | str) – The second argument, usually a testfunction(). A string is taken as a field name, i.e. "u" means testfunction("u").

  • dimensional_dx (bool) – If set to True, the weak contribution is treated as a dimensional contribution, i.e. spatial integration dx will carry dimension.

  • lagrangian (bool) – If set to True, the weak contribution is integrated in the Lagrangian frame of reference.

  • coordsys (BaseCoordinateSystem | None) – The coordinate system in which the weak contribution is defined. If not set, the coordinate system of the equations or the problem is used. The former name coordinate_system is deprecated, but still accepted.

  • destination (str | None) – The residual destination of the weak contribution. Can be used to define multiple residuals.

property coordinate_system: Any

Deprecated alias of coordsys.

pyoomph.equations.generic.get_interface_field_connection_space(inside_space, outside_space, use_highest_space=False, parent_space='', parent_dim=0)[source]

The space the Lagrange multiplier coupling the two sides of an interface lives in.

By default the MEET of the two – the largest space both sides can represent – capped by what the inner domain can actually carry on a facet (the multiplier is a nodal value on the INNER domain’s bulk nodes, so only that side’s facet has to hold it).

This used to walk a total order [“D2TB”,”C2TB”,”D2”,”C2”,”D1TB”,”C1TB”,”D1”,”C1”], which is wrong: C1TB and C2 are incomparable, so “the one further down that list” is not the meet. A C2 domain coupled to a C1TB one negotiated a C1TB multiplier – a space a C2 triangle does not have – and the run segfaulted rather than complained. See dev_docs/interface_refinement_coupling.md section 14.5 and find_subordinate_element_space, which is the lattice this now uses.

Return type:

Union[Literal['C1', 'C1TB', 'C2', 'C2TB', 'D1', 'D1TB', 'D2', 'D2TB', 'DL', 'D0'], Literal['']]

pyoomph.equations.generic.interface_transport_velocities(host, fluid_velocity=None, interface_velocity=None)[source]

The two velocities a quantity transported along an interface needs: the fluid velocity that carries it tangentially, and the velocity of the interface itself, which it follows normally.

Both default to nothing at all when there is nothing to take them from: a surfactant or a surface charge sitting on a prescribed, immobile interface is a legitimate configuration, and asking for var("velocity") there fails at code generation with a message about an undefined field rather than about the equations being incomplete.

Shared by SurfactantTransportEquations and SurfaceChargeConservation, which assemble the same conservative surface transport and would otherwise carry two copies of this - and of the reason the conservative form takes u and w separately rather than one combined velocity.

Return type:

tuple[Expression, Expression]