Skip to content

Commit 2a3e023

Browse files
fix: mark bounded optimization unknowns as irreducible
1 parent cfeaf23 commit 2a3e023

File tree

3 files changed

+27
-2
lines changed

3 files changed

+27
-2
lines changed

src/systems/optimization/optimizationsystem.jl

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,17 @@ function OptimizationSystem(op, unknowns, ps;
103103
ps′ = value.(ps)
104104
op′ = value(scalarize(op))
105105

106+
irreducible_subs = Dict()
107+
for i in eachindex(unknowns′)
108+
var = unknowns′[i]
109+
if hasbounds(var)
110+
irreducible_subs[var] = irrvar = setirreducible(var, true)
111+
unknowns′[i] = irrvar
112+
end
113+
end
114+
op′ = substitute(op′, irreducible_subs)
115+
constraints = substitute.(constraints, (irreducible_subs,))
116+
106117
if !(isempty(default_u0) && isempty(default_p))
107118
Base.depwarn(
108119
"`default_u0` and `default_p` are deprecated. Use `defaults` instead.",
@@ -113,7 +124,8 @@ function OptimizationSystem(op, unknowns, ps;
113124
throw(ArgumentError("System names must be unique."))
114125
end
115126
defaults = todict(defaults)
116-
defaults = Dict(value(k) => value(v)
127+
defaults = Dict(substitute(value(k), irreducible_subs) => substitute(
128+
value(v), irreducible_subs)
117129
for (k, v) in pairs(defaults) if value(v) !== nothing)
118130

119131
var_to_name = Dict()

src/variables.jl

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,7 @@ isoutput(x) = isvarkind(VariableOutput, x)
106106
# Before the solvability check, we already have handled IO variables, so
107107
# irreducibility is independent from IO.
108108
isirreducible(x) = isvarkind(VariableIrreducible, x)
109+
setirreducible(x, v) = setmetadata(x, VariableIrreducible, v)
109110
state_priority(x) = convert(Float64, getmetadata(x, VariableStatePriority, 0.0))::Float64
110111

111112
function default_toterm(x)

test/optimizationsystem.jl

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
using ModelingToolkit, SparseArrays, Test, Optimization, OptimizationOptimJL,
2-
OptimizationMOI, Ipopt, AmplNLWriter, Ipopt_jll
2+
OptimizationMOI, Ipopt, AmplNLWriter, Ipopt_jll, SymbolicIndexingInterface
33
using ModelingToolkit: get_metadata
44

55
@testset "basic" begin
@@ -347,3 +347,15 @@ end
347347
prob = @test_nowarn OptimizationProblem(sys, nothing)
348348
@test_nowarn solve(prob, NelderMead())
349349
end
350+
351+
@testset "Bounded unknowns are irreducible" begin
352+
@variables x
353+
@variables y [bounds = (-Inf, Inf)]
354+
@variables z [bounds = (1.0, 2.0)]
355+
obj = x^2 + y^2 + z^2
356+
cons = [y ~ 2x
357+
z ~ 2y]
358+
@mtkbuild sys = OptimizationSystem(obj, [x, y, z], []; constraints = cons)
359+
@test is_variable(sys, z)
360+
@test !is_variable(sys, y)
361+
end

0 commit comments

Comments
 (0)