Write expressions in JuMP model based on condition

Hi @mast-lfl, welcome to the forum.

Correct. You cannot define an expression with the same name twice. Take a read of Variables · JuMP (it is in the variables, section, but it applies equally to expressions).

One approach would be to write your model as:

@expression(
    model,
    ex[p=P, t=T],
    if p in P_1
        I[p,t] * 5
    else
        I[p,t] * 7
    end,
)

Another approach would be:

@expression(model, ex[p=P, t=T], I[p,t] * (p in P_1 ? 5 : 7))

Another approach would be:

data = Dict("a" => 5, "b" => 5, "c" => 5, "d" => 7, "e" => 7)
@expression(model, ex[p=P, t=T], I[p,t] * data[p])

This hints at the strength and weakness of JuMP: we are flexible in how to write things, but because there is more than one way it can be hard to know (or document) what is the “best.” The answer is problem-dependent.

1 Like