# Defining the objective using function

Dear users,
I need to minimize this nonlinear function: f(x1,x2) = 1 + x2^2 - x - sin(x1) with box constraints.
How can I do this by using a function, named E-restrito, providing as argument f?
My code is:

``````function E_restrito( f(x1,x2) )
optimizer = Juniper.Optimizer
params = Dict{Symbol,Any}()
params[:nl_solver] = with_optimizer(Ipopt.Optimizer, print_level=0)
modelo = Model(with_optimizer(optimizer, params))

@variable(modelo, l[i] <= x[i in 1:2] <= u[i], start = 1)

@objective(modelo, Min,  f(x1,x2))

optimize!(modelo)

end
``````

Hi there. Have you read http://www.juliaopt.org/JuMP.jl/v0.19.2/nlp/?

Yes, but no solved my problem. I want to define a given objective-function and call it by using a function.

You should use User defined functions as explained here:
http://www.juliaopt.org/JuMP.jl/v0.19.2/nlp/#User-defined-Functions-1
The signature of `E_restrito` should be `function E_restrito(f::Function)`

To flesh out @blegat’s suggestion:

``````using JuMP, Ipopt

function E_restrito(f)
model = Model(with_optimizer(Ipopt.Optimizer))
@variable(model, x[1:2] >= 0)
JuMP.register(model, :f, 2, f, autodiff=true)
@NLobjective(model, Min, f(x, x))
optimize!(model)
return value.(x)
end

foo(x, y) = 1 + y^2 - x - sin(x)
E_restrito(foo)
``````
4 Likes

Wonderfull!
Works very well.
Thank you so much for the complete response.