-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSimplex Method.py
84 lines (57 loc) · 2 KB
/
Simplex Method.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import math
import numpy as np
def to_tableau(c, A, b):
xb = [eq + [x] for eq, x in zip(A, b)]
z = c + [0]
return xb + [z]
def can_be_improved(tableau):
z = tableau[-1]
return any(x > 0 for x in z[:-1])
def get_pivot_position(tableau):
z = tableau[-1]
column = next(i for i, x in enumerate(z[:-1]) if x > 0)
restrictions = []
for eq in tableau[:-1]:
el = eq[column]
restrictions.append(math.inf if el <= 0 else eq[-1] / el)
row = restrictions.index(min(restrictions))
return row, column
def pivot_step(tableau, pivot_position):
new_tableau = [[] for eq in tableau]
i, j = pivot_position
pivot_value = tableau[i][j]
new_tableau[i] = np.array(tableau[i]) / pivot_value
for eq_i, eq in enumerate(tableau):
if eq_i != i:
multiplier = np.array(new_tableau[i]) * tableau[eq_i][j]
new_tableau[eq_i] = np.array(tableau[eq_i]) - multiplier
return new_tableau
def is_basic(column):
return sum(column) == 1 and len([c for c in column if c == 0]) == len(column) - 1
def get_solution(tableau):
columns = np.array(tableau).T
solutions = []
for column in columns:
solution = 0
if is_basic(column):
one_index = column.tolist().index(1)
solution = columns[-1][one_index]
solutions.append(solution)
return solutions
def simplex(c, A, b):
tableau = to_tableau(c, A, b)
while can_be_improved(tableau):
pivot_position = get_pivot_position(tableau)
tableau = pivot_step(tableau, pivot_position)
return get_solution(tableau)
c = [10, 12.5, 16, 18.8, -5.75, 0, 0]
A = [
[ 1, 1, 0, 0, -5, 0, 0],
[ 0, 0, 1, 1, -2, 0, 0],
[ 0, 0, 0, 0, 1, 1, 0],
[ 0, 0.1, 0, 0.08, 0.05, 0, 1]
]
b = [ 0, 0, 12000, 1000]
solution = simplex(c, A, b)
for i in range(len(solution)):
print('x%d:%d'%(i, round(solution[i])))