I would like to use a GLPK linear programming model in Ruby using the Rglpk wrapper.
Unfortunately, I do not get the same solution when comparing the glpk and Rglpk outputs. Despite I am setting the column kind to Binary (cols.kind = Rglpk::GLP_BV), the solution shows integer values instead of boolean.
Maximize NPV of projects (x1…x5) by taking into account Budget and Resource constraints (c1, c2). Solution can only be 0 or 1
The model is rather simple, but somehow I am missing something in the ruby code.
require 'rglpk'
p = Rglpk::Problem.new
p.name = "Project selection"
p.obj.dir = Rglpk::GLP_MAX
rows = p.add_rows(2)
rows[0].name = "p"
rows[0].set_bounds(Rglpk::GLP_UP, 0, 800)
rows[1].name = "q"
rows[1].set_bounds(Rglpk::GLP_UP, 0, 200)
cols = p.add_cols(5)
cols[0].name = "x1"
cols[0].kind = Rglpk::GLP_BV
cols[0].set_bounds(Rglpk::GLP_BV, 0, 1)
cols[1].name = "x2"
cols[1].kind = Rglpk::GLP_BV
cols[1].set_bounds(Rglpk::GLP_BV, 0, 1)
cols[2].name = "x3"
cols[2].kind = Rglpk::GLP_BV
cols[2].set_bounds(Rglpk::GLP_BV, 0, 1)
cols[3].name = "x4"
cols[3].kind = Rglpk::GLP_BV
cols[3].set_bounds(Rglpk::GLP_BV, 0, 1)
cols[4].name = "x5"
cols[4].kind = Rglpk::GLP_BV
cols[4].set_bounds(Rglpk::GLP_BV, 0, 1)
p.obj.coefs = [928, 908, 801, 543, 944]
p.set_matrix([
398, 151, 129, 275, 291,
111, 139, 56, 54, 123
])
p.simplex
z = p.obj.get
x1 = cols[0].get_prim
x2 = cols[1].get_prim
x3 = cols[2].get_prim
x4 = cols[3].get_prim
x5 = cols[4].get_prim
printf("z = %g; x1 = %g; x2 = %g; x3 = %g; x4 = %g; x5 = %g\n", z, x1, x2, x3, x4, x5)
————————————————————————————
2) glpk in mathprog format (returns CORRECT solution):
————————————————————————————
set PROJECT;
param Budget {i in PROJECT};
param Resources {i in PROJECT};
param NPV {i in PROJECT};
var x {i in PROJECT} >=0, binary;
maximize z: sum{i in PROJECT} NPV[i]*x[i];
s.t. Bud : sum{i in PROJECT} Budget[i]*x[i] <= 800;
s.t. Res : sum{i in PROJECT} Resources[i]*x[i] <= 200;
data;
set PROJECT := p1 p2 p3 p4 p5;
param Budget:=
p1 398
p2151
p3129
p4275
p5291;
param Resources:=
p1111
p2139
p356
p454
p5123;
param NPV:=
p1928
p2908
p3801
p4543
p5944;
end;
————————————————————————————