Julia - 在@variable 和@constraint 表达式中按名称访问 Dict 值

Julia - accessing Dict values by name in @variable and @constraint expressions

我想知道是否可以在表达式中按名称访问 Dict 值,例如:

@objective(
    premex,
    Min,
    sum((u["cap"] - PRODAMOUNT[op, u, t]) * u["util_cost1"]
        for op in _ORDER_PRODUCTS, u in UNITS, t in TIME))

_ORDER_PRODUCTS:

Dict{String,Dict{String,Any}}("o18-p25" => Dict("order" => "o18","value" => 3000.0f0,"product" => "p25"),"o18-p36" => Dict("order" => "o18","value" => 63.0f0,"product" => "p36"),"o23-p39" => Dict("order" => "o23","value" => 204.75f0,"product" => "p39"),"o16-p32" => Dict("order" => "o16","value" => 336.0f0,"product" => "p32"),"o22-p37" => Dict("order" => "o22","value" => 50.0f0,"product" => "p37"),"o1-p5" => Dict("order" => "o1","value" => 60.0f0,"product" => "p5"),"o11-p28" => Dict("order" => "o11","value" =....

单位:

UNITS = Dict(["CINTAS" => Dict(["cap" => 1000, "mincap" => 50, "dcap" => 24830, "util_cost1" => 1000, "maxprodr" => 24830]), "BUHLER1" => Dict(["cap" => 1500, "mincap" => 60, "dcap" => 37245, "util_cost1" => 1000, "maxprodr" => 37245]), ...

当我 运行 这个时,我得到了一个错误:

错误:LoadError:MethodError:没有方法匹配 getindex(::Pair{String,Dict{String,Integer}},::String)

当我将 u["cap"] 替换为一个数字时,它起作用了。

自己找到答案(...):

    @variable(premex, PRODAMOUNT[op in keys(_ORDER_PRODUCTS), u in keys(UNITS), t in TIME])

    @objective(
        premex,
        Min,
        sum((u["cap"] - PRODAMOUNT[key1, key2, t]) * u["util_cost1"]
            for (key1, op) in _ORDER_PRODUCTS, (key2, u) in UNITS, t in TIME
                ))

有 3 个因素需要注意:

  1. 不能用字典对象索引变量,所以它必须是 Int 或 String
  2. 这是遍历 Dict 的方法:for (key1, op) in _ORDER_PRODUCTS
  3. 这是只获取索引变量键的方法:op in keys(_ORDER_PRODUCTS)