-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSimplex.py
116 lines (82 loc) · 2.86 KB
/
Simplex.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
import numpy as np
from pandas import DataFrame as pdData
import math
SIZE_MATRIX_X = 1
SIZE_MATRIX_Y = 6
def generate_tabinitial(A, b, c):
[m, n] = A.shape
if m != b.size:
print()
exit(1)
if n != c.size:
print()
exit(1)
result = np.column_stack((A, b))
result = np.append(result, np.column_stack((c, 0)), axis=0)
return range(n, n + m), result
def generate_tabinitial_withID(A, b, c):
m, n = A.shape
rng, tabinitial = generate_tabinitial(A, b, c)
identity = np.vstack((np.identity(m), np.zeros(m)))
return rng, np.concatenate((tabinitial, identity), axis=1)
def positive(v):
return all(v >= 0), np.amin(v), np.where(v == np.amin(v))
def init(tab, A):
m, n = A.shape
opt = -tab[m, n]
tab_b = tab[:m, n]
tab_c = np.concatenate((tab[m , 0:n]
,tab[m , n + 1:]))
tab_A = np.hstack((tab[0:m ,0:n ]
,tab[ 0:m , n + 1 :]))
return opt, tab_b, tab_c, tab_A
def index_smallest_pos(v):
return np.where(v > 0, v, np.inf).argmin()
def rapportmin(a, b, m):
out = []
for i in range(0, m-1):
if b[i] != 0:
out.append(a[i] / b[i])
return index_smallest_pos(np.array(out))
def resolution(tab, A, c):
opt, tab_b, tab_c, tab_A = init(tab, A)
m, n = tab.shape
sign, minimum, index_min = positive(tab_c)
if (index_min[0] > c.size).all():
index_min = list(index_min)
index_min[0] += 1
index_min = tuple(index_min)
tab = tab.astype(np.float32)
if sign:
return tab_b, opt
else:
if all(tab[:,index_min] <= 0):
print()
exit(1)
else:
A_s = tab[:A.shape[0],index_min]
index_pivot = rapportmin(tab_b, A_s, m)
ligne_pivot = tab[index_pivot]
colonne_pivot = tab[:,index_min]
pivot = tab[index_pivot,index_min]
tab[index_pivot] = ligne_pivot / float(pivot)
for i in range(0, len(tab)):
if not np.array_equal(tab[i], tab[index_pivot]):
tab[i] = tab[i] - tab[index_pivot] * tab[i, index_min]
print("\n",pdData(tab))
return resolution(tab, A, c)
if __name__ == '__main__':
c = [[-3,-4,0,0,1]]
A = [
[1,1,1,0,0],
[2,1,0,1,0]
]
b = [4,5]
(c, A, b) = map(lambda t: np.array(t), [c, A, b])
range_tab1, tab_initail1 = generate_tabinitial_withID(A, b, c)
data_frame1 = pdData(tab_initail1)
print()
print(data_frame1)
x, y = resolution(tab_initail1, A, c)
print('Optimal Solution', abs(y))
print('X', x,)