Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow using ternary operator inside @constraint #3183

Closed
hdavid16 opened this issue Jan 10, 2023 · 2 comments
Closed

Allow using ternary operator inside @constraint #3183

hdavid16 opened this issue Jan 10, 2023 · 2 comments

Comments

@hdavid16
Copy link
Contributor

hdavid16 commented Jan 10, 2023

It would be great to do something like this:

m=Model()
@variable(m,x)
@constraint(m, [i=1:2],
    i == 1 ? exp(x) <= 0 : x^2 <= 0
)

Currently, this gives the error:

Unsupported constraint expression: we don't know how to parse constraints containing expressions of type :if.

This is, however, supported in @expression (the macro below does work):

@constraint(m, [i=1:2],
    i == 1 ? exp(x) : x^2
)

Tested in JuMP v.1.6.0

Current workaround is to use the ternary operator in @expression and then use that expression to build the needed constraints.

@odow
Copy link
Member

odow commented Jan 10, 2023

Multiple problems here:

  • @constraint doesn't support exp
  • Second example doesn't form a constraint

This is, however, supported in @expression
Current workaround is to use the ternary operator in @expression and then use that expression to build the needed constraints.

Not sure what you mean? This shouldn't work in @expression because it doesn't support exp.

The correct way to write this is:

julia> model = Model()
A JuMP Model
Feasibility problem with:
Variables: 0
Model mode: AUTOMATIC
CachingOptimizer state: NO_OPTIMIZER
Solver name: No optimizer attached.

julia> @variable(model, x)
x

julia> @NLconstraint(model, [i=1:2], ifelse(i == 1, exp(x), x^2) <= 0)
2-element Vector{NonlinearConstraintRef{ScalarShape}}:
 ifelse(1.0 == 1.0, exp(x), x ^ 2.0) - 0.0  0
 ifelse(2.0 == 1.0, exp(x), x ^ 2.0) - 0.0  0

@hdavid16
Copy link
Contributor Author

Yes, you are right, exp is nonlinear. Instead of exp(x) <= 0, say x <= 0 instead.

Ok, I see that I can actually use the ternary operator if I wrap it in parenthesis. For example,

@constraint(m,[i=1:3], x <= (i == 3 ? 0 : 2))

The above works as long as the ternary operator part is in parenthesis. Otherwise, it errors.

Thanks for looking into this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants