def test_3(): filename = os.path.join("datasets", "ORLibrary", "steinb13.txt") reader = ReaderORLibrary() STPG = reader.parser(filename) GA = GeneticAlgorithm(STPG) GA.logger = BaseLogger() GA.generate_population(population_size=10) MAX_GENERATION = 100 counter = 0 while counter < MAX_GENERATION: print("Iteration: ", counter + 1, end='\r') GA.evaluate(iteration=counter) GA.sort_population() GA.selection() GA.recombine() counter += 1 GA.evaluate(iteration=counter+1) print("\nPOPULATION FITNESS\n") print_pop(GA) GA.logger.report() return GA
def __test__(): filename = os.path.join("datasets", "ORLibrary", "steinb13.txt") reader = ReaderORLibrary() STPG = reader.parser(filename) graph = Graph(vertices=STPG.nro_nodes, edges=STPG.graph) ## DETERMINAR DUAS SOLUÇÕES PARCIAIS PELAS HEURISTICAS # escolher aleatoriamente um vértice terminal s1, s2 = random.sample(STPG.terminals, k=2) SUBTREE_A, cost1 = shortest_path_with_origin(graph, s1, STPG.terminals) # 0 ate 16 SUBTREE_B, cost2 = shortest_path_with_origin(graph, s2, STPG.terminals) SPX = SimplePartitionCrossover(graphinstance=graph) offspring = SPX.operation(TreeBasedChromosome(SUBTREE_A), TreeBasedChromosome(SUBTREE_B)) offspring_cost = gg_total_weight(offspring.graph) print( f"Parent A: {cost1}", f"Parent B: {cost2}\n" f"Offspring: {offspring_cost}" ) print("Has cycle", has_cycle(offspring.graph))
def test_2(): filename = os.path.join("datasets", "ORLibrary", "steinb13.txt") reader = ReaderORLibrary() STPG = reader.parser(filename) GA = GeneticAlgorithm(STPG) GA.logger = BaseLogger() GA.generate_population(population_size=10) GA.evaluate() GA.normalize() GA.sort_population() print("\nPOPULATION FITNESS\n") print_pop(GA) GA.selection() GA.recombine() GA.evaluate() GA.normalize() GA.sort_population() print("\nPOPULATION FITNESS\n") print_pop(GA) return GA
def test(): import random from os import path from graph import Reader from graph.steiner_heuristics import shortest_path_with_origin filename = path.join("datasets", "ORLibrary", "steinb13.txt") reader = ReaderORLibrary() STPG = reader.parser(filename) graph = Graph(vertices=STPG.nro_nodes, edges=STPG.graph) ## DETERMINAR DUAS SOLUÇÕES PARCIAIS PELAS HEURISTICAS # escolher aleatoriamente um vértice terminal s1 = random.choice(STPG.terminals) subtree_1, cost1 = shortest_path_with_origin(graph, s1, STPG.terminals) # 0 ate 16 s2 = random.choice(STPG.terminals) subtree_2, cost2 = shortest_path_with_origin(graph, s2, STPG.terminals) parent_1 = Chromossome(subtree_1, s1, cost1) parent_2 = Chromossome(subtree_2, s2, cost2) PX = PartitionCrossover(graph) child = PX.crossing(parent_1, parent_2)
def simulation(): dataset = os.path.join("datasets","ORLibrary","steinb13.txt") reader = ReaderORLibrary() STPG = reader.parser(dataset) graph = Graph(vertices=STPG.nro_nodes, edges=STPG.graph) GA = GeneticAlgorithm(graph, STPG.terminals) GA.set_crossover_operator(PartitionCrossover(graph), probability = 1) POPULATION_SIZE = 10 MAX_GENERATION = 100 iteration = 0 GA.initial_population(POPULATION_SIZE) GA.evaluate() GA.sort_population() for c in GA.population: print(c.fitness) while iteration < MAX_GENERATION: print("Iteration: ", (iteration + 1), end="\r") GA.evaluate() # GA.normalized_fitness() GA.selection() GA.recombine() iteration += 1 GA.evaluate() print("\n\n=============================\n\n") print(GA.best_chromossome.fitness)
def test(dataset): from tqdm import tqdm from graph.util import has_cycle reader = ReaderORLibrary() STPG = reader.parser(dataset) GA = GeneticAlgorithm(STPG) GA.logger = BaseLogger() GA.generate_population(population_size=100) time_starts = time.time() for iteration in tqdm(range(0, 50)): # print("Iteration: ", (iteration + 1), end="\r") GA.evaluate() GA.selection() GA.recombine() # problema identificado aqui GA.mutation() time_ends = time.time() GA.evaluate() GA.logger.report() print("Total run time: ", (time_ends - time_starts)) subgraph, _ = GA.subgraph_from_chromosome(GA.best_chromosome) dtree, cost = prim(subgraph, STPG.terminals[0]) print("Final prim cost: ", cost) print("Final fitness: ", GA.eval_chromosome(GA.best_chromosome)) test_genes = GA.chromosome_from_subgraph(subgraph) print(test_genes) print(GA.best_chromosome.genes) print(all(z == w for z, w in zip(test_genes, GA.best_chromosome.genes)))
def simulation(dataset: str, nro_trial = 0, global_optimum = 0): '''Run a simulation trial''' # Lendo a instância do problema reader = ReaderORLibrary() STPG = reader.parser(dataset) # Definindo o diretório que será destinado os dados datafolder = os.path.join("outputdata", "20200422_simplest", STPG.name) if not os.path.exists(datafolder): os.makedirs(datafolder) # or mkdir ## Parâmetros comuns a cada execução GA = GeneticAlgorithm(STPG) GA.tx_crossover = 0.85 GA.tx_mutation = 0.2 POPULATION_SIZE = 100 MAX_GENERATION = 10000 MAX_LAST_IMPROVEMENT = 500 GLOBAL_OPTIMUN = global_optimum ## Definindo a função com os critérios de parada def check_stop_criterions(iteration=0): if iteration >= MAX_GENERATION: return (False, "max_generation_reached") elif GA.last_time_improvement > MAX_LAST_IMPROVEMENT: return (False, "stagnation") elif GA.best_chromosome.cost == GLOBAL_OPTIMUN : return (False, "global_optimum_reached") else : return (True, "non stop") ## Configurando a coleta de informações GA.logger.prefix = f'trial_{nro_trial}' GA.logger.mainfolder = datafolder GA.logger.register("simulation", "csv", "nro_trial", "instance_problem", "nro_nodes", "nro_edges", "nro_terminals", "tx_crossover", "tx_mutation", "global_optimum", "best_cost", "best_fitness", "population_size", "max_generation", "iterations", "run_time", "max_last_improvement", "why_stopped" ) ## ============================================================= ## EXECUTANDO O ALGORITMO GENÉTICO GA.generate_population(population_size=POPULATION_SIZE) # GA.generate_population(POPULATION_SIZE, opt="MST") running = True epoch = 0 timestart = time.time() while running: GA.evaluate(iteration=epoch) GA.normalize(iteration=epoch) GA.selection() GA.recombine() GA.mutation() GA.last_time_improvement += 1 epoch += 1 running, why_stopped = check_stop_criterions(iteration=epoch) time_ends = time.time() GA.evaluate(iteration=epoch) ## Record general simulation data GA.logger.log("simulation", nro_trial, STPG.name, STPG.nro_nodes, STPG.nro_edges, STPG.nro_terminals, GA.tx_crossover, GA.tx_mutation, GLOBAL_OPTIMUN, GA.best_chromosome.cost, GA.best_chromosome.fitness, POPULATION_SIZE, MAX_GENERATION, epoch, (time_ends - timestart), MAX_LAST_IMPROVEMENT, why_stopped ) ## Generates the reports GA.logger.report()
INSTANCE_DATA = list() # instância do problema HEURISTIC_RESULTS = list() # resultado obtido OUTPUT_DATA = path.join("output_data", "heuristics") INPUT_DATA = path.join("datasets", "ORLibrary") READER = ReaderORLibrary() for item in heuristics: heuristic = item['function'] nickname = item['nickname'] for filename in generate_file_names('c'): print("Processing... ", filename, end="\r") ff = path.join(INPUT_DATA, filename) stp = READER.parser(ff) terminals = set(stp.terminals) graph = Graph(edges=stp.graph) # stp_data = [ # stp.name, # stp.nro_nodes, # stp.nro_edges, # stp.nro_terminals # ] # INSTANCE_DATA.append(stp_data) HEURISTIC_RESULTS = list()
def setup_dataset(self, dataset, **kwargs): print(f"setting instance problem from dataset : {dataset}") filename = os.path.join("datasets", "ORLibrary", dataset) reader = ReaderORLibrary() self.STPG = reader.parser(filename) self.GRAPH = Graph(edges=self.STPG.graph)