Example #1
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)
     #############
     """
Example #2
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)
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
Example #4
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)
Example #5
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
Example #6
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)))
Example #7
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
Example #8
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)
Example #9
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)
Example #10
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
Example #11
0
class BranchesMethod(object):
    def __init__(self, c, a, b, bounds):
        self._simplex = Simplex()
        self._c = c
        self._a = a
        self._b = b
        self._bounds = bounds

    @staticmethod
    def is_integer(val, eps=1e-6):
        return True if abs((val + eps) // 1 - val) < eps else False

    def solve_simplex(self, c, a, b, bounds):
        try:
            d_low = [i[0] for i in bounds]
            d_top = [i[1] for i in bounds]
            Jb = self._simplex.get_allowable_plan(c[:], a[:], b[:], d_low[:],
                                                  d_top[:])
            res, Jb = self._simplex.solve(c[:], a[:], b[:], d_low[:], d_top[:],
                                          Jb[:])
            return res
        except Exception as e:
            raise e

    def solve(self):
        eps = 1e-6
        r = -np.inf
        mu0 = False
        mu = np.zeros(len(self._c))

        queue = [self._bounds]
        while queue:
            bounds = queue.pop(0)
            x = self.solve_simplex(self._c, self._a, self._b, bounds)
            if x is None:
                continue

            if any(not self.is_integer(coeff) for coeff in x):
                if np.dot(x, self._c) < r:
                    continue

            for i in range(len(x)):
                if not self.is_integer(x[i]):
                    l = x[i]
                    bounds_1, bounds_2 = bounds[:], bounds[:]
                    bounds_1[i] = [bounds[i][0], int(l)]
                    bounds_2[i] = [int(l) + 1, bounds[i][1]]
                    queue.append(bounds_1)
                    queue.append(bounds_2)
                    break

            if all(self.is_integer(coeff) for coeff in x):
                new_r = np.dot(x, self._c)
                if new_r > r:
                    mu, mu0, r = x, True, new_r

        return mu if mu0 == True else None
Example #12
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)
Example #13
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
Example #14
0
 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()
Example #15
0
 def testTrivialUnbounded(self):
     """
         Maximize x_0 st x_0 >= 4
     """
     s = Simplex(Array([
         [F(-1), F(0), F(0)],
         [F(-1), F(1),F(-4)]
     ]))
     s.variableFromIndex = {i : str(i) for i in range(s.nbVariables)}
     with self.assertRaises(Unbounded):
         s.solve()
Example #16
0
 def testAddRemoveVariable(self):
     s = Simplex(testMatrix2)
     s.addVariable()
     self.assertEqual(s.nbVariables, 4)
     expected = Array(testMatrix2FirstPhase)
     for i in range(len(expected)):
         self.assertEqual(s.tableaux[i], expected[i], "(row %d)" % i)
     s.removeVariable()
     self.assertEqual(s.nbVariables, 3)
     for i in range(len(expected)):
         self.assertEqual(s.tableaux[i], testMatrix2[i], "(row %d)" % i)
Example #17
0
    def test_can_add_slack_variables_to_matrix(self):
        """Checks that the slack variables can be added correctly."""
        simplex = Simplex()
        coefficients = np.array([[1,  1],
                                 [1, -1]])
        simplex.coefficients = coefficients
        expected_coefficients = np.array([[1,  1, 1, 0],
                                          [1, -1, 0, 1]])

        simplex.initialize_slack()

        assert np.array_equal(simplex.coefficients, expected_coefficients)
Example #18
0
    def test_adding_slack_extends_objective_with_zeros(self):
        """Checks that the slack variables can be added for larger matrices."""
        simplex = Simplex()
        coefficients = np.array([[1,  1],
                                 [1, -1]])
        simplex.coefficients = coefficients
        simplex.objective = np.array([-3, -2])
        expected_objective = np.array([-3, -2, 0, 0])

        simplex.initialize_slack()

        assert np.array_equal(simplex.objective, expected_objective)
Example #19
0
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])
Example #20
0
 def testTrivialEmpty(self):
     """
         Maximize 0 st x_0 <= 3 AND x_0 >= 4
     """
     s = Simplex(Array([
         [F(0), F(0), F(0), F(0)],
         [F(1), F(1), F(0), F(3)],
         [F(-1), F(0), F(1), F(-4)]
     ]))
     s.variableFromIndex = {i : str(i) for i in range(s.nbVariables)}
     with self.assertRaises(Empty):
         s.solve()
Example #21
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]]))
Example #22
0
    def test_initializing_basis_sets_the_basis_initial_solution_to_the_initial_constraints(self):
        """Should set the basis based on the number of variables."""
        simplex = Simplex()
        simplex.coefficients = np.array([[1,  1],
                                         [1, -1]])
        simplex.constraints = np.array([[4],
                                        [2]])
        expected_basis_solution = np.array([[4],
                                            [2]])

        simplex.initialize_basis()

        assert np.array_equal(simplex.basis_solution, expected_basis_solution)
Example #23
0
 def testSimplex(self):
     s = Simplex(testMatrix2)
     obj = s.runSimplex()
     self.assertEqual(obj, 13)
     expected = Array([
         [F(0), F(3), F(0), F(1), F(0), F(1), F(13)],
         [F(1), F(2), F(0), F(2), F(0), F(-1), F(2)],
         [F(0), F(-5), F(0), F(-2), F(1), F(0), F(1)],
         [F(0), F(-1), F(1), F(-3), F(0), F(2), F(1)],
     ])
     for i in range(len(expected)):
         self.assertEqual(s.tableaux[i], expected[i], "(row %d)" % i)
     self.assertEqual(s.basicVariables[1:], [0, 4, 2])
    def test_full_simplex(self):
        coefficients = np.array([[1,  1],
                                 [1, -1]])
        constraints = np.array([[4],
                                [2]])
        objective = np.array([3, 2])
        simplex = Simplex(coefficients=coefficients, constraints=constraints, objective=objective)

        simplex.run()

        assert simplex.is_optimal
        assert simplex.value == 11
        assert np.array_equal(simplex.solution, np.array([[3], [1]]))
Example #25
0
    def test_can_add_slack_variables_for_different_size_matrices(self):
        """Checks that the slack variables can be added for larger matrices."""
        simplex = Simplex()
        coefficients = np.array([[1,  1, 1],
                                 [1, -1, 2],
                                 [2,  1, 1]])
        simplex.coefficients = coefficients
        expected_a = np.array([[1,  1, 1, 1, 0, 0],
                               [1, -1, 2, 0, 1, 0],
                               [2,  1, 1, 0, 0, 1]])

        simplex.initialize_slack()

        assert np.array_equal(simplex.coefficients, expected_a)
Example #26
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
    def test_full_simplex2(self):
        coefficients = np.array([[ 1,  1],
                                 [ 3, -8],
                                 [10,  7]])
        constraints = np.array([[ 4],
                                [24],
                                [35]])
        objective = np.array([5, 7])
        simplex = Simplex(coefficients=coefficients, constraints=constraints, objective=objective)

        simplex.run()

        assert simplex.is_optimal
        assert simplex.value == 28
        assert np.array_equal(simplex.solution, np.array([[0], [4]]))
Example #28
0
 def testRemoveBasicVariable(self):
     s = Simplex(Array([
         [0, -1, -1, 0, 0],
         [1, -1, +1, 0, 0],
         [0, -1, -1, 1, 2]
     ]))
     s.basicVariables = [None, 0, 3]
     expected = Array([
         [0, -2, 0, 0],
         [1, -1, 0, 0],
         [0, -2, 1, 2]
     ])
     s.removeVariable()
     for i in range(len(expected)):
         self.assertEqual(s.tableaux[i], expected[i], "(row %d)" % i)
     self.assertEqual(s.basicVariables[1:], [0, 2])
Example #29
0
    def __init__(self, seed, inChunkPos):
        self.chunkPos = inChunkPos
        random.seed(seed)
        self.noiseGen = Simplex(seed)
        self.chunkSize = 16

        self.mats = {}
        self.mats[-10] = terrain.Water.id
        self.mats[-9] = terrain.Water.id
        self.mats[-8] = terrain.Water.id
        self.mats[-7] = terrain.Water.id
        self.mats[-6] = terrain.Water.id
        self.mats[-5] = terrain.Water.id
        self.mats[-4] = terrain.Water.id
        self.mats[-3] = terrain.Water.id
        self.mats[-2] = terrain.Water.id
        self.mats[-1] = terrain.Water.id
        self.mats[0] = terrain.Water.id
        self.mats[1] = terrain.Sand.id
        self.mats[2] = terrain.Grass.id
        self.mats[3] = terrain.Grass.id
        self.mats[4] = terrain.Brush.id
        self.mats[5] = terrain.Foothills.id
        self.mats[6] = terrain.Mountain.id
        self.mats[7] = terrain.Mountain.id
        self.mats[8] = terrain.Peak.id
        self.mats[9] = terrain.Peak.id
        self.mats[10] = terrain.Peak.id
Example #30
0
	def test_simplex_key_generators(self):
		simplex = Simplex(4, 20)

		simplex_keys_1 = []
		for simplex_key in simplex.simplex_keys():
			simplex_keys_1.append(simplex_key)

		simplex_keys_2 = []
		for simplex_key in simplex.simplex_keys_lazy_but_correct():
			simplex_keys_2.append(simplex_key)

		self.assertEqual(len(simplex_keys_1), len(simplex_keys_2))
		self.assertEqual(len(simplex_keys_1), 10626)

		for i in range(len(simplex_keys_1)):
			numpy.testing.assert_array_equal(simplex_keys_1[i], simplex_keys_2[i])
Example #31
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)
Example #32
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)
Example #33
0
def simplex_optimize():
    c = np.array([[6, 5, 4]])
    A = np.array([[2, 1, 1], [1, 3, 2], [2, 1, 2]])
    b = np.array([[240, 360, 300]])

    simplex = Simplex(c, A, b)
    optimal = False
    count = 0
    while not optimal:
        tab, optimal = simplex.simplex_solve()
        count += 1
        print('-------Tableau {}-------'.format(count))
        print(tab.astype('float'))
    optimal = simplex.optimal()

    print('x1* = {} \n x2* = {} \n x3* = {}'.format(optimal[0], optimal[1], 0))
    print('Optimal objective = {}'.format(optimal[-1]))
Example #34
0
def testf1():
    print("Testing f1...")
    '''
    max Z = 3x + 2y (objective function)
    s.t.
        x + 2y <= 4
        x - y <= 1
        x,y >= 0
    '''
    c = [3, 2]
    A = [[1,  2],
         [1, -1]]
    b = [4, 1]
    maxi = True
    f1 = Simplex(c, A, b, maxi)
    x1, z1 = f1.simplex()
    assert(x1 == [2, 1] and z1 == 8)
Example #35
0
    def test_swap_basis_variables(self):
        simplex = Simplex()
        simplex.basis_size = 2
        simplex.basis_variables = [Variable(index=0, is_slack=True), Variable(index=1, is_slack=True)]
        simplex.objective = np.array([3, 2, 0, 0], dtype='float')
        simplex.basis_objective = np.array([[0],
                                            [0]], dtype='float')
        simplex.pivot_row_index = 1
        simplex.pivot_column_index = 0

        simplex.swap_basis_variable()

        expected_basis_objective = np.array([[0],
                                             [3]], dtype='float')
        expected_basis_variables = [Variable(index=0, is_slack=True), Variable(index=0, is_slack=False)]
        assert np.array_equal(simplex.basis_objective, expected_basis_objective)
        assert simplex.basis_variables == expected_basis_variables
Example #36
0
def testf2():
    print("Testing f2...")
    '''
	min Z = 3x + 2y (objective function)
	s.t.
		x + 2y <= 4
		x - y <= 1
		x,y >= 0
	'''
    c = [3, 2]
    A = [[-1,  -2],
         [-1, 1]]
    b = [-4, -1]
    maxi = False
    f2 = Simplex(c, A, b, maxi)
    x2, z2 = f2.simplex()
    assert(x2 == [0, 0] and z2 == 0)
Example #37
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
Example #38
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
Example #39
0
    def test_making_pivot_element_one_multiplies_the_basis_objective_row(self):
        simplex = Simplex()
        simplex.pivot_column_index = 2
        simplex.pivot_row_index = 1
        simplex.basis_objective = np.array([[1], [1], [1]], dtype='float')
        simplex.basis_solution = np.array([[2], [3], [4]], dtype='float')
        simplex.coefficients = np.array([[1, 2, -4],
                                         [2, 1,  3],
                                         [2, 1,  1]], dtype='float')

        simplex.make_pivot_element_one()

        expected_basis_objective = np.array([[1], [1/3.0], [1]], dtype='float')
        assert np.array_equal(simplex.basis_objective, expected_basis_objective)
Example #40
0
 def testPerformPivot(self):
     s = Simplex(testMatrix2)
     row, column = s.choosePivot()
     self.assertEqual((row, column), (1, 0))
     s.performPivot(row, column)
     expected = Array([
         [F(0), F(7, 2), F(-1, 2), F(5, 2), F(0), F(0), F(25, 2)],
         [F(1), F(3, 2), F(1, 2), F(1, 2), F(0), F(0), F(5, 2)],
         [F(0), F(-5), F(0), F(-2), F(1), F(0), F(1)],
         [F(0), F(-1, 2), F(1, 2), F(-3, 2), F(0), F(1), F(1, 2)],
     ])
     for i in range(len(expected)):
         self.assertEqual(s.tableaux[i], expected[i], "(row %d)" % i)
     self.assertEqual(s.basicVariables[1:], [0, 4, 5])
     row, column = s.choosePivot()
     self.assertEqual((row, column), (3, 2))
     s.performPivot(row, column)
     expected = Array([
         [F(0), F(3), F(0), F(1), F(0), F(1), F(13)],
         [F(1), F(2), F(0), F(2), F(0), F(-1), F(2)],
         [F(0), F(-5), F(0), F(-2), F(1), F(0), F(1)],
         [F(0), F(-1), F(1), F(-3), F(0), F(2), F(1)],
     ])
     for i in range(len(expected)):
         self.assertEqual(s.tableaux[i], expected[i], "(row %d)" % i)
     self.assertEqual(s.basicVariables[1:], [0, 4, 2])
Example #41
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()
Example #42
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()
Example #43
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()
Example #44
0
	def __init__(self, chunkManager, seed):
		
		self.chunkManager = chunkManager
		self.mapDir = 'save/map/'
		self.noise = Simplex(seed)
		
		if not os.path.isdir(self.mapDir):
			os.mkdir(self.mapDir)
		
		self.basePath = os.path.dirname(__file__)
		self.cache = {}
Example #45
0
    def test_can_make_tableau_from_constraints_coefficients_and_objective(self):
        simplex = Simplex()
        simplex.coefficients = np.array([[1,  1],
                                         [1, -1]])
        simplex.constraints = np.array([[4],
                                        [2]])

        simplex.initialize_tableau()

        expected_coefficients = np.array([[1,  1, 1, 0],
                                          [1, -1, 0, 1]])
        expected_basis_variables = [Variable(index=0, is_slack=True), Variable(index=1, is_slack=True)]
        expected_basis_objective = np.array([[0],
                                             [0]])
        expected_basis_solution = np.array([[4],
                                            [2]])
        np.array_equal(simplex.coefficients, expected_coefficients)
        assert simplex.basis_variables == expected_basis_variables
        np.array_equal(simplex.basis_objective, expected_basis_objective)
        np.array_equal(simplex.basis_solution, expected_basis_solution)
Example #46
0
def step(request):

    iteration = int(request.GET.get('iteration'))
    points = json.loads(request.GET.get('points'))
    bounds_json = request.GET.get('bounds')
    bounds = json.loads(bounds_json) if bounds_json is not None else None
    get_images = bool(request.GET.get('get_images'))

    # Store the ranks that have been given so far
    for p in points:
        Rank.objects.create(
            rank=p['rank'],
            index=p['index'],
            iteration=iteration,
            type=p['type'],
        )

    if len(points) > 0:
        simplex = Simplex()
        new_points = simplex.step(points, bounds)
    else:
        new_points = [
            {'value': [0, 0, 0], 'type': 'vertex'},
            {'value': [0, 0, 4], 'type': 'vertex'},
            {'value': [0, 4, 0], 'type': 'vertex'},
            {'value': [4, 0, 0], 'type': 'vertex'},
        ]

    for p in new_points:
        if 'rank' not in p:
            Job.objects.create(
                ipAddr=get_real_ip(request),
                value=json.dumps(p['value']),
                type=p['type'],
            )
        if get_images and 'img' not in p:
            p['img'] = get_cut_image_name(*p['value'])

    return JsonResponse({
        'points': new_points,
    })
Example #47
0
    def test_calculate_reduced_costs(self):
        simplex = Simplex()
        simplex.basis_size = 2
        simplex.coefficients = np.array([[1,  1, 1, 0],
                                         [1, -1, 0, 1]])
        simplex.basis_objective = np.array([[0],
                                            [0]])
        simplex.basis_solution = np.array([[4],
                                           [2]])
        simplex.objective = np.array([3, 2, 0, 0])

        simplex.calculate_reduced_costs()

        expected_reduced_costs = np.array([-3, -2, 0, 0])
        assert np.array_equal(simplex.reduced_costs, expected_reduced_costs)
Example #48
0
    def test_row_independence_subtracts_basis_solution_rows(self):
        simplex = Simplex()
        simplex.pivot_column_index = 0
        simplex.pivot_row_index = 1
        simplex.coefficients = np.array([[1,  1, 1, 0],
                                         [1, -1, 0, 1]], dtype='float')
        simplex.basis_solution = np.array([[4],
                                           [2]], dtype='float')
        simplex.basis_objective = np.array([[0],
                                            [0]], dtype='float')

        simplex.make_pivot_independent()

        expected_basis_solution = np.array([[2],
                                            [2]], dtype='float')
        assert np.array_equal(simplex.basis_solution, expected_basis_solution)
Example #49
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'))
Example #50
0
 def testChosePivot(self):
     s = Simplex(testMatrix2)
     row, column = s.choosePivot()
     self.assertEqual(column, 0)
     self.assertEqual(row, 1)
     for i in range(3):
         s.tableaux[0][i] = F(1)
     with self.assertRaises(EndOfAlgorithm):
         row, column = s.choosePivot()
     s.tableaux[0][0] = F(-1)
     for i in range(1, 4):
         s.tableaux[i][0] = F(-1)
     with self.assertRaises(Unbounded):
         row, column = s.choosePivot()
Example #51
0
    def test_pivot_row_attaining(self):
        simplex = Simplex()
        simplex.pivot_column_index = 1
        simplex.coefficients = np.array([[1, 2, -1],
                                         [2, 1,  1],
                                         [2, 1,  1]])
        simplex.basis_solution = np.array([[-5], [1], [2]])

        simplex.obtain_pivot_row_index()

        assert simplex.pivot_row_index == 1