Skip to content

Instantly share code, notes, and snippets.

@juanplopes
Created November 3, 2016 00:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juanplopes/da9a63563e594ca6fea2e4b4984a58bb to your computer and use it in GitHub Desktop.
Save juanplopes/da9a63563e594ca6fea2e4b4984a58bb to your computer and use it in GitHub Desktop.
Generates ILP problem to be solved by glpsol
from collections import defaultdict
def name1(i):
return chr(ord('A')+i)
def name2(x, n):
return ''.join(name1(i) for i in xrange(n) if x&(1<<i))
def print_model(L, U, n, G):
for x in range(1, 2**n):
print 'var c{}, integer, >=0;'.format(name2(x, n))
print
for i in range(n):
for j in range(i+1, n):
a, b = U if G[i][j] else L
mult = -1 if G[i][j] else 1
line = []
for x in range(2**n):
coeff = 0
if x&(1<<i) and x&(1<<j): coeff += mult * b
if x&(1<<i) or x&(1<<j): coeff -= mult * a
line.append(coeff)
expr = ' + '.join('{}*c{}'.format(x, name2(i, n)) for i,x in enumerate(line) if x)
print "s.t. s{}{}: {} <= 0;".format(name1(i), name1(j), expr)
print
for i in range(n):
expr = ' + '.join('c{}'.format(name2(x, n)) for x in range(2**n) if x&(1<<i))
print "s.t. m{}: {} >= 1;".format(name1(i), expr)
print
print "minimize z: {};".format(' + '.join('c' + name2(x, n) for x in range(1, 2**n)))
print
print 'solve;'
print 'end;'
N = 6
G = defaultdict(lambda: defaultdict(lambda: False))
for i in range(0, 3):
for j in range(3, 6):
G[i][j] = G[j][i] = True
print_model((1,3), (1,2), N, G)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment