Created
December 23, 2015 05:32
-
-
Save w1ndy/195ea6255918680a1c6e to your computer and use it in GitHub Desktop.
Simple python library for linear programming solving
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from copy import deepcopy | |
from fractions import Fraction | |
def find(eqns): | |
x = -1 | |
a = 0 | |
en = len(eqns) | |
vn = len(eqns[0]) | |
for i in range(0, vn - 1): | |
if eqns[0][i] > a: | |
a = eqns[0][i] | |
x = i | |
if x == -1: | |
print("Couldn't locate main column") | |
return | |
n = -1 | |
a = 99999 | |
for i in range(1, en): | |
if eqns[i][x] > 0 and eqns[i][-1] / eqns[i][x] < a: | |
a = eqns[i][-1] / eqns[i][x] | |
n = i | |
if n == -1: | |
print("No positive element in main column") | |
return | |
return n, x | |
def finddual(eqns): | |
n = -1 | |
a = 0 | |
en = len(eqns) | |
vn = len(eqns[0]) | |
for i in range(1, en): | |
if eqns[i][-1] < a: | |
a = eqns[i][-1] | |
n = i | |
if n == -1: | |
print("Problem has been solved") | |
return | |
x = -1 | |
a = 0 | |
for i in range(0, vn - 1): | |
if eqns[n][i] < 0 and eqns[0][i] < 0: | |
r = eqns[0][i] / eqns[n][i] | |
if a > r or a == 0: | |
a = r | |
x = i | |
if x == -1: | |
print("Couldn't locate element") | |
return | |
return n, x | |
def tofraction(eqns): | |
for i in range(len(eqns)): | |
eqns[i] = map(lambda x: Fraction(x), eqns[i]) | |
return eqns | |
def solve(eqns, n, x): | |
ret = [] | |
vn = len(eqns[0]) | |
en = len(eqns) | |
for i in range(en): | |
ret.append(deepcopy(eqns[i])) | |
if i == n: | |
for j in range(vn): | |
ret[i][j] /= eqns[i][x] | |
else: | |
r = eqns[i][x] / eqns[n][x] | |
for j in range(vn): | |
ret[i][j] -= r * eqns[n][j] | |
return ret | |
def printeqns(eqns): | |
templates = [] | |
vn = len(eqns[0]) | |
for i in range(vn - 1): | |
templates.append("{" + str(i) + ":10} x" + str(i)) | |
templates.append("{" + str(i + 1) + ":10}") | |
template = "\t".join(templates) | |
print(template) | |
for eq in eqns: | |
print(template.format(*eq)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment