Skip to content

Commit

Permalink
fix: propagate bounds information to variable metadata in `modelingto…
Browse files Browse the repository at this point in the history
…olkitize`
  • Loading branch information
AayushSabharwal committed Oct 22, 2024
1 parent b5c5b34 commit cfeaf23
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
9 changes: 9 additions & 0 deletions src/systems/optimization/modelingtoolkitize.jl
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,15 @@ function modelingtoolkitize(prob::DiffEqBase.OptimizationProblem;
end
_vars = reshape(_vars, size(prob.u0))
vars = ArrayInterface.restructure(prob.u0, _vars)
if prob.ub !== nothing # lb is also !== nothing
vars = map(vars, prob.lb, prob.ub) do sym, lb, ub
if iszero(lb) && iszero(ub) || isinf(lb) && lb < 0 && isinf(ub) && ub > 0
sym
else
Symbolics.setmetadata(sym, VariableBounds, (lb, ub))
end
end
end
params = if has_p
if p_names === nothing && SciMLBase.has_sys(prob.f)
p_names = Dict(parameter_index(prob.f.sys, sym) => sym
Expand Down
10 changes: 10 additions & 0 deletions test/modelingtoolkitize.jl
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,16 @@ sol = solve(prob, BFGS())
sol = solve(prob, Newton())
@test sol.objective < 1e-8

prob = OptimizationProblem(ones(3); lb = [-Inf, 0.0, 1.0], ub = [Inf, 0.0, 2.0]) do u, p
sum(abs2, u)
end

sys = complete(modelingtoolkitize(prob))
@test !ModelingToolkit.hasbounds(unknowns(sys)[1])
@test !ModelingToolkit.hasbounds(unknowns(sys)[2])
@test ModelingToolkit.hasbounds(unknowns(sys)[3])
@test ModelingToolkit.getbounds(unknowns(sys)[3]) == (1.0, 2.0)

## SIR System Regression Test

β = 0.01# infection rate
Expand Down

0 comments on commit cfeaf23

Please sign in to comment.