def txn_view_serial(conflict_status, graph_status, *txns): dataset = set([txns[i][j][2] for i in range(len(txns)) for j in range(len(txns[0])) if txns[i][j] != "*"]) edges = list() for d in dataset: update_list = list() first_reads = list() last_update = "" for i in range(len(txns[0])): for j in range(len(txns)): if txns[j][i] == "*": continue if txns[j][i][2] == d: if txns[j][i][0] == "W": update_list.append(f"T{j + 1}") last_update = f"T{j + 1}" if txns[j][i][0] == "R": if not last_update: first_reads.append(f"T{j + 1}") else: edges.append((last_update, f"T{j + 1}")) update_list_read = list(set(update_list) - set(first_reads)) update_list = list(set(update_list)) if first_reads: edges.extend([(x, y) for x in first_reads for y in update_list_read if x != y]) if last_update: edges.extend([(x, last_update) for x in update_list if x != last_update]) edges = [(e[0], e[1]) for e in edges if e[0] != e[1]] edges = list(set(edges)) graph = nx.DiGraph() graph.add_nodes_from([f"T{x + 1}" for x in range(len(txns))]) graph.add_edges_from(edges) if conflict_status and not blind_write(dataset, *txns): graph.clear() print("There is no Blind Write!") graph = graph_status try: nx.planar_layout(graph) except nx.exception.NetworkXException: pass try: nx.find_cycle(graph) plt.title("Not View Serializable", fontsize=10, color="red") print("This schedule is not View Serializable.") print() nx.draw(graph, with_labels=True, node_size=1500, font_size=20, font_color="yellow", font_weight="bold", connectionstyle='arc3, rad = 0.1') except nx.exception.NetworkXNoCycle: plt.title(f"View Serializable: <{','.join(nx.topological_sort(graph))}>", fontsize=10, color="red") print(f"This schedule is View Serializable and View Equivalent to <{','.join(nx.topological_sort(graph))}>") print() nx.draw(graph, with_labels=True, node_size=1500, font_size=20, font_color="yellow", font_weight="bold", connectionstyle='arc3, rad = 0.1') plt.show()
def txn_conflict_serial(*txns): edges = list() for i in range(len(txns)): flag = 0 for j in range(len(txns[0])): if flag: break if txns[i][j] != "*": if txns[i][j][0] == "W": for m in range(len(txns)): if m == i: continue for n in range(j + 1, len(txns[0])): if txns[m][n] == "*": continue if txns[i][j][2] == txns[m][n][2]: if (f"T{i + 1}", f"T{m + 1}") not in edges: edges.append((f"T{i + 1}", f"T{m + 1}")) flag = 1 break if txns[i][j][0] == "R": for m in range(len(txns)): if m == i: continue for n in range(j + 1, len(txns[0])): if txns[m][n] == "*" or txns[m][n][0] == "R": continue if txns[i][j][2] == txns[m][n][2]: if (f"T{i + 1}", f"T{m + 1}") not in edges: edges.append((f"T{i + 1}", f"T{m + 1}")) flag = 1 break graph = nx.DiGraph() graph.add_nodes_from([f"T{i + 1}" for i in range(len(txns))]) graph.add_edges_from(edges) try: nx.planar_layout(graph) except nx.exception.NetworkXException: pass try: nx.find_cycle(graph) plt.title("Not Conflict Serializable", fontsize=10, color="red") print("This schedule is not Conflict Serializable.") print() nx.draw(graph, with_labels=True, node_size=1500, font_size=20, font_color="yellow", font_weight="bold", connectionstyle='arc3, rad = 0.1') plt.show() return 1, graph except nx.exception.NetworkXNoCycle: plt.title(f"Conflict Serializable: <{','.join(nx.topological_sort(graph))}>", fontsize=10, color="red") print(f"This schedule is Conflict Serializable and Conflict Equivalent to <{','.join(nx.topological_sort(graph))}>") print() nx.draw(graph, with_labels=True, node_size=1500, font_size=20, font_color="yellow", font_weight="bold", connectionstyle='arc3, rad = 0.1') plt.show() return 0, ""
def draw_Lineage(Lineage, cluster_label, ax): uni_lab = np.unique(cluster_label) rootedTree = nx.DiGraph() for i in range(len(np.where(Lineage != -1)[0])): rootedTree.add_edge(uni_lab[Lineage[Lineage != -1][i]], uni_lab[np.where(Lineage != -1)[0][i]]) nx.draw(rootedTree, pos=nx.planar_layout(rootedTree, 1), ax=ax) nx.draw_networkx_labels(rootedTree, pos=nx.planar_layout(rootedTree), ax=ax) return ax
def test_smoke_empty_graph(self): G = [] nx.random_layout(G) nx.circular_layout(G) nx.planar_layout(G) nx.spring_layout(G) nx.fruchterman_reingold_layout(G) nx.spectral_layout(G) nx.shell_layout(G) nx.bipartite_layout(G, G) nx.spiral_layout(G) nx.kamada_kawai_layout(G)
def test_smoke_string(self): G = self.Gs nx.random_layout(G) nx.circular_layout(G) nx.planar_layout(G) nx.spring_layout(G) nx.fruchterman_reingold_layout(G) nx.spectral_layout(G) nx.shell_layout(G) nx.spiral_layout(G) nx.kamada_kawai_layout(G) nx.kamada_kawai_layout(G, dim=1) nx.kamada_kawai_layout(G, dim=3)
def show_weighted_graph(G): pos = nx.planar_layout(G) nx.draw(G, pos) labels = nx.get_edge_attributes(G, 'weight') nx.draw_networkx_edge_labels(G, pos, edge_labels=labels) plt.show()
def draw_subtree(G, T): pos = nx.planar_layout(G) nx.draw_networkx(G, pos) labels = nx.get_edge_attributes(G, 'weight') nx.draw_networkx_edge_labels( G, pos, edge_labels=labels, ) nx.draw_networkx_edges( G, pos, edgelist=T.edges(), width=8, alpha=0.5, edge_color='r', ) nx.draw_networkx_nodes(G, pos, nodelist=T.nodes(), node_color='r', node_size=500, alpha=0.8) plt.show() # Function to draw the subtree
def do_graph(args): AS_countries = load_AS_countries() country_continent = load_country_continent() ASNs = nx.convert_node_labels_to_integers(nx.read_gml(args.file)) core = extract_core(ASNs) print("Positioning") pos = {} for node in ASNs.nodes(): pos[node] = wiggle((0.5, 0.5) if node in core else initial_positions[ country_continent[AS_countries[node]]] if node in AS_countries else (0.5, 0.5), 0.1) if args.layout == "spring": pos = nx.spring_layout(ASNs, pos=pos) elif args.layout == "kamada-kawai": pos = nx.kamada_kawai_layout(ASNs, pos=pos) elif args.layout == "spectral": pos = nx.spectral_layout(ASNs, pos=pos) elif args.layout == "planar": pos = nx.planar_layout(ASNs, pos=pos) elif args.layout == "random": pos = nx.random_layout(ASNs, pos=pos) elif args.layout == "shell": pos = nx.shell_layout(ASNs, pos=pos) labels = {} if args.degree_display is not None: print("Assigning labels") for node, degree in ASNs.degree(): if degree > args.degree_display: labels[node] = node print("Drawing") nx.draw( ASNs, pos, arrowstyle="->", with_labels=False, node_color=[ "r" if x in core else colors[country_continent[AS_countries[x]]] if x in AS_countries else "black" for x in ASNs.nodes() ], node_size=[3 * x**(2 / 3) for _, x in ASNs.degree()], width=0.3, edge_color="grey", alpha=0.7) if args.degree_display is not None: print("drawing labels") nx.draw_networkx_labels(ASNs, pos, labels, font_size=8) if args.output_file is not None: plt.savefig(args.output_file, dpi=args.dpi) plt.show()
def plot(self): pos = nx.planar_layout(self) nc = ['c' for _ in range(self.number_of_nodes())] plt.figure("Dependency Graph", figsize=(10, 10)) nx.draw_networkx_nodes(self, pos, node_color=nc, cmap=plt.get_cmap('jet'), node_size=900) nx.draw_networkx_labels( self, pos, dict( map(lambda x: (x[0], x[1]), nx.get_node_attributes(self, 'char').items()))) nx.draw_networkx_edges(self, pos, edgelist=self.edges(), edge_cmap=plt.cm.Wistia, width=2, arrows=True, arrowstyle='-|>', arrowsize=20, node_size=1000) plt.draw() plt.show()
def draw_network(connections): # Connection Containers con_from = [] con_to = [] # Fill connection containers from our connections list for i in connections: con_from.append(i[0]) con_to.append(i[1]) # Create a dataframe to represent our connections df = pd.DataFrame({"from": con_from, "to": con_to}) # Produce the edges from the dataframe G = nx.from_pandas_edgelist(df, "from", "to") # Color our nodes node_colors = ["green"] + ["skyblue"] * (len(G.nodes()) - 2) + ["red"] # Apply the colors to the nodes carac = pd.DataFrame({'ID': G.nodes(), 'myvalue': node_colors}) carac = carac.set_index('ID') carac = carac.reindex(G.nodes()) # Type of graph we want, in this case a planar graph representation pos = nx.planar_layout(G) # Draw the graph nx.draw(G, pos=pos, node_size=100, node_color=carac['myvalue'], with_labels=True) # , node_color="skyblue") plt.show()
def draw_subtree(G,T): """ creates and shows the weightwed graph Parameters ---------- G : NetworkX graph or list of nodes T = Subtree, gets edge attributes Returns ------- The corresponding subtree of the weighted graph """ pos = nx.planar_layout(G) ## nx.draw_networkx(G,pos) labels = nx.labels = nx.get_edge_attributes(G,'weight') nx.draw_networkx_edge_labels(G, pos, ## Creates edge labels for subtree using graph layout, position and weights edge_labels = labels) nx.draw_networkx_edges(G, pos, edgelist=T.edges(), #### Draws tree's edges using graph layout width=8, alpha=0.5, ### and assigns other attributes (e.g. color, width) to network edges edge_color='r') nx.draw_networkx_nodes(G, pos, ### Draws tree's nodes using layout nodelist=T.nodes(), ## and ssigns other attributes (e.g. size, color) to network nodes node_size=500, alpha=0.5, node_color='r') plt.show() ## shows plot
def generateSpectralLayout(layout: Layout): positions = nx.spectral_layout(layout.G) print(positions) nx.draw(layout.G, positions) plt.show() positions = nx.planar_layout(layout.G) print(positions) nx.draw(layout.G, positions) plt.show() positions = nx.circular_layout(layout.G) print(positions) nx.draw(layout.G, positions) plt.show() positions = nx.bipartite_layout(layout.G, nx.bipartite.sets(layout.G)[0]) print(positions) nx.draw(layout.G, positions) plt.show() positions = nx.shell_layout(layout.G) print(positions) nx.draw(layout.G, positions) plt.show() positions = nx.random_layout(layout.G) print(positions) nx.draw(layout.G, positions) plt.show() positions = nx.spiral_layout(layout.G) print(positions) nx.draw(layout.G, positions) plt.show()
def main(harfile_path, cur_domain): g=nx.Graph() pos=nx.planar_layout(g) g.add_node(cur_domain) domains=set() #harfile = open('G:\Privacy\hw3\www.macys.com_Archive [19-10-11 16-36-30].har', 'r') harfile = open(harfile_path, encoding="utf8") harfile_json = json.loads(harfile.read()) i = 0 for entry in harfile_json['log']['entries']: i = i + 1 url = entry['request']['url'] urlparts = urlparse(url) res = get_tld(url, as_object=True) subdomain=res.subdomain maindomain=res.domain thisdomain= res.fld if maindomain != cur_domain and thisdomain not in domains and thisdomain !=cur_domain: print (thisdomain) domains.add(thisdomain) for dm in domains: if dm != cur_domain: g.add_node(dm,node_color='#FFFF33') e= g.add_edge(dm, cur_domain) nx.draw(g, with_labels=True, font_size=8) plt.show() print('')
def disrupt_network_edge(H, edges): #edges is the list of disrupted links (list of tuples) H.remove_edges_from(edges) fig = plt.figure(figsize=(10, 9)) pos = nx.planar_layout(H) nx.draw_networkx(H, pos=pos) fig.savefig('SF_network_disrupted.png', dpi=fig.dpi) return H
def show(self) -> None: plt.subplot(111) pos = nx.planar_layout(self.G) nx.draw(self.G, pos=pos, with_labels=True) nx.draw_networkx_edges(self.G, pos, edgelist=self.feedbacks, with_labels=True, edge_color='r', connectionstyle='arc3, rad=0.5') plt.show()
def plot(self, label_as_index=False, position=None, filepos=None): """Plot the graph in a matplotlib graph. :param bool label_as_index: Display the index vertex instead of the label if True. (Default False) :param iterable position: The position for the """ G = nx.Graph() G.add_nodes_from([(i, { "label": self.label[i] }) for i in range(len(self.label))]) edges = self.get_edges() for edge in edges: G.add_edge(edge[0], edge[1], weight=edge[2]) if filepos is not None: pos = read_coordinates(filepos) elif position is not None: pos = position else: pos = nx.planar_layout(G) if position is None else position nx.draw(G, pos, with_labels=label_as_index, font_weight='bold') if not label_as_index: nx.draw_networkx_labels( G, pos, dict(zip(range(len(self.label)), self.label))) labels = nx.get_edge_attributes(G, 'weight') nx.draw_networkx_edge_labels(G, pos, edge_labels=labels)
def generatePlanarLayout(layout: Layout): positions = nx.planar_layout(layout.G) print('Positions for all the cells:', positions) print(positions) nx.draw(layout.G, positions) plt.show() plt.savefig('test.png')
def draw_subtree(G, T): # defines and displays the sub-graph pos = nx.planar_layout(G) nx.draw_networkx(G, pos) labels = nx.get_edge_attributes(G, 'weight') nx.draw_networkx_edge_labels( G, #displays the labels of edges of the Sub-Graph pos, edge_labels=labels, ) nx.draw_networkx_edges( G, pos, #displays the edges of the Sub-Graph edgelist=T.edges(), width=8, alpha=0.5, edge_color='r', ) nx.draw_networkx_nodes( G, #displays the nodes of theSub- Graph pos, nodelist=T.nodes(), node_color='r', node_size=500, alpha=0.8) plt.show()
def print_graph(g, DIRECTED): if DIRECTED: G = nx.DiGraph() else: G = nx.Graph() for i in range(len(g)): G.add_node(i) for i in range(len(g)): for j in range(len(g[i])): G.add_edge(i, g[i][j][0], weight=g[i][j][1]) for i in range(len(g)): print("from node %02i: " % (i), end="") print(g[i]) try: pos = nx.planar_layout(G) nx.draw(G, pos, with_labels=True) except nx.NetworkXException: print("\nGraph is not planar, using alternative representation") pos = nx.spring_layout(G) nx.draw(G, pos, with_labels=True) if DIRECTED: labels = dict([(( u, v, ), d['weight']) for u, v, d in G.edges(data=True)]) nx.draw_networkx_edge_labels(G, pos, edge_labels=labels, label_pos=0.3) else: labels = nx.get_edge_attributes(G, 'weight') nx.draw_networkx_edge_labels(G, pos, edge_labels=labels)
def __init__(self, input_matrix, matrix_type): """ PMFG class creates the Planar Maximally Filtered Graph and stores it as an attribute. :param input_matrix: (pd.Dataframe) Input distance matrix :param matrix_type: (str) Matrix type name (e.g. "distance"). """ super().__init__(matrix_type) # To store the MST edges self.mst_edges = [] # Create a nx.Graph object from ALSMT dataframe self.graph = self.create_pmfg(input_matrix) # Create positions with warnings.catch_warnings(): # Silencing specific FutureWarning warnings.filterwarnings( 'ignore', r'arrays to stack must be passed as a "sequence"') self.pos = nx.planar_layout(self.graph) # Attribute to store 3 cliques and 4 cliques self.three_cliques = [] self.four_cliques = [] # Generate the cliques self._generate_cliques() # Calculate disparity measure for the cliques self.disparity = self._calculate_disparity()
def __init__(self, cu_dict: Dict[str, ObjectifiedElement], dependencies_list: List[DependenceItem], loop_data: Dict[str, int], reduction_vars: List[Dict[str, str]]): self.g = nx.MultiDiGraph() self.reduction_vars = reduction_vars for id, node in cu_dict.items(): n = parse_cu(node) if n.name == "main": self.main = n self.g.add_node(id, data=n) for node in self.all_nodes(NodeType.LOOP): node.loop_iterations = loop_data.get(node.start_position(), 0) for node_id, node in cu_dict.items(): source = node_id if 'childrenNodes' in dir(node): for child in [n.text for n in node.childrenNodes]: if child not in self.g: print(f"WARNING: no child node {child} found") self.g.add_edge(source, child, data=Dependency(EdgeType.CHILD)) if 'successors' in dir(node) and 'CU' in dir(node.successors): for successor in [n.text for n in node.successors.CU]: if successor not in self.g: print(f"WARNING: no successor node {successor} found") self.g.add_edge(source, successor, data=Dependency(EdgeType.SUCCESSOR)) # calculate position before dependencies affect them try: self.pos = nx.planar_layout(self.g) # good except nx.exception.NetworkXException: try: # fallback layouts self.pos = nx.shell_layout(self.g) # maybe # self.pos = nx.kamada_kawai_layout(self.graph) # maybe except nx.exception.NetworkXException: self.pos = nx.random_layout(self.g) for dep in dependencies_list: if dep.type == 'INIT': continue sink_cu_ids = readlineToCUIdMap[dep.sink] source_cu_ids = writelineToCUIdMap[dep.source] for sink_cu_id in sink_cu_ids: for source_cu_id in source_cu_ids: if sink_cu_id == source_cu_id and (dep.type == 'WAR' or dep.type == 'WAW'): continue elif sink_cu_id and source_cu_id: self.g.add_edge(sink_cu_id, source_cu_id, data=parse_dependency(dep))
def show_dag(self, expand=set()): """Generate and show a DAG for the model """ from matplotlib.pyplot import show as pltshow G = self.make_dag(expand=expand) with warnings.catch_warnings(): warnings.simplefilter("ignore") ## Plotting edge_labels = dict([(( u, v, ), d["label"]) for u, v, d in G.edges(data=True)]) n = G.size() ## Manual layout # if n == 2: if False: pos = { "(var)": [-0.5, +0.5], "(out)": [+0.5, -0.5], } pos[self.functions[0].name] = [+0.5, +0.5] ## Optimized layout else: try: ## Planar, if possible pos = nx.planar_layout(G) except nx.NetworkXException: ## Scaled spring layout pos = nx.spring_layout( G, k=0.6 * n, pos={ "(Inputs)": [-0.5 * n, +0.5 * n], "(Outputs)": [+0.5 * n, -0.5 * n], }, fixed=["(var)", "(out)"], threshold=1e-6, iterations=100, ) # Generate colormap color_map = [] for node in G: if G.nodes[node]["parent"] == self.name: color_map.append("blue") else: color_map.append("green") # Draw nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels) nx.draw(G, pos, node_size=1000, with_labels=True, node_color=color_map) pltshow()
def build_img(self): G = nx.from_sparse6_bytes(self.sparse6.encode('ascii')) try: node_dic = {k:tuple(v) for k,v in nx.planar_layout(G).items()} except nx.NetworkXException: node_dic = {k:tuple(v) for k,v in nx.circular_layout(G, scale=0.6).items()} self.image_dic = node_dic self.has_image = True
def draw(self): labels = dict(self.nodes()) for k in labels.keys(): labels[k] = str(k.__class__.__name__) + " " + str( k.coord).split(":")[1] nx.draw_networkx(self, labels=labels, pos=nx.planar_layout(self)) plt.show()
def test_smoke_int(self): G = self.Gi nx.random_layout(G) nx.circular_layout(G) nx.planar_layout(G) nx.spring_layout(G) nx.fruchterman_reingold_layout(G) nx.fruchterman_reingold_layout(self.bigG) nx.spectral_layout(G) nx.spectral_layout(G.to_directed()) nx.spectral_layout(self.bigG) nx.spectral_layout(self.bigG.to_directed()) nx.shell_layout(G) nx.spiral_layout(G) nx.kamada_kawai_layout(G) nx.kamada_kawai_layout(G, dim=1) nx.kamada_kawai_layout(G, dim=3)
def draw_text_graph(G, labels): plt.figure(figsize=(18, 12)) pos = nx.planar_layout(G, scale=18) nx.draw_networkx_nodes(G, pos, node_color="red", linewidths=0, node_size=500) nx.draw_networkx_labels(G, pos, font_size=20, labels=labels) nx.draw_networkx_edges(G, pos) plt.xticks([]) plt.yticks([]) plt.show()
def drawPlanarGraph(G, filename): posit = nx.planar_layout(G) fig = plt.figure() fig.show() nx.draw(G, posit, with_labels=True) fig.canvas.draw() plt.savefig(filename, format="PNG")
def MPG_network(n,z=0): G = sample_MPG(n) nodes = np.asanyarray(G.nodes()) arcs = np.asanyarray(G.edges()) pos = nx.planar_layout(G) posConv = {} for i in range(n): posConv[i] = (pos[i][0], pos[i][1], z) return nodes, arcs, posConv
def main(): warnings.filterwarnings("ignore") #To ignore warning given by matplotlib G = ptpg.PTPG() G.add_nesw_vertices() G.node_position = nx.planar_layout(nx.from_numpy_matrix(G.matrix)) draw_undirected_graph(G) x = input() G.initialize_degrees() G.initialize_good_vertices() v, u = G.contract() while v != -1: print("Contracted the edge between " + str(v) + " and " + str(u)) node_position = nx.planar_layout(nx.from_numpy_matrix(G.matrix)) draw_undirected_graph(G) x = input() v, u = G.contract() G.get_trivial_rel() draw_directed_graph(G) # REMOVE following 2 lines later construct_rdg(G) draw_rdg(G) while len(G.contractions) != 0: x = input() G.expand() draw_directed_graph(G) #REMOVE following 2 lines later construct_rdg(G) draw_rdg(G) # G.populate_t1_matrix() # print(G.t1_matrix) # G.populate_t2_matrix() # print(G.t2_matrix) # G.get_dimensions() # print(G.room_x) # print(G.room_y) # print(G.room_width) # print(G.room_height) construct_rdg(G) draw_rdg(G)
def syncGraph(self): # graphs self.ui.widget__displayGraph.canvas.axes.clear() # Selecting a layout from self.selected_layout if self.selected_layout == 'Планарный вид': pos = nx.planar_layout(self.history_graphs[self.current_time]) elif self.selected_layout == 'Декартова плоскость': pos = self.cartesian_coordinate_layout() elif self.selected_layout == 'Круговой вид': pos = nx.circular_layout(self.history_graphs[self.current_time]) elif self.selected_layout == 'Вид оболочки': pos = nx.shell_layout(self.history_graphs[self.current_time]) elif self.selected_layout == 'Фрюхтерман-Рейнгольд': pos = nx.spring_layout(self.history_graphs[self.current_time]) # Edge labels edge_labels = { (u, v): round(d['weight'], DEFAULT_ROUND_DIGIT) for u, v, d in self.history_graphs[self.current_time].edges( data=True) } # And draw the graph nx.draw_networkx_nodes( self.history_graphs[self.current_time], pos=pos, nodelist=range(1, self.nodes_amount), node_color='#509bff', ax=self.ui.widget__displayGraph.canvas.axes, ) nx.draw_networkx_nodes( self.history_graphs[self.current_time], pos=pos, nodelist=[0], node_color='#ff3b3f', ax=self.ui.widget__displayGraph.canvas.axes, ) nx.draw_networkx_labels( self.history_graphs[self.current_time], pos=pos, ax=self.ui.widget__displayGraph.canvas.axes, ) nx.draw_networkx_edges( self.history_graphs[self.current_time], pos=pos, alpha=0.8, ax=self.ui.widget__displayGraph.canvas.axes, ) nx.draw_networkx_edge_labels( self.history_graphs[self.current_time], pos=pos, edge_labels=edge_labels, font_size=9, ax=self.ui.widget__displayGraph.canvas.axes, ) #self.ui.widget__displayGraph.canvas.axes.axis('off') self.ui.widget__displayGraph.canvas.axes.figure.tight_layout() self.ui.widget__displayGraph.canvas.draw()