-
Notifications
You must be signed in to change notification settings - Fork 0
/
solve_LP.py
348 lines (282 loc) · 9.87 KB
/
solve_LP.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
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
from fractions import Fraction
from equation import Equation, EqElement
from copy import deepcopy
def _div(l, divider, new=False):
#print(f"dividing {l} by {divider}")
if new:
ln = []
for i in range(len(l)):
if new:
ln.append(l[i] / divider)
else:
l[i] = l[i] / divider
if new:
return ln
def _sub(l, lSub):
for i in range(len(l)):
l[i] -= lSub[i]
def remove_bases_from_fn(l, log=False):
rows = len(l)
cols = len(l[0])
for c in range(1, cols):
values = []
for r in range(1, rows):
if l[r][c] != 0:
values.append((r, c))
is_base = len(values) == 1 and l[values[0][0]][values[0][1]] == 1
if not is_base: continue
r, c = values[0]
if (l[0][c]) != 0:
if log: print("Subtracting row {} from fn (col {})".format(r, c))
subtract = _div(l[r], l[r][c] / l[0][c], True)
_sub(l[0], subtract)
if log:
print(getMatrix(l))
def simplex_move(l, el, log=False):
lead_r, lead_c = el
for r in range(len(l)):
if r == lead_r:
_div(l[r], l[r][lead_c])
continue
if l[r][lead_c] == 0:
continue
subtract = _div(l[lead_r], l[lead_r][lead_c] / l[r][lead_c], True)
#print(f"subtracting {subtract} from row {r}")
_sub(l[r], subtract)
if log: print(getMatrix(l))
def contains_negative(L):
l = L[0][1:]
global M, ex
for i in range(len(l)): # big M method check
if (i+1 not in M) and (not l[i].is_const()):
return True
for i in range(len(l)):
if i+1 in M: continue
if l[i] < 0: return True
if ex == 5: # dual simplex
for row in range(1, len(L)):
if L[row][0] < 0:
return True
return False
def get_lead_el(l):
try:
lead_col = min([(l[0][col], col) for col in range(1, len(l[0]))], key=lambda x: x[0])[1]
except ValueError:
lead_col = min([(l[0][col].elem["M"].multi, col) for col in range(1, len(l[0])) if "M" in l[0][col].elem], key=lambda x: x[0])[1]
lead_row = max([(l[row][lead_col] / l[row][0] if l[row][lead_col] > 0 else float("-inf"), row)
for row in range(1, len(l))], key=lambda x: x[0])[1]
return (lead_row, lead_col)
def get_dual_simplex_lead_el(l):
lead_row = min(((l[row][0], row) for row in range(1, len(l))), key=lambda x: x[0])[1]
lead_col = min(((l[0][col] / abs(l[lead_row][col]), col) for col in range(1, len(l[0])) if l[lead_row][col] < 0), key=lambda x: x[0])[1]
return (lead_row, lead_col)
def solve_simplex(l, log=False, lead_el_fn=get_lead_el):
global test
test = []
used_cols = set()
while contains_negative(l):
if log: print("Table does not contain an optimal solution")
r,c = lead_el_fn(l)
if c in used_cols:
print(f"Error: solver looped (to col {c}), no solution is possible!")
return False
#if log: print("\nLead column (min fn value): {}\nLead row (min var and free el div): {}".format(c, r))
if log: print(f"Lead row, col [↑]: {r}, {c}.\n")
simplex_move(l, (r,c), log)
test.append(deepcopy(l))
used_cols.add(c)
if log: print("Optimal solution found!")
return True
def getInput():
l = []
col_count = None
ex = int(input("{}Solver (1:simplex, 2:2-phase max, 3:M-max, 4:M-min, 5:dual-smplx max): ".format("" if log else "Silent")))
#ex = 1
if ex < 0: return (ex, [], [])
variables = input("Variable names: (leave empty for x1...xn): ".format()).split(" ")
print("Input simplex table (separate elements with spaces, rows with new line; leave line empty to end input):")
while True:
row = []
try:
vals = input().strip()
if vals == "":
break
for val in vals.split(" "):
row.append(Equation(val))
if col_count is None:
col_count = len(row)
elif len(row) != col_count:
print("Input does not match column count! (use a single space as the separator between numbers)")
continue
except Exception as e:
if isinstance(e, KeyboardInterrupt):
print("Input cancelled!\n")
raise KeyboardInterrupt()
print("Input parsing failed!")
print(e)
l.append(row)
row_count = len(l)
if row_count < 2 or col_count <= row_count:
print("<rows> must be larger than 2 (got {}) and <cols> must be larger <rows> + 1 (got {})!".format(row_count, col_count))
#return (0, [], [])
if variables == ['']:
variables = ["x{}".format(i) for i in range(1, col_count)]
print()
return (ex, variables, l)
def _getStrings(l, getMax=False):
lp = [[] for i in range(len(l))]
maxLen = 0
for r in range(len(l)):
for v in l[r]:
#lp[r].append((str(v.numerator) if v.denominator == 1 else str(v.numerator) + "/" + str(v.denominator)))
lp[r].append(str(v))
maxLen = max(maxLen, len(lp[r][-1]))
return lp if not getMax else (lp, maxLen)
def getMatrix(l, highlight=None):
global var
lp, maxLen = _getStrings(l, True)
ls = []
formatStr = "{: >" + str(maxLen) + "} "
s = formatStr + "| " + formatStr * (len(lp[0]) - 1)
if var is not None:
ls.append(s.format("", *var, *([""] * (len(lp[0]) - len(var) - 1))))
ls.append("-" * len(ls[0]))
for r in range(len(l)):
ls.append(s.format(*lp[r]))
if r == 0: ls.append("-" * len(ls[0]))
return "\n".join(ls)
def getValues(l):
v = [0]*(len(l[0]))
for col in range(1, len(l[0])):
valExists = False
for row in range(1, len(l)):
if l[row][col] != 0:
if valExists:
v[col] = 0
else:
valExists = True
v[col] = l[row][0] / l[row][col]
return v[1:]
def getValueDict(l):
global var
val = getValues(l)
vd = {}
for i in range(len(var)):
if var[i] != "":
vd[var[i]] = val[i]
return vd
def getValueStrings(l, var):
global fn
v = getValues(l)
#s = [getZ(l[0], v)[0]]
fn_val = fn.calc(getValueDict(l), True)
s = [f"fn = {fn_val[0]} = {fn_val[1]} = {fn}"]
for i in range(len(var)):
if (var[i] != ""):
s.append("{} = {}".format(var[i], v[i]))
return s
def exec_solve_simplex(l, log, lead_el_fn=get_lead_el):
remove_bases_from_fn(l, log)
return solve_simplex(l, log, lead_el_fn)
def get_fn(l, var):
eq = Equation()
var = [""] + var
for i in range(len(var)):
if var[i] == "" and i != 0:
continue
eq += EqElement(-l[i].calc(), {var[i]: 1})
return eq
def check_M(l):
global M
for i in range(len(l[0])):
if not l[0][i].is_const():
M.add(i)
if len(M) != 0: print("M-table detected")
def solver(ex, l, log):
global var, M
if ex != 0 and log:
print("\n\tGOT INPUT:")
print(getMatrix(l), end="\n\n")
check_M(l)
if ex == 1:
return exec_solve_simplex(l, log)
elif ex == 2:
fn_ = l[0]
var_ = var
rows = len(l)
cols = len(fn_)
var = var + ["y"+str(i) for i in range(1, rows)]
# identity matrix
l[0] = ([Equation("0")]*cols) + ([Equation("1")]*(rows-1))
for r in range(1,rows):
l[r] = l[r] + ([Equation("0")]*(r-1)) + [Equation("1")] + ([Equation("0")]*(rows-r-1))
if log: print("\tPhase 1\n{}".format(getMatrix(l)))
if not exec_solve_simplex(l, log): return
p1_fn = get_fn(l[0], var)
if p1_fn.calc(getValueDict(l)) != 0:
print("\nError: unable to solve (fn = {0} = {1} = {2})!".format(*p1_fn.calc(getValueDict(l), True), str(p1_fn)))
return False
l[0] = fn_
var = var_
for r in range(1, rows):
l[r] = l[r][:-rows+1]
if log: print("\n\n\tPhase 2\n{}".format(getMatrix(l)))
return exec_solve_simplex(l, log)
elif ex == 3 or ex == 4:
fn_ = l[0]
rows = len(l)
# identity M-matrix
l[0] += ([Equation("M") if ex == 3 else Equation("-M")]*(rows-1))
for r in range(1,rows):
l[r] = l[r] + ([Equation("0")]*(r-1)) + [Equation("1")] + ([Equation("0")]*(rows-r-1))
if log: print("\tM-table: \n{}".format(getMatrix(l)))
check_M(l)
v = exec_solve_simplex(l, log)
l[0] = fn_
return v
elif ex == 5:
return exec_solve_simplex(l, log, get_dual_simplex_lead_el)
else:
print("Error: Unknown solver {}!".format(ex))
return False
log = True
#manual_mode = 0
while True:
l = [[]]
var = []
ex = 0
M = set()
fn = None
# calculate
while ex == 0:
try:
ex, var, l = getInput()
except Exception as e:
print("Input parsing failed!")
print(e)
ex = 0
print()
if ex == -1:
log = not log
continue
fn = get_fn(l[0], var)
solved = solver(ex, l, log)
"""
if manual_mode < 2:
if log: print("Ensuring simplex compatibility...")
remove_bases_from_fn(l, log)
if manual_mode < 1:
if log: print("\n\nSolving...")
solved = solve_simplex(l, log)
if manual_mode:
while True:
c,r = map(int, input("\nLead element coords (<col> <row>): ").strip().split(" "))
simplex_move(l, (r,c), True)
"""
if solved: # print values
print("\nRaw data:")
print("\n".join([" ".join(map(str, row)) for row in l]))
print()
print("\n".join(getValueStrings(l, var)))
print("\n")
l = [[]]