Python networkx.DiGraph() Examples
The following are 30
code examples of networkx.DiGraph().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
networkx
, or try the search function
.
Example #1
Source File: module_tree.py From msticpy with MIT License | 6 votes |
def _add_call_edge( call_graph: nx.DiGraph, call_name: str, func_span: Dict[str, Any], call_lines, call_type="local", ): call_graph.add_node(call_name, call_type=call_type) for line in call_lines: calling_func = [ func for func, span in func_span.items() if span[0] <= line <= span[1] ] if calling_func: call_graph.add_edge(calling_func[0], call_name, line=line) else: call_graph.add_edge("ext", call_name, line=line)
Example #2
Source File: tree.py From dgl with Apache License 2.0 | 6 votes |
def _build_tree(self, root): g = nx.DiGraph() def _rec_build(nid, node): for child in node: cid = g.number_of_nodes() if isinstance(child[0], str) or isinstance(child[0], bytes): # leaf node word = self.vocab.get(child[0].lower(), self.UNK_WORD) g.add_node(cid, x=word, y=int(child.label()), mask=1) else: g.add_node(cid, x=SST.PAD_WORD, y=int(child.label()), mask=0) _rec_build(cid, child) g.add_edge(cid, nid) # add root g.add_node(0, x=SST.PAD_WORD, y=int(root.label()), mask=0) _rec_build(0, root) ret = DGLGraph() ret.from_networkx(g, node_attrs=['x', 'y', 'mask']) return ret
Example #3
Source File: edge2vec.py From edge2vec with BSD 3-Clause "New" or "Revised" License | 6 votes |
def read_graph(edgeList,weighted=False, directed=False): ''' Reads the input network in networkx. ''' if weighted: G = nx.read_edgelist(edgeList, nodetype=str, data=(('type',int),('weight',float),('id',int)), create_using=nx.DiGraph()) else: G = nx.read_edgelist(edgeList, nodetype=str,data=(('type',int),('id',int)), create_using=nx.DiGraph()) for edge in G.edges(): G[edge[0]][edge[1]]['weight'] = 1.0 if not directed: G = G.to_undirected() # print (G.edges(data = True)) return G
Example #4
Source File: generate_scalefree.py From AMLSim with Apache License 2.0 | 6 votes |
def powerlaw_cluster_generator(_n, _edge_factor): edges = nx.barabasi_albert_graph(_n, _edge_factor, seed=0).edges() # Undirected edges # Swap the direction of half edges to diffuse degree di_edges = [(edges[i][0], edges[i][1]) if i % 2 == 0 else (edges[i][1], edges[i][0]) for i in range(len(edges))] _g = nx.DiGraph() _g.add_edges_from(di_edges) # Create a directed graph return _g
Example #5
Source File: prep_data_prune.py From EvalNE with MIT License | 6 votes |
def prep_ws(inpath): """ Preprocess web spam graph. """ # Create an empty digraph G = nx.DiGraph() # Read the file and create the graph src = 0 f = open(inpath, 'r') for line in f: if src != 0: arr = line.split() for dst in arr: dst_id = int(dst.split(':')[0]) # We consider the graph unweighted G.add_edge(src, dst_id) src += 1 # G.add_node(src-2) # Preprocess the graph G, ids = pp.prep_graph(G, relabel=True, del_self_loops=False) # Return the preprocessed graph return G
Example #6
Source File: task_graph.py From metal with Apache License 2.0 | 6 votes |
def __init__(self, cardinalities=[2], edges=[]): self.K = cardinalities # Cardinalities for each task self.t = len(cardinalities) # Total number of tasks self.edges = edges # Create the graph of tasks self.G = nx.DiGraph() self.G.add_nodes_from(range(self.t)) self.G.add_edges_from(edges) # Pre-compute parents, children, and leaf nodes self.leaf_nodes = [i for i in self.G.nodes() if self.G.out_degree(i) == 0] self.parents = {t: self.get_parent(t) for t in range(self.t)} self.children = {t: self.get_children(t) for t in range(self.t)} # Save the cardinality of the feasible set self.k = len(list(self.feasible_set()))
Example #7
Source File: graph_index.py From dgl with Apache License 2.0 | 6 votes |
def to_networkx(self): """Convert to networkx graph. The edge id will be saved as the 'id' edge attribute. Returns ------- networkx.DiGraph The nx graph """ src, dst, eid = self.edges() # xiangsx: Always treat graph as multigraph ret = nx.MultiDiGraph() ret.add_nodes_from(range(self.number_of_nodes())) for u, v, e in zip(src, dst, eid): ret.add_edge(u, v, id=e) return ret
Example #8
Source File: test_heterograph.py From dgl with Apache License 2.0 | 6 votes |
def create_test_heterograph2(index_dtype): plays_spmat = ssp.coo_matrix(([1, 1, 1, 1], ([0, 1, 2, 1], [0, 0, 1, 1]))) wishes_nx = nx.DiGraph() wishes_nx.add_nodes_from(['u0', 'u1', 'u2'], bipartite=0) wishes_nx.add_nodes_from(['g0', 'g1'], bipartite=1) wishes_nx.add_edge('u0', 'g1', id=0) wishes_nx.add_edge('u2', 'g0', id=1) develops_g = dgl.bipartite([(0, 0), (1, 1)], 'developer', 'develops', 'game') g = dgl.heterograph({ ('user', 'follows', 'user'): [(0, 1), (1, 2)], ('user', 'plays', 'game'): plays_spmat, ('user', 'wishes', 'game'): wishes_nx, ('developer', 'develops', 'game'): develops_g, }) return g
Example #9
Source File: test_heterograph.py From dgl with Apache License 2.0 | 6 votes |
def create_test_heterograph3(index_dtype): plays_spmat = ssp.coo_matrix(([1, 1, 1, 1], ([0, 1, 2, 1], [0, 0, 1, 1]))) wishes_nx = nx.DiGraph() wishes_nx.add_nodes_from(['u0', 'u1', 'u2'], bipartite=0) wishes_nx.add_nodes_from(['g0', 'g1'], bipartite=1) wishes_nx.add_edge('u0', 'g1', id=0) wishes_nx.add_edge('u2', 'g0', id=1) follows_g = dgl.graph([(0, 1), (1, 2)], 'user', 'follows', _restrict_format='coo') plays_g = dgl.bipartite( [(0, 0), (1, 0), (2, 1), (1, 1)], 'user', 'plays', 'game', _restrict_format='coo') wishes_g = dgl.bipartite([(0, 1), (2, 0)], 'user', 'wishes', 'game', _restrict_format='coo') develops_g = dgl.bipartite( [(0, 0), (1, 1)], 'developer', 'develops', 'game', _restrict_format='coo') g = dgl.hetero_from_relations([follows_g, plays_g, wishes_g, develops_g]) return g
Example #10
Source File: test_pickle.py From dgl with Apache License 2.0 | 6 votes |
def test_pickling_heterograph(): # copied from test_heterograph.create_test_heterograph() plays_spmat = ssp.coo_matrix(([1, 1, 1, 1], ([0, 1, 2, 1], [0, 0, 1, 1]))) wishes_nx = nx.DiGraph() wishes_nx.add_nodes_from(['u0', 'u1', 'u2'], bipartite=0) wishes_nx.add_nodes_from(['g0', 'g1'], bipartite=1) wishes_nx.add_edge('u0', 'g1', id=0) wishes_nx.add_edge('u2', 'g0', id=1) follows_g = dgl.graph([(0, 1), (1, 2)], 'user', 'follows') plays_g = dgl.bipartite(plays_spmat, 'user', 'plays', 'game') wishes_g = dgl.bipartite(wishes_nx, 'user', 'wishes', 'game') develops_g = dgl.bipartite([(0, 0), (1, 1)], 'developer', 'develops', 'game') g = dgl.hetero_from_relations([follows_g, plays_g, wishes_g, develops_g]) g.nodes['user'].data['u_h'] = F.randn((3, 4)) g.nodes['game'].data['g_h'] = F.randn((2, 5)) g.edges['plays'].data['p_h'] = F.randn((4, 6)) new_g = _reconstruct_pickle(g) _assert_is_identical_hetero(g, new_g)
Example #11
Source File: test_pickle.py From dgl with Apache License 2.0 | 6 votes |
def test_pickling_heterograph_index_compatibility(): plays_spmat = ssp.coo_matrix(([1, 1, 1, 1], ([0, 1, 2, 1], [0, 0, 1, 1]))) wishes_nx = nx.DiGraph() wishes_nx.add_nodes_from(['u0', 'u1', 'u2'], bipartite=0) wishes_nx.add_nodes_from(['g0', 'g1'], bipartite=1) wishes_nx.add_edge('u0', 'g1', id=0) wishes_nx.add_edge('u2', 'g0', id=1) follows_g = dgl.graph([(0, 1), (1, 2)], 'user', 'follows') plays_g = dgl.bipartite(plays_spmat, 'user', 'plays', 'game') wishes_g = dgl.bipartite(wishes_nx, 'user', 'wishes', 'game') develops_g = dgl.bipartite([(0, 0), (1, 1)], 'developer', 'develops', 'game') g = dgl.hetero_from_relations([follows_g, plays_g, wishes_g, develops_g]) with open("tests/compute/hetero_pickle_old.pkl", "rb") as f: gi = pickle.load(f) f.close() new_g = dgl.DGLHeteroGraph(gi, g.ntypes, g.etypes) _assert_is_identical_hetero(g, new_g)
Example #12
Source File: graph_utils.py From nucleus7 with Mozilla Public License 2.0 | 6 votes |
def topological_sort_of_nucleotides(graph: nx.DiGraph) -> List[Nucleotide]: """ Perform topological order of the graph Parameters ---------- graph Returns ------- sorted_nucleotides list of nucleotides sorted in topological order """ nucleotides_without_inputs = [ each_nucleotide for each_nucleotide in graph if not list(graph.predecessors(each_nucleotide))] nucleotides_without_inputs_sorted = sorted( nucleotides_without_inputs, key=lambda x: x.name) topological_order = list(nx.topological_sort(graph)) topological_order_only_with_inputs = [ each_nucleotide for each_nucleotide in topological_order if each_nucleotide not in nucleotides_without_inputs] topological_order_sorted = (nucleotides_without_inputs_sorted + topological_order_only_with_inputs) return topological_order_sorted
Example #13
Source File: vis_utils.py From nucleus7 with Mozilla Public License 2.0 | 6 votes |
def _add_update_events(subplot: plt_axes.Subplot, dna_helix_graph: nx.DiGraph, nucleotide_plots: Dict[Nucleotide, _NUCLEOTIDE_PLOT]): subplot.figure.canvas.mpl_connect( 'draw_event', lambda x: subplot.pchanged()) subplot.figure.canvas.mpl_connect( 'resize_event', lambda x: subplot.pchanged()) text_initial_position = list(nucleotide_plots.values())[0].body.center text_object = subplot.text( text_initial_position[0], text_initial_position[1], "", ha="right", va="top", ma="left", bbox=dict(facecolor='white', edgecolor='blue', pad=5.0)) text_object.set_visible(False) subplot.figure.canvas.mpl_connect( 'button_press_event', partial(_remove_nucleotide_info_text, text_object=text_object)) subplot.figure.canvas.mpl_connect( 'pick_event', partial(_draw_nucleotide_info, dna_helix_graph=dna_helix_graph, text_object=text_object, subplot=subplot))
Example #14
Source File: vis_utils.py From nucleus7 with Mozilla Public License 2.0 | 6 votes |
def _create_subgraph_plot(event, dna_helix_graph: nx.DiGraph): mouseevent = event.mouseevent if not mouseevent.dblclick or mouseevent.button != 1: return logger = logging.getLogger(__name__) nucleotide_name = event.artist.get_label().split(":")[-1] nucleotide = _get_nucleotide_by_name(nucleotide_name, dna_helix_graph) logger.info("Create subgraph plot for %s", nucleotide_name) figure, subplot = _create_figure_with_subplot() figure.suptitle("Subgraph of nucleotide {}".format(nucleotide_name)) nucleotide_with_neighbors_subgraph = _get_nucleotide_subgraph( dna_helix_graph, nucleotide) draw_dna_helix_on_subplot( nucleotide_with_neighbors_subgraph, subplot, verbosity=1) _draw_click_instructions(subplot, doubleclick=False) plt.draw() logger.info("Done!")
Example #15
Source File: module_tree.py From msticpy with MIT License | 6 votes |
def analyze_calls(module: str, all_calls=False) -> nx.DiGraph: """ Analyze and build call graph of simple module. Parameters ---------- module : str Module path all_calls : bool Return graph of all calls, default is False Returns ------- nx.DiGraph Directed graph of functions and call """ file_analysis = analyze(module) # create a set of all imports return _create_call_graph(file_analysis["calls"], file_analysis["funcs"], all_calls)
Example #16
Source File: path_check.py From bap-tutorial with MIT License | 5 votes |
def enter_Sub(self, sub): cfg = nx.DiGraph() self.callgraph.add_node(sub.id.number, name=sub.name, sub=sub, cfg=cfg) self.sub = sub.id.number self.cfgs.append(cfg)
Example #17
Source File: path_check.py From bap-tutorial with MIT License | 5 votes |
def __init__(self): self.callgraph = nx.DiGraph() self.cfgs = [] self.sub = None self.blk = None
Example #18
Source File: startupplanner.py From minemeld-core with Apache License 2.0 | 5 votes |
def _build_graph(config): graph = nx.DiGraph() # nodes for nodename, _ in config.nodes.iteritems(): graph.add_node(nodename) # edges for nodename, nodevalue in config.nodes.iteritems(): inputs = nodevalue.get('inputs', []) graph.add_edges_from([(i, nodename) for i in inputs]) return graph
Example #19
Source File: gph_uno_bipartite.py From QCElemental with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _formDirected(g, match): """Form directed graph D from G and matching M. Parameters ---------- g : Undirected bipartite graph. Nodes are separated by their 'bipartite' attribute. match : List of edges forming a matching of `g`. Returns ------- networkx.DiGraph Directed graph, with edges in `match` pointing from set-0 (bipartite attribute==0) to set-1 (bipartite attrbiute==1), and the other edges in `g` but not in `match` pointing from set-1 to set-0. """ import networkx as nx d = nx.DiGraph() for ee in g.edges(): if ee in match or (ee[1], ee[0]) in match: if g.nodes[ee[0]]["bipartite"] == 0: d.add_edge(ee[0], ee[1]) else: d.add_edge(ee[1], ee[0]) else: if g.nodes[ee[0]]["bipartite"] == 0: d.add_edge(ee[1], ee[0]) else: d.add_edge(ee[0], ee[1]) return d
Example #20
Source File: test_heterograph.py From dgl with Apache License 2.0 | 5 votes |
def test_empty_heterograph(index_dtype): def assert_empty(g): assert g.number_of_nodes('user') == 0 assert g.number_of_edges('plays') == 0 assert g.number_of_nodes('game') == 0 # empty edge list assert_empty(dgl.heterograph({('user', 'plays', 'game'): []})) # empty src-dst pair assert_empty(dgl.heterograph({('user', 'plays', 'game'): ([], [])})) # empty sparse matrix assert_empty(dgl.heterograph({('user', 'plays', 'game'): ssp.coo_matrix((0, 0))})) # empty networkx graph assert_empty(dgl.heterograph({('user', 'plays', 'game'): nx.DiGraph()})) g = dgl.heterograph({('user', 'follows', 'user'): []}, index_dtype=index_dtype) assert g._idtype_str == index_dtype assert g.number_of_nodes('user') == 0 assert g.number_of_edges('follows') == 0 # empty relation graph with others g = dgl.heterograph({('user', 'plays', 'game'): [], ('developer', 'develops', 'game'): [ (0, 0), (1, 1)]}, index_dtype=index_dtype) assert g._idtype_str == index_dtype assert g.number_of_nodes('user') == 0 assert g.number_of_edges('plays') == 0 assert g.number_of_nodes('game') == 2 assert g.number_of_edges('develops') == 2 assert g.number_of_nodes('developer') == 2
Example #21
Source File: clusterer.py From bingraphvis with BSD 2-Clause "Simplified" License | 5 votes |
def cluster(self, graph): for node in graph.nodes: key = node.obj.callstack_key cluster = graph.get_cluster(key) if not cluster: cluster = graph.create_cluster(key, visible=self.visible) cluster.add_node(node) # merge by jump edges jgraph = nx.DiGraph() for e in graph.edges: if e.src.cluster and e.dst.cluster and e.src.cluster != e.dst.cluster: if e.meta['jumpkind'] == 'Ijk_Boring': jgraph.add_edge(e.src.cluster.key, e.dst.cluster.key) for n in jgraph.nodes(): in_edges = list(jgraph.in_edges(n)) if len(in_edges) == 1: s,t = in_edges[0] scluster = graph.get_cluster(s) for n in graph.nodes: if n.cluster.key == t: n.cluster.remove_node(n) scluster.add_node(n) # build cluster hierarchy cgraph = nx.DiGraph() for e in graph.edges: if e.src.cluster and e.dst.cluster and e.src.cluster != e.dst.cluster: if e.meta['jumpkind'] == 'Ijk_Call': cgraph.add_edge(e.src.cluster.key, e.dst.cluster.key) for n in cgraph.nodes(): in_edges = cgraph.in_edges(n) if len(in_edges) == 1: s,t = list(in_edges)[0] scluster = graph.get_cluster(s) tcluster = graph.get_cluster(t) tcluster.parent = scluster
Example #22
Source File: test_graph_index.py From dgl with Apache License 2.0 | 5 votes |
def generate_from_networkx(): edges = [[2, 3], [2, 5], [3, 0], [1, 0], [4, 3], [4, 5]] nx_graph = nx.DiGraph() nx_graph.add_edges_from(edges) g = create_graph_index(nx_graph, readonly=False) ig = create_graph_index(nx_graph, readonly=True) return g, ig
Example #23
Source File: _graphs.py From tmppy with Apache License 2.0 | 5 votes |
def compute_condensation_in_topological_order(dependency_graph: nx.DiGraph, sort_by = lambda x: x): if not dependency_graph.number_of_nodes(): return condensed_graph = nx.condensation(dependency_graph) assert isinstance(condensed_graph, nx.DiGraph) for connected_component_index in nx.lexicographical_topological_sort(condensed_graph, key=sort_by): yield list(sorted(condensed_graph.nodes[connected_component_index]['members'], key=sort_by))
Example #24
Source File: _remove_unused_toplevel_elems.py From tmppy with Apache License 2.0 | 5 votes |
def remove_unused_toplevel_elems(header: ir.Header, linking_final_header: bool): toplevel_elem_names = {elem.name for elem in itertools.chain(header.toplevel_content, header.template_defns) if not isinstance(elem, (ir.StaticAssert, ir.NoOpStmt))} public_names = header.public_names if not linking_final_header: public_names = public_names.union(split_name for _, split_name in header.split_template_name_by_old_name_and_result_element_name) elem_dependency_graph = nx.DiGraph() for elem in itertools.chain(header.template_defns, header.toplevel_content): if isinstance(elem, (ir.TemplateDefn, ir.ConstantDef, ir.Typedef)): elem_name = elem.name else: # We'll use a dummy name for non-template toplevel elems. elem_name = '' elem_dependency_graph.add_node(elem_name) if elem_name in public_names or (isinstance(elem, (ir.ConstantDef, ir.Typedef)) and any(isinstance(expr, ir.TemplateInstantiation) and expr.instantiation_might_trigger_static_asserts for expr in elem.transitive_subexpressions)): # We also add an edge from the node '' to all toplevel defns that must remain, so that we can use '' as a source below. elem_dependency_graph.add_edge('', elem_name) for identifier in elem.referenced_identifiers: if identifier in toplevel_elem_names: elem_dependency_graph.add_edge(elem_name, identifier) elem_dependency_graph.add_node('') used_elem_names = nx.single_source_shortest_path(elem_dependency_graph, source='').keys() return ir.Header(template_defns=tuple(template_defn for template_defn in header.template_defns if template_defn.name in used_elem_names), toplevel_content=tuple(elem for elem in header.toplevel_content if isinstance(elem, (ir.StaticAssert, ir.NoOpStmt)) or elem.name in used_elem_names), public_names=header.public_names, split_template_name_by_old_name_and_result_element_name=header.split_template_name_by_old_name_and_result_element_name, check_if_error_specializations=header.check_if_error_specializations)
Example #25
Source File: _recalculate_template_instantiation_can_trigger_static_asserts_info.py From tmppy with Apache License 2.0 | 5 votes |
def recalculate_template_instantiation_can_trigger_static_asserts_info(header: ir.Header): if not header.template_defns: return header template_defn_by_name = {template_defn.name: template_defn for template_defn in header.template_defns} template_defn_dependency_graph = compute_template_dependency_graph(header.template_defns, template_defn_by_name) condensed_graph = nx.condensation(template_defn_dependency_graph) assert isinstance(condensed_graph, nx.DiGraph) template_defn_dependency_graph_transitive_closure = nx.transitive_closure(template_defn_dependency_graph) assert isinstance(template_defn_dependency_graph_transitive_closure, nx.DiGraph) # Determine which connected components can trigger static assert errors. condensed_node_can_trigger_static_asserts = defaultdict(lambda: False) for connected_component_index in reversed(list(nx.lexicographical_topological_sort(condensed_graph))): condensed_node = condensed_graph.nodes[connected_component_index] # If a template defn in this connected component can trigger a static assert, the whole component can. for template_defn_name in condensed_node['members']: if _template_defn_contains_static_assert_stmt(template_defn_by_name[template_defn_name]): condensed_node_can_trigger_static_asserts[connected_component_index] = True # If a template defn in this connected component references a template defn in a connected component that can # trigger static asserts, this connected component can also trigger them. for called_condensed_node_index in condensed_graph.successors(connected_component_index): if condensed_node_can_trigger_static_asserts[called_condensed_node_index]: condensed_node_can_trigger_static_asserts[connected_component_index] = True template_defn_can_trigger_static_asserts = dict() for connected_component_index in condensed_graph: for template_defn_name in condensed_graph.nodes[connected_component_index]['members']: template_defn_can_trigger_static_asserts[template_defn_name] = condensed_node_can_trigger_static_asserts[connected_component_index] return _apply_template_instantiation_can_trigger_static_asserts_info(header, template_defn_can_trigger_static_asserts)
Example #26
Source File: _template_dependency_graph.py From tmppy with Apache License 2.0 | 5 votes |
def compute_template_dependency_graph(template_defns: Iterable[ir.TemplateDefn], template_defn_by_name: Dict[str, ir.TemplateDefn]): template_dependency_graph = nx.DiGraph() for template_defn in template_defns: template_dependency_graph.add_node(template_defn.name) for identifier in template_defn.referenced_identifiers: if identifier in template_defn_by_name.keys(): template_dependency_graph.add_edge(template_defn.name, identifier) return template_dependency_graph
Example #27
Source File: base.py From audiomate with MIT License | 5 votes |
def __init__(self, name=None, min_frames=1, left_context=0, right_context=0): self.graph = nx.DiGraph() self.name = name self.min_frames = min_frames self.left_context = left_context self.right_context = right_context self.steps_sorted = [] self.buffers = {} self.target_buffers = {}
Example #28
Source File: lookml_grapher.py From lookml-tools with Apache License 2.0 | 5 votes |
def create_graph(self): '''add nodes and edges to a graph Returns: instance of networkx graph ''' g = nx.DiGraph() [g.add_node(node_name) for node_name in self.node_map] [g.add_edge(p[0], p[1]) for p in self.models_to_explores] [g.add_edge(p[0], p[1]) for p in self.explores_to_views] return g
Example #29
Source File: test_lookml_grapher.py From lookml-tools with Apache License 2.0 | 5 votes |
def test_create_graph(config): grapher = LookMlGrapher(config) grapher.node_map['model_a'] = NodeType.MODEL grapher.node_map['explore_a'] = NodeType.EXPLORE grapher.node_map['view_a'] = NodeType.VIEW grapher.models_to_explores.append(('model_a', 'explore_a')) grapher.explores_to_views.append(('explore_a','view_a')) g = grapher.create_graph() assert isinstance(g, nx.DiGraph) assert len(g) == 3
Example #30
Source File: core.py From BMSpy with GNU Lesser General Public License v3.0 | 5 votes |
def _get_Graph(self): if not self._utd_graph: # Generate graph self._graph = nx.DiGraph() for variable in self.variables: self._graph.add_node(variable, bipartite=0) for block in self.blocks: self._graph.add_node(block, bipartite=1) for variable in block.inputs: self._graph.add_edge(variable, block) for variable in block.outputs: self._graph.add_edge(block, variable) self._utd_graph = True return self._graph