pyoomph.generic.problem module
- class pyoomph.generic.problem.GenericProblemHooks[source]
Bases:
objectA class that can be attached to a problem to call additional functions after e.g. newton solves, etc.
- actions_after_transient_solve()[source]
Called once per accepted timestep, not once per Newton solve. See
Problem.actions_after_transient_solve().
- exception pyoomph.generic.problem.InvertedElementRemeshRequest[source]
Bases:
RuntimeErrorRaised from the C++ core when an element has been inside out on enough consecutive Newton solves that reducing the step has clearly stopped helping, and a
RemeshWhen(on_inverted_element=True)is armed to remesh instead.It is raised on every rank or on none - the decision is reduced across the processes before it is taken, because an inversion is only seen by whichever rank happens to hold the folded element while a remesh is collective.
Users do not normally see this:
Problem.solve()catches it, restores the last good state, remeshes and retries the step. It escapes only when the retry budget (Problem.inversion_remesh_max_retries) is exhausted, i.e. when remeshing did not help either.- __init__(*args, **kwargs)
- add_note()
Exception.add_note(note) – add a note to the exception
- with_traceback()
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- class pyoomph.generic.problem.PeriodicOrbit(problem, mode, lyap_coeff, param, omega, pvalue, pdvalue, al, order, GL_order, T_constraint)[source]
Bases:
objectA class representing a periodic orbit.
- classmethod from_stored_blocks(problem, info, blocks, T_nondim)[source]
Re-create the handler from stored time blocks and hand back the orbit carrying it.
The stored info dict is what says which discretization to rebuild;
_install_blocks()does the rest, so there is one copy of the block/history/permutation rules.- Return type:
- get_T(dimensional=True)[source]
Returns the period time of the orbit
- Return type:
Union[Expression,GiNaC_GlobalParam,int,float]
- get_floquet_multipliers(n=None, valid_threshold=10000, shift=None, ignore_periodic_unity=False, quiet=True, method='condensed', dense_threshold=2000, shift_invert=True, sigma=None, sampling_NT=None, sampling_order=3, resolve=True)[source]
See
get_floquet_multipliers().Unlike that one, this also answers for an orbit discretized with
mode="bspline", which carries no explicit end-of-period degree of freedom and therefore has no structure for any of the Floquet routes to key off (see_sampled_onto_collocation()). Such an orbit is SAMPLED onto a collocation discretization for the computation and put back afterwards, unchanged - so what comes back is the spectrum of the collocation discretization of this orbit, to that discretization’s accuracy.- Parameters:
sampling_NT (
int|None) – Time points of the sampling, or None for this orbit’s own count raised to what collocation needs (a multiple of the order, and even - see_collocation_time_steps()). Only used when a sampling is taken.sampling_order (
int) – Collocation order of the sampling.resolve (
bool) – Re-solve the sampled orbit before taking the multipliers. On, because a B-spline orbit satisfies the B-spline equations and not the collocation ones, so without it the variational operator is evaluated at a state that is not a collocation orbit and the multipliers carry an extra error of the size of that residual.
Note that after a SAMPLED call the problem’s last eigenvectors are laid out over the collocation discretization (
sampling_NT*nbase+1entries), not over this orbit’s.
- classmethod load_from_state(problem, statefile, restore_tangent=True, **loadkwargs)[source]
Load a stored periodic orbit - state dump plus companion - onto
problem.This is what makes a point tagged in the bifurcation GUI usable from a script of its own:
output/tag01/holdsstate.dump, the companion with the rest of the cycle, and the mesh files both refer to, so:orbit=PeriodicOrbit.load_from_state(problem,"output/tag01/state.dump") print(orbit.get_T()) orbit.output_orbit("cycle")
The problem must be set up (
initialise()) and have the same equations; the mesh comes from the dump. Afterwards the orbit handler is installed, i.e. the problem solves for the whole cycle at once - usewith(or__exit__()) to hand the cycle over to a transient run, ordeactivate_bifurcation_tracking()to drop it.- Parameters:
statefile (
str) – The state dump. Its companion is found beside it, by name.restore_tangent (
bool) – Put the stored arclength tangent of the AUGMENTED system back, so that continuing the branch goes on the way it was going. Off means the next arclength step picks its own direction.loadkwargs (
Any) – Passed on toProblem.load_state()for the base dump.
- Return type:
- class pyoomph.generic.problem.Problem[source]
Bases:
ProblemA class representing a problem in the pyoomph library.
This class provides methods and attributes for defining and solving a problem. Usually, in the
__init__()method, you define any parameters with default settings. The problem itself is defined by thedefine_problem()method, where you define the equations and the mesh(es). After creation of an instance, you can solve the problem by calling therun()method (transient solves) or thesolve()method (stationary solve). Outputs (potentially with plots) can be generated by calling theoutput()method.- additional_equations
Additional equations for the problem.
- Type:
Union[Literal[0], EquationTree]
- continuation_data_in_states
Flag indicating whether to store continuation data in the states.
- Type:
bool
- default_1d_file_extension
Default file extension for 1D files.
- Type:
Union[Literal[“txt”, “mat”], List[Literal[“txt”, “mat”]]]
- default_spatial_integration_order
Default spatial integration order.
- Type:
Union[int, None]
- default_timestepping_scheme
Default timestepping scheme.
- Type:
Literal[“BDF2”, “BDF1”, “Newmark2”]
- eigen_data_in_states
Flag indicating whether to store eigen data in the states.
- Type:
Union[int, bool]
- eigenvector_position_scale
Scaling factor for eigenvector positions.
- Type:
float
- extra_compiler_flags
Extra compiler flags for the problem.
- Type:
List[str]
- ignore_command_line
Flag indicating whether to ignore command line arguments.
- Type:
bool
- latex_printer
LaTeX printer for the problem.
- Type:
Optional[LaTeXPrinter]
- plot_in_dedicated_process
Flag indicating whether to plot in a dedicated process.
- Type:
bool
- remove_macro_elements_after_initial_adaption
Flag indicating whether to remove macro elements after initial adaption.
- Type:
Union[bool, Literal[“auto”]]
- scaling
Dictionary of scaling factors.
- Type:
Dict[str, Union[str, ExpressionOrNum]]
- states_compression_level
Compression level for the states.
- Type:
Union[int, None]
- timestepper
Timestepper for the problem.
- Type:
- write_states
Flag indicating whether to write states.
- Type:
bool
- property DTSF_max_increase_factor
Maximum possible increase factor of the time step dt between successive time steps in adaptive time stepping.
- property DTSF_maximum_dt
Maximum desired time step during adaptive time stepping.
- property DTSF_min_decrease_factor
Minimum allowed decrease factor of the time step dt between successive time steps in adaptive time stepping; a proposed reduction below this factor causes the time step to be rejected and retried with a smaller dt.
- property DTSF_minimum_dt
Minimum desired time step during adaptive time stepping; the solve aborts with an error if dt falls below this value.
- __init__()[source]
Initialise the problem object. After calling
super().__init__(), you should set the default parameters for the problem. Afterwards, the user can change them before solving the problem.
- abort_current_run()[source]
If called within a run(…) statement, e.g. from some action_{after/before}_* methods, the run will abort
- actions_after_transient_solve()[source]
Dispatched once per accepted timestep, at the end of
solve()with atimestep, after any spatial adaptation and after temporal adaptivity has settled on a step it accepts.This is where anything that must advance exactly once per step in time belongs.
actions_after_newton_solve()cannot serve that purpose: it also fires for stationary solves, for each arclength continuation step, for every discarded temporal retry, and once per adaptation level.
- actions_before_eigen_solve(force_reassign_eqs=False, must_not_renumber=False)[source]
Prepare the mode-dependent state of an eigensolve.
must_not_renumberis set while a bifurcation tracker is installed: the tracker cached the base equation count and pushed dof pointers built against the current numbering, so a reapply_boundary_conditions() here would leave it describing a problem that no longer exists. The mode is then refused rather than accommodated – see the snapshot dance below.
- actions_before_newton_step(self) None
Hook, overridable in Python, called before each Newton step.
- Return type:
None
- activate_bifurcation_tracking(parameter, bifurcation_type=None, blocksolve=False, eigenvector=None, omega=None, azimuthal_mode=None, cartesian_wavenumber_k=None, eigenvalue_for_branch_tracking=None, eigenvector_scaling='unit')[source]
Activates bifurcation tracking for the specified parameter and bifurcation type. Subsequent calls of solve(…) and arclength_continuation(…) will then track the bifurcation.
- Parameters:
parameter (
str|GiNaC_GlobalParam|None) – The parameter to change in order to find the bifurcation. If None, we track the current eigenbranch, i.e. Re(lambda) will be found and is not necessarily 0.bifurcation_type (
Optional[Literal['hopf','fold','pitchfork','azimuthal','cartesian_normal_mode','real','complex','normal_mode']]) – The type of bifurcation to track. Defaults to None, i.e. auto-detect.blocksolve (
bool) – Refused. Passing True raises: upstream’s block linear solvers cast the installed handler to oomph-lib’s own FoldHandler/HopfHandler with a static_cast, which pyoomph’s handlers are not, so the fold and Hopf paths segfault and every other type ignores the flag. See the error message and dev_docs/mpi_augmented_systems.md section 4.eigenvector (
NDArray[float64] |NDArray[complex128] |int|None) – The eigenvector to use for tracking. Defaults to None, which means the eigenvector corresponding to the eigenvalue with largest real part. Can be either an index or a custom vector.omega (
float|None) – The omega value for Hopf bifurcation tracking. Defaults to None, then it will be Im(lambda).azimuthal_mode (
int|None) – The azimuthal mode for azimuthal bifurcation tracking. Defaults to None.eigenvector_scaling (
Literal['unit','auto']) – How the eigenvector normalization constraint is scaled. “unit” (default) keeps the historical behaviour: the eigenvector guess is normalized to unit length and the constraint reads c.y = 1, so on a problem with N degrees of freedom the eigenvector unknowns are of order 1/sqrt(N). “auto” instead normalizes the guess by its largest entry and moves the constraint’s right-hand side to match, keeping the eigenvector unknowns and the constraint row of order one however large the problem is. This is recommended for very large systems. It does not move the bifurcation itself, only the (always arbitrary) amplitude of the reported eigenfunction.
- activate_eigenbranch_tracking(branch_type=None, eigenvector=None, eigenvalue=None)[source]
Activates eigenbranch tracking for the specified eigenbranch type. Subsequent calls of solve(…) and arclength_continuation(…) will then track the eigenbranch. This is similar to bifurcation tracking, but it does not adjust a parameter to find a bifurcation, i.e. where Re(lambda)=0. Instead, it starts with a eigenvalue/eigenvector pair. Once activated, you can follow the eigenbranch by calling arclength_continuation(…). At each step, the eigenvalue/eigenvector pair will be updated and is available via get_last_eigenvalues()[0] and get_last_eigenvectors()[0].
- Parameters:
branch_type (
Optional[Literal['real','complex','normal_mode']]) – The type of eigenbranch to track. Defaults to None, i.e. auto-detect.eigenvector (
NDArray[float64] |NDArray[complex128] |int|None) – The previously calculated eigenvector index to use for tracking. Defaults to None, i.e. the eigenvector at index zero.
- activate_periodic_orbit_handler(T, history_dofs=[], mode='collocation', order=2, GL_order=-1, T_constraint='phase')[source]
Activates periodic orbit tracking based on history dofs. Use
set_current_dofs()to set the first time point of the orbit guess. The other time points must be shipped with the history_dofs argument.- Parameters:
T (
Expression|GiNaC_GlobalParam|int|float) – The guessed period of the orbithistory_dofs – The history dofs to use for the orbit tracking. Must be non-empty.
mode (
Literal['collocation','floquet','bspline','central','BDF2']) – The mode of the time discretization.order (
int) – The order of the time discretization.GL_order (
int) – The Gauss-Legendre order for some time discretization modes. Defaults to -1, meaning a suitable integration order is chosen automatically based on the interpolation order.T_constraint (
Literal['plane','phase']) – The constraint for the period. Defaults to “phase”.
- Returns:
The resulting periodic orbit. Note that it still must be solved, i.e. it is only the provided guess at this stage.
- Return type:
- adapt(self) tuple[int, int]
Perform spatial mesh adaptation (refinement/unrefinement) on all refineable submeshes. Returns (n_refined, n_unrefined).
- Return type:
tuple[int,int]
- adaptive_resolve_recovery: AdaptiveResolveRecovery | None
What to do when the Newton solve after a spatial adaptation fails. By default
None, i.e. such a failure ends the run, since the pre-adapt mesh is gone by then and nothing can be recovered. Set anAdaptiveResolveRecoveryto snapshot the state before each adaptation and fall back to it instead.
- adaptive_unsteady_newton_solve(self, dt_desired: float, epsilon: float) float
- adaptive_unsteady_newton_solve(self, dt_desired: float, epsilon: float, shift_values: bool) float
Overloaded function.
adaptive_unsteady_newton_solve(self, dt_desired: float, epsilon: float) -> float
Attempt to advance time by
dt_desired, halving the time step on non-convergence until it succeeds or falls below the minimum time step.epsilonis the desired magnitude of the global temporal error at each time step. Always shifts the time history values. Returns the suggested next time step, to be passed again asdt_desired.adaptive_unsteady_newton_solve(self, dt_desired: float, epsilon: float, shift_values: bool) -> float
Same as the two-argument overload, but
shift_valuescontrols whether the time history values are shifted.- Return type:
float
- add_equations(eqs)[source]
Add equations to the system. Should be called within the define_problem() method.
- Parameters:
eqs (
EquationTree) – The equations (restricted to a domain) to add to the problem.- Return type:
None
- add_global_dof(name, equation_contribution=0, *, scaling=None, testscaling=None, domain='globals', only_for_stationary_solve=False, initial_condition=None, set_zero_on_normal_mode_eigensolve=True)[source]
Add a global degree of freedom, e.g. a global Lagrange multiplier to the problem.
- Parameters:
name (
str) – The name of the degree of freedom.equation_contribution (
Expression|GiNaC_GlobalParam|int|float) – The global contribution of the degree of freedom to its equation. Defaults to 0.scaling (
Expression|GiNaC_GlobalParam|int|float|None) – The scaling factor for the degree of freedom. Defaults to None.testscaling (
Expression|GiNaC_GlobalParam|int|float|None) – The scaling factor for the test function. Defaults to None.domain (
str) – The domain to which the degree of freedom belongs. Defaults to “globals”.only_for_stationary_solve (
bool) – Whether the degree of freedom is only used for stationary solves, if set, it will be 0 and pinned during transient solves. Defaults to False.initial_condition (
Expression|GiNaC_GlobalParam|int|float|None) – The initial condition for the degree of freedom. Defaults to None.set_zero_on_normal_mode_eigensolve (
bool) – Deactivate this dof for normal mode eigensolves. Defaults to True.
- Returns:
A tuple containing the variable and test function associated with the degree of freedom.
- Return type:
tuple
- add_mesh(mesh)[source]
Adds a mesh to the problem. Based on the domain and boundary names of the mesh, equations can be added by using the same domain and boundary names.
- Parameters:
mesh (
TypeVar(_TypeVarMeshTemplate, bound=MeshTemplate)) – Any mesh instance to be added (1d, 2d, 3d, etc.)- Return type:
TypeVar(_TypeVarMeshTemplate, bound=MeshTemplate)- Returns:
Returns itself for chaining
- add_mesh_template(mesh)[source]
Same as self+=mesh or self.add_mesh(mesh). Will be deprecated soon.
- Return type:
TypeVar(_TypeVarMeshTemplate, bound=MeshTemplate)
- add_sub_mesh(self, mesh: pyoomph._pyoomph_core.Mesh) int
Add
meshas a sub-mesh of the problem; combine all sub-meshes into the global mesh afterwards via build_global_mesh().- Return type:
int
- add_time_stepper_pt(self, time_stepper: pyoomph._pyoomph_core.TimeStepper) None
Add a time stepper to the problem, automatically (re-)sizing the Time object to hold the required number of history levels.
- Return type:
None
- after_bifurcation_tracking_step(self) None
Hook called after each solve step while bifurcation tracking is active, to update internally cached tracking information.
- Return type:
None
- property always_take_one_newton_step
If True, a Newton step is always taken even if the initial residuals are already below the required tolerance.
- analyse_jacobian_singularity(k=2, ntop=6, quiet=False, **kwargs)[source]
Find out which degrees of freedom and which equations make the Jacobian singular, which is the usual reason why Newton’s method stalls after a boundary condition has been applied twice, e.g. an
EnforcedDirichleton a contact line where a kinematic boundary condition is already acting.It prints the dofs left undetermined, the equations that conflict, and everything sitting on the node that carries the singular mode. The problem must be initialised, but it does not have to be solved first: an over-constraint is present in the Jacobian of the initial condition already.
The cost is one sparse LU plus a few triangular solves, so a good deal less than a nullspace computation. See
analyse_jacobian_singularity()for the remaining arguments.- Parameters:
k (
int) – Number of singular modes to report.ntop (
int) – Maximum number of dofs listed per singular vector.quiet (
bool) – Only return the result instead of printing a report.
- Returns:
The modes and the verdict, see
JacobianSingularityInfo.
- property apply_Dirichlet_BCs_by_dof_removing
When set to True, we apply Dirichlet boundary conditions by removing the corresponding dofs from the system. This yields a smaller matrix, but iterative solvers using strided block matrices will run into troubles. If False, all DirichletBCs are kept in the dof vector and the matrix is augmented accordingly.
- arclength_continuation(parameter, step, *, spatial_adapt=0, max_ds=None, max_newton_iterations=None, newton_relaxation_factor=None, newton_solver_tolerance=None, min_ds=None, dof_direction=None, globally_convergent_newton=False)[source]
Perform arclength continuation on the basis of a given parameter.
- Parameters:
parameter (
str|GiNaC_GlobalParam) – The parameter to perform arclength continuation on.step (
float) – The step for the continuation.spatial_adapt (
int) – The level of spatial adaptation. Defaults to 0.max_ds (
float|None) – The maximum step size. Defaults to None.max_newton_iterations (
int|None) – The maximum number of Newton iterations. Defaults to None.newton_relaxation_factor (
float|None) – The relaxation factor for the Newton solver. Defaults to None.newton_solver_tolerance (
float|None) – The tolerance for the Newton solver. Defaults to None.min_ds (
float|None) – The minimum step size. Defaults to None.dof_direction (
list[float] |None) – The direction of degrees of freedom. Defaults to None.globally_convergent_newton (
bool|None) – Whether to use globally convergent Newton solver. Defaults to False.
- Returns:
The new step size for the continuation.
- Return type:
float
- are_hessian_products_calculated_analytically(self) bool
Whether Hessian-vector products are currently set to be computed analytically via the generated code (see set_analytic_hessian_products()), rather than by finite differences.
- Return type:
bool
- assemble_eigenproblem_matrices(self, sigma_r: float) tuple[int, int, int, numpy.ndarray[dtype=float64], numpy.ndarray[dtype=int32], numpy.ndarray[dtype=int32], int, int, numpy.ndarray[dtype=float64], numpy.ndarray[dtype=int32], numpy.ndarray[dtype=int32]]
Assemble the mass matrix M and Jacobian J of the generalized eigenproblem (e.g. for a shift-invert eigensolver with real shift
sigma_r). Both are returned exactly as they enter the residualR(U, dU/dt) = 0, i.e.J = dR/dUandM = dR/d(dU/dt), so the eigenvalue problem they define islambda M x + J x = 0for a perturbation growing likeexp(lambda*t). Callers that want the usualA x = lambda M xform must therefore negate J, as the eigensolvers do. Returns (n, M_nnz, M_nrow_local, M_values, M_column_index, M_row_start, J_nnz, J_nrow_local, J_values, J_column_index, J_row_start), both matrices in local compressed sparse row (CSR) format.- Return type:
tuple[int,int,int,NDArray[float64],NDArray[int32],NDArray[int32],int,int,NDArray[float64],NDArray[int32],NDArray[int32]]
- assemble_jacobian(with_residual=True, which_one='', global_csr=True)[source]
Assemble the Jacobian (and optionally the residual vector) as a scipy sparse matrix.
- Parameters:
with_residual (
bool) – Also return the residual vector, as (residuals, Jacobian).which_one (
str) – Name of the residual/Jacobian combination to assemble. Defaults to the one currently active.global_csr (
bool) – Return the whole (n x n) Jacobian on every process. Under mpirun oomph row-partitions the matrix even without –distribute, so this costs an allgather and replicates the matrix on each rank. Pass False to get this rank’s row block instead, shaped (nrow_local, n) with global column indices - cheaper, but the caller then has to know its own first_row. Irrelevant without MPI, where the two agree.
- Return type:
csr_matrix|tuple[NDArray[float64],csr_matrix]- Returns:
The Jacobian, or (residuals, Jacobian) if with_residual. The residuals are always the full global vector, irrespective of global_csr.
- assembly_handler_pt(self) pyoomph._pyoomph_core.AssemblyHandler
Return the AssemblyHandler currently used to assemble residuals and Jacobians, e.g. a bifurcation-tracking handler if one is active.
- Return type:
AssemblyHandler
- assign_eqn_numbers(self, assign_local_eqn_numbers: bool = True) int
(Re-)assign the global equation numbers to all degrees of freedom of the problem. Must be called whenever the problem structure (meshes, pinning, …) changes. Returns the total number of degrees of freedom.
- Return type:
int
- assign_initial_values_impulsive(self, dt: float) None
- assign_initial_values_impulsive(self) None
Overloaded function.
assign_initial_values_impulsive(self, dt: float) -> None
Initialize data and nodal positions to simulate an impulsive start from the current configuration, also setting the initial and previous time step to
dt.assign_initial_values_impulsive(self) -> None
Initialize data and nodal positions to simulate an impulsive start from the current configuration/solution.
- Return type:
None
- automatically_remove_dofs_without_equations: bool
After analyzing the Jacobian, a field with an empty Jacobian row will be pinned automatically
- backup_state(quiet=True)[source]
Write the full state of the problem to a memory buffer, so that it can be restored with load_state. This is a convenience wrapper around save_state that uses an in-memory stream instead
- Parameters:
quiet (
bool) – If True, suppresses output messages during the backup process. Default is True.- Returns:
A binary stream containing the serialized state of the problem.
- Return type:
IO[bytes]
- build_global_mesh(self) None
Combine all sub-meshes added via add_sub_mesh() into the problem’s global mesh.
- Return type:
None
- call_load_balance_in_initial_adaption
In distributed runs, we call load balance after each non-uniform adaptions
- check_interface_conformity(throw_on_mismatch=False, when='')[source]
Count boundary facets of a coupled interface that have no counterpart on the opposite side.
Zero means the two sides are conforming and the opposite-element matcher will succeed. A non-zero result names the offending facets by position and says, for each, which side is the coarser one. Collective under MPI: every process must call it.
- Return type:
int
- check_mesh_integrity: bool | Literal['initially']
Checks whether the elements in the meshes are nicely oriented (facing) so that refinement works as it should. Can be only done once initially or at each refinement step
- classify_bifurcation(parameter=None, eigenindex=0, assume=None, fd_eps=None)[source]
Normal form of the bifurcation the problem is currently sitting at.
The returned dict names the bifurcation in
["type"]-"fold","transcritical","pitchfork"or"hopf"- and, for the ones that have a second branch, carries the predictorsswitch_branch()uses to step onto it.Call it at a located bifurcation, i.e. after
activate_bifurcation_tracking()and asolve(), or wherever the last computed eigenvalue is the critical one. With bifurcation tracking still active the critical eigenpair is already to hand; without it the eigenproblem is solved here first.Needs an analytic Hessian, so the problem must have been set up with
setup_for_stability_analysis(analytic_hessian=True).Refused at a bifurcation of an azimuthal
m != 0or Cartesiank != 0normal mode: the normal form would be the base-mode Hessian contracted with a mode-meigenvector, and the branch it describes cannot be represented in these degrees of freedom.- Parameters:
parameter (
str|GiNaC_GlobalParam|None) – The parameter the bifurcation is in. Defaults to the one being tracked.eigenindex (
int) – Which computed eigenpair is the critical one. Defaults to the first.assume (
str|None) –"fold"or"branch_point"to decide that question rather than have it read off the normal form. Worth passing whenever the branch itself already answers it - a continuation that walked THROUGH the point without the parameter turning around did not pass a fold."pitchfork"or"transcritical"likewise force the second decision, which the problem’s symmetry usually answers better than the numbers do - note that an imperfect pitchfork, one whose symmetry is broken by an inexact boundary condition or a non-symmetric mesh, genuinely IS a transcritical and is now reported as one.fd_eps (
float|None) – Relative step of the finite difference that supplies the third derivative (there is none in the code generator, sob3has to come from a difference of the analytic Hessian). Defaults to1e-5, near theeps_mach**(1/3)optimum.
- Return type:
dict[str,Any]- Returns:
The normal-form dictionary.
- condense_dofs(field, *, values=None, part='all')[source]
Select degrees of freedom that static condensation may eliminate from the linear system.
The equation-tree way of saying this is
StaticCondensation, which is the recommended interface -eqs += StaticCondensation(velocity="bubble", pressure=[1,2])states the selection on the domain it belongs to and switches the feature on by itself. This method is the problem-level plumbing underneath it, useful when the selection is decided outside the equations.Experimental. Static condensation eliminates element-local unknowns from the Jacobian before it reaches the linear solver and reconstructs them after the Newton update. It is exact - the solution is the same, iteration by iteration - but only Newton solves benefit: residual evaluations, eigenvalue and Hessian assemblies, and arclength continuation always see the full system, while Jacobian reuse and the globally convergent (line search) Newton method are refused with an error rather than ignored. Distributed (
--distribute) runs are supported; a selection whose coupled block would be split across ranks is refused, collectively, and a replicated MPI run (mpirunwithout--distribute) is refused too.This only declares a rule. Unlike
StaticCondensation, it does not switch condensation on: setuse_static_condensation=Truefor that. Rules are stated in terms of a domain and a field, so they survive mesh adaptation and remeshing, and several rules can be added, their selections being unioned. Pinned values are never selected.The classical Crouzeix-Raviart elimination needs two rules, and needs both: the bubble velocities and the gradient modes of the DL pressure are only invertible together, and the constant pressure mode must stay a global unknown (taking it as well is refused, with an explanation):
problem.condense_dofs("domain/velocity", part="bubble") problem.condense_dofs("domain/pressure", values=[1,2]) # [1,2,3] in 3d problem.use_static_condensation = True
- Parameters:
field (
str) – Full path of the field, i.e."domain/fieldname"(or"domain/subdomain/fieldname"). A vector field may be given by its base name, e.g."domain/velocity", which selects all of its components.values (
list[int] |None) – Restrict the selection to these value indices of the elemental data, e.g.[1,2]for the gradient modes of a DL pressure in 2d. Defaults to all values.part (
str) –"all"/"internal"for an elemental (DL/D0/DG) field,"bubble"for the cell-interior bubble nodes of a nodal C1TB/C2TB field, or"DL_gradients"for every value of a"DL"field except the constant, i.e.values=[1,2]in 2d and[1,2,3]in 3d, taken from the dimension of the domain rather than from the script. Defaults to"all".
- Return type:
None
- condense_element_private_dofs(domain=None)[source]
Select every elemental (internal) degree of freedom that no other element reads for static condensation.
The equation-tree way of saying this is
eqs += StaticCondensation(), i.e. aStaticCondensationwithout arguments, which is restricted to the domain it is added to and switches the feature on by itself. This method is the problem-level plumbing.Experimental - see
condense_dofs()for what that means. This is the convenient rule for auxiliary fields projected onto a discontinuous space (DL/D0/DG), e.g. a dissipation or a stress measure computed for output: they are unknowns of the system but couple to nothing outside their element, so condensing them removes them from the matrix the solver factorises without changing anything else.Internal data adopted as external data elsewhere - by an interface element on a free surface, or by an interior-facet DG coupling - is excluded, since such a dof is not element-local at all. That test is always made against the whole problem, even when
domainrestricts which dofs are considered. (A dof named explicitly bycondense_dofs()is not excluded this way; the elimination handles those correctly too, this rule simply has no way of knowing whether they were meant.) Likecondense_dofs(), this only declares a rule;use_static_condensationis a separate switch.- Parameters:
domain (
str|None) – Restrict the rule to this domain. Defaults to every bulk domain.- Return type:
None
- continue_from_outdir(old_out_dir, statenumber=-1, ignore_outstep=True)[source]
Loads a previous state from another output directory. Make sure the scripts are in all specifications of equations, meshes, parameters, settings etc.
- Parameters:
old_out_dir (
str) – Old output directorystatenumber (
int) – Which state to load. A negative value is an index into the state files sorted by name, so the default -1 is the last one. A non-negative value is the output step, i.e. the number in thestate_NNNNNN.dumpfile name. (The asymmetry is historical.)ignore_outstep (
bool) – Do not load the outstep (default: True)
- create_eigendynamics_animation(outdir, plotter, eigenvector=0, init_amplitude=None, max_amplitude=None, numperiods=1, numouts=25, phi0=0)[source]
Creates an animation of the eigenfunction dynamics. The eigenfunction is animated by varying the time and the amplitude of the eigenfunction, which is added to the degrees of freedom at each time. All images are saved in the specified output directory (relative to the output directory of the problem). The plotter is used to create the images. Azimuthal instabilities will automatically mirror the eigenfunction to the left in the appropriate way.
- Parameters:
outdir (
str) – Output directory for the animation images relative to the output directory of the problem.plotter (
MatplotlibPlotter) – Plotter class to use for the animation.eigenvector (
int) – Optional index of the eigenfunction to animate. Defaults to 0.init_amplitude (
float|None) – Initial amplitude of the eigenperturbation. If this andmax_amplitudeis not provided, the amplitude is set to 1. Defaults to None.max_amplitude (
float|None) – Maximum amplitude of the eigenperturbation. If this is provided, the amplitude is set to this value at the beginning and decreases over time (eigenvalue has negative real part) or will reach this amplitude at the end of the considered time (eigenvalue has positive real part). Defaults to None.numperiods (
float) – Number of periods to animate. For purely real eigenvalues, the characteristic time is given by the real part. Defaults to 1.numouts (
int) – Number of output steps. Defaults to 25.phi0 (
float) – Initial phase. Defaults to 0.
Works on a mesh distributed with
--distributeas well: the perturbation that makes a frame is applied by every process, not by the drawing one alone (seepyoomph.meshes.meshdatamerge.merge_perturbed_global_mesh_data), and plotted tracers are gathered from all processes as well.
- create_text_file_output(filename, header=None, relative_to_output_dir=True)[source]
Creates a
NumericalTextOutputFile. By default, in the output directory.- Parameters:
filename (
str) – File nameheader (
list[str] |None) – Header of the file Defaults to None.relative_to_output_dir (
bool) – If True, the file is created in the output directory. Defaults to True.
- Return type:
- deactivate_bifurcation_tracking()[source]
Deactivate bifurcation tracking. Afterwards, the problem can be solved as usual.
- debug_analytic_hessian_by_fd(epsilon=1e-05, num_vectors=2, seed=1, verbose=False, only_domains=None)[source]
Check the analytically generated Hessian against finite differences, element by element.
For each element this forms random vectors Y and C and compares the analytic Hessian-vector product
d2R_i/(du_j du_k) Y_i C_kagainst a finite difference of the analytic Jacobian along C. It therefore validates the Hessian only relative to the Jacobian; combine it withequation_compilation_flags.debug_jacobian_epsilon, which validates the Jacobian against finite differences of the residual, to pin down the whole chain.Requires the analytic Hessian to have been generated, i.e.
setup_for_stability_analysis(analytic_hessian=True)before initialisation.- Parameters:
epsilon (
float) – entries whose discrepancy exceeds this are printed. Also the threshold this method raises on, unless it is <= 0.num_vectors (
int) – how many C directions to test per element.seed (
int) – seed of the (deterministic) random vectors.verbose (
bool) – print a line per element rather than only the offenders.only_domains (
list[str] |None) – restrict to these mesh names; all meshes by default.
- Return type:
float- Returns:
The largest relative discrepancy found over all elements. Each entry is scaled by
max(1, |analytic|, |finite difference|), since the products range over many orders of magnitude and an absolute threshold would either drown in noise or miss the small entries.- Raises:
RuntimeError – if that discrepancy exceeds
epsilonandepsilon>0.
- define_global_parameter(**params)[source]
Define a single global parameter for the problem.
- Parameters:
**params (
float) – Exactly one keyword argument giving the parameter name and its initial value.- Returns:
The defined global parameter, which can be used in expressions.
- Return type:
Deprecated since version Passing: more than one keyword argument at once (to define several parameters in a single call, returning a tuple) still works, but is deprecated and emits a DeprecationWarning - call this once per parameter instead. Python’s type system cannot express a return type that depends on the runtime length of **params, so the declared return type here only reflects the single-parameter form; the multi-parameter form’s actual tuple return is not statically visible.
- define_named_var(**kwargs)[source]
Named vars are global expressions that are bound to a name.
You can e.g. use define_named_var(temperature=20*celsius) to define a temperature variable at problem level. When an equation tried to expand var(“temperature”) and no field “temperature” is defined on the current domain or its parents, the variable will be expanded by the global variable.
- define_problem()[source]
Define the problem by creating the mesh(es) and other necessary components.
This method should be overridden by subclasses to define the specific problem.
- deflated_continuation(deflation_alpha=0.1, deflation_p=2, perturbation_amplitude=0.5, max_newton_iterations=None, newton_relaxation_factor=None, use_eigenperturbation=False, skip_initial_solution=False, num_random_tries=1, max_branches=None, branch_continue_iterations=10, random_seed=0, distinct_solution_tolerance=1e-06, deflation_scale=None, **param_range)[source]
Scan over a parameter range and try to find multiple solutions for each parameter step by deflation This is an implemetation according to: The computation of disconnected bifurcation diagrams by Patrick E. Farrell, Casper H. L. Beentjes, Ásgeir Birkisson https://arxiv.org/pdf/1603.00809.pdf
- Parameters:
deflation_alpha (
float) – Shift of the deflation operator. Defaults to 0.1.deflation_p (
int) – Order of the deflation. Defaults to 2.perturbation_amplitude (
float) – Perturbation amplitude to move away from the previous solution. Defaults to 0.5.max_newton_iterations (
int|None) – Optional override of the number of Newton iterations during deflated search for additional solutions. Defaults to None.newton_relaxation_factor (
float|None) – Optional override of the Newton relaxation factor during deflated search for additional solutions. Defaults to None.use_eigenperturbation (
bool) – Whether to use eigen perturbation for the next solution during deflation. Defaults to False.num_random_tries (
int) – Number of random tries for finding solutions during deflation. Defaults to 1.random_seed (
int|None) – Seed of the random perturbations. Pass None for a different sequence every run. Defaults to 0.max_branches (
int|None) – Maximum number of branches to find. Defaults to None.branch_continue_iterations (
int) – Number of iterations for continuing branches. Defaults to 10.
- Yields:
A tuple of branch index (from 0 to …), the current parameter value and the current degrees of freedom (dofs) for the solution.
- deflated_solve_by_eigenperturbation(eigenindex=0, keep_deflation_active=False, perturbation_factor=1, deflation_alpha=0.1, deflation_power=2, *, max_newton_iterations=None, newton_relaxation_factor=None, newton_solver_tolerance=None, globally_convergent_newton=False)[source]
Tries to find another stationary solution by deflation. The procedure is implemented according to ‘Deflation techniques for finding distinct solutions of nonlinear partial differential equations’ by Patrick E. Farrell, Ásgeir Birkisson & Simon W. Funke, https://arxiv.org/pdf/1410.5620.pdf .
- Args:
deflation_alpha (float, optional): Shift of the deflation operator. Defaults to 0.1. deflation_p (int, optional): Order of the deflation. Defaults to 2. perturbation_amplitude (float, optional): Perturbation amplitude to move away from the previous solution. Defaults to 1. max_newton_iterations (Optional[int], optional): Optional override of the number of Newton iterations to try. Defaults to None. newton_relaxation_factor (Optional[float], optional): Optional override of the Newton relaxation factor. Defaults to None.
- desired_ndof: int | None
If set to an int, adaptation aims at this problem size instead of at a fixed error tolerance: the elements with the largest estimated errors are refined (or the smallest unrefined) until
ndof()is approximatelydesired_ndof. While it is set, min_permitted_error and max_permitted_error are outputs of the controller rather than inputs - they are recomputed before every adaptation and restored when this is set back to None.
- desired_ndof_damping: float
Fraction of the remaining gap the desired_ndof controller closes per adaptation step. Below 1 because 2:1 balancing refines further elements of its own accord, so a step that aimed exactly at the target would systematically overshoot.
- desired_ndof_max_growth: float
Largest factor by which the desired_ndof controller may grow ndof in a single adaptation step.
- desired_ndof_tolerance: float
Relative dead band of the desired_ndof controller. Inside it nothing is refined or unrefined, which is what makes the adaptation loops terminate instead of oscillating about the target.
- property dist_problem_matrix_distribution
one of “default”, “problem” or “uniform”. No-op without MPI support.
- Type:
How the Jacobian matrix rows are distributed across MPI processes in a distributed problem
- distribute()[source]
Distribute the problem’s meshes over the MPI processes.
Only checks the prerequisites here - the distribution itself is done by oomph-lib. The check must happen on all ranks (see
ensure_pymetis_available()).Leaves the problem undistributed (with a note) when there are fewer elements than processes, which is always the case for a pure ODE problem.
- do_call_remeshing_when_necessary: bool
Flag indicating whether to call remeshing when necessary. Can be set to
Falseto disable remeshing, e.g. when tracking bifurcations, it is better to check it manually invoking the remeshing methodremesh_handler_during_continuation()after each solve.
- dof_ordering
Layout(s) for the global dof numbering, e.g.
NodalBlockOrdering("domain/velocity_x","domain/velocity_y","domain/pressure"), or a list of layouts for a problem with several meshes. None (the default) keeps oomph-lib’s own numbering, which puts every nodal value of a mesh before any element-internal one. See pyoomph.generic.dof_ordering.
- dof_strings_to_global_equations(string_dof_set)[source]
Takes strings like
"domain/velocity_x"and returns a set of global equations. Entries that are already an int (a global equation number, as returned e.g. by some InterfaceEquations._get_forced_zero_dofs_for_eigenproblem implementations) are passed through as-is.- Parameters:
string_dof_set (
str|Iterable[str|int]) – Degrees of freedom you want to resolve to equation numbers- Returns:
Global equation set
- Return type:
Set[int]
- doubly_adaptive_unsteady_newton_solve(self, dt: float, epsilon: float, max_adapt: int, suppress_resolve_after_spatial_adapt_flag: int, first: bool, shift: bool = True) float
Advance time by
dt, first performing temporal adaptation (adjusting dt until the temporal error toleranceepsilonis met), then up tomax_adaptrounds of spatial adaptation without re-checking the temporal error. Iffirstis True, the initial conditions are re-assigned after mesh adaptation.shiftcontrols whether time history values are shifted. Returns the suggested next time step.- Return type:
float
- enable_store_local_dof_pt_in_elements(self) None
Enable storing direct pointers to the local degrees of freedom in each element (an internal performance optimization).
- Return type:
None
- enforce_interface_conformity()[source]
Make both sides of every coupled interface carry identical boundary facets.
oomph-lib adapts meshes one at a time, so two domains sharing an interface can refine different facets of it – and then the opposite-element matcher (which pairs interface elements by exact vertex-position sets) has nothing to pair up and throws. This refines the coarser side wherever they disagree, interleaved with each mesh’s own 2:1 balancing, until they agree. Refinement only, so it terminates.
The same fixed point also closes the VERTEX-connected balance: an element touching a coupled interface at a single vertex carries no facet, so none of the above can see it, and it would otherwise be left arbitrarily coarser than the interface beside it. Those refinements are not counted in the return value, since they are a grading closure inside one mesh rather than a conformity repair.
Collective under MPI: every process must call it. Returns the number of elements refined to repair facet conformity.
- Return type:
int
- ensure_dummy_values_to_be_dummy(self) None
Sanity-check/reset helper that ensures dummy (unused, placeholder) degrees of freedom hold their expected dummy value.
- Return type:
None
- equation_compilation_flags: EquationCompilationFlags
Code generation settings used on every domain, unless a domain (or one of its parent domains) overrides individual ones by adding an
EquationCompilationFlags. The values here are the defaults of the code generator itself (seeFiniteElementCodein src/codegen.cpp).
- experimental_distributed_remeshing: bool
Let
force_remesh()run on a distributed (--distribute) problem even in a configuration it refuses. Remeshing distributed works for the combination dev_docs/distributed_remeshing.md has built (recreation from merged boundary data, transfer pooled across the ranks); the parts that are not there yet are refused by name, because what they do instead is produce a plausible wrong answer rather than fail. This bypasses those refusals - to develop the remaining stages, or to accept the result.
- find_bifurcation_via_eigenvalues(parameter, initstep, shift=0, neigen=6, spatial_adapt=0, epsilon=1e-08, reset_arclength=False, max_ds=None, stay_stable_file=None, before_eigensolving=None, do_solve=True, azimuthal_m=None, normal_mode_k=None, eigenindex=0)[source]
Approximates a bifurcation point by bisecting on the basis of the eigenvalues. Must be called as a generator, e.g.
for parameter, eigenvalue in find_bifurcation_via_eigenvalues(...): print("Currently at ",parameter,eigenvalue)
- Parameters:
parameter (
str|GiNaC_GlobalParam) – The parameter to vary to find a bifurcation. It can be either a string representing the name of a global parameter or a global parameter directly.initstep (
float) – The initial step size for the bisection.shift (
None|float|complex) – The shift value for the eigenvalue problem. It can be a float, complex number, or None.neigen (
int) – The number of eigenvalues to compute.spatial_adapt (
int) – The spatial adaptation level.epsilon (
float) – The tolerance for determining the real part of an eigenvalue to be close to zero.reset_arclength (
bool) – Whether to reset the arc length parameters after each step.max_ds (
float|Callable[[float],float] |None) – The maximum step size for the continuation. It can be a float, a callable function that takes the current parameter value and returns a float, or None.stay_stable_file (
str|None) – The file path to save the state when the solution is stable. If it is unstable, the state is reloaded.before_eigensolving (
Callable[[float],None] |None) – A callable function to be called before solving the eigenvalue problem.do_solve (
bool) – Whether to solve the problem before continuation. If the solution does not depend on the parameter, it can be set to False.azimuthal_m – The azimuthal mode number if you want to find azimuthal perturbations.
- Yields:
param(float) – The current parameter value. eigenvalue (complex): The eigenvalue corresponding to the specified eigenindex.
- Raises:
RuntimeError – If the eigenindex is greater than or equal to neigen.
RuntimeError – If the initial solution is already unstable.
- floquet_artefact_tolerance: float = 1e-06
Distance from -1 (or +1) within which a Floquet multiplier is taken to BE the collocation artefact of _warn_about_collocation_artefact_multipliers rather than merely near it. The artefact is exact – verified to 1e-14 – so anything this loose is the artefact or is sitting on the bifurcation itself, and both are worth saying out loud.
- flush_sub_meshes(self) None
Remove all sub-meshes previously added via add_sub_mesh(), without deleting them.
- Return type:
None
- property force_jacobian_diagonal_entries
Whether an entry is kept on every diagonal of the Jacobian, even where no field pair contributes to it – as a Taylor-Hood pressure-pressure block does not, once the pattern is pruned by field coupling.
Reading it gives the EFFECTIVE value. By default that is whatever the active linear solver asks for via
requires_explicit_diagonal(), since needing a diagonal is a property of the factorisation and not of the problem: only some PETSc factorisations require one, MUMPS does not. Assigning to it overrides the solver in either direction and stops it being consulted (call_set_force_jacobian_diagonal_entries_auto()to undo). Stored zeros are not free – they change the matrix a direct solver sees, hence its pivoting. Only has an effect together withkeep_structural_zeros.Setting
apply_Dirichlet_BCs_by_dof_removing = Falsealso forces the diagonal, and that one cannot be overridden: the constrained row’s identity diagonal is only written where the pattern already has a slot for it, so without it a Dirichlet condition on a field with no self-coupling gives an identically zero row.
- generate_and_compile_bulk_element_code(self, my_element: pyoomph._pyoomph_core.FiniteElementCode, code_trunk: str, suppress_writing: bool, suppress_compilation: bool, bulkmesh: pyoomph._pyoomph_core.Mesh, quiet: bool, extra_flags: collections.abc.Sequence[str]) pyoomph._pyoomph_core.DynamicJITCode
Generate the C source code for the symbolic finite element definition
my_element(writing it tocode_trunk.c unlesssuppress_writingis True), compile it with the problem’s C compiler (unlesssuppress_compilationis True, passingextra_flagsto the compiler) and load the resulting shared library, binding it tobulkmesh. Returns the resulting DynamicJITCode.quietsuppresses progress output.- Return type:
DynamicJITCode
- get_arc_length_parameter_derivative(self) float
Return the current derivative of the continuation parameter with respect to arclength.
- Return type:
float
- get_arc_length_theta_sqr(self) float
Return theta^2, the weighting parameter that controls the proportion of the arclength taken up by the continuation parameter.
- Return type:
float
- get_arclength_dof_current_vector(self) numpy.ndarray[dtype=float64]
Return the degrees of freedom at the last converged point on the arclength continuation branch.
- Return type:
NDArray[float64]
- get_arclength_dof_derivative_vector(self) numpy.ndarray[dtype=float64]
Return the current derivative of the degrees of freedom with respect to arclength, as used/updated during arclength continuation.
- Return type:
NDArray[float64]
- get_bifurcation_tracking_mode(self) str
Return the currently active bifurcation tracking mode as a string (e.g. “fold”, “pitchfork”, “hopf”, “azimuthal”), or an empty string if no bifurcation is being tracked.
- Return type:
str
- get_cached_mesh_data(msh, nondimensional=False, tesselate_tri=True, eigenvector=None, eigenmode='abs', history_index=0, with_halos=False, operator=None, discontinuous=False, add_eigen_to_mesh_positions=True, global_mesh=False)[source]
Return the current data (i.e. values) of a mesh. These are cached in case they are required multiple times, e.g. for plotting and output. The cache is invalidated whenever we solve the problem or set some initial condition.
- Parameters:
msh (str | AnySpatialMesh) – Mesh object or mesh name
nondimensional (bool) – Getting nondimensional values instead of dimensional ones. Defaults to False.
tesselate_tri (bool) – Split quad elements into tris. Helpful e.g. for plotting via matplotlib, which requires triangular meshes. Defaults to True.
eigenvector (int | Sequence[int] | None) – If not None, we can obtain the values of the eigenfunction with the given index. Defaults to None.
eigenmode (MeshDataEigenModes) – Since eigenfunctions are in general complex, we must select the desired projection to real numbers here in case of eigenvector!=None. Defaults to “abs”.
history_index (int) – Set to 1 or 2 to access the previous time steps. Defaults to 0.
with_halos (bool) – Include halos to the output. Defaults to False.
operator (MeshDataCacheOperatorBase | None) – Apply an operator on the cache, e.g. to add eigenvectors or extrude it in 3d. Defaults to None.
global_mesh (bool) – Get the whole mesh instead of this process’ partition. Only makes a difference on a mesh distributed with –distribute, where it is a collective call that returns the merged data on rank 0 and None on all other ranks. Every rank must reach it - either by calling this with the same arguments, or by being inside a
run_with_global_mesh_data()block while rank 0 asks. Defaults to False.
- Returns:
The combined information of the mesh cache. None on the non-root ranks of a distributed mesh when global_mesh is set.
- Return type:
MeshDataCacheEntry | None
- get_ccompiler(self) pyoomph._pyoomph_core.CCompiler
Return the C compiler currently used to compile generated element code.
- Return type:
CCompiler
- get_coordinate_system()[source]
Get the coordinate system set at problem level.
- Returns:
The coordinate system at problem level.
- Return type:
BaseCoordinateSystem
- get_current_dofs(self) tuple[numpy.ndarray[dtype=float64], numpy.ndarray[dtype=bool]]
Return a tuple (values, is_positional) of numpy arrays with the current values of all degrees of freedom and, for each, whether it is a nodal position (mesh coordinate) degree of freedom rather than a field value.
- Return type:
tuple[NDArray[float64],NDArray[bool]]
- get_current_pinned_values(self, with_position_dofs: bool) numpy.ndarray[dtype=float64]
Return the current values of all pinned degrees of freedom; also includes pinned nodal position dofs if
with_position_dofsis True.- Return type:
NDArray[float64]
- get_current_time(dimensional=True, as_float=False)[source]
Get the current time of the problem.
- Parameters:
dimensional (
bool) – Flag indicating whether to return the dimensional time. Defaults to True.as_float (
bool) – Flag indicating whether to return the time as a float. Defaults to False.
- Returns:
The current time of the problem.
- Return type:
Expression|GiNaC_GlobalParam|int|float- Raises:
ValueError – If the problem is not initialized.
- get_dof_description()[source]
Returns two arrays containing the description of the degrees of freedom. The first is a list of dof-type indices, where the i-th entry is the type of the i-th degree of freedom. To resolve what each dof-type index means, the second array contains the type names of the degrees of freedom.
For a simple Poisson equation for a field
uon a line domain name"domain", the first returned array will contain numbers between 0 and 2 (dof-type indices), and the second array will contain the type names["domain/u", "domain/left/u", "domain/right/u"]. Note how the boundaries get their own dof-type indices.On a distributed (
--distribute) problem this is collective: each rank can only describe the dofs its own elements reach, so the per-rank answers are merged and every rank returns the same full-length description - which is what the callers need, since the residual vector they index it with is gathered as well.- Returns:
A pair of arrays containing the dof-type indices and the type names to classify the degrees of freedom.
- get_eigen_solver()[source]
Get the eigenproblem solver instance.
- Returns:
The currently used eigensolver
- Return type:
GenericEigenSolver
- get_equations(path, error_if_not_found=True)[source]
Return the equations added at the specified path.
- Parameters:
path (
str) – Path to the domainerror_if_not_found (
bool) – Raise an error if the domain path is not valid. Defaults to True.
- Raises:
RuntimeError – In case you specify a path where not equations are defined and error_if_not_found==True, you will get this error
- Returns:
The equations at the desired domain path. If error_if_not_found==False, it is None if there are no equations at the desired path specified.
- Return type:
BaseEquations|None
- get_floquet_multipliers(n=None, valid_threshold=10000, shift=None, ignore_periodic_unity=False, quiet=True, method='condensed', dense_threshold=2000, shift_invert=True, sigma=None)[source]
Calculates the Floquet multipliers of the currently tracked periodic orbit.
The orbit must be discretized in a mode that carries an explicit degree of freedom at the end of the period, i.e.
mode="collocation"(the default) ormode="floquet", and it must be solved before this is called.- Parameters:
n (
int|None) – Number of multipliers to compute. Defaults to all of them (the number of degrees of freedom of the underlying problem).valid_threshold (
float|None) – Only used bymethod="eigenproblem": eigenvalues above this magnitude are discarded as spurious.shift (
float|None) – Only used bymethod="eigenproblem": shift handed to the eigensolver.ignore_periodic_unity (
bool|float) – Remove the trivial multiplier 1 (which always exists, due to the time-shift invariance of the orbit) from the result. IfTrue, a tolerance of 1e-5 is used.quiet (
bool) – Suppress the eigensolver output, and the accuracy report of the trivial multiplier.method (
Literal['condensed','periodic_schur','eigenproblem']) –"condensed"(default) condenses the block bidiagonal orbit Jacobian into the monodromy matrix, which yields exactly the multipliers and nothing else."periodic_schur"computes the same multipliers by a periodic Schur (periodic QR) sweep, which never forms the product and is therefore more accurate for multipliers many orders of magnitude below the dominant one, at a considerably higher cost."eigenproblem"is the older formulation, which solves one large singular eigenproblem over all time points and filters the result.dense_threshold (
int) – Only used bymethod="condensed": above this number of degrees of freedom, only the dominant multipliers are computed by default, and the monodromy matrix is applied matrix-free rather than formed whenever few enough of them are wanted.shift_invert (
bool) – Only used by the matrix-free route: seek the multipliers nearsigmarather than by largest magnitude. Plain Arnoldi converges badly when they are clustered, which is the normal case for a PDE orbit.sigma (
complex|None) – The shift forshift_invert. Defaults to just outside the unit circle, where the stability question lives.
- Returns:
The Floquet multipliers, sorted by ascending magnitude.
- Return type:
NDArray[complex128]
- get_global_parameter(self, parameter_name: str) pyoomph._pyoomph_core.GiNaC_GlobalParam
Return a global parameter. If it does not exist, it will be added and initialized with value 0.
- Return type:
GiNaC_GlobalParam
- get_global_parameter_names(self) list[str]
Return the names of all global parameters currently defined on this problem, sorted alphabetically.
- Return type:
list[str]
- get_history_dofs(self, t: int) numpy.ndarray[dtype=float64]
Return the values of all degrees of freedom at history/time level
t(t=0: current values, t=1: previous time step, …).- Return type:
NDArray[float64]
- get_interpolate_new_interface_dofs(self) bool
Whether newly created interface degrees of freedom are interpolated from their neighbours (see set_interpolate_new_interface_dofs).
- Return type:
bool
- get_la_solver()[source]
Get the linear solver instance.
- Returns:
The currently used linear solver
- Return type:
GenericLinearSystemSolver
- get_last_eigenmodes_k()[source]
Get the cartesian normal mode numbers for the last computed eigenvalues.
- Returns:
Array containing the cartesian normal mode numbers corresponding to the eigenvalues.
- Return type:
NDArray[float64] |None
- get_last_eigenmodes_m()[source]
Get the azimuthal mode numbers for the last computed eigenvalues.
- Returns:
Array containing the azimuthal mode numbers corresponding to the eigenvalues.
- Return type:
NDArray[int32] |None
- get_last_eigenvalues(dimensional=False)[source]
Returns the last computed eigenvalues.
- Returns:
Eigenvalues as array.
- Return type:
NDArray[complex128]
- get_last_eigenvectors()[source]
Return the last computed eigenvector.
- Returns:
Eigenvectors as 2d array.
- Return type:
NDArray[complex128]
- get_last_jacobian_setup_time(self) float
Return the wall-clock time (in seconds) spent setting up the Jacobian in the most recent linear solve.
- Return type:
float
- get_last_linear_solver_solution_time(self) float
Return the wall-clock time (in seconds) spent in the linear solver during the most recent linear solve.
- Return type:
float
- get_last_residual_convergence(self) list[float]
Return the maximum residual recorded at the start of, and after each iteration of, the most recent Newton solve; useful for diagnosing convergence behavior.
- Return type:
list[float]
- get_mesh(name, return_None_if_not_found=False)[source]
Get the mesh at the desired domain path. Invokes initialization if the problem is not initialised!
- Parameters:
name (str) – Domain path of the mesh
return_None_if_not_found (bool) – If True, None will be returned if the given domain path is invalid. If False, an error will be raised in that case. Defaults to False.
- Raises:
RuntimeError – Raised if there is no mesh at the given domain path in case of return_None_if_not_found==False (default). Same happens if an ODE domain is tried to be accessed like this. Use get_ode() for this.
- Returns:
The mesh at the domain path. None can only be returned if return_None_if_not_found==True and the domain path is invalid.
- Return type:
AnySpatialMesh | None
- get_ode(name)[source]
Return the ODE object at the given domain path. Invokes initialization if the problem is not initialised!
- Parameters:
name (
str) – Domain path of the ODE- Raises:
RuntimeError – If the given domain path is invalid or a spatial mesh is defined at this domain, this error will occur.
- Returns:
The ODE object at the given domain path
- Return type:
- get_output_directory(relative_path=None)[source]
Return the output directory of the problem. Set it with set_output_directory(). Otherwise, it will default to the name of the invoked script minus the extension .py. Optionally, you can add a relative path to assemble e.g. a file name within the output directory.
- Parameters:
relative_path (
str|None) – If set, we join this relative additional path to the output directory. Defaults to None.- Returns:
The output directory of the problem (potentially joined with the additionally passed relative_path)
- Return type:
str
- get_parameter_derivative(self, parameter_name: str) numpy.ndarray[dtype=float64]
Return the derivative of the residual vector with respect to the global parameter
parameter_name(i.e. dR/dparam), evaluated at the current state.- Return type:
NDArray[float64]
- get_residual_scale_factor()[source]
The scalar the assembled residual is multiplied by; 1 unless deflation is active.
Called from C++ once per residual assembly, and only while
residual_scale_hook_active.- Return type:
float
- get_residuals(self) numpy.ndarray[dtype=float64]
Assemble and return the current residual vector (without the Jacobian) at the current state. On a distributed (MPI) problem, the residuals are gathered so that every process returns the same full-length vector.
- Return type:
NDArray[float64]
- get_scaling(s, none_if_not_set=False)[source]
Get the scaling factor for the problem variables for nondimensionalization.
- Parameters:
s (
str) – Name of the scale to get.none_if_not_set (
bool) – Returns None if this scaling is not set. Otherwise, the default scale 1 is returned. Defaults toFalse.
- Return type:
Expression|GiNaC_GlobalParam|int|float|None- Returns:
Scaling set by
set_scaling()or None ifnone_if_not_set==Trueand the scale is not set.
- get_second_order_directional_derivative(self, direction: collections.abc.Sequence[float]) numpy.ndarray[dtype=float64]
Return the second order directional derivative of the residuals along
direction, i.e. the contraction of the Hessian withdirectiontwice (a Hessian-vector-vector product).- Return type:
NDArray[float64]
- get_symmetric_hessian_assembly(self) bool
Whether Hessian assembly currently exploits its symmetry in the last two indices (see set_analytic_hessian_products()).
- Return type:
bool
- get_use_eigen_Z2_error_estimators(self) bool
Whether the Z2 error estimator uses the eigenvector flux set (see set_use_eigen_Z2_error_estimators).
- Return type:
bool
- gitignore_output: bool
Add a .gitignore with content “*” to output folders
- go_to_param(_param=None, *, reset_pars=True, startstep=None, call_after_step=None, final_adaptive_solve=False, max_newton_iterations=None, epsilon=1e-06, max_step=None, **kwargs)[source]
Perform arclength continuation in a parameter until we reach the desired value.
- Parameters:
reset_pars (
bool) – Whether to reset arc length parameters. Defaults to True.startstep (
float|None) – The initial step size for the parameter continuation. Defaults to None.call_after_step (
Callable[[float],None] |None) – A function to call after each step. If it returns “stop”, we stop any further continuation. Defaults to None.final_adaptive_solve (
bool|int) – Whether to perform a final adaptive solve. Defaults to False.max_newton_iterations (
int|None) – The maximum number of Newton iterations. Defaults to None.epsilon (
float) – The tolerance for considering as converged to the parametermax_step (
float|None) – The maximum step size for the continuation. Defaults to None.**kwargs (
float) – The parameter name and desired value.
- Raises:
RuntimeError – If more than one parameter is provided.
RuntimeError – If the specified parameter is not part of the problem.
- Return type:
None- Returns:
None
- guess_nearest_bifurcation_type(eigenvector=0)[source]
Guesses the nearest bifurcation type based on the last computed eigenvalues. This is only possible after calling solve_eigenproblem(…). It cannot guess e.g. pitchfork or transcritical bifurcations, only “hopf” or “fold” - or “azimuthal” if the last eigenvalues correspond to azimuthal modes m!=0. :returns: Guessed bifurcation type
- Return type:
Literal['hopf','fold','pitchfork','azimuthal','cartesian_normal_mode']
- initial_adaption_steps: None | int
Spatial adaption steps for the initial condition. If set to
None, we refine initially up tomax_refinement_level.
- initialise()[source]
Initializes the problem by performing the necessary setup and initialization steps. If not done before, this method is automatically called by several methods, e.g.
solve(),run()oroutput(). After initialization, you cannot change the problem anymore, except for global parameter values.- Raises:
RuntimeError – If the problem is already initialised or if a function that calls initialize is called during initialization.
- initialise_dt(self, dt: float) None
Set all time steps of all time steppers in the problem to
dtand (re-)assign their weights.- Return type:
None
- invalidate_cached_mesh_data(only_eigens=False)[source]
Mesh data is cached for potentially multiple usage (e.g. plotting and output to file). Whenever we change anything (e.g. changing values), we must hence invalidate the cache.
- Parameters:
only_eigens (
bool) – Only flush the cache of eigenfunctions, not of the current state. Defaults to False.
- inversion_remesh_dt_collapse: float
A step that reported an inversion counts as folded when it achieved less than this fraction of the last clean step. 1/16 is four halvings: an ordinary transient inversion costs one or two and stays well above it, while a fold goes to the dt floor and falls far below.
- inversion_remesh_max_retries: int
How many times one solve() call may remesh and retry after an inverted element before giving up. A domain that stays folded should fail loudly rather than loop.
- inversion_remesh_size_factors: list[float]
Element sizes to ask the remesher for on successive retries, as multiples of each template’s own
default_resolution. Retrying without varying anything cannot work - same geometry, same dt, same settings, so the same mesh - which is why a budget of 10 was measured to fail at exactly the same time as one of 3. The first retry keeps the template’s own sizes, so a fold a plain remesh does cure is cured as before; only the later ones differ. Entries beyond the last are the last.
- is_distributed(self) bool
Return whether the problem’s meshes are currently distributed across multiple MPI processes.
- Return type:
bool
- is_initialised()[source]
Returns whether the problem has been initialised or not.
- Returns:
True if already initialised, False otherwise
- Return type:
bool
- is_normal_mode_stability_set_up()[source]
Returns True when
setup_for_stability_analysis()has been called withazimuthal_stability=Trueoradditional_cartesian_mode=True. Can be used to e.g. set additional BCs for velocity_phi or similar.- Return type:
Union[Literal['azimuthal','cartesian'],Literal[False]]
- is_quiet(self) bool
Return whether output messages from the oomph-lib and pyoomph C++ core are currently suppressed.
- Return type:
bool
- is_stable_solution()[source]
Shortcut to check whether we have a stable solution. This is only possible after calling solve_eigenproblem(…).
- Return type:
bool
- iterate_over_multiple_solutions_by_deflation(deflation_alpha=0.1, deflation_p=2, perturbation_amplitude=0.5, max_newton_iterations=None, newton_relaxation_factor=None, use_eigenperturbation=False, skip_initial_solution=False, num_random_tries=1, keep_deflation_operator_active=False, random_seed=0, distinct_solution_tolerance=1e-06, deflation_scale=None)[source]
Tries to find multiple stationary solutions by deflation. The procedure is implemented according to ‘Deflation techniques for finding distinct solutions of nonlinear partial differential equations’ by Patrick E. Farrell, Ásgeir Birkisson & Simon W. Funke, https://arxiv.org/pdf/1410.5620.pdf .
- Args:
deflation_alpha (float, optional): Shift of the deflation operator. Defaults to 0.1. deflation_p (int, optional): Order of the deflation. Defaults to 2. perturbation_amplitude (float, optional): Perturbation amplitude to move away from the previous solution. Defaults to 0.5. max_newton_iterations (Optional[int], optional): Optional override of the number of Newton iterations to try. Defaults to None. newton_relaxation_factor (Optional[float], optional): Optional override of the Newton relaxation factor. Defaults to None. random_seed: Seed of the random perturbations. Pass None for a different sequence every run. Defaults to 0.
- Yields:
The found solutions as lists of degrees of freedom
- Return type:
Generator[NDArray[float64],None,None]
- property jacobian_structure_id
Identifier of the current Jacobian sparsity pattern. Anything derived from the pattern stays valid as long as this value is unchanged and non-zero. It is 0 whenever
keep_structural_zerosis off, since the pattern is then value-dependent and cannot be reused.
- property keep_structural_zeros
Whether the assembled Jacobian keeps entries that evaluate to exactly zero. By default they are dropped, which makes the sparsity pattern depend on the current degrees of freedom and hence change between Newton steps. Keeping them makes the pattern depend on the equation numbering alone, so linear solvers can reuse their symbolic phase across solves (see
jacobian_structure_id), and every diagonal entry is guaranteed to be present. Costs a few percent more nonzeros for single-physics problems, more for weakly coupled multi-physics ones.
- property keep_structural_zeros_in_mass_matrix
the mass matrix is typically several times sparser than the Jacobian (only fields carrying a time derivative contribute), so giving it the Jacobian’s pattern inflates it for no benefit – what a stable pattern buys is symbolic-factorisation reuse, and the operator being factorised is the Jacobian.
- Type:
Whether
keep_structural_zerosalso applies to the secondary matrices of a multi-matrix assembly, i.e. to the mass matrix of the eigenproblem assembly. Off by default and usually best left off
- property keep_temporal_error_below_tolerance
If True (default), a time step is rejected and retried with a smaller dt if the temporal error estimate after solving exceeds the requested tolerance.
- load_state(fname, ignore_outstep=False, relative_to_output=False, ignore_eigendata=False, ignore_continuation_data=False, additional_info={}, quiet=False)[source]
Restore a state written by save_state. Every rank reads the whole file for itself.
Collective under MPI, in two ways that both matter. The load itself already was - it rebuilds the global mesh and renumbers the equations - but the outcome was not: a rank that could not read the file unwound alone while the others went on into the next collective and waited there for good. So the outcome is agreed on here, and since that agreement is collective it is also the barrier that keeps a rank from overwriting or deleting the file while another one is still reading it.
- logfile_name: str | None
Name of the logfile (or None for no logfile), relative to the output directory
- property max_newton_iterations
Maximum number of Newton iterations for solving before giving up.
- max_permitted_error: float
Maximum error of all meshes for spatial adaptivity. If the error is above this threshold, we must refine locally.
- max_refinement_level: int
Maximum number of refinements of all meshes. After initialization, use set_max_refinement_level instead of this property.
- property max_residuals
if the maximum residual exceeds this value at any point during a Newton solve, the solver gives up.
- Type:
Maximum desired residual
- mesh_interpolator: type['BaseMeshToMeshInterpolator']
Which mesh-to-mesh interpolator to use whenever the meshes are rebuilt - remeshing,
force_remesh(),redefine_problem(), and the remesh handler used during continuation. Defaults toInternalInterpolator, which transfers by interpolation: it evaluates the old solution at each new node, which is fast and pointwise accurate.Set it to
ProjectionInternalInterpolatorto transfer by L2 projection instead. That is the better choice when the transferred quantity has to keep its integral - the projection conserves it, interpolation does not - at the cost of pointwise accuracy and one linear solve per history level. See dev_docs/mesh_point_locator.md.An explicit
interpolator=argument still wins where one is passed.
- mesh_pt(self) object
- mesh_pt(self, i: int) object
Overloaded function.
mesh_pt(self) -> object
Return the problem’s global mesh.
mesh_pt(self, i: int) -> object
Return the
i-th sub-mesh of the problem.- Return type:
object
- min_permitted_error: float
Minimum error of all meshes for spatial adaptivity. If the error is below this threshold, we may unrefine locally.
- min_refinement_level: int
Minimum refinement level of all meshes.
- property minimum_arclength_ds
Minimum desired value of the arclength step ds during arclength continuation.
- ndof(self) int
Returns the number of equations, i.e. degrees of freedom
- Return type:
int
- property newton_relaxation_factor
only a fraction (this value) of the full Newton correction is applied if less than 1 (default 1).
- Type:
Relaxation factor for the Newton method
- newton_solve(self, max_adapt: int = 0) None
Perform a newton solve
- Return type:
None
- property newton_solver_tolerance
Maximum value in the residual vector to consider the solution as converged during the Newton method.
- property nodal_block_dof_arrangement_used
REMOVED - raises. It set oomph-lib’s Block_dof_arrangement_used flag, whose every consumer is commented out in the vendored copy (linear_solver.cc, linear_algebra_distribution.cc), so setting it did nothing at all. The working replacement is
problem.dof_ordering; see pyoomph.generic.dof_ordering.
- nsub_mesh(self) int
Return the number of sub-meshes added via add_sub_mesh().
- Return type:
int
- ntime_stepper(self) int
Return the number of time steppers added to the problem.
- Return type:
int
- output(stage='', quiet=None, increase_time_for_PVD=False)[source]
Invoke an output of the current solution at the current time by calling all Output objects.
- Parameters:
stage (
str) – The stage of the output, at the moment, only “” is meaninfull.quiet (
bool|None) – Flag to control the verbosity of the output.increase_time_for_PVD (
bool|Expression|GiNaC_GlobalParam|int|float) – Advance the current time before writing. A Paraview PVD collection indexes its entries by time, so a sequence of stationary solutions - a parameter scan, a bifurcation diagram - all written at the same time would overlay each other there.Truesteps the time byscale_factor("temporal"); pass a time step instead ofTrueto control the increment.
- Return type:
None- Returns:
None
- output_at_increased_time(dt=None)[source]
Increases the current time by the specified time step (dt, default scale_factor(“temporal”)) and calls the output method. Useful for Paraview PVD output of multiple stationary solutions, which otherwise overlays multiple outputs at the same time step.
- Parameters:
dt (
Expression|GiNaC_GlobalParam|int|float|None) – The time step to increase the current time by. If not provided, the scaling factor for temporal is used.- Return type:
None- Returns:
None
Deprecated since version Use:
output()withincrease_time_for_PVD=Trueinstead (orincrease_time_for_PVD=dtfor an explicit time step).
- output_every_step_outputs(stage='')[source]
Invoke only those Output objects that were created with
output_every_step=True(e.g.ODEFileOutputandIntegralObservableOutput). Called byrun()after every successful transient step that is not already an output step, so that these line-per-call files resolve the whole trajectory instead of just the output times.Deliberately none of the rest of
output(): no state dump, no plot, no “OUTPUT at t=…” line, and in particular no increment of the output step counter - the numbered outputs (mesh files, states, plots) must stay in step with the requested output times.- Parameters:
stage (
str) – The stage of the output, at the moment, only “” is meaningful.- Return type:
None- Returns:
None
- perturb_by_eigenfunction(*, dt=None, eigenmode=0, time_steps_per_growth=20, desired_initial_residuals=0.1)[source]
Perturb the current solution by an eigenfunction corresponding to the specified eigenmode index. The if the time step dt is not set, it is chosen so that there are time_steps_per_growth time steps per growth time of the eigenmode. Eigenindex selects which eigenmode to use (default 0 for the most unstable mode). The perturbation amplitude is chosen so that the initial residuals after perturbation are approximately desired_initial_residuals (if not None). Returns the time step dt to be used for time stepping after the perturbation.
- Parameters:
dt (
Expression|GiNaC_GlobalParam|int|float|None) – Time step to use after perturbation. If None, it is computed based on the eigenvalue using time_steps_per_growth.eigenmode (
int) – Index of the eigenmode to use for the perturbation.time_steps_per_growth (
float) – Number of time steps per growth time of the eigenmode (used if dt is None).desired_initial_residuals (
float|None) – Desired initial residuals after perturbation. If None, no scaling is done.
- Return type:
Expression|GiNaC_GlobalParam|int|float|None
- perturb_dofs(dofpert)[source]
Perturbs all degrees of freedom by a given perturbation array (must have the length of
ndof())- Parameters:
dofpert (
NDArray[float64]) – Perturbation array to be added to the degrees of freedom (nondimensional)
- petsc_fieldsplit
“p”} to automatically setup field split IS for PETSc with names “u” and “p”. If None, the default split is set like the field indices in the Jacobian information file, i.e. using “0”, “1”, etc. as prefixes
- Type:
Set e.g. to {“domain/velocity_*”
- Type:
“u”,”domain/pressure”
- plotter: list[MatplotlibPlotter] | MatplotlibPlotter | None
Set this to a (list of ) plotter(s) to automatically plot on
output()calls. If set toNone, no plotting will be done.
- precice_config_file: str
Must be set to the config file when using preCICE
- precice_initialise()[source]
Initializes the preCICE adapter for the problem. You must set precice_participant and precice_config_file in the Problem class.
- precice_participant: str
Must be set to the participant name when using preCICE. Default is an empty string, if you do not use preCICE.
- precice_run(maxstep=None, temporal_error=None, output_initially=True, fast_dof_backup=False)[source]
Runs a simulation with the precice adapter. To that end, you must set precice_participant and precice_config_file in the Problem class. There is less control compared to the normal py:meth:pyoomph.generic.problem.Problem.run (i.e. without preCICE), but a lot of settings can be adjusted in the preCICE configuration file.
- Parameters:
maxstep (
float|None) – Maximum nondimensional time step. Defaults to None.temporal_error (
float|None) – Use temporal adaptivity with this given error factor. Defaults to None.output_initially (
bool) – Outputs before the simulation starts. Defaults to True.fast_dof_backup (
bool) – If True, only the DoFs will be backed up, nothing else. Defaults to False.
- process_eigenvectors(eigenvectors)[source]
Here, you can optionally scale or negate the eigenvectors, e.g. normalize them, by overriding this method
- Parameters:
eigenvectors (
NDArray[complex128]) – 2d array of eigenvectors- Returns:
Processed array of eigenvectors
- Return type:
NDArray[complex128]
- project_initial_conditions
When set to True, we assign the initial conditions via projection, not on a nodal basis
- property prune_structural_zeros_by_field_coupling
pruning reproduced the numerical pattern exactly on every problem measured, against up to 1.37x more nonzeros for plain connectivity on weakly coupled multi-physics. Only has an effect together with
keep_structural_zeros. Incompatible withsparse_assembly_method="lists".- Type:
Whether the value-independent sparsity pattern is pruned to the field pairs the code generator proves can contribute at all, rather than being the full element-connectivity pattern. On by default
- quiet(self, quiet: bool = True) None
Deactivate output messages from the oomph-lib and pyoomph C++ core
- Return type:
None
- rebuild_global_mesh(self) None
Re-build the problem’s global mesh from the current set of sub-meshes, e.g. after sub-meshes were modified.
- Return type:
None
- redefine_problem(code_dir, interpolator=None, num_adapt=None)[source]
Redefines the problem by recompiling equations. This can in principle be used if problem parameters have changed, but it is not recommended to change the problem structure. If possible, it is advised to use the global parameter system to change any parameters.
- Parameters:
code_dir (
str) – Subdirectory in the output directory where the C++ code of the redefined problem will be written.interpolator (
type[BaseMeshToMeshInterpolator] |None) – Mesh interpolator to map the fields of the old meshes to the new ones. If None,mesh_interpolatoris used.num_adapt (
int|None) – Number of adaption steps after redefining the problem. If None, the number of adaption steps is determined by the max_refinement_level attribute.
- Raises:
RuntimeError – If the problem contains no equations after the redefinition
- refine_eigenfunction(numadapt=1, eigenindex=0, resolve_base_state=True, resolve_neigen=1, use_startvector=False)[source]
After calculating an eigenproblem, you can adapt the mesh according ot the eigenfunction of a specific eigenvalue. This can be useful to refine the mesh in regions where the eigenfunction has a high gradient. It requires SpatialErrorEsitmators to be added to the problem and an adaptive mesh.
- Parameters:
numadapt (
int) – The number of adaptations to perform. Defaults to 1.eigenindex (
int) – The index of the eigenvalue to refine the mesh for. Defaults to 0.resolve_base_state (
bool) – If True, the base state is resolved after each adaptation. Defaults to True.resolve_neigen (
int) – The number of eigenvalues to resolve after each adaptation. Defaults to 1.
- Returns:
The eigenvalue and eigenvector of the adapted eigenproblem.
- Return type:
Tuple[float, NPFloatArray]
- refine_uniformly(self) None
Uniformly refine all refineable meshes of the problem by one level.
- Return type:
None
- remesh_handler_during_continuation(force=False, resolve=True, resolve_before_eigen=False, reactivate_biftrack_neigen=4, reactivate_biftrack_shift=0, resolve_max_newton_steps=None, num_adapt=None, resolve_globally_convergent_newton=False)[source]
Handle remeshing during continuation. We might have to calculate e.g. a new eigenvector when doing bifurcation tracking. In that case, set Problem.do_remeshing_when_necessary to False to prevent any automatic remeshing.
- Parameters:
force (
bool) – Force remeshing even if not necessary. Defaults to False.resolve (
bool) – Resolve the problem after remeshing. Defaults to True.resolve_before_eigen (
bool) – Resolve the problem before solving the eigenproblem. Defaults to False.reactivate_biftrack_neigen (
int) – Number of eigenvalues to reactivate bifurcation tracking. Defaults to 4.reactivate_biftrack_shift (
float) – Shift for the eigenvalues to reactivate bifurcation tracking. Defaults to 0.resolve_max_newton_steps (
int|None) – Maximum number of Newton steps to resolve the problem.resolve_globally_convergent_newton (
bool) – Use a globally convergent Newton solver. Defaults to False.
- Returns:
True if remeshing was performed, False otherwise.
- Return type:
bool
- remesh_if_necessary()[source]
Invokes remeshing if one RemeshWhen object indicates that.
- Returns:
True if remeshing was performed, False otherwise.
- Return type:
bool
- remeshing_necessary()[source]
Checks whether any RemeshWhen object indicates that remeshing should be done.
- Returns:
True if remeshing would be required, False otherwise.
- Return type:
bool
- reset_arc_length_parameters(self) None
Reset all internal arclength continuation parameters (theta^2, sign of Jacobian, continuation direction, parameter derivative, …) to their default starting values.
- Return type:
None
- property residual_scale_hook_active
If True, the assembled residual is multiplied by get_residual_scale_factor() before it reaches the Newton solver. Set by Problem.set_deflation_operator(); left False otherwise so that problems without deflation never call into the hook.
- rotate_eigenvectors(eigenvectors, dofs_to_real, normalize_dofs=False, normalize_amplitude=1, normalize_max=True)[source]
Should be called within the method
process_eigenvectors()to rotate the eigenvectors to e.g. a common phase. This is optional, but avoids phase jumps in the eigenvectors when following an eigenbranch.- Parameters:
eigenvectors – Eigenvectors to rotate, usually the ones passed in the automatically method
process_eigenvectors().dofs_to_real (
str|list[str] |set[str]) – Which degrees of freedom to consider to find the phase. Can be a single string, a list of strings or a set of strings.normalize_dofs (
bool) – Normalizes the eigenvector with respect to the selected dofs as well. Defaults to False.normalize_amplitude (
float|complex) – If normalization is active, we can scale the overall magnitude of the eigenvector by this value. Defaults to 1.normalize_max (
bool) – If True, we normalize by the maximum magnitude of the listed dofs, otherwise by the average magnitude. Defaults to True.
- Returns:
The processed eigenvectors, return it as result of the method
process_eigenvectors().
- run(endtime, timestep=None, *, outstep=None, numouts=None, out_initially=None, temporal_error=None, outstep_relative_to_zero=True, spatial_adapt=0, startstep=None, maxstep=None, newton_solver_tolerance=None, do_not_set_IC='auto', globally_convergent_newton=False, max_newton_iterations=None, starttime=None, suppress_resolve_after_adapt=False, max_newton_to_increase_time_step=None)[source]
Run the problem for a specified duration, potential with output calls and temporal and/or spatial adaptivity. All time quantities must be given in dimensional units, e.g.
second, if you use e.g.set_scaling()with e.g.temporal=1*secondfor a dimensional problem.- Parameters:
endtime (
Expression|GiNaC_GlobalParam|int|float) – The end time of the simulation.timestep (
Expression|GiNaC_GlobalParam|int|float|None) – The time step size. If not specified, it will be determined automatically, e.g. by the outstep.outstep (
Expression|GiNaC_GlobalParam|int|float|None|bool) – The time interval between outputs. If set to True, outputs will be generated at each time step. If set to False, no outputs will be generated. If not specified, it defaults to the value of timestep, except with temporal adaptivity (temporal_error), where it defaults to True. Note that time steps are clamped to hit the output times exactly, so a finite outstep is also an upper bound for the adaptive time step.numouts (
int|None) – The number of outputs to generate. If specified, it will override the value of outstep.out_initially (
bool|None) – Whether to generate an output at the initial time. If not specified, it will be set to True if outstep is not False, otherwise it will be set to False.temporal_error (
None|float) – The temporal error tolerance. If specified, it will be used to control the time step size.outstep_relative_to_zero (
bool) – Whether the outstep is relative to the initial time or the current time. If set to True, the outstep will be relative to the initial time. If set to False, the outstep will be relative to the current time.spatial_adapt (
int) – The level of spatial adaptation. If specified, it will be used to control the spatial refinement level.startstep (
Expression|GiNaC_GlobalParam|int|float|None) – The time step size at the start of the simulation (for temporal adaptivity). If specified, it will override the value of timestep. It is ignored when this run statement is resumed by--runmode continue, unlessuse_state_dt_when_continueis set toFalse.maxstep (
Expression|GiNaC_GlobalParam|int|float|None) – The maximum time step size. If specified, it will be used to limit the time step size during temporal adaptivity.newton_solver_tolerance (
None|float) – The tolerance for the Newton solver. If specified, it will be used to control the convergence of the solver during this run call.do_not_set_IC (
Union[bool,Literal['auto']]) – Whether to set the initial condition. If set to True, the initial condition will not be set.globally_convergent_newton (
bool) – Whether to use a globally convergent Newton solver. If set to True, a globally convergent Newton solver will be used.max_newton_iterations (
None|int) – The maximum number of iterations for the Newton solver. If specified, it will override to limit the number of iterations for this run call.starttime (
Expression|GiNaC_GlobalParam|int|float|None) – The start time of the simulation. If specified, it will override the current time.suppress_resolve_after_adapt – Whether to suppress the resolve after adaptation. If set to True, the resolve after adaptation will be suppressed.
max_newton_to_increase_time_step (
int|None) – The maximum number of Newton iterations to increase the time step size. If specified, the adaptive time step will only be increased if the number of Newton iterations is less than this value.
- Return type:
Expression|GiNaC_GlobalParam|int|float- Returns:
The final time of the simulation after the run call.
- Raises:
ValueError – If endtime is not specified.
ValueError – If outstep and numouts are specified simultaneously.
RuntimeError – If a suitable time step cannot be determined.
- save_state(fname, relative_to_output=False, quiet=False)[source]
Write the full state of the problem to a file, so that it can be restored with load_state.
fnamemay also be an open binary stream (e.g. anio.BytesIO), which is what_snapshot_state()uses to keep a state in memory instead of on disk.On a distributed problem this is collective: every rank contributes its part of the mesh, the data is merged into one partition-independent file (see dev_docs/distributed_state_files.md) and rank 0 writes it. The resulting file is the same one a serial run would write and can be read back on any number of processes.
Writing to a FILE is collective under MPI in every case, distributed or not: no rank returns before the file is complete on disk, so a load_state of it right afterwards is safe. Writing to a stream is rank-local when the problem is not distributed. When it IS, the merged stream is broadcast so that every rank ends up holding the same complete state – load_state needs every rank to read the whole thing back.
- Return type:
None
- select_dofs()[source]
Returns a
_DofSelectorobject that allows to select degrees of freedom (DoFs) for further operations. For example, you can select all DoFs on a certain domain or with a certain equation type. The selected DoFs can then be used to e.g. get their values, set their values, or apply boundary conditions. It should be wrapped in a with statement to ensure proper cleanup after use. For example:with problem.select_dofs() as dofs: dofs.select("domain/velocity_x", "domain/velocity_y", "domain/pressure") dofs.unselect("domain/temperature") problem.solve() # Only solve for the velocity/pressure fields, not for the temperature field
- Return type:
_DofSelector
- set_FD_step_used_in_get_hessian_vector_products(self, step: float) None
Set the finite-difference step size used when Hessian-vector products are computed by finite differences (see set_analytic_hessian_products()).
- Return type:
None
- set_analytic_hessian_products(self, active: bool, use_symmetry: bool = False) None
Select whether Hessian-vector products are computed analytically via the generated code (
activeTrue) or by finite differences, and whether the Hessian assembly exploits its symmetry in the last two indices (use_symmetry).- Return type:
None
- set_arclength_inner_product(kind='l2')[source]
Choose the inner product in which arclength measures the solution part of a step.
oomph’s arclength constraint is:
(dparameter/ds)^2 + theta^2 * |dU/ds|^2 = 1
where
|.|is the plain Euclidean norm of the dof vector - a sum over degrees of freedom, not an integral, so it has no continuum limit. Measured on the Bratu problem, that sum grows exactly in proportion to ndof (its ratio to ndof is constant to three digits over three decades), which means the defaulttheta^2 = 1is not a neutral choice but a mesh-dependent one: the same ds buys 21x less parameter movement at 50000 dofs than at 39.Scale_arc_lengthpapers over it by tuning theta^2 until the parameter takes a fixed share of the arclength, and what it converges to is theta^2 proportional to 1/ndof - i.e. it rediscovers the normalisation at runtime, once per step.This sets it directly instead, from a norm that is mesh-independent by construction:
"l2"(or"mass"): the mean square of the field,(v^T M v)/volumewith the mass matrix M. Mesh-independent and aware of how large each field actually is, since M carries the integration weights. Requires the problem to have a mass matrix: dofs that appear in no time-derivative term (pressure in an incompressible flow, Lagrange multipliers) get no weight at all, so a step that only moves those is invisible to the constraint."ndof":|v|^2/ndof. Free - no assembly - and mesh-independent, weighting every dof equally whatever it represents. The safe choice when there is no usable mass matrix.a callable taking the dof-derivative vector and returning its SQUARED norm, for a problem- specific weighting (per-field scales, a subset of the dofs, …).
None: leave theta^2 alone, i.e. the historical behaviour.
Since a scalar theta^2 has to reproduce a weighted norm, this works because only ONE direction is ever measured: for the current tangent,
theta^2 = ||v||_W^2 / ||v||_2^2makes the Euclidean constraint agree with the W-weighted one exactly. It is re-derived before every step, as the tangent turns.Turns
Scale_arc_lengthoff, since the two would fight over the same scalar.
- set_c_compiler(compiler_or_name)[source]
Selects the C compiler for the problem. “tcc” is fast in compilation, but slower in execution. Good for setting up a problem class. “system” is slower in compilation, but faster in execution. Good for running the final problem. set_c_compiler(“system”).optimize_for_max_speed() makes it even faster by using compiler flags for maximum speed.
- Parameters:
compiler_or_name (
str|BaseCCompiler) – The C compiler to use (“tcc” or “system” at the moment).- Returns:
The C compiler that was set.
- Return type:
CCompiler|BaseCCompiler
- set_coordinate_system(coordsys)[source]
Set the default coordinate system at problem level. You can specify coordinate systems also at equation level, but if you don’t do, the coordinate system will default to this one.
- Parameters:
coordsys (
Union[Literal['axisymmetric','axisymmetric_flipped','cartesian','radialsymmetric'],BaseCoordinateSystem]) – The coordinate system to set as default. The former namecsysis deprecated, but still accepted.- Raises:
RuntimeError – Raised in case we do not set a valid coordinate system
- set_current_dofs(self, values: collections.abc.Sequence[float]) None
Set the current values of all (unpinned and pinned) degrees of freedom from
values.- Return type:
None
- set_current_pinned_values(self, values: collections.abc.Sequence[float], with_position_dofs: bool, t: int = 0) None
Set the values of all pinned degrees of freedom (and, if
with_position_dofsis True, pinned nodal position dofs) at history/time leveltfromvalues.- Return type:
None
- set_current_time(val, dimensional=True, as_float=False)[source]
Set the current time of the problem.
- Parameters:
val (
Expression|GiNaC_GlobalParam|int|float) – The value of the time to set.dimensional (
bool) – Flag indicating whether the time is dimensional or not. Defaults to True.as_float (
bool) – Flag indicating whether to convert the time to a float. Defaults to False.
- Raises:
ValueError – If the nondimensional time is not a number.
ValueError – If the dimensional time cannot be nondimensionalized.
- Returns:
None
- set_deflation_operator(op)[source]
Install (or remove) a deflation operator.
Unlike
set_custom_assembler(), this leaves the assembly alone: the residual is multiplied by the operator’s scalar factor in C++ (Problem::apply_residual_scale_factor) and the linear solver rescales the Newton step. Everything else – the elemental assembly, the frozen sparsity pattern, the choice of backend, MPI – is the ordinary path, which is why deflation works undermpirunand--distributewhile the custom-assembler trackers do not. See dev_docs/deflation.md.- Return type:
None
- set_eigensolver(solv)[source]
Set the eigensolver backend. “scipy”, “pardiso”, “spectra”, “slepc” and “slepc_mumps” are available (“pardiso” only with MKL installed, the “slepc” ones only with petsc4py/slepc4py, and “spectra” only if the build was configured with PYOOMPH_HAS_SPECTRA=ON, which is the default).
“scipy” and “pardiso” are both scipy’s ARPACK and cannot target an eigenvalue at all. “spectra” and the “slepc” ones can; only “slepc” with a complex PETSc build, and the “slepc” ones alone run in parallel. Use
python -m pyoomph check eigen allto see what this installation actually has.- Returns:
The eigenproblem solver instance after setting
- set_history_dofs(self, t: int, values: collections.abc.Sequence[float]) None
Set the values of all degrees of freedom at history/time level
tfromvalues.- Return type:
None
- set_initial_condition(ic_name='', all_unset_dofs_to_zero=False, numadapt=0)[source]
Set the initial condition for the problem.
- Parameters:
ic_name (
str) – Name of the initial condition. Multiple initial conditions can be defined in the problem definition by using the optional argument InitialConditions. Defaults to “”.all_unset_dofs_to_zero (
bool) – Flag indicating whether to set all unset degrees of freedom, i.e. without any InitialCondition with this ic_name, to zero. Defaults to False.
- set_interpolate_new_interface_dofs(self, on: bool) None
Controls whether newly created interface degrees of freedom (e.g. after refinement) are interpolated from the neighbouring nodes or initialized to zero. Was a process-wide switch; it is per Problem, because remeshing turns it off and on again around itself.
- Return type:
None
- set_linear_solver(solv)[source]
Set the linear solver backend. “scipy”, “umfpack”, “pardiso”, “petsc” are available (the latter two only if the packages MKL and/or petsc4py are installed)
- Returns:
The linear solver instance after setting
- set_max_refinement_level(level, do_adapt=True)[source]
After initialisation, the property max_refinement_level is not considered anymore. You can set the maximum refinement level of the meshes with this function
- set_mesh_pt(self, mesh: pyoomph._pyoomph_core.Mesh) None
Set the (single) global mesh of the problem.
- Return type:
None
- set_num_threads(nthread)[source]
Set how many threads the element assembly and the linear solver may use. Most direct solvers are internally threaded, and pyoomph’s own element loop is threaded with OpenMP, so this is what decides whether a serial run keeps one core or several busy.
The threaded element loop is bit-identical to the serial one - it changes the time and nothing else - and it declines by itself, saying why once, wherever it cannot apply (a finite-difference Jacobian, an assembly-time diagnostic switched on, a build without OpenMP).
A threaded direct SOLVER, on the other hand, is not bit-reproducible, so a converged state can differ in its last digits between one thread and several. That is unchanged by, and unrelated to, the threaded assembly; if you want the two effects apart, set the assembly count on its own with
problem._set_num_assembly_threads(n).The count is remembered on the problem, not just handed to the current solver: it is applied again to any backend selected later with
set_linear_solver(). PassingNoneleaves the backend at its own default, which is usually whateverOMP_NUM_THREADSsays.Under
mpirunthis matters mainly for the solvers that are not MPI-parallel: they gather the system onto rank 0 and solve it there, and the other ranks sleep so that rank 0 may use their cores - which it can only do if the launcher did not pin each process to one (mpirun --bind-to none).- Parameters:
nthread (
int|None) – Number of threads, orNonefor the backend’s own default.
- set_output_directory(d)[source]
Change the output directory of the problem. Note: It should not be changed after the problem is initialised.
- Parameters:
d (
str) – Output directory- Return type:
None
- set_scaling(**kwargs)[source]
Set the scaling factors for the problem variables for nondimensionalization. You can provide also scaling at equation level, but if not set there, it will ultimately default to the problem level scaling. Particular scales are
"temporal"for the time and"spatial"for the spatial coordinates.- Parameters:
**kwargs (
Expression|GiNaC_GlobalParam|int|float|str) – Keyword arguments specifying the scaling factors. The keys are the variable names, and the values are either numerical scaling factors or string expressions. In the latter case, we can set one scaling to another one, e.g.set_scaling(u=1*meter/second,v="u")would set the scaling of “v” to the one of “u”.- Return type:
None
- set_use_eigen_Z2_error_estimators(self, on: bool) None
Controls whether the Zienkiewicz-Zhu (Z2) spatial error estimator uses the eigenvector flux set instead of the base-state one. Was a process-wide switch.
- Return type:
None
- setup_for_stability_analysis(analytic_hessian=True, use_hessian_symmetry=True, improve_pitchfork_on_unstructured_mesh=False, improve_pitchfork_coordsys=None, improve_pitchfork_position_coordsys=None, shared_shapes_for_multi_assemble=None, azimuthal_stability=None, additional_cartesian_mode=None, expand_element_size=False)[source]
Sets up the problem for stability analysis, e.g. for improved pitchfork tracking on unsymmetric meshes, azimuthal stability, etc. Arguments which are None are not changed.
- Parameters:
analytic_hessian (
bool) – Flag indicating whether to use an analytically derived symbolical Hessian. Defaults to True.use_hessian_symmetry (
bool) – Flag indicating whether to use symmetry in the Hessian. Defaults to True.improve_pitchfork_on_unstructured_mesh (
bool) – Flag indicating whether to improve pitchfork tracking on unsymmetric meshes. Defaults to False.improve_pitchfork_coordsys (
CustomCoordinateSystem|None) – Coordinate system for improving pitchfork tracking unsymmetric meshes. Defaults to None.improve_pitchfork_position_coordsys (
CustomCoordinateSystem|None) – Coordinate system for improving pitchfork position space. Defaults to None.shared_shapes_for_multi_assemble (
bool|None) – Flag indicating whether to use shared shapes for multi-assemble. Defaults to None.azimuthal_stability (
bool|None) – Flag indicating whether to set up azimuthal stability code. Defaults to None.expand_element_size (
bool) – Whether the mode expansion also perturbs the element size, i.e. whether a stabilization parameter tau built from it follows the mesh. Defaults to False, the “frozen tau” reading: the element size keeps its base-state value in the perturbation equations. That is the meaningful choice - the element size is a Cartesian mesh metric, and at m!=0 the perturbed configuration is not even a revolved 2d element, so its azimuthal extent is not represented at all - and it is also the one whose augmented Jacobian is exact. Only matters on a moving mesh, and only for equations that use the element size at all (the residual-based stabilizations do); on the rising bubble it moves the tracked onset by 0.36%.
- setup_interior_facet_halo_scheme(self) None
Give the interior-facet skeletons (‘<domain>/_internal_facets_’) their halo/haloed element lists and mark the halo facets’ own Data as halo. A facet between two elements that ended up on different processes exists on both, so without this its unknowns would be numbered once per holder – two independent copies of what is meant to be one single-valued trace. With it, they are numbered on the process that assembles the facet and oomph-lib’s own machinery copies the numbers and the values to the others. COLLECTIVE, and a no-op serially, on a replicated (non—distribute) run, and when the problem has no skeleton. Called from actions_after_adapt() (hence also after distribute()), after remeshing and after loading a state file; there is no reason to call it by hand.
- Return type:
None
- shift_time_values(self) None
Shift the stored time history values of all data (copy current values to the storage locations of the previous time step), in preparation for the next time step.
- Return type:
None
- solve(*, spatial_adapt=0, timestep=None, shift_values=True, temporal_error=None, max_newton_iterations=None, newton_relaxation_factor=None, suppress_resolve_after_adapt=False, newton_solver_tolerance=None, do_not_set_IC=False, globally_convergent_newton=False)[source]
Solves the problem stationary, unless a timestep is given. In that case, the time step is taken.
- Parameters:
spatial_adapt (
int) – The level of spatial adaptation. Default is 0.timestep (
Expression|GiNaC_GlobalParam|int|float|None|list[Expression|GiNaC_GlobalParam|int|float|None] |tuple[Expression|GiNaC_GlobalParam|int|float|None,...]) – The time step(s) for the transient solve. Can be a single value or a list/tuple of values, which are then taken one after the other. Default is None, meaning stationary solve without advancing in time.shift_values (
bool) – Whether to shift the values during the solve, i.e. shifting the history value buffer. Default is True.temporal_error (
float|None) – The temporal error for adaptive time stepping. Default is None.max_newton_iterations (
int|None) – Override the maximum number of Newton iterations. Default is None.newton_relaxation_factor (
float|None) – Override the relaxation factor for the Newton solver. Default is None.suppress_resolve_after_adapt (
bool) – Whether to suppress resolving after adaptation. Default is False.newton_solver_tolerance (
float|None) – Override the tolerance for the Newton solver. Default is None.do_not_set_IC (
bool) – Whether to not set the initial condition in the first call. Default is False.globally_convergent_newton (
bool) – Whether to use globally convergent Newton solver. Default is False.
- Returns:
The current time after solving.
- Return type:
Expression|GiNaC_GlobalParam|int|float
- solve_auxiliary_residual(residual_name, **solve_kwargs)[source]
Solve an auxiliary residual on its own, leaving the main solution untouched.
Equations may be added to a named residual instead of the default one, by passing
destinationtoadd_residual(). Anything that is only ever postprocessed - a projection of some expression onto a field for output, say - belongs there rather than in the residual the Newton solver works on: on the main residual those unknowns have no Jacobian row at all, so they are pinned automatically and cost nothing, and this method solves for them when they are actually wanted. While it runs, the roles are reversed and the unknowns of the main residual are the pinned ones.Switching the residual is not sufficient by itself.
_set_solved_residual()only marks which fields have an empty Jacobian row; the pinning takes effect when the equation numbers are reassigned, which is whatreapply_boundary_conditions()does. Both are therefore done here, on the way in and on the way back out - the latter even if the solve raises, since leaving the problem on the auxiliary residual would silently corrupt every subsequent solve.- Parameters:
residual_name (
str) – name of the residual to solve, i.e. thedestinationthe equations were added with.**solve_kwargs – passed on to
solve().
- Return type:
None
- solve_eigenproblem(n, shift=0, quiet=False, azimuthal_m=None, normal_mode_k=None, normal_mode_L=None, report_accuracy=False, sort=True, which='LM', OPpart=None, v0=None, filter=None, target=None, ncv=None)[source]
Solves the associated generalized eigenproblem for the given number of eigenvalues and eigenvectors.
With
Jthe Jacobian andMthe mass matrix of the residualR(U, dU/dt) = 0, i.e.J = dR/dUandM = dR/d(dU/dt), the eigenvalues returned are the solutions oflambda * M * v + J * v = 0
so a perturbation of the stationary solution evolves like
v*exp(lambda*t): an eigenvalue with a positive real part means the solution is unstable (cf.is_stable_solution()), and the imaginary part is the angular frequency of the oscillation. The same convention holds for the normal-mode variants selected byazimuthal_mornormal_mode_k, and for the eigenvalue reported while a bifurcation or eigenbranch tracker is active.While a bifurcation tracker is active this solves the eigenproblem of the BASE state, i.e. of the first
ndofentries of the augmented dof vector, which is how a secondary (codim-2) bifurcation is detected along a bifurcation locus. Nothing is renumbered and the tracked state is left untouched. Three things differ from an ordinary call:shiftmust be non-zero. The tracker has converged the base state onto the bifurcation, solambda = 0(fold, pitchfork) or+-i*omega(Hopf, azimuthal) is an exact eigenvalue – exactly where the shift-invert transform would be asked to factorise. A zero (orNone) shift raises rather than handing the solver a singular operator.without
azimuthal_m/normal_mode_kthe mode is whatever the corresponding global parameter currently holds, i.e. the tracked mode during azimuthal or normal-mode tracking. Passazimuthal_m=0for the axisymmetric base-state spectrum.a mode that would require the equations to be renumbered is refused. In practice that means
azimuthal_m != 0while tracking a fold, Hopf or pitchfork, where the strong axis conditions are still active; while tracking an azimuthal or Cartesian normal-mode bifurcation they are already released and every mode is available.
The results replace
get_last_eigenvalues()/get_last_eigenvectors(), so they no longer hold the tracked critical eigenpair – ask the handler through_get_bifurcation_eigenvector()if you need that afterwards.- Parameters:
n (
int) – The number of eigenvalues and eigenvectors to compute.shift (
float|complex|None) – The shift applied for shift-inverted approaches to solve the eigenproblem. Defaults to 0. Must be non-zero while bifurcation tracking is active, see above.quiet (
bool) – If True, suppresses the output. Defaults to False.azimuthal_m (
int|list[int] |None) – The azimuthal mode number(s) for axial symmetry breaking. Defaults to None, i.e. the axisymmetric mode.normal_mode_k (
Expression|GiNaC_GlobalParam|int|float|list[Expression|GiNaC_GlobalParam|int|float] |None) – The wave number(s) for an additional direction in Cartesian coordinates. Defaults to None, i.e. the base mode.normal_mode_L (
Expression|GiNaC_GlobalParam|int|float|list[Expression|GiNaC_GlobalParam|int|float] |None) – The periodic length for an additional direction in Cartesian coordinates. Defaults to None, i.e. the base mode.report_accuracy (
bool) – If True, reports the accuracy of the computed eigenvalues. Defaults to False.sort (
bool) – If True, sorts the eigenvalues in ascending order. Defaults to True.which (
Literal['LM','SM','LR','SR','SI']) – The type of eigenvalues to compute. Defaults to “LM”.OPpart (
Optional[Literal['r','i']]) – The part of the operator to use. Defaults to None.v0 (
NDArray[float64] |NDArray[complex128] |None) – The initial guess for the eigenvectors. Defaults to None.filter (
Callable[[complex],bool] |None) – A function to filter the computed eigenvalues. Only the eigenvalues for which the filter returns True will be kept. Defaults to None.target (
complex|None) – The target eigenvalue. Defaults to None.ncv (
int|None) – The number of Krylov (Arnoldi/Lanczos) basis vectors used by the underlying eigensolver. Defaults to None, i.e. the eigensolver’s own default. Set this to a larger value than the default if the eigensolver fails to converge or returns inaccurate eigenvalues, e.g. for clustered eigenvalues.
- Returns:
A tuple containing the computed eigenvalues and eigenvectors.
- Return type:
tuple[NDArray[complex128],NDArray[complex128]]
- property sparse_assembly_method
There are different methods implemented in oomph-lib to fill the sparse matrices (Jacobian, mass matrix, etc.). Depending on the problem, one or the other method may be faster or more memory efficient. The default method is “vectors_of_pairs”, which is the most general one.
- property static_condensation_max_component_size
Largest connected component of mutually coupled condensed dofs that will be accepted (default 64). Condensation is only a win while the selected dofs decompose into small per-element patches, each of which is inverted densely; a selection that instead percolates through the mesh (interior-penalty DG velocities, say) would amount to a dense solve and is refused with a diagnostic naming the offending size.
- steady_newton_solve(self, max_adapt: int = 0) None
Perform a steady newton solve
- Return type:
None
- stop_on_jacobian_structure_warning
When you have e.g. a field without any equations, it will stop the simulation and give a warning about the Jacobian structure. Setting this to False, it will just go through
- switch_branch(parameter, normal_form=None, offset=None, direction=1, relative_offset=0.02, max_newton_iterations=15, quiet=False, offset_ratio=1.25, max_attempts=120)[source]
Step from a bifurcation onto the OTHER branch that passes through it.
Usable on its own, without the bifurcation GUI:
problem.solve_eigenproblem(1) problem.activate_bifurcation_tracking("gamma") problem.solve() # now AT the bifurcation ds = problem.switch_branch("gamma") # now on the other branch while ...: ds = problem.arclength_continuation("gamma", ds)
The switch is done by predicting a point on the new branch from the normal form and then doing an ordinary Newton solve there - not by seeding the arclength state. Seeding does not work: the continuation setters take derivatives while the normal form gives increments, and oomph normalises its own tangent to
(dparameter/ds)^2 + theta^2*|dU/ds|^2 = 1, so a mis-scaled seed makes the arclength constraint ask for a wildly inflated step and Newton falls back onto the branch it started from. A short way off the bifurcation the Jacobian is regular again, so a plain solve converges, and the prediction is what decides which branch it converges to. See dev_docs/branch_switching.md.Bifurcation tracking is deactivated here: the switch needs the plain system.
- Parameters:
parameter (
str|GiNaC_GlobalParam) – The parameter the bifurcation is in.normal_form (
dict[str,Any] |None) – The result ofclassify_bifurcation(). Computed here if not given.offset (
float|None) – Parameter offset to step off the bifurcation by. Defaults torelative_offsettimes the parameter’s own magnitude; smaller is truer to the normal form but closer to the singular point.direction (
int) –+1or-1to pick which of the two branches through the bifurcation is predicted first; both are tried either way. For a pitchfork this is the only thing that tells its two arms apart - they sit on the same side of the parameter and differ in the sign of the amplitude - and the landing is accepted only if it moved along the requested direction, so which arm is reached is a guarantee and not a hope.relative_offset (
float) – Used whenoffsetis not given.max_newton_iterations (
int) – For the solve onto the new branch.quiet (
bool) – Suppress the progress messages.offset_ratio (
float) – Spacing of the ladder of offsets that is tried, from three timesoffsetdown over three decades. Closer to 1 samples more finely and costs one Newton solve per rung and side; the window that works can be narrower than a factor of 1.5.max_attempts (
int) – Hard cap on those Newton solves, so a large problem cannot spend minutes failing.
- Returns:
a quarter of the offset actually taken, signed. It is deliberately that small: just off the bifurcation
dU/dparameteris still badly conditioned and a larger step overshoots back onto the old branch, andarclength_continuation()grows it again by itself.Noneif no side of the bifurcation could be reached, in which case the problem is left where it was.- Return type:
float|None- Raises:
RuntimeError – If the bifurcation is a fold (one branch, which turns around - there is nothing to switch to), if it is a Hopf (which sheds a periodic orbit rather than a second steady branch - see
switch_to_hopf_orbit()), if it belongs to an azimuthalm != 0or Cartesiank != 0normal mode (the branch it sheds breaks the symmetry this dof vector is built on and cannot be represented in it), or if its normal form carries no branch predictor.
- switch_to_hopf_orbit(eps=0.01, dparam=None, NT=30, mode='collocation', order=3, GL_order=-1, T_constraint='phase', amplitude_factor=1, FD_delta=1e-05, FD_param_delta=0.001, do_solve=True, solve_kwargs={}, check_collapse_to_stationary=True, orbit_amplitude=None, patch_number_of_nodes=True)[source]
After solving for a Hopf bifurcation by bifurcation tracking, this method will calculate the first Lyapunov exponent and initializes a good guess for the tracking of the periodic orbits originating at this Hopf bifurcation.
It is best to call it like:
- with problem.switch_to_hopf_orbit(…) as orbit:
…
to deactivate orbit tracking after the with-statement.
- Parameters:
eps (
float) – A small number to construct the initial guess of the orbit and shift the parameter accordingly. Defaults to 0.01.dparam (
float|None) – Optional parameter shift. If given and orbit_amplitude is also given, eps is ignored. Defaults to None.NT (
int) – Number of discrete time steps to consider for the orbit. Defaults to 30.mode (
Literal['collocation','floquet','central','BDF2','bspline']) – Selects the time discretization and interpolation mode. Defaults to “collocation”.order (
int) – Selects the order of the time discretization method. Defaults to 3.GL_order (
int) – Selects the Gauss-Legendre integration order for some time discretization modes. Defaults to -1, which is auto-select depending on the order.T_constraint (
Literal['phase','plane']) – Either use the “plane” or the “phase” constraint as equation for T. Defaults to “phase”.amplitude_factor (
float) – Additional multiplicative factor for the amplitude of the orbit guess. Defaults to 1.FD_delta (
float) – Finite difference step for the third order calculations used in the determination of the first Lyapunov coefficient. Defaults to 1e-5.FD_param_delta – Finite difference step to determine the change of the real part of the eigenvalue with respect to the parameter. Defaults to 1e-3.
do_solve (
bool) – Solve the orbit guess. Defaults to True.solve_kwargs (
dict[str,Any]) – Additional keywords arguments to pass to the solve method for the initial solve. Defaults to {}.check_collapse_to_stationary (
bool) – Since an orbit can collapse to the stationary Hopf branch, we can check for it to make sure we are actually on an orbit. Defaults to True.orbit_amplitude (
float|None) – Amplitude for the orbit. If set together with dparam, eps is ignored. Defaults to None.patch_number_of_nodes (
bool) – Depending on the order, we might have to slightly modify NT to have the right number of time nodes. Defaults to True.
- Returns:
The periodic orbit object
- Return type:
- property target_error_safety_factor
the next dt is predicted so that the temporal error hits this factor times the requested tolerance, rather than the tolerance itself. Must be <= 1. With the default of 1.0 the prediction aims exactly at the tolerance, so about half of the steps exceed it and are rejected; values around 0.25-0.40 are usually the most efficient, and values up to 0.95 mainly improve robustness of the dt prediction.
- Type:
Safety factor for adaptive time stepping
- time_pt(self) pyoomph._pyoomph_core.Time
Return the problem’s Time object, holding the current time and time step history.
- Return type:
Time
- time_stepper_pt(self, i: int = 0) pyoomph._pyoomph_core.TimeStepper
Return the
i-th time stepper added to the problem via add_time_stepper_pt() (default: the first/main one).- Return type:
TimeStepper
- unrefine_uniformly(self) int
Uniformly unrefine all refineable meshes of the problem by one level. Returns the number of elements that could not be unrefined further.
- Return type:
int
- unsteady_newton_solve(self, dt: float, shift_values: bool) None
- unsteady_newton_solve(self, dt: float, max_adapt: int, first: bool, shift: bool = True) None
Overloaded function.
unsteady_newton_solve(self, dt: float, shift_values: bool) -> None
Advance time by
dtand solve by Newton’s method.shift_valuescontrols whether the current data values are shifted to the storage locations of the previous time step before the solve (must be True on the very first time step).unsteady_newton_solve(self, dt: float, max_adapt: int, first: bool, shift: bool = True) -> None
Advance time by
dtwith up tomax_adaptrounds of spatial mesh adaptation to satisfy the error targets of the refineable submeshes. Iffirstis True, the initial conditions are re-assigned after each mesh adaptation.shiftcontrols whether time history values are shifted.- Return type:
None
- property use_custom_residual_jacobian
If True, residuals/Jacobians are obtained by calling the (Python-overridable) get_custom_residuals_jacobian() hook instead of the generated finite element code.
- property use_frozen_distributed_sparsity
a replicated problem whose elements are merely split across ranks (its element ranges are re-tuned from measured timings, so they are not a function of the equation numbering), a residual-only assembly, an augmented system, or a pattern the code generator cannot describe symbolically. Always False in a non-MPI build.
- Type:
The distributed counterpart of
use_frozen_sparsity- Type:
on a
--distributed run, freeze the whole assembly plan – which rows this rank touches, which rank owns each of them, the column indices, and how the pieces arriving from several ranks merge into one row – so that only values and residuals travel per assembly. oomph-lib redoes all of it every time, and its owner-side merge rescans the row built so far for every incoming entry. Falls back to oomph-lib’s routine by itself whenever it cannot apply
- property use_frozen_sparsity
Whether assembly writes straight into a preallocated CSR through a precomputed scatter map, instead of accumulating into a searchable container and compressing it afterwards. Requires a value-independent pattern (
keep_structural_zeros), and falls back to oomph-lib’s assembly by itself whenever it cannot apply – distributed runs, augmented systems (bifurcation tracking), compressed-column output, or any element the code generator cannot describe symbolically.
- use_state_dt_when_continue: bool
When resuming with
--runmode continue, carry on with the time step stored in the state file instead of thestartstep(or any other initial dt) requested by the run statement we resume into. Only that one statement is affected; later run statements in the script were never entered, so their own initial dt still applies. Set toFalseto get the old behaviour, where a continued run always restarted from the scripted initial step.
- property use_static_condensation
residual evaluations, eigenvalue and Hessian assemblies, arclength continuation and a bare
assemble_jacobian()always see the full system. Combinations refused with an error rather than silently ignored: Jacobian reuse, the globally convergent (line search) Newton method, an MPI run that was never distributed, and a selection whose coupled block is split across ranks. Under MPI every refusal is collective, so all ranks raise the same error.- Type:
Master switch for static condensation
- Type:
eliminating the element-local degrees of freedom selected by a
StaticCondensationequation (or bycondense_dofs()) from the linear system before it is handed to the solver, and reconstructing them afterwards. EXPERIMENTAL. Serial and distributed (--distribute) runs are both supported. Off by default, but adding aStaticCondensationequation to the equation tree switches it on automatically - assigning it explicitly, in either direction, always wins over that, so setting it to False is the kill switch that disables the feature wholesale. The selection rules are declared independently of it, so a selection can be built up and inspected with this left off. The elimination is exact – the same solution and the same Newton iteration count as with the switch off – and buys roughly half the factorisation time on a Crouzeix-Raviart system. Only Newton solves are affected
- warn_about_unused_global_parameters: bool | Literal['error']
When set to True, we warn about unused global parameters for arclength continuation or bifurcation tracking. If set to “error”, we raise an error.