def ErdosRenyiKnotting(): """ Finds the relationship between the probability in an Erdos Renyi graph (p) and the odds that this graph has a knot. """ for num_vert in [5,15,30]: p = .01 ps = [] vs = [Vertex(str(v)) for v in range(num_vert)] ys = [] for k in range(100): knot_count = 0 for i in range(100): drg = DirectedGraph(vs) drg.add_random_arcs(p) #~ c = CircleLayout(drg) if drg.has_knot(): knot_count += 1 knot_prob = knot_count/100.0 ys.append(knot_prob) ps.append(p) p += .01 pyplot.figure(1) pyplot.plot(ps,ys,'o') pyplot.xlabel('p') pyplot.ylabel('Odds of having a knot') pyplot.legend(('5 Vertices','15 Vertices','30 Vertices')) pyplot.show()
def test_is_complete(self): v = Vertex('v') w = Vertex('w') dg = DirectedGraph([v,w]) dg.add_all_edges() self.assertTrue(dg.is_complete())
def test_clustering_coefficient(self): """tests the clustering coefficent""" v = Vertex('v') w = Vertex('w') x = Vertex('x') e = Arc(v,w) e2 = Arc(x, w) e3 = Arc(x, v) dg = DirectedGraph([v, w, x],[e, e2, e3]) self.assertAlmostEqual(dg.clustering_coefficient(),0.5)
def __init__(self, criteria): """ initialize a lattice to the equilibrium state. """ self.__graph = DirectedGraph() self.__weights = dict() #coeff self.__descriptors = dict() #{'a' : 'Gout'} self.__importanceValue = dict() self.__visited = dict() for i in range(len(criteria)-1): self.__descriptors[DESCRIPTORS[i]] = criteria[i] self.__contribute() self.__equilibrate()
def test_complete(self): """a two-vertex complete graph is strongly connected.""" v = Vertex('v') w = Vertex('w') dg = DirectedGraph([v,w]) dg.add_all_edges() self.assertTrue(dg.is_strongly_connected())
def test_is_connected(self): v = Vertex('v') w = Vertex('w') e1 = Arc(v, w) e2 = Arc(w,v) dg = DirectedGraph([v, w], [e1,e2]) self.assertEqual(dg.is_strongly_connected(),True) dg.remove_edge(w,v) self.assertEqual(dg.is_strongly_connected(),False)
def test_remove_edge(self): v = Vertex('v') w = Vertex('w') e = Arc(v, w) dg = DirectedGraph([v, w], [e]) dg.remove_arc(v, w) self.assertEqual(dg[v],{}) self.assertEqual(dg.reverse_graph[w],{}) self.assertEqual(dg[w], {}) self.assertEqual(dg.reverse_graph[v], {})
def createRandomDAGIter(n): rng = 0 graph = DirectedGraph.DirectedGraph() for i in range(0,n): node = Graph.GraphNode(i) graph.verticies.append(node) rng = random.randint(0,len(graph.verticies)-1) if len(graph.verticies) > 1 and rng != node.data: graph.addDirectedEdge(node,graph.verticies[rng]) return graph
def ErdosRenyiClustering(): """ Creates an Erdos-Renyi graph of 1000 vertices and iterates through p, checking the clustering coefficient each time. Uses pylot to graph all that stuff, to see if there's anything interesting """ import matplotlib.pyplot as pyplot vs = [Vertex(str(v)) for v in range(100)] cs = [] ps = [] p = 0.01 for i in range(100): drg = DirectedGraph(vs) drg.add_random_arcs(p) ps.append(p) cs.append(drg.clustering_coefficient()) p += 0.01 pyplot.plot(ps,cs) pyplot.xlabel('p') pyplot.ylabel('clustering coefficient') pyplot.show()
def test_correct_reverse_graph(self): """checks that every out-edge in dg also exists as an in-edge in dg.inverse_graph""" v = Vertex('v') w = Vertex('w') e = Arc(v,w) dg = DirectedGraph([v,w],[e]) #~ dg.complete() out_edges = set() in_edges = set() for v in dg.keys(): for key,val in dg[v].items(): out_edges.update(val) for w in dg.reverse_graph.keys(): for key,val in dg.reverse_graph[w].items(): in_edges.update(val) self.assertEqual(out_edges,in_edges)
def test_in_out_degrees(self): v = Vertex('v') w = Vertex('w') x = Vertex('x') e = Arc(v, w) dg = DirectedGraph([v, w], [e]) self.assertEqual(dg.out_degree(v),1) self.assertEqual(dg.in_degree(w),1) self.assertEqual(dg.out_degree(x),None) self.assertEqual(dg.in_degree(x),None) dg.remove_edge(v,w) self.assertEqual(dg.out_degree(v),0) self.assertEqual(dg.in_degree(w),0)
def remove_unit_productions(self): g = DirectedGraph() productions = self.productions.copy() for key in productions: # construimos el grafo for rule in productions[key]: if len(rule) == 1 and rule in self.nonterminals: g.add_edge(key, rule) followings = { v: g.vertices_forward(v) for v in g.vertices() } not_unit = dict() not_unit_fun = lambda s: len(s) != 1 or s in self.terminals for vertex in g.vertices(): not_unit[vertex] = set(filter(not_unit_fun, productions[vertex])) for e0, e1 in g.edges(): productions[e0].remove(e1) for node in followings[e0]: productions[e0] = productions[e0] | not_unit[node] return productions
def createRandomDAGIter(n: int) -> DirectedGraph: g = DirectedGraph.DirectedGraph() taken = set() for i in range(n): g.addNode(random.randint(0, 10 * n)) for i in range(random.randint(1, n - 1)): first = random.sample(g.getAllNodes(), 1)[0] second = random.sample(g.getAllNodes(), 1)[0] if first != second and (first not in taken or second not in taken): g.addDirectedEdge( random.sample(g.getAllNodes(), 1)[0], random.sample(g.getAllNodes(), 1)[0]) taken.add(first) taken.add(second) return g
def setUp(self): self.graph = DirectedGraph.DirectedGraph() self.graph.insert(1, 2) self.graph.insert(1, 3) self.graph.insert(2, 3) self.graph.insert(2, 4) self.graph.insert(3, 5) self.graph.insert(3, 6) self.graph.insert(5, 6) self.graph.insert(6, 7) self.graph.insert(7, 5) self.graph.insert(6, 8) self.graph.insert(4, 9) self.graph.insert(4, 10) self.graph.insert(8, 9) self.graph.insert(8, 11) self.graph.insert(9, 10) self.graph.insert(10, 11) self.graph.insert(11, 9)
class Lattice(object): def __init__(self, criteria): """ initialize a lattice to the equilibrium state. """ self.__graph = DirectedGraph() self.__weights = dict() #coeff self.__descriptors = dict() #{'a' : 'Gout'} self.__importanceValue = dict() self.__visited = dict() for i in range(len(criteria)-1): self.__descriptors[DESCRIPTORS[i]] = criteria[i] self.__contribute() self.__equilibrate() def __contribute(self): """ construct a directed graph with combinaison les descriptors, and initialize with all coefficients non visited. """ descriptors = sorted(self.__descriptors.keys()) end = len(descriptors) empty = '.' for x in descriptors: self.__graph.add_edge(empty, x) #layer0 & 1 iteration = 1 while iteration <= end: iteration += 1 concat = set() for i in range(len(descriptors)-1): for j in range(i+1, len(descriptors)): new_vertex = ''.join(sorted(set(descriptors[i] + descriptors[j]))) if len(new_vertex) == iteration : concat.add(new_vertex) self.__graph.add_edge(descriptors[i], new_vertex) self.__graph.add_edge(descriptors[j], new_vertex) descriptors = list(concat) for x in self.__graph.vertices(): self.__visited[x] = False def __equilibrate(self): """ status equilibrium """ for i in self.__graph.vertices(): self.__weights[i] = len(i)/len(self.__descriptors) self.__weights['.'] = 0 def set_coeff_value(self, v, value): """ modify the v coefficient's value and be touched. """ self.__weights[v] = value self.__visited[v] = True def get_coeff_value(self, v): """ return coefficient's value""" return self.__weights[v] def set_importanceValue(self, data): """ associate every criterion with its importance value. (can be modified when data change) """ for i in range(len(data)-1): self.__importanceValue[DESCRIPTORS[i]] = data[i] def permute_importanceValue(self): """ return a pair of list ordered with importance value. """ return list(x for x in sorted(list(self.__importanceValue.items()), key = lambda x: x[1])) def deduce_path(self): """ return a path deduced by the importance values""" path = ['.'] for x in reversed(list((x[0] for x in self.permute_importanceValue()))): if path[-1] == '.': path.append(x) else: path.append(''.join(sorted(path[-1]+x))) return path def has_visited(self, v): """ return whether the vertex / coefficient v has been visited. """ return self.__visited[v] def lower_neighbors_values(self, v): """ return a list of value of its lower neighbors. """ return list(map(lambda x: self.get_coeff_value(x), self.__graph.lower_neighbors(v))) def upper_neighbors_values(self, v): """ return a list of value of its upper neighbors. """ return list(map(lambda x: self.get_coeff_value(x), self.__graph.upper_neighbors(v))) def get_coefficients_non_modified(self): """ return all coefficients non modified. """ return list(filter(lambda x: not self.has_visited(x), self.__graph.vertices())) def get_coefficients(self): """ return all coefficients. """ return self.__graph.vertices() def get_coeffs_without(self, i): """ return all coefficients that dosen't contain element i. """ return sorted(list(filter(lambda x: i not in x, self.__graph.vertices()))) def get_criteria(self, i): """ return the real criteria's name in the context. """ return self.__descriptors[i] def get_criterias(self): """ return all criteria with pair of (supdo , real name in context). """ return self.__descriptors # uncomment in need of visualizing """
random.sample(g.getAllNodes(), 1)[0]) taken.add(first) taken.add(second) return g if __name__ == "__main__": # just here for printout def printvals(lst: list) -> None: for i in range(len(lst) - 1): print(lst[i].val, end=" -> ") if len(lst) > 0: print(lst[-1].val) graph = DirectedGraph.DirectedGraph() graph.addNode('A') graph.addNode('B') graph.addNode('C') graph.addNode('D') graph.addNode('E') graph.addNode('F') graph.addNode('G') graph.addNode('H') graph.nodes[0].neighbors = set([graph.nodes[1], graph.nodes[3]]) graph.nodes[2].neighbors = set( [graph.nodes[3], graph.nodes[6], graph.nodes[7]]) graph.nodes[3].neighbors = set([graph.nodes[6]]) graph.nodes[7].neighbors = set([graph.nodes[4], graph.nodes[5]])
from DirectedGraph import * g = DirectedGraph() def test1(): g.add_edge('a', 'b') g.add_edge('b', 'f') g.add_edge('c', 'd') g.add_edge('d', 'h') g.add_edge('f', 'd') g.add_edge('f', 'i') g.add_edge('g') g.add_edge('i', 'e') g.add_edge('e', 'e') print('g.out_edges') for a in {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'}: print(a) print(g.out_edges(a)) def test2(): g.add_edge('s', 'b') g.add_edge('b', 'a') g.add_edge('a', 'b') for a in {'s', 'a', 'b'}: print(a) print(g.out_edges(a))
def test_random_directed_graph(self): vs = [Vertex(str(x)) for x in range(100)] rdg = DirectedGraph(vs) rdg.add_random_arcs(p=.2) self.assertFalse(rdg.is_complete())