1

在尝试运行此代码时,只要我尝试访问需求 [i],Julia 就会不断给我错误消息“KeyError: key 18=>63 not found”。似乎每次 dem 中的元素大于 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

不知道如何解决这个问题。

4

2 回答 2

1

您正在使用 Python 风格的for x in dict. 在 Julia 中,这会迭代字典的键值对,而不是键。尝试

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

或者

for (h, d) in demand
    if d > 50
        @constraint(m, y[h] == d)
    else
        @constraint(m, x[h] == d)
    end
end
于 2018-10-06T04:43:44.417 回答
0

这对我有用,使用 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))

参考:

  1. @Fengyang Wang 的回复
  2. @Wikunia 在https://stackoverflow.com/a/51910619/1096140的评论
  3. https://jump.readthedocs.io/en/latest/quickstart.html
于 2018-10-06T05:50:42.103 回答