The solvers layer#

Solving the discrete counterparts of sumfem.discrete.

Newton’s method#

class sumfem.solvers.Solver(system, bcs=(), petsc_options=None, petsc_options_prefix=None, kind=None)[source]#

Solve a System.

Parameters:
  • system (discrete_system.System) – The discrete system.

  • bcs (Iterable[symbolic.DirichletBC | dolfinx.fem.DirichletBC]) – Dirichlet conditions, symbolic or as DOLFINx objects. Symbolic conditions must be on unknowns of the system.

  • petsc_options (Mapping[str, Any] | None) – PETSc options for the SNES solver, on top of DEFAULT_PETSC_OPTIONS, and of FACTORIZED_PETSC_OPTIONS for factorized equations. An LU solve without pc_factor_mat_solver_type gets the package of direct_solver_options().

  • petsc_options_prefix (str | None) – Options prefix of the PETSc objects. Defaults to a unique prefix.

  • kind (str | None) – PETSc matrix and vector kind, e.g. "nest" for field-split preconditioning.

Symbolic boundary values are evaluated before every solve and every Newton iteration, so they follow parameters, time and known coefficients, as in Irksome’s DOLFINx backend.

For factorized equations, Newton iterates on the unknowns divided by their scales, in SI, and the rows of the Dirichlet conditions are divided by the scale of their unknown, so that the whole system is dimensionless: the residual, the step and every entry of the Jacobian are of size one. This is a two-sided diagonal scaling of the Jacobian, a form of equilibration (Habera and Zilian, 2026, Section 4.1). The Newton update is the same; the norms that stop Newton are not, nor are the pivots of an LU factorization. The functions of the unknowns hold SI values before and after a solve, which must go through solve(), not the nonlinear_problem.

property system: System#

The discrete system being solved.

property nonlinear_problem: NonlinearProblem#

The DOLFINx problem, giving access to the PETSc objects.

For factorized equations, its SNES iterates on scaled unknowns, see Solver.

property boundary_values: tuple[Function | Constant, ...]#

The functions or constants holding the prescribed boundary values.

property iterations: int#

Newton iterations of the last solve.

property converged: bool#

Whether the last solve converged.

property converged_to_tolerance: bool#

Whether the last solve stopped at a residual or step tolerance.

Solving again from its result then changes nothing, unlike after a solve stopped at its iteration count, e.g. a smoother.

pack_bcs()[source]#

Evaluate symbolic boundary values with the current values of their inputs.

Return type:

None

solve()[source]#

Solve the system, starting from the current values of the unknowns.

Returns:

The function of each unknown, in block order, holding the solution in SI units.

Raises:

ValueError – If a parameter of the system has no value.

Return type:

tuple[Function, …]

Time stepping#

class sumfem.solvers.TimeScheme[source]#

A scheme that turns a semi-discrete model into one time step.

Subclasses give prepare(), which a Simulation calls once per stage, and set_step(), which it calls before every step.

property order: int#

Order of accuracy of the scheme.

property given_history: bool#

Whether the user sets the previous values before the first step.

Otherwise a simulation sets them to the initial values.

prepare(model, clock)[source]#

The model of one step, and substitutions for its system.

Pass both to build_system().

Parameters:
Return type:

tuple[Residual, dict[Coefficient, Expr]]

set_step(step, dt, discretization, previous=())[source]#

Set the scheme’s parameters for a time step.

Parameters:
  • step (int) – Number of the step, starting at 1.

  • dt (float) – Time step size.

  • discretization (Discretization) – The discretization holding the parameter values.

  • previous (Sequence[float]) – Sizes of the steps before, most recent first. Missing ones are taken equal to dt.

Return type:

None

class sumfem.solvers.BDF(order=1, name='bdf', blend=1.0, given_history=False)[source]#

Backward differentiation formula of order 1 (backward Euler), 2 or 3.

The scheme replaces each time derivative field.dot by w0 * field + w1 * field.previous(1) + ..., and the time derivative Dt(q) of an expression by w0 * q + w1 * q(previous(1)) + ..., the expression of the fields’ previous values. The weights are parameters, set at every step from the sizes of the current and the previous steps: they differentiate, at the new time, the polynomial through the values at the times of the steps. The steps may thus change in size, e.g. between the runs of a Simulation or in an AdaptiveSimulation; with equal steps the weights are the classical ones. The first steps of a higher order scheme use the highest order the available history allows, so one compiled system serves every step.

A step that grows fast relative to the previous one can make the higher orders unstable: BDF2 stays zero-stable while each step is less than 1 + sqrt(2) times the one before, and BDF3 needs smaller ratios. Shrinking steps are safe. BDF3 is not A-stable, so it suits damped problems better than waves.

Without a given history, the first steps use lower orders. The first, backward Euler step then limits BDF3 to second order in general. To keep the full order, set the previous values field.previous(k) before running, e.g. to an exact solution or a finer start-up run, and pass given_history=True. The given values are taken one step of the first step’s size apart.

Parameters:
  • order (int) – 1, 2 or 3.

  • name (str) – Prefix of the weight parameters, "<name>.<domain>.w<k>".

  • blend (float) – For order 2, the weight a of the generalized formula a * BDF2 + (1 - a) * BDF1, e.g. of SWEMniCS; 1 is BDF2 and 0 implicit Euler.

  • given_history (bool) – Use the full order from the first step, with the previous values set by the user.

property order: int#

Order of the scheme, also the number of previous values it needs.

property given_history: bool#

Whether the user sets the previous values before the first step.

Otherwise a simulation sets them to the initial values.

prepare(model, clock)[source]#

The model itself, with its time derivatives replaced.

Parameters:
Return type:

tuple[Residual, dict[Coefficient, Expr]]

substitutions(model)[source]#

Replacements of the time derivatives in a model.

Pass them to build_system().

Parameters:

model (Residual)

Return type:

dict[Coefficient, Expr]

set_step(step, dt, discretization, previous=())[source]#

Set the weights for a time step.

Parameters:
  • step (int) – Number of the step, starting at 1.

  • dt (float) – Time step size.

  • discretization (Discretization) – The discretization holding the weight values.

  • previous (Sequence[float]) – Sizes of the steps before, most recent first. Missing ones, e.g. of a given history or of a loop that steps with one size, are taken equal to dt.

Return type:

None

class sumfem.solvers.Theta(theta, name='theta')[source]#

The theta method, between forward (0) and backward (1) Euler.

A model’s residual R = M(dot) + F(u, t), with M linear in the time-derivative placeholders, becomes

M((u - u_n) / dt) + theta F(u, t) + (1 - theta) F(u_n, t_n),

where the old part replaces every field by its previous(1) and the clock’s time by the previous time. Time derivatives Dt(q) of expressions become (q(u) - q(u_n)) / dt. The method is of order 2 for theta = 1/2, and of order 1 otherwise.

Data that changes in time other than through the clock, e.g. a known coefficient updated between steps, is taken at the new time in both parts. Hand-written Jacobians are not carried over: the Jacobian is derived from the residual.

Parameters:
  • theta (float) – The weight theta of the new time, in [0, 1].

  • name (str) – Prefix of the scheme’s parameters.

property theta: float#

The weight of the new time.

property order: int#

Order of accuracy of the scheme.

prepare(model, clock)[source]#

Every summand of the model as its theta step.

Parameters:
Return type:

tuple[Residual, dict[Coefficient, Expr]]

set_step(step, dt, discretization, previous=())[source]#

Set 1 / dt and the previous time; a one-step method needs no previous step sizes.

Parameters:
Return type:

None

class sumfem.solvers.CrankNicolson(name='crank_nicolson')[source]#

The Crank-Nicolson method, the theta method of order 2 with theta 1/2.

Parameters:

name (str) – Prefix of the scheme’s parameters.

class sumfem.solvers.ForwardEuler(name='forward_euler')[source]#

The forward Euler method, the theta method with theta 0.

Each step solves with the time-derivative terms alone, e.g. a mass matrix, so it is cheap where that is easy to solve, as for discontinuous elements. It is stable only for small steps.

Parameters:

name (str) – Prefix of the scheme’s parameters.

Simulations#

class sumfem.solvers.Simulation(discretization, model, bcs=(), clock=None, scheme=None, petsc_options=None, kind=None, output=None, check_units=False, factorize_equations=False, time_scale=None)[source]#

Step a model in time.

The model is prepared with the time-stepping scheme and built into a system once. Each step sets the clock and the scheme’s weights, solves the system with a Solver, and advances the history. A steady problem needs no simulation: solve the model with a Solver.

A simulation may run in parts, e.g. to change a load or the step size between them. The first run starts the history from the current values; later runs continue from where the last one ended, with the history, the numbering of the steps and the output of the earlier runs, so a multistep scheme keeps its order across them. restart() starts afresh, e.g. from new initial values.

Output stays open across the runs. Close it with close(), or by using the simulation in a with block. Every process must close it at the same point, as writing is collective; an output left open is closed when the simulation is garbage collected or the program ends.

Parameters:
  • discretization (Discretization) – The meshes and the functions of all terminals.

  • model (Residual) – The model, solved monolithically.

  • bcs (Iterable[symbolic.DirichletBC | dolfinx.fem.DirichletBC]) – Dirichlet conditions, symbolic or as DOLFINx objects.

  • clock (Clock | None) – The time and time step.

  • scheme (TimeScheme | None) – Time-stepping scheme, needed if the model has time derivatives.

  • petsc_options (Mapping[str, Any] | None) – PETSc options of the solver.

  • kind (str | None) – PETSc matrix and vector kind.

  • output (Output | None) – Where and what to write. Nothing is written without it.

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

  • factorize_equations (bool) – Solve in dimensionless form, see build_system(). Fields are still stored and written in SI units.

  • time_scale (float | None) – Reference time in seconds of the time derivatives, for the unit check and the sizes of factorized equations. Defaults to the clock’s time step, which makes the change over one step, the dominant term of a step, of order one; without a step, to one second. The size divides each equation by one number, so it does not change the solution or Newton’s iterates, but it gives Newton’s absolute tolerance its meaning: a reference time far below the steps makes the scaled residual small, and stops Newton’s method early.

The simulation declares on the discretization what it creates: the clock, the system with the terminals of the time-stepping scheme, and its symbolic boundary conditions.

Raises:

ValueError – Without a clock, or if the model has time derivatives but no scheme is given.

Parameters:
property discretization: Discretization#

The meshes and the functions of all terminals.

property solver: Solver#

The solver of one step.

property steps_taken: int#

Number of steps since the start, over all runs.

restart()[source]#

Start afresh at the next run.

The next run starts the history from the current values, e.g. new initial values, numbers its steps from one, and opens the output again, which overwrites the earlier files.

Return type:

None

close()[source]#

Close the output. A later run opens it again, overwriting it.

Return type:

None

run(num_steps=None, t_end=None, callback=None)[source]#

Take time steps of the clock’s step size, from the clock’s time.

Parameters:
  • num_steps (int | None) – Number of time steps.

  • t_end (float | None) – End time, a whole number of steps after the start. Give exactly one of num_steps and t_end.

  • callback (Callable[[float, int], None] | None) – Called after each step with the time and the step number, counted over all runs since the start, e.g. to post-process.

Raises:

ValueError – For inconsistent time arguments, or without a time step size.

Return type:

None

metadata()[source]#

A description of the simulation, for archiving with its results.

Return type:

dict[str, Any]

class sumfem.solvers.AdaptiveSimulation(discretization, model, time_step, clock, scheme=None, **kwargs)[source]#

A simulation whose time steps adapt to Newton’s iterations.

Steps grow or shrink by the iterations of the last step and stop at milestones and the end time. A failed step is retried from the previous values with a shorter step. The rules are those of an AdaptiveTimeStep.

Parameters:
  • discretization (Discretization) – See Simulation.

  • model (Residual) – See Simulation.

  • time_step (AdaptiveTimeStep) – The rules of the steps.

  • clock (Clock) – The time and time step.

  • scheme (TimeScheme | None) – A time-stepping scheme. BDF of order two or three adapts its weights to the changing steps; it stays stable while the steps grow slowly, see BDF.

  • **kwargs (Any) – The other arguments of Simulation. The time_scale defaults to the largest step, if it is a number, so that the absolute tolerance of Newton’s method is no looser for any step than for the largest; otherwise to the first step.

Like a Simulation, it may run in parts. Each run starts with the initial step of the rules, as a run usually starts at a change, e.g. of a load, that a long step could miss.

run(t_end, callback=None)[source]#

Step from the clock’s time to the end time.

Parameters:
  • t_end (float) – End time.

  • callback (Callable[[float, int], None] | None) – Called after each step with the time and the step number, counted over all runs since the start, e.g. to post-process.

Raises:

RuntimeError – If a step fails after its retries.

Return type:

None

class sumfem.solvers.AdaptiveTimeStep(initial, growth_factor=None, cutback_factor=None, target_iterations=None, max_step=None, min_step=0.0, milestones=(), milestone_tolerance=1e-05, max_retries=0)[source]#

A time step adapted to the Newton iterations.

After a solve with fewer Newton iterations than target_iterations the step grows by growth_factor, and after one with more it is cut by cutback_factor, as in FESTIM. A step whose solve fails is retried, cut by cutback_factor, up to max_retries times and not below min_step. Every step is capped by max_step, and shortened to end at the next milestone, e.g. an output time, and at the end time. An AdaptiveSimulation steps by these rules.

Parameters:
  • initial (float) – The first step, in s.

  • growth_factor (float | None) – Factor above one after easy solves.

  • cutback_factor (float | None) – Factor below one after hard or failed solves.

  • target_iterations (int | None) – Newton iterations of a solve that keeps the step.

  • max_step (float | Callable[[float], float] | None) – Largest step, a number or a callable of the time.

  • min_step (float) – Smallest step a failed solve is retried with.

  • milestones (Sequence[float]) – Times steps must end at.

  • milestone_tolerance (float) – Relative tolerance of reaching a milestone.

  • max_retries (int) – Retries of a step whose solve fails.

Raises:

ValueError – For a non-positive step, or retries without a cutback.

limit(dt, t, t_end)[source]#

A step from t, capped and ending at the next milestone or the end.

Parameters:
Return type:

float

next(dt, iterations)[source]#

The step after a step dt solved in iterations Newton iterations.

Parameters:
Return type:

float

retry(dt)[source]#

The step to retry a failed step dt with, or None to give up.

Parameters:

dt (float)

Return type:

float | None

class sumfem.solvers.Output(directory, fields=None, every=1)[source]#

Where and what a simulation writes.

Parameters:
directory#

Output directory, created if needed.

Type:

str | os.PathLike

fields#

Names of the fields to write. Defaults to every field.

Type:

tuple[str, …] | None

every#

Write every every-th time step.

Type:

int

sumfem.solvers.simulation.owned(function)[source]#

The values of a function’s degrees of freedom owned by this process.

Parameters:

function (Function)

Return type:

ndarray[tuple[Any, …], dtype[Any]]

sumfem.solvers.simulation.versions()[source]#

The versions of sumfem and the libraries it builds on.

Return type:

dict[str, str]

PETSc options#

sumfem.solvers.solver.DEFAULT_PETSC_OPTIONS: Mapping[str, Any] = {'ksp_error_if_not_converged': True, 'ksp_type': 'preonly', 'pc_type': 'lu', 'snes_atol': 1e-12, 'snes_error_if_not_converged': True, 'snes_linesearch_type': 'none', 'snes_rtol': 1e-10, 'snes_type': 'newtonls'}#

Newton’s method with a direct LU solve, raising if it fails to converge. Options passed to Solver are applied on top. The LU package is chosen by direct_solver_options(), unless the options name one.

sumfem.solvers.solver.FACTORIZED_PETSC_OPTIONS: Mapping[str, Any] = {'snes_atol': 1e-10, 'snes_stol': 0.0}#

Defaults for factorized equations, on top of DEFAULT_PETSC_OPTIONS.

Their residuals are dimensionless, and so are the unknowns that Newton iterates on, see Solver, so Newton converges on the residual alone, with the absolute tolerance of FACTORIZED_ABSOLUTE_TOLERANCES, and the step-size test is off.

sumfem.solvers.solver.FACTORIZED_ABSOLUTE_TOLERANCES: Mapping[dtype, float] = {dtype('float32'): 0.001, dtype('float64'): 1e-10}#

Newton’s absolute tolerance for factorized equations, in each precision of PETSc’s real type. Their residuals are dimensionless, of size one, and stall at round-off some thousand machine epsilons above zero, so the absolute tolerance is well above that.

sumfem.solvers.solver.NEWTON_TOLERANCES: Mapping[dtype, Mapping[str, float]] = {dtype('float32'): {'snes_atol': 1e-06, 'snes_rtol': 1e-05}, dtype('float64'): {'snes_atol': 1e-12, 'snes_rtol': 1e-10}}#

Newton’s tolerances in each precision of PETSc’s real type, which DEFAULT_PETSC_OPTIONS takes from dolfinx.default_real_type. The absolute tolerance is in the units of the residual, SI unless the equations are factorized, so a problem may need its own.

sumfem.solvers.solver.direct_solver_options(comm)[source]#

PETSc options choosing the LU package, by what PETSc was built with.

MUMPS is preferred, with null pivot detection so that systems with a null space, e.g. a pure Neumann problem, can be factorized. Without it, SuperLU_dist is used, and in serial without either, PETSc’s own LU.

Parameters:

comm (Intracomm) – The communicator of the system to solve.

Raises:

RuntimeError – In parallel, if PETSc has neither MUMPS nor SuperLU_dist, since PETSc’s own LU runs in serial only.

Return type:

dict[str, Any]