# New to Jump and Julia

Hey all,
I am trying to programm a simple optimization problem which minimizes the cost of a of an energy system with 4 suppliers subject to capacitiy constraints for 6 periods.

The costs are for each period are: costs = Dict(
“A” => [1.0,1.0,1.0,1.0,1.0,1.0],
“B” => [2.0,2.0,2.0,2.0,2.0,2.0],
“C” => [1.0,1.0,1.0,1.0,1.0,1.0],
“D” => [2.0,2.0,2.0,2.0,2.0,2.0],
)

The capacity contraints for each period are:
cap = Dict(
“A” => [1.0,2.0,1.0,0.0,0.0,0.0],
“B” => [2.0,1.0,2.0,0.0,0.0,0.0],
“C” => [0.0,0.0,0.0,1.0,2.0,1.0],
“D” => [0.0,0.0,0.0,2.0,1.0,2.0],

generator = keys(costs)
# Variables
@variable(dispatch_model, 0 <= y[generator],Int)

``````# Objective Function
@objective(dispatch_model,Min,
sum(costs[g]*y[g] for g in generator)
)
``````

# capacity constraint:

@constraint(dispatch_model, cap[g in generator], (y[g] for g in generator) .<=cap[g] )

I could write the capacity constraint for each generator, like:
@constraint(dispatch_model, y[“A”].<= cap[“A”])
@constraint(dispatch_model, y[“B”].<= cap[“B”])

but I would prefer to only specify one constraint by looping through the cap dictionary, how do I achieve that in Julia?

2 Likes

Here’s how I would write your model

``````costs = Dict(
"A" => [1.0,1.0,1.0,1.0,1.0,1.0],
"B" => [2.0,2.0,2.0,2.0,2.0,2.0],
"C" => [1.0,1.0,1.0,1.0,1.0,1.0],
"D" => [2.0,2.0,2.0,2.0,2.0,2.0],
)

cap = Dict(
"A" => [1.0,2.0,1.0,0.0,0.0,0.0],
"B" => [2.0,1.0,2.0,0.0,0.0,0.0],
"C" => [0.0,0.0,0.0,1.0,2.0,1.0],
"D" => [0.0,0.0,0.0,2.0,1.0,2.0],
)

model = Model()
@variable(model, 0 <= y[g in keys(cap)] <= cap[g], Int)
@objective(model, Min, sum(c * y[g] for (c, g) in costs))
``````

You can loop over constraints like

``````@constraint(model, [g in keys(cap)], y[g] <= cap[g])
``````

but you can also just use a for loop

``````for (key, value) in cap
@constraint(model, y[key] <= value)
end
``````

If you’re new to JuMP, here’s a good place to get started:

If you’re interested in power systems, you might want to read:

2 Likes

p.s., I moved your question to the “Optimization (Mathematical)” section, which is where we try to keep JuMP-related questions.

2 Likes

I run the above code, but some errors happened.

Oops. I guess I should have tried to run the code. the issue is that `cap[g]` is a vector, so perhaps the original author meant to include a time dimension. This works:

``````costs = Dict(
"A" => [1.0,1.0,1.0,1.0,1.0,1.0],
"B" => [2.0,2.0,2.0,2.0,2.0,2.0],
"C" => [1.0,1.0,1.0,1.0,1.0,1.0],
"D" => [2.0,2.0,2.0,2.0,2.0,2.0],
)

cap = Dict(
"A" => [1.0,2.0,1.0,0.0,0.0,0.0],
"B" => [2.0,1.0,2.0,0.0,0.0,0.0],
"C" => [0.0,0.0,0.0,1.0,2.0,1.0],
"D" => [0.0,0.0,0.0,2.0,1.0,2.0],
)

model = Model()
@variable(model, 0 <= y[g in keys(cap), t=1:6] <= cap[g][t], Int)
@objective(model, Min, sum(sum(c[t] * y[g, t] for t in 1:6) for (g, c) in costs))
``````
2 Likes

Thx, odow, the code you provided worked. I understand the right syntax is the bounds cannot be a vector but an element.

1 Like