JuMP: vector variable to user defined NLobjective

I I’m trying to optimize an user defined function with JuMP. The variable is a vector of length 30.
I’ve tried the following two ways to define the objective, but both of them throw an error.
The first way I tried with the @eval -macro:

m = Model(solver = NLoptSolver(algorithm=:LD_SLSQP))
JuMP.register(m, :f, 1, f, autodiff = true)
n = 30
@variable(m, x[1:n])
for i in 1:n
    setvalue(x[i],x0[i])
end

@eval @NLobjective(m, Max, $(Expr(:call, :f, [Expr(:ref,:x,i) for i=1:n]...)))
status = solve(m)

Julia> ERROR: LoadError: Incorrect number of arguments for "f" in nonlinear expression.

The other way I tried with setNLobjective -function:

m = Model(solver = NLoptSolver(algorithm=:LD_SLSQP))
JuMP.register(m, :f, 1, f, autodiff = true)
n = 30 
@variable(m, x[1:n])
for i in 1:n
    setvalue(x[i],x0[i])
end 
JuMP.setNLobjective(m, :Min, Expr(:call, :f, [x[i] for i=1:n]...))
status = solve(m) 

Julia> ERROR: LoadError: KeyError: key :f not found

Anyone having a clue what I might be doing wrong here?

I figured the problem was the number of variables on the line

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

And that it should be

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

Because x is a vector of length 30.

1 Like