Julia:使用JuMP模型变量作为索引

时间:2018-04-15 01:22:26

标签: julia

我正在朱莉娅编写一个程序,它根据约束(围绕它的**)最大化图像块的大小,如下面的代码所示:

using Images, Colors, JuMP, Gurobi
m = Model(solver=GurobiSolver(OutputFlag=0))
Idiff=load("Idiff.png")
a=16; b=16;
Block=Idiff[1:a,1:b]; #initial block size
squareBlock=sum(Block.^2) #sum of squares of block
@variable(m,x>=0,Int) #variable determining size of block in x
@variable(m,y>=0,Int) #variable determining size of block in y
@constraint(m,x<=192,Int)
@constraint(m,y<=144,Int)
**@constraint(m,abs(sum(Idiff[1:x,1:y]).^2-squareBlock)<=.1) #attempt to use 
the variable I am optimizing as an index**
@objective(m,Max,x+y)

当我尝试使用我正在优化的变量作为索引时,我收到一个错误。有没有办法解决这个问题?

1 个答案:

答案 0 :(得分:1)

我不确定你的约束是否正确(似乎不是,但我不是该领域的专家)。

以下是使用MIP求解器和Bin变量的解决方案(我必须生成假数据,因为您没有提供任何来源;我也有CPLEX而不是Gurobi,但这不应该是一个很大的区别):

using JuMP, CPLEX
m = Model(solver=CplexSolver())
mx = 192
my = 144
Idiff = rand(mx, my)
a=16; b=16;
Block=Idiff[1:a,1:b]; #initial block size
squareBlock=sum(Block.^2) #sum of squares of block
@variable(m, xi[1:mx], Bin)
@variable(m, yi[1:my], Bin)
for i in 1:mx-1
    @constraint(m, xi[i] >= xi[i+1])
end
for i in 1:my-1
    @constraint(m, yi[i] >= yi[i+1])
end
@constraint(m,sum(Idiff[i,j]*xi[i]*yi[j] for i in 1:mx for j in 1:my) <= sqrt(squareBlock+0.1))
@constraint(m,sum(Idiff[i,j]*xi[i]*yi[j] for i in 1:mx for j in 1:my) >= sqrt(squareBlock-0.1))
@objective(m,Max,sum(xi)+sum(yi))
solve(m)

然而,对于这个问题(因为它相对较小并且实际上只有2个变量和1个约束),可能更快不使用MIP求解器,而是对{{1的所有可能值进行强力搜索}和x(你可以非常快速地截止,因为关键约束是yx严格增加所以如果你在上面那么。)