How can I extract MOI expression from a linear JuMP obj expression

Hello,

I am struggling to generate an MOI (MathOptInterface) expression from a linear JuMP expression.

I have a JuMP model as follows.

m = Model(Ipopt.Optimizer)
@variable(m, 0 <= x[1:3] <= 10)
@constraint(m, sum(x[i] for i in 1:3) >= 0)
@objective(m, Min, sum(x[i] for i in 1:3))

The obj JuMP expression is

obj_expr = JuMP.objective_function(m)
julia> print(obj_expr)
x[1] + x[2] + x[3]

I can generate MOI expressions for nonlinear objective or constraints, but don’t know how to do it for linear ones. My goal is to generate another JuMP model with the same objective function. For example,

nm = Model(Ipopt.Optimizer)
@variable(nm, x[1:3])
func = moi_obj_expr  #suppose this is the moi expression
MOI.set(nm, MOI.ObjectiveFunction{typeof(func)}(), func)
MOI.set(nm, MOI.ObjectiveSense(), JuMP.objective_sense(m))

Thank you.

You can go from JuMP to MOI with moi_function
https://github.com/jump-dev/JuMP.jl/blob/2b0d9100b83985f67bbb673c9e34dbedc9e30da6/src/aff_expr.jl#L498
And the other way around with jump_function
https://github.com/jump-dev/JuMP.jl/blob/2b0d9100b83985f67bbb673c9e34dbedc9e30da6/src/aff_expr.jl#L515

1 Like

@blegat Thank you so much. The problem is solved now.