Search code examples
juliajulia-jumpijulia-notebook

Julia Key Error when accessing a value in dictionary


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.


Solution

  • 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