### Install DiffEqCallbacks.jl Source: https://docs.sciml.ai/DiffEqCallbacks/stable Use the Julia package manager to add DiffEqCallbacks.jl to your project. ```julia using Pkg Pkg.add("DiffEqCallbacks") ``` -------------------------------- ### Gauss-Kronrod Summation Integration Source: https://docs.sciml.ai/DiffEqCallbacks/stable/integrating This example demonstrates `IntegratingGKSumCallback` with `IntegrandValuesSum` for adaptive summation integration using the Gauss-Kronrod method. It integrates a cosine function and verifies the accumulated sum. ```julia integrated = IntegrandValuesSum(zeros(1)) sol = solve(prob, Euler(), callback = IntegratingGKSumCallback( (u, t, integrator) -> [cos.(1000*u[1])], integrated, Float64[0.0], 1e-7), dt = 0.1) @test integrated.integrand[1] ≈ sin(1000)/1000 ``` -------------------------------- ### Saving Example: Basic Usage Source: https://docs.sciml.ai/DiffEqCallbacks/stable/output_saving Solves a matrix equation and saves the trace and norm of the matrix at each step using SavingCallback. The results are stored in the provided SavedValues cache. ```julia using DiffEqCallbacks, OrdinaryDiffEq, LinearAlgebra prob = ODEProblem((du, u, p, t) -> du .= u, rand(4, 4), (0.0, 1.0)) saved_values = SavedValues(Float64, Tuple{Float64, Float64}) cb = SavingCallback((u, t, integrator) -> (tr(u), norm(u)), saved_values) sol = solve(prob, Tsit5(), callback = cb) print(saved_values.saveval) ``` ```julia [(1.1492630845558645, 2.1628354583301186), (1.2702331449750137, 2.3904929369238768), (1.6279824786266597, 3.0637530062793377), (2.276271379576986, 4.283788906726876), (3.124020821456864, 5.879196065729068)] ``` -------------------------------- ### Summation Integration with State-Dependent Integrand Source: https://docs.sciml.ai/DiffEqCallbacks/stable/integrating This example uses `IntegrandValuesSum` with `IntegratingSumCallback` where the integrand depends on the state variable `u[1]`. The final sum is verified against the expected value. ```julia integrated = IntegrandValuesSum(zeros(1)) sol = solve(prob, Euler(), callback = IntegratingSumCallback( (u, t, integrator) -> [u[1]], integrated, Float64[0.0]), dt = 0.1) @test integrated.integrand[1] == 0.5 ``` -------------------------------- ### FunctionCallingCallback Constructor Source: https://docs.sciml.ai/DiffEqCallbacks/stable/output_saving Defines a callback to execute a function at specified time points during integration. Configure the function, evaluation times, and whether to call at the start or every step. ```julia FunctionCallingCallback(func; funcat = Vector{Float64}(), func_everystep = isempty(funcat), func_start = true, tdir = 1) ``` -------------------------------- ### Integration with State-Dependent Integrand Source: https://docs.sciml.ai/DiffEqCallbacks/stable/integrating This example shows how to use `IntegrandValues` with a state-dependent integrand in `IntegratingCallback`. The integrated values are compared against a calculated sum based on the state variable `u[1]`. ```julia integrated = IntegrandValues(Float64, Vector{Float64}) sol = solve(prob, Euler(), callback = IntegratingCallback( (u, t, integrator) -> [u[1]], integrated, Float64[0.0]), dt = 0.1) @test all(integrated.integrand .≈ [[((n * 0.1)^2 - ((n - 1) * (0.1))^2) / 2] for n in 1:10]) @test sum(integrated.integrand)[1] ≈ 0.5 ``` -------------------------------- ### Saving Example: Controlled Saving with saveat Source: https://docs.sciml.ai/DiffEqCallbacks/stable/output_saving Solves the same problem but controls the saving times using the `saveat` option in SavingCallback. This ensures values are saved only at the specified time points. ```julia saved_values = SavedValues(Float64, Tuple{Float64, Float64}) cb = SavingCallback((u, t, integrator) -> (tr(u), norm(u)), saved_values, saveat = 0.0:0.1:1.0) sol = solve(prob, Tsit5(), callback = cb) print(saved_values.saveval) print(saved_values.t) ``` ```julia [(1.1492630845558645, 2.1628354583301186), (1.2701321382958328, 2.3903028491796543), (1.4037131511832222, 2.6416932880748103), (1.5513428040117274, 2.9195223179368894), (1.7144993658480396, 3.2265719412484897), (1.8948143932218917, 3.5659126371385406), (2.094093063344883, 3.9409416271260165), (2.3143316499385054, 4.355415763447273), (2.5577322347873825, 4.813479215205044), (2.8267301451683244, 5.319715103755701), (3.124020821456864, 5.879196065729068)][0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0] ``` -------------------------------- ### AutoAbstol Callback for Adaptive Absolute Tolerance Source: https://docs.sciml.ai/DiffEqCallbacks/stable/step_control The `AutoAbstol` callback automatically adapts the absolute tolerance of the ODE solver. It starts with an initial maximum absolute tolerance and updates it based on the maximum state value reached, multiplied by the relative tolerance. ```julia using DiffEqCallbacks # Example usage with default init_curmax # cb = AutoAbstol() # Example usage with a custom initial absolute tolerance # cb = AutoAbstol(init_curmax=1e-5) ``` -------------------------------- ### PeriodicCallback for Regular Time Intervals Source: https://docs.sciml.ai/DiffEqCallbacks/stable/timed_callbacks Employ PeriodicCallback when an affect! function needs to be executed at regular intervals (Δt) relative to the integration start time. A phase argument can shift these intervals. ```julia PeriodicCallback(f, Δt::Number; phase = 0, initial_affect = false, final_affect = false, kwargs...) ``` -------------------------------- ### Lorenz Attractor Model Definition Source: https://docs.sciml.ai/DiffEqCallbacks/stable/uncertainty_quantification Defines the Lorenz system of differential equations, including the function 'g', initial conditions 'u0', time span 'tspan', and parameters 'p'. This setup is used for uncertainty quantification on chaotic systems. ```julia function g(du, u, p, t) du[1] = p[1] * (u[2] - u[1]) du[2] = u[1] * (p[2] - u[3]) - u[2] du[3] = u[1] * u[2] - p[3] * u[3] end u0 = [1.0; 0.0; 0.0] tspan = (0.0, 30.0) p = [10.0, 28.0, 8 / 3] prob = ODEProblem(g, u0, tspan, p) ``` -------------------------------- ### Adaptive ProbInts Callback Initialization Source: https://docs.sciml.ai/DiffEqCallbacks/stable/uncertainty_quantification Initializes the AdaptiveProbIntsUncertainty callback with order 5 for use with the Lorenz attractor problem. ```julia cb = AdaptiveProbIntsUncertainty(5) ``` -------------------------------- ### Create ProbIntsUncertainty Callback (σ=0.2) Source: https://docs.sciml.ai/DiffEqCallbacks/stable/uncertainty_quantification Initializes the ProbIntsUncertainty callback for an order 1 method (Euler) with a noise scaling of 0.2. This simulates an error of approximately 0.2 at each step. ```julia cb = ProbIntsUncertainty(0.2, 1) ``` -------------------------------- ### Create ProbIntsUncertainty Callback (σ=0.5) Source: https://docs.sciml.ai/DiffEqCallbacks/stable/uncertainty_quantification Initializes the ProbIntsUncertainty callback with a higher noise scaling of 0.5. This increases the simulated error per step. ```julia cb = ProbIntsUncertainty(0.5, 1) ``` -------------------------------- ### Adaptive ProbInts on FitzHugh-Nagumo (Default Tolerances) Source: https://docs.sciml.ai/DiffEqCallbacks/stable/uncertainty_quantification Applies AdaptiveProbIntsUncertainty with default tolerances to the FitzHugh-Nagumo model to visualize solution uncertainty. ```julia cb = AdaptiveProbIntsUncertainty(5) sol = solve(prob, Tsit5()) ensemble_prob = EnsembleProblem(prob) sim = solve(ensemble_prob, Tsit5(), trajectories = 100, callback = cb) plot(sim, idxs = (0, 1), linealpha = 0.4) ``` -------------------------------- ### Adaptive ProbInts on FitzHugh-Nagumo (Increased Tolerances) Source: https://docs.sciml.ai/DiffEqCallbacks/stable/uncertainty_quantification Demonstrates the effect of increased tolerances (abstol=1e-3, reltol=1e-1) on solution uncertainty for the FitzHugh-Nagumo model using AdaptiveProbIntsUncertainty. ```julia cb = AdaptiveProbIntsUncertainty(5) sol = solve(prob, Tsit5()) ensemble_prob = EnsembleProblem(prob) sim = solve(ensemble_prob, Tsit5(), trajectories = 100, callback = cb, abstol = 1e-3, reltol = 1e-1) plot(sim, idxs = (0, 1), linealpha = 0.4) ``` -------------------------------- ### Define FitzHugh-Nagumo Model Source: https://docs.sciml.ai/DiffEqCallbacks/stable/uncertainty_quantification Sets up the FitzHugh-Nagumo differential equation model, including initial conditions, parameters, and time span. ```julia using DiffEqCallbacks, OrdinaryDiffEq, Plots gr(fmt = :png) function fitz(du, u, p, t) V, R = u a, b, c = p du[1] = c * (V - V^3 / 3 + R) du[2] = -(1 / c) * (V - a - b * R) end u0 = [-1.0; 1.0] tspan = (0.0, 20.0) p = (0.2, 0.2, 3.0) prob = ODEProblem(fitz, u0, tspan, p) ``` -------------------------------- ### Initialize IntegrandValuesSum for Array and Scalar Integrands Source: https://docs.sciml.ai/DiffEqCallbacks/stable/integrating Demonstrates how to initialize `IntegrandValuesSum` for both array-valued and scalar-valued integrands. ```julia # For array-valued integrands integrated = IntegrandValuesSum(zeros(3)) # For scalar-valued integrands integrated = IntegrandValuesSum(0.0) ``` -------------------------------- ### Julia System and Build Information Source: https://docs.sciml.ai/DiffEqCallbacks/stable Provides details about the Julia version, commit, build information, and platform used for building the documentation. ```text Julia Version 1.12.6 Commit 15346901f00 (2026-04-09 19:20 UTC) Build Info: Official https://julialang.org release Platform Info: OS: Linux (x86_64-linux-gnu) CPU: 4 × AMD EPYC 7763 64-Core Processor WORD_SIZE: 64 LLVM: libLLVM-18.1.7 (ORCJIT, znver3) GC: Built with stock GC Threads: 1 default, 1 interactive, 1 GC (on 4 virtual cores) ``` -------------------------------- ### Monte Carlo Simulation with ProbInts on Lorenz Attractor Source: https://docs.sciml.ai/DiffEqCallbacks/stable/uncertainty_quantification Solves an EnsembleProblem of the Lorenz attractor using Tsit5(), 100 trajectories, and the AdaptiveProbIntsUncertainty callback to visualize solution uncertainty over time. ```julia ensemble_prob = EnsembleProblem(prob) sim = solve(ensemble_prob, Tsit5(), trajectories = 100, callback = cb) plot(sim, idxs = (0, 1), linealpha = 0.4) ``` -------------------------------- ### AdaptiveProbIntsUncertainty Callback Source: https://docs.sciml.ai/DiffEqCallbacks/stable/uncertainty_quantification Use AdaptiveProbIntsUncertainty for automated uncertainty quantification with adaptive time-stepping methods. It estimates the noise scaling factor automatically. ```julia AdaptiveProbIntsUncertainty(order, save = true) ``` -------------------------------- ### PositiveDomain Callback for Non-Negative Solutions Source: https://docs.sciml.ai/DiffEqCallbacks/stable/step_control Use the `PositiveDomain` callback to ensure non-negative values in ODE solutions by reducing time steps and setting negative values to 0. This callback is inspired by Shampine's et al. paper on non-negative ODE solutions. ```julia using DiffEqCallbacks # Example usage (assuming 'ode_problem' is defined) # cb = PositiveDomain() # sol = solve(ode_problem, Tsit5(), callback=cb) ``` -------------------------------- ### Manifest.toml Dependencies Source: https://docs.sciml.ai/DiffEqCallbacks/stable A comprehensive list of all dependencies and their versions, including transitive dependencies, for the DiffEqCallbacks.jl documentation build. ```toml Status `~/work/DiffEqCallbacks.jl/DiffEqCallbacks.jl/docs/Manifest.toml` [47edcb42] ADTypes v1.21.0 [a4c015fc] ANSIColoredPrinters v0.0.1 [1520ce14] AbstractTrees v0.4.5 [7d9f7c33] Accessors v0.1.44 [79e6a3ab] Adapt v4.5.2 [66dad0bd] AliasTables v1.1.3 [4fba245c] ArrayInterface v7.24.0 [d1d4a3ce] BitFlags v0.1.9 [62783981] BitTwiddlingConvenienceFunctions v0.1.6 [7034ab61] BracketingNonlinearSolve v1.12.1 [2a0fbf3d] CPUSummary v0.2.7 [fb6a15b2] CloseOpenIntervals v0.1.13 [944b1d66] CodecZlib v0.7.8 [35d6a980] ColorSchemes v3.31.0 [3da002f7] ColorTypes v0.12.1 [c3611d14] ColorVectorSpace v0.11.0 [5ae59095] Colors v0.13.1 [38540f10] CommonSolve v0.2.6 [bbf7d656] CommonSubexpressions v0.3.1 [f70d9fcc] CommonWorldInvalidations v1.0.0 [34da2185] Compat v4.18.1 [a33af91c] CompositionsBase v0.1.2 [2569d6c7] ConcreteStructs v0.2.3 [f0e56b4a] ConcurrentUtilities v2.5.1 [187b0558] ConstructionBase v1.6.0 [d38c429a] Contour v0.6.3 [adafc99b] CpuId v0.3.1 [9a962f9c] DataAPI v1.16.0 [864edb3b] DataStructures v0.19.4 [8bb1440f] DelimitedFiles v1.9.1 [2b5f629d] DiffEqBase v6.218.0 [459566f4] DiffEqCallbacks v4.16.0 `~/work/DiffEqCallbacks.jl/DiffEqCallbacks.jl` [163ba53b] DiffResults v1.1.0 [b552c78f] DiffRules v1.15.1 [a0c0ee7d] DifferentiationInterface v0.7.16 [ffbed154] DocStringExtensions v0.9.5 [e30172f5] Documenter v1.17.0 [4e289a0a] EnumX v1.0.7 [f151be2c] EnzymeCore v0.8.19 [460bff9d] ExceptionUnwrapping v0.1.11 [d4d017d3] ExponentialUtilities v1.30.0 [e2ba6199] ExprTools v0.1.10 [55351af7] ExproniconLite v0.10.14 [c87230d0] FFMPEG v0.4.5 [7034ab61] FastBroadcast v1.3.1 [9aa1b823] FastClosures v0.3.2 [442a2c76] FastGaussQuadrature v1.1.0 [a4df4552] FastPower v1.3.1 [1a297f60] FillArrays v1.16.0 [6a86dc24] FiniteDiff v2.30.0 [53c48c17] FixedPointNumbers v0.8.5 [1fa38f19] Format v1.3.7 [f6369f11] ForwardDiff v1.3.3 [069b7b12] FunctionWrappers v1.1.3 [77dc65aa] FunctionWrappersWrappers v1.7.0 [46192b85] GPUArraysCore v0.2.0 [28b8d3ca] GR v0.73.24 [c145ed77] GenericSchur v0.5.6 [d7ba0133] Git v1.5.0 [42e2da0e] Grisu v1.0.2 [cd3eb016] HTTP v1.11.0 [b5f81e59] IOCapture v1.0.0 [615f187c] IfElse v0.1.1 [3587e190] InverseFunctions v0.1.17 [92d709cd] IrrationalConstants v0.2.6 [82899510] IteratorInterfaceExtensions v1.0.0 [1019f520] JLFzf v0.1.11 [692b3bcd] JLLWrappers v1.7.1 [682c06a0] JSON v1.5.0 [ae98c720] Jieko v0.2.1 [ba0b0d4f] Krylov v0.10.6 [b964fa9f] LaTeXStrings v1.4.0 [23fbe1c1] Latexify v0.16.10 [10f19ff3] LayoutPointers v0.1.17 [0e77f7df] LazilyInitializedFields v1.3.0 [87fe0de2] LineSearch v0.1.8 [d3585ca7] LineSearches v7.6.1 [7ed4a6bd] LinearSolve v3.75.0 [2ab3a3ac] LogExpFunctions v0.3.29 [e6f89c97] LoggingExtras v1.2.0 [1914dd2f] MacroTools v0.5.16 [d125e4d3] ManualMemory v0.1.8 [d0879d2d] MarkdownAST v0.1.3 [bb5d69b7] MaybeInplace v0.1.4 [739be429] MbedTLS v1.1.10 [442fdcdd] Measures v0.3.3 [e1d29d7a] Missings v1.2.0 [2e0e35c7] Moshi v0.3.7 [46d2c3a1] MuladdMacro v0.2.4 [d41bc354] NLSolversBase v8.0.0 [77ba4419] NaNMath v1.1.3 [8913a72c] NonlinearSolve v4.18.0 [be0214bd] NonlinearSolveBase v2.25.0 [5959db7a] NonlinearSolveFirstOrder v2.1.1 [9a2c21bd] NonlinearSolveQuasiNewton v1.13.1 [26075421] NonlinearSolveSpectralMethods v1.7.1 [4d8831e6] OpenSSL v1.6.1 [bac558e1] OrderedCollections v1.8.1 [1dea7af3] OrdinaryDiffEq v6.111.0 [89bda076] OrdinaryDiffEqAdamsBashforthMoulton v1.11.0 [6ad6398a] OrdinaryDiffEqBDF v1.26.0 [bbf590c4] OrdinaryDiffEqCore v3.33.0 [50262376] OrdinaryDiffEqDefault v1.14.0 [4302a76b] OrdinaryDiffEqDifferentiation v2.9.0 [9286f039] OrdinaryDiffEqExplicitRK v1.12.0 [e0540318] OrdinaryDiffEqExponentialRK v1.15.0 [becaefa8] OrdinaryDiffEqExtrapolation v1.18.0 [5960d6e9] OrdinaryDiffEqFIRK v1.26.0 [101fe9f7] OrdinaryDiffEqFeagin v1.10.0 [d3585ca7] OrdinaryDiffEqFunctionMap v1.11.0 [d28bc4f8] OrdinaryDiffEqHighOrderRK v1.12.0 ``` -------------------------------- ### Basic Integration with IntegrandValues Source: https://docs.sciml.ai/DiffEqCallbacks/stable/integrating This snippet demonstrates the basic usage of `IntegrandValues` with `IntegratingCallback` to collect integrated values over time. It solves an ODE and asserts that the collected values match the expected constant rate. ```julia using OrdinaryDiffEq, DiffEqCallbacks, Test prob = ODEProblem((u, p, t) -> [1.0], [0.0], (0.0, 1.0)) integrated = IntegrandValues(Float64, Vector{Float64}) sol = solve(prob, Euler(), callback = IntegratingCallback( (u, t, integrator) -> [1.0], integrated, Float64[0.0]), dt = 0.1) @test all(integrated.integrand .≈ [[0.1] for i in 1:10]) ``` -------------------------------- ### Project.toml Dependencies Source: https://docs.sciml.ai/DiffEqCallbacks/stable Lists the direct dependencies and their versions for the DiffEqCallbacks.jl package documentation build. ```toml Status `~/work/DiffEqCallbacks.jl/DiffEqCallbacks.jl/docs/Project.toml` [47edcb42] ADTypes v1.21.0 [459566f4] DiffEqCallbacks v4.16.0 `~/work/DiffEqCallbacks.jl/DiffEqCallbacks.jl` [e30172f5] Documenter v1.17.0 [8913a72c] NonlinearSolve v4.18.0 [1dea7af3] OrdinaryDiffEq v6.111.0 [91a5bcdd] Plots v1.41.6 [37e2e46d] LinearAlgebra v1.12.0 ``` -------------------------------- ### GeneralDomain Callback Source: https://docs.sciml.ai/DiffEqCallbacks/stable/step_control Defines arbitrary domains for state vectors, generalizing PositiveDomain. Steps are accepted if extrapolated values are within tolerance. It's coupled with ManifoldProjection but doesn't guarantee all state vectors are within the domain. ```julia GeneralDomain( g, u = nothing; save = true, abstol = nothing, scalefactor = nothing, autonomous = nothing, domain_jacobian = nothing, nlsolve_kwargs = (; abstol = 10 * eps()), kwargs...) ``` -------------------------------- ### Gauss-Kronrod Integration with IntegrandValues Source: https://docs.sciml.ai/DiffEqCallbacks/stable/integrating This snippet illustrates the use of `IntegratingGKCallback` with `IntegrandValues` for adaptive integration using the Gauss-Kronrod method. It integrates a cosine function and checks the result against the analytical solution. ```julia integrated = IntegrandValues(Float64, Vector{Float64}) sol = solve(prob, Euler(), callback = IntegratingGKCallback( (u, t, integrator) -> [cos.(1000*u[1])], integrated, Float64[0.0], 1e-7), dt = 0.1) @test sum(integrated.integrand)[1] .≈ sin(1000)/1000 ``` -------------------------------- ### Summation Integration with IntegrandValuesSum Source: https://docs.sciml.ai/DiffEqCallbacks/stable/integrating This snippet demonstrates using `IntegrandValuesSum` with `IntegratingSumCallback` for accumulating a single sum of integrated values. It verifies that the sum is correctly calculated for a constant integrand. ```julia integrated = IntegrandValuesSum(zeros(1)) sol = solve(prob, Euler(), callback = IntegratingSumCallback( (u, t, integrator) -> [1.0], integrated, Float64[0.0]), dt = 0.1) @test integrated.integrand[1] == 1 ``` -------------------------------- ### IntegratingCallback Source: https://docs.sciml.ai/DiffEqCallbacks/stable/integrating Allows for solving definite integrals efficiently by using free local interpolation of a given step to approximate Gaussian quadrature. This method achieves accuracy without requiring the post-solution dense interpolation to be saved. ```APIDOC ## Function: IntegratingCallback ### Description Allows one to be able to solve such definite integrals in a way that is both memory and compute efficient. It uses the free local interpolation of a given step in order to approximate the Gaussian quadrature for a given step to the order of the numerical differential equation solve, thus achieving accuracy while not requiring the post-solution dense interpolation to be saved. ### Arguments * `integrand_func(out, u, t, integrator)` for in-place problems and `out = integrand_func(u, t, integrator)` for out-of-place problems. Returns the quantity in the integral for computing dG/dp. Note that for out-of-place problems, this should allocate the output (not as a view to `u`). * `integrand_values::IntegrandValues` is the types that `integrand_func` will return, i.e. `integrand_func(t, u, integrator)::integrandType`. It's specified via `IntegrandValues(integrandType)`, i.e. give the type that `integrand_func` will output (or higher compatible type). * `integrand_prototype` is a prototype of the output from the integrand. ### Note This method is currently limited to ODE solvers of order 10 or lower. Open an issue if other solvers are required. If `integrand_func` is in-place, you must use `cache` to store the output of `integrand_func`. ``` -------------------------------- ### Solve Ensemble Problem with Uncertainty Callback (σ=0.2) Source: https://docs.sciml.ai/DiffEqCallbacks/stable/uncertainty_quantification Runs an ensemble simulation of 100 trajectories using the Euler method with the defined uncertainty callback and a time step of 1/10. ```julia ensemble_prob = EnsembleProblem(prob) sim = solve(ensemble_prob, Euler(), trajectories = 100, callback = cb, dt = 1 / 10) ``` -------------------------------- ### IntegratingGKCallback Source: https://docs.sciml.ai/DiffEqCallbacks/stable/integrating Defines a callback for numerical integration using the Gauss-Kronrod quadrature rule. It allows for automatic error control and is suitable for ODE solvers up to order 10. The integrand function can be defined in-place or out-of-place. ```APIDOC ## Function: IntegratingGKCallback ### Description Callback for numerical integration using Gauss-Kronrod quadrature with automatic error control. Suitable for ODE solvers up to order 10. ### Signature ```julia IntegratingGKCallback(integrand_func, integrand_values::IntegrandValues, integrand_prototype) ``` ### Arguments * `integrand_func(out, u, t, integrator)`: For in-place problems. Computes the quantity in the integral for dG/dp. * `integrand_func(u, t, integrator)`: For out-of-place problems. Allocates and returns the output. * `integrand_values::IntegrandValues`: Specifies the type that `integrand_func` will return (e.g., `IntegrandValues(Float64)`). * `integrand_prototype`: A prototype of the output from the integrand. ### Notes - Uses Gauss-Kronrod quadrature for error control. - Limited to ODE solvers of order 10 or lower. - If `integrand_func` is in-place, use `cache` to store its output. ``` -------------------------------- ### PositiveDomain Callback Source: https://docs.sciml.ai/DiffEqCallbacks/stable/step_control Ensures that the solution remains in a positive domain. Steps are accepted if extrapolated values are within tolerance. ```julia PositiveDomain(u = nothing; save = true, abstol = nothing, scalefactor = nothing) ``` -------------------------------- ### Solve ODE with ManifoldProjection Callback Source: https://docs.sciml.ai/DiffEqCallbacks/stable/projection Solves the ODE problem using the Vern7 method and the ManifoldProjection callback. save_everystep is set to false to disable standard saving and rely on the callback for saving. ```julia sol = solve(prob, Vern7(), save_everystep = false, callback = cb) @show sol.u[end][1]^2 + sol.u[end][2]^2 ≈ 2 ``` -------------------------------- ### ProbIntsUncertainty Callback Source: https://docs.sciml.ai/DiffEqCallbacks/stable/uncertainty_quantification Use ProbIntsUncertainty for uncertainty quantification when a noise scaling factor is known or can be estimated. It transforms an ODE into an associated SDE. ```julia ProbIntsUncertainty(σ, order, save = true) ``` -------------------------------- ### Extended Time Simulation on Lorenz Attractor (Higher Order) Source: https://docs.sciml.ai/DiffEqCallbacks/stable/uncertainty_quantification Extends the simulation time to 40.0 and uses a higher-order method (Vern7()) with stricter tolerances (reltol=1e-6) and an order 7 AdaptiveProbIntsUncertainty callback to analyze uncertainty in the chaotic Lorenz system over a longer duration. ```julia tspan = (0.0, 40.0) prob = ODEProblem(g, u0, tspan, p) cb = AdaptiveProbIntsUncertainty(7) ensemble_prob = EnsembleProblem(prob) sim = solve(ensemble_prob, Vern7(), trajectories = 100, callback = cb, reltol = 1e-6) plot(sim, idxs = (0, 1), linealpha = 0.4) ``` -------------------------------- ### Define IntegratingGKCallback for Numerical Integration Source: https://docs.sciml.ai/DiffEqCallbacks/stable/integrating Shows the function signature for `IntegratingGKCallback`, used for numerical integration with adaptive error control. It requires an integrand function, its value type, and a prototype. ```julia IntegratingGKCallback(integrand_func, integrand_values::IntegrandValues, integrand_prototype) ``` -------------------------------- ### Solve Ensemble Problem with Reduced Time Step (σ=0.5, dt=1/100) Source: https://docs.sciml.ai/DiffEqCallbacks/stable/uncertainty_quantification Runs an ensemble simulation with the same high noise scaling (0.5) but a significantly reduced time step (1/100). This illustrates how decreasing the time step can contract uncertainty. ```julia cb = ProbIntsUncertainty(0.5, 1) ensemble_prob = EnsembleProblem(prob) sim = solve(ensemble_prob, Euler(), trajectories = 100, callback = cb, dt = 1 / 100) ``` -------------------------------- ### IntegratingGKSumCallback Source: https://docs.sciml.ai/DiffEqCallbacks/stable/integrating Defines a callback for numerical integration, similar to IntegratingGKCallback, but specifically named IntegratingGKSumCallback. It supports both in-place and out-of-place integrand functions and utilizes Gauss-Kronrod quadrature for error control. ```APIDOC ## Function: IntegratingGKSumCallback ### Description Callback for numerical integration using Gauss-Kronrod quadrature with automatic error control. Supports both in-place and out-of-place integrand functions. ### Signature ```julia IntegratingGKSumCallback(integrand_func, integrand_values::IntegrandValues, cache = nothing) ``` ### Arguments * `integrand_func(out, u, t, integrator)`: For in-place problems. Computes the quantity in the integral for dG/dp. * `integrand_func(u, t, integrator)`: For out-of-place problems. Allocates and returns the output. * `integrand_values::IntegrandValues`: Specifies the type that `integrand_func` will return (e.g., `IntegrandValues(Float64)`). * `cache`: Optional cache for storing the output of `integrand_func` if it's in-place. ### Notes - Uses Gauss-Kronrod quadrature rule for error control. - Limited to ODE solvers of order 10 or lower. - If `integrand_func` is in-place, the `cache` argument should be used. ``` -------------------------------- ### Define IntegratingGKSumCallback for Numerical Integration Source: https://docs.sciml.ai/DiffEqCallbacks/stable/integrating Illustrates the function signature for `IntegratingGKSumCallback`, which utilizes Gauss-Kronrod quadrature for numerical integration with error control. It accepts an integrand function, its value type, and an optional cache. ```julia IntegratingCallback(integrand_func, integrand_values::IntegrandValues, cache = nothing) ``` -------------------------------- ### IntegratingSumCallback Source: https://docs.sciml.ai/DiffEqCallbacks/stable/integrating Similar to `IntegratingCallback`, but instead of returning the timeseries of the interval results of the integration, it simply returns the final integral value. ```APIDOC ## Function: IntegratingSumCallback ### Description Lets one define a function `integrand_func(u, t, integrator)` which returns Integral(integrand_func(u(t),t)dt over the problem tspan. ### Arguments * `integrand_func(out, u, t, integrator)` for in-place problems and `out = integrand_func(u, t, integrator)` for out-of-place problems. Returns the quantity in the integral for computing dG/dp. Note that for out-of-place problems, this should allocate the output (not as a view to `u`). * `integrand_values::IntegrandValues` is the types that `integrand_func` will return, i.e. `integrand_func(t, u, integrator)::integrandType`. It's specified via `IntegrandValues(integrandType)`, i.e. give the type that `integrand_func` will output (or higher compatible type). * `integrand_prototype` is a prototype of the output from the integrand. ### Note This method is currently limited to ODE solvers of order 10 or lower. Open an issue if other solvers are required. ``` -------------------------------- ### Plot Monte Carlo Solution (σ=0.2) Source: https://docs.sciml.ai/DiffEqCallbacks/stable/uncertainty_quantification Visualizes the ensemble solution for the first state variable (index 1) with reduced line opacity to show the spread of trajectories. ```julia plot(sim, idxs = (0, 1), linealpha = 0.4) ``` -------------------------------- ### Use a Callback with a Solver Source: https://docs.sciml.ai/DiffEqCallbacks/stable Pass a pre-built callback object `cb` to the `solve` function using the `callback` keyword argument. ```julia sol = solve(prob, alg; callback = cb) ``` -------------------------------- ### Create ManifoldProjection Callback Source: https://docs.sciml.ai/DiffEqCallbacks/stable/projection Constructs the ManifoldProjection callback using the defined manifold function 'g'. It specifies autodifferentiation method and the prototype for the residual vector. ```julia cb = ManifoldProjection(g; autodiff = AutoForwardDiff(), resid_prototype = zeros(1)) ``` -------------------------------- ### ManifoldProjection Constructor Source: https://docs.sciml.ai/DiffEqCallbacks/stable/projection Defines the ManifoldProjection callback. It requires a manifold residual function and optionally accepts nonlinear solver configurations, saving options, and autodifferentiation settings. ```julia ManifoldProjection( manifold; nlsolve = missing, save = true, autonomous = nothing, manifold_jacobian = nothing, autodiff = nothing, kwargs...) ``` -------------------------------- ### StepsizeLimiter Callback Source: https://docs.sciml.ai/DiffEqCallbacks/stable/step_control Limits the step size based on a provided function that calculates the maximum stable timestep. Useful for hyperbolic PDEs where the CFL condition dictates step size. ```julia StepsizeLimiter(dtFE;safety_factor=9//10,max_step=false,cached_dtcache=0.0) ``` -------------------------------- ### ManifoldProjection Callback Object Source: https://docs.sciml.ai/DiffEqCallbacks/stable/projection This is the internal representation of the created ManifoldProjection callback object, showing its configuration including the manifold function, autodiff settings, and other internal parameters. ```text SciMLBase.DiscreteCallback{Returns{Bool}, ManifoldProjection{DiffEqCallbacks.UntypedNonAutonomousFunction{typeof(Main.g)}, Nothing, ADTypes.AutoForwardDiff{nothing, Nothing}, Missing, Base.Pairs{Symbol, Vector{Float64}, Nothing, @NamedTuple{resid_prototype::Vector{Float64}}}, Nothing}, typeof(DiffEqCallbacks.initialize_manifold_projection), typeof(SciMLBase.FINALIZE_DEFAULT), Nothing, Tuple{}}(Returns{Bool}(true), ManifoldProjection{DiffEqCallbacks.UntypedNonAutonomousFunction{typeof(Main.g)}, Nothing, ADTypes.AutoForwardDiff{nothing, Nothing}, Missing, Base.Pairs{Symbol, Vector{Float64}, Nothing, @NamedTuple{resid_prototype::Vector{Float64}}}, Nothing}(DiffEqCallbacks.UntypedNonAutonomousFunction{typeof(Main.g)}(false, Main.g, nothing), nothing, ADTypes.AutoForwardDiff(), nothing, missing, Base.Pairs(:resid_prototype => [0.0]), nothing), DiffEqCallbacks.initialize_manifold_projection, SciMLBase.FINALIZE_DEFAULT, Bool[0, 1], nothing, (), true) ``` -------------------------------- ### Define ODE Problem for Harmonic Oscillator Source: https://docs.sciml.ai/DiffEqCallbacks/stable/projection Sets up the ODE problem for a harmonic oscillator, including the initial conditions and the differential equation function. ```julia using OrdinaryDiffEq, DiffEqCallbacks, NonlinearSolve, Plots, ADTypes u0 = ones(2) function f(du, u, p, t) du[1] = u[2] du[2] = -u[1] end prob = ODEProblem(f, u0, (0.0, 100.0)) ``` -------------------------------- ### TerminateSteadyState Callback Function Signature Source: https://docs.sciml.ai/DiffEqCallbacks/stable/steady_state Defines the signature for the `TerminateSteadyState` callback, used to automatically stop integration when a steady state is detected. It accepts absolute and relative tolerances, a custom test function, and an optional minimum time. ```julia TerminateSteadyState(abstol = 1e-8, reltol = 1e-6, test = allDerivPass; min_t = nothing, wrap_test::Val = Val(true)) ``` -------------------------------- ### Integrand Function Signature for IntegratingCallback Source: https://docs.sciml.ai/DiffEqCallbacks/stable/integrating The integrand_func should return the quantity to be integrated. It can be defined in-place or out-of-place. For out-of-place functions, ensure the output is allocated. ```julia integrand_func(out, u, t, integrator) ``` ```julia out = integrand_func(u, t, integrator) ``` -------------------------------- ### ODEProblem Definition Output Source: https://docs.sciml.ai/DiffEqCallbacks/stable/projection This output shows the details of the defined ODEProblem, including the type of u and t, whether it's in-place, mass matrix presence, timespan, and initial conditions. ```text ODEProblem with uType Vector{Float64} and tType Float64. In-place: true Non-trivial mass matrix: false timespan: (0.0, 100.0) u0: 2-element Vector{Float64}: 1.0 1.0 ``` -------------------------------- ### TerminateSteadyState Source: https://docs.sciml.ai/DiffEqCallbacks/stable/steady_state `TerminateSteadyState` is a callback function used to automatically stop the integration process when a steady state is detected. It's an alternative to root-finding methods for finding steady-state solutions. ```APIDOC ## Function `TerminateSteadyState` ### Description This function is designed to automatically terminate integration when a steady state is reached. It allows for solving the problem for the steady-state by running the solver until the derivatives of the problem converge to 0 or `tspan[2]` is reached. ### Arguments * `abstol` (Float64 or Array{Float64}) - Absolute tolerance for convergence. Can be a scalar or an array matching the problem states. * `reltol` (Float64 or Array{Float64}) - Relative tolerance for convergence. Can be a scalar or an array matching the problem states. * `test` (Function) - A function that evaluates the condition for termination. The default checks if all derivatives are smaller than `abstol` or states times `reltol`. It can be customized to implement different termination conditions. The function signature depends on `wrap_test`. ### Keyword Arguments * `min_t` (Union{Nothing, Float64}) - Optional minimum time `t` before steady state calculations are allowed to terminate. * `wrap_test` (Val{true} or Val{false}) - Determines the signature of the `test` function. If `Val(true)` (default), `test` must accept `(integrator, abstol, reltol, min_t)`. If `Val(false)`, `test` must accept `(u, t, integrator)`. ``` -------------------------------- ### SavingCallback Constructor Source: https://docs.sciml.ai/DiffEqCallbacks/stable/output_saving Defines a callback to save quantities of interest during integration. Specify a save function, a SavedValues cache, and optional saving controls like saveat. ```julia SavingCallback(save_func, saved_values::SavedValues; saveat = Vector{eltype(saved_values.t)}(), save_everystep = isempty(saveat), save_start = true, tdir = 1) ``` -------------------------------- ### Define an IntegratingSumCallback Source: https://docs.sciml.ai/DiffEqCallbacks/stable/integrating IntegratingSumCallback is similar to IntegratingCallback but returns only the final integral value, not the timeseries of interval results. It can accept an optional cache. ```julia IntegratingCallback(integrand_func, integrand_values::IntegrandValues, cache = nothing) ``` -------------------------------- ### PeriodicCallback Source: https://docs.sciml.ai/DiffEqCallbacks/stable/timed_callbacks A callback that executes a function periodically based on integration time. It's useful for modeling discrete-time controllers or other periodic events within a continuous simulation. ```APIDOC ## PeriodicCallback ### Description `PeriodicCallback` can be used when a function should be called periodically in terms of integration time (as opposed to wall time), i.e. at `t = tspan[1]`, `t = tspan[1] + Δt`, `t = tspan[1] + 2Δt`, and so on. If a non-zero `phase` is provided, the invocations of the callback will be shifted by `phase` time units, i.e., the calls will occur at `t = tspan[1] + phase`, `t = tspan[1] + phase + Δt`, `t = tspan[1] + phase + 2Δt`, and so on. This callback can, for example, be used to model a discrete-time controller for a continuous-time system, running at a fixed rate. ### Function Signature ```julia PeriodicCallback(f, Δt::Number; phase = 0, initial_affect = false, final_affect = false, kwargs...) ``` ### Arguments * `f` the `affect!(integrator)` function to be called periodically * `Δt` is the period ### Keyword Arguments * `phase` is a phase offset * `initial_affect` is whether to apply the affect at the initial time, which defaults to `false` * `final_affect` is whether to apply the affect at the final time, which defaults to `false` * `kwargs` are keyword arguments accepted by the `DiscreteCallback` constructor. ``` -------------------------------- ### PresetTimeCallback Source: https://docs.sciml.ai/DiffEqCallbacks/stable/timed_callbacks A callback that triggers `affect!` functions at predefined time points. It simplifies the process of scheduling callbacks at specific times without manual management of `tstops`. ```APIDOC ## PresetTimeCallback ### Description A callback that adds callback `affect!` calls at preset times. No playing around with `tstops` or anything is required: this callback adds the triggers for you to make it automatic. ### Function Signature ```julia PresetTimeCallback(tstops, user_affect!; initialize = DiffEqBase.INITIALIZE_DEFAULT, filter_tstops = true, kwargs...) ``` ### Arguments * `tstops` : the times for the `affect!` to trigger at. * `user_affect!`: an `affect!(integrator)` function to use at the time points. ### Keyword Arguments * `filter_tstops` : Whether to filter out tstops beyond the end of the integration timespan. Defaults to true. If false, then tstops can extend the interval of integration. ``` -------------------------------- ### PresetTimeCallback for Fixed Trigger Times Source: https://docs.sciml.ai/DiffEqCallbacks/stable/timed_callbacks Use PresetTimeCallback to trigger an affect! function at a predefined list of time points. It automatically manages the trigger times based on the provided tstops. ```julia PresetTimeCallback(tstops, user_affect!; initialize = DiffEqBase.INITIALIZE_DEFAULT, filter_tstops = true, kwargs...) ``` -------------------------------- ### Plot Solution Trajectory Source: https://docs.sciml.ai/DiffEqCallbacks/stable/projection Generates a plot of the solution trajectory in the phase space (u[1] vs u[2]) using the Plots.jl package. ```julia using Plots plot(sol, idxs = (1, 2)) ```