From 1aa8e20c9d00810fb96b0a7027ec3df800e11532 Mon Sep 17 00:00:00 2001 From: Olivier Cots Date: Wed, 11 Nov 2026 17:56:40 +0100 Subject: [PATCH 1/7] feat(models): beam in the ModelingToolkit modeling (#308) A bounded state (two path constraints), boundary conditions, a Lagrange cost. Passes the continuous comparison with OptimalControl and the smoke solve. Co-Authored-By: Claude Sonnet 5.5 --- ext/MetaData/beam.jl | 2 +- ext/ModelingToolkitModels/beam.jl | 51 +++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-) create mode 100644 ext/ModelingToolkitModels/beam.jl diff --git a/ext/MetaData/beam.jl b/ext/MetaData/beam.jl index 94f63d6d5..801e97959 100644 --- a/ext/MetaData/beam.jl +++ b/ext/MetaData/beam.jl @@ -1,7 +1,7 @@ beam_meta = OrderedDict( :grid_size => 500, :parameters => (t0=0, tf=1, x₁_l=0, x₁_u=0.1, x₁_t0=0, x₂_t0=1, x₁_tf=0, x₂_tf=-1), - :status => (OptimalControl=:valid, OptimalControlScalarized=:valid, JuMP=:valid), + :status => (OptimalControl=:valid, OptimalControlScalarized=:valid, JuMP=:valid, ModelingToolkit=:valid), # initial guess of every modeling (#377), from the parameters :init => p -> (state=[0.05, 0.1], control=0.1), :reference_solution => diff --git a/ext/ModelingToolkitModels/beam.jl b/ext/ModelingToolkitModels/beam.jl new file mode 100644 index 000000000..4ec234984 --- /dev/null +++ b/ext/ModelingToolkitModels/beam.jl @@ -0,0 +1,51 @@ +"""The **clamped beam problem** is a classical benchmark in constrained optimal control. + +Builds the `beam` problem with the ModelingToolkit backend. + +```julia-repl +julia> using ModelingToolkit, OptimalControlProblems +julia> pb = beam(ModelingToolkitBackend()) +``` + +Default parameters and the modeling status are available through +`problem_metadata(:beam)` and `OptimalControlProblems.status(:beam)`. +""" +function OptimalControlProblems.beam( + ::ModelingToolkitBackend; + parameters::Union{Nothing,NamedTuple}=nothing, + init=nothing, +) + OptimalControlProblems.Catalogue._warn_if_draft(:beam, :ModelingToolkit) + params = OptimalControlProblems.parameters_data(:beam, parameters) + t0, tf = float(params[:t0]), float(params[:tf]) + x₁_l, x₁_u = float(params[:x₁_l]), float(params[:x₁_u]) + x₁_t0, x₂_t0 = float(params[:x₁_t0]), float(params[:x₂_t0]) + x₁_tf, x₂_tf = float(params[:x₁_tf]), float(params[:x₂_tf]) + + t = ModelingToolkit.t_nounits + D = ModelingToolkit.Differential(t) + + ModelingToolkit.@variables x₁(..) = x₁_t0 [tunable = false] + ModelingToolkit.@variables x₂(..) = x₂_t0 [tunable = false] + ModelingToolkit.@variables u(..) [input = true] + + eqs = [D(x₁(t)) ~ x₂(t), D(x₂(t)) ~ u(t)] + costs = [ModelingToolkit.Symbolics.Integral(t in (t0, tf))(u(t)^2)] + constraints = [ + x₁(tf) ~ x₁_tf, + x₂(tf) ~ x₂_tf, + ModelingToolkit.Symbolics.:≳(x₁(t), x₁_l), + ModelingToolkit.Symbolics.:≲(x₁(t), x₁_u), + ] + + ModelingToolkit.@named sys = ModelingToolkit.System( + eqs, t; costs=costs, constraints=constraints + ) + + # initial guess: from the metadata (#377), unless given + init = OptimalControlProblems.Metadata._initial_guess(:beam, params, init) + + return OptimalControlProblems.Problems._problem( + :beam, :ModelingToolkit, sys, init, params + ) +end From bb1b2a92ae916b06f464f1be8e3e3603f3f3e77e Mon Sep 17 00:00:00 2001 From: Olivier Cots Date: Wed, 11 Nov 2026 18:05:33 +0100 Subject: [PATCH 2/7] test(mtk): states of free initial value start from the guess, components compared in order (#308) A state with tunable = true has a free initial value in Corleone: prepare starts it from the state guess of the problem, as it does for the controls. The initial guess is indexed in the order of the components of the OptimalControl model, so the equivalence test now compares the components in order, not as sets. Co-Authored-By: Claude Sonnet 5.5 --- test/common/solve_modelingtoolkit.jl | 31 ++++++++++++++++---- test/suite/ModelingToolkit/test_methods.jl | 4 +++ test/suite/ModelingToolkit/test_modelings.jl | 5 ++-- 3 files changed, 32 insertions(+), 8 deletions(-) diff --git a/test/common/solve_modelingtoolkit.jl b/test/common/solve_modelingtoolkit.jl index 04fb929e5..7ac778f63 100644 --- a/test/common/solve_modelingtoolkit.jl +++ b/test/common/solve_modelingtoolkit.jl @@ -114,18 +114,30 @@ The start value of each of the `m` controls, from the initial guess `init` of th guess. Corleone starts every interval of a control from one value. """ function control_start(init, t0, m::Int) - g = haskey(init, :control) ? init.control : 0.0 + return _start(init, :control, t0, m) +end + +""" +The start value of each of the `n` states, from the initial guess `init` of the problem, as +`control_start`; used for the states whose initial value is free, `0.0` without a state guess. +""" +function state_start(init, t0, n::Int) + return _start(init, :state, t0, n) +end + +function _start(init, key::Symbol, t0, n::Int) + g = haskey(init, key) ? init[key] : 0.0 g isa Function && (g = g(t0)) - v = g isa Number ? fill(Float64(g), m) : Float64.(vec(collect(g))) - length(v) == m || - throw(DimensionMismatch("control guess of length $(length(v)), $m controls")) + v = g isa Number ? fill(Float64(g), n) : Float64.(vec(collect(g))) + length(v) == n || throw(DimensionMismatch("$key guess of length $(length(v)), $n $(key)s")) return v end """ Prepare the solve of the ModelingToolkit problem `pb` with Corleone, built once: the path constraints imposed at the `grid_size` nodes of the grid, the controls piecewise constant -between them and started from the initial guess of the problem. Returns the +between them and started from the initial guess of the problem, as the states whose initial +value is free (`tunable = true`). Returns the `Optimization.OptimizationProblem` (`problem`) and the `Corleone.CorleoneDynamicOptProblem` it was built from (`dynamic`), from which the trajectory of a solution is recovered. """ @@ -145,8 +157,15 @@ function prepare( # Controls: started from the initial guess, switching at the nodes of the grid ctrl_syms = filter(MTK.isinput, MTK.unknowns(sys)) - start = control_start(OCP.initial_guess(pb), t0, length(ctrl_syms)) + init = OCP.initial_guess(pb) + start = control_start(init, t0, length(ctrl_syms)) inits = [u => start[i] for (i, u) in enumerate(ctrl_syms)] + + # States whose initial value is free: started from the initial guess. The order of the + # states is the one of `state_components`, that of the OptimalControl model. + states = filter(!MTK.isinput, MTK.unknowns(sys)) + start_x = state_start(init, t0, length(states)) + append!(inits, [x => start_x[i] for (i, x) in enumerate(states) if MTK.istunable(x, false)]) switches = [u => collect(grid[1:(end - 1)]) for u in ctrl_syms] dynamic = Corleone.CorleoneDynamicOptProblem( diff --git a/test/suite/ModelingToolkit/test_methods.jl b/test/suite/ModelingToolkit/test_methods.jl index 1f9b04b61..7979d9d7e 100644 --- a/test/suite/ModelingToolkit/test_methods.jl +++ b/test/suite/ModelingToolkit/test_methods.jl @@ -57,6 +57,10 @@ function test_methods() Test.@test S.control_start((control=t -> 3t,), 1.0, 1) == [3.0] Test.@test S.control_start((state=[0.0, 0.0],), 0.0, 1) == [0.0] Test.@test_throws DimensionMismatch S.control_start((control=[1, 2],), 0.0, 1) + # the states of free initial value start from the state guess, in the same way + Test.@test S.state_start((state=[0.1, 0.2],), 0.0, 2) == [0.1, 0.2] + Test.@test S.state_start((state=t -> [t, 2t],), 0.5, 2) == [0.5, 1.0] + Test.@test S.state_start((control=0.5,), 0.0, 2) == [0.0, 0.0] # and it is the value the controls of the problem solved start from other = OCP.bryson_denham(backend; init=(state=[0.0, 0.0], control=0.7)) started = S.prepare(other; grid_size=6).dynamic diff --git a/test/suite/ModelingToolkit/test_modelings.jl b/test/suite/ModelingToolkit/test_modelings.jl index ef24832b2..388fb618d 100644 --- a/test/suite/ModelingToolkit/test_modelings.jl +++ b/test/suite/ModelingToolkit/test_modelings.jl @@ -33,9 +33,10 @@ function test_modelings() pb_mtk, pb = build(mtk), build(other) sys, ocp = OCP.model(pb_mtk), OCP.model(pb) xs, us = OCP.state_components(ocp), OCP.control_components(ocp) + # the same components in the same order: the initial guess is indexed by it Test.@testset "components" begin - Test.@test sort(OCP.state_components(sys)) == sort(xs) - Test.@test sort(OCP.control_components(sys)) == sort(us) + Test.@test OCP.state_components(sys) == xs + Test.@test OCP.control_components(sys) == us end tspan = Main.SolveModelingToolkit.tspan(pb_mtk) data = Main.ContinuousModelingToolkit.problem_data(sys, xs, us, tspan) From 202108657339b3be921a14f2fdbb12c7375ffa93 Mon Sep 17 00:00:00 2001 From: Olivier Cots Date: Wed, 11 Nov 2026 18:05:33 +0100 Subject: [PATCH 3/7] feat(models): double_oscillator in the ModelingToolkit modeling (#308) Four states with the last two free at the initial time, a force that depends on the time, a bounded control. Passes the continuous comparison with OptimalControl and the smoke solve. Co-Authored-By: Claude Sonnet 5.5 --- ext/MetaData/double_oscillator.jl | 2 +- .../double_oscillator.jl | 60 +++++++++++++++++++ 2 files changed, 61 insertions(+), 1 deletion(-) create mode 100644 ext/ModelingToolkitModels/double_oscillator.jl diff --git a/ext/MetaData/double_oscillator.jl b/ext/MetaData/double_oscillator.jl index 8a396c45d..b9ca27586 100644 --- a/ext/MetaData/double_oscillator.jl +++ b/ext/MetaData/double_oscillator.jl @@ -13,7 +13,7 @@ double_oscillator_meta = OrderedDict( x₁_t0=0, x₂_t0=0, ), - :status => (OptimalControl=:valid, OptimalControlScalarized=:valid, JuMP=:valid), + :status => (OptimalControl=:valid, OptimalControlScalarized=:valid, JuMP=:valid, ModelingToolkit=:valid), # initial guess of every modeling (#377), from the parameters :init => p -> (state=[0.1, 0.1, 0.1, 0.1], control=0.1), ) diff --git a/ext/ModelingToolkitModels/double_oscillator.jl b/ext/ModelingToolkitModels/double_oscillator.jl new file mode 100644 index 000000000..0fc4a0de6 --- /dev/null +++ b/ext/ModelingToolkitModels/double_oscillator.jl @@ -0,0 +1,60 @@ +"""The **clamped double_oscillator problem** is a classical benchmark in constrained optimal control. + +Builds the `double_oscillator` problem with the ModelingToolkit backend. + +```julia-repl +julia> using ModelingToolkit, OptimalControlProblems +julia> pb = double_oscillator(ModelingToolkitBackend()) +``` + +Default parameters and the modeling status are available through +`problem_metadata(:double_oscillator)` and `OptimalControlProblems.status(:double_oscillator)`. +""" +function OptimalControlProblems.double_oscillator( + ::ModelingToolkitBackend; + parameters::Union{Nothing,NamedTuple}=nothing, + init=nothing, +) + OptimalControlProblems.Catalogue._warn_if_draft(:double_oscillator, :ModelingToolkit) + params = OptimalControlProblems.parameters_data(:double_oscillator, parameters) + t0, tf = float(params[:t0]), float(params[:tf]) + m1, m2, c, k1, k2 = params[:m1], params[:m2], params[:c], params[:k1], params[:k2] + u_l, u_u = float(params[:u_l]), float(params[:u_u]) + x₁_t0, x₂_t0 = float(params[:x₁_t0]), float(params[:x₂_t0]) + + t = ModelingToolkit.t_nounits + D = ModelingToolkit.Differential(t) + + # x₃ and x₄ have a free initial value: no default, started from the initial guess + ModelingToolkit.@variables x₁(..) = x₁_t0 [tunable = false] + ModelingToolkit.@variables x₂(..) = x₂_t0 [tunable = false] + ModelingToolkit.@variables x₃(..) [tunable = true] + ModelingToolkit.@variables x₄(..) [tunable = true] + ModelingToolkit.@variables u(..) [input = true, bounds = (u_l, u_u)] + + # the force on the first mass, a function of the time + F = sin((t - t0) * 2π / (tf - t0)) + + eqs = [ + D(x₁(t)) ~ x₃(t), + D(x₂(t)) ~ x₄(t), + D(x₃(t)) ~ -(k1 + k2) / m1 * x₁(t) + k2 / m1 * x₂(t) + 1 / m1 * F, + D(x₄(t)) ~ k2 / m2 * x₁(t) - k2 / m2 * x₂(t) - c * (1 - u(t)) / m2 * x₄(t), + ] + costs = [ + ModelingToolkit.Symbolics.Integral(t in (t0, tf))( + 0.5 * (x₁(t)^2 + x₂(t)^2 + u(t)^2) + ), + ] + constraints = [] + ModelingToolkit.@named sys = ModelingToolkit.System( + eqs, t; costs=costs, constraints=constraints + ) + + # initial guess: from the metadata (#377), unless given + init = OptimalControlProblems.Metadata._initial_guess(:double_oscillator, params, init) + + return OptimalControlProblems.Problems._problem( + :double_oscillator, :ModelingToolkit, sys, init, params + ) +end From bfbe01ae4c34ff66197465a622bdd8f4c4f1f492 Mon Sep 17 00:00:00 2001 From: Olivier Cots Date: Wed, 11 Nov 2026 18:11:25 +0100 Subject: [PATCH 4/7] feat(models): chain in the ModelingToolkit modeling (#308) A Mayer cost and boundary conditions on two of the three states. Passes the continuous comparison with OptimalControl and the smoke solve. Co-Authored-By: Claude Sonnet 5.5 --- ext/MetaData/chain.jl | 2 +- ext/ModelingToolkitModels/chain.jl | 52 ++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 1 deletion(-) create mode 100644 ext/ModelingToolkitModels/chain.jl diff --git a/ext/MetaData/chain.jl b/ext/MetaData/chain.jl index d9dd055a2..4cc47aa8a 100644 --- a/ext/MetaData/chain.jl +++ b/ext/MetaData/chain.jl @@ -1,7 +1,7 @@ chain_meta = OrderedDict( :grid_size => 500, :parameters => (t0=0, tf=1, L=4, a=1, b=3, x₂_t0=0, x₃_t0=0), - :status => (OptimalControl=:valid, OptimalControlScalarized=:valid, JuMP=:valid), + :status => (OptimalControl=:valid, OptimalControlScalarized=:valid, JuMP=:valid, ModelingToolkit=:valid), # initial guess of every modeling (#377), from the parameters :init => p -> begin (; t0, tf, a, b) = p diff --git a/ext/ModelingToolkitModels/chain.jl b/ext/ModelingToolkitModels/chain.jl new file mode 100644 index 000000000..91d128902 --- /dev/null +++ b/ext/ModelingToolkitModels/chain.jl @@ -0,0 +1,52 @@ +"""The **Hanging Chain problem** is a classical benchmark in optimal control. + +Builds the `chain` problem with the ModelingToolkit backend. + +```julia-repl +julia> using ModelingToolkit, OptimalControlProblems +julia> pb = chain(ModelingToolkitBackend()) +``` + +Default parameters and the modeling status are available through +`problem_metadata(:chain)` and `OptimalControlProblems.status(:chain)`. +""" +function OptimalControlProblems.chain( + ::ModelingToolkitBackend; + parameters::Union{Nothing,NamedTuple}=nothing, + init=nothing, +) + OptimalControlProblems.Catalogue._warn_if_draft(:chain, :ModelingToolkit) + params = OptimalControlProblems.parameters_data(:chain, parameters) + t0, tf = float(params[:t0]), float(params[:tf]) + L = float(params[:L]) + a, b = float(params[:a]), float(params[:b]) + x₂_t0, x₃_t0 = float(params[:x₂_t0]), float(params[:x₃_t0]) + + t = ModelingToolkit.t_nounits + D = ModelingToolkit.Differential(t) + + ModelingToolkit.@variables x₁(..) = a [tunable = false] + ModelingToolkit.@variables x₂(..) = x₂_t0 [tunable = false] + ModelingToolkit.@variables x₃(..) = x₃_t0 [tunable = false] + ModelingToolkit.@variables u(..) [input = true] + + eqs = [ + D(x₁(t)) ~ u(t), + D(x₂(t)) ~ x₁(t) * sqrt(1 + u(t)^2), + D(x₃(t)) ~ sqrt(1 + u(t)^2), + ] + # a Mayer cost: the final value of x₂ + costs = [x₂(tf)] + constraints = [x₁(tf) ~ b, x₃(tf) ~ L] + + ModelingToolkit.@named sys = ModelingToolkit.System( + eqs, t; costs=costs, constraints=constraints + ) + + # initial guess: from the metadata (#377), unless given + init = OptimalControlProblems.Metadata._initial_guess(:chain, params, init) + + return OptimalControlProblems.Problems._problem( + :chain, :ModelingToolkit, sys, init, params + ) +end From 20480f47afb240a6f4b928c7d13f781684c816fa Mon Sep 17 00:00:00 2001 From: Olivier Cots Date: Wed, 11 Nov 2026 18:11:25 +0100 Subject: [PATCH 5/7] feat(models): electric_vehicle in the ModelingToolkit modeling (#308) States named x and v, a polynomial road, a Lagrange cost. Passes the continuous comparison with OptimalControl and the smoke solve. Co-Authored-By: Claude Sonnet 5.5 --- ext/MetaData/electric_vehicle.jl | 2 +- ext/ModelingToolkitModels/electric_vehicle.jl | 53 +++++++++++++++++++ 2 files changed, 54 insertions(+), 1 deletion(-) create mode 100644 ext/ModelingToolkitModels/electric_vehicle.jl diff --git a/ext/MetaData/electric_vehicle.jl b/ext/MetaData/electric_vehicle.jl index 6e246040c..713415848 100644 --- a/ext/MetaData/electric_vehicle.jl +++ b/ext/MetaData/electric_vehicle.jl @@ -17,7 +17,7 @@ electric_vehicle_meta = OrderedDict( x_tf=10, v_tf=0, ), - :status => (OptimalControl=:valid, OptimalControlScalarized=:valid, JuMP=:valid), + :status => (OptimalControl=:valid, OptimalControlScalarized=:valid, JuMP=:valid, ModelingToolkit=:valid), # initial guess of every modeling (#377), from the parameters :init => p -> (state=[0.1, 0.1], control=0.1), ) diff --git a/ext/ModelingToolkitModels/electric_vehicle.jl b/ext/ModelingToolkitModels/electric_vehicle.jl new file mode 100644 index 000000000..303c50413 --- /dev/null +++ b/ext/ModelingToolkitModels/electric_vehicle.jl @@ -0,0 +1,53 @@ +"""The **Electric Vehicle (EV) trajectory problem** is a benchmark in optimal control for energy-efficient driving. + +Builds the `electric_vehicle` problem with the ModelingToolkit backend. + +```julia-repl +julia> using ModelingToolkit, OptimalControlProblems +julia> pb = electric_vehicle(ModelingToolkitBackend()) +``` + +Default parameters and the modeling status are available through +`problem_metadata(:electric_vehicle)` and `OptimalControlProblems.status(:electric_vehicle)`. +""" +function OptimalControlProblems.electric_vehicle( + ::ModelingToolkitBackend; + parameters::Union{Nothing,NamedTuple}=nothing, + init=nothing, +) + OptimalControlProblems.Catalogue._warn_if_draft(:electric_vehicle, :ModelingToolkit) + params = OptimalControlProblems.parameters_data(:electric_vehicle, parameters) + t0, tf = float(params[:t0]), float(params[:tf]) + b1, b2 = params[:b1], params[:b2] + h0, h1, h2 = params[:h0], params[:h1], params[:h2] + α0, α1, α2, α3 = params[:α0], params[:α1], params[:α2], params[:α3] + x_t0, v_t0 = float(params[:x_t0]), float(params[:v_t0]) + x_tf, v_tf = float(params[:x_tf]), float(params[:v_tf]) + + t = ModelingToolkit.t_nounits + D = ModelingToolkit.Differential(t) + + ModelingToolkit.@variables x(..) = x_t0 [tunable = false] + ModelingToolkit.@variables v(..) = v_t0 [tunable = false] + ModelingToolkit.@variables u(..) [input = true] + + # the slope of the road at the position x + road(x) = α0 + α1 * x + α2 * x^2 + α3 * x^3 + + eqs = [D(x(t)) ~ v(t), D(v(t)) ~ h1 * u(t) - h2 * v(t)^2 - h0 - road(x(t))] + costs = [ + ModelingToolkit.Symbolics.Integral(t in (t0, tf))(b1 * u(t) * v(t) + b2 * u(t)^2), + ] + constraints = [x(tf) ~ x_tf, v(tf) ~ v_tf] + + ModelingToolkit.@named sys = ModelingToolkit.System( + eqs, t; costs=costs, constraints=constraints + ) + + # initial guess: from the metadata (#377), unless given + init = OptimalControlProblems.Metadata._initial_guess(:electric_vehicle, params, init) + + return OptimalControlProblems.Problems._problem( + :electric_vehicle, :ModelingToolkit, sys, init, params + ) +end From 15d0192e1e9b45d1c3d0bb5d69459d00122e7170 Mon Sep 17 00:00:00 2001 From: Olivier Cots Date: Wed, 11 Nov 2026 18:30:13 +0100 Subject: [PATCH 6/7] test: compare at times that are not all round, merge the one-sided rows on one expression (#308) The comparison evaluated the models at 0, 25, 50, 75 and 100 % of the interval: for bioreactor, whose light has a period of 10 on [0, 200], the light was 0 at every point, and a wrong light term passed. Two irregular fractions are added (0.137, 0.618); changing the light of the ModelingToolkit model now fails the dynamics check. The ModelingToolkit reader merges the one-sided rows on the same expression (l <= h, h <= u) into one two-sided row, as OptimalControl writes l <= h <= u: the box of the initial state of bioreactor. Co-Authored-By: Claude Sonnet 5.5 --- test/common/continuous.jl | 4 ++- test/common/continuous_modelingtoolkit.jl | 32 ++++++++++++++++++++--- 2 files changed, 31 insertions(+), 5 deletions(-) diff --git a/test/common/continuous.jl b/test/common/continuous.jl index 8a1648832..ec50eae30 100644 --- a/test/common/continuous.jl +++ b/test/common/continuous.jl @@ -13,8 +13,10 @@ const OC = OptimalControl # The perturbations of the initial guess, and the points of each trajectory (fractions of the # time interval): the objective is not affine, several trajectories tell two objectives apart. +# The fractions are not all round: a time that depends on the time periodically (the light of +# `bioreactor`, of period 10 on [0, 200]) would be the same at every round fraction. const AMPLITUDES = (0.0, 0.01, 0.05) -const FRACTIONS = (0.0, 0.25, 0.5, 0.75, 1.0) +const FRACTIONS = (0.0, 0.137, 0.25, 0.5, 0.618, 0.75, 1.0) const TOL = 1e-10 vec1(a::Number) = [Float64(a)] diff --git a/test/common/continuous_modelingtoolkit.jl b/test/common/continuous_modelingtoolkit.jl index 6b2216961..6abc079e3 100644 --- a/test/common/continuous_modelingtoolkit.jl +++ b/test/common/continuous_modelingtoolkit.jl @@ -107,6 +107,23 @@ function bounded(c) throw(ArgumentError("unsupported constraint $c")) end +""" +The rows `(lower, h, upper)` with the one-sided rows on the same expression `h` merged into one +two-sided row: `l ≤ h` and `h ≤ u` are written `l ≤ h ≤ u` by OptimalControl. +""" +function merged(rows) + out = Tuple{Float64,Any,Float64}[] + for (lo, h, hi) in rows + i = findfirst(r -> isequal(r[2], h), out) + if isnothing(i) + push!(out, (lo, h, hi)) + else + out[i] = (max(out[i][1], lo), h, min(out[i][3], hi)) + end + end + return out +end + """Initial value of the state `x` when it is fixed (not tunable), `nothing` otherwise.""" function initial_value(sys, x) MTK.istunable(x, false) && return nothing @@ -178,7 +195,7 @@ function problem_data(sys, state_names, control_names, tspan) end lower_x, upper_x = first.(metadata_bounds.(xs)), last.(metadata_bounds.(xs)) lower_u, upper_u = first.(metadata_bounds.(us)), last.(metadata_bounds.(us)) - path, boundary = Tuple{Any,Function,Any}[], Tuple{Any,Function,Any}[] + path_rows, boundary_rows = Tuple{Float64,Any,Float64}[], Tuple{Float64,Any,Float64}[] for c in MTK.get_constraints(sys) lo, h, hi = bounded(c) if depends_on_time(h, iv) @@ -189,13 +206,20 @@ function problem_data(sys, state_names, control_names, tspan) elseif !isnothing(k) lower_u[k], upper_u[k] = max(lower_u[k], lo), min(upper_u[k], hi) else - f = (x, u, v, t) -> evaluate(h, sig, point(; t, x, u)) - push!(path, (lo, f, hi)) + push!(path_rows, (lo, h, hi)) end else - push!(boundary, (lo, (x0, xf, v) -> evaluate(h, sig, point(; x0, xf)), hi)) + push!(boundary_rows, (lo, h, hi)) end end + path = Tuple{Any,Function,Any}[ + (lo, (x, u, v, t) -> evaluate(h, sig, point(; t, x, u)), hi) for + (lo, h, hi) in merged(path_rows) + ] + boundary = Tuple{Any,Function,Any}[ + (lo, (x0, xf, v) -> evaluate(h, sig, point(; x0, xf)), hi) for + (lo, h, hi) in merged(boundary_rows) + ] for (i, x) in enumerate(xs) a = initial_value(sys, x) isnothing(a) || push!(boundary, (a, (x0, xf, v) -> x0[i], a)) From e438e3616799029951aeb79b8f6dea22813c14ca Mon Sep 17 00:00:00 2001 From: Olivier Cots Date: Wed, 11 Nov 2026 18:30:14 +0100 Subject: [PATCH 7/7] feat(models): bioreactor in the ModelingToolkit modeling (#308) A free initial state in a box, a state lower bound, a bounded control, and a light that depends on the time periodically (floor, ifelse). Passes the continuous comparison with OptimalControl and the smoke solve; the comparison fails when the light or a bound of the initial box is changed. Co-Authored-By: Claude Sonnet 5.5 --- ext/MetaData/bioreactor.jl | 2 +- ext/ModelingToolkitModels/bioreactor.jl | 75 +++++++++++++++++++++++++ 2 files changed, 76 insertions(+), 1 deletion(-) create mode 100644 ext/ModelingToolkitModels/bioreactor.jl diff --git a/ext/MetaData/bioreactor.jl b/ext/MetaData/bioreactor.jl index 0247c5311..d0ced5ea5 100644 --- a/ext/MetaData/bioreactor.jl +++ b/ext/MetaData/bioreactor.jl @@ -23,7 +23,7 @@ bioreactor_meta = OrderedDict( b_t0_l=0.5, b_t0_u=3, ), - :status => (OptimalControl=:valid, JuMP=:valid), + :status => (OptimalControl=:valid, JuMP=:valid, ModelingToolkit=:valid), # initial guess of every modeling (#377), from the parameters :init => p -> (state=[50, 50, 50], control=0.5), ) diff --git a/ext/ModelingToolkitModels/bioreactor.jl b/ext/ModelingToolkitModels/bioreactor.jl new file mode 100644 index 000000000..1f4ce27c3 --- /dev/null +++ b/ext/ModelingToolkitModels/bioreactor.jl @@ -0,0 +1,75 @@ +"""The **photobioreactor–digester system problem** is a benchmark in constrained optimal control. + +Builds the `bioreactor` problem with the ModelingToolkit backend. + +```julia-repl +julia> using ModelingToolkit, OptimalControlProblems +julia> pb = bioreactor(ModelingToolkitBackend()) +``` + +Default parameters and the modeling status are available through +`problem_metadata(:bioreactor)` and `OptimalControlProblems.status(:bioreactor)`. +""" +function OptimalControlProblems.bioreactor( + ::ModelingToolkitBackend; + parameters::Union{Nothing,NamedTuple}=nothing, + init=nothing, +) + OptimalControlProblems.Catalogue._warn_if_draft(:bioreactor, :ModelingToolkit) + params = OptimalControlProblems.parameters_data(:bioreactor, parameters) + t0, tf = float(params[:t0]), float(params[:tf]) + β, c, γ = params[:β], params[:c], params[:γ] + halfperiod, Ks, μ2m, μbar, r = ( + params[:halfperiod], params[:Ks], params[:μ2m], params[:μbar], params[:r] + ) + y_l, s_l, b_l = float(params[:y_l]), float(params[:s_l]), float(params[:b_l]) + u_l, u_u = float(params[:u_l]), float(params[:u_u]) + y_t0_l, y_t0_u = float(params[:y_t0_l]), float(params[:y_t0_u]) + s_t0_l, s_t0_u = float(params[:s_t0_l]), float(params[:s_t0_u]) + b_t0_l, b_t0_u = float(params[:b_t0_l]), float(params[:b_t0_u]) + + t = ModelingToolkit.t_nounits + D = ModelingToolkit.Differential(t) + + # the initial state is free, in a box: no default, started from the initial guess + ModelingToolkit.@variables y(..) [tunable = true] + ModelingToolkit.@variables s(..) [tunable = true] + ModelingToolkit.@variables b(..) [tunable = true] + ModelingToolkit.@variables u(..) [input = true, bounds = (u_l, u_u)] + + # light model: max(0, sin)^2 * μbar, on a day/night cycle of period 2 halfperiod + days = t / (halfperiod * 2) + tau = (days - floor(days)) * 2π + μ = ifelse(sin(tau) > 0, sin(tau), 0)^2 * μbar + # growth model (Monod) + μ2 = μ2m * s(t) / (s(t) + Ks) + + eqs = [ + D(y(t)) ~ μ * y(t) / (1 + y(t)) - (r + u(t)) * y(t), + D(s(t)) ~ -μ2 * b(t) + u(t) * β * (γ * y(t) - s(t)), + D(b(t)) ~ (μ2 - u(t) * β) * b(t), + ] + costs = [ModelingToolkit.Symbolics.Integral(t in (t0, tf))(-μ2 * b(t) / (β + c))] + constraints = [ + ModelingToolkit.Symbolics.:≳(y(t), y_l), + ModelingToolkit.Symbolics.:≳(s(t), s_l), + ModelingToolkit.Symbolics.:≳(b(t), b_l), + ModelingToolkit.Symbolics.:≳(y(t0), y_t0_l), + ModelingToolkit.Symbolics.:≲(y(t0), y_t0_u), + ModelingToolkit.Symbolics.:≳(s(t0), s_t0_l), + ModelingToolkit.Symbolics.:≲(s(t0), s_t0_u), + ModelingToolkit.Symbolics.:≳(b(t0), b_t0_l), + ModelingToolkit.Symbolics.:≲(b(t0), b_t0_u), + ] + + ModelingToolkit.@named sys = ModelingToolkit.System( + eqs, t; costs=costs, constraints=constraints + ) + + # initial guess: from the metadata (#377), unless given + init = OptimalControlProblems.Metadata._initial_guess(:bioreactor, params, init) + + return OptimalControlProblems.Problems._problem( + :bioreactor, :ModelingToolkit, sys, init, params + ) +end