本文整理汇总了Python中networkx.DiGraph方法的典型用法代码示例。如果您正苦于以下问题:Python networkx.DiGraph方法的具体用法?Python networkx.DiGraph怎么用?Python networkx.DiGraph使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类networkx
的用法示例。
在下文中一共展示了networkx.DiGraph方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: prep_ws
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import DiGraph [as 别名]
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
示例2: read_graph
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import DiGraph [as 别名]
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
示例3: __init__
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import DiGraph [as 别名]
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()))
示例4: _build_tree
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import DiGraph [as 别名]
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
示例5: to_networkx
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import DiGraph [as 别名]
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
示例6: create_test_heterograph2
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import DiGraph [as 别名]
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
示例7: create_test_heterograph3
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import DiGraph [as 别名]
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
示例8: test_pickling_heterograph
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import DiGraph [as 别名]
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)
示例9: test_pickling_heterograph_index_compatibility
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import DiGraph [as 别名]
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)
示例10: topological_sort_of_nucleotides
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import DiGraph [as 别名]
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
示例11: _add_update_events
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import DiGraph [as 别名]
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))
示例12: _create_subgraph_plot
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import DiGraph [as 别名]
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!")
示例13: analyze_calls
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import DiGraph [as 别名]
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)
示例14: _add_call_edge
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import DiGraph [as 别名]
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)
示例15: build_mol_graph
# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import DiGraph [as 别名]
def build_mol_graph(self):
mol = self.mol
graph = nx.DiGraph(Chem.rdmolops.GetAdjacencyMatrix(mol))
for atom in mol.GetAtoms():
graph.nodes[atom.GetIdx()]['label'] = (atom.GetSymbol(), atom.GetFormalCharge())
for bond in mol.GetBonds():
a1 = bond.GetBeginAtom().GetIdx()
a2 = bond.GetEndAtom().GetIdx()
btype = MolGraph.BOND_LIST.index( bond.GetBondType() )
graph[a1][a2]['label'] = btype
graph[a2][a1]['label'] = btype
return graph