def read(path): (V,L) = loadWeightedGraph(path) G = [ Node() for i in range(V+1) ] for (x,y,c) in L: G[x].addEdge(y,c) G[y].addEdge(x,c) return G, set([i for i in range(1,V+1)])
def testStoerWagner(path): V, L, solution = dimacs.loadWeightedGraph(path) g = Graph(V, L) res = StoerWagnerAlgorithm(g) print("compare", res, solution) return res == solution
def solve(test): (V, E) = loadWeightedGraph(r"Laboratory\Lab_1\Tests" + "\\" + test) E.sort(key=lambda edge: edge[2]) sys.setrecursionlimit(5000) solution = bin_search_solution(E, V, 1, 2) return solution
def loadGraph(name): (V,L) = loadWeightedGraph(name) G = [Node() for i in range(V+1)] for u, v, c in L: G[u].out.add(v) G[v].out.add(u) return G
def loadGraph(path): n, edges = renumber(*dimacs.loadWeightedGraph(path)) vertices = [Node(vtx) for vtx in range(n)] for u, v, _ in edges: vertices[u].connect_to(v) vertices[v].connect_to(u) return vertices
def load_graph(file_path): (v_num, edges) = loadWeightedGraph(file_path) graph = [None] + [Node(i) for i in range(1, v_num + 1) ] # to index vertices by their number for (u, v, _) in edges: graph[u].connect_to(v) graph[v].connect_to(u) return graph
def run(name): (V, L) = loadWeightedGraph(name) G = [None] + [Node(i) for i in range(1, V + 1)] # żeby móc indeksować numerem wierzchołka for (u, v, _) in L: G[u].connect_to(v) G[v].connect_to(u) return G, lex_bfs(G)
def find_union_method(name): Graph = loadWeightedGraph(name) Unia = union(Graph[0]) Graph[1].sort(reverse=True, key=lambda x: x[2]) result = None for i in Graph[1]: Unia.make_union(i[0], i[1]) result = i[2] if Unia.find_set(1) == Unia.find_set(2): break return result
def check_graph_planarity(path): (v_num, edges) = loadWeightedGraph(path) graph = nx.Graph() nodes = [i for i in range(1, v_num+1)] graph.add_nodes_from(nodes) graph.add_weighted_edges_from(edges) print(1) if check_planarity(graph)[0] else print(0)
def articulation_points(): v_len, edges = loadWeightedGraph("articulation/AT") graph = [[] for _ in range(v_len + 1)] for x, y, _ in edges: graph[x].append(y) graph[y].append(x) tremaux_tree, low = dfs(graph) print(tremaux_tree) for node in tremaux_tree: print(node.idx) print(low)
def solve(test_path): (V, L) = loadWeightedGraph(test_path) FU = [[i, 0] for i in range(V + 1)] s = 1 t = 2 L = sorted(L, key=lambda x: -x[2]) res = L[0][2] for edge in L: union(edge[0], edge[1], FU) res = min(res, edge[2]) if find(s, FU) == find(t, FU): break return res
def edge_connectivity(test): (V, _) = loadWeightedGraph(test) minimum = float("inf") for s in range(1, V): t = s + 1 while t <= V: v = ford_fulkerson(test, s, t) if v < minimum: minimum = v t = t + 1 return minimum
def main(): graphs = os.listdir("maxclique") #graphs = ["game", "cycle3", "house"] #graphs = ["interval-rnd50"] graphs = [sys.argv[1]] print(len(graphs)) for name in graphs: #print(name, file=sys.stderr) V, L = loadWeightedGraph("maxclique/" + name) print(V, len(L)) for u, v, _ in L: print(u, v)
def tour(graph): # V - liczba wierzchołków, L - lista krawędzi postaci(x,y,weight) (V, L) = loadWeightedGraph(graph) # sortowanie krawędzi grafu malejąco - sortuję krotki po wadze L.sort(key=lambda tup: tup[2], reverse=True) nodes = [Node(i + 1) for i in range(V)] for x, y, weight in L: if find_set(nodes[x - 1]) != find_set(nodes[y - 1]): union(nodes[x - 1], find_set(nodes[y - 1])) # koniec algorytmu if find_set(nodes[0]) == find_set(nodes[1]): return weight
def solve(test): (V, E) = loadWeightedGraph(r"Laboratory\Lab_1\Tests" + "\\" + test) subsets = [Subset(u) for u in range(V + 1)] s, t = 1, 2 graph = Graph(V, E) graph.sort_edges() for (u, v, w) in graph.edges: union(subsets, u, v) s_repr = find(subsets, s) t_repr = find(subsets, t) if s_repr == t_repr: return w return -1
def edge_connectivity(graph): (_, V, L) = loadWeightedGraph(graph) # wykorzystujemy słownik mapujący wierzchołki do których są krawędzie na ich wagi G = [{} for i in range(V + 1)] for u, v, c in L: G[u][v] = G[v][u] = c deleted = 0 result = float("inf") while deleted != len(G) - 2: res, deleted = minimumCutPhase(G, deleted) result = min(result, res) return result
for j in range(i + 1, n - 1): Ni = G[vs[i]].out Nj = G[vs[j]].out verts = [pi[v] for v in Nj - Ni if pi[v] < i] if verts: viable = [pi[v] for v in Ni - Nj] if not viable or min(verts) <= min(viable): return False return True grDir = "graphs/chordal" for f in os.listdir(grDir): (V, L) = loadWeightedGraph(os.path.join(grDir, f)) G = [None] + [Node(i) for i in range(1, V + 1)] for (u, v, _) in L: G[u].connect_to(v) G[v].connect_to(u) print("{}: {}".format(f, checkLexBFS(G, lexBFS(G, V)))) """ (V, L) = loadWeightedGraph(os.path.join(grDir, "interval-rnd10")) G = [None] + [Node(i) for i in range(1, V + 1)] for (u, v, _) in L: G[u].connect_to(v) G[v].connect_to(u) print(checkLexBFS(G, lexBFS(G, V))) """
""" main module of this laboratory""" from FindUnionMethod import find_union_method from dimacs import loadWeightedGraph from Testing import testing from BS_BFS_DFS import bs_dfs_method from lab1.GraphFunctions import dfs_limited, edge_list_to_adjacency_list if __name__ == "__main__": #print(dfs_limited(edge_list_to_adjacency_list(loadWeightedGraph("Graf/path10")), 11, 1, 2)) print(bs_dfs_method(loadWeightedGraph("Graf/cloque5")))
q.put(graph[curr_v][i][0]) return False def binary_search(v, edge_list, search_algorithm): # search algorithm: dfs, dfs_rec or bfs graph = make_adj_list(v, edge_list) edge_list.sort(key=lambda l: l[2]) max_weight = edge_list[len(edge_list) - 1][2] min_weight = edge_list[0][2] curr_weight = (max_weight + min_weight) // 2 while max_weight - min_weight > 1: if search_algorithm(graph, curr_weight): min_weight = curr_weight else: max_weight = curr_weight curr_weight = (max_weight + min_weight) // 2 if search_algorithm(graph, min_weight + 1): print(min_weight + 1) else: print(min_weight) (v_len, edges) = dimacs.loadWeightedGraph(sys.argv[1]) # reading graph binary_search(v_len, edges, dfs)
C = {fst_elem_key: G[fst_elem_key]} cut_weight = None while len(C) < len(G): u, cut_weight = max(tightness(G, C).items(), key=lambda item: item[1]) C[u] = G[u] r_iter = reversed(G.keys()) t = next(r_iter) s = next(r_iter) merge_vertices(G, s, t) return cut_weight def minimum_cut(size, edge_list): edge_list = list( map(lambda edge: (edge[0] - 1, edge[1] - 1, edge[2]), edge_list)) G = {i: Node() for i in range(size)} for u, v, w in edge_list: G[u].add_edge(v, w) G[v].add_edge(u, w) return min([minimum_cut_phase(G) for _ in range(size - 1)]) data = dimacs.loadWeightedGraph("graphs/clique200") print(minimum_cut(*data))
return (flow, path) else: return (0, []) def findBestPath(G, s, t): graph = Graph(G[1], G[0]) edges = G[1] edges = sorted(edges, key=lambda edge: edge[2]) q = len(edges) - 1 p = 0 if BFS(graph, s, t, edges[q][2])[0] > 0: return edges[q][2] if BFS(graph, s, t, edges[p][2])[0] == 0: return 0 while p < q - 1: half = int((p + q) / 2) flow = BFS(graph, s, t, edges[half][2])[0] if flow > 0: p = half elif flow == 0: q = half if BFS(graph, s, t, edges[q][2])[0] > 0: return edges[q][2] else: return edges[p][2] print(findBestPath(dimacs.loadWeightedGraph(sys.argv[1]), 1, 2))
def testFindUnion(path): V,L,expected = dimacs.loadWeightedGraph(path) return przewodnikTurystycznyFindUnion(V,L) == expected
def __init__(self, V, L): self.G = [Node() for i in range(V + 1)] self.V = V for (x, y, c) in L: self.G[x].addEdge(y, c) self.G[y].addEdge(x, c) def add_edge(self, u, v, weight): self.G[u].addEdge(v, weight) def delete_edge(self, u, v): self.G[u].delEdge(v) def print_graph(self): for (u, node) in enumerate(self.G): for v in range(1, self.V + 1): weight = node.edges.get(v, 0) if weight != 0: print(f"From: {u}, to: {v}, weight: {weight}") # def stoer_wagner(test): test_dir = "Laboratory\\Lab_3\\tests\\connectivity" (V, L) = loadWeightedGraph(test_dir + "\\simple") # wczytaj graf graph = Graph(V, L) graph.print_graph()
# print("aktualny",res, "best", best, "zostalo", x) # print("result:",min(res)) return best def testStoerWagner(path): V, L, solution = dimacs.loadWeightedGraph(path) g = Graph(V, L) res = StoerWagnerAlgorithm(g) print("compare", res, solution) return res == solution V, L, res = dimacs.loadWeightedGraph("tests/grid5x5") # for (x,y,c) in L: # przeglądaj krawędzie z listy # print( "krawedz miedzy", x, "i", y,"o wadze", c ) # wypisuj import time g = Graph(V, L) g.print() start = time.time() print("powinno byc", res, "a jest", StoerWagnerAlgorithm(g)) print("time:", time.time() - start) from runAllTests import run
def run(file): (V, E) = loadWeightedGraph(file) return stoerWagner(V, E)
def read_from_file(pathToFile): source, target, emf = dimacs.read_source(pathToFile) V, L = dimacs.loadWeightedGraph(pathToFile) L = list(map(lambda x: (x[0] - 1, x[1] - 1, x[2]), L)) return Circuit(V, L, source, target, emf)
# https://faliszew.github.io/algograf/lab3 from dimacs import loadWeightedGraph from queue import PriorityQueue from flow_method import * from utils import * from stoer_wagner import * (V,L) = loadWeightedGraph("graphs/clique200") graph = nodesFromEdges(L, V) print(stoerWagner(graph))
import networkx as nx from dimacs import loadWeightedGraph import matplotlib.pyplot as plt G = nx.Graph() filename = 'graphs-lab6/plnar/clique20' (V, L) = loadWeightedGraph(filename) v = [i for i in range(V + 1)] G.add_nodes_from(v) for a, b, w in L: G.add_edge(a, b) from networkx.algorithms.planarity import check_planarity print(check_planarity(G)[0]) pos = nx.spring_layout(G) nx.draw_networkx_nodes(G, pos) nx.draw_networkx_edges(G, pos) plt.show()
y = find_set(y) if x.rank > y.rank: y.parent = x elif y.rank > x.rank: x.parent = y else: x.parent = y y.rank += 1 # wczytuje graf i wypisuje krawędzi (V, L) = loadWeightedGraph("g1") # wczytaj graf for (x, y, c) in L: # przeglądaj krawędzie z listy print("krawedz miedzy", x, "i", y, "o wadze", c) # wypisuj print() def tour(graph): # V - liczba wierzchołków, L - lista krawędzi postaci(x,y,weight) (V, L) = loadWeightedGraph(graph) # sortowanie krawędzi grafu malejąco - sortuję krotki po wadze L.sort(key=lambda tup: tup[2], reverse=True) nodes = [Node(i + 1) for i in range(V)]