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 __init__(self): self.getUserInput() self.initOperations() verticesList = self.getVerticesList() self.graph = DirectedGraph(verticesList) self.addEdgesToGraph() self.graph.topologicalSort()
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 initializeInDegreeMap(graph: DirectedGraph) -> dict: inDegree = {} for node in graph.getAllNodes(): inDegree[node] = 0 for node in graph.getAllNodes(): for neighbor in node.neighbors: inDegree[neighbor] += 1 return inDegree
def setUp(self): self.v = Vertex('v') self.w = Vertex('w') self.x = Vertex('x') self.e1 = Arc(self.v, self.w) self.e2 = Arc(self.w, self.x) self.e3 = Arc(self.x, self.v) self.dg = DirectedGraph([self.v, self.w, self.x], [self.e1, self.e2, self.e3])
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 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 mDFS(graph: DirectedGraph) -> list(): stack = [] visited = [] for node in graph.getAllNodes(): if node not in visited: TopSort.DFSHelper(node, stack, visited, graph) output = [] while (len(stack) > 0): output.append(stack.pop()) return output
def test_ngon_with_chord(self): v1 = Vertex('v1') v2 = Vertex('v2') v3 = Vertex('v3') v4 = Vertex('v4') v5 = Vertex('v5') e1 = Arc(v2,v1) e2 = Arc(v3,v2) e3 = Arc(v3,v4) e4 = Arc(v4,v5) e5 = Arc(v5,v1) ngon = DirectedGraph([v1,v2,v3,v4,v5], [e1,e2,e3,e4,e5]) self.assertFalse(ngon.has_knot()) chord = Arc(v1,v4) ngon.add_edge(chord) self.assertTrue(ngon.has_knot())
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
class SQLConflictSerializable: graph = None userInput = None operations = [] def __init__(self): self.getUserInput() self.initOperations() verticesList = self.getVerticesList() self.graph = DirectedGraph(verticesList) self.addEdgesToGraph() self.graph.topologicalSort() # self.graph.print() def initOperations(self): splittedInput = self.userInput.split(";") for command in splittedInput: indexOfP = command.find("(") operand = command[0] transactionsNumber = int(command[1:indexOfP]) variable = command[indexOfP + 1:-1] operationToAdd = operation(operand, transactionsNumber, variable) self.operations.append(operationToAdd) def getVerticesList(self): listOfTransactions = [] for operation in self.operations: if operation.transactionId not in listOfTransactions: listOfTransactions.append(operation.transactionId) return listOfTransactions def getUserInput(self): print("Please type your transactions list") self.userInput = input() def addEdgesToGraph(self): numberOfOperand = len(self.operations) for i in range(numberOfOperand): currentOperand = self.operations[i] for j in range(i + 1, numberOfOperand): if self.operations[j].variable == currentOperand.variable and self.operations[j].transactionId != currentOperand.transactionId: if currentOperand.operand == 'R' and self.operations[j].operand == 'W': self.graph.addEdge(currentOperand.transactionId, self.operations[j].transactionId) elif currentOperand.operand == 'W' and self.operations[j].operand == 'R': self.graph.addEdge(currentOperand.transactionId, self.operations[j].transactionId) elif currentOperand.operand == 'W' and self.operations[j].operand == 'W': self.graph.addEdge(currentOperand.transactionId, self.operations[j].transactionId)
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): # 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
def mDFS(graph: DirectedGraph) -> list: topSort = [] visited = set() for node in graph.getAllNodes(): stack = [node] while len(stack) != 0: curr = stack.pop() if curr not in visited: visited.add(curr) n = len(stack) for neighbor in node.neighbors: if neighbor not in visited: stack.insert(n, neighbor) topSort.append(node) return topSort[::-1]
def Kahns(graph: DirectedGraph): output = [] queue = [] for node in graph.getAllNodes(): if node.inDegree is 0: queue.append(node) while len(queue) is not 0: currNode = queue.pop(0) output.append(currNode) for neighbor in graph.adjList[currNode]: neighbor.inDegree = neighbor.inDegree - 1 if neighbor.inDegree is 0: queue.append(neighbor) currNode.inDegree = -1 return output
class TestKnots(unittest.TestCase): def setUp(self): self.v = Vertex('v') self.w = Vertex('w') self.x = Vertex('x') self.e1 = Arc(self.v, self.w) self.e2 = Arc(self.w, self.x) self.e3 = Arc(self.x, self.v) self.dg = DirectedGraph([self.v, self.w, self.x], [self.e1, self.e2, self.e3]) def test_positive(self): #triangular knot self.assertEqual(self.dg.has_knot(), True) #triangular knot w/ an edge into it self.a = Vertex('a') self.dg.add_vertex(self.a) self.Kanye = Arc(self.a,self.v) self.dg.add_edge(self.Kanye) self.assertTrue(self.dg.has_knot()) def test_ngon_with_chord(self): v1 = Vertex('v1') v2 = Vertex('v2') v3 = Vertex('v3') v4 = Vertex('v4') v5 = Vertex('v5') e1 = Arc(v2,v1) e2 = Arc(v3,v2) e3 = Arc(v3,v4) e4 = Arc(v4,v5) e5 = Arc(v5,v1) ngon = DirectedGraph([v1,v2,v3,v4,v5], [e1,e2,e3,e4,e5]) self.assertFalse(ngon.has_knot()) chord = Arc(v1,v4) ngon.add_edge(chord) self.assertTrue(ngon.has_knot())
return topological_list def dfs_visit(graph: Graph, u: Any, time: int, status: dict, topological_list: LinkedList) -> None: """ Completely explores each vertex connected to the source vertex u, starting from lowest depth :param graph: the graph to perform dfs_visit on :param u: the vertex to recurse down :param time: the time called :return: the time after dfs_visit() completes on the source vertex """ status[u] = 1 # update u to grey time += 1 for v in graph.adjacency_list[u]: if status[v] == 0: dfs_visit(graph, v, time, status, topological_list) status[u] = 2 time += 1 topological_list.insert_first(u) if __name__ == '__main__': graph = DirectedGraph() graph.add_vertices(["a", "b", "c", "d", "e", "f"]) graph.add_edges([("a", "b"), ("a", "d"), ("b", "e"), ("c", "f"), ("d", "b"), ("f", "d")]) print(graph) print(topological_sort(graph))
# -*- coding: utf-8 -*- """ Created on Tue Jan 7 23:02:05 2020 @author: erick """ from DirectedGraph import DirectedGraph graph = DirectedGraph(8) graph.addEdge(0, 1, 1) graph.addEdge(1, 2, 4) graph.addEdge(1, 3, 3) graph.addEdge(2, 3, 3) graph.addEdge(2, 4, 2) graph.addEdge(2, 5, 5) graph.addEdge(4, 5, 2) graph.addEdge(4, 6, 6) graph.addEdge(5, 6, 1) graph.addEdge(7, 0, 2) graph.addEdge(7, 1, 4) graph.addEdge(7, 3, 8) distances = graph.altDijkstra(7) for i in range(len(distances)): print("node:", i, "distance", distances[i])
#!/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")
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])
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))
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])
def topological_sort(self, graph): visited = [False] * len(graph) stack = [] # iterate through all the vertices to ensure disconnected vertices are included for vertex in range(len(graph)): # condition is important to not visit redundant vertices (i.e vertices # that are already in the recursion stack) if not visited[vertex]: self.topological_sort_util(graph, vertex, visited, stack) print("Topological sorted order of vertices: ", stack) def topological_sort_util(self, graph, source, visited, stack): visited[source] = True if graph[source]: for adj_vertex in graph[source]: if not visited[adj_vertex]: self.topological_sort_util(graph, adj_vertex, visited, stack) stack.insert(0, source) 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) TopologicalSort().topological_sort(g.adj_list)
queue.enqueue(source) while not queue.is_empty(): r = queue.dequeue() for node in r.links: if node.visited is False: print(node, target) if node == target: return True node.visited = True queue.enqueue(node) return False if __name__ == '__main__': g = DirectedGraph() a = g.add_node('A') b = g.add_node('B') c = g.add_node('C') d = g.add_node('D') e = g.add_node('E') f = g.add_node('F') a.points_to(b) a.points_to(f) b.points_to(d) b.points_to(e) c.points_to(b)
#Prijesh Dholaria # CS 435 Section 6 # Question 4 from DirectedGraph import DirectedGraph import random class Main def createRandomDAGIter(n) g = DirectedGraph() d = {} for num in range (n) g.addNode(num) nodes = g.getAllNodes() for node in nodes numofNodes = random.randint() numsinList= []; while len(numsinList)!= numofNodes num = random.randint(1, nn) if num not in numsinList numsinList.append(num) graph.addDirectedEdge(node, num) return g;
while queue: v = queue.pop(0) if graph[v]: for adj_v in graph[v]: if color[adj_v] == color[v]: return False if color[adj_v] is None: queue.append(adj_v) color[ adj_v] = "red" if color[v] == "black" else "black" return True g = DirectedGraph(6) g.add_edge(0, 2) g.add_edge(2, 0) g.add_edge(1, 2) g.add_edge(0, 3) g.add_edge(0, 4) g.add_edge(0, 5) g.add_edge(4, 5) # g.add_edge(2, 3) obj = BipartiteGraph() # print(obj.is_bipartite(g.get_graph(), 0)) lst = [[2, 4], [2, 3, 4], [0, 1], [1], [0, 1], [7], [9], [5], [], [6], [12, 14], [], [10], [], [10], [19], [18], [], [16], [15], [23], [23], [], [20, 21], [], [], [27], [26], [], [], [34], [33, 34], [], [31], [30, 31], [38, 39], [37, 38, 39], [36], [35, 36],
def _depth_first_search(self, graph, source): self._marked[source] = True for neighbor in graph.adj(source): if not self._marked[neighbor]: self._depth_first_search(graph, neighbor) # Check if a vertex is reachable from the source def reachable(self, vertex): return self._marked[vertex] if __name__ == "__main__": argc = len(argv) file_name = argv[1] sources = Bag() for i in range(2, argc): sources.add(int(argv[i])) graph = DirectedGraph.read_file(file_name) vertex_num = graph.vertex_num() path = DFSDirectedGraph(graph) path.search_mulitple_sources(graph, sources) print("The graph: ") print(graph) for vertex in range(0, vertex_num): if path.reachable(vertex): print(vertex, end=" ") print()
def createRandomDAGIter(n : int) -> DirectedGraph: return populateGraph(DirectedGraph(), n)