def KruskalMST(graph:EdgeWeightedGraph): MST = [] EdgeSequence=[] UF = UnionFind(graph.numVertices()) #Pre-processing the edges PQ = [] for item in graph.adj: PQ += graph.adj[item] heapq.heapify(PQ) while (len(PQ)>0) & (len(MST) < graph.numVertices()-1): e = heapq.heappop(PQ) v = e.either() w = e.other(v) if (UF.connected(v,w)): continue else: UF.union(v,w) heapq.heappush(MST, e) EdgeSequence.append(e) cluster = set() for item in UF.id: cluster.add(item) print ("cluster:", cluster, len(cluster)) print (e.weight) return MST
def main(): V = set() file_handle = open("Edges.txt", 'r') for line in file_handle: if len(line.split()) <= 2: numNodes = int(line.split()[0]) numEdges = int(line.split()[1]) graph = EdgeWeightedGraph(numNodes) else: v = int(line.split()[0]) w = int(line.split()[1]) weight = int(line.split()[2]) edge = Edge(v, w, weight) graph.addEdge(edge) V.add(v) V.add(w) # for item in graph.adj[1]: # print(item.either(),item.other(item.either()), item.weight) # # print ("min",minEdge(graph.adj[1]).weight) # #print(graph.adj[1][1].either(),graph.adj[1][1].other(graph.adj[1][1].either()), graph.adj[1][1].weight) # #print(graph.adj[1][2].either(),graph.adj[1][2].other(graph.adj[1][2].either()), graph.adj[1][2].weight) # #print(graph.adj[1][1] > graph.adj[1][2] ) Primedges = primMST(graph, V, 1) sum = 0 for item in Primedges: sum += item.weight print(sum)
def LoadGraph(filename): file_handle = open(filename, 'r') for line in file_handle: if len(line.split()) <= 1: numNodes = int(line.split()[0]) graph = EdgeWeightedGraph(numNodes) else: v = int(line.split()[0]) w = int(line.split()[1]) weight = int(line.split()[2]) edge = Edge(v, w, weight) graph.addEdge(edge) return graph
def main(): G = EdgeWeightedGraph(16384,0) mst = PrimMST(G) mst.toString() mst.sum_weight
class Network: graph = EdgeWeightedGraph() path = [] def __init__(self): graph = EdgeWeightedGraph() def readGraph(self, filename): f = open(filename, 'r') for line in f: v1, v2, v3 = line.split(" ") weight = float(v3) self.graph.addEdge(v1, v2, weight, 0, 0) def createPath(self): e1 = Edge("A", "B", 0.0, 0, 0) e2 = Edge("B", "C", 0.0, 0, 0) self.path.append(e1) self.path.append(e2) # draw the graph def drawGraph(self, filename): # create an empty undirected graph G = pgv.AGraph('graph myGraph {}') # draw edges for n in self.graph.V(): for e in self.graph.adj(n): x = e.either() y = e.other(x) G.add_edge(x, y, e.weight, label=e.weight) #highlight edges in path with red color for e in self.path: v1 = e.either() v2 = e.other(v1) edge = G.get_edge(v1, v2) edge.attr['color'] = 'red' # render graph into PNG file G.draw(filename, prog='dot') os.startfile(filename)
class Question4b: graph = EdgeWeightedGraph() storeEdges = [] def __init__(self): graph = EdgeWeightedGraph() def readGraph(self, filename, nodeName, nodeWeight): f = open(filename, 'r') for line in f: v1, v2, v3 = line.split(" ") weight = float(v3) travelTime = 0 costs = 0 self.graph.addEdge(v1, v2, weight, travelTime, costs) self.getVerticesFromEither(nodeName) self.displayVerticesAndDistance(nodeWeight, nodeName) def getVerticesFromEither(self, nodeName): for e in self.graph.adj(nodeName): x = e.either() y = e.other(x) if x is nodeName: self.storeEdges.append(e) elif y is nodeName: self.storeEdges.append(e) def displayVerticesAndDistance(self, edgeWeight, nodeName): for x in range(0, len(self.storeEdges)): if self.storeEdges[x].weight < edgeWeight: if nodeName is self.storeEdges[x].v: print "node: " + str(self.storeEdges[x].w), print " weight: " + str(self.storeEdges[x].weight) if nodeName is self.storeEdges[x].w: print "node: " + str(self.storeEdges[x].v), print " weight: " + str(self.storeEdges[x].weight)
def drawGraph(self, filename): Gpgv = pgv.AGraph('graph myGraph {}') for n in G.V(): for e in G.adj(n): x = e.either() y = e.other(x) Gpgv.add_edge(x, y, e.weight, label=e.weight) for e in self.path: v1 = e.either() v2 = e.other(v1) edge = Gpgv.get_edge(v1, v2) edge.attr['color'] = 'red' Gpgv.draw(filename, prog='dot') os.startfile(filename) G = EdgeWeightedGraph() G.readGraph("tinyEWG.txt") s = G.V()[5] sp = DijkstraSP(G, s, "distance") for v in G.V(): print str(s) + " to " + str(v) + " (" + str(sp.distTo[v]) + "):", for e in reversed(sp.pathTo(6)): sp.createPath(e.src(), e.dest(), e.weight, 0, 0) print str(e.src()) + "->" + str(e.dest()) + " " + str(e.weight) + " ", print filename = "dijkstragenerate.png" sp.drawGraph(filename)
if not self.marked[v] == True: self._visit(ewg, v) if not self.marked[w] == True: self._visit(ewg, w) def _visit(self, ewg, v): self.marked[v] = True for e in ewg.adj(v): if not self.marked[e.other(v)] == True: self.pq.enqueue(e) def edges(self): return self.mst j = EdgeWeightedGraph(6) e1 = Edge(5, 1, 10) j.addEdge(e1) e2 = Edge(1, 2, 4) j.addEdge(e2) e3 = Edge(1, 3, 3) j.addEdge(e3) e4 = Edge(3, 4, 4) j.addEdge(e4) e5 = Edge(2, 0, 5) j.addEdge(e5) e6 = Edge(0, 4, 4) j.addEdge(e6) w = LazyPrimMST(j) for x in w.edges():
y = e.other(x) Gpgv.add_edge(x, y, e.weight, label=e.weight) for e in self.path: v1 = e.either() v2 = e.other(v1) edge = Gpgv.get_edge(v1, v2) edge.attr['color'] = 'red' Gpgv.draw(filename, prog='dot') os.startfile(filename) ''' end question 3a ''' G = EdgeWeightedGraph() G.readGraph("tinyEWG.txt") mst = PrimMST(G, "distance") sum = 0 for e in mst.edges(): eV = e.either() #get left node eW = e.other(eV) #get right node mst.createPath(eV, eW, e.weight, 0, 0) print e.toString() sum += e.weight filename = "primgenerate.png" mst.drawGraph(filename) print sum
def __init__(self): graph = EdgeWeightedGraph()
if self.pq.contains(w): self.pq.decreaseKey(w, self.distTo[w]) else: self.pq.insert(w, self.distTo[w]) def edges(self): mst = [] for v in range(0, len(self.edgeTo)): e = self.edgeTo[v] if e != None: mst += [e] return mst def weight(self): weight = 0.0 for e in self.edges(): weight += e.Weight() return weight def check(self, G): pass if __name__ == '__main__': myin = In(sys.argv[1], None) G = EdgeWeightedGraph(myin) mst = PrimMST(G) for e in mst.edges(): print(e) print("%.5f\n" % mst.weight())
# Mark a vertex when visit it and add all the adjacent edges to it on to the MinPQ def _visit(self, vertex, graph): self._marked[vertex] = True for edge in graph.adj(vertex): if not self._marked[edge.other(vertex)]: self._pq.insert(edge) # All the edges in the minimum spanning tree def edges(self): return self._mst # The total weight of the minimum spanning tree def weight(self): weight = 0 for edge in self._mst: weight += edge.weight() return weight # Unit Test if __name__ == "__main__": file_name = argv[1] graph = EdgeWeightedGraph.read_file(file_name) mst = MSTPrim(graph) for edge in mst.edges(): print(edge) print(mst.weight())
if not self.marked[v]: self.visit(G, v) if not self.marked[w]: self.visit(G, w) self.edges.append(edge) self.weight += edge.getWeight() def visit(self, G, vid): self.marked[vid] = True edges = G.getAdjacentEdges(vid) for edge in edges: if not self.marked[edge.other(vid)]: self.pq.insert(edge) def getEdges(self): return self.edges def getWeight(self): return self.weight if __name__ == '__main__': inputFile = sys.argv[1] g = EdgeWeightedGraph(inputFile) mst = MST(g) for e in mst.getEdges(): print e print mst.getWeight()
if __name__ == "__main__": import sys from PrimMST import PrimMST from EdgeWeightedGraph import EdgeWeightedGraph flag = int(sys.argv[1]) numpoints = int(sys.argv[2]) numtrials = int(sys.argv[3]) dimension = int(sys.argv[4]) ave_weight = [] # simulate trials for i in range(numtrials): # generate random complete undirected graph G = EdgeWeightedGraph(numpoints, dimension) mst = PrimMST(G) # debug if flag == 1: mst.toString() ave_weight.append(mst.sum_weight) print("%f %d %s %s" % (sum(ave_weight) / numtrials, numpoints, numtrials, dimension))
self._visit(ewg,v) if not self.marked[w] == True : self._visit(ewg,w) def _visit(self,ewg,v): self.marked[v] = True for e in ewg.adj(v): if not self.marked[e.other(v)] == True : self.pq.enqueue(e) def edges(self): return self.mst j = EdgeWeightedGraph(6) e1 = Edge(5,1,10) j.addEdge(e1) e2 = Edge(1,2,4) j.addEdge(e2) e3 = Edge(1,3,3) j.addEdge(e3) e4 = Edge(3,4,4) j.addEdge(e4) e5 = Edge(2,0,5) j.addEdge(e5) e6 = Edge(0,4,4) j.addEdge(e6) w = LazyPrimMST(j) for x in w.edges():