multigraph.py 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294
  1. """Base class for MultiGraph."""
  2. from copy import deepcopy
  3. from functools import cached_property
  4. import networkx as nx
  5. from networkx import NetworkXError, convert
  6. from networkx.classes.coreviews import MultiAdjacencyView
  7. from networkx.classes.graph import Graph
  8. from networkx.classes.reportviews import MultiDegreeView, MultiEdgeView
  9. __all__ = ["MultiGraph"]
  10. class MultiGraph(Graph):
  11. """
  12. An undirected graph class that can store multiedges.
  13. Multiedges are multiple edges between two nodes. Each edge
  14. can hold optional data or attributes.
  15. A MultiGraph holds undirected edges. Self loops are allowed.
  16. Nodes can be arbitrary (hashable) Python objects with optional
  17. key/value attributes. By convention `None` is not used as a node.
  18. Edges are represented as links between nodes with optional
  19. key/value attributes, in a MultiGraph each edge has a key to
  20. distinguish between multiple edges that have the same source and
  21. destination nodes.
  22. Parameters
  23. ----------
  24. incoming_graph_data : input graph (optional, default: None)
  25. Data to initialize graph. If None (default) an empty
  26. graph is created. The data can be any format that is supported
  27. by the to_networkx_graph() function, currently including edge list,
  28. dict of dicts, dict of lists, NetworkX graph, 2D NumPy array,
  29. SciPy sparse array, or PyGraphviz graph.
  30. multigraph_input : bool or None (default None)
  31. Note: Only used when `incoming_graph_data` is a dict.
  32. If True, `incoming_graph_data` is assumed to be a
  33. dict-of-dict-of-dict-of-dict structure keyed by
  34. node to neighbor to edge keys to edge data for multi-edges.
  35. A NetworkXError is raised if this is not the case.
  36. If False, :func:`to_networkx_graph` is used to try to determine
  37. the dict's graph data structure as either a dict-of-dict-of-dict
  38. keyed by node to neighbor to edge data, or a dict-of-iterable
  39. keyed by node to neighbors.
  40. If None, the treatment for True is tried, but if it fails,
  41. the treatment for False is tried.
  42. attr : keyword arguments, optional (default= no attributes)
  43. Attributes to add to graph as key=value pairs.
  44. See Also
  45. --------
  46. Graph
  47. DiGraph
  48. MultiDiGraph
  49. Examples
  50. --------
  51. Create an empty graph structure (a "null graph") with no nodes and
  52. no edges.
  53. >>> G = nx.MultiGraph()
  54. G can be grown in several ways.
  55. **Nodes:**
  56. Add one node at a time:
  57. >>> G.add_node(1)
  58. Add the nodes from any container (a list, dict, set or
  59. even the lines from a file or the nodes from another graph).
  60. >>> G.add_nodes_from([2, 3])
  61. >>> G.add_nodes_from(range(100, 110))
  62. >>> H = nx.path_graph(10)
  63. >>> G.add_nodes_from(H)
  64. In addition to strings and integers any hashable Python object
  65. (except None) can represent a node, e.g. a customized node object,
  66. or even another Graph.
  67. >>> G.add_node(H)
  68. **Edges:**
  69. G can also be grown by adding edges.
  70. Add one edge,
  71. >>> key = G.add_edge(1, 2)
  72. a list of edges,
  73. >>> keys = G.add_edges_from([(1, 2), (1, 3)])
  74. or a collection of edges,
  75. >>> keys = G.add_edges_from(H.edges)
  76. If some edges connect nodes not yet in the graph, the nodes
  77. are added automatically. If an edge already exists, an additional
  78. edge is created and stored using a key to identify the edge.
  79. By default the key is the lowest unused integer.
  80. >>> keys = G.add_edges_from([(4, 5, {"route": 28}), (4, 5, {"route": 37})])
  81. >>> G[4]
  82. AdjacencyView({3: {0: {}}, 5: {0: {}, 1: {'route': 28}, 2: {'route': 37}}})
  83. **Attributes:**
  84. Each graph, node, and edge can hold key/value attribute pairs
  85. in an associated attribute dictionary (the keys must be hashable).
  86. By default these are empty, but can be added or changed using
  87. add_edge, add_node or direct manipulation of the attribute
  88. dictionaries named graph, node and edge respectively.
  89. >>> G = nx.MultiGraph(day="Friday")
  90. >>> G.graph
  91. {'day': 'Friday'}
  92. Add node attributes using add_node(), add_nodes_from() or G.nodes
  93. >>> G.add_node(1, time="5pm")
  94. >>> G.add_nodes_from([3], time="2pm")
  95. >>> G.nodes[1]
  96. {'time': '5pm'}
  97. >>> G.nodes[1]["room"] = 714
  98. >>> del G.nodes[1]["room"] # remove attribute
  99. >>> list(G.nodes(data=True))
  100. [(1, {'time': '5pm'}), (3, {'time': '2pm'})]
  101. Add edge attributes using add_edge(), add_edges_from(), subscript
  102. notation, or G.edges.
  103. >>> key = G.add_edge(1, 2, weight=4.7)
  104. >>> keys = G.add_edges_from([(3, 4), (4, 5)], color="red")
  105. >>> keys = G.add_edges_from([(1, 2, {"color": "blue"}), (2, 3, {"weight": 8})])
  106. >>> G[1][2][0]["weight"] = 4.7
  107. >>> G.edges[1, 2, 0]["weight"] = 4
  108. Warning: we protect the graph data structure by making `G.edges[1,
  109. 2, 0]` a read-only dict-like structure. However, you can assign to
  110. attributes in e.g. `G.edges[1, 2, 0]`. Thus, use 2 sets of brackets
  111. to add/change data attributes: `G.edges[1, 2, 0]['weight'] = 4`.
  112. **Shortcuts:**
  113. Many common graph features allow python syntax to speed reporting.
  114. >>> 1 in G # check if node in graph
  115. True
  116. >>> [n for n in G if n < 3] # iterate through nodes
  117. [1, 2]
  118. >>> len(G) # number of nodes in graph
  119. 5
  120. >>> G[1] # adjacency dict-like view mapping neighbor -> edge key -> edge attributes
  121. AdjacencyView({2: {0: {'weight': 4}, 1: {'color': 'blue'}}})
  122. Often the best way to traverse all edges of a graph is via the neighbors.
  123. The neighbors are reported as an adjacency-dict `G.adj` or `G.adjacency()`.
  124. >>> for n, nbrsdict in G.adjacency():
  125. ... for nbr, keydict in nbrsdict.items():
  126. ... for key, eattr in keydict.items():
  127. ... if "weight" in eattr:
  128. ... # Do something useful with the edges
  129. ... pass
  130. But the edges() method is often more convenient:
  131. >>> for u, v, keys, weight in G.edges(data="weight", keys=True):
  132. ... if weight is not None:
  133. ... # Do something useful with the edges
  134. ... pass
  135. **Reporting:**
  136. Simple graph information is obtained using methods and object-attributes.
  137. Reporting usually provides views instead of containers to reduce memory
  138. usage. The views update as the graph is updated similarly to dict-views.
  139. The objects `nodes`, `edges` and `adj` provide access to data attributes
  140. via lookup (e.g. `nodes[n]`, `edges[u, v, k]`, `adj[u][v]`) and iteration
  141. (e.g. `nodes.items()`, `nodes.data('color')`,
  142. `nodes.data('color', default='blue')` and similarly for `edges`)
  143. Views exist for `nodes`, `edges`, `neighbors()`/`adj` and `degree`.
  144. For details on these and other miscellaneous methods, see below.
  145. **Subclasses (Advanced):**
  146. The MultiGraph class uses a dict-of-dict-of-dict-of-dict data structure.
  147. The outer dict (node_dict) holds adjacency information keyed by node.
  148. The next dict (adjlist_dict) represents the adjacency information
  149. and holds edge_key dicts keyed by neighbor. The edge_key dict holds
  150. each edge_attr dict keyed by edge key. The inner dict
  151. (edge_attr_dict) represents the edge data and holds edge attribute
  152. values keyed by attribute names.
  153. Each of these four dicts in the dict-of-dict-of-dict-of-dict
  154. structure can be replaced by a user defined dict-like object.
  155. In general, the dict-like features should be maintained but
  156. extra features can be added. To replace one of the dicts create
  157. a new graph class by changing the class(!) variable holding the
  158. factory for that dict-like structure. The variable names are
  159. node_dict_factory, node_attr_dict_factory, adjlist_inner_dict_factory,
  160. adjlist_outer_dict_factory, edge_key_dict_factory, edge_attr_dict_factory
  161. and graph_attr_dict_factory.
  162. node_dict_factory : function, (default: dict)
  163. Factory function to be used to create the dict containing node
  164. attributes, keyed by node id.
  165. It should require no arguments and return a dict-like object
  166. node_attr_dict_factory: function, (default: dict)
  167. Factory function to be used to create the node attribute
  168. dict which holds attribute values keyed by attribute name.
  169. It should require no arguments and return a dict-like object
  170. adjlist_outer_dict_factory : function, (default: dict)
  171. Factory function to be used to create the outer-most dict
  172. in the data structure that holds adjacency info keyed by node.
  173. It should require no arguments and return a dict-like object.
  174. adjlist_inner_dict_factory : function, (default: dict)
  175. Factory function to be used to create the adjacency list
  176. dict which holds multiedge key dicts keyed by neighbor.
  177. It should require no arguments and return a dict-like object.
  178. edge_key_dict_factory : function, (default: dict)
  179. Factory function to be used to create the edge key dict
  180. which holds edge data keyed by edge key.
  181. It should require no arguments and return a dict-like object.
  182. edge_attr_dict_factory : function, (default: dict)
  183. Factory function to be used to create the edge attribute
  184. dict which holds attribute values keyed by attribute name.
  185. It should require no arguments and return a dict-like object.
  186. graph_attr_dict_factory : function, (default: dict)
  187. Factory function to be used to create the graph attribute
  188. dict which holds attribute values keyed by attribute name.
  189. It should require no arguments and return a dict-like object.
  190. Typically, if your extension doesn't impact the data structure all
  191. methods will inherited without issue except: `to_directed/to_undirected`.
  192. By default these methods create a DiGraph/Graph class and you probably
  193. want them to create your extension of a DiGraph/Graph. To facilitate
  194. this we define two class variables that you can set in your subclass.
  195. to_directed_class : callable, (default: DiGraph or MultiDiGraph)
  196. Class to create a new graph structure in the `to_directed` method.
  197. If `None`, a NetworkX class (DiGraph or MultiDiGraph) is used.
  198. to_undirected_class : callable, (default: Graph or MultiGraph)
  199. Class to create a new graph structure in the `to_undirected` method.
  200. If `None`, a NetworkX class (Graph or MultiGraph) is used.
  201. **Subclassing Example**
  202. Create a low memory graph class that effectively disallows edge
  203. attributes by using a single attribute dict for all edges.
  204. This reduces the memory used, but you lose edge attributes.
  205. >>> class ThinGraph(nx.Graph):
  206. ... all_edge_dict = {"weight": 1}
  207. ...
  208. ... def single_edge_dict(self):
  209. ... return self.all_edge_dict
  210. ...
  211. ... edge_attr_dict_factory = single_edge_dict
  212. >>> G = ThinGraph()
  213. >>> G.add_edge(2, 1)
  214. >>> G[2][1]
  215. {'weight': 1}
  216. >>> G.add_edge(2, 2)
  217. >>> G[2][1] is G[2][2]
  218. True
  219. """
  220. # node_dict_factory = dict # already assigned in Graph
  221. # adjlist_outer_dict_factory = dict
  222. # adjlist_inner_dict_factory = dict
  223. edge_key_dict_factory = dict
  224. # edge_attr_dict_factory = dict
  225. def to_directed_class(self):
  226. """Returns the class to use for empty directed copies.
  227. If you subclass the base classes, use this to designate
  228. what directed class to use for `to_directed()` copies.
  229. """
  230. return nx.MultiDiGraph
  231. def to_undirected_class(self):
  232. """Returns the class to use for empty undirected copies.
  233. If you subclass the base classes, use this to designate
  234. what directed class to use for `to_directed()` copies.
  235. """
  236. return MultiGraph
  237. # This __new__ method just does what Python itself does automatically.
  238. # We include it here as part of the dispatchable/backend interface.
  239. # If your goal is to understand how the graph classes work, you can ignore
  240. # this method, even when subclassing the base classes. If you are subclassing
  241. # in order to provide a backend that allows class instantiation, this method
  242. # can be overridden to return your own backend graph class.
  243. @nx._dispatchable(name="multigraph__new__", graphs=None, returns_graph=True)
  244. def __new__(cls, *args, **kwargs):
  245. return object.__new__(cls)
  246. def __init__(self, incoming_graph_data=None, multigraph_input=None, **attr):
  247. """Initialize a graph with edges, name, or graph attributes.
  248. Parameters
  249. ----------
  250. incoming_graph_data : input graph
  251. Data to initialize graph. If incoming_graph_data=None (default)
  252. an empty graph is created. The data can be an edge list, or any
  253. NetworkX graph object. If the corresponding optional Python
  254. packages are installed the data can also be a 2D NumPy array, a
  255. SciPy sparse array, or a PyGraphviz graph.
  256. multigraph_input : bool or None (default None)
  257. Note: Only used when `incoming_graph_data` is a dict.
  258. If True, `incoming_graph_data` is assumed to be a
  259. dict-of-dict-of-dict-of-dict structure keyed by
  260. node to neighbor to edge keys to edge data for multi-edges.
  261. A NetworkXError is raised if this is not the case.
  262. If False, :func:`to_networkx_graph` is used to try to determine
  263. the dict's graph data structure as either a dict-of-dict-of-dict
  264. keyed by node to neighbor to edge data, or a dict-of-iterable
  265. keyed by node to neighbors.
  266. If None, the treatment for True is tried, but if it fails,
  267. the treatment for False is tried.
  268. attr : keyword arguments, optional (default= no attributes)
  269. Attributes to add to graph as key=value pairs.
  270. See Also
  271. --------
  272. convert
  273. Examples
  274. --------
  275. >>> G = nx.MultiGraph()
  276. >>> G = nx.MultiGraph(name="my graph")
  277. >>> e = [(1, 2), (1, 2), (2, 3), (3, 4)] # list of edges
  278. >>> G = nx.MultiGraph(e)
  279. Arbitrary graph attribute pairs (key=value) may be assigned
  280. >>> G = nx.MultiGraph(e, day="Friday")
  281. >>> G.graph
  282. {'day': 'Friday'}
  283. """
  284. attr.pop("backend", None) # Ignore explicit `backend="networkx"`
  285. # multigraph_input can be None/True/False. So check "is not False"
  286. if isinstance(incoming_graph_data, dict) and multigraph_input is not False:
  287. Graph.__init__(self)
  288. try:
  289. convert.from_dict_of_dicts(
  290. incoming_graph_data, create_using=self, multigraph_input=True
  291. )
  292. self.graph.update(attr)
  293. except Exception as err:
  294. if multigraph_input is True:
  295. raise nx.NetworkXError(
  296. f"converting multigraph_input raised:\n{type(err)}: {err}"
  297. )
  298. Graph.__init__(self, incoming_graph_data, **attr)
  299. else:
  300. Graph.__init__(self, incoming_graph_data, **attr)
  301. @cached_property
  302. def adj(self):
  303. """Graph adjacency object holding the neighbors 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-data-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, edgesdict in G.adj[n].items():`.
  310. The neighbor information is also provided by subscripting the graph.
  311. Examples
  312. --------
  313. >>> e = [(1, 2), (1, 2), (1, 3), (3, 4)] # list of edges
  314. >>> G = nx.MultiGraph(e)
  315. >>> G.edges[1, 2, 0]["weight"] = 3
  316. >>> result = set()
  317. >>> for edgekey, data in G[1][2].items():
  318. ... result.add(data.get("weight", 1))
  319. >>> result
  320. {1, 3}
  321. For directed graphs, `G.adj` holds outgoing (successor) info.
  322. """
  323. return MultiAdjacencyView(self._adj)
  324. def new_edge_key(self, u, v):
  325. """Returns an unused key for edges between nodes `u` and `v`.
  326. The nodes `u` and `v` do not need to be already in the graph.
  327. Notes
  328. -----
  329. In the standard MultiGraph class the new key is the number of existing
  330. edges between `u` and `v` (increased if necessary to ensure unused).
  331. The first edge will have key 0, then 1, etc. If an edge is removed
  332. further new_edge_keys may not be in this order.
  333. Parameters
  334. ----------
  335. u, v : nodes
  336. Returns
  337. -------
  338. key : int
  339. """
  340. try:
  341. keydict = self._adj[u][v]
  342. except KeyError:
  343. return 0
  344. key = len(keydict)
  345. while key in keydict:
  346. key += 1
  347. return key
  348. def add_edge(self, u_for_edge, v_for_edge, key=None, **attr):
  349. """Add an edge between u and v.
  350. The nodes u and v will be automatically added if they are
  351. not already in the graph.
  352. Edge attributes can be specified with keywords or by directly
  353. accessing the edge's attribute dictionary. See examples below.
  354. Parameters
  355. ----------
  356. u_for_edge, v_for_edge : nodes
  357. Nodes can be, for example, strings or numbers.
  358. Nodes must be hashable (and not None) Python objects.
  359. key : hashable identifier, optional (default=lowest unused integer)
  360. Used to distinguish multiedges between a pair of nodes.
  361. attr : keyword arguments, optional
  362. Edge data (or labels or objects) can be assigned using
  363. keyword arguments.
  364. Returns
  365. -------
  366. The edge key assigned to the edge.
  367. See Also
  368. --------
  369. add_edges_from : add a collection of edges
  370. Notes
  371. -----
  372. To replace/update edge data, use the optional key argument
  373. to identify a unique edge. Otherwise a new edge will be created.
  374. NetworkX algorithms designed for weighted graphs cannot use
  375. multigraphs directly because it is not clear how to handle
  376. multiedge weights. Convert to Graph using edge attribute
  377. 'weight' to enable weighted graph algorithms.
  378. Default keys are generated using the method `new_edge_key()`.
  379. This method can be overridden by subclassing the base class and
  380. providing a custom `new_edge_key()` method.
  381. Examples
  382. --------
  383. The following each add an additional edge e=(1, 2) to graph G:
  384. >>> G = nx.MultiGraph()
  385. >>> e = (1, 2)
  386. >>> ekey = G.add_edge(1, 2) # explicit two-node form
  387. >>> G.add_edge(*e) # single edge as tuple of two nodes
  388. 1
  389. >>> G.add_edges_from([(1, 2)]) # add edges from iterable container
  390. [2]
  391. Associate data to edges using keywords:
  392. >>> ekey = G.add_edge(1, 2, weight=3)
  393. >>> ekey = G.add_edge(1, 2, key=0, weight=4) # update data for key=0
  394. >>> ekey = G.add_edge(1, 3, weight=7, capacity=15, length=342.7)
  395. For non-string attribute keys, use subscript notation.
  396. >>> ekey = G.add_edge(1, 2)
  397. >>> G[1][2][0].update({0: 5})
  398. >>> G.edges[1, 2, 0].update({0: 5})
  399. """
  400. u, v = u_for_edge, v_for_edge
  401. # add nodes
  402. if u not in self._adj:
  403. if u is None:
  404. raise ValueError("None cannot be a node")
  405. self._adj[u] = self.adjlist_inner_dict_factory()
  406. self._node[u] = self.node_attr_dict_factory()
  407. if v not in self._adj:
  408. if v is None:
  409. raise ValueError("None cannot be a node")
  410. self._adj[v] = self.adjlist_inner_dict_factory()
  411. self._node[v] = self.node_attr_dict_factory()
  412. if key is None:
  413. key = self.new_edge_key(u, v)
  414. if v in self._adj[u]:
  415. keydict = self._adj[u][v]
  416. datadict = keydict.get(key, self.edge_attr_dict_factory())
  417. datadict.update(attr)
  418. keydict[key] = datadict
  419. else:
  420. # selfloops work this way without special treatment
  421. datadict = self.edge_attr_dict_factory()
  422. datadict.update(attr)
  423. keydict = self.edge_key_dict_factory()
  424. keydict[key] = datadict
  425. self._adj[u][v] = keydict
  426. self._adj[v][u] = keydict
  427. nx._clear_cache(self)
  428. return key
  429. def add_edges_from(self, ebunch_to_add, **attr):
  430. """Add all the edges in ebunch_to_add.
  431. Parameters
  432. ----------
  433. ebunch_to_add : container of edges
  434. Each edge given in the container will be added to the
  435. graph. The edges can be:
  436. - 2-tuples (u, v) or
  437. - 3-tuples (u, v, d) for an edge data dict d, or
  438. - 3-tuples (u, v, k) for not iterable key k, or
  439. - 4-tuples (u, v, k, d) for an edge with data and key k
  440. attr : keyword arguments, optional
  441. Edge data (or labels or objects) can be assigned using
  442. keyword arguments.
  443. Returns
  444. -------
  445. A list of edge keys assigned to the edges in `ebunch`.
  446. See Also
  447. --------
  448. add_edge : add a single edge
  449. add_weighted_edges_from : convenient way to add weighted edges
  450. Notes
  451. -----
  452. Adding the same edge twice has no effect but any edge data
  453. will be updated when each duplicate edge is added.
  454. Edge attributes specified in an ebunch take precedence over
  455. attributes specified via keyword arguments.
  456. Default keys are generated using the method ``new_edge_key()``.
  457. This method can be overridden by subclassing the base class and
  458. providing a custom ``new_edge_key()`` method.
  459. When adding edges from an iterator over the graph you are changing,
  460. a `RuntimeError` can be raised with message:
  461. `RuntimeError: dictionary changed size during iteration`. This
  462. happens when the graph's underlying dictionary is modified during
  463. iteration. To avoid this error, evaluate the iterator into a separate
  464. object, e.g. by using `list(iterator_of_edges)`, and pass this
  465. object to `G.add_edges_from`.
  466. Examples
  467. --------
  468. >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
  469. >>> G.add_edges_from([(0, 1), (1, 2)]) # using a list of edge tuples
  470. >>> e = zip(range(0, 3), range(1, 4))
  471. >>> G.add_edges_from(e) # Add the path graph 0-1-2-3
  472. Associate data to edges
  473. >>> G.add_edges_from([(1, 2), (2, 3)], weight=3)
  474. >>> G.add_edges_from([(3, 4), (1, 4)], label="WN2898")
  475. Evaluate an iterator over a graph if using it to modify the same graph
  476. >>> G = nx.MultiGraph([(1, 2), (2, 3), (3, 4)])
  477. >>> # Grow graph by one new node, adding edges to all existing nodes.
  478. >>> # wrong way - will raise RuntimeError
  479. >>> # G.add_edges_from(((5, n) for n in G.nodes))
  480. >>> # right way - note that there will be no self-edge for node 5
  481. >>> assigned_keys = G.add_edges_from(list((5, n) for n in G.nodes))
  482. """
  483. keylist = []
  484. for e in ebunch_to_add:
  485. ne = len(e)
  486. if ne == 4:
  487. u, v, key, dd = e
  488. elif ne == 3:
  489. u, v, dd = e
  490. key = None
  491. elif ne == 2:
  492. u, v = e
  493. dd = {}
  494. key = None
  495. else:
  496. msg = f"Edge tuple {e} must be a 2-tuple, 3-tuple or 4-tuple."
  497. raise NetworkXError(msg)
  498. ddd = {}
  499. ddd.update(attr)
  500. try:
  501. ddd.update(dd)
  502. except (TypeError, ValueError):
  503. if ne != 3:
  504. raise
  505. key = dd # ne == 3 with 3rd value not dict, must be a key
  506. key = self.add_edge(u, v, key)
  507. self[u][v][key].update(ddd)
  508. keylist.append(key)
  509. nx._clear_cache(self)
  510. return keylist
  511. def remove_edge(self, u, v, key=None):
  512. """Remove an edge between u and v.
  513. Parameters
  514. ----------
  515. u, v : nodes
  516. Remove an edge between nodes u and v.
  517. key : hashable identifier, optional (default=None)
  518. Used to distinguish multiple edges between a pair of nodes.
  519. If None, remove a single edge between u and v. If there are
  520. multiple edges, removes the last edge added in terms of
  521. insertion order.
  522. Raises
  523. ------
  524. NetworkXError
  525. If there is not an edge between u and v, or
  526. if there is no edge with the specified key.
  527. See Also
  528. --------
  529. remove_edges_from : remove a collection of edges
  530. Examples
  531. --------
  532. >>> G = nx.MultiGraph()
  533. >>> nx.add_path(G, [0, 1, 2, 3])
  534. >>> G.remove_edge(0, 1)
  535. >>> e = (1, 2)
  536. >>> G.remove_edge(*e) # unpacks e from an edge tuple
  537. For multiple edges
  538. >>> G = nx.MultiGraph() # or MultiDiGraph, etc
  539. >>> G.add_edges_from([(1, 2), (1, 2), (1, 2)]) # key_list returned
  540. [0, 1, 2]
  541. When ``key=None`` (the default), edges are removed in the opposite
  542. order that they were added:
  543. >>> G.remove_edge(1, 2)
  544. >>> G.edges(keys=True)
  545. MultiEdgeView([(1, 2, 0), (1, 2, 1)])
  546. >>> G.remove_edge(2, 1) # edges are not directed
  547. >>> G.edges(keys=True)
  548. MultiEdgeView([(1, 2, 0)])
  549. For edges with keys
  550. >>> G = nx.MultiGraph()
  551. >>> G.add_edge(1, 2, key="first")
  552. 'first'
  553. >>> G.add_edge(1, 2, key="second")
  554. 'second'
  555. >>> G.remove_edge(1, 2, key="first")
  556. >>> G.edges(keys=True)
  557. MultiEdgeView([(1, 2, 'second')])
  558. """
  559. try:
  560. d = self._adj[u][v]
  561. except KeyError as err:
  562. raise NetworkXError(f"The edge {u}-{v} is not in the graph.") from err
  563. # remove the edge with specified data
  564. if key is None:
  565. d.popitem()
  566. else:
  567. try:
  568. del d[key]
  569. except KeyError as err:
  570. msg = f"The edge {u}-{v} with key {key} is not in the graph."
  571. raise NetworkXError(msg) from err
  572. if len(d) == 0:
  573. # remove the key entries if last edge
  574. del self._adj[u][v]
  575. if u != v: # check for selfloop
  576. del self._adj[v][u]
  577. nx._clear_cache(self)
  578. def remove_edges_from(self, ebunch):
  579. """Remove all edges specified in ebunch.
  580. Parameters
  581. ----------
  582. ebunch: list or container of edge tuples
  583. Each edge given in the list or container will be removed
  584. from the graph. The edges can be:
  585. - 2-tuples (u, v) A single edge between u and v is removed.
  586. - 3-tuples (u, v, key) The edge identified by key is removed.
  587. - 4-tuples (u, v, key, data) where data is ignored.
  588. See Also
  589. --------
  590. remove_edge : remove a single edge
  591. Notes
  592. -----
  593. Will fail silently if an edge in ebunch is not in the graph.
  594. Examples
  595. --------
  596. >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
  597. >>> ebunch = [(1, 2), (2, 3)]
  598. >>> G.remove_edges_from(ebunch)
  599. Removing multiple copies of edges
  600. >>> G = nx.MultiGraph()
  601. >>> keys = G.add_edges_from([(1, 2), (1, 2), (1, 2)])
  602. >>> G.remove_edges_from([(1, 2), (2, 1)]) # edges aren't directed
  603. >>> list(G.edges())
  604. [(1, 2)]
  605. >>> G.remove_edges_from([(1, 2), (1, 2)]) # silently ignore extra copy
  606. >>> list(G.edges) # now empty graph
  607. []
  608. When the edge is a 2-tuple ``(u, v)`` but there are multiple edges between
  609. u and v in the graph, the most recent edge (in terms of insertion
  610. order) is removed.
  611. >>> G = nx.MultiGraph()
  612. >>> for key in ("x", "y", "a"):
  613. ... k = G.add_edge(0, 1, key=key)
  614. >>> G.edges(keys=True)
  615. MultiEdgeView([(0, 1, 'x'), (0, 1, 'y'), (0, 1, 'a')])
  616. >>> G.remove_edges_from([(0, 1)])
  617. >>> G.edges(keys=True)
  618. MultiEdgeView([(0, 1, 'x'), (0, 1, 'y')])
  619. """
  620. for e in ebunch:
  621. try:
  622. self.remove_edge(*e[:3])
  623. except NetworkXError:
  624. pass
  625. nx._clear_cache(self)
  626. def has_edge(self, u, v, key=None):
  627. """Returns True if the graph has an edge between nodes u and v.
  628. This is the same as `v in G[u] or key in G[u][v]`
  629. without KeyError exceptions.
  630. Parameters
  631. ----------
  632. u, v : nodes
  633. Nodes can be, for example, strings or numbers.
  634. key : hashable identifier, optional (default=None)
  635. If specified return True only if the edge with
  636. key is found.
  637. Returns
  638. -------
  639. edge_ind : bool
  640. True if edge is in the graph, False otherwise.
  641. Examples
  642. --------
  643. Can be called either using two nodes u, v, an edge tuple (u, v),
  644. or an edge tuple (u, v, key).
  645. >>> G = nx.MultiGraph() # or MultiDiGraph
  646. >>> nx.add_path(G, [0, 1, 2, 3])
  647. >>> G.has_edge(0, 1) # using two nodes
  648. True
  649. >>> e = (0, 1)
  650. >>> G.has_edge(*e) # e is a 2-tuple (u, v)
  651. True
  652. >>> G.add_edge(0, 1, key="a")
  653. 'a'
  654. >>> G.has_edge(0, 1, key="a") # specify key
  655. True
  656. >>> G.has_edge(1, 0, key="a") # edges aren't directed
  657. True
  658. >>> e = (0, 1, "a")
  659. >>> G.has_edge(*e) # e is a 3-tuple (u, v, 'a')
  660. True
  661. The following syntax are equivalent:
  662. >>> G.has_edge(0, 1)
  663. True
  664. >>> 1 in G[0] # though this gives :exc:`KeyError` if 0 not in G
  665. True
  666. >>> 0 in G[1] # other order; also gives :exc:`KeyError` if 0 not in G
  667. True
  668. """
  669. try:
  670. if key is None:
  671. return v in self._adj[u]
  672. else:
  673. return key in self._adj[u][v]
  674. except KeyError:
  675. return False
  676. @cached_property
  677. def edges(self):
  678. """Returns an iterator over the edges.
  679. edges(self, nbunch=None, data=False, keys=False, default=None)
  680. The MultiEdgeView provides set-like operations on the edge-tuples
  681. as well as edge attribute lookup. When called, it also provides
  682. an EdgeDataView object which allows control of access to edge
  683. attributes (but does not provide set-like operations).
  684. Hence, ``G.edges[u, v, k]['color']`` provides the value of the color
  685. attribute for the edge from ``u`` to ``v`` with key ``k`` while
  686. ``for (u, v, k, c) in G.edges(data='color', keys=True, default="red"):``
  687. iterates through all the edges yielding the color attribute with
  688. default `'red'` if no color attribute exists.
  689. Edges are returned as tuples with optional data and keys
  690. in the order (node, neighbor, key, data). If ``keys=True`` is not
  691. provided, the tuples will just be (node, neighbor, data), but
  692. multiple tuples with the same node and neighbor will be generated
  693. when multiple edges exist between two nodes.
  694. Parameters
  695. ----------
  696. nbunch : single node, container, or all nodes (default= all nodes)
  697. The view will only report edges from these nodes.
  698. data : string or bool, optional (default=False)
  699. The edge attribute returned in 3-tuple (u, v, ddict[data]).
  700. If True, return edge attribute dict in 3-tuple (u, v, ddict).
  701. If False, return 2-tuple (u, v).
  702. keys : bool, optional (default=False)
  703. If True, return edge keys with each edge, creating (u, v, k)
  704. tuples or (u, v, k, d) tuples if data is also requested.
  705. default : value, optional (default=None)
  706. Value used for edges that don't have the requested attribute.
  707. Only relevant if data is not True or False.
  708. Returns
  709. -------
  710. edges : MultiEdgeView
  711. A view of edge attributes, usually it iterates over (u, v)
  712. (u, v, k) or (u, v, k, d) tuples of edges, but can also be
  713. used for attribute lookup as ``edges[u, v, k]['foo']``.
  714. Notes
  715. -----
  716. Nodes in nbunch that are not in the graph will be (quietly) ignored.
  717. For directed graphs this returns the out-edges.
  718. Examples
  719. --------
  720. >>> G = nx.MultiGraph()
  721. >>> nx.add_path(G, [0, 1, 2])
  722. >>> key = G.add_edge(2, 3, weight=5)
  723. >>> key2 = G.add_edge(2, 1, weight=2) # multi-edge
  724. >>> [e for e in G.edges()]
  725. [(0, 1), (1, 2), (1, 2), (2, 3)]
  726. >>> G.edges.data() # default data is {} (empty dict)
  727. MultiEdgeDataView([(0, 1, {}), (1, 2, {}), (1, 2, {'weight': 2}), (2, 3, {'weight': 5})])
  728. >>> G.edges.data("weight", default=1)
  729. MultiEdgeDataView([(0, 1, 1), (1, 2, 1), (1, 2, 2), (2, 3, 5)])
  730. >>> G.edges(keys=True) # default keys are integers
  731. MultiEdgeView([(0, 1, 0), (1, 2, 0), (1, 2, 1), (2, 3, 0)])
  732. >>> G.edges.data(keys=True)
  733. MultiEdgeDataView([(0, 1, 0, {}), (1, 2, 0, {}), (1, 2, 1, {'weight': 2}), (2, 3, 0, {'weight': 5})])
  734. >>> G.edges.data("weight", default=1, keys=True)
  735. MultiEdgeDataView([(0, 1, 0, 1), (1, 2, 0, 1), (1, 2, 1, 2), (2, 3, 0, 5)])
  736. >>> G.edges([0, 3]) # Note ordering of tuples from listed sources
  737. MultiEdgeDataView([(0, 1), (3, 2)])
  738. >>> G.edges([0, 3, 2, 1]) # Note ordering of tuples
  739. MultiEdgeDataView([(0, 1), (3, 2), (2, 1), (2, 1)])
  740. >>> G.edges(0)
  741. MultiEdgeDataView([(0, 1)])
  742. """
  743. return MultiEdgeView(self)
  744. def get_edge_data(self, u, v, key=None, default=None):
  745. """Returns the attribute dictionary associated with edge (u, v,
  746. key).
  747. If a key is not provided, returns a dictionary mapping edge keys
  748. to attribute dictionaries for each edge between u and v.
  749. This is identical to `G[u][v][key]` except the default is returned
  750. instead of an exception is the edge doesn't exist.
  751. Parameters
  752. ----------
  753. u, v : nodes
  754. default : any Python object (default=None)
  755. Value to return if the specific edge (u, v, key) is not
  756. found, OR if there are no edges between u and v and no key
  757. is specified.
  758. key : hashable identifier, optional (default=None)
  759. Return data only for the edge with specified key, as an
  760. attribute dictionary (rather than a dictionary mapping keys
  761. to attribute dictionaries).
  762. Returns
  763. -------
  764. edge_dict : dictionary
  765. The edge attribute dictionary, OR a dictionary mapping edge
  766. keys to attribute dictionaries for each of those edges if no
  767. specific key is provided (even if there's only one edge
  768. between u and v).
  769. Examples
  770. --------
  771. >>> G = nx.MultiGraph() # or MultiDiGraph
  772. >>> key = G.add_edge(0, 1, key="a", weight=7)
  773. >>> G[0][1]["a"] # key='a'
  774. {'weight': 7}
  775. >>> G.edges[0, 1, "a"] # key='a'
  776. {'weight': 7}
  777. Warning: we protect the graph data structure by making
  778. `G.edges` and `G[1][2]` read-only dict-like structures.
  779. However, you can assign values to attributes in e.g.
  780. `G.edges[1, 2, 'a']` or `G[1][2]['a']` using an additional
  781. bracket as shown next. You need to specify all edge info
  782. to assign to the edge data associated with an edge.
  783. >>> G[0][1]["a"]["weight"] = 10
  784. >>> G.edges[0, 1, "a"]["weight"] = 10
  785. >>> G[0][1]["a"]["weight"]
  786. 10
  787. >>> G.edges[1, 0, "a"]["weight"]
  788. 10
  789. >>> G = nx.MultiGraph() # or MultiDiGraph
  790. >>> nx.add_path(G, [0, 1, 2, 3])
  791. >>> G.edges[0, 1, 0]["weight"] = 5
  792. >>> G.get_edge_data(0, 1)
  793. {0: {'weight': 5}}
  794. >>> e = (0, 1)
  795. >>> G.get_edge_data(*e) # tuple form
  796. {0: {'weight': 5}}
  797. >>> G.get_edge_data(3, 0) # edge not in graph, returns None
  798. >>> G.get_edge_data(3, 0, default=0) # edge not in graph, return default
  799. 0
  800. >>> G.get_edge_data(1, 0, 0) # specific key gives back
  801. {'weight': 5}
  802. """
  803. try:
  804. if key is None:
  805. return self._adj[u][v]
  806. else:
  807. return self._adj[u][v][key]
  808. except KeyError:
  809. return default
  810. @cached_property
  811. def degree(self):
  812. """A DegreeView for the Graph as G.degree or G.degree().
  813. The node degree is the number of edges adjacent to the node.
  814. The weighted node degree is the sum of the edge weights for
  815. edges incident to that node.
  816. This object provides an iterator for (node, degree) as well as
  817. lookup for the degree for a single node.
  818. Parameters
  819. ----------
  820. nbunch : single node, container, or all nodes (default= all nodes)
  821. The view will only report edges incident to these nodes.
  822. weight : string or None, optional (default=None)
  823. The name of an edge attribute that holds the numerical value used
  824. as a weight. If None, then each edge has weight 1.
  825. The degree is the sum of the edge weights adjacent to the node.
  826. Returns
  827. -------
  828. MultiDegreeView or int
  829. If multiple nodes are requested (the default), returns a `MultiDegreeView`
  830. mapping nodes to their degree.
  831. If a single node is requested, returns the degree of the node as an integer.
  832. Examples
  833. --------
  834. >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
  835. >>> nx.add_path(G, [0, 1, 2, 3])
  836. >>> G.degree(0) # node 0 with degree 1
  837. 1
  838. >>> list(G.degree([0, 1]))
  839. [(0, 1), (1, 2)]
  840. """
  841. return MultiDegreeView(self)
  842. def is_multigraph(self):
  843. """Returns True if graph is a multigraph, False otherwise."""
  844. return True
  845. def is_directed(self):
  846. """Returns True if graph is directed, False otherwise."""
  847. return False
  848. def copy(self, as_view=False):
  849. """Returns a copy of the graph.
  850. The copy method by default returns an independent shallow copy
  851. of the graph and attributes. That is, if an attribute is a
  852. container, that container is shared by the original an the copy.
  853. Use Python's `copy.deepcopy` for new containers.
  854. If `as_view` is True then a view is returned instead of a copy.
  855. Notes
  856. -----
  857. All copies reproduce the graph structure, but data attributes
  858. may be handled in different ways. There are four types of copies
  859. of a graph that people might want.
  860. Deepcopy -- A "deepcopy" copies the graph structure as well as
  861. all data attributes and any objects they might contain.
  862. The entire graph object is new so that changes in the copy
  863. do not affect the original object. (see Python's copy.deepcopy)
  864. Data Reference (Shallow) -- For a shallow copy the graph structure
  865. is copied but the edge, node and graph attribute dicts are
  866. references to those in the original graph. This saves
  867. time and memory but could cause confusion if you change an attribute
  868. in one graph and it changes the attribute in the other.
  869. NetworkX does not provide this level of shallow copy.
  870. Independent Shallow -- This copy creates new independent attribute
  871. dicts and then does a shallow copy of the attributes. That is, any
  872. attributes that are containers are shared between the new graph
  873. and the original. This is exactly what `dict.copy()` provides.
  874. You can obtain this style copy using:
  875. >>> G = nx.path_graph(5)
  876. >>> H = G.copy()
  877. >>> H = G.copy(as_view=False)
  878. >>> H = nx.Graph(G)
  879. >>> H = G.__class__(G)
  880. Fresh Data -- For fresh data, the graph structure is copied while
  881. new empty data attribute dicts are created. The resulting graph
  882. is independent of the original and it has no edge, node or graph
  883. attributes. Fresh copies are not enabled. Instead use:
  884. >>> H = G.__class__()
  885. >>> H.add_nodes_from(G)
  886. >>> H.add_edges_from(G.edges)
  887. View -- Inspired by dict-views, graph-views act like read-only
  888. versions of the original graph, providing a copy of the original
  889. structure without requiring any memory for copying the information.
  890. See the Python copy module for more information on shallow
  891. and deep copies, https://docs.python.org/3/library/copy.html.
  892. Parameters
  893. ----------
  894. as_view : bool, optional (default=False)
  895. If True, the returned graph-view provides a read-only view
  896. of the original graph without actually copying any data.
  897. Returns
  898. -------
  899. G : Graph
  900. A copy of the graph.
  901. See Also
  902. --------
  903. to_directed: return a directed copy of the graph.
  904. Examples
  905. --------
  906. >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
  907. >>> H = G.copy()
  908. """
  909. if as_view is True:
  910. return nx.graphviews.generic_graph_view(self)
  911. G = self.__class__()
  912. G.graph.update(self.graph)
  913. G.add_nodes_from((n, d.copy()) for n, d in self._node.items())
  914. G.add_edges_from(
  915. (u, v, key, datadict.copy())
  916. for u, nbrs in self._adj.items()
  917. for v, keydict in nbrs.items()
  918. for key, datadict in keydict.items()
  919. )
  920. return G
  921. def to_directed(self, as_view=False):
  922. """Returns a directed representation of the graph.
  923. Returns
  924. -------
  925. G : MultiDiGraph
  926. A directed graph with the same name, same nodes, and with
  927. each edge (u, v, k, data) replaced by two directed edges
  928. (u, v, k, data) and (v, u, k, data).
  929. Notes
  930. -----
  931. This returns a "deepcopy" of the edge, node, and
  932. graph attributes which attempts to completely copy
  933. all of the data and references.
  934. This is in contrast to the similar D=MultiDiGraph(G) which
  935. returns a shallow copy of the data.
  936. See the Python copy module for more information on shallow
  937. and deep copies, https://docs.python.org/3/library/copy.html.
  938. Warning: If you have subclassed MultiGraph to use dict-like objects
  939. in the data structure, those changes do not transfer to the
  940. MultiDiGraph created by this method.
  941. Examples
  942. --------
  943. >>> G = nx.MultiGraph()
  944. >>> G.add_edge(0, 1)
  945. 0
  946. >>> G.add_edge(0, 1)
  947. 1
  948. >>> H = G.to_directed()
  949. >>> list(H.edges)
  950. [(0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1)]
  951. If already directed, return a (deep) copy
  952. >>> G = nx.MultiDiGraph()
  953. >>> G.add_edge(0, 1)
  954. 0
  955. >>> H = G.to_directed()
  956. >>> list(H.edges)
  957. [(0, 1, 0)]
  958. """
  959. graph_class = self.to_directed_class()
  960. if as_view is True:
  961. return nx.graphviews.generic_graph_view(self, graph_class)
  962. # deepcopy when not a view
  963. G = graph_class()
  964. G.graph.update(deepcopy(self.graph))
  965. G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
  966. G.add_edges_from(
  967. (u, v, key, deepcopy(datadict))
  968. for u, nbrs in self.adj.items()
  969. for v, keydict in nbrs.items()
  970. for key, datadict in keydict.items()
  971. )
  972. return G
  973. def to_undirected(self, as_view=False):
  974. """Returns an undirected copy of the graph.
  975. Returns
  976. -------
  977. G : Graph/MultiGraph
  978. A deepcopy of the graph.
  979. See Also
  980. --------
  981. copy, add_edge, add_edges_from
  982. Notes
  983. -----
  984. This returns a "deepcopy" of the edge, node, and
  985. graph attributes which attempts to completely copy
  986. all of the data and references.
  987. This is in contrast to the similar `G = nx.MultiGraph(D)`
  988. which returns a shallow copy of the data.
  989. See the Python copy module for more information on shallow
  990. and deep copies, https://docs.python.org/3/library/copy.html.
  991. Warning: If you have subclassed MultiGraph to use dict-like
  992. objects in the data structure, those changes do not transfer
  993. to the MultiGraph created by this method.
  994. Examples
  995. --------
  996. >>> G = nx.MultiGraph([(0, 1), (0, 1), (1, 2)])
  997. >>> H = G.to_directed()
  998. >>> list(H.edges)
  999. [(0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 2, 0), (2, 1, 0)]
  1000. >>> G2 = H.to_undirected()
  1001. >>> list(G2.edges)
  1002. [(0, 1, 0), (0, 1, 1), (1, 2, 0)]
  1003. """
  1004. graph_class = self.to_undirected_class()
  1005. if as_view is True:
  1006. return nx.graphviews.generic_graph_view(self, graph_class)
  1007. # deepcopy when not a view
  1008. G = graph_class()
  1009. G.graph.update(deepcopy(self.graph))
  1010. G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
  1011. G.add_edges_from(
  1012. (u, v, key, deepcopy(datadict))
  1013. for u, nbrs in self._adj.items()
  1014. for v, keydict in nbrs.items()
  1015. for key, datadict in keydict.items()
  1016. )
  1017. return G
  1018. def number_of_edges(self, u=None, v=None):
  1019. """Returns the number of edges between two nodes.
  1020. Parameters
  1021. ----------
  1022. u, v : nodes, optional (Default=all edges)
  1023. If u and v are specified, return the number of edges between
  1024. u and v. Otherwise return the total number of all edges.
  1025. Returns
  1026. -------
  1027. nedges : int
  1028. The number of edges in the graph. If nodes `u` and `v` are
  1029. specified return the number of edges between those nodes. If
  1030. the graph is directed, this only returns the number of edges
  1031. from `u` to `v`.
  1032. See Also
  1033. --------
  1034. size
  1035. Examples
  1036. --------
  1037. For undirected multigraphs, this method counts the total number
  1038. of edges in the graph::
  1039. >>> G = nx.MultiGraph()
  1040. >>> G.add_edges_from([(0, 1), (0, 1), (1, 2)])
  1041. [0, 1, 0]
  1042. >>> G.number_of_edges()
  1043. 3
  1044. If you specify two nodes, this counts the total number of edges
  1045. joining the two nodes::
  1046. >>> G.number_of_edges(0, 1)
  1047. 2
  1048. For directed multigraphs, this method can count the total number
  1049. of directed edges from `u` to `v`::
  1050. >>> G = nx.MultiDiGraph()
  1051. >>> G.add_edges_from([(0, 1), (0, 1), (1, 0)])
  1052. [0, 1, 0]
  1053. >>> G.number_of_edges(0, 1)
  1054. 2
  1055. >>> G.number_of_edges(1, 0)
  1056. 1
  1057. """
  1058. if u is None:
  1059. return self.size()
  1060. try:
  1061. edgedata = self._adj[u][v]
  1062. except KeyError:
  1063. return 0 # no such edge
  1064. return len(edgedata)