MethodError: no method matching add_to_expression!(::JuMP.AffExpr, ::JuMP.QuadExpr)

I got a model like

using JuMP, Ipopt
m = Model(Ipopt.Optimizer)
@variable(m, x[i=1:2]>=0)
@expression(m, e1[i=1:2], i*m[:x][i]) ## Affine
@expression(m, e2[i=1:2], m[:x][i]^i) ## At most quadric
add_to_expression!.(m[:e1], m[:e2])

The last add_to_expression!. should fail while non-inplace way of m[:e1] += m[:e2] works. But I got plent of expressions like e3, e4, e5, e6... which are built upon e1, e2, making every following epression construction inefficient using +=. Will add_to_expression support different combinations of AffExpr and QuadExpr expressions?

Will add_to_expression support different combinations of AffExpr and QuadExpr expressions?

No, because you cannot add a quadratic expression to an affine expression without changing the type of e1.

Just write your code differently:

using JuMP, Ipopt
model = Model(Ipopt.Optimizer)
@variable(model, x[1:2] >= 0)
@expression(model, e1[i in 1:2], i * x[i])
@expression(model, e2[i in 1:2], x[i]^i)
@expression(model, e3[i in 1:2], e1[i] + e2[i])

My general rule of thumb is that if you feel like you are fighting the JuMP syntax, there is probably a better data structure that you could be using. If you post a large snippet of your code, people may have suggestions.

Thanks @odow, I got a large project to maintain so sorry that I can’t po all my codes here till it’s public.

1 Like