Skip to content

Commit

Permalink
fix: mark bounded optimization unknowns as irreducible
Browse files Browse the repository at this point in the history
  • Loading branch information
AayushSabharwal committed Oct 22, 2024
1 parent cfeaf23 commit dedbf6b
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 2 deletions.
13 changes: 12 additions & 1 deletion src/systems/optimization/optimizationsystem.jl
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,17 @@ function OptimizationSystem(op, unknowns, ps;
ps′ = value.(ps)
op′ = value(scalarize(op))

irreducible_subs = Dict()
for i in eachindex(unknowns′)
var = unknowns′[i]
if hasbounds(var)
irreducible_subs[var] = irrvar = setirreducible(var, true)
unknowns′[i] = irrvar
end
end
op′ = substitute(op′, irreducible_subs)
constraints = substitute.(constraints, (irreducible_subs,))

if !(isempty(default_u0) && isempty(default_p))
Base.depwarn(
"`default_u0` and `default_p` are deprecated. Use `defaults` instead.",
Expand All @@ -113,7 +124,7 @@ function OptimizationSystem(op, unknowns, ps;
throw(ArgumentError("System names must be unique."))
end
defaults = todict(defaults)
defaults = Dict(value(k) => value(v)
defaults = Dict(substitute(value(k), irreducible_subs) => substitute(value(v), irreducible_subs)
for (k, v) in pairs(defaults) if value(v) !== nothing)

var_to_name = Dict()
Expand Down
1 change: 1 addition & 0 deletions src/variables.jl
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ isoutput(x) = isvarkind(VariableOutput, x)
# Before the solvability check, we already have handled IO variables, so
# irreducibility is independent from IO.
isirreducible(x) = isvarkind(VariableIrreducible, x)
setirreducible(x, v) = setmetadata(x, VariableIrreducible, v)
state_priority(x) = convert(Float64, getmetadata(x, VariableStatePriority, 0.0))::Float64

function default_toterm(x)
Expand Down
16 changes: 15 additions & 1 deletion test/optimizationsystem.jl
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
using ModelingToolkit, SparseArrays, Test, Optimization, OptimizationOptimJL,
OptimizationMOI, Ipopt, AmplNLWriter, Ipopt_jll
OptimizationMOI, Ipopt, AmplNLWriter, Ipopt_jll, SymbolicIndexingInterface
using ModelingToolkit: get_metadata

@testset "basic" begin
Expand Down Expand Up @@ -347,3 +347,17 @@ end
prob = @test_nowarn OptimizationProblem(sys, nothing)
@test_nowarn solve(prob, NelderMead())
end

@testset "Bounded unknowns are irreducible" begin
@variables x
@variables y [bounds = (-Inf, Inf)]
@variables z [bounds = (1.0, 2.0)]
obj = x^2 + y^2 + z^2
cons = [
y ~ 2x
z ~ 2y
]
@mtkbuild sys = OptimizationSystem(obj, [x, y, z], []; constraints = cons)
@test is_variable(sys, z)
@test !is_variable(sys, y)
end

0 comments on commit dedbf6b

Please sign in to comment.