Skip to content

Commit cfeaf23

Browse files
fix: propagate bounds information to variable metadata in modelingtoolkitize
1 parent b5c5b34 commit cfeaf23

File tree

2 files changed

+19
-0
lines changed

2 files changed

+19
-0
lines changed

src/systems/optimization/modelingtoolkitize.jl

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,15 @@ function modelingtoolkitize(prob::DiffEqBase.OptimizationProblem;
3333
end
3434
_vars = reshape(_vars, size(prob.u0))
3535
vars = ArrayInterface.restructure(prob.u0, _vars)
36+
if prob.ub !== nothing # lb is also !== nothing
37+
vars = map(vars, prob.lb, prob.ub) do sym, lb, ub
38+
if iszero(lb) && iszero(ub) || isinf(lb) && lb < 0 && isinf(ub) && ub > 0
39+
sym
40+
else
41+
Symbolics.setmetadata(sym, VariableBounds, (lb, ub))
42+
end
43+
end
44+
end
3645
params = if has_p
3746
if p_names === nothing && SciMLBase.has_sys(prob.f)
3847
p_names = Dict(parameter_index(prob.f.sys, sym) => sym

test/modelingtoolkitize.jl

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,16 @@ sol = solve(prob, BFGS())
6767
sol = solve(prob, Newton())
6868
@test sol.objective < 1e-8
6969

70+
prob = OptimizationProblem(ones(3); lb = [-Inf, 0.0, 1.0], ub = [Inf, 0.0, 2.0]) do u, p
71+
sum(abs2, u)
72+
end
73+
74+
sys = complete(modelingtoolkitize(prob))
75+
@test !ModelingToolkit.hasbounds(unknowns(sys)[1])
76+
@test !ModelingToolkit.hasbounds(unknowns(sys)[2])
77+
@test ModelingToolkit.hasbounds(unknowns(sys)[3])
78+
@test ModelingToolkit.getbounds(unknowns(sys)[3]) == (1.0, 2.0)
79+
7080
## SIR System Regression Test
7181

7282
β = 0.01# infection rate

0 commit comments

Comments
 (0)