def test(): v1 = Vertex(1) v2 = Vertex(2) v3 = Vertex(3) v4 = Vertex(4) v5 = Vertex(5) v6 = Vertex(6) v7 = Vertex(7) v1.add_edge(v2) v1.add_edge(v3) v2.add_edge(v3) v1.add_edge(v5) v5.add_edge(v4) v4.add_edge(v3) v6.add_edge(v7) g = Graph(v1, v2, v3, v4, v5, v6, v7) g.print() print(g.E) print("BFS:") BFS(g, v1) print("\nDFS:") DFS(g) print("\nTopological sort:") print(topological_sort(g))
class MetisGraphReader: def __init__(self, filename): self.__filename = filename if not os.path.exists(self.__filename): print "GRAPH file " + self.__filename + " was not found" sys.exit(1) self.__fhandler = open(self.__filename, 'r') def __ParseNumVertices(self, first_line_splits): return int(first_line_splits[0]) def __ParseNumEdges(self, first_line_splits): return int(first_line_splits[1]) def __CreateWeightedGraph(self, filelines): for i in range(1, len(filelines)): splits = filelines[i].strip().split() if len(splits) % 2 != 0: print "Incorrect line of GRAPH file " + self.__filename + " contains odd number of elements:" print filelines[i] sys.exit(1) for j in range(0, len(splits) / 2): neigh = int(splits[j * 2]) - 1 weight = float(splits[j * 2 + 1]) self.__graph.AddEdge(Edge(i - 1, neigh, weight)) def __CreateUnweightedGraph(self, filelines): for i in range(1, len(filelines)): splits = filelines[i].strip().split() for j in range(0, len(splits)): neigh = int(splits[j]) - 1 weight = 1.0 self.__graph.AddEdge(Edge(i - 1, neigh, weight)) def __GraphIsUnweighted(self, first_line_splits): return len(first_line_splits) == 2 def __GraphIsWeighted(self, first_line_splits): if len(first_line_splits) < 3: return False return first_line_splits[2] == '001' def ExtractGraph(self): lines = self.__fhandler.readlines() first_line_splits = lines[0].strip().split() self.__graph = Graph(self.__ParseNumVertices(first_line_splits)) if self.__GraphIsUnweighted(first_line_splits): #print "Unweighted graph reader was chosen" self.__CreateUnweightedGraph(lines) elif self.__GraphIsWeighted(first_line_splits): #print "Weighted graph reader was chosen" self.__CreateWeightedGraph(lines) print "Graph with " + str(self.__graph.VertexNumber()) + " & " + str(self.__graph.EdgeNumber()) + \ " edges was extracted from " + self.__filename self.__fhandler.close() return self.__graph
def ExtractGraph(self): lines = self.__fhandler.readlines() first_line_splits = lines[0].strip().split() self.__graph = Graph(self.__ParseNumVertices(first_line_splits)) if self.__GraphIsUnweighted(first_line_splits): #print "Unweighted graph reader was chosen" self.__CreateUnweightedGraph(lines) elif self.__GraphIsWeighted(first_line_splits): #print "Weighted graph reader was chosen" self.__CreateWeightedGraph(lines) print "Graph with " + str(self.__graph.VertexNumber()) + " & " + str(self.__graph.EdgeNumber()) + \ " edges was extracted from " + self.__filename self.__fhandler.close() return self.__graph
def test2(): """ Test for johnson """ # comparator = "d" to make dijksta's min-pri-queue work # rank = vertex index to be used in johnsons computation of h(v) = v.d v1 = Vertex("1", 0, comparator="d") v2 = Vertex("2", 1, comparator="d") v3 = Vertex("3", 2, comparator="d") v4 = Vertex("4", 3, comparator="d") v5 = Vertex("5", 4, comparator="d") v1.add_edge(v2, 3) v1.add_edge(v3, 8) v1.add_edge(v5, -4) v2.add_edge(v5, 7) v2.add_edge(v4, 1) v3.add_edge(v2, 4) v4.add_edge(v3, -5) v4.add_edge(v1, 2) # v1.add_edge(v4, -3) # remove comment to create a negative cycle v5.add_edge(v4, 6) g = Graph(v1, v2, v3, v4, v5) D = johnson(g) for vertex, row in enumerate(D): print(f"Shortest paths from {vertex+1} to all:", row)
def johnson(G): """ Finds all-pair shortest paths in sparse graphs using bellman-ford and dijkstra as subroutines. \n Returns matrix D with computed shortest paths from u to v in D[u][v] """ # add a new vertex s to a copy of G, called G_s, where there is an edge (s, v, 0) for all v in G.V s = Vertex("s", -1) for v in G.V: s.add_edge(v, 0) G_s = Graph(*G.V, s) # run bellman-ford to compute v.d from s for all v in G_s.V if not bellman_ford(G_s, s): raise ValueError("Input graph contains a negative-weight cycle") # h is an array satisfying h[v.rank] = v.d, computed from bellman-ford above # here v.rank is used as an index h = [0 for i in range(len(G_s.V))] for v in G_s.V: h[v.rank] = v.d # make every edge non-negative for u in G_s.V: for edge in G_s.adj(u): # edge format: (v, weight) edge[1] = edge[1] + h[u.rank] - h[edge[0].rank] # n x n-array for storing computed all-pair shortest paths n = len(G.V) D = [[None for i in range(n)] for i in range(n)] # runs dijkstra for each vertex u in G.V to compute shortest paths from u to all other vertices v for u in G.V: dijkstra(G, u) for v in G.V: # redo the re-weighting, and store the shortest paths in D D[u.rank][v.rank] = v.d + h[v.rank] - h[u.rank] return D
def ExtractGraph(self): lines = self.__fhandler.readlines() header_index = self.__GetIndexOfHeaderLine(lines) header_line_splits = lines[header_index].strip().split() if not self.__MatrixIsSymmetric(header_line_splits): print "WARN: graph " + self.__filename + " is not symmetric. Undirected graph can not be constructed" sys.exit(1) graph = Graph(self.__ParseNumVertices(header_line_splits)) for i in range(header_index + 1, len(lines)): splits = lines[i].strip().split() if splits[0] == splits[1]: continue weight = 1 if len(splits) > 2: weight = float(splits[2]) v1 = int(splits[0]) - 1 v2 = int(splits[1]) - 1 graph.AddEdge(Edge(v1, v2, weight)) print "Graph with " + str(graph.VertexNumber()) + " vertices & " + str(graph.EdgeNumber()) + \ " edges was extracted from " + self.__filename self.__fhandler.close() return graph
def __init__(self, graph=Graph(0), permutation=Permutation(0), decomposition=Decomposition(), mode="", output_img="", image_size=600, background_color="white"): self.graph = graph self.permutation = permutation self.decomposition = decomposition self.__mode = mode self.output_img = output_img self.image_size = image_size self.background_color = background_color
def _init(): v1 = Vertex("1", 0, comparator="d") v2 = Vertex("2", 1, comparator="d") v3 = Vertex("3", 2, comparator="d") v4 = Vertex("4", 3, comparator="d") v5 = Vertex("5", 4, comparator="d") v1.add_edge(v2, 3) v1.add_edge(v3, 8) v1.add_edge(v5, -4) v2.add_edge(v5, 7) v2.add_edge(v4, 1) v3.add_edge(v2, 4) v4.add_edge(v3, -5) v4.add_edge(v1, 2) v5.add_edge(v4, 6) g = Graph(v1, v2, v3, v4, v5) return g
def test1(): """ Test for floyd-warshall """ # rank = row/col-index in matrix-representation v1 = Vertex("1", 0) v2 = Vertex("2", 1) v3 = Vertex("3", 2) v4 = Vertex("4", 3) v5 = Vertex("5", 4) v1.add_edge(v2, 3) v1.add_edge(v3, 8) v1.add_edge(v5, -4) v2.add_edge(v4, 1) v2.add_edge(v5, 7) v3.add_edge(v2, 4) v4.add_edge(v1, 2) v4.add_edge(v3, -5) v5.add_edge(v4, 6) g = Graph(v1, v2, v3, v4, v5) D, P = floyd_warshall(g)
# adding undirected edges by adding directed edges from both u to v and v to u v1.add_edge(v2, 2) v2.add_edge(v1, 2) v1.add_edge(v3, 4) v3.add_edge(v1, 4) v2.add_edge(v3, 12) v3.add_edge(v2, 12) v1.add_edge(v5, 32) v5.add_edge(v1, 32) v5.add_edge(v4, 11) v4.add_edge(v5, 11) v4.add_edge(v3, 2) v3.add_edge(v4, 2) v6.add_edge(v7, 1) v7.add_edge(v6, 1) v5.add_edge(v6, 9) v6.add_edge(v5, 9) v5.add_edge(v7, 2) v7.add_edge(v5, 2) v7.add_edge(v3, 4) v3.add_edge(v7, 4) g = Graph(v1, v2, v3, v4, v5, v6, v7) g.print() print("MST by Kruskal:") kruskal(g) print("MST by Prim, started in v1 ... v7:") for v in g.V: prim(g, v)