Skip to content

Commit

Permalink
Fix parsing of double-sided nl constraints (#3045)
Browse files Browse the repository at this point in the history
  • Loading branch information
odow authored Aug 21, 2022
1 parent 51d0864 commit f6720f9
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/macros.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1838,6 +1838,7 @@ function _parse_nonlinear_expression(model, x)
_init_NLP($model)
end
operators = Set{Tuple{Symbol,Int}}()
_assert_constant_comparison(code, x)
y = _parse_nonlinear_expression_inner(code, x, operators)
user_defined_operators = filter(operators) do (op, i)
if op in (:<=, :>=, :(==), :<, :>, :&&, :||)
Expand All @@ -1859,6 +1860,22 @@ function _parse_nonlinear_expression(model, x)
return code, y
end

# JuMP special-cases the error for constant LHS and RHS terms in a comparison
# expression. In JuMP v1.1 and earlier, it evaluted the outer terms in the
# current scope, and checked to see if they were Real. To keep the same behavior
# we do the same here.
function _assert_constant_comparison(code::Expr, expr::Expr)
if Meta.isexpr(expr, :comparison)
lhs, rhs = gensym(), gensym()
push!(code.args, esc(:($lhs = $(expr.args[1]))))
push!(code.args, esc(:($rhs = $(expr.args[5]))))
expr.args[1], expr.args[5] = lhs, rhs
end
return
end

_assert_constant_comparison(::Expr, ::Any) = nothing

function _auto_register_expression(op_var, op, i)
q_op = Meta.quot(op)
return quote
Expand Down
13 changes: 13 additions & 0 deletions test/nlp.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1474,6 +1474,19 @@ function test_user_defined_hessian()
return
end

function test_nlp_comparison()
model = Model()
@variable(model, x)
c1 = @NLconstraint(model, 1 - 2 <= sin(x) <= -1 + 2)
@test c1 isa NonlinearConstraintRef
a, b = 1.0, 2.0
c2 = @NLconstraint(model, a / b <= sin(x) <= a * b)
@test c2 isa NonlinearConstraintRef
@NLconstraint(model, c3[i = 1:2], -i <= sin(x) <= i^2)
@test c3 isa Vector{<:NonlinearConstraintRef}
return
end

end

TestNLP.runtests()

0 comments on commit f6720f9

Please sign in to comment.