def run(do_print): tk=0 tp=0 for i in range(100): G,C,Gp,N,n=load_data_2('testing_graph_'+str(i)+'.txt') start=time.time() if do_print: print_kruskal(C,n,str(i)) else: kruskal(C,n) tk=tk+time.time()-start n=G.shape[0] start=time.time() if do_print: print_prim(Gp,N,n,str(i)) else: prim(Gp,N,n) tp=tp+time.time()-start tp=tp/100.0 tk=tk/100.0 print tp print tk f=open('runtime.txt','w') f.write('Prim: '+str(tp)+' seconds\nKruskal: '+str(tk)+' seconds') f.close() return
def grid_span(): grid = full_grid() spanning_tree1 = kruskal(grid.nodes(), sorted(grid.edges())) spanning_tree2 = kruskal(grid.nodes(), reversed(sorted(grid.edges()))) grid.remove_edges_from(grid.edges()) grid.add_edges_from(spanning_tree1 + spanning_tree2) grid.graph['name'] = 'grid_span' for i in range(10): if i != 4: grid.add_edge((i, 5), (i + 1, 5)) grid.graph['init path'].append(((i, 5), (i + 1, 5))) return grid
def grid_span_rand(): grid = full_grid() edges = grid.edges() shuffle(edges) spanning_tree1 = kruskal(grid.nodes(), edges) shuffle(edges) spanning_tree2 = kruskal(grid.nodes(), edges) grid.remove_edges_from(grid.edges()) grid.add_edges_from(spanning_tree1 + spanning_tree2) grid.graph['name'] = 'grid_span_rand' for i in range(10): if i != 4: grid.add_edge((i, 5), (i + 1, 5)) grid.graph['init path'].append(((i, 5), (i + 1, 5))) return grid
def main(): graph = { 'A': ['B'], 'B': ['D'], 'C': ['D', 'E'], 'D': ['F', 'G'], 'E': ['J'], 'F': ['I'], 'G': ['J'], 'H': ['K'], 'I': ['K'], 'J': ['L'], 'K': [], 'L': [] } newGraph = moralizeGraph(graph) addEdge = minfill(newGraph) for edge in addEdge: a = edge[0][0] b = edge[0][1] newGraph[a] += [b] newGraph[b] += [a] clique = findMaximalClique(newGraph) print clique print '================================' cliqueGraph = createCliqueGraph(clique) print cliqueGraph print '================================' cliqueTree = kruskal.kruskal(cliqueGraph) print cliqueTree print '================================'
def test_kruskal(): input_graph = Graph( Edge(1, 2, 1), Edge(1, 3, 4), Edge(1, 4, 3), Edge(2, 4, 2), Edge(3, 4, 5) ) expected_graph = Graph(Edge(1, 2, 1), Edge(1, 3, 4), Edge(2, 4, 2)) actual_graph = kruskal(input_graph) assert actual_graph == expected_graph
def Kruskal_Algorithm(): #Sets the number of vertices in the graph n = 10 #Creates the maximum number of vertices for this graph g = K.kruskal(n) print("Applying a graph of ", n, " vertices.") print("") #Sets the edges that are present in the graph, reading from, to, and its weight value g.addEdge(0, 1, 4) g.addEdge(0, 4, 3) g.addEdge(1, 4, 2) g.addEdge(1, 5, 5) g.addEdge(1, 2, 4) g.addEdge(2, 5, 6) g.addEdge(2, 6, 9) g.addEdge(3, 6, 13) g.addEdge(4, 7, 1) g.addEdge(4, 5, 12) g.addEdge(5, 7, 21) g.addEdge(7, 8, 14) g.addEdge(5, 8, 11) g.addEdge(5, 6, 17) g.addEdge(6, 8, 10) g.addEdge(8, 9, 16) g.addEdge(3, 9, 20) print("") print("Creating the new graph using Kruskal's Algorithm...") #Sends the new formed graph to be sorted using kruskal's algorithm. The next class will print its result g.Kruskal_al()
def main(): grafo = Grafo() archivo = "map.osm" depurar(archivo) print("fin de depuracion") archivo2 = "modificado.xml" grafo = Grafo() grafo = grafoOSM(archivo2) print("fin de procesamiento de datos OSM") # PRUEBA arbol = kruskal(grafo) print("fin de kruskal") idA = encuentra_punto(grafo, -12.066159, -77.073635) # -12.071697, -77.076262) assert idA in grafo.dic_vertices.keys( ), "idA no se encuentra dentro del grafo" idB = encuentra_punto( grafo, -12.072115, -77.072334) # -12.070534, -77.066984) # -12.086531, -77.063292) assert idB in grafo.dic_vertices.keys( ), "idB no se encuentra dentro del grafo" camino = dijkstra(grafo, arbol, idA, idB) print("fin de dijkstra") mapeoarbol(grafo, arbol, camino) print("fin de grafico de mapa") print("FIN")
def main(): for filename in get_test_files(): print("%s:" % filename, end=" ") with open(filename, "r") as fhandler: lines = fhandler.readlines() nb_edges = int(lines[0]) edges = [ (lambda s: (int(s[0]), int(s[1]), int(s[2])))(lines[i + 1].strip().split()) for i in range(nb_edges) ] try: t1 = time.perf_counter() _, prim_c = prim(edges) t2 = time.perf_counter() _, kruskal_c = kruskal(edges) t3 = time.perf_counter() except Exception: print("runtime error") else: if prim_c != kruskal_c: print("KO (Prim: %d, Kruskal: %d)" % (prim_c, kruskal_c)) else: print("OK (both %d)\t- %d edges\t" "- Prim: %.3f ms, \tKruskal: %.3f ms" % (prim_c, nb_edges, 1000 * (t2 - t1), 1000 * (t3 - t2)))
def get_all_results(from_to_cost, no_of_nodes, source, node_x_y, result, ui): kruskal_output = kruskal.kruskal(from_to_cost, no_of_nodes) prims_output = prims.PRIMS(from_to_cost, no_of_nodes, source) dijkstra_output = dijkstra.DIJKSTRA(from_to_cost, no_of_nodes, source) bellman_output = bellmanford.BELLMANFORD(from_to_cost, no_of_nodes, source) floyd_output = FloydWarshall.FLOYDWARSHALL(from_to_cost, no_of_nodes, source, node_x_y) # print(kruskal_output) # print(prims_output) # print(dijkstra_output) # print(bellman_output) # print(floyd_output) kruskal_cost = kruskal_output[1] prims_cost = prims_output[1] dijkstra_cost = dijkstra_output[1] bellman_cost = bellman_output[1] floyd_cost = floyd_output[1] local_cluster_average = LocalCluster.LOCALCLUSTERAVERAGE(result) # print(kruskal_cost) # print(prims_cost) # print(dijkstra_cost) # print(bellman_cost) # print(floyd_cost) # print(local_cluster_average) data = [ kruskal_cost, prims_cost, dijkstra_cost, bellman_cost, floyd_cost, local_cluster_average ] for y in range(0, len(data)): # print('col test : ' + str(ui.tableWidget.item(0,y).text())) ui.tableWidget.item(0, y).setText(str(data[y]))
def compute_max_spanning_tree(graph): mst = kruskal(graph) print(">>> [mst]") pprint(dict(mst)) # show_graph(mst) return mst
def heuristic_tree(points, iterations=1000, alpha=0.01): """heuristic algorithm for Steiner tree.""" size = points.shape[0] adjacentcy_list = kruskal(points) points, adjacentcy_list = add_steiner_points(points, adjacentcy_list) points, adjacentcy_list = move_steiner_points(points, adjacentcy_list, size, iterations=iterations, alpha=alpha) return points, adjacentcy_list
def test_kruskal_str_vertices(self): graph = Graph() graph.add_edge(Edge(Vertex("A"), Vertex("D"), 2)) graph.add_edge(Edge(Vertex("A"), Vertex("G"), 3)) graph.add_edge(Edge(Vertex("A"), Vertex("B"), 1)) graph.add_edge(Edge(Vertex("B"), Vertex("E"), 6)) graph.add_edge(Edge(Vertex("B"), Vertex("F"), 7)) graph.add_edge(Edge(Vertex("F"), Vertex("D"), 10)) graph.add_edge(Edge(Vertex("F"), Vertex("C"), 12)) graph.add_edge(Edge(Vertex("E"), Vertex("G"), 9)) self.assertEqual(kruskal(graph), 31)
def kruskal_graph(): graph = {} edges_l = [] graph['vertices'] = list_vertics(vertic) pytanie = raw_input("Czy chcesz podac wagi? (T or F) ") for i in edge_list: if pytanie != 'F': waga = int(raw_input("Podaj wage wierzcholka " + str(i) + ': ')) else: waga = 1 edg = waga, i[0], i[1] edges_l.append(edg) edges_l.sort() print edges_l graph['edges'] = edges_l return kruskal.kruskal(graph)
def runAct(dataArray): print "Choosing the list of samples." #or use partition by metadatum values sampleNameList,metadataList,interval1List,interval2List = createSampleNameList(dataArray) n = len(sampleNameList) print "\nAVAILABLE COMPARISON FUNCTION(S):" fctF = printComparison() f = raw_input("\nChoose your comparison function above those printed above.\n") isInDatabase([f],fctF) completeGraph = Graph(n).constructComplete(sampleNameList,dataArray[7],f) superTree,w = kruskal(completeGraph) #Constructing distance matrix matrix = np.zeros((n,n)) print "\nAVAILABLE DISTANCE FUNCTION(S):" fctD = printDistance() d = raw_input("\nChoose your distance function above those printed above.\n") isInDatabase([d],fctD) valueArray = [] print "\nSUPERTREE of weight:",w print superTree.vertices print superTree.edges for i in range(n): for j in range(i,n): #matrix is symmetric (distance) s = applyFctD(d,superTree,i,j) matrix[i][j] = s matrix[j][i] = s valueArray.append(s) valueArray = sorted(valueArray) valueNumber = n*n/2 quartile3 = valueNumber*3/4 valueQuartile = valueArray[quartile3] mostDifferent = [] #Distance is symmetric for i in range(n): for j in range(i+1,n): if matrix[i][j] >= valueQuartile: mostDifferent.append((sampleNameList[i],sampleNameList[j])) print "\nRESULTING MATRIX:" print matrix print "\n---\nMost different samples groups from:\n" for sampleGroup in sampleNameList: print sampleGroup print "\nare:\n" print mostDifferent print "\n--- END OF DISPLAY\n"
def benchmark(): n = 10**4 m = 10 * n G = Graph.random_graph(n, m, weighted=True) begin = time.time() A = kruskal(G) end = time.time() print('* Kruskal {:.5} s'.format(end - begin)) print('-- total weight:', sum(G[u][v] for u, v in A)) print() begin = time.time() B = prim(G) end = time.time() print('* Prim {:.5} s'.format(end - begin)) print('-- total weight:', sum(G[u][v] for u, v in B))
def run_equivalence_test(n, trace=False): """ Compare all algorithms for the same input graph :param n: size of the test graph :param trace: print debug info is test failed :return True if test succeeds """ t = timeit.default_timer() adj_list, vertex_list, edge_list = generate_graph(n) if trace: print 'Generate graph: {}'.format(timeit.default_timer() - t) t = timeit.default_timer() min_span_tree_boruvka = set(boruvka(adj_list)) normalize_edge_list(min_span_tree_boruvka) if trace: print 'Boruvka: {}'.format(timeit.default_timer() - t) t = timeit.default_timer() min_span_tree_kruskal = set(kruskal(vertex_list, edge_list)) if trace: print 'Kruskal: {}'.format(timeit.default_timer() - t) t = timeit.default_timer() min_span_tree_prim = build_mst_edge_list(prim(adj_list), adj_list) if trace: print 'Prim: {}'.format(timeit.default_timer() - t) success = min_span_tree_boruvka == min_span_tree_kruskal == min_span_tree_prim if not success and trace and n < 100: print 'TEST FAILED:' print 'Adjacency list: {}'.format(adj_list) print 'Edge and vertex list: {}'.format(edge_list) print 'Minimum spanning tree with Boruvka: {}'.format(min_span_tree_boruvka) print 'Minimum spanning tree with Kruskal: {}'.format(min_span_tree_kruskal) print 'Minimum spanning tree with Prim: {}'.format(min_span_tree_prim) print '----------------------------------' return success
def eulerKruskal(n, s, G, input): tracemalloc.start() cost = 0 k = 0 v = s MST = [[] for _ in range(n)] T = kruskal(n, input) for t in T: MST[t[0].value].append([t[1].value, 0]) MST[t[1].value].append([t[0].value, 0]) to_visit = len(T) * 2 vertices = [] while to_visit > 0: vertices.append(v) u = -1 vi = 3 for edg in MST[v]: if edg[1] < 2 and edg[1] < vi: u = edg[0] vi = edg[1] idx = MST[v].index([u, vi]) MST[v][idx][1] += 1 idx = MST[u].index([v, vi]) MST[u][idx][1] += 1 v = u to_visit -= 1 visited = [False for _ in range(n)] i = 0 route = [] route.append(s) while i < len(vertices): if visited[vertices[i]]: vertices.pop(i) else: visited[vertices[i]] = True i += 1 for i in range(0, n - 1): k += 1 cost += G[vertices[i]][vertices[i + 1]] route.append(vertices[i + 1]) memory = tracemalloc.get_traced_memory()[1] tracemalloc.stop() return cost, memory, route, len(route)
def test_kruskal_int_vertices(self): graph = Graph() graph.add_edge(Edge(Vertex(0), Vertex(1), 1)) graph.add_edge(Edge(Vertex(0), Vertex(4), 1)) graph.add_edge(Edge(Vertex(1), Vertex(0), 1)) graph.add_edge(Edge(Vertex(1), Vertex(3), 1)) graph.add_edge(Edge(Vertex(1), Vertex(4), 1)) graph.add_edge(Edge(Vertex(1), Vertex(2), 1)) graph.add_edge(Edge(Vertex(2), Vertex(3), 1)) graph.add_edge(Edge(Vertex(2), Vertex(1), 1)) graph.add_edge(Edge(Vertex(3), Vertex(1), 1)) graph.add_edge(Edge(Vertex(3), Vertex(2), 1)) graph.add_edge(Edge(Vertex(3), Vertex(4), 1)) self.assertEqual(kruskal(graph), 4)
def testMST(self): size = 50 for _ in range(100): adjList = defaultdict(list) edges = [] cnt = 0 weights = range(size * (size - 1) / 2) random.shuffle(weights) for i in range(size): for j in range(i + 1, size): adjList[i].append((j, weights[cnt])) adjList[j].append((i, weights[cnt])) edges.append((i, j, weights[cnt])) cnt += 1 parent = prim(adjList) edges = kruskal(size, edges) self.assertEqual(len(edges) + 1, len(parent)) for u, v in edges: self.assertTrue(parent[u] == v or parent[v] == u)
def clustering(dataP, confLevel=0.95, minRate=0.01, _lambda=10, KMax=50, verbose=False, visualization=False): numPoints = len(dataP) #print(numPoints) print("********************** Clustering **********************") # Complete Graph and Kruskal MST distMatrix = np.zeros((numPoints, numPoints)) repEdges = np.zeros((numPoints * (numPoints - 1), 2)) repEdgeWeights = np.zeros((numPoints * (numPoints - 1), 1)) count = 0 for k in range(numPoints): for l in range(k + 1, numPoints): dist = np.linalg.norm(dataP[k][:] - dataP[l][:], 2) distMatrix[k][l] = dist distMatrix[l][k] = dist repEdges[count][0] = k repEdges[count][1] = l repEdgeWeights[count][0] = dist count += 1 repEdges[count][0] = l repEdges[count][1] = k repEdgeWeights[count][0] = dist count += 1 totalWeight, ST, XSt = kruskal(repEdges, repEdgeWeights) #print(distMatrix) return 1
def kruskal_test(G, expected): mst = kruskal(G) assert len(mst) == len(G.get_vertices()) - 1 mst_cost = 0 unvisited = set(G.get_vertices()) for u, v in mst: unvisited.discard(u) unvisited.discard(v) mst_cost += G.get_weight(u, v) assert len(unvisited) == 0, f"Tkrus is not spanning: {mst}" unvisited = set(G.get_vertices()) expt_cost = 0 for u, v in expected: unvisited.discard(u) unvisited.discard(v) expt_cost += G.get_weight(u, v) assert len(unvisited) == 0, f"Expected is not spanning: {expected}" assert mst_cost == expt_cost
nd6 = Vertice(6) nd6.x = 4 nd6.y = 4 grafo.agregarVertice(nd6) nd7 = Vertice(7) nd7.x = 12 nd7.y = 4 grafo.agregarVertice(nd7) # ALMACENAMIENTO DE CALLES EN GRAFO grafo.conj_aristas.add((1, 1, 2)) grafo.conj_aristas.add((5, 2, 3)) grafo.conj_aristas.add((3, 2, 4)) grafo.conj_aristas.add((4, 3, 4)) grafo.conj_aristas.add((2, 4, 5)) grafo.conj_aristas.add((2, 4, 6)) grafo.conj_aristas.add((3, 6, 7)) # PRUEBA arbol = kruskal(grafo) print("fin de kruskal") camino = dijkstra(grafo, arbol) print("fin de dijkstra") print(camino) mapeoarbol(grafo, arbol, camino) print("fin de grafico de mapa") print("FIN")
} G = weighted_graph.Graph(len(node_numbers)) for node in node_numbers: G.set_vertex(node_numbers[node], node) G.add_edge(node_numbers['N1'], node_numbers['N2'], 3) G.add_edge(node_numbers['N1'], node_numbers['N4'], 2) G.add_edge(node_numbers['N1'], node_numbers['N3'], 3) G.add_edge(node_numbers['N2'], node_numbers['N4'], 9) G.add_edge(node_numbers['N2'], node_numbers['N5'], 4) G.add_edge(node_numbers['N2'], node_numbers['N7'], 2) G.add_edge(node_numbers['N3'], node_numbers['N4'], 4) G.add_edge(node_numbers['N3'], node_numbers['N5'], 1) G.add_edge(node_numbers['N3'], node_numbers['N7'], 6) G.add_edge(node_numbers['N3'], node_numbers['N8'], 6) G.add_edge(node_numbers['N4'], node_numbers['N6'], 1) G.add_edge(node_numbers['N5'], node_numbers['N7'], 7) G.print_graph() print('Breadth First Traversal:') G.breadth_first_traverse() MST = kruskal.kruskal(G) MST.print_graph()
def show_kruskal(self): text = kruskal(self.df) self.k_weight.setText(str(text))
import weighted_graph import kruskal node_numbers = {'John':0, 'Sally':1, 'George':2, 'Phil':3, 'Rose':4, 'Alice':5} G = weighted_graph.Graph(len(node_numbers)) for node in node_numbers: G.set_vertex(node_numbers[node],node) G.add_edge(node_numbers['John'],node_numbers['Sally'],1) G.add_edge(node_numbers['John'],node_numbers['George'],2) G.add_edge(node_numbers['John'],node_numbers['Rose'],3) G.add_edge(node_numbers['George'],node_numbers['Sally'],4) G.add_edge(node_numbers['Phil'],node_numbers['Sally'],5) G.add_edge(node_numbers['Rose'],node_numbers['Alice'],6) G.print_graph() print('Breadth First Traversal:') G.breadth_first_traverse() MST = kruskal.kruskal(G) MST.print_graph()
elaspedTime = time.time() - startTime print('elaspedTime: %f' % elaspedTime) print('') s_name = [] t_name = [] for i in range(0, 6): sid = random.randint(1, VNUM) s_name.append(sid) tid = random.randint(1, VNUM) t_name.append(tid) #print(s_name) #print(t_name) print('---- Test on G1 by kruskal ----') k = kruskal.kruskal() startTime = time.time() mst = k.kruskal(g1) mst.collectEdges() gmst = k.adjgraph() s = s_name[0] t = t_name[0] #ssp = bfs.bfs(gmst, s, t) ssp = bfsdfs.dfs_iter(gmst, s) #print(ssp) elaspedTime = time.time() - startTime print('#1 pair elaspedTime: %f' % elaspedTime) et_arr = [elaspedTime] for i in range(1, 6): #s_id = s_name[i]
def kruskal(): visualKruskal.kruskal(listofEdges, listofVertexes, window)
def kruskal(self): kruskal.kruskal(self)
from kruskal import kruskal vertexs = ['A', 'B', 'C', 'D', 'E', 'F'] edges = [ (5, 'A', 'B'), (1, 'A', 'F'), (2, 'A', 'D'), (3, 'B', 'C'), (3, 'B', 'E'), (1, 'C', 'D'), (4, 'C', 'F'), (4, 'D', 'E'), (2, 'E', 'F'), ] print kruskal(vertexs, edges)
# Brazil's graph, just change the variables # 's' and 'f' in this file and run it like: # $ python work.py < inputs/BR.txt # from graph import Graph from kruskal import kruskal from dijkstra_h import path, dijkstra_h G = Graph() G.build_graph() # minimmum spanning tree mst = kruskal(G) length = sum([edge.weight for edge in mst]) print length # shortest path from city s to f s = 93; f = 112 d, p = dijkstra_h(G, s) print d[f] # shortest path tree from city s s = 104 d, p = dijkstra_h(G, s) edges = [] for v in G.vertices():
def main(): file = open("bnet", "r") # define nodes of the graph nodes = [] for line in file: node, parents, values = line.split(";") values = map(float, values.strip().split()) parents = parents.strip().split() bn_n = { "name": node.strip(), "neighbors": [], "named_neighbors": [], "named_parent": parents, "parent": [], "values": values } nodes.append(bn_n) define_parents_and_neighbors(nodes) define_named_neighbors(nodes) print "MORALIZED GRAPH" moralize_graph(nodes) pretty_print_graph(nodes) print "\nTRIANGULATED GRAPH" triangulate_graph(nodes, deepcopy(nodes)) pretty_print_graph(nodes) print "\nMAXIMAL CLIQUES" maximal_cliques.bron_kerbosch([], nodes, []) cliques = maximal_cliques.cliques str_cliques = [] clique_nodes = {} k = 1 for clique in cliques: str_clique = [node["name"] for node in clique] str_cliques.append(str_clique) maximal_cliques.print_clique(clique) name = "c" + str(k) clique_nodes[name] = str_clique k += 1 edges = set() for i in range(len(clique_nodes)): for j in range(i + 1, len(clique_nodes)): key1 = clique_nodes.keys()[i] key2 = clique_nodes.keys()[j] clique1 = clique_nodes[key1] clique2 = clique_nodes[key2] share = maximal_cliques.share_check(clique1, clique2) if share: # print clique1, clique2, len(share) edges.add((len(share), key1, key2)) edges.add((len(share), key2, key1)) vertices = clique_nodes.keys() # print clique_nodes # print vertices # print edges my_graph = dict() my_graph["vertices"] = vertices my_graph["edges"] = edges # print my_graph mst = kruskal.kruskal(my_graph) print "\nMAXIMUM SPANNING TREE" print mst # for edge in mst: print "(" + str(clique_nodes[edge[1]]) + ", " + str(clique_nodes[edge[2]]) + ") -> " + str(edge[0]) # *********** second part *********** query = {"E": 0} print "\nQUERY:", query clique_tree_nodes = [] orig_clique_nodes = deepcopy(clique_nodes) for clique in clique_nodes: # print clique_nodes[clique], "->", clique str_nodes = clique_nodes[clique] # format your CPD graph representation clique_nodes[clique] = [ get_node_values(nodes, node, clique_nodes[clique]) for node in str_nodes ] cn = { "name": clique, "neighbors": [], "children": [], "named_children": [], "parent": [], "named_parent": [], "leaf": False, "recv_child_map": None, "recv_parent_map": None, "msg_child_map": None, "msg_parent_map": None } cn["cpd"] = clique_nodes[clique] clique_tree_nodes.append(cn) # print orig_clique_nodes # set clique nodes neighbors for edge in mst: clqn1 = find_node_by_name(clique_tree_nodes, edge[1]) clqn2 = find_node_by_name(clique_tree_nodes, edge[2]) clqn1["neighbors"].append(clqn2) clqn2["neighbors"].append(clqn1) clique1 = orig_clique_nodes[clqn1["name"]] clique2 = orig_clique_nodes[clqn2["name"]] share = maximal_cliques.share_check(clique1, clique2) # print clique1, clique2, share # set sepsets if share: if not "sepset" in clqn1: clqn1["sepset"] = {clqn2["name"]: share} else: clqn1["sepset"][clqn2["name"]] = share if not "sepset" in clqn2: clqn2["sepset"] = {clqn1["name"]: share} else: clqn2["sepset"][clqn1["name"]] = share print "\nSEPSETS" for c in clique_tree_nodes: print c["name"], c["sepset"] for evidence in query: incorporate_evidence(clique_tree_nodes, evidence, query[evidence]) print "\nFACTORS" for c in clique_tree_nodes: print c["name"], c["cpd"] # pretty_print_graph_v1(clique_tree_nodes, "neighbors") # root = clique_tree_nodes[random.randint(0, len(clique_tree_nodes) - 1)] root = [node for node in clique_tree_nodes if node["name"] == "c1"][0] global global_root global_root = root["name"] print "\n-> ROOT:", root["name"] # set children/parent according to root init set_links(root) print "\nPARENTS:" pretty_print_graph_v1(clique_tree_nodes, "parent") print "\nLEAVES:" for c in clique_tree_nodes: if c["leaf"]: print c["name"] for node in clique_tree_nodes: node["recv_child_map"] = { children: False for children in node["named_children"] } node["recv_parent_map"] = { parent: False for parent in node["named_parent"] } node["msg_child_map"] = { children: None for children in node["named_children"] } node["msg_parent_map"] = { parent: None for parent in node["named_parent"] } print "\nINITIAL STATUS OF THE CLIQUE NODES" if 1 == 2: for n in clique_tree_nodes: print n["name"], "sent to parent -> ", n["recv_parent_map"] print n["name"], "received from child -> ", n["recv_child_map"] else: print "INITIALIZED." print "----------------" print "\nSEND_MESSAGES" print "----------------" print "[[LEAVES -> ROOT]]\n" leaf_threads = [] for c in clique_tree_nodes: if c["leaf"]: thread = Thread(target=leaf_function, kwargs=(c)) thread.setName(c["name"]) leaf_threads.append(thread) thread.start() non_leaf_threads = [] for c in clique_tree_nodes: if not c["leaf"]: thread = Thread(target=intermediary_node_function, kwargs=(c)) thread.setName(c["name"]) non_leaf_threads.append(thread) thread.start() for thread in leaf_threads: thread.join() print thread.name, "leaf finished...exiting" for thread in non_leaf_threads: thread.join() print thread.name, "node finished...exiting" print "\nALL DONE."
import networkx as nx import random import unittest import kruskal ''' for i in range(1,500,1): for j in range(i+1,500,1): G.add_edge(int(i),int(j),weight=random.randint(1,20)) nx.write_weighted_edgelist(G, "k500.adjlist") ''' G = nx.read_weighted_edgelist("k500.adjlist" , nodetype=int) print kruskal.kruskal(G) print ('coucou') T = nx.minimum_spanning_tree(G) print(sorted(T.edges(data=True))) #print nx.all_pairs_dijkstra_path_length(G)[1]
# -------------- # In order to obtain the results for # Brazil's graph, just change the variables # 's' and 'f' in this file and run it like: # $ python work.py < inputs/BR.txt # from graph import Graph from kruskal import kruskal from dijkstra_h import path, dijkstra_h G = Graph() G.build_graph() # minimmum spanning tree mst = kruskal(G) length = sum([edge.weight for edge in mst]) print length # shortest path from city s to f s = 93 f = 112 d, p = dijkstra_h(G, s) print d[f] # shortest path tree from city s s = 104 d, p = dijkstra_h(G, s) edges = [] for v in G.vertices(): edges += path(p, s, v)
print "Node tool Selected" mode = [True, False, False, False] if ButtonUndirectedPath.pressed(pos): print "Undirected Path Tool Selected" mode = [False, True, False, False] if ButtonDirectedPath.pressed(pos): print "Directed Path Tool Selected" mode = [False, False, True, False] if ButtonRun.pressed(pos): print("Minimum Spanning Tree Is:") print(kruskal.kruskal(Graph)) print("Topological Sort") print(topsort.dfs_topsort(Graph)) print("Breadth First Search") answer = inputbox.ask(window, "Enter Node for BFS") answer = ord(answer) - ord('1') print(BFS.BFS(Graph, Graph.vertexList[answer])) print("Dijkstra Tree") answer = inputbox.ask(window, "Enter Node for Dijkstra Tree")
plt.plot([x[0] for x in c], [x[1] for x in c], "b--") # m => set of edges in mst def plot_mst(m): for e in m: c = e.tuple_rep() plt.plot([x[0] for x in c], [x[1] for x in c], "b-") if __name__ == "__main__": # base data graph, points = setup() # find the mst mst_prim = prim(graph, points, len(points)) mst_kruskal = kruskal(graph) # metadata for Kruskal p1 = plt.subplot(221) p1.set_title("Kruskal") plt.ylim([-1, 5]) plt.xlim([-1, 5]) # basic plot_base(graph, points) # the goods plot_mst(mst_kruskal) # metadata for Prim p2 = plt.subplot(222)
from parseOsm import * from grafos import * from kruskal import kruskal from grafico import mapeoarbol from depuracion import depurar archivo = "mapa.osm" depurar(archivo) print("fin de depuracion") archivo2 = "modificado.xml" grafo = Grafo() grafo = grafoOSM(archivo2) print("fin de procesamiento de datos OSM") # PRUEBA k = kruskal(grafo) print("fin de kruskal") mapeoarbol(grafo, k) print("fin de grafico de mapa") #otros comentarios print("FIN") # comentarios para probar un segundo commit