def test_algs(towns_matrix): print("\nAnts colony algorithm started...") start = time.monotonic() ac = AntsColony(towns_matrix=towns_matrix, ants_count=5, interations_count=10000, vaporization_coef=0.95, power_coef=2) shortest_way = ac.run() print("Shortest way:", shortest_way, "Time: ", time.monotonic() - start) print("\nBrute Force algorithm started...") start = time.monotonic() bf = BruteForce(towns_matrix=towns_matrix) shortest_way = bf.run() print("Shortest way:", shortest_way, "Time: ", time.monotonic() - start)
def single_experiment(input_file, algo): tracemalloc.start() nodes = read_data(input_file) n = len(nodes) if algo == 'bf': solver = BruteForce(nodes) elif algo == 'a-star': solver = AStarAlgorithm(nodes) elif algo == 'greedy': solver = GreedyAlgorithm(nodes) else: raise Exception(f'Algorithm {algo} not implemented!') _, cost, time = solver.run() _, peak = tracemalloc.get_traced_memory() return n, time, cost, peak
def main(): directory, make_plot, force_yes = parse_args() results = { 'a-star': [], 'bf': [], 'greedy': [], } files = glob(f'{directory}/*.in') files.sort() experiment_start = process_time() tracemalloc.start() for i, file in enumerate(files): case_start = process_time() nodes = read_data(file) n = len(nodes) # Brute Force solver = BruteForce(nodes) path, cost, time = solver.run() results['bf'].append({'n': n, 'time': time}) # A* solver = AStarAlgorithm(nodes) path, cost, time = solver.run() results['a-star'].append({'n': n, 'time': time}) # Greedy solver = GreedyAlgorithm(nodes) path, cost, time = solver.run() results['greedy'].append({'n': n, 'time': time}) case_end = process_time() case_time = case_end - case_start print( f'Case {i + 1}/{len(files)}: Finished {n} nodes in {case_time:.4f} seconds' ) if not force_yes and case_time > 60 and i + 1 < len(files): response = input('Continue? [Y/n]: ') if response == 'n': break experiment_stop = process_time() experiment_time = experiment_stop - experiment_start print(f'Finished experiments in {experiment_time:.2f} seconds') _, peak = tracemalloc.get_traced_memory() print(f'Peak memory usage: {(peak / 10**6):.1f}MB') for algo in results.keys(): with open(f'results_{algo}.csv', 'w') as file: writer = DictWriter(file, ['n', 'time']) writer.writeheader() writer.writerows(results[algo])
def main(): check('nbrs.radius_neighbors(p, radius)', setup_str_bt) check('nbrs.radius_neighbors(p, radius)', setup_str_bf) n, d = 1000, 3 X = np.random.rand(n, d) p = X[0] radius = 0.4 ball_tree_inds = BallTree(X).radius_neighbors(p, radius) brute_force_inds = BruteForce(X).radius_neighbors(p, radius) print(ball_tree_inds == brute_force_inds)
def main(): file, algorithm, text_only = parse_args() nodes = read_data(file) if algorithm == 'bf': solver = BruteForce(nodes) elif algorithm == 'a-star': solver = AStarAlgorithm(nodes) elif algorithm == 'greedy': solver = GreedyAlgorithm(nodes) else: raise Exception(f'Algorithm {algorithm} not implemented!') path, cost, time = solver.run() labels = [node.label for node in path] print(' '.join(labels)) print(cost) print(time) if not text_only: plot_path(path)
def execute_command(command, file): commands = { 'brute_force': BruteForce().find_shortest_path, 'two_opt': TwoOpt().find_shortest_path, 'nearest_neighbor': NNHeuristic().find_shortest_path } coordinates_list = read_csv(file) if len(coordinates_list) > 10 and command == 'brute_force': stderr.write('Brute Force algorithm should only be use for map <=' + ' 10 cities\n' + '\033[01;91mBetter options\033[00m: ' + 'two_opt, nearest_neighbor\n') exit(0) return commands[command](coordinates_list)
import time from grid_digraph_generator import GridDigraphGenerator from brute_force import BruteForce if __name__ == '__main__': m = n = 10 gh = GridDigraphGenerator() graph = gh.generate(m, n, edge_weighted=False) terminals = [88, 66, 77, 5, 33, 53, 71] pois = [65, 12] db_woc = BruteForce(graph) start_time = time.clock() db_woc.steiner_forest(terminals, pois, 4) elapsed_time = time.clock() - start_time
'--image', required=True, help='Path to the input image containing the logo/image') ap.add_argument('-M', '--match', help='Type of matching algorithm to use', default='F') args = vars(ap.parse_args()) #Getting the images ready img1 = cv2.imread(args['logo'], cv2.IMREAD_GRAYSCALE) img2 = cv2.imread(args['image'], cv2.IMREAD_GRAYSCALE) match_type = args['match'] img_matches = None if match_type == 'B': #Matching the images using the Brute-Force algorithm. img_matches = BruteForce(img1, img2) elif match_type == 'R': #Matching the images using BruteForce KNN algorithm with Ratio Test. img_matches = BruteForceKNN(img1, img2) elif match_type == 'F': img_matches = FLANN(img1, img2) elif match_type == 'H': img_matches = Homography(img1, img2) #Displaying the results and storing them plt.imshow(img_matches) plt.show() cv2.imwrite('matched.png', img_matches)
def main(): '''define some global variables''' results = [] '''set the simulated annealing algorithm parameter grid''' temp = list(range(100, 5000, 100)) stopping_temp = [0.000000001, 0.00000001, 0.0000001, 0.000001, 0.00001] alpha = [a / 100 for a in range(1,100)] parameter_dict = { "temp": temp, "stopping_temp": stopping_temp, "alpha": alpha } stopping_iter = 10000000 parameter_grid = ParameterGrid(parameter_dict) parameter_size = len(list(parameter_grid)) '''set the dimensions of the grid''' size_width = 200 size_height = 200 '''set the number of nodes''' population_size = 12 '''generate random list of nodes''' nodes = NodeGenerator(size_width, size_height, population_size).generate() '''run simulated annealing algorithm with 2-opt''' ordered_temp = [] ordered_stopping_temp = [] ordered_alpha = [] for parameters in parameter_grid: temp = parameters['temp'] stopping_temp = parameters['stopping_temp'] alpha = parameters['alpha'] ordered_temp.append(temp) ordered_stopping_temp.append(stopping_temp) ordered_alpha.append(alpha) sa = SimulatedAnnealing(nodes, temp, alpha, stopping_temp, stopping_iter) initial_solution = sa.curr_solution start_time = time.time() sa.anneal() execution_time = time.time() - start_time results.append((sa.min_weight, sa.iteration, execution_time, parameters)) weights, iterations, execution_times, parameters = zip(*results) weights = list(weights) iterations = list(iterations) execution_times = list(execution_times) simulations = list(range(parameter_size)) # Get optimal parameters from all sumulations: optimal_run_data = optimal_run(results) '''run brute force solution''' # The same initial solution is used bf = BruteForce(nodes, initial_solution) start_time = time.time() bf.solve() bf_execution_time = time.time() - start_time bf_min_weight = bf.min_weight bf_iterations = bf.iteration '''general plots''' plt.scatter(simulations, ordered_temp) plt.title('Temperatura') plt.ylabel('Temperatura') plt.xlabel('Simulacion') plt.show() plt.scatter(simulations, ordered_stopping_temp) plt.title('Temperatura Limite') plt.ylabel('Temperatura') plt.xlabel('Simulacion') plt.show() plt.scatter(simulations, ordered_alpha) plt.title('Alpha') plt.ylabel('Alpha') plt.xlabel('Simulacion') plt.show() plt.scatter(simulations, weights) plt.title('Distancias Finales') plt.ylabel('Distancia') plt.xlabel('Simulacion') plt.show() plt.scatter(simulations, iterations) plt.title('Iteraciones Totales') plt.ylabel('Numero de Iteraciones') plt.xlabel('Simulacion') plt.show() plt.scatter(simulations, execution_times) plt.title('Tiempos de Ejecucion') plt.ylabel('Tiempo') plt.xlabel('Simulacion') plt.show() plt.scatter(simulations, weights) line_bf = plt.axhline(y = bf_min_weight, color='r', linestyle='--') plt.legend([line_bf], ['Distancia con Fuerza Bruta']) plt.title('Distancias Finales') plt.ylabel('Distancia') plt.xlabel('Simulacion') plt.show() plt.scatter(simulations, iterations) line_bf = plt.axhline(y = bf_iterations, color='r', linestyle='--') plt.legend([line_bf], ['Iteraciones con Fuerza Bruta']) plt.title('Iteraciones Totales') plt.ylabel('Numero de Iteraciones') plt.xlabel('Simulacion') plt.show() plt.scatter(simulations, execution_times) line_bf = plt.axhline(y = bf_execution_time, color='r', linestyle='--') plt.legend([line_bf], ['Tiempo con Fuerza Bruta']) plt.title('Tiempos de Ejecucion') plt.ylabel('Tiempo') plt.xlabel('Simulacion') plt.show() '''animate''' sa.animateSolutions() '''show the improvement over time''' sa.plotLearning() '''animate (brute force)''' bf.animateSolutions() '''show the improvement over time (brute force)''' bf.plotLearning()