How to add user-defined nonlinear functions as constraints with JuMP?

Is it possible to add user-defined nonlinear functions as constraints in JuMP? I couldn’t find any documentation about a case like this nor any examples where someone would have done this.
I mean something like this:

JuMP.register(m, :g, 1, g, autodiff=true)
JuMP.addNLconstraint(m, g(x) <= 0)

If this is not possible, then is there any way to do this kind of optimization with Julia?

Have you tried? It should work exactly as you have :slight_smile: (Although you probably want to use @NLconstraint instead of addNLconstraint.)

The docs are being updated for the new version of JuMP, but I have opened an issue to make sure it gets addressed. https://github.com/JuliaOpt/JuMP.jl/issues/1323

1 Like

Yes of course I’ve tried my example @odow , but it didn’t work, probably because my variable was a vector. However I now figured how it can be done:

f(x) = x[1]^2+2*x[2]+3
g(x) = x[1]^3+x[2]^2

JuMP.register(m, :f, 2, f, autodiff=true)
JuMP.register(m, :g, 2, g, autodiff=true)

JuMP.setNLobjective(m, :Min, :(f($(x...)))
JuMP.addNLconstraint(m, :(g($(x...))<=10))) # This line is the one I had trouble with

Interesting that similar examples really don’t exist anywhere in JuMP’s documentation.

Yes of course I’ve tried my example

Oops, sorry for coming across as blunt, it wasn’t clear if it was a general question or whether there was a specific problem.

Glad you got it working. Another option is:

using JuMP, Ipopt

m=Model(solver=IpoptSolver())
@variable(m, x[1:2])

f(x...) = x[1]^2+2*x[2]+3
g(x...) = x[1]^3+x[2]^2

JuMP.register(m, :f, 2, f, autodiff=true)
JuMP.register(m, :g, 2, g, autodiff=true)

@NLobjective(m, Min, f(x[1], x[2]))
@NLconstraint(m, g(x[1], x[2]) <= 10)

solve(m)

Interesting that similar examples really don’t exist anywhere in JuMP’s documentation.

Yes. Pull requests to improve the docs are always welcome :slight_smile:

1 Like