from sympy import *
from simplex import *
def example_0():
x1, x2, x3 = symbols('x1, x2, x3')
obj = -3 * x1 + x2 + x3
variables = [x1, x2, x3]
c0 = -4 * x1 + x2 + 2 * x3 >= 3
c1 = x1 - 2 * x2 + x3 X=', simplex.optimal_X)
print('==> y=', simplex.optimal_y)
def example_1():
x1, x2 = symbols('x1, x2')
obj = -(2*x1 + 3*x2)
variables = [x1, x2]
c0 = x1 + 2*x2 <= 8
c1 = 4*x1 <= 16
c2 = 4*x2 X=', simplex.optimal_X)
print('==> y=', -simplex.optimal_y)
def example_2():
# X=[21/5, 6/5], min_f=-18
x1, x2 = symbols('x1, x2')
obj = -4*x1 - x2
variables = [x1, x2]
c0 = -x1 + 2*x2 <= 4
c1 = 2*x1 + 3*x2 <= 12
c2 = x1 - x2 X=', simplex.optimal_X)
print('==> y=', simplex.optimal_y)
def example_3():
x1, x2, x3, x4, x5 = symbols('x1, x2, x3, x4, x5')
obj = 2*x1 + 3*x2 + 5*x3 + 2*x4 + 3*x5
variables = [x1, x2, x3, x4, x5]
c0 = x1 + x2 + 2*x3 + x4 + 3*x5 >= 4
c1 = 2*x1 - x2 + 3*x3 + x4 + x5 >= 3
constrs = [c0, c1] constrs_com = [GEQ, GEQ]
simplex = Simplex(obj, variables, constrs, constrs_com)
simplex.start()
print('==> X=', simplex.optimal_X)
print('==> y=', simplex.optimal_y)
def example_4():
# X=[3, 0], max_f=6
x1, x2 = symbols('x1, x2')
obj = -(2*x1 - x2)
variables = [x1, x2]
c0 = x1 + x2 >= 2
c1 = x1 - x2 >= 1
c2 = x1 X=', simplex.optimal_X)
print('==> y=', -simplex.optimal_y)
def example_5():
# X=[0, 12, 5, 8], min_f=-19
x1, x2, x3, x4 = symbols('x1, x2, x3, x4')
obj = x1 - 2*x2 + x3
variables = [x1, x2, x3, x4]
c0 = 2*x1 - x2 + 4*x3 <= 8
c1 = -x1 + 2*x2 - 4*x3 X=', simplex.optimal_X)
print('==> y=', simplex.optimal_y)
def example_6():
# X=[0,1, 0], min_f=-1
x1, x2, x3 = symbols('x1, x2, x3')
obj = x1 - x2
variables = [x1, x2, x3]
c0 = -x1 + 2*x2 + x3 X=', simplex.optimal_X)
print('==> y=', simplex.optimal_y)
def example_7():
x1, x2, x3 = symbols('x1, x2, x3')
obj = 3*x1 - 2*x2 + x3
variables = [x1, x2, x3]
c0 = 2*x1 + 3*x2 >= 8
c1 = (2*x1 - 3*x2 + x3, 1)
constrs = [c0, c1] constrs_com = [GEQ, EQ]
simplex = Simplex(obj, variables, constrs, constrs_com)
simplex.start()
print('==> X=', simplex.optimal_X)
print('==> y=', simplex.optimal_y)
def main():
print('-'*25, '算例', '-'*25)
print('- 算例0 - 约束含有">=", "=0, 求min')
print('- 算例1 - 约束全为"=0, 求max')
print('- 算例2 - 约束全为"=0, 求mix')
print('- 算例3 - 约束全为">=", 所有变量均>=0, 求min')
print('- 算例4 - 约束含有">="和"=0, 求max')
print('- 算例5 - 约束含有"=0, 求min')
print('- 算例6 - 约束含有"=0, 求min')
print('- 算例7 - 约束含有">="和“=”, 所有变量均>=0, 求min')
print('-' * 56)
ex = input('输入算例编号(0~7):')
if int(ex) == 0:
example_0()
elif int(ex) == 1:
example_1()
elif int(ex) == 2:
example_2()
elif int(ex) == 3:
example_3()
elif int(ex) == 4:
example_4()
elif int(ex) == 5:
example_5()
elif int(ex) == 6:
example_6()
elif int(ex) == 7:
example_7()
if __name__ == "__main__":
main()