multidigraph.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963
  1. """Base class for MultiDiGraph."""
  2. from copy import deepcopy
  3. from functools import cached_property
  4. import networkx as nx
  5. from networkx import convert
  6. from networkx.classes.coreviews import MultiAdjacencyView
  7. from networkx.classes.digraph import DiGraph
  8. from networkx.classes.multigraph import MultiGraph
  9. from networkx.classes.reportviews import (
  10. DiMultiDegreeView,
  11. InMultiDegreeView,
  12. InMultiEdgeView,
  13. OutMultiDegreeView,
  14. OutMultiEdgeView,
  15. )
  16. from networkx.exception import NetworkXError
  17. __all__ = ["MultiDiGraph"]
  18. class MultiDiGraph(MultiGraph, DiGraph):
  19. """A directed graph class that can store multiedges.
  20. Multiedges are multiple edges between two nodes. Each edge
  21. can hold optional data or attributes.
  22. A MultiDiGraph holds directed edges. Self loops are allowed.
  23. Nodes can be arbitrary (hashable) Python objects with optional
  24. key/value attributes. By convention `None` is not used as a node.
  25. Edges are represented as links between nodes with optional
  26. key/value attributes.
  27. Parameters
  28. ----------
  29. incoming_graph_data : input graph (optional, default: None)
  30. Data to initialize graph. If None (default) an empty
  31. graph is created. The data can be any format that is supported
  32. by the to_networkx_graph() function, currently including edge list,
  33. dict of dicts, dict of lists, NetworkX graph, 2D NumPy array, SciPy
  34. sparse matrix, or PyGraphviz graph.
  35. multigraph_input : bool or None (default None)
  36. Note: Only used when `incoming_graph_data` is a dict.
  37. If True, `incoming_graph_data` is assumed to be a
  38. dict-of-dict-of-dict-of-dict structure keyed by
  39. node to neighbor to edge keys to edge data for multi-edges.
  40. A NetworkXError is raised if this is not the case.
  41. If False, :func:`to_networkx_graph` is used to try to determine
  42. the dict's graph data structure as either a dict-of-dict-of-dict
  43. keyed by node to neighbor to edge data, or a dict-of-iterable
  44. keyed by node to neighbors.
  45. If None, the treatment for True is tried, but if it fails,
  46. the treatment for False is tried.
  47. attr : keyword arguments, optional (default= no attributes)
  48. Attributes to add to graph as key=value pairs.
  49. See Also
  50. --------
  51. Graph
  52. DiGraph
  53. MultiGraph
  54. Examples
  55. --------
  56. Create an empty graph structure (a "null graph") with no nodes and
  57. no edges.
  58. >>> G = nx.MultiDiGraph()
  59. G can be grown in several ways.
  60. **Nodes:**
  61. Add one node at a time:
  62. >>> G.add_node(1)
  63. Add the nodes from any container (a list, dict, set or
  64. even the lines from a file or the nodes from another graph).
  65. >>> G.add_nodes_from([2, 3])
  66. >>> G.add_nodes_from(range(100, 110))
  67. >>> H = nx.path_graph(10)
  68. >>> G.add_nodes_from(H)
  69. In addition to strings and integers any hashable Python object
  70. (except None) can represent a node, e.g. a customized node object,
  71. or even another Graph.
  72. >>> G.add_node(H)
  73. **Edges:**
  74. G can also be grown by adding edges.
  75. Add one edge,
  76. >>> key = G.add_edge(1, 2)
  77. a list of edges,
  78. >>> keys = G.add_edges_from([(1, 2), (1, 3)])
  79. or a collection of edges,
  80. >>> keys = G.add_edges_from(H.edges)
  81. If some edges connect nodes not yet in the graph, the nodes
  82. are added automatically. If an edge already exists, an additional
  83. edge is created and stored using a key to identify the edge.
  84. By default the key is the lowest unused integer.
  85. >>> keys = G.add_edges_from([(4, 5, dict(route=282)), (4, 5, dict(route=37))])
  86. >>> G[4]
  87. AdjacencyView({5: {0: {}, 1: {'route': 282}, 2: {'route': 37}}})
  88. **Attributes:**
  89. Each graph, node, and edge can hold key/value attribute pairs
  90. in an associated attribute dictionary (the keys must be hashable).
  91. By default these are empty, but can be added or changed using
  92. add_edge, add_node or direct manipulation of the attribute
  93. dictionaries named graph, node and edge respectively.
  94. >>> G = nx.MultiDiGraph(day="Friday")
  95. >>> G.graph
  96. {'day': 'Friday'}
  97. Add node attributes using add_node(), add_nodes_from() or G.nodes
  98. >>> G.add_node(1, time="5pm")
  99. >>> G.add_nodes_from([3], time="2pm")
  100. >>> G.nodes[1]
  101. {'time': '5pm'}
  102. >>> G.nodes[1]["room"] = 714
  103. >>> del G.nodes[1]["room"] # remove attribute
  104. >>> list(G.nodes(data=True))
  105. [(1, {'time': '5pm'}), (3, {'time': '2pm'})]
  106. Add edge attributes using add_edge(), add_edges_from(), subscript
  107. notation, or G.edges.
  108. >>> key = G.add_edge(1, 2, weight=4.7)
  109. >>> keys = G.add_edges_from([(3, 4), (4, 5)], color="red")
  110. >>> keys = G.add_edges_from([(1, 2, {"color": "blue"}), (2, 3, {"weight": 8})])
  111. >>> G[1][2][0]["weight"] = 4.7
  112. >>> G.edges[1, 2, 0]["weight"] = 4
  113. Warning: we protect the graph data structure by making `G.edges[1,
  114. 2, 0]` a read-only dict-like structure. However, you can assign to
  115. attributes in e.g. `G.edges[1, 2, 0]`. Thus, use 2 sets of brackets
  116. to add/change data attributes: `G.edges[1, 2, 0]['weight'] = 4`
  117. (for multigraphs the edge key is required: `MG.edges[u, v,
  118. key][name] = value`).
  119. **Shortcuts:**
  120. Many common graph features allow python syntax to speed reporting.
  121. >>> 1 in G # check if node in graph
  122. True
  123. >>> [n for n in G if n < 3] # iterate through nodes
  124. [1, 2]
  125. >>> len(G) # number of nodes in graph
  126. 5
  127. >>> G[1] # adjacency dict-like view mapping neighbor -> edge key -> edge attributes
  128. AdjacencyView({2: {0: {'weight': 4}, 1: {'color': 'blue'}}})
  129. Often the best way to traverse all edges of a graph is via the neighbors.
  130. The neighbors are available as an adjacency-view `G.adj` object or via
  131. the method `G.adjacency()`.
  132. >>> for n, nbrsdict in G.adjacency():
  133. ... for nbr, keydict in nbrsdict.items():
  134. ... for key, eattr in keydict.items():
  135. ... if "weight" in eattr:
  136. ... # Do something useful with the edges
  137. ... pass
  138. But the edges() method is often more convenient:
  139. >>> for u, v, keys, weight in G.edges(data="weight", keys=True):
  140. ... if weight is not None:
  141. ... # Do something useful with the edges
  142. ... pass
  143. **Reporting:**
  144. Simple graph information is obtained using methods and object-attributes.
  145. Reporting usually provides views instead of containers to reduce memory
  146. usage. The views update as the graph is updated similarly to dict-views.
  147. The objects `nodes`, `edges` and `adj` provide access to data attributes
  148. via lookup (e.g. `nodes[n]`, `edges[u, v, k]`, `adj[u][v]`) and iteration
  149. (e.g. `nodes.items()`, `nodes.data('color')`,
  150. `nodes.data('color', default='blue')` and similarly for `edges`)
  151. Views exist for `nodes`, `edges`, `neighbors()`/`adj` and `degree`.
  152. For details on these and other miscellaneous methods, see below.
  153. **Subclasses (Advanced):**
  154. The MultiDiGraph class uses a dict-of-dict-of-dict-of-dict structure.
  155. The outer dict (node_dict) holds adjacency information keyed by node.
  156. The next dict (adjlist_dict) represents the adjacency information
  157. and holds edge_key dicts keyed by neighbor. The edge_key dict holds
  158. each edge_attr dict keyed by edge key. The inner dict
  159. (edge_attr_dict) represents the edge data and holds edge attribute
  160. values keyed by attribute names.
  161. Each of these four dicts in the dict-of-dict-of-dict-of-dict
  162. structure can be replaced by a user defined dict-like object.
  163. In general, the dict-like features should be maintained but
  164. extra features can be added. To replace one of the dicts create
  165. a new graph class by changing the class(!) variable holding the
  166. factory for that dict-like structure. The variable names are
  167. node_dict_factory, node_attr_dict_factory, adjlist_inner_dict_factory,
  168. adjlist_outer_dict_factory, edge_key_dict_factory, edge_attr_dict_factory
  169. and graph_attr_dict_factory.
  170. node_dict_factory : function, (default: dict)
  171. Factory function to be used to create the dict containing node
  172. attributes, keyed by node id.
  173. It should require no arguments and return a dict-like object
  174. node_attr_dict_factory: function, (default: dict)
  175. Factory function to be used to create the node attribute
  176. dict which holds attribute values keyed by attribute name.
  177. It should require no arguments and return a dict-like object
  178. adjlist_outer_dict_factory : function, (default: dict)
  179. Factory function to be used to create the outer-most dict
  180. in the data structure that holds adjacency info keyed by node.
  181. It should require no arguments and return a dict-like object.
  182. adjlist_inner_dict_factory : function, (default: dict)
  183. Factory function to be used to create the adjacency list
  184. dict which holds multiedge key dicts keyed by neighbor.
  185. It should require no arguments and return a dict-like object.
  186. edge_key_dict_factory : function, (default: dict)
  187. Factory function to be used to create the edge key dict
  188. which holds edge data keyed by edge key.
  189. It should require no arguments and return a dict-like object.
  190. edge_attr_dict_factory : function, (default: dict)
  191. Factory function to be used to create the edge attribute
  192. dict which holds attribute values keyed by attribute name.
  193. It should require no arguments and return a dict-like object.
  194. graph_attr_dict_factory : function, (default: dict)
  195. Factory function to be used to create the graph attribute
  196. dict which holds attribute values keyed by attribute name.
  197. It should require no arguments and return a dict-like object.
  198. Typically, if your extension doesn't impact the data structure all
  199. methods will inherited without issue except: `to_directed/to_undirected`.
  200. By default these methods create a DiGraph/Graph class and you probably
  201. want them to create your extension of a DiGraph/Graph. To facilitate
  202. this we define two class variables that you can set in your subclass.
  203. to_directed_class : callable, (default: DiGraph or MultiDiGraph)
  204. Class to create a new graph structure in the `to_directed` method.
  205. If `None`, a NetworkX class (DiGraph or MultiDiGraph) is used.
  206. to_undirected_class : callable, (default: Graph or MultiGraph)
  207. Class to create a new graph structure in the `to_undirected` method.
  208. If `None`, a NetworkX class (Graph or MultiGraph) is used.
  209. **Subclassing Example**
  210. Create a low memory graph class that effectively disallows edge
  211. attributes by using a single attribute dict for all edges.
  212. This reduces the memory used, but you lose edge attributes.
  213. >>> class ThinGraph(nx.Graph):
  214. ... all_edge_dict = {"weight": 1}
  215. ...
  216. ... def single_edge_dict(self):
  217. ... return self.all_edge_dict
  218. ...
  219. ... edge_attr_dict_factory = single_edge_dict
  220. >>> G = ThinGraph()
  221. >>> G.add_edge(2, 1)
  222. >>> G[2][1]
  223. {'weight': 1}
  224. >>> G.add_edge(2, 2)
  225. >>> G[2][1] is G[2][2]
  226. True
  227. """
  228. # node_dict_factory = dict # already assigned in Graph
  229. # adjlist_outer_dict_factory = dict
  230. # adjlist_inner_dict_factory = dict
  231. edge_key_dict_factory = dict
  232. # edge_attr_dict_factory = dict
  233. def __init__(self, incoming_graph_data=None, multigraph_input=None, **attr):
  234. """Initialize a graph with edges, name, or graph attributes.
  235. Parameters
  236. ----------
  237. incoming_graph_data : input graph
  238. Data to initialize graph. If incoming_graph_data=None (default)
  239. an empty graph is created. The data can be an edge list, or any
  240. NetworkX graph object. If the corresponding optional Python
  241. packages are installed the data can also be a 2D NumPy array, a
  242. SciPy sparse array, or a PyGraphviz graph.
  243. multigraph_input : bool or None (default None)
  244. Note: Only used when `incoming_graph_data` is a dict.
  245. If True, `incoming_graph_data` is assumed to be a
  246. dict-of-dict-of-dict-of-dict structure keyed by
  247. node to neighbor to edge keys to edge data for multi-edges.
  248. A NetworkXError is raised if this is not the case.
  249. If False, :func:`to_networkx_graph` is used to try to determine
  250. the dict's graph data structure as either a dict-of-dict-of-dict
  251. keyed by node to neighbor to edge data, or a dict-of-iterable
  252. keyed by node to neighbors.
  253. If None, the treatment for True is tried, but if it fails,
  254. the treatment for False is tried.
  255. attr : keyword arguments, optional (default= no attributes)
  256. Attributes to add to graph as key=value pairs.
  257. See Also
  258. --------
  259. convert
  260. Examples
  261. --------
  262. >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
  263. >>> G = nx.Graph(name="my graph")
  264. >>> e = [(1, 2), (2, 3), (3, 4)] # list of edges
  265. >>> G = nx.Graph(e)
  266. Arbitrary graph attribute pairs (key=value) may be assigned
  267. >>> G = nx.Graph(e, day="Friday")
  268. >>> G.graph
  269. {'day': 'Friday'}
  270. """
  271. # multigraph_input can be None/True/False. So check "is not False"
  272. if isinstance(incoming_graph_data, dict) and multigraph_input is not False:
  273. DiGraph.__init__(self)
  274. try:
  275. convert.from_dict_of_dicts(
  276. incoming_graph_data, create_using=self, multigraph_input=True
  277. )
  278. self.graph.update(attr)
  279. except Exception as err:
  280. if multigraph_input is True:
  281. raise nx.NetworkXError(
  282. f"converting multigraph_input raised:\n{type(err)}: {err}"
  283. )
  284. DiGraph.__init__(self, incoming_graph_data, **attr)
  285. else:
  286. DiGraph.__init__(self, incoming_graph_data, **attr)
  287. @cached_property
  288. def adj(self):
  289. """Graph adjacency object holding the neighbors of each node.
  290. This object is a read-only dict-like structure with node keys
  291. and neighbor-dict values. The neighbor-dict is keyed by neighbor
  292. to the edgekey-dict. So `G.adj[3][2][0]['color'] = 'blue'` sets
  293. the color of the edge `(3, 2, 0)` to `"blue"`.
  294. Iterating over G.adj behaves like a dict. Useful idioms include
  295. `for nbr, datadict in G.adj[n].items():`.
  296. The neighbor information is also provided by subscripting the graph.
  297. So `for nbr, foovalue in G[node].data('foo', default=1):` works.
  298. For directed graphs, `G.adj` holds outgoing (successor) info.
  299. """
  300. return MultiAdjacencyView(self._succ)
  301. @cached_property
  302. def succ(self):
  303. """Graph adjacency object holding the successors of each node.
  304. This object is a read-only dict-like structure with node keys
  305. and neighbor-dict values. The neighbor-dict is keyed by neighbor
  306. to the edgekey-dict. So `G.adj[3][2][0]['color'] = 'blue'` sets
  307. the color of the edge `(3, 2, 0)` to `"blue"`.
  308. Iterating over G.adj behaves like a dict. Useful idioms include
  309. `for nbr, datadict in G.adj[n].items():`.
  310. The neighbor information is also provided by subscripting the graph.
  311. So `for nbr, foovalue in G[node].data('foo', default=1):` works.
  312. For directed graphs, `G.succ` is identical to `G.adj`.
  313. """
  314. return MultiAdjacencyView(self._succ)
  315. @cached_property
  316. def pred(self):
  317. """Graph adjacency object holding the predecessors of each node.
  318. This object is a read-only dict-like structure with node keys
  319. and neighbor-dict values. The neighbor-dict is keyed by neighbor
  320. to the edgekey-dict. So `G.adj[3][2][0]['color'] = 'blue'` sets
  321. the color of the edge `(3, 2, 0)` to `"blue"`.
  322. Iterating over G.adj behaves like a dict. Useful idioms include
  323. `for nbr, datadict in G.adj[n].items():`.
  324. """
  325. return MultiAdjacencyView(self._pred)
  326. def add_edge(self, u_for_edge, v_for_edge, key=None, **attr):
  327. """Add an edge between u and v.
  328. The nodes u and v will be automatically added if they are
  329. not already in the graph.
  330. Edge attributes can be specified with keywords or by directly
  331. accessing the edge's attribute dictionary. See examples below.
  332. Parameters
  333. ----------
  334. u_for_edge, v_for_edge : nodes
  335. Nodes can be, for example, strings or numbers.
  336. Nodes must be hashable (and not None) Python objects.
  337. key : hashable identifier, optional (default=lowest unused integer)
  338. Used to distinguish multiedges between a pair of nodes.
  339. attr : keyword arguments, optional
  340. Edge data (or labels or objects) can be assigned using
  341. keyword arguments.
  342. Returns
  343. -------
  344. The edge key assigned to the edge.
  345. See Also
  346. --------
  347. add_edges_from : add a collection of edges
  348. Notes
  349. -----
  350. To replace/update edge data, use the optional key argument
  351. to identify a unique edge. Otherwise a new edge will be created.
  352. NetworkX algorithms designed for weighted graphs cannot use
  353. multigraphs directly because it is not clear how to handle
  354. multiedge weights. Convert to Graph using edge attribute
  355. 'weight' to enable weighted graph algorithms.
  356. Default keys are generated using the method `new_edge_key()`.
  357. This method can be overridden by subclassing the base class and
  358. providing a custom `new_edge_key()` method.
  359. Examples
  360. --------
  361. The following all add the edge e=(1, 2) to graph G:
  362. >>> G = nx.MultiDiGraph()
  363. >>> e = (1, 2)
  364. >>> key = G.add_edge(1, 2) # explicit two-node form
  365. >>> G.add_edge(*e) # single edge as tuple of two nodes
  366. 1
  367. >>> G.add_edges_from([(1, 2)]) # add edges from iterable container
  368. [2]
  369. Associate data to edges using keywords:
  370. >>> key = G.add_edge(1, 2, weight=3)
  371. >>> key = G.add_edge(1, 2, key=0, weight=4) # update data for key=0
  372. >>> key = G.add_edge(1, 3, weight=7, capacity=15, length=342.7)
  373. For non-string attribute keys, use subscript notation.
  374. >>> ekey = G.add_edge(1, 2)
  375. >>> G[1][2][0].update({0: 5})
  376. >>> G.edges[1, 2, 0].update({0: 5})
  377. """
  378. u, v = u_for_edge, v_for_edge
  379. # add nodes
  380. if u not in self._succ:
  381. if u is None:
  382. raise ValueError("None cannot be a node")
  383. self._succ[u] = self.adjlist_inner_dict_factory()
  384. self._pred[u] = self.adjlist_inner_dict_factory()
  385. self._node[u] = self.node_attr_dict_factory()
  386. if v not in self._succ:
  387. if v is None:
  388. raise ValueError("None cannot be a node")
  389. self._succ[v] = self.adjlist_inner_dict_factory()
  390. self._pred[v] = self.adjlist_inner_dict_factory()
  391. self._node[v] = self.node_attr_dict_factory()
  392. if key is None:
  393. key = self.new_edge_key(u, v)
  394. if v in self._succ[u]:
  395. keydict = self._adj[u][v]
  396. datadict = keydict.get(key, self.edge_attr_dict_factory())
  397. datadict.update(attr)
  398. keydict[key] = datadict
  399. else:
  400. # selfloops work this way without special treatment
  401. datadict = self.edge_attr_dict_factory()
  402. datadict.update(attr)
  403. keydict = self.edge_key_dict_factory()
  404. keydict[key] = datadict
  405. self._succ[u][v] = keydict
  406. self._pred[v][u] = keydict
  407. return key
  408. def remove_edge(self, u, v, key=None):
  409. """Remove an edge between u and v.
  410. Parameters
  411. ----------
  412. u, v : nodes
  413. Remove an edge between nodes u and v.
  414. key : hashable identifier, optional (default=None)
  415. Used to distinguish multiple edges between a pair of nodes.
  416. If None, remove a single edge between u and v. If there are
  417. multiple edges, removes the last edge added in terms of
  418. insertion order.
  419. Raises
  420. ------
  421. NetworkXError
  422. If there is not an edge between u and v, or
  423. if there is no edge with the specified key.
  424. See Also
  425. --------
  426. remove_edges_from : remove a collection of edges
  427. Examples
  428. --------
  429. >>> G = nx.MultiDiGraph()
  430. >>> nx.add_path(G, [0, 1, 2, 3])
  431. >>> G.remove_edge(0, 1)
  432. >>> e = (1, 2)
  433. >>> G.remove_edge(*e) # unpacks e from an edge tuple
  434. For multiple edges
  435. >>> G = nx.MultiDiGraph()
  436. >>> G.add_edges_from([(1, 2), (1, 2), (1, 2)]) # key_list returned
  437. [0, 1, 2]
  438. When ``key=None`` (the default), edges are removed in the opposite
  439. order that they were added:
  440. >>> G.remove_edge(1, 2)
  441. >>> G.edges(keys=True)
  442. OutMultiEdgeView([(1, 2, 0), (1, 2, 1)])
  443. For edges with keys
  444. >>> G = nx.MultiDiGraph()
  445. >>> G.add_edge(1, 2, key="first")
  446. 'first'
  447. >>> G.add_edge(1, 2, key="second")
  448. 'second'
  449. >>> G.remove_edge(1, 2, key="first")
  450. >>> G.edges(keys=True)
  451. OutMultiEdgeView([(1, 2, 'second')])
  452. """
  453. try:
  454. d = self._adj[u][v]
  455. except KeyError as err:
  456. raise NetworkXError(f"The edge {u}-{v} is not in the graph.") from err
  457. # remove the edge with specified data
  458. if key is None:
  459. d.popitem()
  460. else:
  461. try:
  462. del d[key]
  463. except KeyError as err:
  464. msg = f"The edge {u}-{v} with key {key} is not in the graph."
  465. raise NetworkXError(msg) from err
  466. if len(d) == 0:
  467. # remove the key entries if last edge
  468. del self._succ[u][v]
  469. del self._pred[v][u]
  470. @cached_property
  471. def edges(self):
  472. """An OutMultiEdgeView of the Graph as G.edges or G.edges().
  473. edges(self, nbunch=None, data=False, keys=False, default=None)
  474. The OutMultiEdgeView provides set-like operations on the edge-tuples
  475. as well as edge attribute lookup. When called, it also provides
  476. an EdgeDataView object which allows control of access to edge
  477. attributes (but does not provide set-like operations).
  478. Hence, ``G.edges[u, v, k]['color']`` provides the value of the color
  479. attribute for the edge from ``u`` to ``v`` with key ``k`` while
  480. ``for (u, v, k, c) in G.edges(data='color', default='red', keys=True):``
  481. iterates through all the edges yielding the color attribute with
  482. default `'red'` if no color attribute exists.
  483. Edges are returned as tuples with optional data and keys
  484. in the order (node, neighbor, key, data). If ``keys=True`` is not
  485. provided, the tuples will just be (node, neighbor, data), but
  486. multiple tuples with the same node and neighbor will be
  487. generated when multiple edges between two nodes exist.
  488. Parameters
  489. ----------
  490. nbunch : single node, container, or all nodes (default= all nodes)
  491. The view will only report edges from these nodes.
  492. data : string or bool, optional (default=False)
  493. The edge attribute returned in 3-tuple (u, v, ddict[data]).
  494. If True, return edge attribute dict in 3-tuple (u, v, ddict).
  495. If False, return 2-tuple (u, v).
  496. keys : bool, optional (default=False)
  497. If True, return edge keys with each edge, creating (u, v, k,
  498. d) tuples when data is also requested (the default) and (u,
  499. v, k) tuples when data is not requested.
  500. default : value, optional (default=None)
  501. Value used for edges that don't have the requested attribute.
  502. Only relevant if data is not True or False.
  503. Returns
  504. -------
  505. edges : OutMultiEdgeView
  506. A view of edge attributes, usually it iterates over (u, v)
  507. (u, v, k) or (u, v, k, d) tuples of edges, but can also be
  508. used for attribute lookup as ``edges[u, v, k]['foo']``.
  509. Notes
  510. -----
  511. Nodes in nbunch that are not in the graph will be (quietly) ignored.
  512. For directed graphs this returns the out-edges.
  513. Examples
  514. --------
  515. >>> G = nx.MultiDiGraph()
  516. >>> nx.add_path(G, [0, 1, 2])
  517. >>> key = G.add_edge(2, 3, weight=5)
  518. >>> key2 = G.add_edge(1, 2) # second edge between these nodes
  519. >>> [e for e in G.edges()]
  520. [(0, 1), (1, 2), (1, 2), (2, 3)]
  521. >>> list(G.edges(data=True)) # default data is {} (empty dict)
  522. [(0, 1, {}), (1, 2, {}), (1, 2, {}), (2, 3, {'weight': 5})]
  523. >>> list(G.edges(data="weight", default=1))
  524. [(0, 1, 1), (1, 2, 1), (1, 2, 1), (2, 3, 5)]
  525. >>> list(G.edges(keys=True)) # default keys are integers
  526. [(0, 1, 0), (1, 2, 0), (1, 2, 1), (2, 3, 0)]
  527. >>> list(G.edges(data=True, keys=True))
  528. [(0, 1, 0, {}), (1, 2, 0, {}), (1, 2, 1, {}), (2, 3, 0, {'weight': 5})]
  529. >>> list(G.edges(data="weight", default=1, keys=True))
  530. [(0, 1, 0, 1), (1, 2, 0, 1), (1, 2, 1, 1), (2, 3, 0, 5)]
  531. >>> list(G.edges([0, 2]))
  532. [(0, 1), (2, 3)]
  533. >>> list(G.edges(0))
  534. [(0, 1)]
  535. >>> list(G.edges(1))
  536. [(1, 2), (1, 2)]
  537. See Also
  538. --------
  539. in_edges, out_edges
  540. """
  541. return OutMultiEdgeView(self)
  542. # alias out_edges to edges
  543. @cached_property
  544. def out_edges(self):
  545. return OutMultiEdgeView(self)
  546. out_edges.__doc__ = edges.__doc__
  547. @cached_property
  548. def in_edges(self):
  549. """A view of the in edges of the graph as G.in_edges or G.in_edges().
  550. in_edges(self, nbunch=None, data=False, keys=False, default=None)
  551. Parameters
  552. ----------
  553. nbunch : single node, container, or all nodes (default= all nodes)
  554. The view will only report edges incident to these nodes.
  555. data : string or bool, optional (default=False)
  556. The edge attribute returned in 3-tuple (u, v, ddict[data]).
  557. If True, return edge attribute dict in 3-tuple (u, v, ddict).
  558. If False, return 2-tuple (u, v).
  559. keys : bool, optional (default=False)
  560. If True, return edge keys with each edge, creating 3-tuples
  561. (u, v, k) or with data, 4-tuples (u, v, k, d).
  562. default : value, optional (default=None)
  563. Value used for edges that don't have the requested attribute.
  564. Only relevant if data is not True or False.
  565. Returns
  566. -------
  567. in_edges : InMultiEdgeView or InMultiEdgeDataView
  568. A view of edge attributes, usually it iterates over (u, v)
  569. or (u, v, k) or (u, v, k, d) tuples of edges, but can also be
  570. used for attribute lookup as `edges[u, v, k]['foo']`.
  571. See Also
  572. --------
  573. edges
  574. """
  575. return InMultiEdgeView(self)
  576. @cached_property
  577. def degree(self):
  578. """A DegreeView for the Graph as G.degree or G.degree().
  579. The node degree is the number of edges adjacent to the node.
  580. The weighted node degree is the sum of the edge weights for
  581. edges incident to that node.
  582. This object provides an iterator for (node, degree) as well as
  583. lookup for the degree for a single node.
  584. Parameters
  585. ----------
  586. nbunch : single node, container, or all nodes (default= all nodes)
  587. The view will only report edges incident to these nodes.
  588. weight : string or None, optional (default=None)
  589. The name of an edge attribute that holds the numerical value used
  590. as a weight. If None, then each edge has weight 1.
  591. The degree is the sum of the edge weights adjacent to the node.
  592. Returns
  593. -------
  594. DiMultiDegreeView or int
  595. If multiple nodes are requested (the default), returns a `DiMultiDegreeView`
  596. mapping nodes to their degree.
  597. If a single node is requested, returns the degree of the node as an integer.
  598. See Also
  599. --------
  600. out_degree, in_degree
  601. Examples
  602. --------
  603. >>> G = nx.MultiDiGraph()
  604. >>> nx.add_path(G, [0, 1, 2, 3])
  605. >>> G.degree(0) # node 0 with degree 1
  606. 1
  607. >>> list(G.degree([0, 1, 2]))
  608. [(0, 1), (1, 2), (2, 2)]
  609. >>> G.add_edge(0, 1) # parallel edge
  610. 1
  611. >>> list(G.degree([0, 1, 2])) # parallel edges are counted
  612. [(0, 2), (1, 3), (2, 2)]
  613. """
  614. return DiMultiDegreeView(self)
  615. @cached_property
  616. def in_degree(self):
  617. """A DegreeView for (node, in_degree) or in_degree for single node.
  618. The node in-degree is the number of edges pointing in to the node.
  619. The weighted node degree is the sum of the edge weights for
  620. edges incident to that node.
  621. This object provides an iterator for (node, degree) as well as
  622. lookup for the degree for a single node.
  623. Parameters
  624. ----------
  625. nbunch : single node, container, or all nodes (default= all nodes)
  626. The view will only report edges incident to these nodes.
  627. weight : string or None, optional (default=None)
  628. The edge attribute that holds the numerical value used
  629. as a weight. If None, then each edge has weight 1.
  630. The degree is the sum of the edge weights adjacent to the node.
  631. Returns
  632. -------
  633. If a single node is requested
  634. deg : int
  635. Degree of the node
  636. OR if multiple nodes are requested
  637. nd_iter : iterator
  638. The iterator returns two-tuples of (node, in-degree).
  639. See Also
  640. --------
  641. degree, out_degree
  642. Examples
  643. --------
  644. >>> G = nx.MultiDiGraph()
  645. >>> nx.add_path(G, [0, 1, 2, 3])
  646. >>> G.in_degree(0) # node 0 with degree 0
  647. 0
  648. >>> list(G.in_degree([0, 1, 2]))
  649. [(0, 0), (1, 1), (2, 1)]
  650. >>> G.add_edge(0, 1) # parallel edge
  651. 1
  652. >>> list(G.in_degree([0, 1, 2])) # parallel edges counted
  653. [(0, 0), (1, 2), (2, 1)]
  654. """
  655. return InMultiDegreeView(self)
  656. @cached_property
  657. def out_degree(self):
  658. """Returns an iterator for (node, out-degree) or out-degree for single node.
  659. out_degree(self, nbunch=None, weight=None)
  660. The node out-degree is the number of edges pointing out of the node.
  661. This function returns the out-degree for a single node or an iterator
  662. for a bunch of nodes or if nothing is passed as argument.
  663. Parameters
  664. ----------
  665. nbunch : single node, container, or all nodes (default= all nodes)
  666. The view will only report edges incident to these nodes.
  667. weight : string or None, optional (default=None)
  668. The edge attribute that holds the numerical value used
  669. as a weight. If None, then each edge has weight 1.
  670. The degree is the sum of the edge weights.
  671. Returns
  672. -------
  673. If a single node is requested
  674. deg : int
  675. Degree of the node
  676. OR if multiple nodes are requested
  677. nd_iter : iterator
  678. The iterator returns two-tuples of (node, out-degree).
  679. See Also
  680. --------
  681. degree, in_degree
  682. Examples
  683. --------
  684. >>> G = nx.MultiDiGraph()
  685. >>> nx.add_path(G, [0, 1, 2, 3])
  686. >>> G.out_degree(0) # node 0 with degree 1
  687. 1
  688. >>> list(G.out_degree([0, 1, 2]))
  689. [(0, 1), (1, 1), (2, 1)]
  690. >>> G.add_edge(0, 1) # parallel edge
  691. 1
  692. >>> list(G.out_degree([0, 1, 2])) # counts parallel edges
  693. [(0, 2), (1, 1), (2, 1)]
  694. """
  695. return OutMultiDegreeView(self)
  696. def is_multigraph(self):
  697. """Returns True if graph is a multigraph, False otherwise."""
  698. return True
  699. def is_directed(self):
  700. """Returns True if graph is directed, False otherwise."""
  701. return True
  702. def to_undirected(self, reciprocal=False, as_view=False):
  703. """Returns an undirected representation of the digraph.
  704. Parameters
  705. ----------
  706. reciprocal : bool (optional)
  707. If True only keep edges that appear in both directions
  708. in the original digraph.
  709. as_view : bool (optional, default=False)
  710. If True return an undirected view of the original directed graph.
  711. Returns
  712. -------
  713. G : MultiGraph
  714. An undirected graph with the same name and nodes and
  715. with edge (u, v, data) if either (u, v, data) or (v, u, data)
  716. is in the digraph. If both edges exist in digraph and
  717. their edge data is different, only one edge is created
  718. with an arbitrary choice of which edge data to use.
  719. You must check and correct for this manually if desired.
  720. See Also
  721. --------
  722. MultiGraph, copy, add_edge, add_edges_from
  723. Notes
  724. -----
  725. This returns a "deepcopy" of the edge, node, and
  726. graph attributes which attempts to completely copy
  727. all of the data and references.
  728. This is in contrast to the similar D=MultiDiGraph(G) which
  729. returns a shallow copy of the data.
  730. See the Python copy module for more information on shallow
  731. and deep copies, https://docs.python.org/3/library/copy.html.
  732. Warning: If you have subclassed MultiDiGraph to use dict-like
  733. objects in the data structure, those changes do not transfer
  734. to the MultiGraph created by this method.
  735. Examples
  736. --------
  737. >>> G = nx.path_graph(2) # or MultiGraph, etc
  738. >>> H = G.to_directed()
  739. >>> list(H.edges)
  740. [(0, 1), (1, 0)]
  741. >>> G2 = H.to_undirected()
  742. >>> list(G2.edges)
  743. [(0, 1)]
  744. """
  745. graph_class = self.to_undirected_class()
  746. if as_view is True:
  747. return nx.graphviews.generic_graph_view(self, graph_class)
  748. # deepcopy when not a view
  749. G = graph_class()
  750. G.graph.update(deepcopy(self.graph))
  751. G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
  752. if reciprocal is True:
  753. G.add_edges_from(
  754. (u, v, key, deepcopy(data))
  755. for u, nbrs in self._adj.items()
  756. for v, keydict in nbrs.items()
  757. for key, data in keydict.items()
  758. if v in self._pred[u] and key in self._pred[u][v]
  759. )
  760. else:
  761. G.add_edges_from(
  762. (u, v, key, deepcopy(data))
  763. for u, nbrs in self._adj.items()
  764. for v, keydict in nbrs.items()
  765. for key, data in keydict.items()
  766. )
  767. return G
  768. def reverse(self, copy=True):
  769. """Returns the reverse of the graph.
  770. The reverse is a graph with the same nodes and edges
  771. but with the directions of the edges reversed.
  772. Parameters
  773. ----------
  774. copy : bool optional (default=True)
  775. If True, return a new DiGraph holding the reversed edges.
  776. If False, the reverse graph is created using a view of
  777. the original graph.
  778. """
  779. if copy:
  780. H = self.__class__()
  781. H.graph.update(deepcopy(self.graph))
  782. H.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
  783. H.add_edges_from(
  784. (v, u, k, deepcopy(d))
  785. for u, v, k, d in self.edges(keys=True, data=True)
  786. )
  787. return H
  788. return nx.graphviews.reverse_view(self)