def poblacionInicial(self, modelo, forDelta): #self.solutions = [] npend = DATOS_TESADO[ "NumPendolas"] #Obtener el numero de pendolas de nuestra instancia min = modelo.tesadoMinimo #Obtenemos nuestro valor de tensado minimo #Se crean magnitudes Random print("Total poblacion: " + str(self.poblacion)) for i in range(self.poblacion): mag = [] mag2 = [] for j in range(npend): mag.append(random.uniform(min, modelo.tesadoMaximo[j])) mag2.append(random.uniform(min, modelo.tesadoMaximo[j])) #for j in range (npend): # mag.append(random.uniform(min, modelo.tesadoMaximo[j])) #La magnitud esta entre min y max #Se crean orden por permutaciones #z = randint(0, npend-1) #orden = self.permutaciones[z] #solution = Solution(orden, mag) #Solution z = randint(0, npend - 1) orden = self.permutaciones[z] solution = Solution(orden, mag) #Solution self.solutions.append(solution) z2 = randint(0, npend - 1) orden2 = self.permutaciones[z2] solution = Solution(orden2, mag2) self.deltaSolution.append(solution)
def __init__(self, my_id, run_id, rng, simulation=None, phi_1=1, phi_2=1, inertia=1): self.run_id = run_id self.id = my_id self.rng = rng self.simulation = simulation # optim self.current = Solution() self.pbest = Solution() self.gbest = Solution() self.size = self.simulation.get_nb_params() self.phi_1 = phi_1 self.phi_2 = phi_2 self.inertia = inertia self.velocity = [] # size = nb param simulation self.neighbours = [] # list of neighbours particles self.init = True self.initSolutions() self.initializeUniform()
def hill_climbing(initial_state, heuristic, limit=10, dimension=3): def add_cost(node): node.cost = node.depth + heuristic(node.state) current_node = Node(Board(initial_state, dimension=dimension), cost_fn=add_cost) side_moves = 0 steps = 0 while True: steps += 1 if(side_moves > limit): return Solution(current_node, steps, 0) best_neighbour = None for child in current_node.expand(): if(not best_neighbour): best_neighbour = child elif (child.cost < best_neighbour.cost): best_neighbour = child if(best_neighbour.cost > current_node.cost): return Solution(current_node, steps, 0) if(best_neighbour.cost == current_node.cost): side_moves += 1 else: side_moves = 0 current_node = best_neighbour
def plot_time(self, X, x0, t, string): """Plot the repartition of density, velocity and pressure at a given time t, on a mesh X, where the origin of the discontinuity is in x0. Save raw data in a file.""" f = open("../output/{}.txt".format(string), "w") f.write('%12s' % "x") f.write('%15s' % "rho") f.write('%15s' % "ux") f.write('%15s' % "p\n") Pressure = [Solution(self, (x - x0) / t).pressure for x in X] Velocity = [Solution(self, (x - x0) / t).velocity for x in X] Density = [Solution(self, (x - x0) / t).rho for x in X] for i in range(len(X)): f.write('%12.5E' % X[i]) f.write('%15.5E' % Density[i]) f.write('%15.5E' % Velocity[i]) f.write('%15.5E' % Pressure[i]) f.write("\n") fig, axs = plt.subplots(3, sharex=True) fig.suptitle("Solution of the Riemann problem\nat t = {}s".format(t)) axs[0].plot(X, Density) axs[1].plot(X, Velocity) axs[2].plot(X, Pressure) axs[0].grid() axs[0].set(ylabel="Density") axs[1].grid() axs[1].set(ylabel="Velocity") axs[2].grid() axs[2].set(ylabel="Pressure") plt.xlim((-.5, .5)) plt.xlabel("Location x")
def heuristic2opt(self, sol): # print(" Solution courante: ",sol.visited) nb = len(sol.visited) if nb > 3: # print(' Cout de : ',sol.cost) for i in range(nb - 3): #On teste jusqu'a 2 villes avant la derniere for j in range(i + 3, nb): sol2 = Solution(sol) sol2.inverser_ville(sol.visited[i], sol.visited[j]) sol2.cost = sol2.get_cost(SOURCE) if sol2.cost < sol.cost: sol = Solution(sol2) sol.cost = sol.get_cost(SOURCE) # print(" **Une permutation effectuee !! ") # print(" Solution nouvelle : ",sol.visited) # print(" Cout de : ",sol.cost) else: print(" Pas assez de villes pour 2-Opt") # print(" Solution finale : ",sol.visited) # print(" Cout final de : ",sol.get_cost(SOURCE)) return sol
def main(): g = Graph("N10.data") Kruskal.kruskal = Kruskal.Kruskal(g) heap = Q.PriorityQueue() sol = Solution(g) root = Node(SOURCE, sol) heap.put(root) while heap.qsize() > 0: node = heap.get() print("curCost: %d" % node.solution.cost) if len(node.solution.not_visited) == 0: if SOURCE in node.solution.visited: node.solution.printf() return else: child_sol = Solution(node.solution) child_sol.add_edge(node.v, SOURCE) child_node = Node(SOURCE, child_sol) heap.put(child_node) else: node.explore_node(heap)
def run(self): """ The hearth of the program All another class are starting with correct order from here :return: nothing """ self.start_window.start() if self.start_window.filename == 0: self.quit_app("No file selected") self.loading = Loading(self.start_window.filename) self.algorithm_type = self.start_window.checkvar.get() del self.start_window if self.loading.open_file() == False: self.quit_app("Corrupted file") if self.loading.scale() == False: self.quit_app( "Something went wrong with the reading from the file") self.tsp_window = TSPWindow(self.loading.node_coord_section, self.loading.scale_x, self.loading.scale_y, self.algorithm_type) #Genetic solution# if self.algorithm_type == 1: self.parameters_window = ParametersWindow() self.parameters_window.start() if self.parameters_window.population_size == 0: self.quit_app("No parameters selected") self.tsp_window.algorithm.set_parameters( self.parameters_window.population_size, self.parameters_window.probability_crossover, self.parameters_window.probability_mutation, self.parameters_window.number_generations, self.parameters_window.elitism_strategy_option, self.parameters_window.population_init_option, self.parameters_window.select_option, self.parameters_window.tournament_size, self.parameters_window.seed_option, self.parameters_window.seed_value) del self.parameters_window self.path_distances = self.tsp_window.start() self.avg_distances = self.tsp_window.avg_distance if self.path_distances != False: # Plot self.plotWindow = PlotWindow(self.path_distances, self.avg_distances) # self.plotWindow.start() # Solution self.solution = Solution(self.algorithm_type) self.solution.start() #Greedy solution# elif self.algorithm_type == 2: self.tsp_window.start() self.solution = Solution(self.algorithm_type) self.solution.start()
def test_something(self): n2 = ListNode(2) n1 = ListNode(1, n2) m2 = ListNode(2) m1 = ListNode(1, m2) self.assertEqual('1122', self.NodeListStr(Solution().mergeTwoLists(n1, m1))) self.assertEqual(None, Solution().mergeTwoLists(None, None))
def test_preorder_traversal(self): self.assertEqual([1, 2, 3], Solution().preorderTraversal( TreeNode(1, None, TreeNode(2, TreeNode(3), None)))) self.assertEqual([], Solution().preorderTraversal(None)) self.assertEqual([1], Solution().preorderTraversal(TreeNode(1)))
def get_solution(self, colors): self.colors = colors start_time = time.time() population = Population(self.graph, self.graph_v, self.population_size, self.fitness_threshold, self.rand, self.colors) while population.best_fitness() != 0 and population.generation() < self.max_generations: population.next_generation() end_time = time.time() if population.best_fitness() == 0: return Solution(population.best_individual(), self.graph, colors, population.generation(), end_time - start_time) return Solution(None, self.graph, colors, population.generation(), end_time - start_time)
def test_something(self): self.assertEqual( '12', self.NodeListStr(Solution().deleteDuplicates( self.create_node([1, 1, 2])))) self.assertEqual( '123', self.NodeListStr(Solution().deleteDuplicates( self.create_node([1, 1, 2, 3, 3])))) self.assertEqual('', self.NodeListStr(Solution().deleteDuplicates(None)))
def evaluate_neighbors(self, solution, N1, N2): ''' Evaluate Neighbors sol is the best solution g_sol is the evaluation selected is the movement (client, origin, destination) top is a list of the best movements: [(selected, g )] ''' min_g = float('inf') selected = None S_ = None #(is_aspirated(self.matrix[x, i]) or not(is_tabu(self.matrix[x, i])) top = [] # penalizations = np.argwhere(self.matrix >= 0) # print(penalizations) # for f, c in enumerate(penalizations): # if for pos in N1: testing = solution.X.copy() testing[pos[1], pos[0]] = 0 testing[pos[2], pos[0]] = 1 Y = [1 if x.sum() > 0 else 0 for x in testing] test_sol = Solution(testing.copy(), Y, solution.costs, solution.fixed) sol = self.g_func(test_sol, self.alpha) flag = self.is_feasible(test_sol, self.c_demand, self.f_capacities) if sol < min_g and (self.is_aspirated(sol, flag) or self.matrix[pos[2], pos[0]] < 0): min_g = sol selected = pos S_ = test_sol top.insert(0, (test_sol.copy(), min_g, selected)) for pos in N2: testing = solution.X.copy() testing[pos[2], pos[0]] = 0 testing[pos[3], pos[1]] = 0 testing[pos[2], pos[1]] = 1 testing[pos[3], pos[0]] = 1 Y = [1 if x.sum() > 0 else 0 for x in testing] test_sol = Solution(testing.copy(), Y, solution.costs, solution.fixed) sol = self.g_func(test_sol, self.alpha) flag = self.is_feasible(test_sol, self.c_demand, self.f_capacities) if sol < min_g and (self.is_aspirated(sol, flag) or self.matrix[pos[2], pos[1]] < 0): min_g = sol selected = pos S_ = test_sol top.insert(0, (test_sol.copy(), min_g, selected)) self.min_g = sol return S_, sol, selected, top
def psoVSmanual(manual_sol, best_pso_sol): best_solutions = [] best_pso = Solution() best_pso.setValues(best_pso_sol) best_pso.setEval(167) manual = Solution() manual.setValues(manual_sol) manual.setEval(450) best_solutions.append(manual) best_solutions.append(best_pso) return best_solutions
def TRANSSHIPMENT(self, R, Sol, T, MaxIter): """Add transferships to a PDP solution At each iteration, the transshipment heuristic is used to improve the PDP solution and obtain a solution to the PDPT. From the current PDP solution, each request (i, i+n) ∈ R; is removed from the solu- tion. Then, (i, i+n) is split into two different requests (i, et) and (st, i + n), where et and st are the inbound/outbound doors of a transshipment point t ∈ T. The best reinsertion cost of (i, i+n) in the solution is computed. The best insertion cost to insert (i, et) following by insertion of (st, i + n) in the solution is computed. The cost to insert (st, i+n) following by the insertion of (i, et) at their best position is computed. Between the three possibilities, the insertion or the reinsertions offering the minimum cost is performed. Runtime: Additional space: Parameters: R (): Sol (): T (): """ Tsol = Sol Tbest = Sol.f() for r in R: sol1 = Sol sol1.path.remove(r) for t in T: sol2 = sol1 sol3 = sol1 sol2 = self.PARA(r, sol2) sol3 = self.PARA((r[0], t), sol3) + self.PARA((t, r[1]), sol3) cost = min(sol2.f(), sol3.f()) if Tbest > cost: Tbest = cost Tsol = sol2 if sol2.f() < sol3.f() else sol3 Sol = Tsol return Tsol sol = Solution(floyd=self.floyd) sol1 = Solution(floyd=self.floyd) sol.distance = math.inf for i in range(MaxIter): for req in self.request: sol1 = self.PARA(req, sol1) sol1 = self.TRANSSHIPMENT(R, sol1, self.transfer_points) if sol1.f() < sol.f(): sol = sol1 sol1 = Solution(floyd=self.floyd) return sol
def test(self): self.assertTrue(Solution().isValid('()')) self.assertTrue(Solution().isValid('({[]})')) self.assertTrue(Solution().isValid('{}')) self.assertTrue(Solution().isValid('[]')) self.assertTrue(Solution().isValid('()[]{}')) self.assertFalse(Solution().isValid('[')) self.assertFalse(Solution().isValid(']')) self.assertFalse(Solution().isValid('(]')) self.assertFalse(Solution().isValid('([)]'))
def runACO(self, maxiteration): # Initialiser la meilleure solution globalement trouvee overall_best = Solution(self.graph) overall_best.cost = 9999999999999.0 for iter in range(maxiteration): # Pour chaque iteration # Initialiser la meilleure solution pour cette iteration iter_best = Solution(self.graph) iter_best.cost = 9999999999999.0 # Pour chacune des K fourmis for k in range(self.parameter_K): sk = Solution( self.graph ) # construction de la solution de chaque fourmis # Execution de la recherche locale for step in range( self.graph.N ): # Boucle chaque ville a visiter (il y en a N) current_city = sk.visited[-1] next_city = self.get_next_city( sk) # Trouver la prochaine ville sk.add_edge(current_city, next_city) # Mise a jour locale des pheromones self.local_update(sk) # Mise a jour de la meilleure solution pour cette iteration (iter): if sk.cost < iter_best.cost: iter_best = sk # Ameliorer la meilleure solution a l'aide de 2-Opt self.heuristic2opt(iter_best) # mise a jour globale de la pheromone self.global_update(iter_best) # Mise a jour de la meilleure solution trouvee a date (sur plusieurs iterations) if iter_best.cost < overall_best.cost: overall_best = iter_best #print('*** Meilleure Solution trouvee au cout de : ', overall_best.cost) #print(overall_best.visited) self.best = overall_best return overall_best
def loadTBFile(fileName, blaze="@:"): openTag = blaze closeTag = blaze + "/" top = currentSolution = Solution() top.fileName = fileName currentName = "" stack = [] for lineNumber, line in enumerate(open(fileName)): # check for / first because the match is more specific if line.count(closeTag): name = parseBlaze(line, closeTag) assert name == currentName, ( "mismatched end tag (%s vs %s) on line %s of %s" % (name, currentName, lineNumber + 1, top.fileName)) currentName, currentSolution = stack.pop() elif line.count(openTag): stack.append((currentName, currentSolution)) currentName = parseBlaze(line, openTag) currentSolution = currentSolution.blaze(currentName) else: currentSolution.append(line) assert stack == [], "expected close tag for %s" % currentName return top
def greedy(matrix_distance: list, start=0, initial=False, return_path=False) -> Solution or list: path = [] path_id = set() i = start while len(path) != len(matrix_distance): # добавляем вершину в результирующий путь path.append(matrix_distance[i][i].point1) path_id.add(matrix_distance[i][i].point1.get_id()) # находим минимальную стоимость future_point_index = -1 min_dist = float("inf") for ind, dist in enumerate(matrix_distance[i]): if dist.dist < min_dist and dist.point2.get_id() not in path_id: min_dist = dist.dist future_point_index = ind i = future_point_index if initial: path.append(matrix_distance[start][start].point1) if return_path: return path return Solution(path)
def local(initial_solution: Solution): """ local search by 2-opt :param initial_solution: :return: """ # print("Start 2-opt") length_path = initial_solution.get_length() best_solution = initial_solution best_path = initial_solution.get_path().copy() it_improved = True while it_improved: it_improved = False for i in range(1, length_path - 2): for j in range(i + 2, length_path): prev = Distance.distance(best_path[i - 1], best_path[i]) + Distance.distance( best_path[j - 1], best_path[j]) fut = Distance.distance(best_path[j], best_path[i]) + Distance.distance( best_path[j - 1], best_path[i - 1]) if prev > fut: best_path[i:j] = best_path[j - 1:i - 1:-1] best_solution = Solution(best_path) it_improved = True return best_solution
def __init__(self, nb_it, nb_eval, n, seed, nb_parti, inertia, phi1, phi2, run_id, conv_threshold): self.run_id = run_id self.iteration = 0 self.max_iterations = nb_it self.max_evaluations = nb_eval self.evaluations = 0 self.seed = seed self.convergence_threshold = conv_threshold self.rng = random.Random(self.seed) self.size = n # problem dimension self.nb_particles = nb_parti # number of particles self.simulation = Simulation(self.size, run_id, self.rng, self.convergence_threshold) # particle coefficients self.inertia = inertia self.phi_1 = phi1 self.phi_2 = phi2 # particle swarm self.swarm = [] # list of Particles self.best_particle = None # ATTENTION ICI PAS DE PARAM? FAUT CHANGER DS PARTICLE self.global_best_sol = Solution() self.best_timing = BIG_NUMBER # value of the best solution found self.printParameters() self.initialize() self.createSwarm()
def main(): """runs solution method """ solution = Solution() nums = [3, 4, 5, 1, 2] print(solution.findMin(nums))
def search(initial_state, frontier, dimension, cost_fn=None, check_explored=True): global explored_nodes initial_node = Node(Board(initial_state, dimension=dimension), cost_fn=cost_fn) frontier.insert(initial_node) # steps = 0 explored = [] while(not frontier.empty()): node = frontier.get() # steps += 1 explored_nodes += 1 if(node.state.check_final_state()): solution = Solution(node, len(explored), frontier.length()) return solution explored.append(node) for child in node.expand(): # Checks if node in frontier and get reference if it is alternative_node = frontier.check_node(child) should_expand = (not check_explored) or (child not in explored) # If not explored and not in frontier just add it if(should_expand and not alternative_node): frontier.update(child) # If node already in frontier but with higher cost just replace it if(alternative_node and alternative_node.cost > child.cost): alternative_node.update(child.parent, child.depth, child.cost) return False
def main(): # Build test tree treeNodeHead = testTree = TreeNode(3) testTree.left = TreeNode(9) testTree.right = TreeNode(20) testTree = testTree.right testTree.left = TreeNode(15) testTree.right = TreeNode(7) placeholder = testTree testTree = testTree.left testTree.left = TreeNode(77) testTree.right = TreeNode(88) testTree = placeholder testTree = testTree.right testTree.left = TreeNode(33) testTree.right = TreeNode(44) # Point to the head before passing to the Solution class testTree = treeNodeHead # Instantiate Solution class s = Solution() # Run the solution answer = s.maxDepth(testTree) print("Max depth of the binary tree: " + str(answer))
def __init__(self, columns, rows, max_iterations, alphabet, threshold_proportion, mutator_name, initial_c): Simulation.__init__(self, columns, rows, max_iterations, alphabet, threshold_proportion, mutator_name) self.initial_c = initial_c self.max_obj_f = FFMSPObjectiveFunction(threshold_proportion * self.columns) self.solution = Solution(self.dataset) self.solution_data = self.solution.get_solution('ffmsp') self.montecarlo_metropolis = Montecarlo(self.data, self.solution_data, self.mutator, self.max_obj_f, self.status)
def test_something(self): sol = Solution() self.assertEqual( 0, sol.minMalwareSpread( [[1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0], [0, 0, 0, 1, 1, 0], [0, 0, 0, 1, 1, 0], [0, 0, 0, 0, 0, 1]], [5, 0])) self.assertEqual( 2, sol.minMalwareSpread([[1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1], [0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0], [0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0], [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0], [0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]], [7, 8, 6, 2, 3])) self.assertEqual( 2, sol.minMalwareSpread([[1, 1, 0], [1, 1, 0], [0, 0, 1]], [0, 1, 2])) self.assertEqual( 0, sol.minMalwareSpread([[1, 1, 0], [1, 1, 0], [0, 0, 1]], [0, 1])) self.assertEqual( 1, sol.minMalwareSpread([[1, 1, 1], [1, 1, 1], [1, 1, 1]], [1, 2])) self.assertEqual( 0, sol.minMalwareSpread([[1, 0, 0], [0, 1, 0], [0, 0, 1]], [0, 2]))
def test_min_depth(self): self.assertEqual( 2, Solution().minDepth( TreeNode(3, TreeNode(9), TreeNode(20, TreeNode(15), TreeNode(7))))) self.assertEqual( 5, Solution().minDepth( TreeNode( 2, None, TreeNode(3, None, TreeNode(4, None, TreeNode(5, None, TreeNode(6))))))) self.assertEqual(1, Solution().minDepth(TreeNode(2)))
def main(): # Build the linked lists with the test inputs # Start pointer references the head, which we pass to solution listOneStart = listOne = ListNode(2) listOne.next = ListNode(4) listOne = listOne.next listOne.next = ListNode(3) listOne = listOneStart listTwoStart = listTwo = ListNode(5) listTwo.next = ListNode(6) listTwo = listTwo.next listTwo.next = ListNode(4) listTwo = listTwoStart # Instantiate Solution class s = Solution() # Run the Solution method answer = s.addTwoNumbers(listOne, listTwo) # Loop through answer list and print all nodes while answer: print(str(answer.val)) answer = answer.next
def test_get_importance(): e1 = Employee.Employee(1, 1, [2, 3, 4]) e2 = Employee.Employee(2, 2, [4]) e3 = Employee.Employee(3, 3, [4, 5]) e4 = Employee.Employee(4, 4, []) e5 = Employee.Employee(5, 5, [4]) e6 = Employee.Employee(6, 6, [5, 4, 1, 2, 3, 7]) e7 = Employee.Employee(7, 0, []) e8 = Employee.Employee(8, 0, [5]) test_runner = Solution() assert test_runner.get_importance( [e1, e2, e3, e4, e5, e6, e7, e8], 1 ) == 15 #Test the case when an employee (4) is a subordinate of 2 or mpre employees(1, 2, 3)- the employee's value should be calculated only once assert test_runner.get_importance([e1, e2, e3, e4, e5, e6, e7, e8], 2) == 6 assert test_runner.get_importance([e1, e2, e3, e4, e5, e6, e7, e8], 3) == 12 assert test_runner.get_importance([e1, e2, e3, e4, e5, e6, e7, e8], 4) == 4 assert test_runner.get_importance([e1, e2, e3, e4, e5, e6, e7, e8], 5) == 9 assert test_runner.get_importance([e1, e2, e3, e4, e5, e6, e7, e8], 6) == 21 assert test_runner.get_importance([e1, e2, e3, e4, e5, e6, e7, e8], 7) == 0 assert test_runner.get_importance([e1, e2, e3, e4, e5, e6, e7, e8], 8) == 9 with pytest.raises(Exception): assert test_runner.get_importance( [e1, e2, e3, e4, e5, e6, e7, e8], 9) #Test if an id (9) not in employees list raises an error assert test_runner.get_importance( [e1, e2, e3], 1 ) #Test if an id (4- subordinate of employee #1) is not in the employees list raises an error
def evaluate(self, chromosome: Chromosome) -> Solution: if chromosome.order_city[0].idx != 1: raise RuntimeError('Thief must start at city id 1') time = 0 profit = 0 weight = 0 for i in range(self.number_of_cities): city = chromosome.order_city[i] for item in city.items: if chromosome.pick_items[item.idx - 1]: weight += item.weight profit += item.profit if weight > self.max_weight: time = sys.float_info.max profit = -sys.float_info.max break speed = self.max_speed - (weight / self.max_weight) * ( self.max_speed - self.min_speed) next_city = chromosome.order_city[(i + 1) % self.number_of_cities] distance = math.ceil(euclidean_distance(city, next_city)) time += distance / speed return Solution(chromosome, profit, time, profit - self.renting_ratio * time, [time, -profit])
def main(): # Create first node and set the head ptr testListHead = testList = ListNode(3) # Add the second node and set a ptr that the end of the list can loop back to testList.next = ListNode(2) testList = testList.next loopback = testList # Populate the remaining nodes in the linked list testList.next = ListNode(0) testList = testList.next testList.next = ListNode(-4) testList = testList.next testList.next = loopback # Set ptr to beginning of list to pass to Solution class testList = testListHead # Instantiate Solution class s = Solution() # Run the solution answer = s.hasCycle(testList) print("The linked list contains a cycle: ") print(answer)