Beispiel #1
0
    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()))
Beispiel #2
0
 def create_complete_connection(self, edgeText, vertices):
     edgeText = self.get_combination(edgeText)
     tempList = []
     tempListGraph = []
     for i in range(len(edgeText)):
         if (edgeText[i] <> ',') and (edgeText[i] <> '.'):
             tempList.append(edgeText[i])
         if (edgeText[i] == ','):
             tempList.sort()
             for j in range(len(tempList)):
                 tempGraph = Simplex(tempList[j])
                 tempGraph.name = tempList[j]
                 tempListGraph.append(tempGraph)
             tempTree = []
             for j in range(len(tempListGraph)):
                 if j <> 0:
                     tempTree.append(tempListGraph[j])
             vertices[int(min(tempList)) - 1].insert_childs(tempTree)
             tempList = []
             tempListGraph = []
         if (edgeText[i] == '.'):
             tempList.sort()
             for j in range(len(tempList)):
                 tempGraph = Simplex(tempList[j])
                 tempGraph.name = tempList[j]
                 tempListGraph.append(tempGraph)
             tempTree = []
             for j in range(len(tempListGraph)):
                 if j <> 0:
                     tempTree.append(tempListGraph[j])
             vertices[int(min(tempList)) - 1].insert_childs(tempTree)
     return
Beispiel #3
0
    def test_checking_for_optimality(self):
        simplex = Simplex()
        simplex.reduced_costs = np.array([3, 0, 2])
        is_optimal = simplex.check_if_optimal()
        assert is_optimal

        simplex = Simplex()
        simplex.reduced_costs = np.array([3, 0, -1])
        is_optimal = simplex.check_if_optimal()
        assert not is_optimal
Beispiel #4
0
    def test_initializing_basis_creates_a_basis_solution_of_zeros_of_the_right_size(self):
        simplex = Simplex()
        simplex.constraints = np.array([[4],
                                        [2]])
        simplex.initialize_basis()
        assert np.array_equal(simplex.basis_objective, np.array([[0], [0]]))

        simplex = Simplex()
        simplex.constraints = np.array([[4],
                                        [2],
                                        [1]])
        simplex.initialize_basis()
        assert np.array_equal(simplex.basis_objective, np.array([[0], [0], [0]]))
Beispiel #5
0
    def test_checking_for_unboundedness(self):
        simplex = Simplex()
        simplex.reduced_costs = np.array([3, 0, -1])
        simplex.coefficients = np.array([[1, 2, -1],
                                         [2, 1,  1]])
        is_unbounded = simplex.check_if_unbounded()
        assert not is_unbounded

        simplex = Simplex()
        simplex.reduced_costs = np.array([3, 0, -1])
        simplex.coefficients = np.array([[1, 2, -1],
                                         [2, 1,  0]])
        is_unbounded = simplex.check_if_unbounded()
        assert is_unbounded
Beispiel #6
0
    def test_pivot_column_attaining(self):
        simplex = Simplex()
        simplex.reduced_costs = np.array([3, -2, -1])

        simplex.obtain_pivot_column_index()

        assert simplex.pivot_column_index == 1
Beispiel #7
0
def get_faces():
    for item in new1.faces:
        temp = []
        for inner_item in item:
            index_vertex = inner_item.find("/")
            if inner_item[0:index_vertex] != '':
                temp.append(int(inner_item[0:index_vertex]))
        faces.append(temp)
    # create simplicial complex
    for i in faces:
        i.sort()
        temp_string_list = []
        for q in i:
            temp_string_list.append(str(q))
        combination = operator.get_combination_with_list(temp_string_list)
        for j in combination:
            tempList = []
            tempListGraph = []
            for q in j:
                tempGraph = Simplex(str(q))
                tempList.append(q)
                tempListGraph.append(tempGraph)
            tempTree = []
            for k in range(len(tempListGraph)):
                if k <> 0:
                    tempTree.append(tempListGraph[k])
            vertices_simpelx[int(min(tempList)) - 1].insert_childs(tempTree)
Beispiel #8
0
def get_vertices():
    counter_temp_name_vertex = 0
    for item in new1.vertices:
        counter_temp_name_vertex += 1
        vertex_simplex = Simplex(str(counter_temp_name_vertex))
        vertex_simplex.set_coordinate(item)
        vertices_simpelx.append(vertex_simplex)
Beispiel #9
0
    def compute_corner_simplex(self):
        if rank(self.indices) < 2:
            self.corner_simplex = Simplex(self.indices)
        else:
            corner_value = self.indices.min()
            corner_index = (self.indices == corner_value).nonzero()

            rest = self.indices[[
                tuple(x) for x in bitwise_xor(
                    eye(rank(self.indices), dtype=int), array(corner_index))
            ]]

            parity = sum(corner_index)[0] % 2

            self.corner_simplex = Simplex([corner_value] + rest.tolist(),
                                          parity)
Beispiel #10
0
def testf5():
    print("Testing f5...")
    '''
	min 180x + 160y
	s.t.
    	6x + y >= 12
    	3x + y >= 8
    	4x + 6y >= 24
    	x <= 5
    	y <= 5
    	x,y >= 0
	'''
    c = [180, 160]
    A = [[6, 1],
         [3, 1],
         [4, 6],
         [-1, 0],
         [-1, 0]]
    b = [12, 8, 24, -5, -5]
    maxi = False
    f = Simplex(c, A, b, maxi)
    x, z = f.simplex()
    assert(almostEqual(x[0], 12/7) and
           almostEqual(x[1], 20/7) and
           almostEqual(z, 180*(12/7) + 160*(20/7)))
Beispiel #11
0
def main():
    ##############
    global deltaall, weis, variables, sigmaFFS
    #Definition of lattice parameters and sigmas at FFS start
    betx = 64.9999
    bety = 17.9997
    gamma = 3e6
    ex = 68e-8
    ey = 1e-8
    sigmaFFS = [
        sqrt(ex * betx / gamma),
        sqrt(ex / betx / gamma),
        sqrt(ey * bety / gamma),
        sqrt(ey / bety / gamma), 0.01
    ]

    print 'Sigmas at FFS start:', sigmaFFSstart
    #Definition of MADX variables to vary (sextupole str)
    variables = ['ksf6', 'ksf5', 'ksd4', 'ksf1', 'ksd0']
    #Definition of weights:
    weis = [10, 10000]
    #Starting point for the MADX variables
    deltafamilies1 = [-0.0, 0.0, -0.00, -0.00, 0.00]
    #Starting increment of the MADX variables.
    #Changes are relative in this example, see writeparams
    incr = [0.05, 0.05, -0.05, -0.01, 0.01]
    s = Simplex(chi2, deltafamilies1, incr)
    values, err, iter = s.minimize(epsilon=6e-18)
    print 'args = ', values
    print 'error = ', err
    print 'iterations = ', iter
Beispiel #12
0
 def solucao_simplex(self):
     s = Simplex()
     s2 = simplex_meth()  #<-
     self.restrincaoL.append(self.aux2)
     s.forma_padrao(self.funcaoObjetiva, self.restrincaoL)
     s2.setMatriz(s.tableau, self.tipo)
     quote = ""
     print("Solução Básica Inicial")
     if (self.tipo.get() == 1):  #Min
         s2.calc_min()
     if (self.tipo.get() == 2):  #Max
         s2.calc_max()
     #############
     print(self.tipo.get())
     print(s2.matriz)
     print(s2.valorFuncObj)
     print(s2.variaveisBasicas)
     print(s2.variaveisNaoBasicas)
     #############
     if (s2.flagIlimitado):
         quote += "A Solução não foi possível pois ela é ilimitada\n"
     else:
         quote += "Valor da função objetivo = "
         quote += str(s2.valorFuncObj) + "\n"
         quote += "Variaveis básicas = "
         quote += str(s2.variaveisBasicas) + "\n"
         quote += "Variaveis não básicas = "
         quote += str(s2.variaveisNaoBasicas) + "\n"
     self.t.insert(END, quote)
     #############
     """
Beispiel #13
0
def test_simplex_resolve():
    simp = Simplex(
        eqs=((15, 7.5, 5), (2, 3, 2), (1, 1, 1)),
        constants=(315, 110, 50),
        max_func=(200, 150, 120),
    )
    assert simp.resolve(show_step=False) == (36.0, 4.0, 10.0)
Beispiel #14
0
 def test3(self):
     '''
     minimise
         4a + 5b + 6c
     subject to
         a + b >= 11
         a - b <= 5
         c - a - b >= 0
         c - a - b <= 0
         7a >= 35 - 12b
         a >= 0 b >= 0 c >= 0
     '''
     A = np.array([
         [-1,  -1,  0],
         [ 1,  -1,  0],
         [-1,  -1,  1],
         [ 1,   1, -1],
         [-7, -12,  0],
     ])
     b = np.array([-11, 5, 0, 0, -35])
     c = np.array([4, 5, 6])
     s = Simplex(A, b, c, 0, "min")
     s.solve()
     pdb.set_trace()
     self.assertEqual(s.obj_val(), 113)
     self.assertTrue(np.allclose(s.sol(), np.array([8, 3, 11])))
Beispiel #15
0
    def solve_simplex_steps(linear_program, pivot_strategy=None, max_iterations=None):
        if max_iterations is None:
            max_iterations = LinearProgramSolver.DEFAULT_MAX_ITERATIONS_COUNT
        if pivot_strategy is None:
            pivot_strategy = strategy.MaxCoefficientStrategy()

        solver = Simplex(pivot_strategy, max_iterations)
        return solver.solution_steps(linear_program)
Beispiel #16
0
def create_simple_structure():
    operator=Operator()
    for i in range(int(e1.get())):
        objGraph = Simplex(str(i + 1))
        vertices.append(objGraph)
    operator.create_simple_connection(e3.get(), vertices)
    operator.show_structures(vertices)
    return
Beispiel #17
0
def main():
    simp = Simplex(
        eqs=((15, 7.5, 5), (2, 3, 2), (1, 1, 1)),
        constants=(315, 110, 50),
        max_func=(200, 150, 120),
    )
    r = simp.resolve(iter_limit=10)
    print("Result is", r)
Beispiel #18
0
def example1():
    coefficients = np.array([[1, 1], [1, -1]], dtype='float')
    constraints = np.array([[4], [2]], dtype='float')
    objective = np.array([3, 2])
    simplex = Simplex(coefficients=coefficients,
                      constraints=constraints,
                      objective=objective)
    display = Display(simplex_init=simplex)
    display.run_simplex()
Beispiel #19
0
def test_case(num_vars, constraints, objective_function, expected_solution):
    s = Simplex(num_vars, constraints, objective_function)
    if expected_solution != s.solution:
        print("[FAIL] Expected '%' received '%'", expected_solution,
              s.solution)
    else:
        print("[OK] num_vars=", num_vars, " constraints='", constraints,
              "' objective='", objective_function, "' solution='",
              expected_solution, "'")
Beispiel #20
0
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()
Beispiel #21
0
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)
Beispiel #22
0
    def test_initializing_basis_marks_slack_variables_as_basis(self):
        simplex = Simplex()
        simplex.constraints = np.array([[4],
                                        [2],
                                        [1]])

        simplex.initialize_basis()

        assert Variable(index=2, is_slack=True) in simplex.basis_variables
Beispiel #23
0
def example3():
    coefficients = np.array([[2, 1, 0], [1, 2, -2], [0, 1, 2]], dtype='float')
    constraints = np.array([[10], [20], [5]], dtype='float')
    objective = np.array([2, -1, 2])
    simplex = Simplex(coefficients=coefficients,
                      constraints=constraints,
                      objective=objective)
    display = Display(simplex_init=simplex)
    display.run_simplex()
Beispiel #24
0
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()
Beispiel #25
0
def example2():
    coefficients = np.array([[4.1, 2], [2, 4]], dtype='float')
    constraints = np.array([[40], [32]], dtype='float')
    objective = np.array([80, 55])
    simplex = Simplex(coefficients=coefficients,
                      constraints=constraints,
                      objective=objective)
    display = Display(simplex_init=simplex)
    display.run_simplex()
Beispiel #26
0
def run_from_txt():
    with open("lp.txt") as file:
        content = file.read()
    kw = {}
    exec(content, globals(), kw)
    A = np.array(kw['A'])
    b = np.array(kw['b'])
    c = np.array(kw['c'])
    d = Display(Simplex(coefficients=A, constraints=b, objective=c))
    d.run_simplex()
Beispiel #27
0
    def test_calculation_of_basis_value(self):
        simplex = Simplex()
        simplex.basis_objective = np.array([[1],
                                            [2]])
        simplex.basis_solution = np.array([[4],
                                           [2]])

        simplex.calculate_basis_value()

        assert simplex.basis_value == 8
Beispiel #28
0
    def test_can_initialize_on_creation(self):
        coefficients = np.array([[5]], dtype='float')
        constraints = np.array([[4]], dtype='float')
        objective = np.array([3], dtype='float')

        simplex = Simplex(coefficients=coefficients, constraints=constraints, objective=objective)

        assert np.array_equal(simplex.coefficients, coefficients)
        assert np.array_equal(simplex.constraints, constraints)
        assert np.array_equal(simplex.objective, objective)
 def onSolve(self):
     #update the problem display, run simplex, redraw graph
     self.solved = True
     if not (self.cChanged or self.AChanged or self.bChanged
             or self.eqChanged):
         self.inputTranslate()
         f = Simplex(self.cSim, self.ASim, self.bSim, self.maxi)
         self.x, self.z = f.simplex()
         self.drawResults()
         self.graphResults()
Beispiel #30
0
    def test_extract_solution(self):
        simplex = Simplex()
        simplex.coefficients = np.array([[1,  1, 1, 0],
                                         [1, -1, 0, 1]], dtype='float')
        simplex.basis_variables = [Variable(index=0, is_slack=True), Variable(index=1, is_slack=False)]
        simplex.basis_solution = np.array([[9], [4]], dtype='float')

        simplex.obtain_solution()

        assert np.array_equal(simplex.solution, np.array([[0], [4]], dtype='float'))