使用RGLPK进行整数编程

时间:2015-10-24 14:22:01

标签: ruby rubygems linear-programming

我试图使用rglpk gem(https://github.com/wtaysom/rglpk)来解决整数约束的优化问题。自述文件给出了使用gem来解决线性编程问题的一个例子(简单 - 没有整数约束)。如果解决方案被强制为全部整数,有谁知道如何修改示例来解决问题?

宝石似乎支持MIP解决,但我似乎无法让它发挥作用。以下是我尝试过的,没有成功。它产生了这个输出:

  

glp_intopt:未提供初始LP松弛的最佳基础

     

z = 0; x1 = 0; x2 = 0; x3 = 0

以下是我尝试修改它的示例:

# maximize
#   z = 10 * x1 + 6 * x2 + 4 * x3
#
# subject to
#   p:      x1 +     x2 +     x3 <= 100
#   q: 10 * x1 + 4 * x2 + 5 * x3 <= 600
#   r:  2 * x1 + 2 * x2 + 6 * x3 <= 300
#
# where all variables are non-negative AND INTEGERS
#   x1 >= 0, x2 >= 0, x3 >= 0
#  
#
p = Rglpk::Problem.new
p.name = "sample"
p.obj.dir = Rglpk::GLP_MAX

rows = p.add_rows(3)
rows[0].name = "p"
rows[0].set_bounds(Rglpk::GLP_UP, 0, 100)
rows[1].name = "q"
rows[1].set_bounds(Rglpk::GLP_UP, 0, 600)
rows[2].name = "r"
rows[2].set_bounds(Rglpk::GLP_UP, 0, 300)

cols = p.add_cols(3)
cols[0].name = "x1"
cols[0].set_bounds(Rglpk::GLP_LO, 0.0, 0.0)
cols[0].kind = Rglpk::GLP_IV #Force variable to be integer in solution
cols[1].name = "x2"
cols[1].set_bounds(Rglpk::GLP_LO, 0.0, 0.0)
cols[0].kind = Rglpk::GLP_IV
cols[2].name = "x3"
cols[2].set_bounds(Rglpk::GLP_LO, 0.0, 0.0)
cols[0].kind = Rglpk::GLP_IV

p.obj.coefs = [10, 6, 4]

p.set_matrix([
                 1, 1, 1,
                 10, 4, 5,
                 2, 2, 6
             ])

p.mip
z = p.obj.mip
x1 = cols[0].mip_val
x2 = cols[1].mip_val
x3 = cols[2].mip_val

printf("z = %g; x1 = %g; x2 = %g; x3 = %g\n", z, x1, x2, x3)
#=> z = 733.333; x1 = 33.3333; x2 = 66.6667; x3 = 0

0 个答案:

没有答案