Julia JuMP 优化错误中的错误生成器

error generator in Julia JuMP optimization error

我正在将 julia 0.6 中的代码转换为 1.2。 这是旧版本:

@variable(model, use[i=eachindex(n), j=1:m], Bin)

Used  = [indmax(getvalue(use[i,j])
                           for j=1:m) for i=eachindex(n)]

我转换成下面的,

@variable(model, use[i=eachindex(n), j=1:m], Bin)

JuMP.optimize!(model)
Used = [argmax(JuMP.value(use[i,j])
                    for j=1:m) for i=eachindex(n)]

但有错误:

MethodError: no method matching keys(::Base.Generator{UnitRange{Int64},getfield(Main, Symbol("##261#266")){Int64,JuMP.Containers.SparseAxisArray{VariableRef,2,Tuple{Any,Any}}}})
Closest candidates are:
  keys(!Matched::Core.SimpleVector) at essentials.jl:606
  keys(!Matched::Cmd) at process.jl:963
  keys(!Matched::BenchmarkTools.BenchmarkGroup) at /Users/shuaiwang/.julia/packages/BenchmarkTools/7aqwe/src/groups.jl:31
  ...
pairs(::Base.Generator{UnitRange{Int64},getfield(Main, Symbol("##261#266")){Int64,JuMP.Containers.SparseAxisArray{VariableRef,2,Tuple{Any,Any}}}}) at abstractdict.jl:132
_findmax(::Base.Generator{UnitRange{Int64},getfield(Main, Symbol("##261#266")){Int64,JuMP.Containers.SparseAxisArray{VariableRef,2,Tuple{Any,Any}}}}, ::Colon) at array.jl:2068
findmax(::Base.Generator{UnitRange{Int64},getfield(Main, Symbol("##261#266")){Int64,JuMP.Containers.SparseAxisArray{VariableRef,2,Tuple{Any,Any}}}}) at array.jl:2065
argmax(::Base.Generator{UnitRange{Int64},getfield(Main, Symbol("##261#266")){Int64,JuMP.Containers.SparseAxisArray{VariableRef,2,Tuple{Any,Any}}}}) at array.jl:2153
(::getfield(Main, Symbol("##260#265")){ScenarioGraph,JuMP.Containers.SparseAxisArray{VariableRef,2,Tuple{Any,Any}}})(::Int64) at none:0
iterate at generator.jl:47 [inlined]
collect at array.jl:606 [inlined]

问题似乎与 JuMP 无关。您的代码的修复是:

Used = [argmax([JuMP.value(use[i,j]) for j=1:m]) for i=eachindex(n)]

(我没有测试整个代码,因为它不完整)

问题的核心是你不能在生成器上使用argmax,你必须传递一个支持pairs的集合给它,例如:

julia> argmax(i for i in 1:3)
ERROR: MethodError: no method matching keys(::Base.Generator{UnitRange{Int64},getfield(Main, Symbol("##15#16"))})

失败,但是

julia> argmax([i for i in 1:3])
3

julia> argmax((1,2,3))
3

julia> argmax((a=1,b=2,c=3))
:c

julia> argmax(Dict(:a=>1,:b=>2,:c=>3))
:c

工作