def __init__(self, file_name, seperator): # First pass reading the file self._hash_table = LPHashTable( ) # This hash table is used to convert from key to vertex index self._graph = None # The actual underlying directed graph file = open(file_name, "r") count = 0 lines = file.read().splitlines() for line in lines: data = line.split(seperator) # Continuously adding keys to the hash table along with the corresponding index for key in data: if not self._hash_table.contains(key): self._hash_table.put(key, count) count += 1 self._keys = np.empty( count, dtype=object) # This array to convert index to key for name in self._hash_table.keys(): self._keys[self._hash_table.get(name)] = name file.close() # Second pass, Build the actual graph after knowing exactly how many vertices we will need second_pass = open(file_name) self._graph = DirectedGraph(count) lines = second_pass.read().splitlines() for line in lines: data = line.split(seperator) start = self._hash_table.get(data[0]) for i in range(1, len(data)): self._graph.add_edge(start, self._hash_table.get(data[i])) second_pass.close()
def __init__(self): self.getUserInput() self.initOperations() verticesList = self.getVerticesList() self.graph = DirectedGraph(verticesList) self.addEdgesToGraph() self.graph.topologicalSort()
def createRandomDagIter(n: int) -> DirectedGraph: newGraph = DirectedGraph() # creates n nodes for the graph for i in range(0, n): newGraph.addNode(i) nodes = newGraph.getAllNodes() for i in range(0, random.randint(1, n * n)): first = nodes[random.randint(0, n - 1)] second = nodes[random.randint(0, n - 1)] if (first == second): continue if second in newGraph.adjList[first] or first in newGraph.adjList[ second]: continue if (len(newGraph.adjList[first]) == 2): continue newGraph.addDirectedEdge(first, second) if newGraph.isAcyclic(first) is False: newGraph.removeDirectedEdge(first, second) return newGraph
def tester(): f = open('SSP_tests.in', 'r') t = int(f.readline()) for _ in range(t): size = int(f.readline()) adj = [None] * size for i in range(size): adj[i] = [int(x) for x in f.readline().split()] soln = [int(x) for x in f.readline().split()] print(dijkstra(DirectedGraph(adj), 0) == soln)
def tester(): f = open('MST_tests.in', 'r') t = int(f.readline()) for _ in range(t): size = int(f.readline()) adj = [None] * size for i in range(size): adj[i] = [int(x) for x in f.readline().split()] soln = int(f.readline()) print(kruskal(DirectedGraph(adj)) == soln)
def createRandomDAGIter(n): """Creates n random nodes with randomly assigned, unweighted, directed edges.""" graph = DirectedGraph() for i in range(n): graph.addNode(i) if i < 2: continue edge = random.sample(graph.getAllNodes(), 2) while not graph.addDirectedEdge(min(edge), max(edge)): edge = random.sample(graph.getAllNodes(), 2) return graph
def createRandomDAGIter(n): randGraph = DirectedGraph() i = 0 # Create n nodes while i < n: randGraph.addNode(i) i += 1 # Assign each node 2 random nodesList (might assign 0, 1 or 2 nodesList) for i in range(len(randGraph.nodesList)): randList = [] #retreive the length of nodesList size = len(randGraph.nodesList) - 1 name = randGraph.nodesList[i].name #generate random number n1 = random.randint(name, size) #d2 n2 = random.randint(name, size) #d1 #if n1 generated is unique checkandCreate(randGraph, name, n1, n2, randList) return randGraph
def createRandomDAGIter(n): # Create new DirectedGraph and add n amount of nodes to it g = DirectedGraph() for i in range(1, n + 1): g.addNode(createLabel(i)) # Copy the list of the nodes from the graph # so we can pop from list nodes = g.getAllNodes().copy() # Shuffle the nodes so the graph doesn't # start with "A" every time shuffle(nodes) # While there are nodes in the list while len(nodes) > 0: cur = nodes.pop(0) if len(nodes) <= 1: break # XXX Choose a random amount of children XXX # Make nodes have 2 children num = 2 # randrange(1,len(nodes)) # Add a random sample of num length # the neighbor of the cur for i in sample(nodes, num): g.addDirectedEdge(cur, i) # For every neighbor of cur do the same for n in cur.neighbors: nodes.pop(nodes.index(n)) if len(nodes) <= 1: break num = 2 # randrange(1,len(nodes)) for i in sample(nodes, num): g.addDirectedEdge(n, i) return g
from DirectedGraph import DirectedGraph def bfs(graph, source): visited = [False] * len(graph.nodes) visited[source] = True bfs_list = [] queue = [source] while queue: s = queue.pop(0) bfs_list.append(s) for vtx in graph.adjacent(s): if not visited[vtx]: visited[vtx] = True queue.append(vtx) return bfs_list inf = float("inf") adj_mat = [[0, 1, 1, inf], [inf, 0, 1, inf], [1, inf, 0, 1], [inf, inf, inf, 0]] search = bfs(DirectedGraph(adj_mat), 2) print(search) print(search == [2, 0, 3, 1])
#!/usr/bin/env python3 # Name: Kyle Aure # Course: CS440 # Date: 07/23/2019 ##### DESCRIPTION ##### # This file hosts graphs for # examples and testing from DirectedGraph import DirectedGraph emptyGraph = DirectedGraph(0) cyclicGraph = DirectedGraph(7) nonCyclicGraph = DirectedGraph(13) cyclicGraph.graph = { 0:[1,2,6], 1:[3], 2:[1], 3:[2,4,5], 4:[], 5:[0,4], 6:[4] } nonCyclicGraph.graph = { 0:[5,6,1], 1:[], 2:[0,3], 3:[5], 4:[], 5:[4], 6:[4,9],
def test_get_graph_from_file(self): with open("graph.txt", "r") as f: firstLine = f.readline() firstLine = firstLine.split() nrVertices = int(firstLine[0]) nrEdges = int(firstLine[1]) graph = DirectedGraph(nrVertices, nrEdges) graph.getGraphFromFile("graph.txt") graph.writeGraphToFile("graphOut.txt") vertices = graph.parseVertices() for vertex in vertices: print(vertex) print(graph.parseNin(vertex)) print(graph.parseNout(vertex)) print("\n") edges = graph.parseEdges() for edge in edges: print(str(edge) + " - " + str(edges[edge])) self.assertEqual(nrVertices, 5) self.assertEqual(graph.isEdge(1, 2), 1) self.assertEqual(graph.isEdge(0, 4), 0) self.assertEqual(graph.getInDegree(1), 2) self.assertEqual(graph.getOutDegree(3), 0) self.assertEqual(graph.parseOutboundEdges(0), [(0, 0), (0, 1)]) self.assertEqual(graph.parseInboundEdges(1), [(0, 1), (2, 1)]) graph.removeEdge((0, 1)) self.assertEqual(graph.getNrEdges(), 5) self.assertEqual(graph.parseOutboundEdges(0), [(0, 0)]) self.assertEqual(graph.parseInboundEdges(1), [(2, 1)]) graph.addEdge(0, 1, 7) graph.removeVertex(2) self.assertEqual(graph.getNrEdges(), 3) self.assertEqual(graph.getNrVertices(), 4) print("\n") for vertex in vertices: print(vertex) print(graph.parseNin(vertex)) print(graph.parseNout(vertex)) print("\n") edges = graph.parseEdges() for edge in edges: print(str(edge) + " - " + str(edges[edge])) self.assertEqual(graph.getCost((0, 1)), 7) graph.modifyCost((0, 1), 5) self.assertEqual(graph.getCost((0, 1)), 5) copyOfGraph = graph.copyGraph() copyOfGraph.modifyCost((0, 1), 7) self.assertEqual(copyOfGraph.getCost((0, 1)), 7) self.assertEqual(graph.getCost((0, 1)), 5) randomGraph = graph.randomGraph(10, 14) randomGraph.writeGraphToFile("randomgraph.txt")
from Main import createRandomDAGIter from DirectedGraph import DirectedGraph from TopSort import * ignore = True # To ignore invalid paths where a node does not exist x = DirectedGraph() for char in "ABCDEFGH": x.addNode(char) x.addDirectedEdge(x.getNode("A"), x.getNode("B")) x.addDirectedEdge(x.getNode("A"), x.getNode("D")) x.addDirectedEdge(x.getNode("C"), x.getNode("D")) x.addDirectedEdge(x.getNode("C"), x.getNode("G")) x.addDirectedEdge(x.getNode("C"), x.getNode("H")) x.addDirectedEdge(x.getNode("D"), x.getNode("G")) x.addDirectedEdge(x.getNode("H"), x.getNode("E")) x.addDirectedEdge(x.getNode("H"), x.getNode("F")) graphs = [createRandomDAGIter(5), createRandomDAGIter(50), x] if __name__ == "__main__": for g in graphs: print(g) print() for func in [TopSort.Kahns, TopSort.mDFS]: arr = func(g) print("Node Count: {} | {}".format(len(arr), arr))
#Me - 6 from DirectedGraph import DirectedGraph from GraphValidator import GraphValidator from Controller import Controller from UI import UI graph = DirectedGraph() validator = GraphValidator() ctrl = Controller(graph, validator) ui = UI(ctrl) ui.runGraph() #9 + 2, 9, 3*10
self.visited = [False] * len(graph) transpose_graph = [None] * len(graph) for vertex in range(len(graph)): if not self.visited[vertex]: self.transpose_util(vertex, transpose_graph) return transpose_graph @staticmethod def display_graph(graph): for v in range(len(graph)): print(v, " --> ", end=" ") if graph[v] is not None: for adj_v in graph[v]: print(adj_v, end=" ") print() g = DirectedGraph(6) g.add_edge(5, 2) g.add_edge(5, 0) g.add_edge(4, 0) g.add_edge(4, 1) g.add_edge(2, 3) g.add_edge(3, 1) TransposeGraph().display_graph(g.get_graph()) print("Transposed ---> ") obj = TransposeGraph() trans = obj.transpose(g.get_graph()) obj.display_graph(trans)
:return: the time after dfs_visit() completes on the source vertex """ status[u] = 1 # update u to grey time += 1 discovery_time[u] = time for v in graph.adjacency_list[u]: if status[v] == 0: parent[v] = u time = dfs_visit(graph, v, time, status, discovery_time, finish_time, parent) status[u] = 2 time += 1 finish_time[u] = time return time if __name__ == '__main__': graph1 = DirectedGraph() graph1.add_vertices([1, 2, 3, 4, 5, 6, 7]) graph1.add_edges([(1, 2), (1, 4), (1, 7), (2, 3), (2, 4), (3, 1), (3, 4), (5, 4), (5, 6), (6, 3), (6, 5), (7, 1), (7, 4)]) print(graph1) print(str(dfs(graph1)) + "\n") graph2 = DirectedGraph() graph2.add_vertices(["a", "b", "c", "d", "e", "f"]) graph2.add_edges([("a", "b"), ("a", "d"), ("b", "e"), ("c", "f"), ("d", "b"), ("e", "d"), ("f", "d"), ("f", "f")]) print(graph2) print(dfs(graph2))
visited[vtx] = True for i in graph.adjacent(vtx): if not visited[i]: top_util(graph,i,visited,stack) stack.append(vtx) def topological_sort(graph): visited = [False]*len(graph.nodes) stack = [] for i in graph.nodes: if not visited[i]: top_util(graph,i,visited,stack) return list(reversed(stack)) inf = float('inf') adj_mat = [ [0,inf,inf,inf,inf,inf], [inf,0,inf,inf,inf,inf], [inf,inf,0,1,inf,inf], [inf,1,inf,0,inf,inf], [1,1,inf,inf,0,inf], [1,inf,1,inf,inf,0] ] so = topological_sort(DirectedGraph(adj_mat)) print(so ) print(so == [5, 4, 2, 3, 1, 0])
def createRandomDAGIter(n : int) -> DirectedGraph: return populateGraph(DirectedGraph(), n)