3

I'm trying to solve the simple example found in https://en.wikipedia.org/wiki/Integer_programming#Example using the CVXOPT library on Python 2.7 ; The optimal answers are either (1,2) or (2,2). I'm getting (0.0 , 0.0). What am I doing wrong in the code below ? Thanks !

import numpy as np
import cvxopt
from cvxopt import glpk

c=cvxopt.matrix([0,-1]) #-1 since we're maximising the 2nd variable
G=cvxopt.matrix([[-1,1],[3,2],[2,3],[-1,0],[0,-1]],tc='d')
h=cvxopt.matrix([1,12,12,0,0],tc='d')
(status, x)=glpk.ilp(c,G.T,h,B=set([0,1]))
print status
print x[0],x[1]    #should be (1,2) or (2,2)
print sum(c.T*x)

2 Answers 2

6

Your code is basically correct but needs two minor modifications:

  1. The c-vector must be a double, too.
  2. The variables x[0] and x[1] are supposed to be integer, not binary.

Then, a working solution is given by:

import numpy as np
import cvxopt

c=cvxopt.matrix([0,-1],tc='d')
G=cvxopt.matrix([[-1,1],[3,2],[2,3],[-1,0],[0,-1]],tc='d')
h=cvxopt.matrix([1,12,12,0,0],tc='d')
(status, x)=cvxopt.glpk.ilp(c,G.T,h,I=set([0,1]))
print status
print x[0],x[1] 
print sum(c.T*x)
Sign up to request clarification or add additional context in comments.

1 Comment

Right, thanks, the variables x[0] (formerly x) and x[1] (formerly y) have been named more appropriately.
0

Update for Python 3.8.8

from cvxopt.glpk import ilp
import numpy as np
from cvxopt import matrix
c=matrix([0,-1],tc='d')
G=matrix([[-1,1],[3,2],[2,3],[-1,0],[0,-1]],tc='d')
h=matrix([1,12,12,0,0],tc='d')
(status, x)=ilp(c,G.T,h,I=set([0,1]))
print (status)
print (x[0],x[1])
print (sum(c.T*x))

Calling:

cvxopt.glpk.ilp(c,G.T,h,I=set([0,1]))

returns: module 'cvxopt' has no attribute 'glpk'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.