Passing a function as an objective function in JuMP

Anyone knows if it is possible and how to pass a function as an objective function in JuMP? I have read the documentation but i haven’t find anything about it. I have many sum as objective and I would like to write it inside a function instead of doing the conventional declaration : @objective(m, Max, “literal expression of the equation”). Something like that:

@objective(m, Max, call function()  ) 

Thanks in advance.

There is nothing stopping you from going

julia> using JuMP

julia> m=Model()
Feasibility problem with:
 * 0 linear constraints
 * 0 variables
Solver is default solver

julia> @variable(m, x)
x

julia> function foo(x)
       2x + 1
       end
foo (generic function with 1 method)

julia> @objective(m, Min, foo(x))
2 x + 1

julia> JuMP.getobjective(m)
2 x + 1

But, if you are building an objective with a large number of elements, this is going to be slow.

Is it really too much to use the macro? With a good data-structure and intendation, it is normally pretty easy to read. Alternatively, you could break it up into a few @expression objects…

julia> using JuMP

julia> m=Model()
Feasibility problem with:
 * 0 linear constraints
 * 0 variables
Solver is default solver

julia> @variable(m, x)
x

julia> @expression(m, foo, 2x + 1)
2 x + 1

julia> @objective(m, Min, foo)
2 x + 1

julia> JuMP.getobjective(m)
2 x + 1
2 Likes

Thanks a lot!!