diff --git a/Project.toml b/Project.toml index a0cc374..a3bc315 100644 --- a/Project.toml +++ b/Project.toml @@ -22,7 +22,7 @@ BinaryHeaps = "1.0.0" CommonSolve = "0.2.4" DiffEqBase = "7.5" ModelingToolkit = "11.26" -OrdinaryDiffEqCore = "4.4" +OrdinaryDiffEqCore = "4.14.3" OrdinaryDiffEqLowOrderRK = "2" OrdinaryDiffEqTsit5 = "2" PrecompileTools = "1.1" diff --git a/src/OrdinaryDiffEqOperatorSplitting.jl b/src/OrdinaryDiffEqOperatorSplitting.jl index 661dc24..773e179 100644 --- a/src/OrdinaryDiffEqOperatorSplitting.jl +++ b/src/OrdinaryDiffEqOperatorSplitting.jl @@ -12,32 +12,146 @@ import SciMLBase: ReturnCode import SciMLBase: DEIntegrator, NullParameters, isadaptive import SymbolicIndexingInterface: variable_symbols +import DiffEqBase: set_proposed_dt! + import RecursiveArrayTools import OrdinaryDiffEqCore: OrdinaryDiffEqCore, isdtchangeable, stepsize_controller!, step_accept_controller!, step_reject_controller!, accept_step_controller +# `@verbosity_specifier` expands to code referring to SciMLLogging's names unqualified, +# so they have to be in scope: the presets handed to it below, plus `Standard`, +# `MessageLevel`, `AbstractVerbosityPreset` and `AbstractVerbositySpecifier`, which the +# generated constructor validates a caller's arguments against. Of those, only +# `MessageLevel` appears in no source line here, so source analysis reads it as a stale +# import -- hence the `no_stale_explicit_imports` ignore in test/qa/qa.jl. +import SciMLLogging: @SciMLMessage, @verbosity_specifier, AbstractVerbosityPreset, + AbstractVerbositySpecifier, All, Detailed, InfoLevel, MessageLevel, Minimal, None, + Silent, Standard + # In OrdinaryDiffEq v7 / DiffEqBase v7, passing verbose::Bool to inner ODE # integrators is no longer supported. Convert Bool → DEVerbosity when available. @static if isdefined(DiffEqBase, :DEVerbosity) + """ + OperatorSplittingVerbosity + + Verbosity configuration for the splitting nodes of an operator-splitting solve. + + A splitting node has diagnostics of its own -- the step size it chose and the + splitting error estimate behind that choice -- which are separate from anything the + inner integrators report. Those are toggled here, while `inner_verbosity` holds the + `DiffEqBase.DEVerbosity` handed to every inner integrator, mirroring the way + `DEVerbosity` itself nests `linear_verbosity` and `nonlinear_verbosity`. + + # Toggles + + - `splitting_step_accepted`: `t`, `dt` and `EEst` of each accepted splitting step. + - `splitting_step_rejected`: the same for a step the controller rejected. + - `inner_solver_stats`: a per-operator summary of the inner integrator work -- + steps, rejections, `f` evaluations, Jacobians, `W` factorizations, linear solves + -- emitted once when the solve finishes. + + # Examples + + ```julia + # A preset applies to this node and travels to the inner integrators. + verbose = OperatorSplittingVerbosity(SciMLLogging.All()) + + # Splitting diagnostics on, inner integrators quiet. + verbose = OperatorSplittingVerbosity( + splitting_step_accepted = SciMLLogging.InfoLevel(), + inner_solver_stats = SciMLLogging.InfoLevel(), + inner_verbosity = DiffEqBase.DEVerbosity(SciMLLogging.None()), + ) + ``` + + A `DEVerbosity`, a `SciMLLogging` preset or a `Bool` passed as `verbose` is accepted + and converted. A `DEVerbosity` becomes the `inner_verbosity` with the splitting + diagnostics left silent, so existing code keeps exactly its previous output. + """ + @verbosity_specifier OperatorSplittingVerbosity begin + toggles = ( + :splitting_step_accepted, :splitting_step_rejected, :inner_solver_stats, + ) + + sub_specifiers = (:inner_verbosity,) + + groups = ( + step_control = (:splitting_step_accepted, :splitting_step_rejected), + performance = (:inner_solver_stats,), + ) + + presets = ( + None = ( + inner_verbosity = None(), + splitting_step_accepted = Silent(), + splitting_step_rejected = Silent(), + inner_solver_stats = Silent(), + ), + Minimal = ( + inner_verbosity = Minimal(), + splitting_step_accepted = Silent(), + splitting_step_rejected = Silent(), + inner_solver_stats = Silent(), + ), + Standard = ( + inner_verbosity = Standard(), + splitting_step_accepted = Silent(), + splitting_step_rejected = Silent(), + inner_solver_stats = Silent(), + ), + Detailed = ( + inner_verbosity = Detailed(), + splitting_step_accepted = Silent(), + splitting_step_rejected = InfoLevel(), + inner_solver_stats = InfoLevel(), + ), + All = ( + inner_verbosity = All(), + splitting_step_accepted = InfoLevel(), + splitting_step_rejected = InfoLevel(), + inner_solver_stats = InfoLevel(), + ), + ) + end + + const DEFAULT_VERBOSITY = OperatorSplittingVerbosity(SciMLLogging.Minimal()) + _inner_verbose(verbose::Bool) = verbose ? DiffEqBase.DEVerbosity(SciMLLogging.Minimal()) : DiffEqBase.DEVerbosity(SciMLLogging.None()) - const DEFAULT_VERBOSITY = DiffEqBase.DEVerbosity(SciMLLogging.Minimal()) + _inner_verbose(verbose::OperatorSplittingVerbosity) = verbose.inner_verbosity + + # A splitting node owns an `OperatorSplittingVerbosity`; anything else a caller + # passes is the inner integrators' setting and is wrapped, leaving the splitting + # diagnostics off so that existing code keeps its previous output. + _process_verbose(verbose::OperatorSplittingVerbosity) = verbose + _process_verbose(verbose::DiffEqBase.DEVerbosity) = OperatorSplittingVerbosity(; + preset = SciMLLogging.Minimal(), inner_verbosity = verbose + ) + _process_verbose(preset::AbstractVerbosityPreset) = + OperatorSplittingVerbosity(preset) + # A `Bool` says how loud the inner integrators should be and nothing about the + # splitting diagnostics, which both presets leave silent -- `verbose = true` keeps + # meaning what it meant before this node had diagnostics of its own. Left + # unconverted it would reach `@SciMLMessage` as a `Bool`, where `true` enables + # *every* toggle and logs a message per step. + _process_verbose(verbose::Bool) = OperatorSplittingVerbosity( + verbose ? SciMLLogging.Minimal() : SciMLLogging.None() + ) else const DEFAULT_VERBOSITY = false end _inner_verbose(verbose) = verbose +_process_verbose(verbose) = verbose # `verbose` reaches us either as a Bool or, through DiffEqBase v7's `init`, as a -# DEVerbosity whose first type parameter is the on/off flag. Neither can be used in -# a boolean context directly. +# verbosity specifier whose first type parameter is the on/off flag. Neither can be +# used in a boolean context directly. _is_verbose(verbose::Bool) = verbose _is_verbose(verbose) = true -@static if isdefined(DiffEqBase, :DEVerbosity) - _is_verbose(::DiffEqBase.DEVerbosity{B}) where {B} = B -end +_is_verbose(::AbstractVerbositySpecifier{B}) where {B} = B """ AbstractOperatorSplitFunction diff --git a/src/integrator.jl b/src/integrator.jl index e5befd1..7663e84 100644 --- a/src/integrator.jl +++ b/src/integrator.jl @@ -146,6 +146,7 @@ function SciMLBase.set_proposed_dt!(sub::SplitSubIntegrator, dt) end return nothing end +SciMLBase.get_proposed_dt(sub::SplitSubIntegrator) = sub.dtcache """ @@ -288,6 +289,15 @@ function SciMLBase.__init( # Every setting is either one value for the whole tree or a TreeOption carrying a # value per node. Beyond the four this integrator handles itself, whatever the # caller passes travels down to the leaf integrators. + # `dtmax` defaults to the length of the integration interval, as in + # OrdinaryDiffEqCore. Without a bound an adaptive splitting node can propose a step + # larger than the whole tspan: its error estimate only sees the *splitting* error, + # which vanishes identically wherever the operators commute, so a solution that has + # collapsed onto a common fixed point reports zero error and lets `dt` run away. + if !haskey(kwargs, :dtmax) + kwargs = merge(values(kwargs), (; dtmax = abs(tf - t0))) + end + verbose = _process_verbose(verbose) config = build_config_tree(prob.f, (; dt, adaptive, verbose, controller, kwargs...)) validate_dt_tree(config) tType = typeof(config.values.dt) @@ -841,10 +851,90 @@ function try_snap_children_to_tstop!(integrator::DEIntegrator, tstop) end end +""" + log_step_diagnostics(integrator, accepted) + +Report the step size a splitting node chose and the error estimate behind it, under the +`splitting_step_accepted` / `splitting_step_rejected` toggles of +[`OperatorSplittingVerbosity`](@ref). + +The splitting error estimate is otherwise invisible from the outside, which makes a step +size driven by an estimate that does not cover the whole error -- see the note in +[`PalindromicPairLieTrotterGodunov`](@ref) -- very hard to diagnose. +""" +function log_step_diagnostics(integrator::AnySplitIntegrator, accepted::Bool) + integrator.controller_cache === nothing && return + verbose = integrator.opts.verbose + t, dt = integrator.t, integrator.dt + eest = OrdinaryDiffEqCore.get_EEst(integrator) + if accepted + @SciMLMessage( + lazy"splitting step accepted: t = $(t), dt = $(dt), EEst = $(eest)", + verbose, :splitting_step_accepted + ) + else + @SciMLMessage( + lazy"splitting step rejected: t = $(t), dt = $(dt), EEst = $(eest)", + verbose, :splitting_step_rejected + ) + end + return +end + +""" + log_inner_solver_stats(integrator) + +Summarise, once at the end of a solve, how much work each operator's inner integrator +did: steps, rejections and whatever of `nf`/`njacs`/`nw`/`nsolve` its solver tracks. + +A splitting node counts only its own steps, so the cost of a solve is otherwise +invisible -- and it is the inner counters that show whether a step size is being paid +for in Jacobians and factorizations. Controlled by the `inner_solver_stats` toggle of +[`OperatorSplittingVerbosity`](@ref). +""" +function log_inner_solver_stats(integrator::OperatorSplittingIntegrator) + verbose = integrator.opts.verbose + @SciMLMessage(verbose, :inner_solver_stats) do + lines = ["inner integrator statistics"] + _collect_inner_stats!(lines, integrator.child_subintegrators, ()) + join(lines, "\n ") + end + return +end + +function _collect_inner_stats!(lines, children::Tuple, path::Tuple) + for (i, child) in enumerate(children) + _collect_inner_stats!(lines, child, (path..., i)) + end + return lines +end +function _collect_inner_stats!(lines, child::SplitSubIntegrator, path::Tuple) + push!(lines, "$(_showpath(path)): $(child.stats.naccept) steps, $(child.stats.nreject) rejected") + return _collect_inner_stats!(lines, child.child_subintegrators, path) +end +function _collect_inner_stats!(lines, child::DEIntegrator, path::Tuple) + s = SciMLBase.has_stats(child) ? child.sol.stats : nothing + if s === nothing + push!(lines, "$(_showpath(path)): no statistics available") + return lines + end + counters = ( + "steps" => :naccept, "rejected" => :nreject, "f" => :nf, + "jacs" => :njacs, "W" => :nw, "linsolve" => :nsolve, + ) + parts = [ + "$name=$(getfield(s, field))" for (name, field) in counters + if hasfield(typeof(s), field) + ] + push!(lines, "$(_showpath(path)) ($(nameof(typeof(child.alg)))): " * join(parts, " ")) + return lines +end + function step_footer!(integrator::AnySplitIntegrator) ttmp = integrator.t + integrator.dt # dt is signed by the integration direction footer_reset_flags!(integrator) setup_validity_flags!(integrator, ttmp) + log_step_diagnostics(integrator, should_accept_step(integrator)) if should_accept_step(integrator) OrdinaryDiffEqCore.increment_accept!(integrator.stats) integrator.last_step_failed = false @@ -1466,6 +1556,13 @@ function step_accept_controller!( # introspection. integrator.dt = dtnew integrator.dtcache = abs(dtnew) + # Bound the stored proposal, not just the step about to be taken. `step_header!` + # clamps `dt` before stepping either way, so this does not change which steps are + # taken -- but an unclamped `dtcache` is what `reinit!` restores and what `dt` + # reports afterwards, and a proposal above `dtmax` there reads as the bound having + # been ignored. + _fix_dt_at_bounds!(integrator) + integrator.dtcache = abs(integrator.dt) return nothing end @@ -1513,6 +1610,7 @@ function SciMLBase.postamble!(integrator::OperatorSplittingIntegrator) # step may run the finalizers and close out the solution. integrator.postamble_done && return nothing integrator.postamble_done = true + log_inner_solver_stats(integrator) DiffEqBase.finalize!(integrator.callback, integrator.u, integrator.t, integrator) save_endpoint!(integrator) # Drop whatever a previous, longer run left behind (`reinit!` without `erase_sol`). diff --git a/src/solver.jl b/src/solver.jl index db76d35..dc27b40 100644 --- a/src/solver.jl +++ b/src/solver.jl @@ -167,6 +167,8 @@ end """ PalindromicPairLieTrotterGodunov <: AbstractOperatorSplittingAlgorithm + PalindromicPairLieTrotterGodunov(inner_algs; local_extrapolation = true) + Second-order sequential operator splitting algorithm. One step solves the palindromic pair of [`LieTrotterGodunov`](@ref) sequences @@ -176,11 +178,21 @@ One step solves the palindromic pair of [`LieTrotterGodunov`](@ref) sequences from the same initial value. The leading splitting error of a Lie-Trotter sequence is ``\\frac{\\Delta t^2}{2}\\sum_{i ") @@ -211,14 +242,18 @@ alg_adaptive_order(::PalindromicPairLieTrotterGodunov) = 1 struct PalindromicPairLieTrotterGodunovCache{uType, uprevType, uforwardType} <: AbstractOperatorSplittingCache u::uType uprev::uprevType - uforward::uforwardType # end state of the A₁ → A₂ sequence; reused as the residual buffer + uforward::uforwardType # end state of the A₁ → A₂ sequence + utmp::uforwardType # half the pair difference, held while `u` is overwritten + local_extrapolation::Bool end function init_cache( f::GenericSplitFunction, alg::PalindromicPairLieTrotterGodunov; uprev::AbstractArray, u::AbstractVector, ) - return PalindromicPairLieTrotterGodunovCache(u, uprev, similar(u)) + return PalindromicPairLieTrotterGodunovCache( + u, uprev, similar(u), similar(u), alg.local_extrapolation + ) end function _ppltg_advance_child!(parent, child, i, dt) @@ -275,14 +310,26 @@ function _perform_step!( _ppltg_reverse_pass!(parent, reverse(children), dt, length(children)) parent.force_stepfail && return - # The average of the pair is the second order solution ... - parent.u .= (parent.u .+ uforward) ./ 2 - if parent.controller_cache !== nothing - # ... and half the pair difference the local error of a single sequence. + # `parent.u` holds the reverse sequence and `uforward` the forward one. Half their + # difference is the local error of a single sequence, whichever of the two the + # `local_extrapolation` setting goes on to propagate -- so it is taken before `u` is + # overwritten, and scaled afterwards against the solution actually advanced. + adaptive = parent.controller_cache !== nothing + adaptive && (@. cache.utmp = (parent.u - uforward) / 2) + + if cache.local_extrapolation + # The average of the pair is the second order solution. + parent.u .= (parent.u .+ uforward) ./ 2 + else + # The forward sequence is first order, and the estimate is exactly its error. + parent.u .= uforward + end + + if adaptive (; abstol, reltol, internalnorm) = parent.opts - @. uforward = (parent.u - uforward) / + @. cache.utmp = cache.utmp / (abstol + max(abs(parent.u), abs(parent.uprev)) * reltol) - OrdinaryDiffEqCore.set_EEst!(parent, internalnorm(uforward, parent.t + dt)) + OrdinaryDiffEqCore.set_EEst!(parent, internalnorm(cache.utmp, parent.t + dt)) end return end diff --git a/src/utils.jl b/src/utils.jl index e7c059e..dd9c165 100644 --- a/src/utils.jl +++ b/src/utils.jl @@ -96,15 +96,79 @@ function forward_sync_subintegrator!( reset_next_sync_continuous(parent) return nothing end + # Hand an adaptive child its step size state for the substep it is about to solve. + # + # * The standing proposal is *capped* at the substep length, never overwritten. + # Capping keeps the child from re-entering with a proposal beyond the substep + # (the sliver-regrowth problem), while a child whose converged step is a + # fraction of the substep keeps it: unconditionally handing the whole substep + # forces a guaranteed too-large first attempt -- one rejected step plus one + # wasted `W` factorization on *every* substep once the inner step is small. + # + # * The controller memory (`errold`/gain) is reset. The state was just rewritten + # from the outside, so the stored error history belongs to a different + # trajectory; carrying it makes the child's step sequence -- and through it the + # splitting error estimate -- an erratic function of the outer step size. + # Resetting it keeps the outer estimate smooth, which is what the outer + # controller needs to propose acceptable steps. + # + # Only for adaptive children. `set_proposed_dt!` writes `dtcache` as well as + # `dtpropose`, and `dtcache` is exactly what a *fixed* step child reads to size its + # step -- overwriting it there discards a per-node `dt` and collapses multi-rate + # subcycling to one inner step per substep. + if _child_is_adaptive(child) && isdtchangeable(child) + if abs(SciMLBase.get_proposed_dt(child)) > abs(parent.dt) + set_proposed_dt!(child, parent.dt) + end + _reinit_child_controller!(child) + end forward_sync_internal!(parent.u, parent.uprev, child, solution_indices) @timeit_debug "external sync" forward_sync_external!(parent, child, sync) return nothing end +# Reset a leaf's step size controller memory at a synchronization point. Guarded by +# `hasfield`: `controller_cache` is an OrdinaryDiffEqCore integrator field, and foreign +# DEIntegrator implementations without one simply keep their controller state. +# +# The stock `reinit_controller!` semantics -- for a PI cache, `errold = qoldinit` +# (1e-4), which throttles the first accepted steps of the substep through the +# `errold^beta2` term -- is kept *deliberately*. It replays the start-of-integration +# ramp at every synchronization, which on an operator whose converged step spans the +# whole substep multiplies its step count (measured ~4x for Heun's PI default; BS3 and +# Tsit5 defaults are unaffected). That cost is the fee for over-resolving the first +# inner steps of each substep, which keeps the inner-error contamination of the +# splitting error estimate below the outer controller's acceptance band. A "neutral" +# reset (`errold = 1`) was measured to halve the cost but inflate the outer rejection +# rate several-fold and the global error by an order of magnitude at tight tolerances. +function _reinit_child_controller!(child::DEIntegrator) + hasfield(typeof(child), :controller_cache) || return nothing + OrdinaryDiffEqCore.reinit_controller!(child, child.controller_cache) + return nothing +end + # Tell a leaf integrator that its state was changed from the outside so it discards # FSAL information. function mark_state_modified!(child::DEIntegrator) SciMLBase.derivative_discontinuity!(child, true) + _suppress_duplicate_fsal_reeval!(child) + return nothing +end + +# OrdinaryDiffEqCore 4.14.1 moved the `on_derivative_discontinuity_at_init!` call in +# `loopheader!` out of its `iter == 0` branch, so a standing `derivative_discontinuity` +# now fires it on every iteration -- on top of the per-step FSAL handling that already +# consumes the flag. That is two derivative evaluations per substep instead of one. +# +# The new call is guarded by `!reeval_fsal`, so flagging the refresh as already +# requested suppresses the duplicate. Only from `iter > 0`: before the first step +# nothing else consumes the flag, and that path is what refreshes the stale derivative +# the parent just invalidated. +function _suppress_duplicate_fsal_reeval!(child) + if hasfield(typeof(child), :reeval_fsal) && hasfield(typeof(child), :iter) && + child.iter > 0 + child.reeval_fsal = true + end return nothing end diff --git a/test/qa/qa.jl b/test/qa/qa.jl index 175052d..d6be868 100644 --- a/test/qa/qa.jl +++ b/test/qa/qa.jl @@ -21,5 +21,14 @@ run_qa( :failfactor_default, ), ), + no_stale_explicit_imports = (; + ignore = ( + # `MessageLevel` is imported for the `@verbosity_specifier` + # expansion in src/OrdinaryDiffEqOperatorSplitting.jl, which + # validates toggle values against it. Source analysis cannot see + # a use inside a macro expansion, so the import reads as stale. + :MessageLevel, + ), + ), ), )