def addEdgeBetweenPeriods(graph, classInfo, tailName, headName, tailPeriod, headPeriod, studentRecord): # Iterating between two dictionaries simultaneously, tail node and head node # Reference: https://stackoverflow.com/questions/20736709/how-to-iterate-over-two-dictionaries-at-once-and-get-a-result-using-values-and-k for (tail_k, tail_v), (head_k, head_v) in zip(classInfo[tailName].items(), classInfo[headName].items()): # varName_k is a str of the class name (i.e Functions A) # varName_v is a list of [ [list of student ids], teacherID, teachingAssistantID) tailStr = "("+ tail_k + ") - " + tailPeriod headStr = "("+ head_k + ") - " + headPeriod # Since some of the TA's dont teach all the courses at a given period, some will not have a TA. So append None as a result if len(tail_v) == 2: tail_v.append(None) if len(head_v) == 2: head_v.append(None) # Calculating the infection risk per class as the start of the class for student in tail_v[0]: infectionRisk.calculateInfectionRisk(studentRecord, student, tail_v[0], tail_v[1], tail_v[2]) # Checking the same students of id that belong in period 1 and in period 2 between 2 classes, making note of which class the students have transitioned to (getting the INTERSECTION). # Reference: https://stackoverflow.com/questions/740287/how-to-check-if-one-of-the-following-items-is-in-a-list students_switching_class = [[_id, studentRecord[_id]["givenRisk"]] for _id in tail_v[0] if _id in head_v[0]] graph.add_edge(tailStr, headStr, students_switching_class)
def draw_graph(counter_total, counter_lives, counter_deaths, n=20): """Draw graph of survival depending on sequence. Parameters: counter_total - Counter object with total number of sequences counter_lives - Counter object with number of sequences without death date counter_deaths - Counter object with number of sequences with death date n - specifies how many of the sequences with highest death rate should be printed to output. If set to 0 then all sequences will be printed """ print 'Creating graph' node_labels = {} edge_labels = {} graph = nx.DiGraph() graph.add_node(0) node_labels[0] = 'End' i = 1 for k, v in counter_total.most_common(n) if n else counter_total.most_common(): lastI = 0 for medicine in reversed(k.split(';')): graph.add_edge(i, lastI) edge_labels[(i, lastI)] = medicine lastI = i i += 1 node_labels[lastI] = '{0}%'.format(100 * counter_deaths[k] / v) print 'Graph created' layout = nx.graphviz_layout(graph) print 'Graph layout created' nx.draw(graph, pos = layout, hold = True, node_color = 'w', node_size = 1000) nx.draw_networkx_labels(graph, layout, labels = node_labels) nx.draw_networkx_edge_labels(graph, layout, edge_labels = edge_labels) plt.show()
def __init__(self, degree, n_nodes): # initialize kr generator = kr_util() self.kr = generator.build_kr(n_nodes, degree) g_p = graph_util().generate_random_regular_bipartite(n_nodes, degree) arbitrary_p = graph_util().generate_random_regular_bipartite( n_nodes, 1) # create the C versions of the graphs self.g_c_structure = graph.create_graph_structure_test(n_nodes) self.g_c = graph.create_graph_edges_test(n_nodes) self.g_c_copy = graph.create_graph_edges_test(n_nodes) for edge in g_p.edges_iter(): graph.add_edge(self.g_c_structure, self.g_c, edge[0], edge[1]) graph.copy_edges(self.g_c, self.g_c_copy, n_nodes) self.arbitrary_c = graph.create_graph_edges_test(n_nodes) for edge in arbitrary_p.edges_iter(): graph.add_edge(self.g_c_structure, self.g_c, edge[0], edge[1]) graph.set_edge(self.g_c_structure, self.g_c_copy, self.arbitrary_c, edge[0], edge[1]) # allocate solution self.solution = kapoorrizzi.create_matching_set()
def test_graph_creation(self): generator = graph_util() for deg in xrange(2, 11, 2): for n_side in xrange(2*deg+4,33,7): g_p = generator.generate_random_regular_bipartite(n_side, deg) g_c_structure = graph.create_graph_structure_test(n_side) g_c = graph.create_graph_edges_test(n_side) # Create the graph in C # first n vertices are on left, second n are on right for edge in g_p.edges_iter(): graph.add_edge(g_c_structure, g_c, edge[0], edge[1]) # Check that graph in C matches the graph in Python for node in xrange(2 * n_side): self.assertEqual(g_p.degree(node), graph.get_degree(g_c, node)) for node in xrange(2 * n_side): if (g_p.degree(node) > 0): self.assertTrue(graph.has_neighbor(g_c, node)) graph.destroy_graph_structure_test(g_c_structure) graph.destroy_graph_edges_test(g_c) pass
def graph_from_numpy_array(X_train, num_nodes, directed=True): all_nodes = set(range(0, num_nodes + 1)) graph = nx.DiGraph() if directed else nx.Graph() graph.add_nodes_from(all_nodes) for u, v in X_train: graph.add_edge(u, v) return graph
def amr_2_graph(sentence, graph): if sentence[0] != '(' or sentence[-1] != ')': raise Exception("Error: Initial and closing character should be parenthesis.") sentence = sentence[1:-1] if re.search('([^:)(]*)([:)(].*)', sentence): root, sentence = re.search('([^:)(]*)([:)(].*)', sentence).group(1, 2) else: root = sentence sentence = "" graph.add_node(root) while sentence.find(':') >= 0: terminal = False argument, sentence = re.search('(:[^ ]+) ?(.*)', sentence).group(1, 2) child_node = None if sentence[0] == '(': subgraph, sentence = find_closing_parenthesis(sentence) child_node = amr_2_graph(subgraph, graph) else: child_node, sentence = re.search('([^ ]+) ?(:.*)?', sentence).group(1, 2) if not sentence: sentence = "" terminal = True graph.add_edge(root, child_node, argument, terminal=terminal) return root
def test(self): degree = 40 n_nodes = 15 # initialize kr generator = kr_util() kr = generator.build_kr(n_nodes, degree, print_debug=True) # generate graph and arbitrary matching g_p = graph_util().generate_random_regular_bipartite(n_nodes, degree) arbitrary_p = graph_util().generate_random_regular_bipartite(n_nodes, 1) # create the C versions of the graphs, and copies g_c_structure = graph.create_graph_structure_test(n_nodes) g_c = graph.create_graph_edges_test(n_nodes) g_c_copy = graph.create_graph_edges_test(n_nodes) for edge in g_p.edges_iter(): graph.add_edge(g_c_structure, g_c, edge[0], edge[1]) graph.copy_edges(g_c, g_c_copy, n_nodes) self.assertEqual(graph.get_max_degree(g_c, n_nodes), degree) self.assertEqual(graph.get_max_degree(g_c_copy, n_nodes), degree) arbitrary_c = graph.create_graph_edges_test(n_nodes) for edge in arbitrary_p.edges_iter(): graph.add_edge(g_c_structure, g_c, edge[0], edge[1]) graph.set_edge(g_c_structure, g_c_copy, arbitrary_c, edge[0], edge[1]) self.assertEqual(graph.get_max_degree(arbitrary_c, n_nodes), 1) # solve solution = kapoorrizzi.create_matching_set() kapoorrizzi.solve(kr, g_c_structure, g_c_copy, arbitrary_c, solution) # check solution # check that we have the correct number of matchings num_matchings = kapoorrizzi.get_num_matchings(solution) self.assertEqual(num_matchings, degree + 1) # check that each matching is a perfect matching for i in range(num_matchings): matching = kapoorrizzi.get_matching(solution, i) self.assertTrue(graph.is_perfect_matching(matching, n_nodes)) # check sum of matchings equals the original graph matchings_graph_c = graph.create_graph_edges_test(n_nodes) for i in range(num_matchings): matching = kapoorrizzi.get_matching(solution, i) graph.add_edges(matchings_graph_c, matching, n_nodes) self.assertTrue(graph.are_equal(matchings_graph_c, g_c, n_nodes)) # clean up kapoorrizzi.destroy_kr(kr) kapoorrizzi.destroy_matching_set(solution) graph.destroy_graph_structure_test(g_c_structure) graph.destroy_graph_edges_test(g_c) graph.destroy_graph_edges_test(g_c_copy) graph.destroy_graph_edges_test(arbitrary_c) pass
def toDOT(self, label=''): """ Convert a Structure object to a graph image via DOT. This is useful for visualizing the functional groups that make up the databases. The output is a string containing a graph in DOT format, which can be passed to graphviz to produce an image; neato is recommended. Atoms are visualized as vertices in the outputted graph. Vertices are labeled with the atom type(s) of each corresponding atom. Labeled atoms ('\*', '\*1', etc.) are color-coded, with a unique color for each label. Bonds are indicated with edges; multiple bonds are represented by multiple edges between the same pair of vertices. The edge line style is used to denote further semantic information: dashed lines indicate optional higher-order bonds, while dotted lines indicate benzene bonds. """ import pydot graph = pydot.Dot(size='5,4', rankdir='LR', graph_type='graph', simplify=True, fontsize='8', overlap='true', dpi='85',center="True") # List of atoms (vertices) for i, atom in enumerate(self.atoms()): # Generate vertex label from atom type labels label = ','.join([atomType.label for atomType in atom._atomType]) # Labeled atoms are color coded color = 'black' if atom.label != '': colors = {'*': 'red', '*1': 'red', '*2': 'green', '*3': 'blue', '*4': 'yellow', '*5': 'purple', '*6': 'orange', '*7': 'magenta', '*8': 'cyan'} color = colors[atom.label] # Create and add vertex to graph node = pydot.Node(str(i+1), label=label, color=color, fontcolor=color) graph.add_node(node) # List of bonds (edges) for i, bond in enumerate(self.bonds()): index1 = self.atoms().index(bond.atoms[0]) index2 = self.atoms().index(bond.atoms[1]) single = False; double = False; triple = False; benzene = False for type in bond._bondType: if type.order == 1: single = True if type.order == 2: double = True if type.order == 3: triple = True if type.order == 1.5: benzene = True label = [] if single: label.append('S') if double: label.append('D') if triple: label.append('T') if benzene: label.append('B') label = ','.join(label) # Create and add edge to graph edge = pydot.Edge(str(index1+1), str(index2+1), label=label, len='2') graph.add_edge(edge) return graph
def load_edges(graph): with open(COAUTHS_FILE,'r') as f: # load edges from coauthors file line = f.readline() while line != "": line = line[1:].split() # remove '#' at the start of each line and split to fields w = int(line[2]) # 3rd field is weight, convert to int graph.add_edge(int(line[0]), int(line[1]), w) # edge from auth1 to auth2 line = f.readline() # read next line
def _update_edge_weight(graph, node1, node2,labels=[],inc_weight=True): """Update or create weighed edge between two nodes""" if graph.has_edge(node1, node2): graph[node1][node2]['label'] += labels if inc_weight: graph[node1][node2]['weight'] += 1.0 else: graph.add_edge(node1, node2, weight=1.0,label=labels)
def _update_edge_weight(graph, node1, node2, labels=[], inc_weight=True): """Update or create weighed edge between two nodes""" if graph.has_edge(node1, node2): graph[node1][node2]['label'] += labels if inc_weight: graph[node1][node2]['weight'] += 1.0 else: graph.add_edge(node1, node2, weight=1.0, label=labels)
def load_edges(graph): with open(COAUTHS_FILE, 'r') as f: # load edges from coauthors file line = f.readline() while line != "": line = line[1:].split( ) # remove '#' at the start of each line and split to fields w = int(line[2]) # 3rd field is weight, convert to int graph.add_edge(int(line[0]), int(line[1]), w) # edge from auth1 to auth2 line = f.readline() # read next line
def sat(): graph_g = graph.Graph() my_dic = [] #reading in file. file = open(sys.argv[1], "r") content = file.readlines() clause_count = int((content[0].count('(') + content[0].count(')')) / 2) content[0] = content[0].strip('\n') #turning into array. clauses = content[0].split('&') for i in range(0, len(clauses)): clauses[i] = clauses[i].replace('|', '') clauses[i] = clauses[i].replace('(', '') clauses[i] = clauses[i].replace(')', '') clauses[i] = clauses[i].split() for j in clauses[i]: my_dic.append(j) #turning into unique numbers for dictionary. for i in range(len(clauses)): for j in range(3): graph.add_vertex(graph_g, str(i*3+j)) #traversing... for i in range(len(clauses)): for j in range(len(clauses[i])): for k in range(len(clauses)): if(i != k): for l in range(len(clauses[k])): negation = "" if(len(clauses[k][l]) == 2): negation = clauses[k][l][1:] else: negation = "~" + clauses[k][l] if(clauses[i][j] != negation): graph.add_edge(graph_g, str(i*3+j), str(k*3+l)) #run isomorph on it. subgraph = is_iso(graph_g) #printing process. result = [] if(subgraph is None): print("No satisfying assignments.") return for i in subgraph: string = my_dic[int(i)] result.append(string) result.sort(key=lambda x: x[-1]) print("Satisfying assignment:") print(", ".join(result))
def _create_dep_network(deps, filter_tokens=False): graph = nx.DiGraph() for dep in deps: for tup in deps[dep]: g = tup[0][0] d = tup[1][0] if filter_tokens: g = preprocess.preprocess_token(g) d = preprocess.preprocess_token(d) if g is not None and d is not None: graph.add_edge(g, d, weight=1.0, label=dep) # add label return graph
def _csr_gen_triples(A): """Converts a SciPy sparse matrix in **Compressed Sparse Row** format to an iterable of weighted edge triples. """ graph = nx.Graph() nrows = A.shape[0] data, indices, indptr = A.data, A.indices, A.indptr for i in range(nrows): for j in range(indptr[i], indptr[i+1]): graph.add_edge(i,indices[j], weight = data[j]) return graph.edges(data = 'weight')
def _csr_gen_triples(A): """Converts a SciPy sparse matrix in **Compressed Sparse Row** format to an iterable of weighted edge triples. """ graph = nx.Graph() nrows = A.shape[0] data, indices, indptr = A.data, A.indices, A.indptr for i in range(nrows): for j in range(indptr[i], indptr[i + 1]): graph.add_edge(i, indices[j], weight=data[j]) return graph.edges(data="weight")
def k_clique(graph_g, k): graph_h = graph.Graph(k) # print(graph_h.matrix) for i in range(k): for j in range(k): if i != j: graph.add_edge(graph_h, i, j) # print(graph_h.matrix) subgraph = si.isomorphic_subgraph(graph_g, graph_h) # print(subgraph) return subgraph
def add_rule(graph, concept1, relation, concept2, context="", author="", weight=0.5, length=1.0, label=""): """ Creates an edge between node1 and node2 of the given relation type and context. Multiple definitions of the same rule (e.g. by different users) increases the edge's weight. Multiple definitions differing in relation or context are currently ignored (e.g. a cookie can't be food and be part of food at the same time). """ if relation == "is-opposite-of": # is-opposite-of edges are not interesting when looking for a shortest path, # because they represent a reversal in logic. weight = 0.25 if author == "": # Discourage rules from anonymous authors. weight -= 0.25 if is_robot(author): # Robots score less than people. weight -= 0.25 e = graph.edge(concept1, concept2) if e and e.relation == relation:# and e.context == context: v = VOTE if is_robot(author): v *= 0.5 e.weight += v else: e = graph.add_edge(concept1, concept2, weight, length, label) if e: e.relation = relation e.context = context e.author = author return e
def test_keeps_edge_set(self): generator = graph_util() for deg in xrange(2, 11, 2): for n_side in xrange(2 * deg + 4, 33, 7): g_p = generator.generate_random_regular_bipartite(n_side, deg) # Create the graph in C g_c_structure = graph.create_graph_structure_test(n_side) g_c = graph.create_graph_edges_test(n_side) g_c_copy = graph.create_graph_edges_test(n_side) for edge in g_p.edges_iter(): graph.add_edge(g_c_structure, g_c, edge[0], edge[1]) graph.copy_edges(g_c, g_c_copy, n_side) self.assertEqual(graph.get_max_degree(g_c, n_side), deg) self.assertEqual(graph.get_max_degree(g_c_copy, n_side), deg) # Create the output graphs g1_c = graph.create_graph_edges_test(n_side) g2_c = graph.create_graph_edges_test(n_side) eulersplit.split(g_c_structure, g_c_copy, g1_c, g2_c) # Check that the input graph is now empty self.assertEqual(graph.get_max_degree(g_c_copy, n_side), 0) for node in xrange(2 * n_side): self.assertEqual(graph.get_degree(g_c_copy, node), 0) # Check that graphs have the correct degree self.assertEqual(graph.get_max_degree(g1_c, n_side), deg / 2) self.assertEqual(graph.get_max_degree(g2_c, n_side), deg / 2) # Check that vertices have the correct degree for node in xrange(2 * n_side): self.assertEqual(graph.get_degree(g1_c, node), deg / 2) self.assertEqual(graph.get_degree(g2_c, node), deg / 2) # Check that the combination of the two graphs equals the original graph graph.add_edges(g1_c, g2_c, n_side) self.assertTrue(graph.are_equal(g_c, g1_c, n_side)) graph.destroy_graph_structure_test(g_c_structure) graph.destroy_graph_edges_test(g_c) graph.destroy_graph_edges_test(g_c_copy) graph.destroy_graph_edges_test(g1_c) graph.destroy_graph_edges_test(g2_c) pass
def test_keeps_edge_set(self): generator = graph_util() for deg in xrange(2, 11, 2): for n_side in xrange(2*deg+4,33,7): g_p = generator.generate_random_regular_bipartite(n_side, deg) # Create the graph in C g_c_structure = graph.create_graph_structure_test(n_side); g_c = graph.create_graph_edges_test(n_side); g_c_copy = graph.create_graph_edges_test(n_side) for edge in g_p.edges_iter(): graph.add_edge(g_c_structure, g_c, edge[0], edge[1]) graph.copy_edges(g_c, g_c_copy, n_side) self.assertEqual(graph.get_max_degree(g_c, n_side), deg) self.assertEqual(graph.get_max_degree(g_c_copy, n_side), deg) # Create the output graphs g1_c = graph.create_graph_edges_test(n_side) g2_c = graph.create_graph_edges_test(n_side) eulersplit.split(g_c_structure, g_c_copy, g1_c, g2_c) # Check that the input graph is now empty self.assertEqual(graph.get_max_degree(g_c_copy, n_side), 0) for node in xrange(2 * n_side): self.assertEqual(graph.get_degree(g_c_copy, node), 0) # Check that graphs have the correct degree self.assertEqual(graph.get_max_degree(g1_c, n_side), deg / 2) self.assertEqual(graph.get_max_degree(g2_c, n_side), deg / 2) # Check that vertices have the correct degree for node in xrange(2 * n_side): self.assertEqual(graph.get_degree(g1_c, node), deg / 2) self.assertEqual(graph.get_degree(g2_c, node), deg / 2) # Check that the combination of the two graphs equals the original graph graph.add_edges(g1_c, g2_c, n_side) self.assertTrue(graph.are_equal(g_c, g1_c, n_side)) graph.destroy_graph_structure_test(g_c_structure) graph.destroy_graph_edges_test(g_c) graph.destroy_graph_edges_test(g_c_copy) graph.destroy_graph_edges_test(g1_c) graph.destroy_graph_edges_test(g2_c) pass
def on_file_new(self, event): """ Event handler for the "New" action """ random_graph2 = NX.generators.random_graphs.watts_strogatz_graph(800, 70, 0.8) print NX.average_clustering(random_graph2) #random_graph = NX.generators.random_graphs.gnm_random_graph(800, 30 * 1000) random_graph = self.my_small_world(800, 70, 0.8) graph = NX.xdigraph.XDiGraph() for edge in random_graph.edges(): first, second, w = edge if random.random() < 0.5: second, first, w = edge graph.add_edge("Gene_" + str(first), "Gene_" + str(second), random.choice([-1, 1]))
def add_edges(graph, list_of_edges, station_mapping): edge_mapping={} for edge in list_of_edges: source_string=edge.source source_vertex=station_mapping[source_string] target_string=edge.target target_vertex=station_mapping[target_string] line_string=edge.line tempedge=graph.add_edge(source_vertex, target_vertex) edge_mapping[graph.edge_index[tempedge]]=line_string return edge_mapping
def __init__(self, degree, n_nodes): # initialize kr generator = kr_util() self.kr = generator.build_kr(n_nodes, degree) g_p = graph_util().generate_random_regular_bipartite(n_nodes, degree) arbitrary_p = graph_util().generate_random_regular_bipartite(n_nodes, 1) # create the C versions of the graphs self.g_c_structure = graph.create_graph_structure_test(n_nodes) self.g_c = graph.create_graph_edges_test(n_nodes) self.g_c_copy = graph.create_graph_edges_test(n_nodes) for edge in g_p.edges_iter(): graph.add_edge(self.g_c_structure, self.g_c, edge[0], edge[1]) graph.copy_edges(self.g_c, self.g_c_copy, n_nodes) self.arbitrary_c = graph.create_graph_edges_test(n_nodes) for edge in arbitrary_p.edges_iter(): graph.add_edge(self.g_c_structure, self.g_c, edge[0], edge[1]) graph.set_edge(self.g_c_structure, self.g_c_copy, self.arbitrary_c, edge[0], edge[1]) # allocate solution self.solution = kapoorrizzi.create_matching_set()
def build_graph(): max_weight = -100000000 top_words, dataset, set_of_words, freq_dict = create_word_dict() # Generate word dictinary word_dict = pd.Series(top_words.index.values, index=top_words.values).to_dict() # Create graph graph = networkx.MultiGraph() graph.add_nodes_from(top_words.index.values) for question1, question2, is_duplicate in \ np.stack((dataset["question1"], dataset["question2"], dataset["is_duplicate"]), axis=-1): for word_q1 in question1.split(): for word_q2 in question2.split(): edge_weight = (1 if is_duplicate else -1) / 6210.0 node_a = word_dict[word_q1] node_b = word_dict[word_q2] # Make always node_a <= node_b if node_a > node_b: temp = node_a node_a = node_b node_b = temp if graph.has_edge(node_a, node_b): graph[node_a][node_b][0]['weight'] = graph[node_a][node_b][0]['weight'] \ + edge_weight max_weight = max(max_weight, abs(graph[node_a][node_b][0]['weight'])) else: graph.add_edge(node_a, node_b, weight=edge_weight) print "Maximum edge weight from graph build:", max_weight return graph, set_of_words, word_dict, dataset, freq_dict
def add_API_nodes(name): """ Queries the API for a list of related nodes from the current_node and their relationships to be added to the database. The process is multithreaded.""" add_node(name) start_time = time.time() all_links = get_top_links(name) if all_links is None: return None # avoids stupid quotations breaking queries all_links = [ link for link in all_links if not contains_quotes(link["title"]) ] threads = [] for link in all_links: #print link q = Queue() print link try: link["name"] = link.pop("title") link.pop("ns") except: pass if not node_exists(link): print 'node does not exist ' add = lambda x: add_node(x) q.put(add) # otherwise always add relationship edge = lambda x, y, z: add_edge(x, y, z) q.put(edge) t = threading.Thread(target=process, args=(q, name, link)) threads.append(t) t.start() [thread.join() for thread in threads] print "--- adding nodes took %s seconds ---" % (time.time() - start_time) return True
def add_rule(graph, concept1, relation, concept2, context="", author="", weight=0.5, length=1.0, label=""): """ Creates an edge between node1 and node2 of the given relation type and context. Multiple definitions of the same rule (e.g. by different users) increases the edge's weight. Multiple definitions differing in relation or context are currently ignored (e.g. a cookie can't be food and be part of food at the same time). """ if relation == "is-opposite-of": # is-opposite-of edges are not interesting when looking for a shortest path, # because they represent a reversal in logic. weight = 0.25 if author == "": # Discourage rules from anonymous authors. weight -= 0.25 if is_robot(author): # Robots score less than people. weight -= 0.25 e = graph.edge(concept1, concept2) if e and e.relation == relation: # and e.context == context: v = VOTE if is_robot(author): v *= 0.5 e.weight += v else: e = graph.add_edge(concept1, concept2, weight, length, label) if e: e.relation = relation e.context = context e.author = author return e
def test_depth_first(): graph = Graph() A = graph.add_node('A') B = graph.add_node('B') C = graph.add_node('C') D = graph.add_node('D') E = graph.add_node('E') F = graph.add_node('F') G = graph.add_node('G') H = graph.add_node('H') graph.add_edge(A,B) graph.add_edge(A,D) graph.add_edge(D,E) graph.add_edge(D,H) graph.add_edge(D,F) graph.add_edge(B,C) graph.add_edge(C,G) output = graph.depth_first(A) assert output[0] == A assert output[1] == B assert output[2] == C assert output[3] == G assert output[4] == D assert output[5] == E assert output[6] == H assert output[7] == F
# print(my_list) sat_graph = graph.Graph(len(my_list)) for i in range(len(my_list)): for j in range(len(my_list)): # print(i, j) #WHERE THE CLAUSE NUMBER IS SAME if my_list[i][1] == my_list[j][1]: pass # WHERE THE 1st LITERAL CONTAINS ~ elif len(my_list[i][0]) == 2: if len(my_list[j][0]) == 2: graph.add_edge(sat_graph, i, j) else: if ord(my_list[i][0][1]) == ord(my_list[j][0]): pass else: graph.add_edge(sat_graph, i, j) # WHERE THE 2nd LITERAL CONTAINS ~ elif len(my_list[j][0]) == 2: if ord(my_list[i][0]) == ord(my_list[j][0][1]): # print(i, j) pass else: graph.add_edge(sat_graph, i, j) # EVERYTHING ELSE
def test_breadth_first(): graph = Graph() a = graph.add_node('a') b = graph.add_node('b') c = graph.add_node('c') d = graph.add_node('d') e = graph.add_node('e') f = graph.add_node('f') g = graph.add_node('g') h = graph.add_node('h') i = graph.add_node('i') k = graph.add_node('k') graph.add_edge(a, b) graph.add_edge(a, c) graph.add_edge(a,e) graph.add_edge(b, d) graph.add_edge(c, f) graph.add_edge(c, b) graph.add_edge(e,g) graph.add_edge(f,h) graph.add_edge(g,h) graph.add_edge(f,i) graph.add_edge(h,k) graph.add_edge(i,k) assert len(graph.breadth_first(a)) == 10 breadth = graph.breadth_first(a) assert breadth[0].value == 'a' assert breadth[1].value == 'b' assert breadth[2].value == 'c' assert breadth[3].value == 'e' assert breadth[4].value == 'd' assert breadth[5].value == 'f' assert breadth[6].value == 'g' assert breadth[7].value == 'h' assert breadth[8].value == 'i' assert breadth[9].value == 'k'
import graph from collections import namedtuple import re, sys infile = sys.argv[1] infile = open(infile, "r") graph = graph.Graph() for i, line in enumerate(infile): if i == 1: s = line.split(', ') if i > 2: nodes = graph.get_nodes() words = line.split() if words[0] not in graph.get_nodes(): graph.add_node(words[0]) elif words[1] not in graph.get_nodes(): graph.add_node(words[1]) graph.add_edge(int(words[0]), int(words[1]), int(words[2])) print(graph.get_nodes()) graph.dijkstra(1, 10)
def test_graph(): # check for successful input graph = Graph() a = graph.add_node('a') assert a.value == 'a' b = graph.add_node('b') c = graph.add_node('c') d = graph.add_node('d') e = graph.add_node('e') f = graph.add_node('f') # check the get_nodes function assert graph.get_nodes()[0].value == 'a' assert graph.get_nodes()[1].value == 'b' assert graph.get_nodes()[5].value == 'f' # check if the add_edges and get_neighbors are working properly graph.add_edge(a, c) graph.add_edge(a, d) graph.add_edge(b, c) graph.add_edge(b, f) graph.add_edge(c, a) graph.add_edge(c, b) graph.add_edge(c, e) graph.add_edge(d, a) graph.add_edge(d, e) graph.add_edge(e, c) graph.add_edge(e, d) graph.add_edge(e, f) graph.add_edge(f, b) graph.add_edge(f, e) assert graph.get_neighbors(a)[0].node.value == 'c' assert graph.get_neighbors(a)[1].node.value == 'd' # testing the size method assert graph.size()==6 # check for empty graph graph2 = Graph() assert graph2.get_nodes() == None
def symmetric_gamma_node(graph, node, formulas_in): value_list = graph.node[node] size = len(value_list) index = 0 for i in range(index,size): value = value_list[i] if value[0] == 'box': formula = value[1] if value not in formulas_in[node]: formulas_in[node].append(value) try: graph.successors(node) except: break next_node = graph.successors(node) for single_node in next_node: if single_node < node: #take the initial size of list to check whether it expanded initial_size = len(graph.node[single_node]) if formula not in graph.node[single_node]: graph.node[single_node].append(formula) alpha_node_solve(graph,single_node) beta_node_solve(graph,single_node, formulas_in) final_size = len(graph.node[single_node]) #take diff to scan for these new entries diff_size = final_size-initial_size if diff_size > 0: value_list_single_node_initial= graph.node[single_node] value_list_single_node = value_list_single_node_initial[-diff_size:] for value in value_list_single_node: if isinstance(value,tuple) and value[0] == 'box': part = value[1] if part not in graph.node[node]: graph.node[node].append(part) elif isinstance(value,tuple) and value[0] == 'not' and value[1][0] == 'diamond': part = ('not',value[1][1]) if part not in graph.node[node]: graph.node[node].append(part) elif isinstance(value, tuple) and value[0] == 'diamond': part = value[1] new_node= graph.number_of_nodes()+1 #adding new world graph.add_edge(single_node,(new_node)) #adding symmetric edge graph.add_edge((new_node),single_node) formulas_in[new_node] = [] graph.node[single_node] = value_list_single_node_initial graph.node[new_node] = [part] #expand new delta formulae previous = graph.predecessors(new_node) for num in previous: set = graph.node[num]; for j in range(0,len(set)): if set[j][0] == 'not' and set[j][1][0] == 'diamond': formula = ('not',set[j][1][1]) if formula not in graph.node[new_node]: graph.node[new_node].append(formula) alpha_node_solve(graph,new_node) beta_node_solve(graph,new_node, formulas_in) elif set[j][0] == 'box': if set[j][1] not in graph.node[new_node]: graph.node[new_node].append(set[j][1]) alpha_node_solve(graph,new_node) beta_node_solve(graph,new_node, formulas_in) elif isinstance(value,tuple) and value[0] == 'not' and value[1][0] == 'box': part = ('not', value[1][1]) new_node= graph.number_of_nodes()+1 #adding new world graph.add_edge(single_node,(new_node)) #adding symmetric edge graph.add_edge((new_node),single_node) formulas_in[new_node] = [] graph.node[single_node] = value_list_single_node_initial graph.node[new_node] = [part] previous = graph.predecessors(new_node) for num in previous: set = graph.node[num]; for j in range(0,len(set)): if set[j][0] == 'not' and set[j][1][0] == 'diamond': formula = ('not',set[j][1][1]) if formula not in graph.node[new_node]: graph.node[new_node].append(formula) alpha_node_solve(graph,new_node) beta_node_solve(graph,new_node, formulas_in) elif set[j][0] == 'box': if set[j][1] not in graph.node[new_node]: graph.node[new_node].append(set[j][1]) alpha_node_solve(graph,new_node) beta_node_solve(graph,new_node, formulas_in) alpha_node_solve(graph, node) beta_node_solve(graph, node, formulas_in) delta_node_solve(graph, node, formulas_in) elif value[0] == 'not' and value[1][0] == 'diamond': formula = ('not', value[1][1]) if value not in formulas_in[node]: formulas_in[node].append(value) try: graph.successors(node) except: break next_node = graph.successors(node) for single_node in next_node: if single_node < node: #take the initial size of list to check whether it expanded initial_size = len(graph.node[single_node]) if formula not in graph.node[single_node]: graph.node[single_node].append(formula) alpha_node_solve(graph, single_node) beta_node_solve(graph, single_node, formulas_in) final_size = len(graph.node[single_node]) #take diff to scan for these new entries diff_size = final_size-initial_size if diff_size > 0: value_list_single_node_initial= graph.node[single_node] value_list_single_node = value_list_single_node_initial[-diff_size:] for value in value_list_single_node: if isinstance(value,tuple) and value[0] == 'box': part = value[1] if part not in graph.node[node]: graph.node[node].append(part) elif isinstance(value,tuple) and value[0] == 'not' and value[1][0] == 'diamond': part = ('not',value[1][1]) if part not in graph.node[node]: graph.node[node].append(part) elif isinstance(value, tuple) and value[0] == 'diamond': part = value[1] new_node= graph.number_of_nodes()+1 #adding new world graph.add_edge(single_node,(new_node)) #adding symmetric edge graph.add_edge((new_node),single_node) formulas_in[new_node] = [] graph.node[single_node] = value_list_single_node_initial graph.node[new_node] = [part] previous = graph.predecessors(new_node) for num in previous: set = graph.node[num]; for j in range(0,len(set)): if set[j][0] == 'not' and set[j][1][0] == 'diamond': formula = ('not',set[j][1][1]) if formula not in graph.node[new_node]: graph.node[new_node].append(formula) alpha_node_solve(graph,new_node) beta_node_solve(graph,new_node, formulas_in) elif set[j][0] == 'box': if set[j][0] not in graph.node[new_node]: graph.node[new_node].append(set[j][1]) alpha_node_solve(graph,new_node) beta_node_solve(graph,new_node, formulas_in) elif isinstance(value,tuple) and value[0] == 'not' and value[1][0] == 'box': part = ('not', value[1][1]) new_node= graph.number_of_nodes()+1 #adding new world graph.add_edge(single_node,(new_node)) #adding symmetric edge graph.add_edge((new_node),single_node) formulas_in[new_node] = [] graph.node[single_node] = value_list_single_node_initial graph.node[new_node] = [part] previous = graph.predecessors(new_node) for num in previous: set = graph.node[num]; for j in range(0,len(set)): if set[j][0] == 'not' and set[j][1][0] == 'diamond': formula = ('not',set[j][1][1]) if formula not in graph.node[new_node]: graph.node[new_node].append(formula) alpha_node_solve(graph,new_node) beta_node_solve(graph,new_node, formulas_in) elif set[j][0] == 'box': if set[j][0] not in graph.node[new_node]: graph.node[new_node].append(set[j][1]) alpha_node_solve(graph,new_node) beta_node_solve(graph,new_node, formulas_in) alpha_node_solve(graph, node) beta_node_solve(graph, node, formulas_in) delta_node_solve(graph, node, formulas_in)
def delta_node_solve(graph, node, formulas_in): delta_list = graph.node[node] for i in range(len(delta_list)-1,-1,-1): part1 = delta_list[i][0] if part1 == 'diamond': sub = delta_list[i] if sub not in formulas_in[node]: formulas_in[node].append(sub) part2 = delta_list[i][1] new_node= graph.number_of_nodes()+1 graph.add_edge(node,(new_node)) #adding new world and relation Rxx' graph.add_edge((new_node), node) #add symmetric edge graph.node[node] = delta_list graph.node[new_node] = [part2] formulas_in[new_node] = [] alpha_node_solve(graph, node) beta_node_solve(graph, node, formulas_in) previous = graph.predecessors(new_node) for num in previous: set = graph.node[num]; for j in range(0,len(set)): if set[j][0] == 'not' and set[j][1][0] == 'diamond': formula = ('not',set[j][1][1]) if formula not in graph.node[new_node]: graph.node[new_node].append(formula) alpha_node_solve(graph, new_node) beta_node_solve(graph, new_node, formulas_in) elif set[j][0] == 'box': if set[j][1] not in graph.node[new_node]: graph.node[new_node].append(set[j][1]) alpha_node_solve(graph, new_node) beta_node_solve(graph, new_node, formulas_in) elif part1 == 'not' and delta_list[i][1][0] == 'box': sub = delta_list[i] if sub not in formulas_in[node]: formulas_in[node].append(sub) part2 = ('not', delta_list[i][1][1]) new_node= graph.number_of_nodes()+1 graph.add_edge(node,(new_node)) #adding new world and relation Rxx' graph.add_edge((new_node), node) #add symmetric edge graph.node[node] = delta_list graph.node[new_node] = [part2] formulas_in[new_node] = [] alpha_node_solve(graph, node) beta_node_solve(graph, node, formulas_in) previous = graph.predecessors(new_node) for num in previous: set = graph.node[num]; for j in range(0,len(set)): if set[j][0] == 'not' and set[j][1][0] == 'diamond': formula = ('not',set[j][1][1]) if formula not in graph.node[new_node]: graph.node[new_node].append(formula) alpha_node_solve(graph, new_node) beta_node_solve(graph, new_node, formulas_in) elif set[j][0] == 'box': if set[j][1] not in graph.node[new_node]: graph.node[new_node].append(set[j][1]) alpha_node_solve(graph, new_node) beta_node_solve(graph, new_node, formulas_in)
#For each value in the current row #add it with each reachable value in the next row #increment row max_path = 0 row = 0 while row < len(triangle): for value in row print max_path # Using data structures import graph triangle_graph = graph.Graph() for level_index, level in enumerate(triangle): for sibling_index, sibling in level: sibling_coordinate = (sibling_index, level_index) if level != 0: if sibling_index == 0: right_parent_coordinate = (sibling_index, level_index - 1) graph.add_vertex(sibling_coordinate, right_parent_coordinate) elif sibling_index == (len(level) - 1): left_parent_coordinate = (sibling_index - 1, level_index - 1) graph.add_vertex(sibling_coordinate, left_parent_coordinate) else: graph.add_vertex(sibling_coordinate, left_parent_coordinate) graph.add_edge(sibling_coordinate, right_parent_coordinate) else: graph.add_vertex(sibling_coordinate)
def generate_cycle(n): graph = generate_1xn(n) if n > 1: graph.add_edge(1, n, 1) graph.add_edge(n, 1, 1) return graph
for map_dict in map: # Selecionamos las vías list_nodes = [] if map_dict['type'] == 'way': if 'highway' in map_dict['data']['tag'] and map_dict['data']['tag']['highway'] in ['trunk', 'residential', 'pedestrian']: way_dict = osmapi.OsmApi().WayGet(map_dict['data']['id']) list_nodes.append(way_dict['nd']) for i, node in enumerate(list_nodes): if not graph.node_exist(node): if i == 0: node_aux = osmapi.OsmApi().NodeGet(node) node_dic = {'lat' : node_aux['lat'], 'lon' : node_aux['lon'], 'id' : node_aux['id'], 'edges' : []} graph.add_node(node_dic) else: node_aux = osmapi.OsmApi().NodeGet(node) node_dic = {'lat' : node_aux['lat'], 'lon' : node_aux['lon'], 'id' : node_aux['id'], 'edges': []} graph.add_node(node_dic) graph.add_edge(list_nodes[i], list_nodes[i-1], 0) graph.add_edge(list_nodes[i-1], list_nodes[i], 0) else: if i != 0: graph.add_edge(list_nodes[i], list_nodes[i-1], 0) graph.add_edge(list_nodes[i-1], list_nodes[i], 0) # Impresión de las aristas de los nodos. for i, node in enumerate(list_nodes): print("[nodo]",node,"->", graph.nodes[node]['edges'])
def array_edgelist_to_graph(X, directed=False): graph = nx.DiGraph() if directed else nx.Graph() for u, v in X: graph.add_edge(u, v) return graph
"Загреб": ["Скопје", "Белград", "Сараево", "Подгорица"], "Сараево": ["Загреб"], "Подгорица": ["Загреб", "Белград"], "Софија": [] } graph = graph.Graph(cities) print(graph) print() print('Ја додаваме Љубљана') graph.add_vertex("Љубљана") print(graph) print() print('Додаваме лет Загреб -> Љубљана') graph.add_edge(('Загреб', 'Љубљана')) print(graph) print() print('Го бришеме Загреб') graph.remove_vertex('Загреб') print(graph) print() print('Го бришеме летот Белград - Подгорица') graph.remove_edge(('Белград', 'Подгорица'), remove_reversed=False) print(graph) print()
if not graph.node_exist(node): if i == 0: node_aux = osmapi.OsmApi().NodeGet(node) node_dic = { 'lat': node_aux['lat'], 'lon': node_aux['lon'], 'id': node_aux['id'], 'edges': [] } graph.add_node(node_dic) else: node_aux = osmapi.OsmApi().NodeGet(node) node_dic = { 'lat': node_aux['lat'], 'lon': node_aux['lon'], 'id': node_aux['id'], 'edges': [] } graph.add_node(node_dic) graph.add_edge(list_nodes[i], list_nodes[i - 1], 0) graph.add_edge(list_nodes[i - 1], list_nodes[i], 0) else: if i != 0: graph.add_edge(list_nodes[i], list_nodes[i - 1], 0) graph.add_edge(list_nodes[i - 1], list_nodes[i], 0) # Impresión de las aristas de los nodos. for i, node in enumerate(list_nodes): print("[nodo]", node, "->", graph.nodes[node]['edges'])
def test(self): degree = 40 n_nodes = 15 # initialize kr generator = kr_util() kr = generator.build_kr(n_nodes, degree, print_debug=True) # generate graph and arbitrary matching g_p = graph_util().generate_random_regular_bipartite(n_nodes, degree) arbitrary_p = graph_util().generate_random_regular_bipartite( n_nodes, 1) # create the C versions of the graphs, and copies g_c_structure = graph.create_graph_structure_test(n_nodes) g_c = graph.create_graph_edges_test(n_nodes) g_c_copy = graph.create_graph_edges_test(n_nodes) for edge in g_p.edges_iter(): graph.add_edge(g_c_structure, g_c, edge[0], edge[1]) graph.copy_edges(g_c, g_c_copy, n_nodes) self.assertEqual(graph.get_max_degree(g_c, n_nodes), degree) self.assertEqual(graph.get_max_degree(g_c_copy, n_nodes), degree) arbitrary_c = graph.create_graph_edges_test(n_nodes) for edge in arbitrary_p.edges_iter(): graph.add_edge(g_c_structure, g_c, edge[0], edge[1]) graph.set_edge(g_c_structure, g_c_copy, arbitrary_c, edge[0], edge[1]) self.assertEqual(graph.get_max_degree(arbitrary_c, n_nodes), 1) # solve solution = kapoorrizzi.create_matching_set() kapoorrizzi.solve(kr, g_c_structure, g_c_copy, arbitrary_c, solution) # check solution # check that we have the correct number of matchings num_matchings = kapoorrizzi.get_num_matchings(solution) self.assertEqual(num_matchings, degree + 1) # check that each matching is a perfect matching for i in range(num_matchings): matching = kapoorrizzi.get_matching(solution, i) self.assertTrue(graph.is_perfect_matching(matching, n_nodes)) # check sum of matchings equals the original graph matchings_graph_c = graph.create_graph_edges_test(n_nodes) for i in range(num_matchings): matching = kapoorrizzi.get_matching(solution, i) graph.add_edges(matchings_graph_c, matching, n_nodes) self.assertTrue(graph.are_equal(matchings_graph_c, g_c, n_nodes)) # clean up kapoorrizzi.destroy_kr(kr) kapoorrizzi.destroy_matching_set(solution) graph.destroy_graph_structure_test(g_c_structure) graph.destroy_graph_edges_test(g_c) graph.destroy_graph_edges_test(g_c_copy) graph.destroy_graph_edges_test(arbitrary_c) pass