2

When trying to run this code Julia keeps giving me the error message "KeyError: key 18=>63 not found" anytime I try to access demand[i]. It seems that this error happens every time the element in dem is larger than 50.

using JuMP, Clp

hours = 1:24

dem = [43 40 36 36 35 38 41 46 49 48 47 47 48 46 45 47 50 63 75 75 72 66 57 50]
demand = Dict(zip(hours, dem))

m = Model(solver=ClpSolver())

@variable(m, x[demand] >= 0) 
@variable(m, y[demand] >= 0)

for i in demand
    if demand[i] > 50
        @constraint(m, y[i] == demand[i])
    else
        @constraint(m, x[i] == demand[i])
    end
end

Not sure how to solve this issue.

mmcook
  • 23
  • 1
  • 3

2 Answers2

1

You are using a Python-style for x in dict. In Julia, this iterates over the key-value pairs of the dictionary, not the keys. Try

for i in keys(demand)
    if demand[i] > 50
        @constraint(m, y[i] == demand[i])
    else
        @constraint(m, x[i] == demand[i])
    end
end

or

for (h, d) in demand
    if d > 50
        @constraint(m, y[h] == d)
    else
        @constraint(m, x[h] == d)
    end
end
Fengyang Wang
  • 11,901
  • 2
  • 38
  • 67
  • Did that just now, but unfortunately a new error saying "Failed attempt to index JuMPArray along dimension 1: 18 ∉ Dict(18=>63,2=>40,16=>47,11=>47,21=>72,7=>41,9=>49,10=>48,19=>75,17=>50,8=>46,22=>66,6=>38,24=>50,4=>36,3=>36,5=>35,20=>75,23=>57,13=>48,14=>46,15=>45,12=>47,1=>43)" came up. I got a similar message previously when trying to iterate over array before using a dictionary. – mmcook Oct 06 '18 at 04:51
  • As hesham_EE mentioned in their answer, you also need to construct your JuMP arrays using a key iterator instead of the dictionary itself. (The lines `@variable(m, x[demand] >= 0)`) – Fengyang Wang Oct 06 '18 at 22:39
0

This worked for me, using Julia 1.0

using JuMP, Clp

hours = 1:24

dem = [43 40 36 36 35 38 41 46 49 48 47 47 48 46 45 47 50 63 75 75 72 66 57 50]
demand = Dict(zip(hours, dem))

m = Model()
setsolver(m, ClpSolver())

@variable(m, x[keys(demand)] >= 0)
@variable(m, y[keys(demand)] >= 0)

for (h, d) in demand
    if d > 50
        @constraint(m, y[h] == d)
    else
        @constraint(m, x[h] == d)
    end
end

status = solve(m)

println("Objective value: ", getobjectivevalue(m))
println("x = ", getvalue(x))
println("y = ", getvalue(y))

REF:

  1. Reply of @Fengyang Wang
  2. Comment of @Wikunia at https://stackoverflow.com/a/51910619/1096140
  3. https://jump.readthedocs.io/en/latest/quickstart.html
hesham_EE
  • 1,125
  • 13
  • 24