diff --git a/Project.toml b/Project.toml index d8f5337..c8cf620 100644 --- a/Project.toml +++ b/Project.toml @@ -7,6 +7,7 @@ authors = ["Dennis Ogiermann and contr BinaryHeaps = "b2a6c25c-c996-4615-94ab-6e519ffb8690" CommonSolve = "38540f10-b2f7-11e9-35d8-d573e4eb0ff2" DiffEqBase = "2b5f629d-d688-5b77-993f-72d75c75574e" +NonlinearSolveFirstOrder = "5959db7a-ea39-4486-b5fe-2dd0bf03d60d" OrdinaryDiffEqCore = "bbf590c4-e513-4bbe-9b18-05decba2e5d8" OrdinaryDiffEqLowOrderRK = "1344f307-1e59-4825-a18e-ace9aa3fa4c6" PrecompileTools = "aea7be01-6a6a-4083-8856-8a6e6704d82a" @@ -22,6 +23,7 @@ BinaryHeaps = "1.0.0" CommonSolve = "0.2.4" DiffEqBase = "7.5" ModelingToolkit = "11" +NonlinearSolveFirstOrder = "2" OrdinaryDiffEqCore = "4.4" OrdinaryDiffEqLowOrderRK = "1.7, 2" OrdinaryDiffEqTsit5 = "1.1.0, 2" @@ -29,8 +31,8 @@ PrecompileTools = "1.1" RecursiveArrayTools = "3.39.0, 4" SafeTestsets = "0.1.0" SciMLBase = "3.36" -SciMLLogging = "2" SciMLIterators = "1" +SciMLLogging = "2" SciMLTesting = "2.4" SymbolicIndexingInterface = "0.3.36" Test = "1" diff --git a/_typos.toml b/_typos.toml index 625e683..94577a4 100644 --- a/_typos.toml +++ b/_typos.toml @@ -3,5 +3,21 @@ Strang = "Strang" # Citation key for Trotter (Tro:1959:psg) used in docstrings Tro = "Tro" +# David Ketcheson, in the citation key AuzHofKetKoc:2017:psm +Ket = "Ket" +# Citation keys for the order barrier: Sheng (She:1989:slp), Suzuki (Suz:1991:gtf) +She = "She" +Suz = "Suz" # Splitting variable name BA = "BA" +# Citation keys for the IMEX multirate methods: Fish/Reynolds/Roberts +# (FisReyRob:2023:iem), Chinomona/Reynolds (ChiRey:2021:iem), +# Sandu/Günther (SanGun:2015:gsa), Luan/Chinomona/Reynolds (LuaChiRey:2020:nch) +Fis = "Fis" +Rey = "Rey" +Rob = "Rob" +Chi = "Chi" +Gun = "Gun" +Lua = "Lua" +# Anders Kvaerno, whose Prothero-Robinson variant is the KPR convergence test problem +Kvaerno = "Kvaerno" diff --git a/docs/src/api-reference/index.md b/docs/src/api-reference/index.md index 44b0610..c9b4d20 100644 --- a/docs/src/api-reference/index.md +++ b/docs/src/api-reference/index.md @@ -18,6 +18,18 @@ GenericSplitFunction LieTrotterGodunov StrangMarchuk PalindromicPairLieTrotterGodunov +Ruth3 +Yoshida4 +AdjointPair +IMEXMRISR2 +IMEXMRISR3 +``` + +### Implicit-explicit multirate + +```@docs +OrdinaryDiffEqOperatorSplitting.AbstractIMEXMRISR +OrdinaryDiffEqOperatorSplitting.MRISRCoefficients ``` ## Per-node configuration diff --git a/docs/src/assets/references.bib b/docs/src/assets/references.bib index 3cb2732..21ed7f8 100644 --- a/docs/src/assets/references.bib +++ b/docs/src/assets/references.bib @@ -52,3 +52,104 @@ @incollection{Mar:1971:tsm year={1971}, publisher={Academic Press} } + +@article{Rut:1983:cim, + title={A canonical integration technique}, + author={Ruth, Ronald D.}, + journal={IEEE Transactions on Nuclear Science}, + volume={NS-30}, + number={4}, + pages={2669--2671}, + year={1983}, + doi={10.1109/TNS.1983.4332919}, + publisher={IEEE} +} + +@article{Yos:1990:cho, + title={Construction of higher order symplectic integrators}, + author={Yoshida, Haruo}, + journal={Physics Letters A}, + volume={150}, + number={5--7}, + pages={262--268}, + year={1990}, + doi={10.1016/0375-9601(90)90092-3}, + publisher={Elsevier} +} + +@article{AuzHofKetKoc:2017:psm, + title={Practical splitting methods for the adaptive integration of nonlinear evolution equations. {P}art {I}: {C}onstruction of optimized schemes and pairs of schemes}, + author={Auzinger, Winfried and Hofst{\"a}tter, Harald and Ketcheson, David and Koch, Othmar}, + journal={BIT Numerical Mathematics}, + volume={57}, + number={1}, + pages={55--74}, + year={2017}, + doi={10.1007/s10543-016-0626-9}, + publisher={Springer} +} + +@article{She:1989:slp, + title={Solving linear partial differential equations by exponential splitting}, + author={Sheng, Qin}, + journal={IMA Journal of Numerical Analysis}, + volume={9}, + number={2}, + pages={199--212}, + year={1989}, + doi={10.1093/imanum/9.2.199}, + publisher={Oxford University Press} +} + +@article{Suz:1991:gtf, + title={General theory of fractal path integrals with applications to many-body theories and statistical physics}, + author={Suzuki, Masuo}, + journal={Journal of Mathematical Physics}, + volume={32}, + number={2}, + pages={400--407}, + year={1991}, + doi={10.1063/1.529425}, + publisher={AIP} +} + +@article{FisReyRob:2023:iem, + title={Implicit-explicit multirate infinitesimal stage-restart methods}, + author={Fish, Alex C. and Reynolds, Daniel R. and Roberts, Steven B.}, + journal={arXiv preprint arXiv:2301.00865}, + year={2023}, + doi={10.48550/arXiv.2301.00865} +} + +@article{ChiRey:2021:iem, + title={Implicit-explicit multirate infinitesimal GARK methods}, + author={Chinomona, Rujeko and Reynolds, Daniel R.}, + journal={SIAM Journal on Scientific Computing}, + volume={43}, + number={5}, + pages={A3082--A3113}, + year={2021}, + doi={10.1137/20M1354349} +} + +@article{SanGun:2015:gsa, + title={A generalized-structure approach to additive Runge--Kutta methods}, + author={Sandu, Adrian and G{\"u}nther, Michael}, + journal={SIAM Journal on Numerical Analysis}, + volume={53}, + number={1}, + pages={17--42}, + year={2015}, + doi={10.1137/130943224} +} + +@article{LuaChiRey:2020:nch, + title={A new class of high-order methods for multirate differential equations}, + author={Luan, Vu Thai and Chinomona, Rujeko and Reynolds, Daniel R.}, + journal={SIAM Journal on Scientific Computing}, + volume={42}, + number={2}, + pages={A1245--A1268}, + year={2020}, + doi={10.1137/19M125621X} +} diff --git a/docs/src/devdocs/index.md b/docs/src/devdocs/index.md index 518509e..13bc6dc 100644 --- a/docs/src/devdocs/index.md +++ b/docs/src/devdocs/index.md @@ -51,6 +51,8 @@ prob = OperatorSplittingProblem(f, u0, tspan) OrdinaryDiffEqOperatorSplitting.AbstractOperatorSplittingAlgorithm OrdinaryDiffEqOperatorSplitting.AbstractOperatorSplittingCache OrdinaryDiffEqOperatorSplitting.init_cache +OrdinaryDiffEqOperatorSplitting.init_cache_with_parameters +OrdinaryDiffEqOperatorSplitting.child_node_count OrdinaryDiffEqOperatorSplitting._perform_step! OrdinaryDiffEqOperatorSplitting.advance_solution_by! OrdinaryDiffEqOperatorSplitting.child_failed @@ -78,6 +80,23 @@ field named `inner_algs`, because that is how the tree of integrators is built alongside the tree of split functions. The cache is where a scheme keeps the buffers it needs beyond `u`/`uprev`. +Two further hooks exist for algorithms that do not fit the "one child per operator, +coupled only through initial conditions" shape. Both have defaults, so an ordinary +scheme never mentions them: + +- [`OrdinaryDiffEqOperatorSplitting.child_node_count`](@ref) says how many of the + operators get a child integrator. The default is all of them; an algorithm that only + *evaluates* some operators returns fewer. +- [`OrdinaryDiffEqOperatorSplitting.init_cache_with_parameters`](@ref) is what the tree + actually calls, and it forwards to `init_cache` while dropping the problem + parameters. Override it when the cache itself needs them -- for instance to build a + nonlinear solver around one of the operators. + +A node's cache is built *before* its children, so a child's right-hand side may be +wrapped around something the cache owns. `IMEXMRISR3` uses all of this: it builds one +child from the fast operator, wrapped so that each stage's forcing term, which lives in +the cache, is added to the fast right-hand side. + ```julia using SciMLBase, OrdinaryDiffEqOperatorSplitting import OrdinaryDiffEqOperatorSplitting as OS @@ -146,8 +165,9 @@ end This example is written for exactly two operators. A scheme that works for any number of them loops over `children` with `Unrolled.@unroll`, as the built-in algorithms in -`src/solver.jl` do; a plain `for` loop over the heterogeneously typed tuple would be -type unstable. +`src/solvers/` do; a plain `for` loop over the heterogeneously typed tuple would be +type unstable. `advance_one_child!` above is `src/solvers/common.jl`'s +`_advance_child!`, which the built-in schemes share. ### Adaptive algorithms @@ -177,9 +197,83 @@ end OrdinaryDiffEqCore interface for the estimate; go through them rather than touching the `EEst` field, whose location on the integrator is an implementation detail. -See [`PalindromicPairLieTrotterGodunov`](@ref) in `src/solver.jl` for a complete -example, and [Adaptive time stepping](@ref) for how the two layers of adaptivity -interact. +See [`PalindromicPairLieTrotterGodunov`](@ref) in `src/solvers/adjoint_pair.jl` for a +complete example, and [Adaptive time stepping](@ref) for how the two layers of +adaptivity interact. + +## Coefficient tables + +Schemes of order three and above are not written out as passes over the children. +They are described by a table of coefficients and stepped by one shared traversal, +which lives in `src/solvers/coefficients.jl`; the schemes themselves +(`src/solvers/tables.jl`) are then little more than the table plus two interface +methods. See [Higher order splittings](@ref theory_higher-order) for where the +tables come from. + +```@docs +OrdinaryDiffEqOperatorSplitting.SplittingCoefficients +OrdinaryDiffEqOperatorSplitting.coefficients +OrdinaryDiffEqOperatorSplitting.order +``` + +A table-driven scheme is added by giving it a struct, a table, `coefficients`, +`order`, and an `init_cache` returning the shared +`SplittingCoefficientsCache` — no stepping code of its own: + +```julia +struct MyThirdOrder{AlgTupleType <: Tuple} <: + OrdinaryDiffEqOperatorSplitting.AbstractOperatorSplittingAlgorithm + inner_algs::AlgTupleType +end + +const MY_COEFFICIENTS = OrdinaryDiffEqOperatorSplitting.SplittingCoefficients( + (7 // 24, 2 // 3), (3 // 4, -2 // 3), (-1 // 24, 1 // 1) +) + +OrdinaryDiffEqOperatorSplitting.coefficients(::MyThirdOrder) = MY_COEFFICIENTS +OrdinaryDiffEqOperatorSplitting.order(::MyThirdOrder) = 3 + +function OrdinaryDiffEqOperatorSplitting.init_cache( + f::GenericSplitFunction, alg::MyThirdOrder; + uprev::AbstractArray, u::AbstractVector, +) + return OrdinaryDiffEqOperatorSplitting.SplittingCoefficientsCache( + u, uprev, OrdinaryDiffEqOperatorSplitting.coefficients(alg)) +end +``` + +Only the consistency condition is checked when the table is built, so a table that +constructs successfully can still fail to reach the order it claims; a convergence +test is the only real check. + +Two properties of the traversal are worth knowing when reading or extending it: + +- **A zero coefficient is skipped entirely**, synchronization included, since the + flow is the identity. `Yoshida4`'s last stage relies on this. +- **The first flow of a step is always synchronized.** Strang-Marchuk skips that + sync because its reverse pass ends on operator 1, leaving that child's buffer + current; a general table ends on operator `N`, so operator 1's buffer is stale and + the same shortcut would silently corrupt every step after the first. + +Because a table with negative coefficients steps some children backward, a +table-driven scheme also depends on the direction reversal described under +[Backward sub-steps](@ref devdocs_backward-substeps). + +If the scheme's order is odd, wrapping it in `AdjointPair` makes it adaptive for +free: the adjoint is the same table traversed backwards, so nothing further is +needed from the scheme. + +## [Backward sub-steps](@id devdocs_backward-substeps) + +An inner integrator fixes its direction of integration when it is constructed, and +a scheme with negative coefficients has to step it the other way. Rather than build +two integrators per child, a sub-step against the child's direction reverses the +child in place, steps, and reverses it back: + +```@docs +OrdinaryDiffEqOperatorSplitting.reverse_direction! +OrdinaryDiffEqOperatorSplitting.tstops_and_saveat_heaps +``` ## Dense output diff --git a/docs/src/topics/adaptivity.md b/docs/src/topics/adaptivity.md index c2f28c8..f0a14db 100644 --- a/docs/src/topics/adaptivity.md +++ b/docs/src/topics/adaptivity.md @@ -6,10 +6,14 @@ Two independent layers of a splitting tree can adapt their step sizes: they would outside of this package. Their behavior is governed by the tolerances and options they receive. - **Splitting nodes** adapt the splitting step itself. This requires an algorithm - that produces an error estimate of the splitting error; - [`PalindromicPairLieTrotterGodunov`](@ref) is currently the only one. It advances - with the average of the two mutually reversed Lie-Trotter sequences and uses half - their difference as the local error estimate. + that produces an error estimate of the splitting error, which here means running a + scheme together with its adjoint: the average of the two is the solution and half + their difference is the local error estimate (see + [Adjoint pairs](@ref theory_higher-order)). + [`PalindromicPairLieTrotterGodunov`](@ref) is that construction for the + Lie-Trotter sequence, and [`AdjointPair`](@ref) builds it from any odd-order + scheme — `AdjointPair(Ruth3((Tsit5(), Tsit5())))` is a fourth-order adaptive + splitting. Both cost two sweeps per step. By default every node adapts exactly if its own algorithm can: for diff --git a/docs/src/topics/time-integration.md b/docs/src/topics/time-integration.md index 9ecb7f5..f029c9b 100644 --- a/docs/src/topics/time-integration.md +++ b/docs/src/topics/time-integration.md @@ -165,6 +165,190 @@ $[L_1, L_2] = L_1 L_2 - L_2 L_1$ to cancel, leaving a local truncation error of $O(t^3)$ and hence second-order global accuracy. The same argument extends to the general $N$-operator palindromic scheme. +## [Higher order splittings](@id theory_higher-order) + +Lie-Trotter-Godunov and Strang-Marchuk are both instances of a more general +construction. A splitting scheme applies the sub-flows in a fixed sequence, each for +a fixed fraction of the step, so for $N$ operators it is completely described by an +$S \times N$ table of coefficients $a_{ji}$: stage $j$ advances operator $i$ by +$a_{ji} \Delta t$. In the linear two-operator case, + +```math +\mathcal{S}(\Delta t) = \prod_{j=1}^{S} e^{a_{jN} \Delta t L_N} \cdots e^{a_{j1} \Delta t L_1} \, . +``` + +Lie-Trotter-Godunov is the one-stage table $a = (1, 1)$ and Strang-Marchuk is the +two-stage table $a = \bigl((\tfrac{1}{2}, 1), (\tfrac{1}{2}, 0)\bigr)$. + +Each operator's coefficients must sum to one, + +```math +\sum_{j=1}^{S} a_{ji} = 1 \quad \text{for every } i \, , +``` + +since otherwise the scheme does not even advance every sub-problem by $\Delta t$. +This is the consistency condition, and it is the only one this package checks when a +table is constructed. Attaining order $p$ imposes further conditions, one per +independent commutator up to order $p$, obtained by matching the +Baker-Campbell-Hausdorff expansion of the product above against that of +$e^{\Delta t (L_1 + L_2)}$ — the same computation as in the two analyses above, +carried further. + +### Composition: the triple jump + +Solving the order conditions directly gets unpleasant quickly. A cheaper route is +*composition*: build a higher-order scheme out of a symmetric one of lower order. +If $\mathcal{S}_2$ is any symmetric second-order scheme, then + +```math +\mathcal{S}_4(\Delta t) = \mathcal{S}_2(w_1 \Delta t) \, \mathcal{S}_2(w_0 \Delta t) \, \mathcal{S}_2(w_1 \Delta t) +``` + +is symmetric for any weights, and hence of even order. It is of order four as soon +as the weights satisfy + +```math +2 w_1 + w_0 = 1 \, , \qquad 2 w_1^3 + w_0^3 = 0 \, , +``` + +the first being consistency and the second the cancellation of the third-order term. +The real solution is $w_1 = 1/(2 - 2^{1/3})$ and $w_0 = -2^{1/3} w_1$, giving +Yoshida's "triple jump" [Yos:1990:cho](@cite), implemented here as +[`Yoshida4`](@ref). Writing the three Strang steps out as a flat sequence of flows +and merging the adjacent flows of the same operator that the composition leaves next +to each other collapses nine flows to eight — which is exactly the four-stage table +`Yoshida4` carries, its last stage having a zero second coefficient. + +### The order barrier and negative coefficients + +Note that $w_0 < 0$ above. This is not an artifact of the construction: no splitting +scheme of order greater than two has all coefficients positive +[She:1989:slp,Suz:1991:gtf](@cite). Any third- or higher-order splitting therefore +integrates some sub-problem *backward in time* during part of every step, which has +two practical consequences. + +First, the sub-problems must admit a backward flow. For a parabolic sub-problem — +diffusion, say — the backward evolution is ill-posed and the negative sub-steps are +violently unstable, so on a reaction-diffusion system the higher-order schemes here +are not usable on the diffusion operator, however attractive their order. This is +the reason Strang-Marchuk remains the workhorse despite being only second order. + +Second, the implementation has to actually run its sub-integrators backwards. An +inner integrator fixes its direction of integration at construction, so a negative +sub-step temporarily reverses it; see the developer documentation for the details. + +### Adjoint pairs + +The *adjoint* of a scheme is + +```math +\mathcal{S}^*(\Delta t) = \mathcal{S}(-\Delta t)^{-1} \, , +``` + +which for a splitting scheme is simply its whole sequence of flows run in reverse +order, every coefficient keeping its sign and its operator. A scheme is symmetric +exactly when $\mathcal{S}^* = \mathcal{S}$, which is why Strang-Marchuk — a +palindrome — gains an order over Lie-Trotter-Godunov. + +If $\mathcal{S}$ has order $p$ with leading local error $C \Delta t^{p+1}$, then +$\mathcal{S}^*$ has the same order with leading error $(-1)^p C \Delta t^{p+1}$. For +**odd** $p$ the two signs oppose, so running the pair from the same initial value +gives, at twice the cost of one scheme, + +```math +\frac{\mathcal{S} + \mathcal{S}^*}{2} \quad \text{of order } p+1 \, , +\qquad +\frac{\mathcal{S} - \mathcal{S}^*}{2} \quad \text{an estimate of the local error of } \mathcal{S} \, , +``` + +the latter being asymptotically correct as $\Delta t \to 0$ +[AuzHofKetKoc:2017:psm](@cite). This is the Milne device applied to a scheme and its +adjoint, and it is what makes the splitting error itself estimable and hence the +splitting step adaptive — see [Adaptive time stepping](@ref). The construction is +[`AdjointPair`](@ref); at $p = 1$, with Lie-Trotter-Godunov as the base, it is the +pair of mutually reversed sequences implemented directly as +[`PalindromicPairLieTrotterGodunov`](@ref). + +For even $p$ the two leading terms are *equal* rather than opposite: averaging +cancels nothing and the difference is not an error estimate, which is why +[`AdjointPair`](@ref) rejects an even-order base scheme. + +## [Implicit-explicit multirate methods](@id theory_imex-multirate) + +Everything above splits the *state*: each operator owns a slice of the solution vector +and a step is a sequence of flows, coupled only through the initial condition each flow +is handed. That weak coupling is what limits Lie-Trotter-Godunov and Strang-Marchuk to +first and second order no matter how accurately the sub-problems are solved +[FisReyRob:2023:iem](@cite). + +The IMEX-MRI-SR methods of [FisReyRob:2023:iem](@cite) break out of that barrier by +splitting the *right-hand side* instead. One additive partition, + +```math +y'(t) = f^{\{F\}}(t, y) + f^{\{E\}}(t, y) + f^{\{I\}}(t, y), +``` + +separates rapidly evolving dynamics ($F$) from slow dynamics that are in turn split in +an implicit-explicit fashion: $f^{\{I\}}$ is stiff and solved implicitly, $f^{\{E\}}$ is +non-stiff and treated explicitly. All three act on the *whole* state. + +A step from $t_n$ to $t_n + H$ evolves a sequence of *forced* fast initial value +problems, each restarted from $y_n$ — hence "stage restart" — and follows each with one +implicit solve at the slow time scale: + +```math +\begin{aligned} +Y_1 &= y_n, \\ +v_i'(\theta) &= f^{\{F\}}(t_n + \theta, v_i(\theta)) + g_i(\theta), + \quad \theta \in [0, c_i H], \quad v_i(0) = y_n, \\ +Y_i &= v_i(c_i H) + H \sum_{j \le i} \gamma_{i,j} f_j^{\{I\}}, +\end{aligned} +``` + +with $y_{n+1} = Y_{s}$, and the forcing built from the slow tendencies of the previous +stages, + +```math +g_i(\theta) = \frac{1}{c_i} \sum_{j < i} + \omega_{i,j}\!\left(\frac{\theta}{c_i H}\right) + \left(f_j^{\{E\}} + f_j^{\{I\}}\right). +``` + +The forcing is what supplies the strong coupling: information from the slow operators +enters the fast sub-problem throughout its evolution, not merely through its initial +condition. Because $\omega_{i,j}$ is a polynomial in the normalized fast time, the sum +over stages collapses once per stage into one vector per power, so a fast right-hand side +evaluation stays cheap regardless of the stage count. + +The fast sub-problem is solved by any ordinary `OrdinaryDiffEq` algorithm, given its own +step size through the per-node `dt` described under +[Multi-rate integration](@ref); the paper's experiments use $h = H/10$. The slow implicit +stages are nonlinear systems, solved by the algorithm's `nlsolve`. + +Two methods are provided, [`IMEXMRISR2`](@ref) and [`IMEXMRISR3`](@ref), of order two +and three. Both carry an embedding one order lower, which gives a genuine local error +estimate and hence adaptivity — unlike the splitting schemes, this needs no second pass +over the step, only one extra fast solve over $[0, H]$. The paper's fourth order method +is deliberately not included: its joint stability region is empty and its embedding +gives poor estimates, which the authors report as getting "stuck" oscillating between +accepted and rejected steps. + +Because the partition is additive rather than state-disjoint, these algorithms expect a +[`GenericSplitFunction`](@ref) whose three operators — in the order +$f^{\{F\}}, f^{\{E\}}, f^{\{I\}}$ — each span the whole state: + +```julia +f = GenericSplitFunction( + (f_fast, f_explicit, f_implicit), + (1:n, 1:n, 1:n), # additive: every operator sees the whole state +) + +dt = TreeOption(f, H) +dt[f[1]] = H / 10 # the fast sub-problem's step size + +solve(OperatorSplittingProblem(f, u0, tspan), IMEXMRISR3(BS3()); dt, adaptive = true) +``` + ## References ```@bibliography diff --git a/src/OrdinaryDiffEqOperatorSplitting.jl b/src/OrdinaryDiffEqOperatorSplitting.jl index 661dc24..9c726dd 100644 --- a/src/OrdinaryDiffEqOperatorSplitting.jl +++ b/src/OrdinaryDiffEqOperatorSplitting.jl @@ -14,6 +14,10 @@ import SymbolicIndexingInterface: variable_symbols import RecursiveArrayTools +# Only for the default `nlsolve` of the IMEX-MRI-SR methods, whose slow implicit stages +# are nonlinear systems. Users can pass any nonlinear algorithm they like instead. +import NonlinearSolveFirstOrder: NewtonRaphson + import OrdinaryDiffEqCore: OrdinaryDiffEqCore, isdtchangeable, stepsize_controller!, step_accept_controller!, step_reject_controller!, accept_step_controller @@ -150,11 +154,19 @@ include("function.jl") include("config_tree.jl") include("problem.jl") include("integrator.jl") -include("solver.jl") +include("solvers/common.jl") +include("solvers/coefficients.jl") +include("solvers/lie_trotter_godunov.jl") +include("solvers/strang_marchuk.jl") +include("solvers/tables.jl") +include("solvers/adjoint_pair.jl") +include("solvers/mri_tables.jl") +include("solvers/imex_mri_sr.jl") include("utils.jl") export GenericSplitFunction, OperatorSplittingProblem, LieTrotterGodunov, StrangMarchuk, - PalindromicPairLieTrotterGodunov + PalindromicPairLieTrotterGodunov, Ruth3, Yoshida4, AdjointPair +export IMEXMRISR2, IMEXMRISR3 export SplitNode, TreeOption include("precompilation.jl") diff --git a/src/integrator.jl b/src/integrator.jl index e5befd1..39e63de 100644 --- a/src/integrator.jl +++ b/src/integrator.jl @@ -134,8 +134,6 @@ end # --- SplitSubIntegrator interface --- -tdir(integrator::SplitSubIntegrator) = sign(integrator.dt) - # proposed-dt interface (mirrors ODEIntegrator) function SciMLBase.set_proposed_dt!(sub::SplitSubIntegrator, dt) if sub.dtcache != dt # only touch if actually changing @@ -306,9 +304,6 @@ function SciMLBase.__init( tstops = () end - # Heaps store raw times and carry the integration direction in their ordering. - # (OrdinaryDiffEqCore's initialize_tstops stores tdir-scaled times instead, which - # is incompatible with the heaps reinit! rebuilds and breaks backward tspans.) tstops_internal, saveat_internal = tstops_and_saveat_heaps( t0, tf, (tstops..., d_discontinuities...), saveat ) @@ -338,6 +333,15 @@ function SciMLBase.__init( DiffEqBase.CallbackCache(u, max_len_cb, eventErrType, eventErrType) end + # The cache is built before the children, not after: an algorithm whose children + # need something the cache owns can only build them once it exists. IMEX-MRI-SR is + # the case in point -- its fast child integrates a right-hand side wrapped around + # the forcing term that lives in the cache. + cache = init_cache_with_parameters( + prob.f, alg, p; + uprev = uprev, u = u, + ) + child_subintegrators = build_subintegrators( prob, alg, uprev, u, @@ -345,16 +349,12 @@ function SciMLBase.__init( 1:length(u), t0, tf, tstops, saveat, d_discontinuities, callback, - config - ) - - cache = init_cache( - prob.f, alg; - uprev = uprev, u = u, + config, cache ) - child_solution_indices = ntuple(i -> prob.f.solution_indices[i], length(prob.f.functions)) - child_synchronizers = ntuple(i -> prob.f.synchronizers[i], length(prob.f.functions)) + nchildren = child_node_count(alg, prob.f) + child_solution_indices = ntuple(i -> prob.f.solution_indices[i], nchildren) + child_synchronizers = ntuple(i -> prob.f.synchronizers[i], nchildren) root_controller_cache = _node_controller_cache(alg, cache, config.values, tType) EEst = root_controller_cache === nothing ? tType(NaN) : one(tType) @@ -447,8 +447,8 @@ function DiffEqBase.reinit!( reinit_callbacks = true, reinit_retcode = true ) - # The heap ordering types and every node's tdir are fixed at init, so a reinit! - # cannot flip the integration direction. + # Every node's tdir is fixed at init, and the heaps it hands to its children are + # scaled by it, so a reinit! cannot flip the integration direction. (tf > t0) == (integrator.tdir > 0) || error("reinit! cannot change the direction of integration. Build a new integrator instead.") @@ -596,22 +596,20 @@ end # --------------------------------------------------------------------------- function _handle_tstop!(integrator::AnySplitIntegrator) if SciMLBase.has_tstop(integrator) - # The heaps store raw times; comparisons happen in tdir-space so that - # "ahead"/"behind" is direction independent. - tdir_t = tdir(integrator) * integrator.t - tdir_tstop = tdir(integrator) * SciMLBase.first_tstop(integrator) + tdir_t = integrator.tdir * integrator.t + tdir_tstop = SciMLBase.first_tstop(integrator) if tdir_t == tdir_tstop while tdir_t == tdir_tstop SciMLBase.pop_tstop!(integrator) SciMLBase.has_tstop(integrator) ? - (tdir_tstop = tdir(integrator) * SciMLBase.first_tstop(integrator)) : break + (tdir_tstop = SciMLBase.first_tstop(integrator)) : break end notify_integrator_hit_tstop!(integrator) elseif tdir_t > tdir_tstop if !integrator.dtchangeable SciMLBase.change_t_via_interpolation!( integrator, - SciMLBase.pop_tstop!(integrator), + pop_next_tstop!(integrator), Val{true} ) notify_integrator_hit_tstop!(integrator) @@ -772,7 +770,7 @@ end function modify_dt_for_tstops!(integrator) if SciMLBase.has_tstop(integrator) tdir_t = integrator.tdir * integrator.t - tdir_tstop = integrator.tdir * SciMLBase.first_tstop(integrator) + tdir_tstop = SciMLBase.first_tstop(integrator) if integrator.opts.adaptive integrator.dt = integrator.tdir * min(abs(integrator.dt), abs(tdir_tstop - tdir_t)) # step! to the end @@ -814,9 +812,11 @@ _snap_window(t, tstop, dt) = function fixed_t_for_floatingpoint_error!(integrator::AnySplitIntegrator, ttmp) return if DiffEqBase.has_tstop(integrator) - tstop = DiffEqBase.first_tstop(integrator) + tstop = next_tstop(integrator) if abs(ttmp - tstop) < _snap_window(integrator.t, tstop, integrator.dt) - try_snap_children_to_tstop!.(integrator.child_subintegrators, tstop) + try_snap_children_to_tstop!.( + integrator.child_subintegrators, tstop, integrator.dt + ) tstop else ttmp @@ -825,16 +825,20 @@ function fixed_t_for_floatingpoint_error!(integrator::AnySplitIntegrator, ttmp) ttmp end end -function try_snap_children_to_tstop!(integrator::SplitSubIntegrator, tstop) - if abs(tstop - integrator.t) < _snap_window(integrator.t, tstop, integrator.dt) +# `scale` is the *outer* step size, and stays the outer one all the way down the tree. +# All the drift being absorbed here was accumulated by subdividing that one step, so it +# is the right yardstick; a child's own `dt` is whatever fraction it last landed on and +# can be arbitrarily smaller, collapsing the window below the drift it has to absorb. +function try_snap_children_to_tstop!(integrator::SplitSubIntegrator, tstop, scale) + if abs(tstop - integrator.t) < _snap_window(integrator.t, tstop, scale) integrator.t = tstop else @warn "Failed to snap timestep for integrator $(integrator.t) with parent integrator hitting the tstop $(tstop)." end - return try_snap_children_to_tstop!.(integrator.child_subintegrators, tstop) + return try_snap_children_to_tstop!.(integrator.child_subintegrators, tstop, scale) end -function try_snap_children_to_tstop!(integrator::DEIntegrator, tstop) - return if abs(tstop - integrator.t) < _snap_window(integrator.t, tstop, integrator.dt) +function try_snap_children_to_tstop!(integrator::DEIntegrator, tstop, scale) + return if abs(tstop - integrator.t) < _snap_window(integrator.t, tstop, scale) integrator.t = tstop else @warn "Failed to snap timestep for integrator $(integrator.t) with parent integrator hitting the tstop $(tstop)." @@ -854,7 +858,9 @@ function step_footer!(integrator::AnySplitIntegrator) # halves) accumulate ulp-level drift from the parent's exact `t`. # Re-anchor children to the parent's canonical time here so the # drift cannot accumulate across outer steps. - try_snap_children_to_tstop!.(integrator.child_subintegrators, integrator.t) + try_snap_children_to_tstop!.( + integrator.child_subintegrators, integrator.t, integrator.dt + ) step_accept_controller!(integrator) validate_time_point(integrator) handle_callbacks!(integrator) # also does the saving @@ -918,8 +924,7 @@ end function DiffEqBase.solve!(integrator::OperatorSplittingIntegrator) while !isempty(integrator.tstops) - while tdir(integrator) * integrator.t < - tdir(integrator) * SciMLBase.first_tstop(integrator) + while integrator.tdir * integrator.t < SciMLBase.first_tstop(integrator) step_header!(integrator) @timeit_debug "check_error" SciMLBase.check_error!(integrator) ∉ ( ReturnCode.Success, ReturnCode.Default, @@ -939,7 +944,7 @@ end function DiffEqBase.step!(integrator::AnySplitIntegrator) @timeit_debug "step!" if integrator.advance_to_tstop - tstop = SciMLBase.first_tstop(integrator) + tstop = next_tstop(integrator) while !reached_tstop(integrator, tstop) step_header!(integrator) @timeit_debug "check_error" SciMLBase.check_error!(integrator) ∉ ( @@ -973,7 +978,7 @@ end # integration. function DiffEqBase.step!(integrator::AnySplitIntegrator, dt, stop_at_tdt = false) @timeit_debug "step!" begin - tdir(integrator) * dt < zero(dt) && error("Cannot step backward.") + integrator.tdir * dt < zero(dt) && error("Cannot step backward.") stop_at_tdt && !integrator.dtchangeable && error("Cannot stop at t + dt if dtchangeable is false") tnext = integrator.t + dt @@ -1235,12 +1240,9 @@ function SciMLBase.savevalues!( return saved, savedexactly tf = integrator.sol.prob.tspan[2] - # The heaps store raw times and carry the direction in their ordering, so the - # comparison is scaled by tdir rather than the stored value. tdir_t = integrator.tdir * integrator.t - while !isempty(integrator.saveat) && - integrator.tdir * first(integrator.saveat) <= tdir_t - curt = pop!(integrator.saveat) + while !isempty(integrator.saveat) && first(integrator.saveat) <= tdir_t + curt = integrator.tdir * pop!(integrator.saveat) if curt == integrator.t # `save_end` owns the final point; leave it to the postamble. (!save_end && curt == tf) && continue @@ -1484,8 +1486,13 @@ end # Time helpers -tdir(integrator) = - integrator.tstops.ordering isa BinaryHeaps.FasterForward ? 1 : -1 +# +# `tstops`/`saveat` keys are tdir-scaled (see `tstops_and_saveat_heaps`), so a raw time +# is compared against them as `tdir * t`, and a key is turned back into a time by the +# same multiplication. +tdir(integrator::AnySplitIntegrator) = integrator.tdir +next_tstop(integrator) = integrator.tdir * SciMLBase.first_tstop(integrator) +pop_next_tstop!(integrator) = integrator.tdir * SciMLBase.pop_tstop!(integrator) is_past_t(integrator, t) = tdir(integrator) * (t - integrator.t) ≤ zero(integrator.t) function reached_tstop(integrator, tstop, stop_at_tstop = integrator.dtchangeable) @@ -1547,7 +1554,7 @@ function advance_solution_by!(integrator::AnySplitIntegrator, dt) return advance_solution_by!(integrator, integrator.cache, dt) end -# Algorithm-level dispatch (implemented in solver.jl per algorithm) +# Algorithm-level dispatch (implemented per algorithm under src/solvers/) function advance_solution_by!( integrator::AnySplitIntegrator, cache::AbstractOperatorSplittingCache, dt @@ -1616,11 +1623,10 @@ function advance_solution_by!( return end -# `dt` stays signed through the splitting tree, following the SciML `step!` -# convention: the sign has to match the child's own integration direction, which -# equals the tree's. Advancing a child *against* its direction (negative substeps -# of higher order compositions) is not supported yet: leaf ODEIntegrators cannot -# step against the tdir their tspan fixed at construction. +# `dt` stays signed through the splitting tree, following the SciML `step!` convention: +# the sign has to match the child's own integration direction. Schemes of order three +# and above have negative coefficients, so a substep can oppose the tree's direction, +# and a child's direction is fixed at construction -- hence `reverse_direction!`. # Recursion dispatch function advance_solution_by!( @@ -1628,13 +1634,26 @@ function advance_solution_by!( sub::SplitSubIntegrator, dt ) - SciMLBase.step!(sub, dt, true) + _step_signed!(sub, dt) return nothing end # Leaf dispatch function advance_solution_by!(outer::AnySplitIntegrator, child::DEIntegrator, dt) - SciMLBase.step!(child, dt, true) + _step_signed!(child, dt) + return nothing +end + +# Reversing first is also what satisfies `step!`'s own direction guard: once `tdir` is +# flipped, a negative `dt` agrees with it. +function _step_signed!(child, dt) + if child.tdir * dt < zero(dt) + reverse_direction!(child) + SciMLBase.step!(child, dt, true) + reverse_direction!(child) + else + SciMLBase.step!(child, dt, true) + end return nothing end @@ -1643,8 +1662,32 @@ end # Tree construction # --------------------------------------------------------------------------- -# Top-level builder: called from __init with the full problem. -# Returns (child_subintegrators::Tuple, cache::AbstractOperatorSplittingCache) +""" + init_cache_with_parameters(f, alg, p; uprev, u) + +Internal entry point the tree uses to build a node's cache. + +Almost no cache depends on the problem parameters, so this forwards to the documented +[`init_cache`](@ref) extension point and drops `p`. IMEX-MRI-SR is the exception: its +cache holds a nonlinear solver for the slow implicit stages, which has to be built +around the parameters of `f^{I}`. +""" +init_cache_with_parameters(f, alg, p; uprev, u) = init_cache(f, alg; uprev, u) + +""" + child_node_count(alg, f) + +How many of `f`'s operators get a child integrator under `alg`. + +Almost every algorithm advances every operator, so this is the number of operators. +IMEX-MRI-SR methods are the exception: they integrate only the fast operator and merely +*evaluate* the two slow ones, so they build a single child. +""" +child_node_count(::AbstractOperatorSplittingAlgorithm, f) = length(f.functions) + +# Top-level builder: called from __init with the full problem, after the root cache has +# been built. `cache` is unused by the stock algorithms and is there for those that wire +# something cache-owned into a child's right-hand side. function build_subintegrators( prob::OperatorSplittingProblem, alg::AbstractOperatorSplittingAlgorithm, @@ -1654,7 +1697,8 @@ function build_subintegrators( solution_indices, t0, tf, tstops, saveat, d_discontinuities, callback, - config::ConfigTree + config::ConfigTree, + cache::AbstractOperatorSplittingCache, ) (; f, p) = prob @@ -1724,8 +1768,8 @@ function _build_child( t0, tf, (tstops..., d_discontinuities...), () ) - level_cache = init_cache( - f, alg; + level_cache = init_cache_with_parameters( + f, alg, p; uprev = uprev_sub, u = u_sub, ) @@ -1865,7 +1909,7 @@ function DiffEqBase.add_tstop!(i::AnySplitIntegrator, t) error("Cannot add a tstop at $t because that is behind the current \ integrator time $(i.t)") DiffEqBase.add_tstop!.(i.child_subintegrators, t) - push!(i.tstops, t) + push!(i.tstops, i.tdir * t) return nothing end @@ -1873,7 +1917,7 @@ function DiffEqBase.add_saveat!(i::OperatorSplittingIntegrator, t) is_past_t(i, t) && error("Cannot add a saveat point at $t because that is behind the \ current integrator time $(i.t)") - push!(i.saveat, t) + push!(i.saveat, i.tdir * t) return nothing end diff --git a/src/solver.jl b/src/solver.jl deleted file mode 100644 index db76d35..0000000 --- a/src/solver.jl +++ /dev/null @@ -1,288 +0,0 @@ -# --------------------------------------------------------------------------- -# Lie-Trotter-Godunov operator splitting -# --------------------------------------------------------------------------- -""" - LieTrotterGodunov <: AbstractOperatorSplittingAlgorithm - -First-order sequential operator splitting algorithm attributed to -[Lie:1880:tti,Tro:1959:psg,God:1959:dmn](@cite). -""" -struct LieTrotterGodunov{AlgTupleType} <: AbstractOperatorSplittingAlgorithm - inner_algs::AlgTupleType # Tuple of timesteppers for inner problems -end - -function Base.show(io::IO, alg::LieTrotterGodunov) - print(io, "LTG (") - for inner_alg in alg.inner_algs[1:(end - 1)] - Base.show(io, inner_alg) - print(io, " -> ") - end - length(alg.inner_algs) > 0 && Base.show(io, alg.inner_algs[end]) - return print(io, ")") -end - -struct LieTrotterGodunovCache{uType, uprevType} <: AbstractOperatorSplittingCache - u::uType - uprev::uprevType -end - -function init_cache( - f::GenericSplitFunction, alg::LieTrotterGodunov; - uprev::AbstractArray, u::AbstractVector, - ) - return LieTrotterGodunovCache(u, uprev) -end - -@unroll function _perform_step!( - parent, - children::Tuple, - cache::LieTrotterGodunovCache, - dt - ) - i = 0 - @unroll for child in children - i += 1 - - idxs = parent.child_solution_indices[i] - sync = parent.child_synchronizers[i] - - @timeit_debug "sync ->" forward_sync_subintegrator!(parent, child, idxs, sync) - @timeit_debug "time solve" advance_solution_by!(parent, child, dt) - if child_failed(child) - parent.force_stepfail = true - return - end - - @timeit_debug "sync <-" backward_sync_subintegrator!(parent, child, idxs, sync) - end -end - -# --------------------------------------------------------------------------- -# Strang-Marchuk operator splitting -# --------------------------------------------------------------------------- -""" - StrangMarchuk <: AbstractOperatorSplittingAlgorithm - -Second-order symmetric (palindromic) operator splitting algorithm attributed to -[Str:1968:ccd,Mar:1971:tsm](@cite). - -For ``N`` operators the scheme performs - -``A_1(\\Delta t/2) \\to \\cdots \\to A_{N-1}(\\Delta t/2) \\to A_N(\\Delta t) \\to A_{N-1}(\\Delta t/2) \\to \\cdots \\to A_1(\\Delta t/2)`` - -achieving second-order accuracy through symmetry. -""" -struct StrangMarchuk{AlgTupleType} <: AbstractOperatorSplittingAlgorithm - inner_algs::AlgTupleType # Tuple of timesteppers for inner problems -end - -function Base.show(io::IO, alg::StrangMarchuk) - print(io, "SM (") - for inner_alg in alg.inner_algs[1:(end - 1)] - Base.show(io, inner_alg) - print(io, " -> ") - end - length(alg.inner_algs) > 0 && Base.show(io, alg.inner_algs[end]) - return print(io, ")") -end - -struct StrangMarchukCache{uType, uprevType} <: AbstractOperatorSplittingCache - u::uType - uprev::uprevType -end - -function init_cache( - f::GenericSplitFunction, alg::StrangMarchuk; - uprev::AbstractArray, u::AbstractVector, - ) - return StrangMarchukCache(u, uprev) -end - -# Forward pass: A₁(dt/2) → … → Aₙ₋₁(dt/2) → Aₙ(dt) -@unroll function _sm_forward_pass!(parent, children::Tuple, half_dt, dt) - N = length(children) - i = 0 - @unroll for child in children - i += 1 - step_dt = i < N ? half_dt : dt - - idxs = parent.child_solution_indices[i] - sync = parent.child_synchronizers[i] - - @timeit_debug "sync ->" forward_sync_subintegrator!(parent, child, idxs, sync) - @timeit_debug "time solve" advance_solution_by!(parent, child, step_dt) - if child_failed(child) - parent.force_stepfail = true - return - end - - @timeit_debug "sync <-" backward_sync_subintegrator!(parent, child, idxs, sync) - end -end - -# Reverse pass: Aₙ₋₁(dt/2) → … → A₁(dt/2) -@unroll function _sm_reverse_pass!(parent, rev_front::Tuple, half_dt, N) - j = 0 - @unroll for child in rev_front - j += 1 - i = N - j - - idxs = parent.child_solution_indices[i] - sync = parent.child_synchronizers[i] - - @timeit_debug "sync ->" forward_sync_subintegrator!(parent, child, idxs, sync) - @timeit_debug "time solve" advance_solution_by!(parent, child, half_dt) - if child_failed(child) - parent.force_stepfail = true - return - end - - @timeit_debug "sync <-" backward_sync_subintegrator!(parent, child, idxs, sync) - end -end - -function _perform_step!( - parent, - children::Tuple, - cache::StrangMarchukCache, - dt - ) - half_dt = dt / 2 - - # Skip sync of for first solve, because it is already in sync - mark_next_sync_continuous(parent) - - _sm_forward_pass!(parent, children, half_dt, dt) - parent.force_stepfail && return - - _sm_reverse_pass!(parent, reverse(children[1:(end - 1)]), half_dt, length(children)) - parent.force_stepfail && return - - return -end - -# --------------------------------------------------------------------------- -# Palindromic pair of Lie-Trotter-Godunov splittings -# --------------------------------------------------------------------------- -""" - PalindromicPairLieTrotterGodunov <: AbstractOperatorSplittingAlgorithm - -Second-order sequential operator splitting algorithm. - -One step solves the palindromic pair of [`LieTrotterGodunov`](@ref) sequences - -``A_1(\\Delta t) \\to \\cdots \\to A_N(\\Delta t)`` and -``A_N(\\Delta t) \\to \\cdots \\to A_1(\\Delta t)`` - -from the same initial value. The leading splitting error of a Lie-Trotter sequence -is ``\\frac{\\Delta t^2}{2}\\sum_{i ") - end - length(alg.inner_algs) > 0 && Base.show(io, alg.inner_algs[end]) - return print(io, ")") -end - -@inline SciMLBase.isadaptive(::PalindromicPairLieTrotterGodunov) = true -# The pair difference estimates the O(dt²) leading error term of a first order -# sequence, so the controller sees a first order error estimator. -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 -end - -function init_cache( - f::GenericSplitFunction, alg::PalindromicPairLieTrotterGodunov; - uprev::AbstractArray, u::AbstractVector, - ) - return PalindromicPairLieTrotterGodunovCache(u, uprev, similar(u)) -end - -function _ppltg_advance_child!(parent, child, i, dt) - idxs = parent.child_solution_indices[i] - sync = parent.child_synchronizers[i] - - @timeit_debug "sync ->" forward_sync_subintegrator!(parent, child, idxs, sync) - @timeit_debug "time solve" advance_solution_by!(parent, child, dt) - if child_failed(child) - parent.force_stepfail = true - return - end - - @timeit_debug "sync <-" backward_sync_subintegrator!(parent, child, idxs, sync) - return -end - -# Forward sequence: A₁(dt) → … → A_N(dt) -@unroll function _ppltg_forward_pass!(parent, children::Tuple, dt) - i = 0 - @unroll for child in children - i += 1 - _ppltg_advance_child!(parent, child, i, dt) - parent.force_stepfail && return - end -end - -# Reverse sequence: A_N(dt) → … → A₁(dt) -@unroll function _ppltg_reverse_pass!(parent, rchildren::Tuple, dt, N) - j = 0 - @unroll for child in rchildren - j += 1 - _ppltg_advance_child!(parent, child, N + 1 - j, dt) - parent.force_stepfail && return - end -end - -function _perform_step!( - parent, - children::Tuple, - cache::PalindromicPairLieTrotterGodunovCache, - dt - ) - (; uforward) = cache - - _ppltg_forward_pass!(parent, children, dt) - parent.force_stepfail && return - uforward .= parent.u - - # Rewind to the initial state of the step; uprev is untouched while stepping. - parent.u .= parent.uprev - rollback_children!(parent) - - _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. - (; abstol, reltol, internalnorm) = parent.opts - @. uforward = (parent.u - uforward) / - (abstol + max(abs(parent.u), abs(parent.uprev)) * reltol) - OrdinaryDiffEqCore.set_EEst!(parent, internalnorm(uforward, parent.t + dt)) - end - return -end diff --git a/src/solvers/adjoint_pair.jl b/src/solvers/adjoint_pair.jl new file mode 100644 index 0000000..fe3164b --- /dev/null +++ b/src/solvers/adjoint_pair.jl @@ -0,0 +1,228 @@ +# --------------------------------------------------------------------------- +# Pairs of a scheme and its adjoint +# +# Running a scheme together with its adjoint from the same initial value gives both a +# solution one order higher and an error estimate, which is what makes these the +# adaptive splitting schemes of the package. See [AuzHofKetKoc:2017:psm](@cite), §3. +# --------------------------------------------------------------------------- + +""" + _pair_average_and_estimate!(parent, uforward, dt) + +Combine the two members of a scheme/adjoint pair, `parent.u` and `uforward`, into the +higher-order solution and, when the node is adaptive, the local error estimate. + +This is the Milne device of [AuzHofKetKoc:2017:psm](@cite), §3: for a base scheme of +odd order `p` the two members have leading error terms `±C h^{p+1}`, so their average +is of order `p+1` and half their difference estimates the base scheme's local error. +`uforward` is overwritten with the scaled residual. +""" +function _pair_average_and_estimate!(parent, uforward, dt) + parent.u .= (parent.u .+ uforward) ./ 2 + if parent.controller_cache !== nothing + (; abstol, reltol, internalnorm) = parent.opts + @. uforward = (parent.u - uforward) / + (abstol + max(abs(parent.u), abs(parent.uprev)) * reltol) + OrdinaryDiffEqCore.set_EEst!(parent, internalnorm(uforward, parent.t + dt)) + end + return +end + +# --------------------------------------------------------------------------- +# Palindromic pair of Lie-Trotter-Godunov splittings +# --------------------------------------------------------------------------- +""" + PalindromicPairLieTrotterGodunov <: AbstractOperatorSplittingAlgorithm + +Second-order sequential operator splitting algorithm. + +One step solves the palindromic pair of [`LieTrotterGodunov`](@ref) sequences + +``A_1(\\Delta t) \\to \\cdots \\to A_N(\\Delta t)`` and +``A_N(\\Delta t) \\to \\cdots \\to A_1(\\Delta t)`` + +from the same initial value. The leading splitting error of a Lie-Trotter sequence +is ``\\frac{\\Delta t^2}{2}\\sum_{i ") + +order(::PalindromicPairLieTrotterGodunov) = 2 + +@inline SciMLBase.isadaptive(::PalindromicPairLieTrotterGodunov) = true +# The pair difference estimates the O(dt²) leading error term of a first order +# sequence, so the controller sees a first order error estimator. +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 +end + +function init_cache( + f::GenericSplitFunction, alg::PalindromicPairLieTrotterGodunov; + uprev::AbstractArray, u::AbstractVector, + ) + return PalindromicPairLieTrotterGodunovCache(u, uprev, similar(u)) +end + +# Forward sequence: A₁(dt) → … → A_N(dt) +@unroll function _ppltg_forward_pass!(parent, children::Tuple, dt) + i = 0 + @unroll for child in children + i += 1 + _advance_child!(parent, child, i, dt) + parent.force_stepfail && return + end +end + +# Reverse sequence: A_N(dt) → … → A₁(dt) +@unroll function _ppltg_reverse_pass!(parent, rchildren::Tuple, dt, N) + j = 0 + @unroll for child in rchildren + j += 1 + _advance_child!(parent, child, N + 1 - j, dt) + parent.force_stepfail && return + end +end + +function _perform_step!( + parent, + children::Tuple, + cache::PalindromicPairLieTrotterGodunovCache, + dt + ) + (; uforward) = cache + + _ppltg_forward_pass!(parent, children, dt) + parent.force_stepfail && return + uforward .= parent.u + + # Rewind to the initial state of the step; uprev is untouched while stepping. + parent.u .= parent.uprev + rollback_children!(parent) + + _ppltg_reverse_pass!(parent, reverse(children), dt, length(children)) + parent.force_stepfail && return + + _pair_average_and_estimate!(parent, uforward, dt) + return +end + +# --------------------------------------------------------------------------- +# Adjoint pairs of a table-driven scheme +# --------------------------------------------------------------------------- +""" + AdjointPair(base) <: AbstractOperatorSplittingAlgorithm + +Adaptive splitting scheme of order `p+1` built from a `base` scheme of odd order `p`, +following [AuzHofKetKoc:2017:psm](@cite), eq. (3.2). + +One step runs `base` and its adjoint ``\\mathcal{S}^*`` from the same initial value. +Their leading error terms are ``C h^{p+1}`` and ``(-1)^p C h^{p+1}``, so for odd `p` +the signs oppose: the average is a solution of order `p+1`, and half the difference is +an asymptotically correct estimate of the base scheme's local error, which drives the +step size controller. A step therefore costs twice the base scheme. + +The base scheme's order must be **odd**. For even `p` the two leading terms are +*equal* rather than opposite, so averaging cancels nothing and the difference stops +being an error estimate. + +``\\mathcal{S}^*(h, u) = \\mathcal{S}^{-1}(-h, u)`` is the base scheme's entire flat +sequence of flows reversed, every coefficient keeping its sign and its operator, so it +reuses the same table and needs no extra coefficients. + +[`PalindromicPairLieTrotterGodunov`](@ref) is this construction at `p = 1`. + +As everywhere here, the order and the estimate cover the *splitting* error only and +presume the inner solvers resolve their subproblems accurately relative to it. +""" +struct AdjointPair{BaseType, AlgTupleType <: Tuple} <: AbstractOperatorSplittingAlgorithm + base::BaseType + inner_algs::AlgTupleType # aliases `base.inner_algs`, so the tree machinery works unchanged + + function AdjointPair(base::AbstractOperatorSplittingAlgorithm) + p = order(base) + isodd(p) || throw( + ArgumentError( + "AdjointPair needs a base scheme of odd order, got order $p. For even \ + orders a scheme and its adjoint share the same leading error term, so \ + averaging them raises no order and their difference is not an error \ + estimate." + ) + ) + return new{typeof(base), typeof(base.inner_algs)}(base, base.inner_algs) + end +end + +function Base.show(io::IO, alg::AdjointPair) + print(io, "AdjointPair (") + Base.show(io, alg.base) + return print(io, ")") +end + +coefficients(alg::AdjointPair) = coefficients(alg.base) +order(alg::AdjointPair) = order(alg.base) + 1 + +@inline SciMLBase.isadaptive(::AdjointPair) = true +# The estimate measures the *base* scheme's leading error, not the pair's. +alg_adaptive_order(alg::AdjointPair) = order(alg.base) + +struct AdjointPairCache{uType, uprevType, uforwardType, coeffType} <: AbstractOperatorSplittingCache + u::uType + uprev::uprevType + uforward::uforwardType # end state of the base sequence; reused as the residual buffer + coeffs::coeffType +end + +function init_cache( + f::GenericSplitFunction, alg::AdjointPair; + uprev::AbstractArray, u::AbstractVector, + ) + return AdjointPairCache(u, uprev, similar(u), coefficients(alg)) +end + +function _perform_step!( + parent, + children::Tuple, + cache::AdjointPairCache, + dt + ) + (; uforward, coeffs) = cache + + _table_stages!(parent, children, coeffs.a, dt) + parent.force_stepfail && return + uforward .= parent.u + + # Rewind to the initial state of the step; uprev is untouched while stepping. + parent.u .= parent.uprev + rollback_children!(parent) + + _table_stages_adjoint!( + parent, reverse(children), reverse(coeffs.a), dt, length(children) + ) + parent.force_stepfail && return + + _pair_average_and_estimate!(parent, uforward, dt) + return +end diff --git a/src/solvers/coefficients.jl b/src/solvers/coefficients.jl new file mode 100644 index 0000000..48e6f63 --- /dev/null +++ b/src/solvers/coefficients.jl @@ -0,0 +1,125 @@ +# --------------------------------------------------------------------------- +# Coefficient tables +# +# A splitting scheme of order three or above is specified by a table of coefficients +# rather than by hand-written passes. This file holds the table type, the interface +# every table-driven scheme implements (`coefficients` and `order`), and the two +# traversals of a table: the scheme itself and its adjoint. +# --------------------------------------------------------------------------- + +""" + SplittingCoefficients(stages::NTuple{N, T}...) + +Coefficients of an `S`-stage splitting scheme over `N` operators, one tuple per stage: +stage `j` advances operator `i` by `stages[j][i] * dt`. + +This is the generalization to `N` operators of the two-operator (`AB`) and +three-operator (`ABC`) coefficient tables of +[AuzHofKetKoc:2017:psm](@cite); their tables are the `N = 2` and `N = 3` cases. + +Each operator's coefficients must sum to one, the consistency condition, and that is +checked here. The remaining order conditions are not, so a table that constructs +successfully can still fail to attain the order it claims. +""" +struct SplittingCoefficients{S, N, T} + a::NTuple{S, NTuple{N, T}} + + # Do not simplify this to `NTuple{S, NTuple{N, T}}`: the empty tuple matches it for + # any element type, leaving parameters unbound for `S == 0` (and `T` unbound for + # `N == 0`). A leading element plus a counted `Vararg` rules both out. + function SplittingCoefficients( + stage1::Tuple{T, Vararg{T, K}}, + rest::Tuple{T, Vararg{T, K}}... + ) where {T, K} + a = (stage1, rest...) + N = K + 1 + S = length(a) + for i in 1:N + total = sum(a[j][i] for j in 1:S) + total ≈ one(T) || throw( + ArgumentError( + "operator $i's coefficients sum to $total rather than 1, so the \ + scheme is not consistent." + ) + ) + end + return new{S, N, T}(a) + end +end + +""" + coefficients(alg) + +The [`SplittingCoefficients`](@ref) table of a coefficient-driven splitting algorithm. +""" +function coefficients end + +""" + order(alg) + +Order of consistency of a splitting algorithm, counting the splitting error only. +""" +function order end + +struct SplittingCoefficientsCache{uType, uprevType, coeffType} <: AbstractOperatorSplittingCache + u::uType + uprev::uprevType + coeffs::coeffType +end + +function _perform_step!( + parent, + children::Tuple, + cache::SplittingCoefficientsCache, + dt + ) + # Deliberately no `mark_next_sync_continuous`: that shortcut needs the previous step + # to have left `parent.u` equal to the buffer of the child solved first, which holds + # for StrangMarchuk only because its reverse pass ends on operator 1. A general table + # ends on operator N, so operator 1's buffer is stale and skipping its forward sync + # resumes from stale state -- the first step stays exact and every later one is wrong. + _table_stages!(parent, children, cache.coeffs.a, dt) + return +end + +@unroll function _table_stages!(parent, children, stages::Tuple, dt) + @unroll for stage in stages + _table_stage!(parent, children, stage, dt) + parent.force_stepfail && return + end +end + +@unroll function _table_stage!(parent, children::Tuple, stage, dt) + i = 0 + @unroll for child in children + i += 1 + coefficient = stage[i] + # A zero coefficient is the identity flow, so it is skipped sync and all. + if !iszero(coefficient) + _advance_child!(parent, child, i, coefficient * dt) + parent.force_stepfail && return + end + end +end + +# The adjoint reverses the whole flat sequence of flows, so both the stage order and +# the operator order within each stage are reversed. +@unroll function _table_stages_adjoint!(parent, rchildren, rstages::Tuple, dt, N) + @unroll for stage in rstages + _table_stage_adjoint!(parent, rchildren, stage, dt, N) + parent.force_stepfail && return + end +end + +@unroll function _table_stage_adjoint!(parent, rchildren::Tuple, stage, dt, N) + j = 0 + @unroll for child in rchildren + j += 1 + i = N + 1 - j + coefficient = stage[i] + if !iszero(coefficient) + _advance_child!(parent, child, i, coefficient * dt) + parent.force_stepfail && return + end + end +end diff --git a/src/solvers/common.jl b/src/solvers/common.jl new file mode 100644 index 0000000..0f01fca --- /dev/null +++ b/src/solvers/common.jl @@ -0,0 +1,48 @@ +# --------------------------------------------------------------------------- +# Pieces shared by every splitting scheme +# --------------------------------------------------------------------------- + +""" + _advance_child!(parent, child, i, dt) + +Advance the `i`-th operator of `parent` by `dt`, syncing state into the child before +and out of it afterwards. A failed child is reported through `parent.force_stepfail`, +which every scheme checks between flows. +""" +function _advance_child!(parent, child, i, dt) + idxs = parent.child_solution_indices[i] + sync = parent.child_synchronizers[i] + + @timeit_debug "sync ->" forward_sync_subintegrator!(parent, child, idxs, sync) + @timeit_debug "time solve" advance_solution_by!(parent, child, dt) + if child_failed(child) + parent.force_stepfail = true + return + end + + @timeit_debug "sync <-" backward_sync_subintegrator!(parent, child, idxs, sync) + return +end + +function _require_two_operators(scheme, inner_algs) + n = length(inner_algs) + n == 2 || throw( + ArgumentError( + "$scheme is a two-operator (AB) table but got $n operators. Group the \ + operators into a nested GenericSplitFunction to use it with more." + ) + ) + return nothing +end + +# Every scheme prints as `NAME (inner -> inner)`; `separator` is what sits between the +# inner algorithms. +function _show_scheme(io::IO, name, inner_algs, separator = " -> ") + print(io, name, " (") + for inner_alg in inner_algs[1:(end - 1)] + Base.show(io, inner_alg) + print(io, separator) + end + length(inner_algs) > 0 && Base.show(io, inner_algs[end]) + return print(io, ")") +end diff --git a/src/solvers/imex_mri_sr.jl b/src/solvers/imex_mri_sr.jl new file mode 100644 index 0000000..5f3c17a --- /dev/null +++ b/src/solvers/imex_mri_sr.jl @@ -0,0 +1,496 @@ +# --------------------------------------------------------------------------- +# Implicit-explicit multirate infinitesimal stage-restart (IMEX-MRI-SR) methods +# +# [FisReyRob:2023:iem](@cite). Unlike every other scheme in this package, these are not +# sequences of flows over disjoint slices of the state: the three operators are an +# *additive* partition of one full-state right-hand side, +# +# y' = f^{F}(t, y) + f^{E}(t, y) + f^{I}(t, y), +# +# into fast, slow-explicit and slow-implicit parts. A step evolves a sequence of forced +# fast initial value problems, each restarted from y_n -- hence "stage-restart" -- and +# follows each with an implicit solve at the slow time scale. +# --------------------------------------------------------------------------- + +""" + AbstractIMEXMRISR <: AbstractOperatorSplittingAlgorithm + +Supertype of the IMEX-MRI-SR methods of [FisReyRob:2023:iem](@cite). + +An algorithm in this family expects exactly three operators, in this order: + +| position | operator | role | +|:---------|:---------|:-------------------------------------------------------| +| 1 | `f^{F}` | fast; integrated by the inner algorithm, with forcing | +| 2 | `f^{E}` | slow explicit; only ever evaluated | +| 3 | `f^{I}` | slow implicit; evaluated and solved against | + +All three must act on the whole state, so all three `solution_indices` of the +[`GenericSplitFunction`](@ref) span it. +""" +abstract type AbstractIMEXMRISR <: AbstractOperatorSplittingAlgorithm end + +# Only operator 1 gets a child integrator; f^{E} and f^{I} are evaluated directly. +child_node_count(::AbstractIMEXMRISR, f) = 1 + +# `inner_algs` is `(fast_alg, nothing, nothing)`, so the generic definition -- which +# maps over every entry -- would trip over the two placeholders. +@inline isdtchangeable(alg::AbstractIMEXMRISR) = isdtchangeable(alg.inner_algs[1]) + +@inline SciMLBase.isadaptive(::AbstractIMEXMRISR) = true + +# The estimate comes from the embedding, whose order is one below the primary method's. +alg_adaptive_order(alg::AbstractIMEXMRISR) = order(alg) - 1 + +Base.show(io::IO, alg::AbstractIMEXMRISR) = + print(io, _imex_mri_sr_name(alg), " (", sprint(Base.show, alg.inner_algs[1]), ")") + +""" + IMEXMRISR2(fast_alg; nlsolve = NewtonRaphson()) + +Second order IMEX-MRI-SR method with a first order embedding, `IMEX-MRI-SR2(1)` of +[FisReyRob:2023:iem](@cite), §4.1. Four stages, `nΩ = 1`, three slow nonlinear solves +per step. + +`fast_alg` integrates the forced fast initial value problems; `nlsolve` solves the slow +implicit stages. See [`AbstractIMEXMRISR`](@ref) for the required operator order. +""" +struct IMEXMRISR2{AlgTupleType <: Tuple, NL} <: AbstractIMEXMRISR + inner_algs::AlgTupleType # (fast_alg, nothing, nothing) + nlsolve::NL +end + +""" + IMEXMRISR3(fast_alg; nlsolve = NewtonRaphson()) + +Third order IMEX-MRI-SR method with a second order embedding, `IMEX-MRI-SR3(2)` of +[FisReyRob:2023:iem](@cite), §4.2. Five stages, `nΩ = 2`, four slow nonlinear solves +per step. + +`fast_alg` integrates the forced fast initial value problems; `nlsolve` solves the slow +implicit stages. See [`AbstractIMEXMRISR`](@ref) for the required operator order. +""" +struct IMEXMRISR3{AlgTupleType <: Tuple, NL} <: AbstractIMEXMRISR + inner_algs::AlgTupleType + nlsolve::NL +end + +for (T, name, ord, table) in ( + (:IMEXMRISR2, "IMEX-MRI-SR2(1)", 2, :IMEX_MRI_SR2_COEFFICIENTS), + (:IMEXMRISR3, "IMEX-MRI-SR3(2)", 3, :IMEX_MRI_SR3_COEFFICIENTS), + ) + @eval begin + $T(fast_alg; nlsolve = NewtonRaphson()) = + $T((fast_alg, nothing, nothing), nlsolve) + _imex_mri_sr_name(::$T) = $name + order(::$T) = $ord + coefficients(::$T) = $table + end +end + +# --------------------------------------------------------------------------- +# Forcing of the fast initial value problems +# --------------------------------------------------------------------------- + +""" + MRIForcing + +The forcing term `g(θ)` currently applied to the fast right-hand side, where +`θ = t - tn` is the elapsed fast time within a stage. + +Definition 1.1 writes the forcing of stage `i` as a sum over previous stages, + +``` +g_i(θ) = (1/c_i) Σ_{j zero(u), NΩ)) + + # One nonlinear solver cache serves every stage of every step: only `t`, `γH` and + # `z` change between stages, and those live in the stage parameters. + stage_params = MRIStageParams(p[3], zero(T), zero(T), zero(u)) + nlprob = SciMLBase.NonlinearProblem( + SciMLBase.NonlinearFunction{true}(MRIStageResidual(get_operator(f, 3))), + zero(u), stage_params, + ) + nlcache = SciMLBase.init(nlprob, alg.nlsolve) + + return IMEXMRISRCache( + u, uprev, coeffs, forcing, + ntuple(_ -> zero(u), S), ntuple(_ -> zero(u), S), ntuple(_ -> zero(u), S), + zero(u), stage_params, nlcache, + ) +end + +function _check_imex_mri_sr_function(f::GenericSplitFunction) + n = num_operators(f) + n == 3 || throw( + ArgumentError( + "an IMEX-MRI-SR method needs exactly three operators (f^{F}, f^{E}, f^{I}) \ + but the split function has $n. This family is an additive partition of one \ + full-state right-hand side, not a splitting over disjoint state slices." + ) + ) + get_operator(f, 1) isa GenericSplitFunction && throw( + ArgumentError( + "the fast operator of an IMEX-MRI-SR method cannot itself be a \ + GenericSplitFunction: its right-hand side is wrapped to carry the stage \ + forcing, which a nested splitting node has no way to apply." + ) + ) + return nothing +end + +# --------------------------------------------------------------------------- +# Tree construction +# +# Only the fast operator becomes a child integrator, and it integrates f^{F} wrapped +# around the cache's forcing term rather than f^{F} itself. +# --------------------------------------------------------------------------- + +function build_subintegrators( + prob::OperatorSplittingProblem, + alg::AbstractIMEXMRISR, + uprevouter::AbstractVector, + uouter::AbstractVector, + u_master::AbstractVector, + solution_indices, + t0, tf, + tstops, saveat, d_discontinuities, callback, + config::ConfigTree, + cache::IMEXMRISRCache, + ) + (; f, p) = prob + _check_imex_mri_sr_indices(f, length(uouter)) + + f_fast = get_operator(f, 1) + forced = SciMLBase.ODEFunction{true}( + ForcedFastFunction(f_fast, cache.forcing); + mass_matrix = _fast_mass_matrix(f_fast), + ) + + child = _build_child( + prob, alg.inner_algs[1], forced, p[1], + uprevouter, uouter, u_master, + get_solution_indices(f, 1), + t0, tf, + tstops, saveat, d_discontinuities, callback, + config.children[1], + ) + return (child,) +end + +_fast_mass_matrix(f::SciMLBase.AbstractDiffEqFunction) = f.mass_matrix +_fast_mass_matrix(_) = SciMLBase.I + +# These methods are an additive partition of one full-state right-hand side, so every +# operator must see the whole state in its natural order. +function _check_imex_mri_sr_indices(f::GenericSplitFunction, n) + for i in 1:3 + idxs = get_solution_indices(f, i) + collect(idxs) == collect(1:n) || throw( + ArgumentError( + "operator $i of an IMEX-MRI-SR split function has solution_indices \ + $idxs, but all three operators must span the whole state as 1:$n. \ + f^{F}, f^{E} and f^{I} are an additive partition of one right-hand \ + side, not a splitting over disjoint slices of the state." + ) + ) + end + return nothing +end + +# An IMEX-MRI-SR node reads f^{E}, f^{I} and their parameters off the integrator, which +# only the root carries, so it cannot sit inside another splitting. +function _build_child( + ::OperatorSplittingProblem, + alg::AbstractIMEXMRISR, + ::GenericSplitFunction, + ::Any, + ::AbstractVector, ::AbstractVector, ::AbstractVector, + _, _, _, _, _, _, _, ::ConfigTree + ) + return throw( + ArgumentError( + "$(_imex_mri_sr_name(alg)) can only be the outermost algorithm of an \ + operator splitting problem, not an inner node of another splitting." + ) + ) +end + +# --------------------------------------------------------------------------- +# The step +# --------------------------------------------------------------------------- + +function _perform_step!( + parent, + children::Tuple, + cache::IMEXMRISRCache, + dt + ) + (; coeffs, Y) = cache + S = nstages(coeffs) + H = dt + tn = parent.t + child = children[1] + + # Stage 1 is Y_1 = y_n at c_1 = 0: no fast solve, no implicit solve. + Y[1] .= parent.uprev + _eval_slow!(cache, parent, 1, tn) + + for i in 2:S + _mri_stage_fast!(parent, child, cache, i, tn, H) + parent.force_stepfail && return + + # parent.u now holds v_i(c_i H); add the explicit part of the implicit stage. + _mri_stage_solve!(parent, cache, i, tn, H) + parent.force_stepfail && return + + # The final stage's slow tendencies are never read, so they are not computed. + # Ω is strictly lower triangular and Γ lower triangular, so stage i only ever + # uses stages j < i -- the j = i term of Γ acts on the trial value inside the + # nonlinear solve, not on a stored tendency -- and the embedding's ω̂_S and γ̂_S + # are both zero, which the table constructor enforces. Skipping this saves two + # full right-hand side evaluations per step. + i < S && _eval_slow!(cache, parent, i, tn + coeffs.c[i] * H) + end + + # First-same-as-last: the last stage *is* the step's solution. + parent.u .= Y[S] + + if parent.controller_cache !== nothing + _mri_embedded_step!(parent, child, cache, tn, H) + parent.force_stepfail && return + _mri_error_estimate!(parent, cache, dt) + end + return +end + +# Evaluate and store the slow tendencies of stage `i`. +function _eval_slow!(cache::IMEXMRISRCache, parent, i, t) + (; Y, fE, fI) = cache + f = parent.f + p = parent.p + get_operator(f, 2)(fE[i], Y[i], p[2], t) + get_operator(f, 3)(fI[i], Y[i], p[3], t) + return nothing +end + +# Solve the forced fast IVP of stage `i` over θ ∈ [0, c_i H], restarted from y_n. +function _mri_stage_fast!(parent, child, cache::IMEXMRISRCache, i, tn, H) + (; coeffs, Y) = cache + ci = coeffs.c[i] + + _set_stage_forcing!(cache, i, ci * H, tn, ci) + + # Stage restart: every stage begins from y_n at t = tn, so the child is re-anchored + # there rather than continued. `rollback_child!` is exactly that re-anchoring, and + # it also clears a transient failure left by an earlier stage. + parent.u .= Y[1] + idxs = parent.child_solution_indices[1] + rollback_child!(child, parent.u, idxs, tn) + + return _advance_child!(parent, child, 1, ci * H) +end + +# G^{k} = (1/c_i) Σ_{j 1 // 1, length(alg.inner_algs))) diff --git a/src/solvers/mri_tables.jl b/src/solvers/mri_tables.jl new file mode 100644 index 0000000..8e6df0e --- /dev/null +++ b/src/solvers/mri_tables.jl @@ -0,0 +1,293 @@ +# --------------------------------------------------------------------------- +# Coefficient tables for IMEX-MRI-SR methods +# +# An IMEX-MRI-SR method is defined by `nΩ` slow-tendency coefficient matrices Ω^{k}, +# a slow-implicit matrix Γ, and an abscissae vector c. This file holds the table type, +# the internal-consistency checks every table must satisfy, and the tables themselves. +# --------------------------------------------------------------------------- + +""" + MRISRCoefficients(Ω, Γ, c) + +Coefficients of an `S`-stage IMEX-MRI-SR method, as defined in +[FisReyRob:2023:iem](@cite), Definitions 1.1 and 1.2. + +`Ω` is a tuple of `nΩ` matrices, `Γ` a matrix, and `c` the slow abscissae. Following +the paper's notation, `Ω` and `Γ` carry the *embedding* as their last row, so each is +`(S+1) × S`: + +``` +Ω^{k} = [ 𝛀^{k} ; ω̂^{k} ], Γ = [ 𝚪 ; γ̂ ] +``` + +The slow tendency coefficients are polynomials in the normalized fast time `τ`, +`ω_{i,j}(τ) = Σ_k ω_{i,j}^{k} τ^k`, so `Ω[k+1][i, j]` is the coefficient of `τ^k`. + +The constructor checks the GARK internal-consistency conditions of Theorem 2.3, which +every IMEX-MRI-SR method must satisfy, along with the structural assumptions of +Definition 1.2. These are cheap and they are the only defence against a transcription +error in a table; the remaining order conditions are *not* checked, so a table that +constructs successfully can still fail to attain the order it claims. +""" +struct MRISRCoefficients{S, R, NΩ, T} + Ω::NTuple{NΩ, NTuple{R, NTuple{S, T}}} # Ω[k+1] is the τ^k matrix; row R = S+1 is ω̂^{k} + Γ::NTuple{R, NTuple{S, T}} # row R = S+1 is γ̂ + c::NTuple{S, T} +end + +function MRISRCoefficients( + Ω::Tuple{AbstractMatrix{T}, Vararg{AbstractMatrix{T}}}, + Γ::AbstractMatrix{T}, + c::AbstractVector{T}, + ) where {T} + S = length(c) + _validate_mrisr_table(Ω, Γ, c, S) + + Ωt = ntuple(k -> _rows_to_tuple(Ω[k], S), length(Ω)) + Γt = _rows_to_tuple(Γ, S) + return MRISRCoefficients{S, S + 1, length(Ω), T}(Ωt, Γt, ntuple(i -> c[i], S)) +end + +_rows_to_tuple(M::AbstractMatrix, S::Int) = + ntuple(i -> ntuple(j -> M[i, j], S), S + 1) + +# The tables below are `vcat`s of comma-separated row vectors rather than matrix +# literals. Inside `[ ]` whitespace is significant and sign handling is context +# dependent: `[a -b]` is a two-element row while `[a - b]` is a one-element row holding a +# subtraction. Many entries here begin with a minus, so under literal syntax one space +# added or removed -- by a formatter, or by hand while aligning columns -- would silently +# fuse two coefficients into their difference, with no error and no shape change to +# catch it. Commas make that impossible. + +function _validate_mrisr_table(Ω, Γ, c, S) + nΩ = length(Ω) + for (k, M) in enumerate(Ω) + size(M) == (S + 1, S) || throw( + ArgumentError( + "Ω^{$(k - 1)} is $(size(M)) but must be $((S + 1, S)): one row per stage \ + plus the embedding row, one column per stage." + ) + ) + end + size(Γ) == (S + 1, S) || throw( + ArgumentError("Γ is $(size(Γ)) but must be $((S + 1, S)).") + ) + + # Definition 1.1 restarts every stage from y_n and forces the fast IVP over + # [0, c_i H] with a 1/c_i factor, so a zero abscissa is only meaningful for the + # first stage, which is Y_1 = y_n and takes no fast solve at all. + iszero(c[1]) || throw(ArgumentError("c[1] is $(c[1]) but must be 0.")) + for i in 2:S + iszero(c[i]) && throw( + ArgumentError( + "c[$i] is zero. Stage $i would force the fast IVP with a 1/c[$i] factor \ + over an empty interval, which Definition 1.1 does not define." + ) + ) + end + + # Definition 1.2: the first row of every coefficient matrix is identically zero + # (stage 1 is y_n) and the Ω^{k} are strictly lower triangular. + for (k, M) in enumerate(Ω) + _require_zero_first_row(M, "Ω^{$(k - 1)}") + for i in 1:S, j in i:S + iszero(M[i, j]) || throw( + ArgumentError( + "Ω^{$(k - 1)}[$i, $j] = $(M[i, j]) is on or above the diagonal, but \ + Definition 1.2 assumes Ω^{$(k - 1)} is strictly lower triangular." + ) + ) + end + end + _require_zero_first_row(Γ, "Γ") + for i in 1:S, j in (i + 1):S + iszero(Γ[i, j]) || throw( + ArgumentError( + "Γ[$i, $j] = $(Γ[i, j]) is above the diagonal, but Γ must be lower \ + triangular; only its diagonal may couple a stage to itself." + ) + ) + end + + # The embedding is evaluated over the whole step, so its abscissa is ĉ = 1 and its + # last coefficient must vanish: ω̂_S = 0 because (1.5d) sums j ≤ S-1, and γ̂_S = 0 + # because that is what lets the embedded solution skip an implicit solve. Our + # embedding pass relies on both, so require them rather than silently mis-stepping. + for (k, M) in enumerate(Ω) + iszero(M[S + 1, S]) || throw( + ArgumentError( + "ω̂^{$(k - 1)}[$S] = $(M[S + 1, S]) must be zero: (1.5d) sums the \ + embedding's forcing over j ≤ $(S - 1) only." + ) + ) + end + iszero(Γ[S + 1, S]) || throw( + ArgumentError( + "γ̂[$S] = $(Γ[S + 1, S]) must be zero. A nonzero value would make the \ + embedded solution require its own implicit solve, which this \ + implementation does not perform." + ) + ) + + # Theorem 2.3, eq. (2.11a): Ω^{0} 𝟙 = c^{S}. The embedding row's abscissa is ĉ = 1. + for i in 1:S + rowsum = sum(Ω[1][i, j] for j in 1:S) + rowsum == c[i] || throw( + ArgumentError( + "row $i of Ω^{0} sums to $rowsum but must equal c[$i] = $(c[i]) \ + (internal consistency, eq. 2.11a)." + ) + ) + end + let rowsum = sum(Ω[1][S + 1, j] for j in 1:S) + isone(rowsum) || throw( + ArgumentError( + "the embedding row of Ω^{0} sums to $rowsum but must equal ĉ = 1." + ) + ) + end + + # Theorem 2.3, eq. (2.11b): Ω^{k} 𝟙 = 0 for k ≥ 1. + for k in 2:nΩ, i in 1:(S + 1) + rowsum = sum(Ω[k][i, j] for j in 1:S) + iszero(rowsum) || throw( + ArgumentError( + "row $i of Ω^{$(k - 1)} sums to $rowsum but must be zero (internal \ + consistency, eq. 2.11b)." + ) + ) + end + + # Theorem 2.3, eq. (2.11c): Γ 𝟙 = 0. + for i in 1:(S + 1) + rowsum = sum(Γ[i, j] for j in 1:S) + iszero(rowsum) || throw( + ArgumentError( + "row $i of Γ sums to $rowsum but must be zero (internal consistency, \ + eq. 2.11c)." + ) + ) + end + return nothing +end + +function _require_zero_first_row(M::AbstractMatrix, name) + for j in axes(M, 2) + iszero(M[1, j]) || throw( + ArgumentError( + "$name[1, $j] = $(M[1, j]) but the first row must be identically zero: \ + stage 1 of an IMEX-MRI-SR method is Y_1 = y_n." + ) + ) + end + return nothing +end + +# --------------------------------------------------------------------------- +# Accessors +# --------------------------------------------------------------------------- + +nstages(::MRISRCoefficients{S}) where {S} = S +num_omega(::MRISRCoefficients{S, R, NΩ}) where {S, R, NΩ} = NΩ + +""" + convert_coefficients(coeffs::MRISRCoefficients, ::Type{T}) + +Convert an exact (`Rational`) table to the working precision `T` of a state vector. +Done once per `init_cache` so the step itself does no rational arithmetic. +""" +function convert_coefficients(coeffs::MRISRCoefficients{S, R, NΩ}, ::Type{T}) where {S, R, NΩ, T} + conv_rows(rows) = map(row -> map(T, row), rows) + return MRISRCoefficients{S, R, NΩ, T}( + map(conv_rows, coeffs.Ω), + conv_rows(coeffs.Γ), + map(T, coeffs.c), + ) +end + +# --------------------------------------------------------------------------- +# IMEX-MRI-SR2(1) -- [FisReyRob:2023:iem](@cite), Appendix A +# +# Four stages, nΩ = 1, three slow nonlinear solves per step. Second order with a +# first-order embedding. +# --------------------------------------------------------------------------- + +const IMEX_MRI_SR2_COEFFICIENTS = MRISRCoefficients( + ( + # Ω^{0}; last row is ω̂^{0} + vcat( + [0, 0, 0, 0]', + [3 // 5, 0, 0, 0]', + [14 // 165, 2 // 11, 0, 0]', + [-13 // 54, 137 // 270, 11 // 15, 0]', + [-1 // 4, 1 // 2, 3 // 4, 0]', + ), + ), + # Γ; last row is γ̂ + vcat( + [0, 0, 0, 0]', + [-11 // 23, 11 // 23, 0, 0]', + [-6692 // 52371, -18355 // 52371, 11 // 23, 0]', + [11621 // 90666, -215249 // 226665, 17287 // 50370, 11 // 23]', + [-31 // 12, -1 // 6, 11 // 4, 0]', + ), + Rational{Int}[0, 3 // 5, 4 // 15, 1], +) + +# --------------------------------------------------------------------------- +# IMEX-MRI-SR3(2) -- [FisReyRob:2023:iem](@cite), Appendix B +# +# Five stages, nΩ = 2, four slow nonlinear solves per step. Third order with a +# second-order embedding. +# --------------------------------------------------------------------------- + +const IMEX_MRI_SR3_COEFFICIENTS = MRISRCoefficients( + ( + # Ω^{0}; last row is ω̂^{0} + vcat( + [0, 0, 0, 0, 0]', + [23 // 34, 0, 0, 0, 0]', + [71 // 70, -3 // 14, 0, 0, 0]', + [124 // 1155, 4 // 7, 5 // 11, 0, 0]', + [162181 // 187680, 119 // 1380, 11 // 32, -5 // 17, 0]', + [76355 // 74834, -46 // 31, 67 // 34, -36 // 71, 0]', + ), + # Ω^{1}; last row is ω̂^{1}. + # + # NOTE: the (4, 2) entry is *positive*, though Appendix B renders it with a + # leading minus. A minus violates eq. (2.11b) -- over the common denominator + # 1206582300 the row would sum to -19813883504 -- while a plus sums to exactly + # zero: -2101267877 + 4·2476735438 - 575·13575085 = 0. + vcat( + [0, 0, 0, 0, 0]', + [0, 0, 0, 0, 0]', + [-14453 // 63825, 14453 // 63825, 0, 0, 0]', + [-2101267877 // 1206582300, 2476735438 // 301645575, -13575085 // 2098404, 0, 0]', + [ + -762580446799 // 588660102960, 11083240219 // 4328383110, + -211274129 // 100368304, 89562055 // 106641323, 0, + ]', + [-3732974 // 2278035, 13857574 // 2278035, -52 // 9, 4 // 3, 0]', + ), + ), + # Γ; last row is γ̂. + # + # NOTE: the (5, 2) and (5, 4) entries are *negative*, though Appendix B renders both + # without a minus. As printed the row sums to 791340692/1009956059 rather than zero, + # violating eq. (2.11c). Negating the two makes it sum to exactly zero and, checked + # independently, makes the slow implicit base method A^{S,I} = Ω̄ + Γ satisfy both + # third-order conditions on its last row exactly (Σb·c = 1/2 and Σb·c² = 1/3, with + # b^{I,T} the last row by eq. 2.8c). No other pair of entries does. + vcat( + [0, 0, 0, 0, 0]', + [-4 // 7, 4 // 7, 0, 0, 0]', + [-2707004 // 3127425, 919904 // 3127425, 4 // 7, 0, 0]', + [852879271 // 703839675, -1575000496 // 703839675, 5 // 11, 4 // 7, 0]', + [ + 43136869 // 2019912118, -73810600 // 1009956059, + -17653551 // 87822266, -13993902 // 43911133, 4 // 7, + ]', + [-179 // 4140, 799 // 14490, 1 // 14, -1 // 12, 0]', + ), + Rational{Int}[0, 23 // 34, 4 // 5, 17 // 15, 1], +) diff --git a/src/solvers/strang_marchuk.jl b/src/solvers/strang_marchuk.jl new file mode 100644 index 0000000..30b12ed --- /dev/null +++ b/src/solvers/strang_marchuk.jl @@ -0,0 +1,75 @@ +# --------------------------------------------------------------------------- +# Strang-Marchuk operator splitting +# --------------------------------------------------------------------------- +""" + StrangMarchuk <: AbstractOperatorSplittingAlgorithm + +Second-order symmetric (palindromic) operator splitting algorithm attributed to +[Str:1968:ccd,Mar:1971:tsm](@cite). + +For ``N`` operators the scheme performs + +``A_1(\\Delta t/2) \\to \\cdots \\to A_{N-1}(\\Delta t/2) \\to A_N(\\Delta t) \\to A_{N-1}(\\Delta t/2) \\to \\cdots \\to A_1(\\Delta t/2)`` + +achieving second-order accuracy through symmetry. +""" +struct StrangMarchuk{AlgTupleType} <: AbstractOperatorSplittingAlgorithm + inner_algs::AlgTupleType # Tuple of timesteppers for inner problems +end + +Base.show(io::IO, alg::StrangMarchuk) = _show_scheme(io, "SM", alg.inner_algs) + +order(::StrangMarchuk) = 2 + +struct StrangMarchukCache{uType, uprevType} <: AbstractOperatorSplittingCache + u::uType + uprev::uprevType +end + +function init_cache( + f::GenericSplitFunction, alg::StrangMarchuk; + uprev::AbstractArray, u::AbstractVector, + ) + return StrangMarchukCache(u, uprev) +end + +# Forward pass: A₁(dt/2) → … → Aₙ₋₁(dt/2) → Aₙ(dt) +@unroll function _sm_forward_pass!(parent, children::Tuple, half_dt, dt) + N = length(children) + i = 0 + @unroll for child in children + i += 1 + _advance_child!(parent, child, i, i < N ? half_dt : dt) + parent.force_stepfail && return + end +end + +# Reverse pass: Aₙ₋₁(dt/2) → … → A₁(dt/2) +@unroll function _sm_reverse_pass!(parent, rev_front::Tuple, half_dt, N) + j = 0 + @unroll for child in rev_front + j += 1 + _advance_child!(parent, child, N - j, half_dt) + parent.force_stepfail && return + end +end + +function _perform_step!( + parent, + children::Tuple, + cache::StrangMarchukCache, + dt + ) + half_dt = dt / 2 + + # Skip sync of for first solve, because it is already in sync + mark_next_sync_continuous(parent) + + _sm_forward_pass!(parent, children, half_dt, dt) + parent.force_stepfail && return + + _sm_reverse_pass!(parent, reverse(children[1:(end - 1)]), half_dt, length(children)) + parent.force_stepfail && return + + return +end diff --git a/src/solvers/tables.jl b/src/solvers/tables.jl new file mode 100644 index 0000000..68a76c0 --- /dev/null +++ b/src/solvers/tables.jl @@ -0,0 +1,93 @@ +# --------------------------------------------------------------------------- +# Schemes defined by a coefficient table +# +# Each of these is a struct, a table, and the two interface methods; the stepping +# itself is the generic table traversal in coefficients.jl. +# --------------------------------------------------------------------------- +""" + Ruth3 <: AbstractOperatorSplittingAlgorithm + +Third-order splitting scheme of [Rut:1983:cim](@cite), in three stages. + +Its coefficients are exactly rational, and -- as is unavoidable for any real +splitting scheme of order three or above -- some of them are negative, so parts of +the step run backward in time. + +As for every splitting scheme here the order statement covers the *splitting* error +only, and presumes the inner solvers resolve their subproblems accurately relative +to it. +""" +struct Ruth3{AlgTupleType <: Tuple} <: AbstractOperatorSplittingAlgorithm + inner_algs::AlgTupleType + + function Ruth3(inner_algs::Tuple) + _require_two_operators("Ruth3", inner_algs) + return new{typeof(inner_algs)}(inner_algs) + end +end + +Base.show(io::IO, alg::Ruth3) = _show_scheme(io, "Ruth3", alg.inner_algs) + +const RUTH3_COEFFICIENTS = SplittingCoefficients( + (7 // 24, 2 // 3), (3 // 4, -2 // 3), (-1 // 24, 1 // 1) +) + +coefficients(::Ruth3) = RUTH3_COEFFICIENTS +order(::Ruth3) = 3 + +function init_cache( + f::GenericSplitFunction, alg::Ruth3; + uprev::AbstractArray, u::AbstractVector, + ) + return SplittingCoefficientsCache(u, uprev, coefficients(alg)) +end + +""" + Yoshida4 <: AbstractOperatorSplittingAlgorithm + +Fourth-order splitting scheme of [Yos:1990:cho](@cite), the "triple jump". + +Built by composing three Strang steps of lengths ``w_1 h``, ``w_0 h`` and ``w_1 h`` +with ``w_1 = 1/(2 - 2^{1/3})`` and ``w_0 = -2^{1/3} w_1``, then merging the adjacent +flows the composition leaves next to each other. That merging is what makes it eight +flow evaluations rather than nine, and it leaves the last stage's second coefficient +zero. + +``w_0`` is negative, so a substantial part of each step runs backward in time -- the +second operator's cumulative time reaches ``1.35\\,h`` before returning through +``-0.35\\,h``. + +As for every splitting scheme here the order statement covers the *splitting* error +only, and presumes the inner solvers resolve their subproblems accurately relative +to it. +""" +struct Yoshida4{AlgTupleType <: Tuple} <: AbstractOperatorSplittingAlgorithm + inner_algs::AlgTupleType + + function Yoshida4(inner_algs::Tuple) + _require_two_operators("Yoshida4", inner_algs) + return new{typeof(inner_algs)}(inner_algs) + end +end + +Base.show(io::IO, alg::Yoshida4) = _show_scheme(io, "Yoshida4", alg.inner_algs) + +const YOSHIDA4_W1 = 1 / (2 - cbrt(2)) +const YOSHIDA4_W0 = -cbrt(2) * YOSHIDA4_W1 + +const YOSHIDA4_COEFFICIENTS = SplittingCoefficients( + (YOSHIDA4_W1 / 2, YOSHIDA4_W1), + ((YOSHIDA4_W1 + YOSHIDA4_W0) / 2, YOSHIDA4_W0), + ((YOSHIDA4_W1 + YOSHIDA4_W0) / 2, YOSHIDA4_W1), + (YOSHIDA4_W1 / 2, 0.0), +) + +coefficients(::Yoshida4) = YOSHIDA4_COEFFICIENTS +order(::Yoshida4) = 4 + +function init_cache( + f::GenericSplitFunction, alg::Yoshida4; + uprev::AbstractArray, u::AbstractVector, + ) + return SplittingCoefficientsCache(u, uprev, coefficients(alg)) +end diff --git a/src/utils.jl b/src/utils.jl index e7c059e..e167ad5 100644 --- a/src/utils.jl +++ b/src/utils.jl @@ -1,15 +1,25 @@ -# helper function for setting up min/max heaps for tstops and saveat +""" + tstops_and_saveat_heaps(t0, tf, tstops, saveat) + +Build the `tstops` and `saveat` heaps of a node covering `t0` to `tf`. + +Both store **`tdir`-scaled** times, the convention OrdinaryDiffEqCore's +`initialize_tstops` follows, so that "the next one" is always the heap minimum and +"ahead of `t`" is always `key > tdir * t`, whichever way the node integrates. It is +also what lets [`reverse_direction!`](@ref) flip a node by re-signing its keys: the +alternative, storing raw times and encoding the direction in the heap's ordering, +puts the direction in the heap's *type*, where it cannot be changed in place. +""" function tstops_and_saveat_heaps(t0, tf, tstops, saveat) FT = typeof(tf) - ordering = tf > t0 ? BinaryHeaps.FasterForward : BinaryHeaps.FasterReverse + tdir = tf > t0 ? one(FT) : -one(FT) # ensure that tstops includes tf and only has values ahead of t0 tstops = [filter(t -> t0 < t < tf || tf < t < t0, tstops)..., tf] - tstops = BinaryHeaps.BinaryHeap{FT, ordering}(tstops) + tstops = BinaryHeaps.BinaryHeap{FT, BinaryHeaps.FasterForward}(tdir .* tstops) # Keep `t0 < t <= tf` in tdir-space: `save_start` owns the initial point and # `save_end` the final one, so leaving either in the heap would duplicate it. - tdir = tf > t0 ? one(FT) : -one(FT) saveat = if isnothing(saveat) FT[] elseif saveat isa Number @@ -19,7 +29,7 @@ function tstops_and_saveat_heaps(t0, tf, tstops, saveat) else filter(t -> tdir * t0 < tdir * t <= tdir * tf, collect(FT, saveat)) end - saveat = BinaryHeaps.BinaryHeap{FT, ordering}(saveat) + saveat = BinaryHeaps.BinaryHeap{FT, BinaryHeaps.FasterForward}(tdir .* saveat) return tstops, saveat end @@ -260,6 +270,75 @@ function _fix_dt_at_bounds!(integrator::AnySplitIntegrator) return nothing end +""" + reverse_direction!(integrator) + +Flip an already-initialized integrator's direction of integration in place. + +Negating `dt` alone does not work: `fix_dt_at_bounds!` re-signs it to `tdir` and would +replace it with `+dtmin` before `perform_step!` saw it. + +The `tstops`/`saveat`/`d_discontinuities` heaps store `tdir`-scaled times, so negating +every key re-expresses the same raw times under the new direction -- which inverts the +heap order, hence the rebuild. Times now *behind* are dropped, because `handle_tstop!` +errors on an unconsumed stop that `t` has passed. + +A `SplitSubIntegrator` follows the same convention (see +[`tstops_and_saveat_heaps`](@ref)) and is reversed the same way; it just has fewer +things to reverse. +""" +function reverse_direction!(integrator::DEIntegrator) + integrator.tdir = -integrator.tdir + integrator.dt = -integrator.dt + integrator.dtcache = -integrator.dtcache + integrator.dtpropose = -integrator.dtpropose + + opts = integrator.opts + opts.dtmax = -opts.dtmax + + threshold = integrator.tdir * integrator.t + _reverse_time_heap!(opts.tstops, threshold) + _reverse_time_heap!(opts.saveat, threshold) + _reverse_time_heap!(opts.d_discontinuities, threshold) + + return integrator +end + +function reverse_direction!(sub::SplitSubIntegrator) + sub.tdir = -sub.tdir + sub.dt = -sub.dt + sub.dtcache = -sub.dtcache + + _reverse_time_heap!(sub.tstops, sub.tdir * sub.t) + + # `add_tstop!` propagates eagerly to every descendant, so a child left facing the + # old direction would reject the reversed node's next tstop as behind it. + _reverse_children!(sub.child_subintegrators) + + return sub +end + +@unroll function _reverse_children!(children::Tuple) + @unroll for child in children + reverse_direction!(child) + end +end + +function _reverse_time_heap!(heap, threshold) + isempty(heap) && return heap + # Drain first: the new keys are the negated old ones, so pushing them back into + # the heap being read from would corrupt the ordering mid-traversal. + old = [pop!(heap)] + while !isempty(heap) + push!(old, pop!(heap)) + end + for key in old + reversed = -key + reversed > threshold && push!(heap, reversed) + end + return heap +end + # Check time-step information consistency validate_time_point(integrator::AnySplitIntegrator) = validate_time_point(integrator, integrator.child_subintegrators) function validate_time_point(parent, child::SplitSubIntegrator) diff --git a/test/adjoint_pair.jl b/test/adjoint_pair.jl new file mode 100644 index 0000000..53bab32 --- /dev/null +++ b/test/adjoint_pair.jl @@ -0,0 +1,88 @@ +using OrdinaryDiffEqOperatorSplitting +using Test + +import DiffEqBase: DiffEqBase, ODEFunction +import SciMLBase +import SciMLBase: ReturnCode +using OrdinaryDiffEqTsit5 + +using OrdinaryDiffEqOperatorSplitting: order, coefficients + +M = [-1.0 0.5; 0.5 -2.0] +odeA(du, u, p, t) = (du[1] = -u[1]; du[2] = -2 * u[2]; nothing) +odeB(du, u, p, t) = (du[1] = 0.5 * u[2]; du[2] = 0.5 * u[1]; nothing) +dofs = [1, 2] +u0 = [1.0, 1.0] +fsplit = GenericSplitFunction((ODEFunction(odeA), ODEFunction(odeB)), (dofs, dofs)) +uexact = exp(M) * u0 + +function splitting_error(alg, dt) + prob = OperatorSplittingProblem(fsplit, copy(u0), (0.0, 1.0)) + integ = DiffEqBase.init( + prob, alg; dt = dt, adaptive = false, abstol = 1.0e-14, reltol = 1.0e-14 + ) + DiffEqBase.solve!(integ) + @assert integ.sol.retcode == ReturnCode.Success + return maximum(abs, integ.u .- uexact) +end + +@testset "Adjoint pairs" begin + @testset "the base scheme must be of odd order" begin + # Odd p is what makes the averaging work: the adjoint's leading error is + # (-1)^p C h^(p+1), so the signs oppose and cancel. For even p they are equal, + # the average stays order p, and the difference is no longer an error estimate. + @test AdjointPair(Ruth3((Tsit5(), Tsit5()))) isa AdjointPair + @test_throws ArgumentError AdjointPair(StrangMarchuk((Tsit5(), Tsit5()))) + @test_throws ArgumentError AdjointPair(Yoshida4((Tsit5(), Tsit5()))) + end + + @testset "the pair raises the order by one" begin + alg = AdjointPair(Ruth3((Tsit5(), Tsit5()))) + @test order(alg) == 4 + # The estimate measures the *base* scheme's leading error, so that is the + # order the controller sees. + @test OrdinaryDiffEqOperatorSplitting.alg_adaptive_order(alg) == 3 + @test SciMLBase.isadaptive(alg) + end + + @testset "AdjointPair(LieTrotterGodunov) reproduces PalindromicPairLieTrotterGodunov" begin + # PPLTG is exactly this construction at p = 1, hand-written. Agreement to + # machine precision tests the whole generic path -- table execution, the + # flat-sequence adjoint, averaging, rollback -- against trusted code. + prob_pair = OperatorSplittingProblem(fsplit, copy(u0), (0.0, 1.0)) + pair = DiffEqBase.init( + prob_pair, AdjointPair(LieTrotterGodunov((Tsit5(), Tsit5()))); + dt = 0.1, adaptive = false, abstol = 1.0e-14, reltol = 1.0e-14 + ) + DiffEqBase.solve!(pair) + + prob_ppltg = OperatorSplittingProblem(fsplit, copy(u0), (0.0, 1.0)) + ppltg = DiffEqBase.init( + prob_ppltg, PalindromicPairLieTrotterGodunov((Tsit5(), Tsit5())); + dt = 0.1, adaptive = false, abstol = 1.0e-14, reltol = 1.0e-14 + ) + DiffEqBase.solve!(ppltg) + + @test pair.u == ppltg.u + end + + @testset "the pair is more accurate than its base scheme" begin + # The order itself is checked in test/convergence.jl. What matters here is that + # averaging buys accuracy rather than merely costing two sequences. + @test splitting_error(AdjointPair(Ruth3((Tsit5(), Tsit5()))), 0.1) < + splitting_error(Ruth3((Tsit5(), Tsit5())), 0.1) + end + + @testset "the pair difference drives adaptive stepping" begin + prob = OperatorSplittingProblem(fsplit, copy(u0), (0.0, 1.0)) + integ = DiffEqBase.init( + prob, AdjointPair(Ruth3((Tsit5(), Tsit5()))); + dt = 0.5, abstol = 1.0e-10, reltol = 1.0e-8 + ) + DiffEqBase.solve!(integ) + @test integ.sol.retcode == ReturnCode.Success + @test integ.t ≈ 1.0 + @test isfinite(integ.EEst) + @test maximum(abs, integ.u .- uexact) < 1.0e-6 + end +end diff --git a/test/callbacks.jl b/test/callbacks.jl index 3ef3fe9..2645e76 100644 --- a/test/callbacks.jl +++ b/test/callbacks.jl @@ -100,6 +100,7 @@ exact_crossing(level) = -10 * log(level / 3) ltg(), StrangMarchuk((Euler(), Euler())), PalindromicPairLieTrotterGodunov((Tsit5(), Tsit5())), + AdjointPair(Ruth3((Tsit5(), Tsit5()))), ) cb = DiscreteCallback( (u, t, integrator) -> isapprox(t, 0.5), diff --git a/test/coefficient_schemes.jl b/test/coefficient_schemes.jl new file mode 100644 index 0000000..4433980 --- /dev/null +++ b/test/coefficient_schemes.jl @@ -0,0 +1,84 @@ +using OrdinaryDiffEqOperatorSplitting +using Test + +import DiffEqBase: DiffEqBase, ODEFunction +import SciMLBase +import SciMLBase: ReturnCode +using OrdinaryDiffEqTsit5 + +using OrdinaryDiffEqOperatorSplitting: SplittingCoefficients, coefficients, order + +# Non-commuting pair with a known exact solution, as in test/backward.jl. +M = [-1.0 0.5; 0.5 -2.0] +odeA(du, u, p, t) = (du[1] = -u[1]; du[2] = -2 * u[2]; nothing) +odeB(du, u, p, t) = (du[1] = 0.5 * u[2]; du[2] = 0.5 * u[1]; nothing) +dofs = [1, 2] +u0 = [1.0, 1.0] +fsplit = GenericSplitFunction((ODEFunction(odeA), ODEFunction(odeB)), (dofs, dofs)) + +# Convergence orders live in test/convergence.jl, which runs every algorithm over two +# and three operators, nested, forward and backward. What is left here is what is +# specific to building a scheme out of a coefficient table. +@testset "Coefficient-table splitting schemes" begin + @testset "each operator's coefficients must sum to one" begin + # Ruth's third order table (Ruth, 1983): both columns sum to 1. + @test SplittingCoefficients((2 // 3, 7 // 24), (-2 // 3, 3 // 4), (1 // 1, -1 // 24)) isa + SplittingCoefficients + # Operator 1 sums to 0.9, so the scheme is not even consistent. + @test_throws ArgumentError SplittingCoefficients((0.5, 0.5), (0.4, 0.5)) + end + + @testset "Ruth3 exposes its table and order" begin + alg = Ruth3((Tsit5(), Tsit5())) + @test order(alg) == 3 + @test coefficients(alg) isa SplittingCoefficients + end + + @testset "Yoshida4's merged table carries a zero coefficient" begin + # Merging the adjacent flows the triple jump leaves next to each other is what + # brings it down to eight evaluations, and it zeroes the last stage's second + # coefficient. Its convergence in test/convergence.jl is therefore also the + # coverage for the zero-coefficient skip path. + table = coefficients(Yoshida4((Tsit5(), Tsit5()))).a + @test order(Yoshida4((Tsit5(), Tsit5()))) == 4 + @test length(table) == 4 + @test count(iszero, Iterators.flatten(table)) == 1 + @test iszero(table[end][end]) + end + + @testset "tables stay compile-time constants" begin + # The stage count is a type parameter derived from `length`, and `@unroll` can + # only unroll the stage loop if that survives inference. Lie-Trotter's table is + # the one actually built at run time, from the length of `inner_algs`. + @test (@inferred coefficients(Ruth3((Tsit5(), Tsit5())))) isa + SplittingCoefficients{3, 2} + @test (@inferred coefficients(LieTrotterGodunov((Tsit5(), Tsit5())))) isa + SplittingCoefficients{1, 2} + end + + @testset "the table is re-applied faithfully on every step" begin + # A table ends on the last operator, so at the next step's start operator 1's + # buffer is stale and the `mark_next_sync_continuous` shortcut is invalid for + # it. That bug leaves the *first* step exact and corrupts every later one, so + # a single-step check cannot see it: compare several steps against the + # scheme's own composition of exact linear flows. + A = [-1.0 0.0; 0.0 -2.0] + B = [0.0 0.5; 0.5 0.0] + a = coefficients(Ruth3((Tsit5(), Tsit5()))).a + + h = 0.1 + reference = copy(u0) + for _ in 1:4, stage in a + reference = exp(B * (float(stage[2]) * h)) * (exp(A * (float(stage[1]) * h)) * reference) + end + + prob = OperatorSplittingProblem(fsplit, copy(u0), (0.0, 4h)) + integ = DiffEqBase.init( + prob, Ruth3((Tsit5(), Tsit5())); dt = h, abstol = 1.0e-14, reltol = 1.0e-14 + ) + DiffEqBase.solve!(integ) + + @test integ.iter == 4 + @test integ.u ≈ reference atol = 1.0e-12 + end +end diff --git a/test/convergence.jl b/test/convergence.jl index bb836d8..2fab596 100644 --- a/test/convergence.jl +++ b/test/convergence.jl @@ -44,21 +44,29 @@ function convergence_rates(f, alg, tspan, ustart, utarget; dts = (0.1, 0.05, 0.0 end @testset "Convergence order" begin - for (AlgType, expected_order) in ( - (LieTrotterGodunov, 1), - (StrangMarchuk, 2), - (PalindromicPairLieTrotterGodunov, 2), - ) - cases = ( - ("two operators", f_two, AlgType((Tsit5(), Tsit5()))), - ("three operators", f_three, AlgType((Tsit5(), Tsit5(), Tsit5()))), - ("nested", f_nested, AlgType((Tsit5(), AlgType((Tsit5(), Tsit5()))))), + # `build` takes the tuple of inner algorithms, so schemes that wrap a base rather + # than taking `inner_algs` directly (AdjointPair) fit the same loop. Ruth3 is a + # two-operator table, so it sits out the three-operator case. + for (name, build, expected_order, supports_three) in ( + ("LieTrotterGodunov", LieTrotterGodunov, 1, true), + ("StrangMarchuk", StrangMarchuk, 2, true), + ("PalindromicPairLieTrotterGodunov", PalindromicPairLieTrotterGodunov, 2, true), + ("Ruth3", Ruth3, 3, false), + ("Yoshida4", Yoshida4, 4, false), + ("AdjointPair(Ruth3)", inner -> AdjointPair(Ruth3(inner)), 4, false), ) + two = ("two operators", f_two, build((Tsit5(), Tsit5()))) + nested = ("nested", f_nested, build((Tsit5(), build((Tsit5(), Tsit5()))))) + cases = if supports_three + (two, ("three operators", f_three, build((Tsit5(), Tsit5(), Tsit5()))), nested) + else + (two, nested) + end directions = ( ("forward", (0.0, 1.0), u0, uT), ("backward", (1.0, 0.0), uT, u0), ) - @testset "$(nameof(AlgType)) | $case | $dir (order $expected_order)" for + @testset "$name | $case | $dir (order $expected_order)" for (case, f, alg) in cases, (dir, tspan, ustart, utarget) in directions rates = convergence_rates(f, alg, tspan, ustart, utarget) @@ -68,3 +76,9 @@ end end end end + +@testset "two-operator tables reject other operator counts" begin + @test_throws ArgumentError Ruth3((Tsit5(), Tsit5(), Tsit5())) + @test_throws ArgumentError Ruth3((Tsit5(),)) + @test_throws ArgumentError Yoshida4((Tsit5(), Tsit5(), Tsit5())) +end diff --git a/test/imex_mri_sr.jl b/test/imex_mri_sr.jl new file mode 100644 index 0000000..5d43366 --- /dev/null +++ b/test/imex_mri_sr.jl @@ -0,0 +1,248 @@ +using OrdinaryDiffEqOperatorSplitting +using Test + +import DiffEqBase: DiffEqBase, ODEFunction +import SciMLBase +using OrdinaryDiffEqLowOrderRK: Heun, BS3 + +using OrdinaryDiffEqOperatorSplitting: MRISRCoefficients, + IMEX_MRI_SR2_COEFFICIENTS, IMEX_MRI_SR3_COEFFICIENTS + +# --------------------------------------------------------------------------- +# The Kvaerno-Prothero-Robinson problem, [FisReyRob:2023:iem] eq. (6.1), with the +# three-way partitioning of eq. (6.3). Nonlinear, non-autonomous, stiff, multirate, and +# with an analytic solution, which is why the paper uses it to measure convergence. +# --------------------------------------------------------------------------- + +const λF = -10.0 +const λS = -1.0 +const ε = 0.1 +const α = 1.0 +const β = 20.0 + +const Λ = [ + λF (1 - ε) / α * (λF - λS) + -α * ε * (λF - λS) λS +] + +kpr_exact(t) = [sqrt(3 + cos(β * t)), sqrt(2 + cos(t))] + +# The bracketed vector shared by all three partitions of (6.3). +@inline function kpr_inner(u, t) + return ( + (-3 + u[1]^2 - cos(β * t)) / (2 * u[1]), + (-2 + u[2]^2 - cos(t)) / (2 * u[2]), + ) +end + +# f^{F} = Λ[1 0; 0 0] * inner +function kpr_fast!(du, u, p, t) + g1, g2 = kpr_inner(u, t) + du[1] = Λ[1, 1] * g1 + du[2] = Λ[2, 1] * g1 + return nothing +end + +# f^{E} = [0 ; sin(t) / (2 v)] with a minus sign, from (6.1)/(6.3) +function kpr_expl!(du, u, p, t) + du[1] = 0.0 + du[2] = -sin(t) / (2 * u[2]) + return nothing +end + +# f^{I} = Λ[0 0; 0 1] * inner, minus the β sin(βt)/(2u) term of (6.1) +function kpr_impl!(du, u, p, t) + g1, g2 = kpr_inner(u, t) + du[1] = Λ[1, 2] * g2 - β * sin(β * t) / (2 * u[1]) + du[2] = Λ[2, 2] * g2 + return nothing +end + +function kpr_split_function() + dofs = 1:2 + return GenericSplitFunction( + (ODEFunction(kpr_fast!), ODEFunction(kpr_expl!), ODEFunction(kpr_impl!)), + (dofs, dofs, dofs), + ) +end + +# Solve KPR with outer step H and fast step H/10, as in §6.1, and return the maximum +# error over ten equally spaced output points. +function kpr_max_error(alg_ctor, fast_alg, H; tend = 5π / 2, adaptive = false, kwargs...) + f = kpr_split_function() + u0 = kpr_exact(0.0) + prob = OperatorSplittingProblem(f, copy(u0), (0.0, tend)) + + dt = TreeOption(f, H) + dt[f[1]] = H / 10 + + saveat = collect(range(0.0, tend; length = 11)) + integrator = DiffEqBase.init( + prob, alg_ctor(fast_alg); + dt, saveat, adaptive, kwargs... + ) + DiffEqBase.solve!(integrator) + sol = integrator.sol + + err = 0.0 + for t in saveat + err = max(err, maximum(abs, sol(t) .- kpr_exact(t))) + end + return err +end + +# Least squares slope of log(error) against log(H). +function observed_order(errors, steps) + x = log.(steps) + y = log.(errors) + x̄, ȳ = sum(x) / length(x), sum(y) / length(y) + return sum((x .- x̄) .* (y .- ȳ)) / sum((x .- x̄) .^ 2) +end + +@testset "IMEX-MRI-SR" begin + # The order of the method as a whole is the real check on both the coefficient + # tables and the step: a wrong coefficient costs an order. + @testset "convergence order on KPR (§6.1)" begin + # H = π/2^k as in the paper. Both methods approach their design order from + # above and are asymptotic by k ≈ 9: measured local orders are 2.14, 2.07, + # 2.04, 2.02 (SR2) and 3.22, 3.12, 3.06, 3.03 (SR3) for k = 9, 10, 11, 12. + # Coarser steps are still in the transition regime -- at k = 5 SR2 measures + # nearly 3 -- and at H ≈ 0.2 the stage solves stop converging altogether. + ks = 9:11 + steps = [π / 2^k for k in ks] + + for (name, ctor, fast_alg, expected) in ( + ("IMEXMRISR2", IMEXMRISR2, Heun(), 2), + ("IMEXMRISR3", IMEXMRISR3, BS3(), 3), + ) + errors = [kpr_max_error(ctor, fast_alg, H) for H in steps] + @test all(isfinite, errors) + @test issorted(errors; rev = true) # error falls as H falls + p = observed_order(errors, steps) + @test isapprox(p, expected; atol = 0.2) + end + end + + @testset "adaptive stepping tracks the tolerance" begin + f = kpr_split_function() + u0 = kpr_exact(0.0) + tend = 5π / 2 + + prev_err = Inf + for tol in (1.0e-4, 1.0e-6, 1.0e-8) + prob = OperatorSplittingProblem(f, copy(u0), (0.0, tend)) + dt = TreeOption(f, 0.05) + dt[f[1]] = 0.005 + integrator = DiffEqBase.init( + prob, IMEXMRISR3(BS3()); + dt, adaptive = true, abstol = tol, reltol = tol, + ) + DiffEqBase.solve!(integrator) + @test SciMLBase.successful_retcode(integrator.sol) + err = maximum(abs, integrator.u .- kpr_exact(tend)) + @test err < prev_err # tighter tolerance, smaller error + prev_err = err + end + end + + @testset "the step is adaptive and reports its orders" begin + @test SciMLBase.isadaptive(IMEXMRISR2(Heun())) + @test SciMLBase.isadaptive(IMEXMRISR3(BS3())) + @test OrdinaryDiffEqOperatorSplitting.order(IMEXMRISR2(Heun())) == 2 + @test OrdinaryDiffEqOperatorSplitting.order(IMEXMRISR3(BS3())) == 3 + # The estimate comes from the embedding, one order below. + @test OrdinaryDiffEqOperatorSplitting.alg_adaptive_order(IMEXMRISR2(Heun())) == 1 + @test OrdinaryDiffEqOperatorSplitting.alg_adaptive_order(IMEXMRISR3(BS3())) == 2 + end + + @testset "reinit! reproduces the same solution" begin + f = kpr_split_function() + u0 = kpr_exact(0.0) + prob = OperatorSplittingProblem(f, copy(u0), (0.0, 1.0)) + dt = TreeOption(f, 0.05) + dt[f[1]] = 0.005 + + integrator = DiffEqBase.init(prob, IMEXMRISR3(BS3()); dt, adaptive = false) + DiffEqBase.solve!(integrator) + first_u = copy(integrator.u) + + DiffEqBase.reinit!(integrator, copy(u0)) + DiffEqBase.solve!(integrator) + @test integrator.u ≈ first_u + end + + # The interface errors are worth testing directly: they are the guard rails around + # reusing GenericSplitFunction for an *additive* partition, which the type system + # cannot express. + @testset "misuse is rejected" begin + dofs = 1:2 + fast, expl, impl = ODEFunction(kpr_fast!), ODEFunction(kpr_expl!), ODEFunction(kpr_impl!) + u0 = kpr_exact(0.0) + + two_ops = GenericSplitFunction((fast, impl), (dofs, dofs)) + @test_throws ArgumentError DiffEqBase.init( + OperatorSplittingProblem(two_ops, copy(u0), (0.0, 1.0)), + IMEXMRISR2(Heun()); dt = 0.1, + ) + + # Disjoint slices: the classic splitting layout, which is wrong here. + sliced = GenericSplitFunction((fast, expl, impl), (1:1, 2:2, dofs)) + @test_throws ArgumentError DiffEqBase.init( + OperatorSplittingProblem(sliced, copy(u0), (0.0, 1.0)), + IMEXMRISR2(Heun()); dt = 0.1, + ) + + # A nested fast operator cannot carry the stage forcing. + nested_fast = GenericSplitFunction( + (GenericSplitFunction((fast, fast), (dofs, dofs)), expl, impl), + (dofs, dofs, dofs), + ) + @test_throws ArgumentError DiffEqBase.init( + OperatorSplittingProblem(nested_fast, copy(u0), (0.0, 1.0)), + IMEXMRISR2(LieTrotterGodunov((Heun(), Heun()))); dt = 0.1, + ) + end + + # The tables themselves are validated by the constructor, which an order test cannot + # reach; this checks that the validation actually rejects bad tables. + @testset "malformed coefficient tables are rejected" begin + good_Ω = Rational{Int}[ + 0 0 0 + 1 // 2 0 0 + -1 // 2 3 // 2 0 + 0 1 0 + ] + good_Γ = Rational{Int}[ + 0 0 0 + -1 // 2 1 // 2 0 + 0 -1 // 2 1 // 2 + 1 -1 0 + ] + good_c = Rational{Int}[0, 1 // 2, 1] + @test MRISRCoefficients((good_Ω,), good_Γ, good_c) isa MRISRCoefficients + + # eq. (2.11a): row 2 of Ω^{0} no longer sums to c[2]. + bad = copy(good_Ω); bad[2, 1] = 1 // 3 + @test_throws ArgumentError MRISRCoefficients((bad,), good_Γ, good_c) + + # eq. (2.11c): Γ's rows must sum to zero. + bad = copy(good_Γ); bad[2, 1] = -1 // 3 + @test_throws ArgumentError MRISRCoefficients((good_Ω,), bad, good_c) + + # Ω^{0} must be strictly lower triangular. + bad = copy(good_Ω); bad[2, 2] = bad[2, 1]; bad[2, 1] = 0 + @test_throws ArgumentError MRISRCoefficients((bad,), good_Γ, good_c) + + # γ̂_S ≠ 0 would demand an implicit solve for the embedding. + bad = copy(good_Γ); bad[4, 3] = 1; bad[4, 2] = -2 + @test_throws ArgumentError MRISRCoefficients((good_Ω,), bad, good_c) + + # A zero abscissa past the first stage. + @test_throws ArgumentError MRISRCoefficients( + (good_Ω,), good_Γ, Rational{Int}[0, 0, 1] + ) + + # No embedding row. + @test_throws ArgumentError MRISRCoefficients((good_Ω[1:3, :],), good_Γ, good_c) + end +end diff --git a/test/saving.jl b/test/saving.jl index bc545f3..2220e1c 100644 --- a/test/saving.jl +++ b/test/saving.jl @@ -33,6 +33,8 @@ algs() = ( LieTrotterGodunov((Tsit5(), Tsit5())), StrangMarchuk((Tsit5(), Tsit5())), PalindromicPairLieTrotterGodunov((Tsit5(), Tsit5())), + Ruth3((Tsit5(), Tsit5())), + AdjointPair(Ruth3((Tsit5(), Tsit5()))), ) function exact(t)