def main(): decisions_variables = int( input("Quantas variaveis de decisao tem o problema: ")) constraints = int( input("Quantas restricoes (Exceto a restrição de não negatividade): ")) goal = int( input("Qual o objetivo da funcao (1-Maximizar / 2-Minimizar): ")) columns = decisions_variables + constraints + 1 # Quantidade de colunas da tabela lines = constraints + 1 # Quantidade de linhas da tabela print("Entre com a Funcao(z) na forma canonica:") # Preenchendo a função objetivo z z = np.zeros(columns) for i in range(0, decisions_variables): z[i] = (int(input('X' + str(i + 1) + ': '))) # Preenchendo as restrições e montando a primeira tabela table = np.zeros((lines, columns)) for i in range(0, columns): if z[i] != 0: table[0][i] = z[i] * -1 for i in range(1, lines): print("Restrição " + str(i) + " (forma canonica):") option = 0 for j in range(0, columns): # Se estiver entrando com as X da restrição if j < decisions_variables: table[i][j] = (input('X' + str(j + 1) + ': ')) # Se estiver entrando com o final da restrição elif j == columns - 1: if option == 1: table[i][j] = (input('<= ')) else: table[i][j] = (input('>= ')) # Coloca 1 ou -1 automaticamente elif j == i + (decisions_variables) - 1: option = int(input("1 - <= / 2 - >= : ")) if option == 1: table[i][i + (decisions_variables) - 1] = 1 else: table[i][i + (decisions_variables) - 1] = -1 sy.simplex(table, lines, columns, decisions_variables, constraints) # Chamando a função para realizar o método simplex
def fFile(): num = [] num1 = [] file = open("testowedane.txt", "r") for line in file: fs = [float(f) for f in line.split(",")] num.append(fs) z = num[0][0] c = num[1][0] for x in range(2, len(num)): num1.append(num[x]) simplex.simplex(num1) messagebox.showinfo("Simplex", "Wczytano z testowedane.txt, zapisano result.txt")
def test_lista6(self): func = [-2, -3, -4] sa = [{ 'type': 'le', 'idx': [1.0, 1.0, 1.0], 'z': 100.0 }, { 'type': 'le', 'idx': [2.0, 1.0, 0.0], 'z': 210.0 }, { 'type': 'le', 'idx': [1.0, 0.0, 0.0], 'z': 80.0 }] result, z = simplex(func, sa) self.assertAlmostEqual(z, -400) expected = [0, 0, 100] for i, x in enumerate(result): self.assertAlmostEqual(x, expected[i])
def test_lista2(self): func = [-4, -5] sa = [{ 'type': 'e', 'idx': [1.0, 1.0], 'z': 98.0 }, { 'type': 'ge', 'idx': [2.0, -1.0], 'z': 10.0 }, { 'type': 'le', 'idx': [-2.0, 1.0], 'z': 5.0 }] result, z = simplex(func, sa) self.assertAlmostEqual(z, -454) expected = [36, 62] for i, x in enumerate(result): self.assertAlmostEqual(x, expected[i])
def test_lista4(self): func = [2, 2, 3] sa = [{ 'type': 'ge', 'idx': [-1.0, 2.0, 5.0], 'z': 30.0 }, { 'type': 'ge', 'idx': [3.0, 4.0, -1.0], 'z': 60.0 }, { 'type': 'e', 'idx': [2.0, 1.0, 2.0], 'z': 40.0 }] result, z = simplex(func, sa) self.assertAlmostEqual(z, 53) expected = [11, 8, 5] for i, x in enumerate(result): self.assertAlmostEqual(x, expected[i])
def test_two(self): func = [-6, 1] sa = [ { 'type': 'le', 'idx': [4.0, 1.0], 'z': 21.0 }, { 'type': 'ge', 'idx': [2.0, 3.0], 'z': 13.0 }, { 'type': 'e', 'idx': [-1.0, 1.0], 'z': 1.0 }, ] result, x = simplex(func, sa) self.assertAlmostEqual(x, -19) expected = [4, 5] for i, x in enumerate(result): self.assertAlmostEqual(x, expected[i])
def hello(dawword, daw3, daw, daw2, b_in, a_in, self): daw4 = [] for i in range(len(daw)): aaaa = daw[i].get() daw4.append(aaaa) daw.clear() for j in range(len(daw4)): bbbb = daw4[j] daw.append(bbbb) daw4.clear() for ii in range(len(daw2)): aa = daw2[ii].get() daw4.append(aa) daw2.clear() for jj in range(len(daw4)): bb = daw4[jj] daw2.append(bb) daw4.clear() daw3.append(daw) daw3.extend(split_list(daw2, b_in)) for row in dawword: if row.get() == "max": for g in range(len(daw3[0]) - a_in): daw3[0][g] = daw3[0][g] * -1 if row.get() == ">=": print(row) print(row.get()) print(dawword.index(row)) for g in range(len(daw3[1]) - a_in): daw3[dawword.index(row)][g] = daw3[dawword.index(row)][g] * -1 simplex.simplex(daw3) daw.clear() daw2.clear() daw3.clear() dawword.clear() self.destroy() messagebox.showinfo("Simplex", "Wyniki zapisano w pliku result.txt")
def solve(self, monitors=None, mapper=None, **options): _fill_defaults(options, self.settings) # TODO: no mapper?? from simplex import simplex self._update = MonitorRunner(problem=self.problem, monitors=monitors) bounds = numpy.array([p.bounds.limits for p in self.problem.parameters]).T result = simplex(f=self.problem.nllf, x0=self.problem.getp(), bounds=bounds, update_handler=self._monitor, maxiter=options['steps'], radius=options['radius']) # Let simplex propose the starting point for the next amoeba # fit in a multistart amoeba context. If the best is always # used, the fit can get stuck in a local minimum. self.problem.setp(result.next_start) return result.x, result.fx
def solve_ilp(dictionary, basic_vars, non_basic_vars): cur_dict, cur_basic, cur_non_basic = simplex( dictionary, basic_vars, non_basic_vars) while True: if all_objective_vars_are_int(cur_dict, cur_basic, non_basic_vars): return cur_dict, cur_basic, cur_non_basic #print("B", cur_dict[ - 1, 0]) #print("B", cur_dict) fractional_eqns=cur_dict[:-1][np.array( cur_dict[:-1,0].H - np.floor(cur_dict[:-1,0]).H > THRESHOLD)[0]] #print(len(fractional_eqns)) cutting_planes = np.c_[ -fractional_eqns[:,0] + np.floor(fractional_eqns[:,0]), -fractional_eqns[:,1:] - np.floor(-fractional_eqns[:,1:])] cur_dict = np.vstack((cur_dict[:-1], cutting_planes, cur_dict[-1])) cur_max_var = max(np.r_[cur_non_basic, cur_basic]) cur_basic = np.r_[cur_basic, range(cur_max_var + 1, cur_max_var + 1 + len(cutting_planes))].astype(int) #print("A", cur_dict, cur_basic, cur_non_basic) cur_dict, cur_basic, cur_non_basic = dual_simplex(cur_dict, cur_basic, cur_non_basic)
def test_one(self): func = [4, 1, 1] sa = [{ 'type': 'e', 'idx': [2.0, 1.0, 2.0], 'z': 4.0 }, { 'type': 'e', 'idx': [3.0, 3.0, 1.0], 'z': 3.0 }] result, x = simplex(func, sa) self.assertAlmostEqual(x, 2.2) expected = [0, 0.4, 1.8] for i, x in enumerate(result): self.assertAlmostEqual(x, expected[i])
def test_lista5(self): func = [-10, -12] sa = [{ 'type': 'le', 'idx': [1.0, 1.0], 'z': 100.0 }, { 'type': 'le', 'idx': [2.0, 3.0], 'z': 270.0 }] result, z = simplex(func, sa) self.assertAlmostEqual(z, -1140) expected = [30, 70] for i, x in enumerate(result): self.assertAlmostEqual(x, expected[i])
def test_lista1(self): func = [4, 6] sa = [{ 'type': 'ge', 'idx': [3.0, 2.0], 'z': 24.0 }, { 'type': 'ge', 'idx': [2.0, 6.0], 'z': 30.0 }] result, z = simplex(func, sa) self.assertAlmostEqual(z, 42) expected = [6, 3] for i, x in enumerate(result): self.assertAlmostEqual(x, expected[i])
import simplex from tables.create_table import create_simplex_table from tables.tables import all_tables_descriptions for table_description in all_tables_descriptions: create_simplex_table(table_description) print(simplex.simplex(table_description))
resp. 500,400 and 400 units. Shipping costs are: Plant 1 --> Depot A = 16€ Plant 2 --> Depot A = 18€ Plant 1 --> Depot B = 20€ Plant 2 --> Depot B = 16€ Plant 1 --> Depot C = 22€ Plant 2 --> Depot C = 14€ What shipping schedule will enable the company to meet the depots' requirements and keep the shipping costs at minimum? What is the minimum cost? Be the variables (X1,X2,....,X6) resp. the numbers of chips shipped from plant 1 to A, plant 1 to B and so on. """ A = np.array([[1, 1, 1, 0, 0, 0], [0, 0, 0, 1, 1, 1], [1, 0, 0, 1, 0, 0], [0, 1, 0, 0, 1, 0], [0, 0, 1, 0, 0, 1]]) B = np.array([[800], [600], [500], [400], [400]]) c = np.array([[16], [20], [22], [18], [16], [14]]) signs = np.array([[-1], [-1], [1], [1], [1]]) minimization = simplex(A, B, c, signs, False, False) minimization.compute_simplex() print("\n \n") """ A company produces four types of engines that are produced from 4 types of machines. The first machine produces the first engine in 1 minute, the second in 2 minutes, the third in 3 minutes and the fourth in 2 minutes. The second machine produces the first engine in 3 minutes, the second in 2 minutes, the third in 4 minutes and the fourth in 6 minutes. The third machine produces the first engine in 2 minutes, the second in 1 minute, the third in 3 minutes, the fourth in 3 minutes. The fourth machine produces the first engine in 2 minutes, the second engine in 4 minutes, the third engine in 3 minutes, the fourth engine in 5 minutes. The first engine is sold for 20€, the second for 35€, the third for 40€ and the fourth for 50€. Which is the number of engines of each type ( namely X1,X2,X3,X4) that should be produced per hour in order to
for i in M[0]: if i!=0: c[k] = -1 k+=1 b = np.zeros(num_vertices-2) b = np.concatenate((b,u),axis=None) x = np.zeros(A.shape[1]) print(A) print('b',b) print('c',c) ################## Example ################################# # A = np.array([[1,1,1,0],[3,2,0,1]]) # b = np.array([5,12]) # # b = b.reshape(b.shape[0],1) # c = np.array([-6,-5,0,0]) # x = np.zeros(A.shape[1]) ################################################### print("Generating Basis") inds = simplex.gen_basis(A,b,A.shape[0],A.shape[1]) print("Done") print("Initial BFS", inds) B = A[:,inds] simplex.simplex(A,c,b,x,A.shape[0],A.shape[1],B,inds)
print u #print f0(u) print 'Solving the optimizing problems with the simplex' f0 = lambda x: (x[0]-0.5)**2+(x[1]+1)**2 s=[[-1.5,-1.9],[1.5,1.5],[1.0,-1]] #f0 = lambda x: (1-x[0])**2+100*(x[1]-x[0]**2)**2 print 'Solving the equation f(x,y)=(x-0.5)^2+(y+1)^2' print 'The starting simplex s=[[-1.5,-1.9],[1.5,1.5],[1.0,-1]] and acceptance 1e-2' #The starting simplex a=simplex.simplex(f0,s,1e-2) pce=[0,0] n=2 h=1 def reflect(pce,s,n): return [pce[i]+(pce[i]-s[h][i]) for i in range(n)] def expand(pce,s,n): return [pce[i]+2*(pce[i]-s[h][i])for i in range(n)] def contract(pce,s,n): return [pce[i]+0.5*(pce[i]-s[h][i]) for i in range(n)] print 'The resulting point' print a#contract(pce,s,n)
) func = parse_function(func) if obj == 'max': func = multiply_array_by_scalar(func, -1) eq_number = int(raw_input('\nNumero de restricoes: ')) sa = [] print '' for i in range(1, eq_number + 1): eq = raw_input('Restricao %d: ' % (i)) sa.append(parse_restriction(eq)) print '\n' result, z = simplex(func, sa) print '' for i, x in enumerate(result): print 'x%d = %.2f' % (i + 1, x) if obj == 'max': z *= -1 print '\nz = %.2f' % z raw_input()
import sys # da liegen die Methoden, da sie Teil des Skripts sind sys.path.append("..") from simplex import simplex # Abbildung 9.3.1 # die zweite Bedingung ist offenbar sinnlos A = array(((-1, -1, -1), (2, 2, 2))) b = array((-1, 2)) for c, res in (((0.5, 0.5, 0), (0.0,0.0,1.0)), ((-0.5, 0.5, 0), (1.0,0.0,0.0)), ((-0.1, -0.5, 0), (0.0,1.0,0.0))): answer = simplex(array(c), A, b) if not allclose(answer, array(res)): raise Exception("Simplex hat das Minimum nicht gefunden") # die guten, alten Beispiele aus den Numerik-Uebungen # Bauer 2a) A = array(((1, 1, 1,0,0), (40,120, 0,1,0), ( 7, 12, 0,0,1)),dtype=float) b = array((40, 2400, 312), dtype=float) c = array((-100, -250, 0, 0, 0), dtype=float) answer = simplex(array(c), A, b) if not allclose(answer, array((24, 12, 4, 0, 0), dtype=float)): raise Exception("Simplex hat das Minimum nicht gefunden")
from simplex import (simplex, phase_I) # Specify the LP and convert to standard form: A_ineq = np.array([ [0, 1], # <= 9 [1, 2], # <= 20 [1, 3], # <= 28 [1, 1], # <= 13 [2, 1], # <= 20 [3, 1], # <= 28 [1, 0] ]) # <= 9 m = A_ineq.shape[0] # m inequality constraints A = np.hstack((A_ineq, np.eye(m))) b = np.array([9, 20, 28, 13, 20, 28, 9]) c = np.hstack((np.array([-1.0, -1.1]), np.zeros((m)))) n = len(c) # n variables in standard form # Solve a Phase-I problem to determine a basic feasible starting point x0 # (could in this simple case also use x0 = np.hstack((np.zeros(n-m), b))): x0, _ = phase_I(A, b) # Solve with simplex (Procedure 13.1), starting from x0: indexing = 1 # print with 1 as base index, like in the texbook x, output = simplex(c, A, b, x0, report=True, indexing=indexing) print('Points visited in the x1-x2 plane:') print(output['iterates'][:2, :]) print(f'Sequence of basic variables ({indexing}-indexed):') print(output['bases'] + indexing)
from functions import f4 from simplex import simplex from hooke_jeeves import hooke_jeeves if __name__ == '__main__': x4 = [5.0, 5.0] xmin4 = [0, 0] fmin4 = 0 print("Hoock Jeeves algorithm:") x = hooke_jeeves(f4, x4) print(x) print("Simplex algorithm:") x = simplex(f4, x4) print(x)
input_pl = np.array(json.loads(hue), dtype=float) #converts to fraction matrix input_pl = np.matrix(input_pl) input_pl = input_pl.astype('object') for i in range(input_pl.shape[0]): for j in range(input_pl.shape[1]): input_pl[i, j] = fractions.Fraction(input_pl[i, j]) #constructs matrix A, in a numpy array format, separating from c vector Amatrix = input_pl[1:, :-1] Bmatrix = input_pl[1:, int(n):] Cmatrix = input_pl[0, :-1] base = {} j = 1 for i in range(int(m), 0, -1): base[i - 1] = (int(n) + int(m) - j) j += 1 op_matrix = pl.make_frac_matrix(np.identity(int(m))) #PL contruction progL = pl.PL(Amatrix, Cmatrix, Bmatrix, int(n), int(m), op_matrix, base) #puts it in FPI format progL.make_FPI() simplex.simplex(progL)
def calculate_simplex(f, A, b, resolution): fr=[ -x for x in f ] constraints=[] for i in range(0, len(A)): constraints.append( ( A[i], b[i] ) ) return simplex.simplex(fr, constraints)
def resultado(): xValsHtml = request.form.getlist('xVals') yValsHtml = request.form.getlist('yVals') desigualdadHtml = request.form.getlist('desigualdad') results = request.form.getlist('results') global cantVars global desigual global desigualdad, mType, valorPivote, indexFP, indexCP global mTypeD, cantVarsD, valorPivoteD, indexFOD, indexCPD print("Antes de create matrix") matrixP, desigual = inp.createMatrix(xValsHtml, yValsHtml, desigualdadHtml, results, cantVars, objFunc, cantRest) print("medio") slackVarsP, cantVarsP, cantRestP, matTranspose, slackDual, cantVarsD, cantRestD, dType, desigualD, ursDual = tp.transpuesta(matrixP, desigual, pType, ursVars) print("despues de create matrix") matRest = matrixP desigualdad = desigual matrixP, mType, cantVars, desigual = bM.bigM(matrixP, slackVarsP, cantVarsP, cantRestP, pType, desigual, ursVars) continueSimp = sp.continueSimplex(mType, matrixP) print("antes de simplex primal") while continueSimp == True: indexCP, indexFP, valorPivote = sp.getPivot(mType, matrixP) matrixP = sp.simplex(matrixP, indexFP, valorPivote, indexCP) continueSimp = sp.continueSimplex(mType, matrixP) print("\nSOLUCION PRIMAL: ", matrixP[0][-1], "\n") matrixD, mTypeD, cantVarsD, desigualD = bM.bigM(matTranspose, slackDual, cantVarsD, cantRestD, dType, desigualD, ursDual) continueSimp = sp.continueSimplex(mTypeD, matrixD) print("antes de simplex dual") print(continueSimp) while continueSimp == True: indexCPD, indexFOD, valorPivoteD = sp.getPivot(mTypeD, matrixD) print("\nindexCPD, indexFOD, valorPivoteD") print(indexCPD, indexFOD, valorPivoteD) matrixD = sp.simplex(matrixD, indexFOD, valorPivoteD, indexCPD) print("m", mTypeD) continueSimp = sp.continueSimplex(mTypeD, matrixD) print(continueSimp) print("\nSOLUCION DUAL: ", matrixD[0][-1]) global xVals, yVals, pts, punts xVals, yVals = ent.maxValues(matRest, desigualdad) pts = ent.puntos(xVals, yVals) punts = ent.ptsReales(pts, matRest, desigualdad) resultadosP, xy = rs.resultados(punts, matRest) print("\nresultss: ") #--------------- BORRAR ---------------------------- print(resultadosP) return render_template('resultado.html', cantVarsP = cantVarsP, cantRestP = cantRestP, pType = pType, desigual = desigual, matrixP = matrixP, cantVarsD = cantVarsD, cantRestD = cantRestD, dType = dType, desigualD = desigualD, matTranspose = matTranspose, matrix = matrixP, matrixD = matrixD, sol = matrixP[0][-1], xVals = xy[0], yVals = xy[1], resultadosP = resultadosP )
import numpy as np import simplex A = np.array([[1, 1], [16, 8], [9000, 5000]]) b = np.array([[44], [512], [300000]]) basis = np.array([2]) c = np.array([30000, 20000]) x, y, cost = simplex.simplex(A, b, c, basis) print x print y print cost
def calculate_simplex(f, A, b, resolution): fr = [-x for x in f] constraints = [] for i in range(0, len(A)): constraints.append((A[i], b[i])) return simplex.simplex(fr, constraints)
def maximum_profit(self): self.assertEqual( simplex.simplex([6, 6], [[2, 0], [1, 2], [1, 4]], [20, 37, 30])[1], 90.0)
from simplex import simplex from functions import f1 if __name__ == '__main__': x1 = [0.5, 0.5] for i in range(1, 21): print("Simplex with dx=", i) x = simplex(f1, x1, dx=i) print(x) print()
src_2_supply = src_2.pop(0) # Demand info dmd_msg = "Demand Information" demand_info_fn = [ "Destination 1 Demand", "Destination 2 Demand", "Destination 3 Demand" ] demand_info = [] demand_info = multenterbox(dmd_msg, title, demand_info_fn) if not all(demand_info): msgbox("Invalid Input") continue obj_func = src_1 + src_2 result = simplex.simplex(obj_func, [src_1_supply, src_2_supply] + demand_info) A1 = result.x[0] A2 = result.x[1] A3 = result.x[2] B1 = result.x[3] B2 = result.x[4] B3 = result.x[5] msgbox("Total Cost: " + str(-1 * result.fun) + "\n" + "From Source A to Destination 1: " + str(A1) + "\n" + "From Source A to Destination 2: " + str(A2) + "\n" + "From Source A to Destination 3: " + str(A3) + "\n" + "From Source B to Destination 1: " + str(B1) + "\n" + "From Source B to Destination 2: " + str(B2) + "\n" + "From Source B to Destination 3: " + str(B3) + "\n" +
import numpy as np import simplex A = np.array([[1, 1],[16, 8],[9000, 5000] ]) b = np.array([[44],[512],[300000]]); basis = np.array([2]); c = np.array([30000, 20000]); x,y,cost = simplex.simplex(A,b,c,basis) print x print y print cost
def variant_4(self): self.assertEqual( simplex.simplex([11, 9], [[2, 3], [3, 1], [0, 1]], [20, 37, 30])[1], 110.0)
def main(): while True: try: number_of_values = int(input('Input number of variables: ')) break except ValueError: print( "ERROR! Number of values - must be integer value. Try again..." ) while True: try: number_of_constraint = int(input('Input number of constraints: ')) break except ValueError: print( "ERROR! Number of constraints - must be integer value. Try again..." ) function_coefficient = [] while True: try: print('Input coefficient of function F(t):') for i in range(number_of_values): t = float(input("Enter t_{0}: ".format(i + 1))) function_coefficient.append(t) break except ValueError: print( "ERROR! Coefficient of function must be float value. Try again..." ) matrix_A = [] while True: try: print( 'Enter matrix A - array of coefficients of the left part of the constraints ' ) for i in range(number_of_constraint): a = [] for j in range(number_of_values): a.append( float(input('Enter a_{0}_{1}: '.format(i + 1, j + 1)))) matrix_A.append(a) break except ValueError: print( 'ERROR! Coefficient of constraints must be float value. Try again...' ) maximum_b = [] while True: try: print('Input value of the right part of the constraints:') for i in range(number_of_constraint): b = float(input("Enter b_{0}: ".format(i + 1))) maximum_b.append(b) break except ValueError: print( "ERROR! Coefficient of function must be float value. Try again..." ) for i in range(0, number_of_constraint): additional_list = [0] * number_of_constraint additional_list[i] = 1 matrix_A[i] += additional_list function_coefficient += [0] * number_of_constraint t, v = simplex.simplex(function_coefficient, matrix_A, maximum_b) print('-' * 30) print('RESULT:') print('END SIMPLEX TABLE:') #[print(x) for x in t] for row in t: new_row = [] for i in range(-1, 2 * number_of_constraint - 1): new_row.append(row[i]) print(new_row) print('Point of maximum:') list_counter = [] # for row in t: # i = 1 # if t.index(row) < number_of_values-1: # list_counter.append(t.index(row)) # for value in row: # if value == 1 and row.index(value) <= number_of_values - 1: # print('t_{0} = '.format(i), row[-1]) # i += 1 # if len(list_counter) < number_of_values: # [print('t_{0} = '.format(x), 0) for x in range(number_of_values - len(list_counter) + 1, number_of_values + 1)] # else: # break list_counter = [] for row in t: i = 1 for value in row: if value == 1 and row.index(value) <= number_of_values - 1: print('t_{0} = '.format(i), row[-1]) i += 1 print('Maximum function =', v) return v
if __name__ == '__main__': print("Start for f1 ---------------------------") xmin1 = [1, 1] fmin1 = 0 print("Hoock Jeeves algoritm:") x = hooke_jeeves(f1, x1) print(x) print("Coordinate search algorith:") x = coordinate_search(f1, x1) print(x) print("Simplex algorithm:") x = simplex(f1, x1) print(x) print("Start for f2 ---------------------------") xmin2 = [4, 2] fmin2 = 0 print("Hoock Jeeves algoritm:") x = hooke_jeeves(f2, x2) print(x) print("Coordinate search algorith:") x = coordinate_search(f2, x2) print(x) print("Simplex algorithm:")