Nonlinear programming function calls involving sine and cosine

Dear all,
I’m trying to build a nonlinear optimization problem and solve it by Ipopt. I have the following code

using MosekTools
using JuMP
using Ipopt
model = Model(Ipopt.Optimizer)
@variable(model,x1)
cons = [
    (x) -> sin(x) + 1
    (x) -> x + 1
]
expr = @NLexpression(model, cons[1](x1))

I got error

LoadError: Unsupported function cons[1]. All function calls must be `Symbol`s.
in expression starting at In[4]:7

Stacktrace:
 [1] error(s::String)
   @ Base ./error.jl:33
 [2] _parse_nonlinear_expression_inner(code::Expr, x::Expr, operators::Set{Tuple{Symbol, Int64}})
   @ JuMP ~/.julia/packages/JuMP/bm7X3/src/macros.jl:1928
 [3] _parse_nonlinear_expression(model::Expr, x::Expr)
   @ JuMP ~/.julia/packages/JuMP/bm7X3/src/macros.jl:1841
 [4] var"@NLexpression"(__source__::LineNumberNode, __module__::Module, args::Vararg{Any, N} where N)
   @ JuMP ~/.julia/packages/JuMP/bm7X3/src/macros.jl:2419
 [5] eval
   @ ./boot.jl:360 [inlined]
 [6] include_string(mapexpr::typeof(REPL.softscope), mod::Module, code::String, filename::String)
   @ Base ./loading.jl:1116

If I change the last line to

using MosekTools
using JuMP
using Ipopt
model = Model(Ipopt.Optimizer)
@variable(model,x1)
cons = [
    (x) -> sin(x) + 1
    (x) -> x + 1
]
expr = @NLexpression(model, sin(x1) + 1)

I got normal output

subexpression[1]: sin(x1) + 1.0

How to fix the first case? Thank you so much for the help.

1 Like

To use a user-defined function in a nonlinear expression, you first need to register it:
https://jump.dev/JuMP.jl/stable/manual/nlp/#User-defined-Functions

But even then, all functions must be symbols, so you can’t look up a function using cons[1].

I’d strongly suggest you re-structure your code to write out the expressions instead of using the cons vector (just like you did in the second example).

But if you must, you can use the (advanced) capability to construct the expressions:
https://jump.dev/JuMP.jl/stable/manual/nlp/#More-complicated-examples

1 Like