julia - 无法访问 JuMP.variable 的第一个元素
问题描述
我有一个线性规划优化的代码,我想在另一个代码中使用它,目前,BoundsError
当我从代码中调用一个函数时,我正在努力修复一个函数:
using JuMP
function scan_maker(A)
m = JuMP.Model(solver=ClpSolver(PrimalTolerance=1e-3, DualTolerance=1e-3, InfeasibleReturn=1, PresolveType=1))
# m = Model(solver=GurobiSolver())
level = size(A, 2)
v = zeros(Int, level)
ub = zeros(Int, level)
lb = zeros(Int, level)
@variable(m, x[1:level])
@constraint(m, con, A*x.>=0)
function setc(c)
for i = 1:size(A, 1)
m.linconstr[i].lb = float(c[i])
end
end
function scan(c::Channel)
i = 1
init = 1
while i > 0
if i >= init
@objective(m, Max, x[i])
res = JuMP.solve(m, suppress_warnings=true)
if res==:Optimal || res==:Unbounded
ub[i] = round(Int, getvalue(x[i]))
setobjectivesense(m, :Min)
res = JuMP.solve(m, suppress_warnings=true)
@assert res==:Optimal || res==:Unbounded
lb[i] = round(Int, getvalue(x[i]))
v[i] = lb[i]
init += 1
else
@assert res==:Infeasible
i -= 1
continue
end
elseif v[i] < ub[i]
v[i] += 1
else
setupperbound(x[i], Inf)
setlowerbound(x[i], -Inf)
init -= 1
i -= 1
continue
end
if i >= level
put!(c, v)
continue
else
setupperbound(x[i], v[i])
setlowerbound(x[i], v[i])
i += 1
end
end
close(c)
end
return setc, scan
end
现在这段代码正在按我想要的方式工作,但是当我scan
从这段代码调用函数到下面这个函数中的另一个文件时:
function prob(na)
@assert count(!iszero, ui2*na) == 0
b = T0*na
setc(-b)
total = 0.0
for x in Channel(scan)
nab = vi2*x + b #the photon numbers for each item in the sum
total += prod([c.^complex(n)/factorial(n) for (c, n) in zip(coef, nab)])
end
return abs(total*omega)^2
end
之后我调用函数:prob(200)
它向我显示了这个错误:
BoundsError: attempt to access 0-element Array{JuMP.Variable,1} at index [1]
我知道在prob
函数的这个表达式中引发了错误:nab = vi2*x + b
并且它正是在x
我在这篇文章中放入的第一个函数中创建的变量中:@variable(m, x[1:level])
,但是我被困在如何解决这个问题上。要检查我遇到此问题的更多功能,您可以检查此链接:在此处输入链接描述
解决方案
虽然您的问题太长(远离 MWE - 最小的工作示例)并且不清楚,但让我们假设您想使用 JuMP 处理数组变量。这是一个最小的例子:
using JuMP
using GLPK
m = Model(with_optimizer(GLPK.Optimizer))
@variable(m, x[1:2] >= 0)
@constraint(m, x[1]+2x[2] <= 100)
@objective(m, Max, 3x[1]+7x[2])
optimize!(m)
现在让我们得到结果
julia> println(m)
Max 3 x[1] + 7 x[2]
Subject to
x[1] + 2 x[2] <= 100.0
x[1] >= 0.0
x[2] >= 0.0
julia> value.(x)
2-element Array{Float64,1}:
0.0
50.0
如果你想得到 x[2] 的值,你只需写value(x[2])
推荐阅读
- c++ - 出现在向量中最接近整数 x 的数字
v1 必须先打印 - json - PUT request in iOS (Swift) with JSONSerialization
- algorithm - 获取排列计数
- javascript - 无论大小写如何,如何检查关键字是否存在?
- c# - 取消令牌引发异常。无法捕获 OperationCanceledException。我得到了用户未处理
- javascript - 比较两个对象数组以获得不同的结果
- css - 单击时关闭纯 CSS Hamburger 菜单
- c# - 使用 c# Interop.domino.dll 使用管理员帐户创建 NotesSession
- reactjs - 如何根据元素的索引在嵌套查询的结果中设置@client 变量
- salesforce-chatter - Salesforce 中 ConnectAPI 的测试类?