-
Notifications
You must be signed in to change notification settings - Fork 6
Sandu projection #162
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Sandu projection #162
Changes from all commits
Commits
Show all changes
52 commits
Select commit
Hold shift + click to select a range
26ddd92
new feature Sandu projection
SKopecz ffb5bc5
format
SKopecz 25a8127
created extension
SKopecz 2cddeee
set_string_names_on_creation false
SKopecz 67ab04a
Merge branch 'main' into sk/sandu_projection
SKopecz 9178c67
Merge branch 'main' into sk/sandu_projection
SKopecz 57ec6a4
test
jmbender f066808
Merge branch 'sk/sandu_projection' of github.com:SKopecz/PositiveInte…
SKopecz 86934e6
temporary output
SKopecz 7fafa9d
Initialize counter with 0
SKopecz 5fca39b
scaled ode, docstrings, tests
SKopecz 0244297
bugfix
SKopecz 3f6e3ee
use clarabel in tests
SKopecz 10e1a7d
use JuMP in tests
SKopecz 7ad138f
Merge branch 'main' into sk/sandu_projection
SKopecz 40b098a
bugfix
SKopecz 0481029
Merge branch 'sk/sandu_projection' of github.com:SKopecz/PositiveInte…
SKopecz e6cbc09
fixed stale imports
SKopecz 201640b
SanduProjection API
SKopecz 6126dda
docu sandu
jmbender 6602592
Merge branch 'sk/sandu_projection' of https://github.com/SKopecz//Pos…
jmbender d733b77
fix SanduProjection docstring issue
SKopecz 52b6fbe
additional test
SKopecz e44f04d
fix sandu projection tutorial
SKopecz 6fb5c14
format
SKopecz 538a79f
additional comments
SKopecz b93f47e
bugfix
SKopecz 3d603b1
improved docs
SKopecz 493f156
revised tutorial
SKopecz 4d7ce23
additional tests
SKopecz 98cc34d
deleted unnecessary comments and more tests
SKopecz 24e78c7
made f_startreac_scaled type stable
SKopecz 459ca11
revised tutorail
SKopecz 105a766
slightly better efficiency
SKopecz 3366227
bugfix tutorial
SKopecz 39e9dc1
new function get_numsteps_SanduProjection
SKopecz 4cc4ec9
fix docs
SKopecz 22d0cf8
minor changes
SKopecz bb080b5
fix cross-ref docu bug
SKopecz 56d9670
Apply suggestions from code review
SKopecz 68bde9b
Apply more suggestions from code review
SKopecz 4e2ff8e
requested changes and bugfixes
SKopecz a7aeb60
format
SKopecz 3eb7e27
Aktualisieren von sandu_projection.md
SKopecz fbbebc8
additional test for get_numsteps_SanduProjection
SKopecz 9863060
Merge branch 'main' into sk/sandu_projection
SKopecz 51f2fb4
Try JuMP 1.28
SKopecz 2153a1a
Merge branch 'main' into sk/sandu_projection
ranocha 0550f80
Apply suggestions from code review
SKopecz e987dc2
define G-norm in docstring
SKopecz 87aadab
Apply suggestion from @JoshuaLampert
SKopecz d969e05
Apply suggestion from @JoshuaLampert
SKopecz File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,78 @@ | ||
| # [Tutorial: Positive-projection method](@id tutorial-sandu) | ||
|
|
||
| This tutorial is about solving an ODE using the projection method introduced by Adrian Sandu in [Positive Numerical Integration Methods for Chemical Kinetic Systems](https://doi.org/10.1006%2Fjcph.2001.6750). It guarantees positivity by solving an optimization problem while preserving all linear invariants. | ||
|
|
||
| The Sandu projection is a post-processing technique that can be used in combination with any ODE solver. | ||
| If the ODE solver computes a negative approximation at any time step, the projection method calculates a positive approximation, also taking into account the linear invariants. | ||
|
|
||
| ## Solution of the ODE system | ||
|
|
||
| As an example we want to the solve the NPZD problem [`prob_pds_npzd`](@ref), which is an ODE system in which negative approximations quickly lead to unacceptable solutions. First, we solve the problem without Sandu projection and select `ROS2` form [`OrdinaryDiffEq.jl`](https://docs.sciml.ai/OrdinaryDiffEq/stable/) as ODE solver. | ||
|
|
||
| ```@example Sandu_NPZD | ||
| using PositiveIntegrators | ||
| using OrdinaryDiffEqRosenbrock | ||
| using Plots | ||
|
|
||
| prob = prob_pds_npzd | ||
|
|
||
| ref_sol = solve(prob, ROS2(); abstol = 1e-8, reltol = 1e-6); # reference solution for plotting | ||
|
|
||
| sol = solve(prob, ROS2(); abstol = 5e-2, reltol = 1e-1) | ||
|
|
||
| plot(ref_sol, linestyle = :dash, label = "", color = palette(:default)[1:4]') | ||
| plot!(sol, ylims = (-2.5, 12.5), denseplot = false, markers = :circle, linewidth = 2, color = palette(:default)[1:4]', label = ["N" "P" "Z" "D"], legend = :right) | ||
| ``` | ||
|
|
||
| The plot shows the numerical solution obtained with `ROS2` compared to a reference solution (dashed lines). | ||
| We see that the `ROS2` method produces negative approximations, which can occur because Rosenbrock methods are not positivity-preserving. For the NPZD problem, however, this is fatal and leads to a completely unacceptable numerical solution. It is therefore particularly important to use techniques that guarantee positivity of the numerical approximations for this problem. We achieve this below with the [`SanduProjection`](@ref). | ||
|
|
||
| To apply the [`SanduProjection`](@ref) we need to choose an [optimization solver](https://jump.dev/JuMP.jl/stable/installation/#Supported-solvers) which is supported by [JuMP.jl](https://jump.dev/JuMP.jl/stable/) and can handle quadratic optimization problems (QP). In this tutorial we select [Clarabel.jl](https://clarabel.org/stable/) as optimization solver. | ||
|
|
||
| In addition, we need to specify the linear invariants of the problem. | ||
| The only linear invariant of the NPZD problem is ``N(t)+P(t)+Z(t)+D(t)=N(0)+P(0)+Z(0)+D(0)=15`` for all times ``t≥0``. | ||
| This can be written in the form | ||
| ```math | ||
| \mathbf{A}^T \begin{pmatrix} N(t)\\ P(t)\\ Z(t)\\ D(t) \end{pmatrix} = \mathbf{b} | ||
| ``` | ||
| with ``\mathbf{A}^T = [1.0,\ 1.0,\ 1.0,\ 1.0]`` and ``\mathbf{b} = [15]``. | ||
|
|
||
| The projection method [`SanduProjection`](@ref) is implemented as a callback and hence, must be passed as an argument to the keyword `callback`. In addition, we must also use `save_everystep = false`. | ||
|
|
||
| ```@example Sandu_NPZD | ||
| using JuMP, Clarabel | ||
|
|
||
| AT = [1.0 1.0 1.0 1.0] | ||
| b = [15.0] | ||
| proj = SanduProjection(Model(Clarabel.Optimizer), AT, b) | ||
|
|
||
| sol_proj = solve(prob, ROS2(); abstol = 5e-2, reltol = 1e-1, | ||
| save_everystep = false, callback = proj); | ||
|
|
||
| plot(ref_sol, linestyle = :dash, label = "", color = palette(:default)[1:4]') | ||
| plot!(sol_proj, ylims = (-2.5, 12.5), denseplot = false, markers = :circle, linewidth = 2, color = palette(:default)[1:4]', label = ["N" "P" "Z" "D"], legend = :right) | ||
| ``` | ||
|
|
||
| As intended, negative approximations no longer occur and we obtain an acceptable approximation. | ||
|
|
||
| The [`SanduProjection`](@ref) is implemented as a [`DiscreteCallback`](https://docs.sciml.ai/DiffEqDocs/stable/features/callback_functions/#SciMLBase.DiscreteCallback) and we can display the number of projection steps in the following way. | ||
|
|
||
| ```@example Sandu_NPZD | ||
| @show get_numsteps_SanduProjection(proj) | ||
| ``` | ||
|
|
||
| We can see that in this example, a single projection step was already sufficient. | ||
|
|
||
| ## Package versions | ||
|
|
||
| These results were obtained using the following versions. | ||
| ```@example NPZD | ||
| using InteractiveUtils | ||
| versioninfo() | ||
| println() | ||
|
|
||
| using Pkg | ||
| Pkg.status(["PositiveIntegrators", "JuMP", "Clarabel", "OrdinaryDiffEqRosenbrock", "Plots"], | ||
| mode=PKGMODE_MANIFEST) | ||
| nothing # hide | ||
| ``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,142 @@ | ||
| module JuMPExt | ||
|
|
||
| using StaticArrays: StaticArray, SVector | ||
| using JuMP: @variable, @objective, @constraint, print, set_silent, | ||
| optimize!, is_solved_and_feasible, value, set_string_names_on_creation, | ||
| set_objective_coefficient, @expression | ||
| using SciMLBase: DiscreteCallback | ||
| using PositiveIntegrators | ||
|
|
||
| mutable struct SanduProjection{M} <: PositiveIntegrators.SanduProjection | ||
| model::M | ||
| cnt::Int | ||
| end | ||
|
|
||
| """ | ||
| SanduProjection(model, AT, b, eps = nothing; [save = true, verbose = false]) | ||
|
|
||
| A projection method which ensures conservation of prescribed linear invariants and positivity. | ||
| If the current approximation ``\\mathbf{u}`` has negative components then a projection ``\\mathbf{z}`` is computed such that | ||
| ```math | ||
| \\min \\lVert \\mathbf{z} - \\mathbf{u} \\rVert_{\\mathbf{G}},\\quad \\mathbf{A}^T\\mathbf{z}=\\mathbf{b},\\quad \\mathbf{z}≥ \\mathbf{0}, | ||
| ``` | ||
| is satisfied, where the matrix ``\\mathbf{A^T}`` and the vector ``\\mathbf{b}`` define the linear invariants. | ||
| The ``G``-norm is defined by ``\\lVert \\mathbf{u}\\rVert_{\\mathbf{G}} = \\sqrt{\\mathbf{u}^T\\mathbf{G}\\mathbf{u}}``, | ||
| and assuming ``\\mathbf{u} = (u_1,\\dots, u_s)^T``, | ||
| the positive definite diagonal matrix ``\\mathbf{G}`` is given by | ||
| ```math | ||
| \\mathbf{G(\\mathbf{u})}=\\operatorname{diag}\\biggl(\\frac{1}{s(\\mathtt{abstol}+\\mathtt{reltol}\\lvert u_i \\rvert^2)}\\biggr), | ||
| ``` | ||
| where `abstol` and `reltol` denote the absolute and relative tolerances of the adaptive step size control, respectively. | ||
| See Sandu (2001) for details. | ||
|
|
||
| To use this callback one must also specify `save_everystep = false`. | ||
|
|
||
| ## Arguments | ||
|
|
||
| - `model`: A [`JuMP Model`](https://jump.dev/JuMP.jl/stable/api/JuMP/#JuMP.Model) to solve the minimization problem. | ||
| - `AT`: The matrix ``\\mathbf{A}^T`` defining the linear invariants. | ||
| - `b`: The vector ``\\mathbf{b}`` defining the linear invariants. | ||
| - `eps`: It may be helpful for the optimization solver that feasible solutions are bounded away from 0. To achieve this one can specify the optional parameter `eps`. The positivity constraint is then replaced by ``\\mathbf{z}≥```eps`, where `eps` can either be a scalar or a vector. | ||
|
|
||
| ## Keyword Arguments | ||
|
|
||
| - `save`: If the keyword argument `save` is set to `false` only the initial value and the last approximation will be saved. | ||
| The default value is `true`. | ||
| - `verbose`: Enables additional output of the optimization solver. The default value is `false`. | ||
|
|
||
| ## References | ||
|
|
||
| - Adrian Sandu. | ||
| "Positive numerical integration methods for chemical kinetic systems." | ||
| Journal of Computational Physics 170 (2001): 589-602. | ||
| [DOI: 10.1006/jcph.2001.6750](https://doi.org/10.1006/jcph.2001.6750) | ||
| """ | ||
| function PositiveIntegrators.SanduProjection(args...; kwargs...) | ||
| SanduProjection(args...; kwargs...) | ||
| end | ||
|
|
||
| function SanduProjection(model, AT, b, eps = nothing; save = true, verbose = false) | ||
| if isnothing(eps) || eps isa Number | ||
| epsv = zeros(eltype(AT), size(AT, 2)) | ||
| if eps isa Number | ||
| fill!(epsv, eps) | ||
| end | ||
| else | ||
| epsv = eps | ||
| end | ||
|
|
||
| # Set up optimization problem | ||
| s = size(AT, 2) | ||
| if !verbose | ||
| set_silent(model) | ||
| end | ||
| set_string_names_on_creation(model, false) | ||
|
|
||
| @variable(model, z[i = 1:s]>=epsv[i]) | ||
| @constraint(model, AT * z.==b) | ||
| # This just initializes the objective. The correct coefficients will be set later | ||
| @expression(model, obj_exp, sum(z .^ 2)+sum(z)) | ||
| @objective(model, Min, obj_exp) | ||
|
|
||
| if verbose | ||
| print(model) | ||
| end | ||
|
|
||
| affect! = SanduProjection(model, 0) | ||
|
|
||
| return DiscreteCallback(Returns(true), affect!; save_positions = (false, save), | ||
| initialize = initialize_sandu_projection!) | ||
| end | ||
|
|
||
| function initialize_sandu_projection!(c, u, t, integrator) | ||
| return initialize_sandu_projection!(c.affect!) | ||
| end | ||
|
|
||
| function initialize_sandu_projection!(proj::SanduProjection) | ||
| proj.cnt = 0 | ||
| end | ||
|
|
||
| function (proj::SanduProjection)(integrator) | ||
| u = integrator.u | ||
|
|
||
| if isnegative(u) | ||
| proj.cnt += 1 | ||
|
|
||
| rtol = integrator.opts.reltol | ||
| atol = integrator.opts.abstol | ||
| model = proj.model | ||
|
|
||
| s = length(u) | ||
| g = @. 1 / (s * (atol + rtol * abs(u))^2) | ||
|
|
||
| # set coefficients of quadratic terms | ||
| set_objective_coefficient(model, model[:z], model[:z], Vector(1 / 2 .* g)) | ||
| # set coefficients of linear terms | ||
| set_objective_coefficient(model, model[:z], Vector(-g .* u)) | ||
|
|
||
| # solve optimization problem | ||
| optimize!(model) | ||
| if !is_solved_and_feasible(model) | ||
| error("Solver did not find an optimal solution") | ||
| end | ||
|
|
||
| if integrator.u isa StaticArray | ||
| integrator.u = SVector{length(integrator.u)}(value.(model[:z])) | ||
| else | ||
| integrator.u = value.(model[:z]) | ||
| end | ||
| end | ||
| return nothing | ||
| end | ||
|
|
||
| """ | ||
| get_numsteps_SanduProjection(proj) | ||
|
|
||
| For a `SanduProjection` `proj`, this function returns the number of the performed projection steps. | ||
| """ | ||
| function PositiveIntegrators.get_numsteps_SanduProjection(proj) | ||
| return proj.affect!.cnt | ||
SKopecz marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| end | ||
|
|
||
| end | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.