-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSimplex.py
More file actions
294 lines (251 loc) · 9.31 KB
/
Copy pathSimplex.py
File metadata and controls
294 lines (251 loc) · 9.31 KB
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
import numpy as np
import matplotlib.pyplot as plt
class simplex:
def __init__(self, num_of_variables=0):
self.num_of_vars = num_of_variables
self.A = []
self.c = np.array([])
self.b = np.array([])
def constraint(self, input_list, b):
if len(input_list) != self.num_of_vars:
raise TypeError('constraint should be of length inputs + b')
self.A.append(input_list)
self.b = np.append(self.b, b)
def objective(self, input_list):
if input_list.shape[0] != self.num_of_vars:
raise TypeError('objective should be of length inputs')
self.c = input_list
def compute(self):
Print = False
self.A = np.array(self.A)
if self.A.shape[0] == 0 or self.c.shape[0] == 0 or self.b.shape[0] == 0:
raise TypeError('one of the inputs is not defined')
if Print:
print('A', self.A)
print('b', self.b)
print('c', self.c)
non_basic = np.array([i for i in range(self.num_of_vars - self.A.shape[0])])
basic = np.array([i for i in range(self.num_of_vars - self.A.shape[0], self.num_of_vars, 1)])
if Print:
print('non_basic', non_basic)
print('basic', basic)
iteration = 0
### Loop
while True:
B = []
N = []
for c in range(self.A.shape[0]):
temp1 = []
temp2 = []
for b in basic:
temp1.append(self.A[c][b])
for n in non_basic:
temp2.append(self.A[c][n])
B.append(temp1)
N.append(temp2)
B = np.array(B)
N = np.array(N)
if Print:
print('B', B)
print('N', N)
try:
B_inv = np.linalg.inv(B)
except Exception:
return None, 0
if Print:
print('B_inv', B_inv)
# for x0 case
if iteration == 0:
x = np.zeros_like(self.c)
for i, b in enumerate(basic):
x[b] = self.b[i]
if Print:
print('x', x)
# calc c
c_b = np.array([])
c_n = np.array([])
for i in range(self.num_of_vars):
if i in basic:
c_b = np.append(c_b, self.c[i])
else:
c_n = np.append(c_n, self.c[i])
if Print:
print('c_b', c_b)
print('c_n', c_n)
lumda = c_b.dot(B_inv)
if Print:
print('lumda', lumda)
u_n = c_n - lumda.dot(N)
if Print:
print('u_n', u_n)
u = np.zeros(self.num_of_vars)
for i, n in enumerate(non_basic):
u[n] = u_n[i]
if Print:
print('u', u)
iteration += 1
if iteration > 50000:
return None, 0
if Print:
print('min(u)', np.amin(u))
if np.amin(u) < 0:
if Print:
print('not optimal')
entering = np.where(u == np.amin(u))
entering = entering[0][0]
# picks the fist min value in case of tie
if Print:
print('entering index', entering)
else:
if Print:
print('Optimal')
print(iteration)
print(x)
break
# to find index of entering in non_basic array
e_l = np.zeros_like(non_basic)
e_l[np.where(non_basic == entering)] = 1
if Print:
print('e_l', e_l)
d_B = - np.matmul(B_inv, N).dot(e_l)
if Print:
print('d_B', d_B)
d = np.zeros(self.num_of_vars)
for i in range(self.num_of_vars):
if i in basic:
d[i] = d_B[np.where(i == basic)]
else:
d[i] = e_l[np.where(i == non_basic)]
if Print:
print('d', d)
a = None
try:
a = min(-1*x[i]/d[i] for i in range(self.num_of_vars) if d[i] < 0)
except Exception as e:
print(e)
#import IPython; IPython.embed()
return None, 0
if Print:
print('a', a)
x = x + a * d
if Print:
print('x', x)
# set leaving as first basic, then check if any other
# basic has lower x value
leaving = basic[0]
for b in basic:
if x[b] < x[leaving]:
leaving = b
if Print:
print('leaving index', leaving)
# Update basic and non basic
basic = np.append(basic, entering)
non_basic = np.append(non_basic, leaving)
basic = np.delete(basic, np.where(basic == leaving))
non_basic = np.delete(non_basic, np.where(non_basic == entering))
basic = np.sort(basic)
non_basic = np.sort(non_basic)
if Print:
print('basic', basic)
print('non_basic', non_basic)
return np.around(x, decimals=3), iteration
def task_1():
output = {}
iterations = []
for n in range(1, 15, 1):
LP = simplex(2*n) # 2* for basic from constraint
for i in range(1, n+1, 1):
const = [2**(i-j+1) for j in range(1, i, 1)]
const.append(1) # for xi
if n > i:
for _ in range(n-i):
const.append(0) # for non-basic but non participating
if (i != 1):
for _ in range(i-1):
const.append(0) # for non participating basic
const.append(1) # for participating basic
if i != n:
for _ in range(n-i):
const.append(0) # for non participating basic
print('const', i, const)
LP.constraint(const, [5**i])
# -2 to convert it to maximize
obj_arr = [-2**(n-j) for j in range(1, n+1, 1)]
for _ in range(n):
obj_arr.append(0) # for basic
print('obj', obj_arr)
LP.objective(np.array(obj_arr))
output[n], itr = LP.compute()
iterations.append(itr)
print('#################################################')
for key in output.keys():
print(key, output[key])
plt.plot(range(1, len(iterations)+1), iterations)
plt.show()
def task_2():
np.random.seed(13) # to make sure it works
output = {}
margin = 0.1
num_of_devi = 9
iter_devi = [] # iter_devi[devi_index][n_val]=itermation
plot_x = []
for devi in range(1, num_of_devi+1):
devi = devi * margin # deviation is from 0.5 till 5 (step: 0.5)
iterations = []
plot_x1 = []
for n in range(1, 11, 1):
LP = simplex(2*n) # 2* for basic from constraint
for i in range(1, n+1, 1):
const = [2**(i-j+1)+np.random.normal(0,devi,None) for j in range(1, i, 1)]
const.append(1+np.random.normal(0,devi,None)) # for xi
if n > i:
for _ in range(n-i):
const.append(0) # for non-basic but non participating
if (i != 1):
for _ in range(i-1):
const.append(0) # for non participating basic
const.append(1) # for participating basic
if i != n:
for _ in range(n-i):
const.append(0) # for non participating basic
print('const', i, const)
LP.constraint(const, [5**i])
# -2 to convert it to maximize
obj_arr = [(-2**(n-j))+np.random.normal(0,devi,None) for j in range(1, n+1, 1)]
for _ in range(n):
obj_arr.append(0) # for basic
print('obj', obj_arr)
LP.objective(np.array(obj_arr))
output[n], itr = LP.compute()
iterations.append(itr)
plot_x1.append(n)
iter_devi.append(iterations)
plot_x.append(plot_x1)
print(iter_devi)
#import IPython; IPython.embed()
#print runs with not answer
for i in range(len(iter_devi)):
j = 0
while j < len(iter_devi[i]):
if iter_devi[i][j] == 0:
print('Solution wasn\'t found at deviation:', np.round((i+1)*margin, decimals=1), 'with number of variables =', j)
del plot_x[i][j]
del iter_devi[i][j]
j -= 1
j += 1
for i in range(num_of_devi):
#plt.plot(range(1, len(iter_devi[i])+1), iter_devi[i], label=str(np.round((i+1)*margin, decimals=1)))
plt.plot(plot_x[i], iter_devi[i], label=str(np.round((i+1)*margin, decimals=1)))
plt.legend()
plt.show()
if __name__ == '__main__':
#LP = simplex(4)
#LP.constraint([1, 2, 1, 0], [3])
#LP.constraint([2, 1, 0, 1], [3])
#LP.objective(np.array([-1, -1, 0, 0]))
#LP.compute()
#LP = simplex(4)
#LP.constraint([8, 3, 1, 1], [12])
#LP.objective(np.array([-4, -2, 5, 0]))
#print(LP.compute())
task_2()