Last active
December 29, 2015 20:29
-
-
Save maraigue/7723525 to your computer and use it in GitHub Desktop.
An example of solving mixed integer programming by rglpk (Ruby interface for GLPK)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "rglpk" | |
# An example of solving mixed integer programming by rglpk (Ruby interface for GLPK) | |
# Original C-language-version by Masahiro Sakai | |
# https://gist.github.com/msakai/2450935/32efeace1ce27b2259b9792e8731436d7b0bb523 | |
# | |
# rglpk must be installed | |
# https://en.wikibooks.org/wiki/GLPK/Ruby | |
# Maximize | |
# obj: x1 + 2 x2 + 3 x3 + x4 | |
# Subject To | |
# c1: - x1 + x2 + x3 + 10 x4 <= 20 | |
# c2: x1 - 3 x2 + x3 <= 30 | |
# c3: x2 - 3.5 x4 = 0 | |
# Bounds | |
# 0 <= x1 <= 40 | |
# 2 <= x4 <= 3 | |
# General | |
# x4 | |
# End | |
p = Rglpk::Problem.new | |
p.name = "sample" | |
p.obj.dir = Rglpk::GLP_MAX | |
rows = p.add_rows(3) | |
rows[0].name = "c1" | |
rows[0].set_bounds(Rglpk::GLP_DB, 0.0, 20.0) | |
rows[1].name = "c2" | |
rows[1].set_bounds(Rglpk::GLP_DB, 0.0, 30.0) | |
rows[2].name = "c3" | |
rows[2].set_bounds(Rglpk::GLP_FX, 0.0, 0.0) | |
cols = p.add_cols(4) | |
cols[0].name = "x1" | |
cols[0].set_bounds(Rglpk::GLP_DB, 0.0, 40.0) | |
cols[1].name = "x2" | |
cols[1].set_bounds(Rglpk::GLP_LO, 0.0, 0.0) | |
cols[2].name = "x3" | |
cols[2].set_bounds(Rglpk::GLP_LO, 0.0, 0.0) | |
cols[3].name = "x4" | |
cols[3].set_bounds(Rglpk::GLP_DB, 2.0, 3.0) | |
cols[3].kind = Rglpk::GLP_IV | |
p.obj.coefs = [1.0, 2.0, 3.0, 1.0] | |
p.set_matrix([ | |
-1.0, 1.0, 1.0, 10.0, | |
1.0, -3.0, 1.0, 0.0, | |
0.0, 1.0, 0.0, -3.5 | |
]) | |
p.mip("presolve" => Rglpk::GLP_ON) | |
z = p.obj.mip | |
x1 = cols[0].mip_val | |
x2 = cols[1].mip_val | |
x3 = cols[2].mip_val | |
x4 = cols[3].mip_val | |
printf("z = %g; x1 = %g; x2 = %g; x3 = %g; x4 = %g\n", z, x1, x2, x3, x4) | |
#=> z = 122.5; x1 = 40; x2 = 10.5; x3 = 19.5, x4 = 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment