def test_add_constraint(self): A = np.array([ [-1, 1], [1, 1] ]) b = np.array([0, 2]) c = np.array([1, 1.5]) const = 0 mode = "max" s1 = Simplex(A, b, c, const, mode) s1.solve() A2 = np.array([ [-1, 1], [1, 1], [0, 1] ]) b2 = np.array([0, 2, 0.5]) c2 = np.array([1, 1.5]) const2 = 0 mode2 = "max" s2 = Simplex(A2, b2, c2, const2, mode2) s2.solve() s1.add_constraint(np.array([0, 1]), 0.5) s1.reset() s1.solve() self.assertTrue(np.allclose(s1.A, s2.A)) self.assertTrue(np.allclose(s1.b, s2.b)) self.assertTrue(np.allclose(s1.c, s2.c)) self.assertTrue(np.allclose(s1.sol(), s2.sol())) self.assertTrue(np.allclose(s1.obj_val(), s2.obj_val()))
def testPivot(): solver = Simplex([0.0, 0.0, 0.0, 1.0, 2.0, 1.0, 1.0]) solver.add_constraint([1, 0, 0, 1, 1, -1], 5) solver.add_constraint([0, 1, 0, 2, -3, 1], 3) solver.add_constraint([0, 0, 1, -1, 2, -1], -1) solver.set_index([1, 2, 3]) print(solver.table) solver.pivot(1, 4) print(solver.table)
def testLPSolver(): solver = Simplex([0, 0, 0, -12, 0, -284]) solver.add_constraint([0, -1, 1, -1, 0], 16) solver.add_constraint([1, 2, 0, 1, 0], 12) solver.add_constraint([0, 3, 0, 1, 1], 17) solver.print_info() solver.set_index([3, 1, 5]) solver.pivot(5, 2) solver.print_info()
def get_relaxation_solution(goal_expr, linear_equations, var_num): s = Simplex(goal_expr['mat'], max_mode=goal_expr['max_mode']) for eq in linear_equations: s.add_constraint(eq['mat'], eq['val']) res = s.solve() if res is None: return expr_val = res[0] for i in range(1, var_num + 1): if res[1].get(i) is None: res[1][i] = 0 return dict(expr_val=expr_val, var_vals=res[1])
def testDegnerateSolver(): solver = Simplex([0.0, 0.0, 0.0, 3 / 4, -20.0, 1 / 2, -6.0, 0.0]) solver.add_constraint([1, 0, 0, 1 / 4, -8, -1, 9], 0) solver.add_constraint([0, 1, 0, 1 / 2, -12, -1 / 2, 3], 0) solver.add_constraint([0, 0, 1, 0, 0, 1, 0], 1) solver.set_index([1, 2, 3]) solver.solveStandard(10) solver.solveBlandRule(10) solver.print_info()
from simplex import Simplex if __name__ == "__main__": print("Solve the first solution.\n") t = Simplex('min', [-3, -1, -3]) t.add_constraint([2, 1, 1], 2, "<=") t.add_constraint([1, 1, 3], 5, "<=") t.add_constraint([2, 2, 1], 6, "<=") t.solve() print("\n\n\nSolve the second solution.\n") t = Simplex("min", [-9, 12, 41]) t.add_constraint([1, -1, -5], 17, "<=") t.add_constraint([1, -2, -8], -36, "<=") t.add_constraint([1, -2, -5], 28, "<=") t.solve()