-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprogassgn1.py
70 lines (55 loc) · 1.78 KB
/
progassgn1.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# solves *bounded* LPs of the form:
# max cx
# sub to: Ax <= b
from sympy import *
from itertools import combinations
# enumerates all the vertices of {x | Ax <= b}
def enumeratevertices(A, b):
m, n = A.rows, A.cols
for rowlist in combinations(range(m), n):
Ap = A.extract(rowlist, range(n))
bp = b.extract(rowlist, [0])
if Ap.det() !=0:
xp = Ap.LUsolve(bp)
d = A * xp - b
feasible = True
for i in range(m):
if d[i] > 0:
feasible = False
if feasible:
yield xp
# finds the optimum using vertex enumeration
def findoptimum(A, b, c):
m, n = A.rows, A.cols
bestvalue, bestvertex = None, None
for vertex in enumeratevertices(A, b):
if bestvalue is None or (vertex.T * c)[0] > bestvalue:
bestvalue = (vertex.T * c)[0]
bestvertex = vertex
return bestvertex
def solve(A, b, c):
x = findoptimum(A, b, c)
if not x:
print 'LP is infeasible'
else:
print 'Vertex', x.T, 'is optimal'
print 'Optimal value is', (c.T * x)[0]
if __name__ == '__main__':
# small example
A = Matrix([[-10, -6, -9, -10],
[ 8, -6, -5, -5],
[ -7, -1, -9, 3],
[ -1, -4, 5, 10],
[ 1, 2, 0, 10],
[ 2, -9, 3, -8],
[ -8, -1, -8, 1],
[ 7, -10, 4, -4],
[-10, 2, 5, 8],
[ -7, 9, 4, -4],
[ -1, 0, 0, 0],
[ 0, -1, 0, 0],
[ 0, 0, -1, 0],
[ 0, 0, 0, -1]])
b = Matrix([9, 7, 3, 4, 8, 0, 3, 2, 4, 8, 0, 0, 0, 0])
c = Matrix([2, -2, -3, 8])
solve(A, b, c)