本文整理匯總了Python中networkx.MultiDiGraph方法的典型用法代碼示例。如果您正苦於以下問題:Python networkx.MultiDiGraph方法的具體用法?Python networkx.MultiDiGraph怎麽用?Python networkx.MultiDiGraph使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類networkx
的用法示例。
在下文中一共展示了networkx.MultiDiGraph方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: nx_graph
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import MultiDiGraph [as 別名]
def nx_graph(self):
"""Convert the data in a ``nodelist`` into a networkx labeled directed graph."""
import networkx
nx_nodelist = list(range(1, len(self.nodes)))
nx_edgelist = [
(n, self._hd(n), self._rel(n))
for n in nx_nodelist if self._hd(n)
]
self.nx_labels = {}
for n in nx_nodelist:
self.nx_labels[n] = self.nodes[n]['word']
g = networkx.MultiDiGraph()
g.add_nodes_from(nx_nodelist)
g.add_edges_from(nx_edgelist)
return g
示例2: to_networkx
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import MultiDiGraph [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
示例3: _to_graphml_simple
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import MultiDiGraph [as 別名]
def _to_graphml_simple(graph: BELGraph) -> nx.MultiDiGraph:
"""Convert a BEL graph to a simple graph.
:param graph: A BEL graph
"""
rv = nx.MultiDiGraph()
for node in graph:
rv.add_node(node.as_bel(), function=node.function)
for u, v, key, edge_data in graph.edges(data=True, keys=True):
u_key, v_key = u.as_bel(), v.as_bel()
rv.add_edge(
u_key,
v_key,
key=key,
interaction=edge_data[RELATION],
bel=graph.edge_to_bel(u, v, edge_data),
)
return rv
示例4: _to_graphml_umbrella
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import MultiDiGraph [as 別名]
def _to_graphml_umbrella(graph: BELGraph) -> nx.MultiDiGraph:
"""Convert a BEL graph to a new graph the nodes as original BEL terms strings.
:param graph: A BEL graph
"""
rv = nx.MultiDiGraph()
for u, v, key, edge_data in graph.edges(data=True, keys=True):
u_key, _, v_key = edge_to_tuple(u, v, edge_data)
rv.add_edge(
u_key,
v_key,
key=key,
relation=edge_data[RELATION],
bel=graph.edge_to_bel(u, v, edge_data),
)
return rv
示例5: test_random_nodes
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import MultiDiGraph [as 別名]
def test_random_nodes(self):
"""Test getting random nodes."""
graph = nx.MultiDiGraph()
graph.add_edge(1, 2)
graph.add_edge(1, 3)
graph.add_edge(1, 4)
graph.add_edge(1, 5)
n = 30000
r = Counter(
get_random_node(graph, set(), invert_degrees=False)
for _ in range(n)
)
degree_sum = 4 + 1 + 1 + 1 + 1
self.assertAlmostEqual(4 / degree_sum, r[1] / n, places=2)
self.assertAlmostEqual(1 / degree_sum, r[2] / n, places=2)
self.assertAlmostEqual(1 / degree_sum, r[3] / n, places=2)
self.assertAlmostEqual(1 / degree_sum, r[4] / n, places=2)
self.assertAlmostEqual(1 / degree_sum, r[5] / n, places=2)
示例6: test_random_nodes_inverted
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import MultiDiGraph [as 別名]
def test_random_nodes_inverted(self):
"""Test getting random nodes."""
graph = nx.MultiDiGraph()
graph.add_edge(1, 2)
graph.add_edge(1, 3)
graph.add_edge(1, 4)
graph.add_edge(1, 5)
n = 30000
r = Counter(
get_random_node(graph, set(), invert_degrees=True)
for _ in range(n)
)
degree_sum = (1 / 4) + (1 / 1) + (1 / 1) + (1 / 1) + (1 / 1)
self.assertAlmostEqual((1 / 4) / degree_sum, r[1] / n, places=2)
self.assertAlmostEqual((1 / 1) / degree_sum, r[2] / n, places=2)
self.assertAlmostEqual((1 / 1) / degree_sum, r[3] / n, places=2)
self.assertAlmostEqual((1 / 1) / degree_sum, r[4] / n, places=2)
self.assertAlmostEqual((1 / 1) / degree_sum, r[5] / n, places=2)
示例7: read_graph
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import MultiDiGraph [as 別名]
def read_graph(self, subgraph_file=None):
if subgraph_file is None:
subraph_file = self.context_graph_file
logging.info("Writing graph.")
# write the graph out
file_format = subgraph_file.split(".")[-1]
if file_format == "graphml":
return nx.read_graphml(subgraph_file)
elif file_format == "gml":
return nx.read_gml(subgraph_file)
elif file_format == "gexf":
return nx.read_gexf(subgraph_file)
elif file_format == "net":
return nx.read_pajek(subgraph_file)
elif file_format == "yaml":
return nx.read_yaml(subgraph_file)
elif file_format == "gpickle":
return nx.read_gpickle(subgraph_file)
else:
logging.warning("File format not found, returning empty graph.")
return nx.MultiDiGraph()
示例8: anonymize_graph
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import MultiDiGraph [as 別名]
def anonymize_graph(self) -> "nx.MultiDiGraph":
"""Anonymizes the underlying graph before sending to Graphistry.
Returns
-------
nx.MultiDiGraph
The same graph structure, but without attributes.
"""
json_graph = self.to_json()
# Remove all properties from nodes, leave only IDs
json_graph["nodes"] = [{"id": node["id"]} for node in json_graph["nodes"]]
json_graph["links"] = [
{"source": edge["source"], "target": edge["target"]} for edge in json_graph["links"]
]
return nx.readwrite.json_graph.node_link_graph(json_graph)
示例9: graph
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import MultiDiGraph [as 別名]
def graph(self) -> nx.MultiDiGraph:
"""Generates the MultiDiGraph.
Places the nodes in the Graph.
Returns
-------
nx.MultiDiGraph
The generated NetworkX object.
"""
logger.info("Beginning graph generation.")
# De-duplicate nodes.
self.nodes = dedup_nodes(self.nodes)
for node in self.nodes:
# Insert the node into the graph.
# This also takes care of edges.
self.insert_node(node, hash(node))
logger.info("Completed graph generation.")
logger.info(f"Graph contains {len(self.G.nodes())} nodes and {len(self.G.edges())} edges.")
return self.G
示例10: multi_graph_to_log_graph
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import MultiDiGraph [as 別名]
def multi_graph_to_log_graph(digraph: nx.MultiDiGraph):
"""
This does not work with the default version of Networkx, but with the fork available at wardbradt/Networkx
Given weighted MultiDigraph m1, returns a MultiDigraph m2 where for each edge e1 in each edge bunch eb1 of m1, the
weight w1 of e1 is replaced with log(w1) and the weight w2 of each edge e2 in the opposite edge bunch of eb is
log(1/w2)
This function is not optimized.
todo: allow this function to be used with Networkx DiGraph objects. Should not be that hard, simply return seen
from self._report in the iterator for digraph's edges() in reportviews.py as it is done for multidigraph's
edge_bunches()
"""
result_graph = nx.MultiDiGraph()
for bunch in digraph.edge_bunches(data=True, seen=True):
for data_dict in bunch[2]:
weight = data_dict.pop('weight')
# if not seen
if not bunch[3]:
result_graph.add_edge(bunch[0], bunch[1], -math.log(weight), **data_dict)
else:
result_graph.add_edge(bunch[0], bunch[1], -math.log(1/weight), **data_dict)
示例11: format_graph_for_json
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import MultiDiGraph [as 別名]
def format_graph_for_json(graph, raise_errors=True):
"""
Currently, only supported types for graph are Graph, DiGraph, MultiGraph, and MultiDiGraph. graph must
be an instance of one of these types, not a class that inherits from one.
"""
graph_dict = nx.to_dict_of_dicts(graph)
graph_type = ''
for key, value in accepted_types.items():
if type(graph) == key:
graph_type = value
break
if graph_type == '':
if raise_errors:
raise TypeError('parameter graph is not of the accepted types.graph is of'
'type {}'.format(str(type(graph))))
else:
graph_type = 'other'
return {'graph_type': graph_type, 'graph_dict': graph_dict}
示例12: from_networkx
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import MultiDiGraph [as 別名]
def from_networkx(cls, graph):
"""Take a networkx MultiDigraph and create a new DAGCircuit.
Args:
graph (networkx.MultiDiGraph): The graph to create a DAGCircuit
object from. The format of this MultiDiGraph format must be
in the same format as returned by to_networkx.
Returns:
DAGCircuit: The dagcircuit object created from the networkx
MultiDiGraph.
"""
dag = DAGCircuit()
for node in nx.topological_sort(graph):
if node.type == 'out':
continue
if node.type == 'in':
dag._add_wire(node.wire)
elif node.type == 'op':
dag.apply_operation_back(node.op.copy(), node.qargs,
node.cargs, node.condition)
return dag
示例13: _gather_succ
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import MultiDiGraph [as 別名]
def _gather_succ(self, node_id, direct_succ):
"""
Function set an attribute successors and gather multiple lists
of direct successors into a single one.
Args:
node_id (int): label of the considered node in the DAG
direct_succ (list): list of direct successors for the given node
Returns:
MultiDiGraph: with update of the attribute ['predecessors']
the lists of direct successors are put into a single one
"""
gather = self._multi_graph
for d_succ in direct_succ:
gather.get_node_data(node_id).successors.append([d_succ])
succ = gather.get_node_data(d_succ).successors
gather.get_node_data(node_id).successors.append(succ)
return gather
示例14: _add_default_nodes
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import MultiDiGraph [as 別名]
def _add_default_nodes(graph: 'networkx.MultiDiGraph',
fontsize: int = 12) -> None:
"""Add the standard nodes we need."""
graph.add_node(START_NODE_ID,
label="START",
fillcolor="green", style="filled", fontsize=fontsize,
**{"class": "start active"})
graph.add_node(END_NODE_ID,
label="END",
fillcolor="red", style="filled", fontsize=fontsize,
**{"class": "end"})
graph.add_node(TMP_NODE_ID,
label="TMP",
style="invis",
**{"class": "invisible"})
示例15: _add_message_edge
# 需要導入模塊: import networkx [as 別名]
# 或者: from networkx import MultiDiGraph [as 別名]
def _add_message_edge(graph: 'networkx.MultiDiGraph',
message: Dict[Text, Any],
current_node: int,
next_node_idx: int,
is_current: bool
):
"""Create an edge based on the user message."""
if message:
message_key = sanitize(message.get("intent", {}).get("name", None))
message_label = sanitize(message.get("text", None))
else:
message_key = None
message_label = None
_add_edge(graph, current_node, next_node_idx, message_key,
message_label,
**{"class": "active" if is_current else ""})