# How to implement a piece-wise defined function in JuMP

I have an optimization problem simplified as:

function α(x)
global Lmin, Lnom, Lmax, α_0 # values calculated outside
a = 0.0019727939
b = 0.0078887
if Lmin <= x < Lnom
return a * (x-Lnom)^2 + α_0
elseif Lnom <= x <= Lmax
return (b * (x-Lnom)^2 + α_0)
end
end

model = Model(Ipopt.Optimizer)
@variable(model, Lmax>=x[1:2]>=Lmin)
@constraint(model, sum(x)==1)
@objective(model, Min, α(x))
optimize!(model)
I have two decision variables: x, x.
How to implement α(x) in JuMP and solve this optimization?

You probably will want to see this section and links therein, but the `if...else` may further complicate your model. Can’t you eliminate it somehow?

2 Likes

Can you write it as a single expression with a dummy variable?

``````(a*(x<Lnom) + b*(x>=Lnom)) *(x-Lnom)^2 + α_0
``````

EDIT: Also it looks like `x` is a vector but your objective function is treating it as a scalar so I’m not certain you’re giving a clear picture of your actual problem.

1 Like

Option 1:

``````using JuMP, Ipopt
α_0 = 1.0
Lmin = -1.0
Lnom = 0.0
Lmax = 1.0
a = 0.0019727939
b = 0.0078887

model = Model(Ipopt.Optimizer)
@variable(model, Lmin <= x[1:2] <= Lmax)
@constraint(model, sum(x) == 1)
@NLobjective(
model,
Min,
ifelse(
x < Lnom,
a * (x-Lnom)^2 + α_0,
b * (x-Lnom)^2 + α_0,
),
)
optimize!(model)
``````

Option 2:

``````using JuMP, Ipopt
Lmin = -1.0
Lmax = 1.0
function α(x...)
α_0 = 1.0
Lnom = 0.0
a = 0.0019727939
b = 0.0078887
if Lmin <= x < Lnom
return a * (x-Lnom)^2 + α_0
else
return (b * (x-Lnom)^2 + α_0)
end
end
model = Model(Ipopt.Optimizer)
@variable(model, Lmin <= x[1:2] <= Lmax)
@constraint(model, sum(x) == 1)
register(model, :α, 2, α; autodiff = true)
@NLobjective(model, Min, α(x...))
optimize!(model)
``````
2 Likes

`(a*(x<Lnom) + b*(x>=Lnom)) *(x-Lnom)^2 + α_0`

You can’t write expressions like this in JuMP, but also yes, there are some vector/scalar problems going on.

2 Likes

In my problem I have several decision variables, in the small example I
mean decision variables: x and x.

Hello, can you help to clarify the vector/scalar problem? In the example, I have two decision variables: x, x. This is what I needed.

Thank you very much for the two examples. I will adapt them in my program.

Hello. Thank you for the reply. I will read the document.