def test_read_b01(self): diretorio_dados = path.join("datasets", "ORLibrary") arquivo_dados = "steinb1.txt" arquivo = path.join(diretorio_dados, arquivo_dados) reader = ReaderORLibrary() stp = reader.parser(arquivo) terminais = [48, 49, 22, 35, 27, 12, 37, 34, 24] self.assertEqual(stp.nro_nodes,50) self.assertEqual(stp.nro_edges,63) self.assertEqual(stp.nro_terminals,9) self.assertEqual(sorted(stp.terminals),sorted(terminais)) self.assertEqual(stp.graph[17][42],6) self.assertEqual(stp.graph[20][40],10) #Ordem inversa ao que aparece no arquivo self.assertEqual(stp.graph[6][42],9) self.assertEqual(stp.graph[13][50],1) self.assertIsInstance(stp.nro_nodes,int) self.assertIsInstance(stp.nro_edges,int) self.assertIsInstance(stp.nro_terminals,int) self.assertIsInstance(stp.terminals,set) self.assertIsInstance(stp.graph,Graph) self.assertEqual(len(stp.graph.vertices), stp.nro_nodes) self.assertEqual(stp.name,'B1') self.assertEqual(stp.remark,'Sparse graph with random weights') self.assertEqual(stp.creator,'J. E. Beasley') self.assertEqual(stp.file_name, arquivo_dados)
def test_vertices_from_chromossome_random_chromosome(self): filename = path.join('tests', 'data', 'test1.txt') stpg = ReaderORLibrary().parser(filename) self.assertIsNotNone(stpg) self.assertEqual(stpg.nro_nodes, 7) self.assertEqual(stpg.nro_edges, 11) self.assertEqual(stpg.nro_terminals, 2) self.assertEqual(stpg.terminals, set([1, 5])) evaluator = EvaluateKruskalBased(stpg) chromosome = '11110' vertices_from = evaluator.vertices_from_chromosome(chromosome) expected_vertices = set([1, 2, 3, 4, 5, 6]) self.assertEqual(vertices_from, expected_vertices) chromosome = '11111' vertices_from = evaluator.vertices_from_chromosome(chromosome) expected_vertices = set([1, 2, 3, 4, 5, 6, 7]) self.assertEqual(vertices_from, expected_vertices) chromosome = '10101' vertices_from = evaluator.vertices_from_chromosome(chromosome) expected_vertices = set([1, 5, 2, 4, 7]) self.assertEqual(vertices_from, expected_vertices)
def test_GenerateUndirectEdges(self): diretorio_dados = path.join("datasets", "ORLibrary") arquivo_dados = "steinb1.txt" arquivo = path.join(diretorio_dados, arquivo_dados) reader = ReaderORLibrary() stp = reader.parser(arquivo) graph = stp.graph edges = set() for e in graph.gen_undirect_edges(): edges.add(e) self.assertEqual(len(edges),stp.nro_edges)
def test_evaluate_test2(self): filename = path.join('tests', 'data', 'test2.txt') stpg = ReaderORLibrary().parser(filename) evaluator = EvaluateKruskalBased(stpg) chromosome = '11110' evaluator_cost, qtd_partitions = evaluator(chromosome) self.assertEqual(qtd_partitions, 2) self.assertEqual(evaluator_cost, 1021)
def test_best_solution_is_steiner_tree(self): filename = path.join('datasets', 'ORLibrary', 'steinb1.txt') stpg = ReaderORLibrary().parser(filename) coder = Coder(stpg) chromosome = "00000010000000001011000110001100010100010" subgraph = coder.binary2treegraph(chromosome) result, _ = is_steiner_tree(subgraph, stpg) self.assertTrue(result)
def simulation(simulation_name, params): datasets_folder = path.join("datasets", "ORLibrary") filename = path.join(datasets_folder, params["dataset"]) STPG = ReaderORLibrary().parser(filename) print("STPG information", '\n', 10 * '- ', '\n') print("Trial: ", parameters['runtrial']) print('Instance: ', STPG.name) print('Best Known cost: ', params['global_optimum']) print("Nro. Node:", STPG.nro_nodes) print("Nro. Edges:", STPG.nro_edges) print("Nro. Terminals:", STPG.nro_terminals) # print("Terminals: \n", STPG.terminals) output_folder = path.join("data", simulation_name, STPG.name) tracker = DataTracker(params['runtrial'], target=output_folder) generator = GenerateBasedPrimRST(STPG) evaluator = EvaluateTreeGraph(STPG) crossover = CrossoverPrimRST(STPG) prunner = Prunning(STPG) mut_prim = PrimBasedMutation(STPG) replace_random = ReplaceByRandomEdge(STPG) population = (GPopulation( chromosomes=[generator() for _ in range(params["population_size"])], eval_function=evaluator, maximize=True).evaluate().normalize( norm_function=normalize).callback(update_best)) evol = (Evolution().evaluate().normalize(norm_function=normalize).callback( update_best).callback(tracker.log_evaluation).select( selection_func=roullete).crossover(combiner=crossover).mutate( mutate_function=replace_random, probability=0.2).mutate( mutate_function=mut_prim, probability=0.2).mutate( mutate_function=prunner, probability=0.2).callback(update_generation).callback( display, every=100)) with Stagnation(interval=params["stagnation_interval"]), \ BestKnownReached(global_optimum=params['global_optimum']): result = population.evolve(evol, n=params["n_iterations"]) tracker.log_simulation(params, STPG, result) best_overall = result.documented_best test, response = is_steiner_tree(best_overall.chromosome, STPG) tracker.log_bestIndividual(best_overall, test, response) tracker.report()
def test_if_has_all_terminals(self): filename = path.join('datasets', 'ORLibrary', 'steinb15.txt') stpg = ReaderORLibrary().parser(filename) terminals = stpg.terminals crossover = CrossoverPrimRST(stpg) parent_a = gen_random_walk(stpg) parent_b = gen_random_walk(stpg) offspring = crossover(parent_a, parent_b) vertices = set([v for v in offspring.vertices]) self.assertTrue(terminals.issubset(vertices))
def test_edge_non_exist_in_stpg_instance(self): filename = path.join("tests", "data", "test4.txt") stpg = ReaderORLibrary().parser(filename) tree = UGraph() edges = [(1, 3), (3, 8), (8, 5), (5, 6), (8, 9)] for edge in edges: v, u = edge tree.add_edge(v, u) evaluator = EvaluateTreeGraph(stpg) self.assertTrue(callable(evaluator)) with self.assertRaises(ValueError): cost, __ = evaluator(tree)
def test_example_solution_two_components(self): filename = path.join("tests", "data", "test4.txt") stpg = ReaderORLibrary().parser(filename) tree = UGraph() edges = [(1, 3), (3, 8), (8, 5), (5, 6), (2, 4)] for edge in edges: v, u = edge tree.add_edge(v, u) evaluator = EvaluateTreeGraph(stpg) self.assertTrue(callable(evaluator)) cost, nro_partition = evaluator(tree) self.assertEqual(nro_partition, 2) self.assertEqual(cost, (5 + 7 + 7 + 15 + 16))
def test_if_return_an_edgeset(self): filename = path.join('datasets', 'ORLibrary', 'steinb15.txt') stpg = ReaderORLibrary().parser(filename) crossover = CrossoverPrimRST(stpg) parent_a = gen_random_walk(stpg) parent_b = gen_random_walk(stpg) self.assertIsInstance(parent_a, EdgeSet) self.assertIsInstance(parent_b, EdgeSet) offspring = crossover(parent_a, parent_b) self.assertIsInstance(offspring, EdgeSet) self.assertFalse(offspring is parent_a) self.assertFalse(offspring is parent_b) self.assertNotEqual(offspring, parent_a) self.assertNotEqual(offspring, parent_b)
def test_if_is_it_a_tree(self): filename = path.join('datasets', 'ORLibrary', 'steinb15.txt') stpg = ReaderORLibrary().parser(filename) crossover = CrossoverKruskalRST(stpg) parent_a = gen_random_walk(stpg) parent_b = gen_random_walk(stpg) offspring = crossover(parent_a, parent_b) tree = UGraph() for edge in offspring: u, v = edge[0], edge[1] tree.add_edge(u, v) _, response = is_steiner_tree(tree, stpg) self.assertTrue(response['all_terminals_in']) self.assertFalse(response['has_cycle']) self.assertTrue(response['all_edges_are_reliable']) self.assertTrue(response['graph_is_connected'])
def test_penality_function(self): filename = path.join("tests", "data", "test4.txt") stpg = ReaderORLibrary().parser(filename) tree = UGraph() edges = [(1, 3), (3, 8), (8, 5), (5, 6), (2, 4)] for edge in edges: v, u = edge tree.add_edge(v, u) evaluator = EvaluateTreeGraph(stpg, penality_function=lambda nro: (nro - 1) * 100) self.assertTrue(callable(evaluator)) cost, nro_partition = evaluator(tree) self.assertEqual(nro_partition, 2) self.assertEqual(cost, (5 + 7 + 7 + 15 + 16 + 100))
def test_evaluate_steinb1(self): filename = path.join('datasets', 'ORLibrary', 'steinb1.txt') stpg = ReaderORLibrary().parser(filename) evaluator = EvaluateKruskalBased(stpg, penality_function=lambda k: (k - 1) * 100) chromosomes = [("00000010000000001011000110001100010100010", 82), ("00011100101110110011011111001110111000111", 362), ("11111111001011010111100110001101111110011", 209), ("10011010001011001111111111101101110111011", 166), ("10000010000000001011000111001100010101011", 100), ("00000010000010011011000111001100010101010", 97), ("00000010001000000011000111001100010001010", 95), ("00000010000011001011000111001100010100010", 92)] for chromosome, expected_value in chromosomes: evaluator_cost, _ = evaluator(chromosome) self.assertEqual(expected_value, evaluator_cost)
def test_decoder_random_chromosome(self): filename = path.join('tests', 'data', 'test1.txt') stpg = ReaderORLibrary().parser(filename) evaluator = EvaluateKruskalBased(stpg) chromosome = '11110' vertices_from = evaluator.vertices_from_chromosome(chromosome) expected_vertices = set([1, 2, 3, 4, 5, 6]) self.assertEqual(vertices_from, expected_vertices) coder = Coder(stpg) subgraph = coder.binary2treegraph(chromosome) for v, u in subgraph.gen_undirect_edges(): self.assertTrue(stpg.graph.has_edge(v, u)) self.assertFalse(subgraph.has_edge(1, 2)) self.assertFalse(subgraph.has_edge(6, 4)) self.assertTrue(subgraph.has_edge(1, 3)) self.assertTrue(subgraph.has_edge(3, 2)) self.assertTrue(subgraph.has_edge(5, 4)) self.assertTrue(subgraph.has_edge(6, 5)) self.assertTrue(subgraph.has_edge(2, 5)) self.assertFalse(subgraph.has_node(7)) #não existe mesmo self.assertFalse(subgraph.has_edge(7, 1)) self.assertFalse(subgraph.has_edge(7, 5)) self.assertFalse(subgraph.has_edge(3, 4)) # não existe no subgrafo self.assertFalse(subgraph.has_edge(7, 2)) self.assertFalse(subgraph.has_edge(7, 3)) self.assertFalse(subgraph.has_edge(7, 4)) self.assertFalse(subgraph.has_edge(7, 6))
def setUp(self) -> None: possibles = [ f'steinb{ii}.txt' for ii in range(10, 19)] filename = choice(possibles) print(filename) filename = path.join('datasets', 'ORLibrary', filename) self.stpg = ReaderORLibrary().parser(filename)
def setUp(self): filename = path.join('datasets', 'ORLibrary', 'steinb15.txt') self.stpg = ReaderORLibrary().parser(filename)
heuristics = [{ 'function': prunning_mst, 'nickname': "PMH" }, { 'function': shortest_path, 'nickname': 'SPH' }, { 'function': shortest_path_origin_prim, 'nickname': 'SPHPrim' }, { 'function': shortest_path_with_origin, 'nickname': 'SPHO' }] reader = ReaderORLibrary() results = list() results.append(['instance_problem', 'heuristic', 'start_node', 'cost']) for item in heuristics: heuristic = item['function'] name_heuristic = item['nickname'] for name in instances: STPG = reader.parser(path.join(instance_folder, name)) graph = STPG.graph terminals = STPG.terminals.copy() vertices = list(graph.vertices) for v in vertices: print(