multidigraph.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977
  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. # This __new__ method just does what Python itself does automatically.
  234. # We include it here as part of the dispatchable/backend interface.
  235. # If your goal is to understand how the graph classes work, you can ignore
  236. # this method, even when subclassing the base classes. If you are subclassing
  237. # in order to provide a backend that allows class instantiation, this method
  238. # can be overridden to return your own backend graph class.
  239. @nx._dispatchable(name="multidigraph__new__", graphs=None, returns_graph=True)
  240. def __new__(cls, *args, **kwargs):
  241. return object.__new__(cls)
  242. def __init__(self, incoming_graph_data=None, multigraph_input=None, **attr):
  243. """Initialize a graph with edges, name, or graph attributes.
  244. Parameters
  245. ----------
  246. incoming_graph_data : input graph
  247. Data to initialize graph. If incoming_graph_data=None (default)
  248. an empty graph is created. The data can be an edge list, or any
  249. NetworkX graph object. If the corresponding optional Python
  250. packages are installed the data can also be a 2D NumPy array, a
  251. SciPy sparse array, or a PyGraphviz graph.
  252. multigraph_input : bool or None (default None)
  253. Note: Only used when `incoming_graph_data` is a dict.
  254. If True, `incoming_graph_data` is assumed to be a
  255. dict-of-dict-of-dict-of-dict structure keyed by
  256. node to neighbor to edge keys to edge data for multi-edges.
  257. A NetworkXError is raised if this is not the case.
  258. If False, :func:`to_networkx_graph` is used to try to determine
  259. the dict's graph data structure as either a dict-of-dict-of-dict
  260. keyed by node to neighbor to edge data, or a dict-of-iterable
  261. keyed by node to neighbors.
  262. If None, the treatment for True is tried, but if it fails,
  263. the treatment for False is tried.
  264. attr : keyword arguments, optional (default= no attributes)
  265. Attributes to add to graph as key=value pairs.
  266. See Also
  267. --------
  268. convert
  269. Examples
  270. --------
  271. >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
  272. >>> G = nx.Graph(name="my graph")
  273. >>> e = [(1, 2), (2, 3), (3, 4)] # list of edges
  274. >>> G = nx.Graph(e)
  275. Arbitrary graph attribute pairs (key=value) may be assigned
  276. >>> G = nx.Graph(e, day="Friday")
  277. >>> G.graph
  278. {'day': 'Friday'}
  279. """
  280. attr.pop("backend", None) # Ignore explicit `backend="networkx"`
  281. # multigraph_input can be None/True/False. So check "is not False"
  282. if isinstance(incoming_graph_data, dict) and multigraph_input is not False:
  283. DiGraph.__init__(self)
  284. try:
  285. convert.from_dict_of_dicts(
  286. incoming_graph_data, create_using=self, multigraph_input=True
  287. )
  288. self.graph.update(attr)
  289. except Exception as err:
  290. if multigraph_input is True:
  291. raise nx.NetworkXError(
  292. f"converting multigraph_input raised:\n{type(err)}: {err}"
  293. )
  294. DiGraph.__init__(self, incoming_graph_data, **attr)
  295. else:
  296. DiGraph.__init__(self, incoming_graph_data, **attr)
  297. @cached_property
  298. def adj(self):
  299. """Graph adjacency object holding the neighbors of each node.
  300. This object is a read-only dict-like structure with node keys
  301. and neighbor-dict values. The neighbor-dict is keyed by neighbor
  302. to the edgekey-dict. So `G.adj[3][2][0]['color'] = 'blue'` sets
  303. the color of the edge `(3, 2, 0)` to `"blue"`.
  304. Iterating over G.adj behaves like a dict. Useful idioms include
  305. `for nbr, datadict in G.adj[n].items():`.
  306. The neighbor information is also provided by subscripting the graph.
  307. So `for nbr, foovalue in G[node].data('foo', default=1):` works.
  308. For directed graphs, `G.adj` holds outgoing (successor) info.
  309. """
  310. return MultiAdjacencyView(self._succ)
  311. @cached_property
  312. def succ(self):
  313. """Graph adjacency object holding the successors of each node.
  314. This object is a read-only dict-like structure with node keys
  315. and neighbor-dict values. The neighbor-dict is keyed by neighbor
  316. to the edgekey-dict. So `G.adj[3][2][0]['color'] = 'blue'` sets
  317. the color of the edge `(3, 2, 0)` to `"blue"`.
  318. Iterating over G.adj behaves like a dict. Useful idioms include
  319. `for nbr, datadict in G.adj[n].items():`.
  320. The neighbor information is also provided by subscripting the graph.
  321. So `for nbr, foovalue in G[node].data('foo', default=1):` works.
  322. For directed graphs, `G.succ` is identical to `G.adj`.
  323. """
  324. return MultiAdjacencyView(self._succ)
  325. @cached_property
  326. def pred(self):
  327. """Graph adjacency object holding the predecessors of each node.
  328. This object is a read-only dict-like structure with node keys
  329. and neighbor-dict values. The neighbor-dict is keyed by neighbor
  330. to the edgekey-dict. So `G.adj[3][2][0]['color'] = 'blue'` sets
  331. the color of the edge `(3, 2, 0)` to `"blue"`.
  332. Iterating over G.adj behaves like a dict. Useful idioms include
  333. `for nbr, datadict in G.adj[n].items():`.
  334. """
  335. return MultiAdjacencyView(self._pred)
  336. def add_edge(self, u_for_edge, v_for_edge, key=None, **attr):
  337. """Add an edge between u and v.
  338. The nodes u and v will be automatically added if they are
  339. not already in the graph.
  340. Edge attributes can be specified with keywords or by directly
  341. accessing the edge's attribute dictionary. See examples below.
  342. Parameters
  343. ----------
  344. u_for_edge, v_for_edge : nodes
  345. Nodes can be, for example, strings or numbers.
  346. Nodes must be hashable (and not None) Python objects.
  347. key : hashable identifier, optional (default=lowest unused integer)
  348. Used to distinguish multiedges between a pair of nodes.
  349. attr : keyword arguments, optional
  350. Edge data (or labels or objects) can be assigned using
  351. keyword arguments.
  352. Returns
  353. -------
  354. The edge key assigned to the edge.
  355. See Also
  356. --------
  357. add_edges_from : add a collection of edges
  358. Notes
  359. -----
  360. To replace/update edge data, use the optional key argument
  361. to identify a unique edge. Otherwise a new edge will be created.
  362. NetworkX algorithms designed for weighted graphs cannot use
  363. multigraphs directly because it is not clear how to handle
  364. multiedge weights. Convert to Graph using edge attribute
  365. 'weight' to enable weighted graph algorithms.
  366. Default keys are generated using the method `new_edge_key()`.
  367. This method can be overridden by subclassing the base class and
  368. providing a custom `new_edge_key()` method.
  369. Examples
  370. --------
  371. The following all add the edge e=(1, 2) to graph G:
  372. >>> G = nx.MultiDiGraph()
  373. >>> e = (1, 2)
  374. >>> key = G.add_edge(1, 2) # explicit two-node form
  375. >>> G.add_edge(*e) # single edge as tuple of two nodes
  376. 1
  377. >>> G.add_edges_from([(1, 2)]) # add edges from iterable container
  378. [2]
  379. Associate data to edges using keywords:
  380. >>> key = G.add_edge(1, 2, weight=3)
  381. >>> key = G.add_edge(1, 2, key=0, weight=4) # update data for key=0
  382. >>> key = G.add_edge(1, 3, weight=7, capacity=15, length=342.7)
  383. For non-string attribute keys, use subscript notation.
  384. >>> ekey = G.add_edge(1, 2)
  385. >>> G[1][2][0].update({0: 5})
  386. >>> G.edges[1, 2, 0].update({0: 5})
  387. """
  388. u, v = u_for_edge, v_for_edge
  389. # add nodes
  390. if u not in self._succ:
  391. if u is None:
  392. raise ValueError("None cannot be a node")
  393. self._succ[u] = self.adjlist_inner_dict_factory()
  394. self._pred[u] = self.adjlist_inner_dict_factory()
  395. self._node[u] = self.node_attr_dict_factory()
  396. if v not in self._succ:
  397. if v is None:
  398. raise ValueError("None cannot be a node")
  399. self._succ[v] = self.adjlist_inner_dict_factory()
  400. self._pred[v] = self.adjlist_inner_dict_factory()
  401. self._node[v] = self.node_attr_dict_factory()
  402. if key is None:
  403. key = self.new_edge_key(u, v)
  404. if v in self._succ[u]:
  405. keydict = self._adj[u][v]
  406. datadict = keydict.get(key, self.edge_attr_dict_factory())
  407. datadict.update(attr)
  408. keydict[key] = datadict
  409. else:
  410. # selfloops work this way without special treatment
  411. datadict = self.edge_attr_dict_factory()
  412. datadict.update(attr)
  413. keydict = self.edge_key_dict_factory()
  414. keydict[key] = datadict
  415. self._succ[u][v] = keydict
  416. self._pred[v][u] = keydict
  417. nx._clear_cache(self)
  418. return key
  419. def remove_edge(self, u, v, key=None):
  420. """Remove an edge between u and v.
  421. Parameters
  422. ----------
  423. u, v : nodes
  424. Remove an edge between nodes u and v.
  425. key : hashable identifier, optional (default=None)
  426. Used to distinguish multiple edges between a pair of nodes.
  427. If None, remove a single edge between u and v. If there are
  428. multiple edges, removes the last edge added in terms of
  429. insertion order.
  430. Raises
  431. ------
  432. NetworkXError
  433. If there is not an edge between u and v, or
  434. if there is no edge with the specified key.
  435. See Also
  436. --------
  437. remove_edges_from : remove a collection of edges
  438. Examples
  439. --------
  440. >>> G = nx.MultiDiGraph()
  441. >>> nx.add_path(G, [0, 1, 2, 3])
  442. >>> G.remove_edge(0, 1)
  443. >>> e = (1, 2)
  444. >>> G.remove_edge(*e) # unpacks e from an edge tuple
  445. For multiple edges
  446. >>> G = nx.MultiDiGraph()
  447. >>> G.add_edges_from([(1, 2), (1, 2), (1, 2)]) # key_list returned
  448. [0, 1, 2]
  449. When ``key=None`` (the default), edges are removed in the opposite
  450. order that they were added:
  451. >>> G.remove_edge(1, 2)
  452. >>> G.edges(keys=True)
  453. OutMultiEdgeView([(1, 2, 0), (1, 2, 1)])
  454. For edges with keys
  455. >>> G = nx.MultiDiGraph()
  456. >>> G.add_edge(1, 2, key="first")
  457. 'first'
  458. >>> G.add_edge(1, 2, key="second")
  459. 'second'
  460. >>> G.remove_edge(1, 2, key="first")
  461. >>> G.edges(keys=True)
  462. OutMultiEdgeView([(1, 2, 'second')])
  463. """
  464. try:
  465. d = self._adj[u][v]
  466. except KeyError as err:
  467. raise NetworkXError(f"The edge {u}-{v} is not in the graph.") from err
  468. # remove the edge with specified data
  469. if key is None:
  470. d.popitem()
  471. else:
  472. try:
  473. del d[key]
  474. except KeyError as err:
  475. msg = f"The edge {u}-{v} with key {key} is not in the graph."
  476. raise NetworkXError(msg) from err
  477. if len(d) == 0:
  478. # remove the key entries if last edge
  479. del self._succ[u][v]
  480. del self._pred[v][u]
  481. nx._clear_cache(self)
  482. @cached_property
  483. def edges(self):
  484. """An OutMultiEdgeView of the Graph as G.edges or G.edges().
  485. edges(self, nbunch=None, data=False, keys=False, default=None)
  486. The OutMultiEdgeView provides set-like operations on the edge-tuples
  487. as well as edge attribute lookup. When called, it also provides
  488. an EdgeDataView object which allows control of access to edge
  489. attributes (but does not provide set-like operations).
  490. Hence, ``G.edges[u, v, k]['color']`` provides the value of the color
  491. attribute for the edge from ``u`` to ``v`` with key ``k`` while
  492. ``for (u, v, k, c) in G.edges(data='color', default='red', keys=True):``
  493. iterates through all the edges yielding the color attribute with
  494. default `'red'` if no color attribute exists.
  495. Edges are returned as tuples with optional data and keys
  496. in the order (node, neighbor, key, data). If ``keys=True`` is not
  497. provided, the tuples will just be (node, neighbor, data), but
  498. multiple tuples with the same node and neighbor will be
  499. generated when multiple edges between two nodes exist.
  500. Parameters
  501. ----------
  502. nbunch : single node, container, or all nodes (default= all nodes)
  503. The view will only report edges from these nodes.
  504. data : string or bool, optional (default=False)
  505. The edge attribute returned in 3-tuple (u, v, ddict[data]).
  506. If True, return edge attribute dict in 3-tuple (u, v, ddict).
  507. If False, return 2-tuple (u, v).
  508. keys : bool, optional (default=False)
  509. If True, return edge keys with each edge, creating (u, v, k,
  510. d) tuples when data is also requested (the default) and (u,
  511. v, k) tuples when data is not requested.
  512. default : value, optional (default=None)
  513. Value used for edges that don't have the requested attribute.
  514. Only relevant if data is not True or False.
  515. Returns
  516. -------
  517. edges : OutMultiEdgeView
  518. A view of edge attributes, usually it iterates over (u, v)
  519. (u, v, k) or (u, v, k, d) tuples of edges, but can also be
  520. used for attribute lookup as ``edges[u, v, k]['foo']``.
  521. Notes
  522. -----
  523. Nodes in nbunch that are not in the graph will be (quietly) ignored.
  524. For directed graphs this returns the out-edges.
  525. Examples
  526. --------
  527. >>> G = nx.MultiDiGraph()
  528. >>> nx.add_path(G, [0, 1, 2])
  529. >>> key = G.add_edge(2, 3, weight=5)
  530. >>> key2 = G.add_edge(1, 2) # second edge between these nodes
  531. >>> [e for e in G.edges()]
  532. [(0, 1), (1, 2), (1, 2), (2, 3)]
  533. >>> list(G.edges(data=True)) # default data is {} (empty dict)
  534. [(0, 1, {}), (1, 2, {}), (1, 2, {}), (2, 3, {'weight': 5})]
  535. >>> list(G.edges(data="weight", default=1))
  536. [(0, 1, 1), (1, 2, 1), (1, 2, 1), (2, 3, 5)]
  537. >>> list(G.edges(keys=True)) # default keys are integers
  538. [(0, 1, 0), (1, 2, 0), (1, 2, 1), (2, 3, 0)]
  539. >>> list(G.edges(data=True, keys=True))
  540. [(0, 1, 0, {}), (1, 2, 0, {}), (1, 2, 1, {}), (2, 3, 0, {'weight': 5})]
  541. >>> list(G.edges(data="weight", default=1, keys=True))
  542. [(0, 1, 0, 1), (1, 2, 0, 1), (1, 2, 1, 1), (2, 3, 0, 5)]
  543. >>> list(G.edges([0, 2]))
  544. [(0, 1), (2, 3)]
  545. >>> list(G.edges(0))
  546. [(0, 1)]
  547. >>> list(G.edges(1))
  548. [(1, 2), (1, 2)]
  549. See Also
  550. --------
  551. in_edges, out_edges
  552. """
  553. return OutMultiEdgeView(self)
  554. # alias out_edges to edges
  555. @cached_property
  556. def out_edges(self):
  557. return OutMultiEdgeView(self)
  558. out_edges.__doc__ = edges.__doc__
  559. @cached_property
  560. def in_edges(self):
  561. """A view of the in edges of the graph as G.in_edges or G.in_edges().
  562. in_edges(self, nbunch=None, data=False, keys=False, default=None)
  563. Parameters
  564. ----------
  565. nbunch : single node, container, or all nodes (default= all nodes)
  566. The view will only report edges incident to these nodes.
  567. data : string or bool, optional (default=False)
  568. The edge attribute returned in 3-tuple (u, v, ddict[data]).
  569. If True, return edge attribute dict in 3-tuple (u, v, ddict).
  570. If False, return 2-tuple (u, v).
  571. keys : bool, optional (default=False)
  572. If True, return edge keys with each edge, creating 3-tuples
  573. (u, v, k) or with data, 4-tuples (u, v, k, d).
  574. default : value, optional (default=None)
  575. Value used for edges that don't have the requested attribute.
  576. Only relevant if data is not True or False.
  577. Returns
  578. -------
  579. in_edges : InMultiEdgeView or InMultiEdgeDataView
  580. A view of edge attributes, usually it iterates over (u, v)
  581. or (u, v, k) or (u, v, k, d) tuples of edges, but can also be
  582. used for attribute lookup as `edges[u, v, k]['foo']`.
  583. See Also
  584. --------
  585. edges
  586. """
  587. return InMultiEdgeView(self)
  588. @cached_property
  589. def degree(self):
  590. """A DegreeView for the Graph as G.degree or G.degree().
  591. The node degree is the number of edges adjacent to the node.
  592. The weighted node degree is the sum of the edge weights for
  593. edges incident to that node.
  594. This object provides an iterator for (node, degree) as well as
  595. lookup for the degree for a single node.
  596. Parameters
  597. ----------
  598. nbunch : single node, container, or all nodes (default= all nodes)
  599. The view will only report edges incident to these nodes.
  600. weight : string or None, optional (default=None)
  601. The name of an edge attribute that holds the numerical value used
  602. as a weight. If None, then each edge has weight 1.
  603. The degree is the sum of the edge weights adjacent to the node.
  604. Returns
  605. -------
  606. DiMultiDegreeView or int
  607. If multiple nodes are requested (the default), returns a `DiMultiDegreeView`
  608. mapping nodes to their degree.
  609. If a single node is requested, returns the degree of the node as an integer.
  610. See Also
  611. --------
  612. out_degree, in_degree
  613. Examples
  614. --------
  615. >>> G = nx.MultiDiGraph()
  616. >>> nx.add_path(G, [0, 1, 2, 3])
  617. >>> G.degree(0) # node 0 with degree 1
  618. 1
  619. >>> list(G.degree([0, 1, 2]))
  620. [(0, 1), (1, 2), (2, 2)]
  621. >>> G.add_edge(0, 1) # parallel edge
  622. 1
  623. >>> list(G.degree([0, 1, 2])) # parallel edges are counted
  624. [(0, 2), (1, 3), (2, 2)]
  625. """
  626. return DiMultiDegreeView(self)
  627. @cached_property
  628. def in_degree(self):
  629. """A DegreeView for (node, in_degree) or in_degree for single node.
  630. The node in-degree is the number of edges pointing into the node.
  631. The weighted node degree is the sum of the edge weights for
  632. edges incident to that node.
  633. This object provides an iterator for (node, degree) as well as
  634. lookup for the degree for a single node.
  635. Parameters
  636. ----------
  637. nbunch : single node, container, or all nodes (default= all nodes)
  638. The view will only report edges incident to these nodes.
  639. weight : string or None, optional (default=None)
  640. The edge attribute that holds the numerical value used
  641. as a weight. If None, then each edge has weight 1.
  642. The degree is the sum of the edge weights adjacent to the node.
  643. Returns
  644. -------
  645. If a single node is requested
  646. deg : int
  647. Degree of the node
  648. OR if multiple nodes are requested
  649. nd_iter : iterator
  650. The iterator returns two-tuples of (node, in-degree).
  651. See Also
  652. --------
  653. degree, out_degree
  654. Examples
  655. --------
  656. >>> G = nx.MultiDiGraph()
  657. >>> nx.add_path(G, [0, 1, 2, 3])
  658. >>> G.in_degree(0) # node 0 with degree 0
  659. 0
  660. >>> list(G.in_degree([0, 1, 2]))
  661. [(0, 0), (1, 1), (2, 1)]
  662. >>> G.add_edge(0, 1) # parallel edge
  663. 1
  664. >>> list(G.in_degree([0, 1, 2])) # parallel edges counted
  665. [(0, 0), (1, 2), (2, 1)]
  666. """
  667. return InMultiDegreeView(self)
  668. @cached_property
  669. def out_degree(self):
  670. """Returns an iterator for (node, out-degree) or out-degree for single node.
  671. out_degree(self, nbunch=None, weight=None)
  672. The node out-degree is the number of edges pointing out of the node.
  673. This function returns the out-degree for a single node or an iterator
  674. for a bunch of nodes or if nothing is passed as argument.
  675. Parameters
  676. ----------
  677. nbunch : single node, container, or all nodes (default= all nodes)
  678. The view will only report edges incident to these nodes.
  679. weight : string or None, optional (default=None)
  680. The edge attribute that holds the numerical value used
  681. as a weight. If None, then each edge has weight 1.
  682. The degree is the sum of the edge weights.
  683. Returns
  684. -------
  685. If a single node is requested
  686. deg : int
  687. Degree of the node
  688. OR if multiple nodes are requested
  689. nd_iter : iterator
  690. The iterator returns two-tuples of (node, out-degree).
  691. See Also
  692. --------
  693. degree, in_degree
  694. Examples
  695. --------
  696. >>> G = nx.MultiDiGraph()
  697. >>> nx.add_path(G, [0, 1, 2, 3])
  698. >>> G.out_degree(0) # node 0 with degree 1
  699. 1
  700. >>> list(G.out_degree([0, 1, 2]))
  701. [(0, 1), (1, 1), (2, 1)]
  702. >>> G.add_edge(0, 1) # parallel edge
  703. 1
  704. >>> list(G.out_degree([0, 1, 2])) # counts parallel edges
  705. [(0, 2), (1, 1), (2, 1)]
  706. """
  707. return OutMultiDegreeView(self)
  708. def is_multigraph(self):
  709. """Returns True if graph is a multigraph, False otherwise."""
  710. return True
  711. def is_directed(self):
  712. """Returns True if graph is directed, False otherwise."""
  713. return True
  714. def to_undirected(self, reciprocal=False, as_view=False):
  715. """Returns an undirected representation of the digraph.
  716. Parameters
  717. ----------
  718. reciprocal : bool (optional)
  719. If True only keep edges that appear in both directions
  720. in the original digraph.
  721. as_view : bool (optional, default=False)
  722. If True return an undirected view of the original directed graph.
  723. Returns
  724. -------
  725. G : MultiGraph
  726. An undirected graph with the same name and nodes and
  727. with edge (u, v, data) if either (u, v, data) or (v, u, data)
  728. is in the digraph. If both edges exist in digraph and
  729. their edge data is different, only one edge is created
  730. with an arbitrary choice of which edge data to use.
  731. You must check and correct for this manually if desired.
  732. See Also
  733. --------
  734. MultiGraph, copy, add_edge, add_edges_from
  735. Notes
  736. -----
  737. This returns a "deepcopy" of the edge, node, and
  738. graph attributes which attempts to completely copy
  739. all of the data and references.
  740. This is in contrast to the similar D=MultiDiGraph(G) which
  741. returns a shallow copy of the data.
  742. See the Python copy module for more information on shallow
  743. and deep copies, https://docs.python.org/3/library/copy.html.
  744. Warning: If you have subclassed MultiDiGraph to use dict-like
  745. objects in the data structure, those changes do not transfer
  746. to the MultiGraph created by this method.
  747. Examples
  748. --------
  749. >>> G = nx.path_graph(2) # or MultiGraph, etc
  750. >>> H = G.to_directed()
  751. >>> list(H.edges)
  752. [(0, 1), (1, 0)]
  753. >>> G2 = H.to_undirected()
  754. >>> list(G2.edges)
  755. [(0, 1)]
  756. """
  757. graph_class = self.to_undirected_class()
  758. if as_view is True:
  759. return nx.graphviews.generic_graph_view(self, graph_class)
  760. # deepcopy when not a view
  761. G = graph_class()
  762. G.graph.update(deepcopy(self.graph))
  763. G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
  764. if reciprocal is True:
  765. G.add_edges_from(
  766. (u, v, key, deepcopy(data))
  767. for u, nbrs in self._adj.items()
  768. for v, keydict in nbrs.items()
  769. for key, data in keydict.items()
  770. if v in self._pred[u] and key in self._pred[u][v]
  771. )
  772. else:
  773. G.add_edges_from(
  774. (u, v, key, deepcopy(data))
  775. for u, nbrs in self._adj.items()
  776. for v, keydict in nbrs.items()
  777. for key, data in keydict.items()
  778. )
  779. return G
  780. def reverse(self, copy=True):
  781. """Returns the reverse of the graph.
  782. The reverse is a graph with the same nodes and edges
  783. but with the directions of the edges reversed.
  784. Parameters
  785. ----------
  786. copy : bool optional (default=True)
  787. If True, return a new DiGraph holding the reversed edges.
  788. If False, the reverse graph is created using a view of
  789. the original graph.
  790. """
  791. if copy:
  792. H = self.__class__()
  793. H.graph.update(deepcopy(self.graph))
  794. H.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
  795. H.add_edges_from(
  796. (v, u, k, deepcopy(d))
  797. for u, v, k, d in self.edges(keys=True, data=True)
  798. )
  799. return H
  800. return nx.reverse_view(self)