Passing objective function into JuMP

I would like to use JuMP for nonlinear constrained optimization. Specifically I want to be able to pass my objective function into it from outside. How do I do that? What I tried is below.

I am not sure if this is a JuMP-specific thing or just a Julia passing functions thing. Thanks

f(x) = x^2 + 3x + 4

using JuMP
import Ipopt
function test_obj(obj_func)
    model = Model(Ipopt.Optimizer)
    @variable(model, x, start = -1.0)
    @NLobjective(model, Min, obj_func)
    @NLconstraint(model, x >= 5)

    
    optimize!(model)
    println("""
    termination_status = $(termination_status(model))
    \n x = $(value(x))    
    """)
    return
end

test_obj(f)

> Unexpected object #22 (of type var"#22#23"{typeof(f)} in nonlinear expression.

Based on this question I also tried:

    model = Model(Ipopt.Optimizer)
    @variable(model, x, start = -1.0)
    @NLobjective(model, Min, f(x))
    

    #     @NLconstraint(model, sqrt(y-π) - b_1 >= sqrt(y-π-x_2) )
#     @NLconstraint(model, π == p_2*(c-x_2) )
    optimize!(model)
> Unrecognized function "f" used in nonlinear expression.

You need to register the function https://jump.dev/JuMP.jl/stable/nlp/#User-defined-Functions

1 Like