multigraph.py 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278
  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. def __init__(self, incoming_graph_data=None, multigraph_input=None, **attr):
  238. """Initialize a graph with edges, name, or graph attributes.
  239. Parameters
  240. ----------
  241. incoming_graph_data : input graph
  242. Data to initialize graph. If incoming_graph_data=None (default)
  243. an empty graph is created. The data can be an edge list, or any
  244. NetworkX graph object. If the corresponding optional Python
  245. packages are installed the data can also be a 2D NumPy array, a
  246. SciPy sparse array, or a PyGraphviz graph.
  247. multigraph_input : bool or None (default None)
  248. Note: Only used when `incoming_graph_data` is a dict.
  249. If True, `incoming_graph_data` is assumed to be a
  250. dict-of-dict-of-dict-of-dict structure keyed by
  251. node to neighbor to edge keys to edge data for multi-edges.
  252. A NetworkXError is raised if this is not the case.
  253. If False, :func:`to_networkx_graph` is used to try to determine
  254. the dict's graph data structure as either a dict-of-dict-of-dict
  255. keyed by node to neighbor to edge data, or a dict-of-iterable
  256. keyed by node to neighbors.
  257. If None, the treatment for True is tried, but if it fails,
  258. the treatment for False is tried.
  259. attr : keyword arguments, optional (default= no attributes)
  260. Attributes to add to graph as key=value pairs.
  261. See Also
  262. --------
  263. convert
  264. Examples
  265. --------
  266. >>> G = nx.MultiGraph()
  267. >>> G = nx.MultiGraph(name="my graph")
  268. >>> e = [(1, 2), (1, 2), (2, 3), (3, 4)] # list of edges
  269. >>> G = nx.MultiGraph(e)
  270. Arbitrary graph attribute pairs (key=value) may be assigned
  271. >>> G = nx.MultiGraph(e, day="Friday")
  272. >>> G.graph
  273. {'day': 'Friday'}
  274. """
  275. # multigraph_input can be None/True/False. So check "is not False"
  276. if isinstance(incoming_graph_data, dict) and multigraph_input is not False:
  277. Graph.__init__(self)
  278. try:
  279. convert.from_dict_of_dicts(
  280. incoming_graph_data, create_using=self, multigraph_input=True
  281. )
  282. self.graph.update(attr)
  283. except Exception as err:
  284. if multigraph_input is True:
  285. raise nx.NetworkXError(
  286. f"converting multigraph_input raised:\n{type(err)}: {err}"
  287. )
  288. Graph.__init__(self, incoming_graph_data, **attr)
  289. else:
  290. Graph.__init__(self, incoming_graph_data, **attr)
  291. @cached_property
  292. def adj(self):
  293. """Graph adjacency object holding the neighbors of each node.
  294. This object is a read-only dict-like structure with node keys
  295. and neighbor-dict values. The neighbor-dict is keyed by neighbor
  296. to the edgekey-data-dict. So `G.adj[3][2][0]['color'] = 'blue'` sets
  297. the color of the edge `(3, 2, 0)` to `"blue"`.
  298. Iterating over G.adj behaves like a dict. Useful idioms include
  299. `for nbr, edgesdict in G.adj[n].items():`.
  300. The neighbor information is also provided by subscripting the graph.
  301. Examples
  302. --------
  303. >>> e = [(1, 2), (1, 2), (1, 3), (3, 4)] # list of edges
  304. >>> G = nx.MultiGraph(e)
  305. >>> G.edges[1, 2, 0]["weight"] = 3
  306. >>> result = set()
  307. >>> for edgekey, data in G[1][2].items():
  308. ... result.add(data.get('weight', 1))
  309. >>> result
  310. {1, 3}
  311. For directed graphs, `G.adj` holds outgoing (successor) info.
  312. """
  313. return MultiAdjacencyView(self._adj)
  314. def new_edge_key(self, u, v):
  315. """Returns an unused key for edges between nodes `u` and `v`.
  316. The nodes `u` and `v` do not need to be already in the graph.
  317. Notes
  318. -----
  319. In the standard MultiGraph class the new key is the number of existing
  320. edges between `u` and `v` (increased if necessary to ensure unused).
  321. The first edge will have key 0, then 1, etc. If an edge is removed
  322. further new_edge_keys may not be in this order.
  323. Parameters
  324. ----------
  325. u, v : nodes
  326. Returns
  327. -------
  328. key : int
  329. """
  330. try:
  331. keydict = self._adj[u][v]
  332. except KeyError:
  333. return 0
  334. key = len(keydict)
  335. while key in keydict:
  336. key += 1
  337. return key
  338. def add_edge(self, u_for_edge, v_for_edge, key=None, **attr):
  339. """Add an edge between u and v.
  340. The nodes u and v will be automatically added if they are
  341. not already in the graph.
  342. Edge attributes can be specified with keywords or by directly
  343. accessing the edge's attribute dictionary. See examples below.
  344. Parameters
  345. ----------
  346. u_for_edge, v_for_edge : nodes
  347. Nodes can be, for example, strings or numbers.
  348. Nodes must be hashable (and not None) Python objects.
  349. key : hashable identifier, optional (default=lowest unused integer)
  350. Used to distinguish multiedges between a pair of nodes.
  351. attr : keyword arguments, optional
  352. Edge data (or labels or objects) can be assigned using
  353. keyword arguments.
  354. Returns
  355. -------
  356. The edge key assigned to the edge.
  357. See Also
  358. --------
  359. add_edges_from : add a collection of edges
  360. Notes
  361. -----
  362. To replace/update edge data, use the optional key argument
  363. to identify a unique edge. Otherwise a new edge will be created.
  364. NetworkX algorithms designed for weighted graphs cannot use
  365. multigraphs directly because it is not clear how to handle
  366. multiedge weights. Convert to Graph using edge attribute
  367. 'weight' to enable weighted graph algorithms.
  368. Default keys are generated using the method `new_edge_key()`.
  369. This method can be overridden by subclassing the base class and
  370. providing a custom `new_edge_key()` method.
  371. Examples
  372. --------
  373. The following each add an additional edge e=(1, 2) to graph G:
  374. >>> G = nx.MultiGraph()
  375. >>> e = (1, 2)
  376. >>> ekey = G.add_edge(1, 2) # explicit two-node form
  377. >>> G.add_edge(*e) # single edge as tuple of two nodes
  378. 1
  379. >>> G.add_edges_from([(1, 2)]) # add edges from iterable container
  380. [2]
  381. Associate data to edges using keywords:
  382. >>> ekey = G.add_edge(1, 2, weight=3)
  383. >>> ekey = G.add_edge(1, 2, key=0, weight=4) # update data for key=0
  384. >>> ekey = G.add_edge(1, 3, weight=7, capacity=15, length=342.7)
  385. For non-string attribute keys, use subscript notation.
  386. >>> ekey = G.add_edge(1, 2)
  387. >>> G[1][2][0].update({0: 5})
  388. >>> G.edges[1, 2, 0].update({0: 5})
  389. """
  390. u, v = u_for_edge, v_for_edge
  391. # add nodes
  392. if u not in self._adj:
  393. if u is None:
  394. raise ValueError("None cannot be a node")
  395. self._adj[u] = self.adjlist_inner_dict_factory()
  396. self._node[u] = self.node_attr_dict_factory()
  397. if v not in self._adj:
  398. if v is None:
  399. raise ValueError("None cannot be a node")
  400. self._adj[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._adj[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._adj[u][v] = keydict
  416. self._adj[v][u] = keydict
  417. return key
  418. def add_edges_from(self, ebunch_to_add, **attr):
  419. """Add all the edges in ebunch_to_add.
  420. Parameters
  421. ----------
  422. ebunch_to_add : container of edges
  423. Each edge given in the container will be added to the
  424. graph. The edges can be:
  425. - 2-tuples (u, v) or
  426. - 3-tuples (u, v, d) for an edge data dict d, or
  427. - 3-tuples (u, v, k) for not iterable key k, or
  428. - 4-tuples (u, v, k, d) for an edge with data and key k
  429. attr : keyword arguments, optional
  430. Edge data (or labels or objects) can be assigned using
  431. keyword arguments.
  432. Returns
  433. -------
  434. A list of edge keys assigned to the edges in `ebunch`.
  435. See Also
  436. --------
  437. add_edge : add a single edge
  438. add_weighted_edges_from : convenient way to add weighted edges
  439. Notes
  440. -----
  441. Adding the same edge twice has no effect but any edge data
  442. will be updated when each duplicate edge is added.
  443. Edge attributes specified in an ebunch take precedence over
  444. attributes specified via keyword arguments.
  445. Default keys are generated using the method ``new_edge_key()``.
  446. This method can be overridden by subclassing the base class and
  447. providing a custom ``new_edge_key()`` method.
  448. When adding edges from an iterator over the graph you are changing,
  449. a `RuntimeError` can be raised with message:
  450. `RuntimeError: dictionary changed size during iteration`. This
  451. happens when the graph's underlying dictionary is modified during
  452. iteration. To avoid this error, evaluate the iterator into a separate
  453. object, e.g. by using `list(iterator_of_edges)`, and pass this
  454. object to `G.add_edges_from`.
  455. Examples
  456. --------
  457. >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
  458. >>> G.add_edges_from([(0, 1), (1, 2)]) # using a list of edge tuples
  459. >>> e = zip(range(0, 3), range(1, 4))
  460. >>> G.add_edges_from(e) # Add the path graph 0-1-2-3
  461. Associate data to edges
  462. >>> G.add_edges_from([(1, 2), (2, 3)], weight=3)
  463. >>> G.add_edges_from([(3, 4), (1, 4)], label="WN2898")
  464. Evaluate an iterator over a graph if using it to modify the same graph
  465. >>> G = nx.MultiGraph([(1, 2), (2, 3), (3, 4)])
  466. >>> # Grow graph by one new node, adding edges to all existing nodes.
  467. >>> # wrong way - will raise RuntimeError
  468. >>> # G.add_edges_from(((5, n) for n in G.nodes))
  469. >>> # right way - note that there will be no self-edge for node 5
  470. >>> assigned_keys = G.add_edges_from(list((5, n) for n in G.nodes))
  471. """
  472. keylist = []
  473. for e in ebunch_to_add:
  474. ne = len(e)
  475. if ne == 4:
  476. u, v, key, dd = e
  477. elif ne == 3:
  478. u, v, dd = e
  479. key = None
  480. elif ne == 2:
  481. u, v = e
  482. dd = {}
  483. key = None
  484. else:
  485. msg = f"Edge tuple {e} must be a 2-tuple, 3-tuple or 4-tuple."
  486. raise NetworkXError(msg)
  487. ddd = {}
  488. ddd.update(attr)
  489. try:
  490. ddd.update(dd)
  491. except (TypeError, ValueError):
  492. if ne != 3:
  493. raise
  494. key = dd # ne == 3 with 3rd value not dict, must be a key
  495. key = self.add_edge(u, v, key)
  496. self[u][v][key].update(ddd)
  497. keylist.append(key)
  498. return keylist
  499. def remove_edge(self, u, v, key=None):
  500. """Remove an edge between u and v.
  501. Parameters
  502. ----------
  503. u, v : nodes
  504. Remove an edge between nodes u and v.
  505. key : hashable identifier, optional (default=None)
  506. Used to distinguish multiple edges between a pair of nodes.
  507. If None, remove a single edge between u and v. If there are
  508. multiple edges, removes the last edge added in terms of
  509. insertion order.
  510. Raises
  511. ------
  512. NetworkXError
  513. If there is not an edge between u and v, or
  514. if there is no edge with the specified key.
  515. See Also
  516. --------
  517. remove_edges_from : remove a collection of edges
  518. Examples
  519. --------
  520. >>> G = nx.MultiGraph()
  521. >>> nx.add_path(G, [0, 1, 2, 3])
  522. >>> G.remove_edge(0, 1)
  523. >>> e = (1, 2)
  524. >>> G.remove_edge(*e) # unpacks e from an edge tuple
  525. For multiple edges
  526. >>> G = nx.MultiGraph() # or MultiDiGraph, etc
  527. >>> G.add_edges_from([(1, 2), (1, 2), (1, 2)]) # key_list returned
  528. [0, 1, 2]
  529. When ``key=None`` (the default), edges are removed in the opposite
  530. order that they were added:
  531. >>> G.remove_edge(1, 2)
  532. >>> G.edges(keys=True)
  533. MultiEdgeView([(1, 2, 0), (1, 2, 1)])
  534. >>> G.remove_edge(2, 1) # edges are not directed
  535. >>> G.edges(keys=True)
  536. MultiEdgeView([(1, 2, 0)])
  537. For edges with keys
  538. >>> G = nx.MultiGraph()
  539. >>> G.add_edge(1, 2, key="first")
  540. 'first'
  541. >>> G.add_edge(1, 2, key="second")
  542. 'second'
  543. >>> G.remove_edge(1, 2, key="first")
  544. >>> G.edges(keys=True)
  545. MultiEdgeView([(1, 2, 'second')])
  546. """
  547. try:
  548. d = self._adj[u][v]
  549. except KeyError as err:
  550. raise NetworkXError(f"The edge {u}-{v} is not in the graph.") from err
  551. # remove the edge with specified data
  552. if key is None:
  553. d.popitem()
  554. else:
  555. try:
  556. del d[key]
  557. except KeyError as err:
  558. msg = f"The edge {u}-{v} with key {key} is not in the graph."
  559. raise NetworkXError(msg) from err
  560. if len(d) == 0:
  561. # remove the key entries if last edge
  562. del self._adj[u][v]
  563. if u != v: # check for selfloop
  564. del self._adj[v][u]
  565. def remove_edges_from(self, ebunch):
  566. """Remove all edges specified in ebunch.
  567. Parameters
  568. ----------
  569. ebunch: list or container of edge tuples
  570. Each edge given in the list or container will be removed
  571. from the graph. The edges can be:
  572. - 2-tuples (u, v) A single edge between u and v is removed.
  573. - 3-tuples (u, v, key) The edge identified by key is removed.
  574. - 4-tuples (u, v, key, data) where data is ignored.
  575. See Also
  576. --------
  577. remove_edge : remove a single edge
  578. Notes
  579. -----
  580. Will fail silently if an edge in ebunch is not in the graph.
  581. Examples
  582. --------
  583. >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
  584. >>> ebunch = [(1, 2), (2, 3)]
  585. >>> G.remove_edges_from(ebunch)
  586. Removing multiple copies of edges
  587. >>> G = nx.MultiGraph()
  588. >>> keys = G.add_edges_from([(1, 2), (1, 2), (1, 2)])
  589. >>> G.remove_edges_from([(1, 2), (2, 1)]) # edges aren't directed
  590. >>> list(G.edges())
  591. [(1, 2)]
  592. >>> G.remove_edges_from([(1, 2), (1, 2)]) # silently ignore extra copy
  593. >>> list(G.edges) # now empty graph
  594. []
  595. When the edge is a 2-tuple ``(u, v)`` but there are multiple edges between
  596. u and v in the graph, the most recent edge (in terms of insertion
  597. order) is removed.
  598. >>> G = nx.MultiGraph()
  599. >>> for key in ("x", "y", "a"):
  600. ... k = G.add_edge(0, 1, key=key)
  601. >>> G.edges(keys=True)
  602. MultiEdgeView([(0, 1, 'x'), (0, 1, 'y'), (0, 1, 'a')])
  603. >>> G.remove_edges_from([(0, 1)])
  604. >>> G.edges(keys=True)
  605. MultiEdgeView([(0, 1, 'x'), (0, 1, 'y')])
  606. """
  607. for e in ebunch:
  608. try:
  609. self.remove_edge(*e[:3])
  610. except NetworkXError:
  611. pass
  612. def has_edge(self, u, v, key=None):
  613. """Returns True if the graph has an edge between nodes u and v.
  614. This is the same as `v in G[u] or key in G[u][v]`
  615. without KeyError exceptions.
  616. Parameters
  617. ----------
  618. u, v : nodes
  619. Nodes can be, for example, strings or numbers.
  620. key : hashable identifier, optional (default=None)
  621. If specified return True only if the edge with
  622. key is found.
  623. Returns
  624. -------
  625. edge_ind : bool
  626. True if edge is in the graph, False otherwise.
  627. Examples
  628. --------
  629. Can be called either using two nodes u, v, an edge tuple (u, v),
  630. or an edge tuple (u, v, key).
  631. >>> G = nx.MultiGraph() # or MultiDiGraph
  632. >>> nx.add_path(G, [0, 1, 2, 3])
  633. >>> G.has_edge(0, 1) # using two nodes
  634. True
  635. >>> e = (0, 1)
  636. >>> G.has_edge(*e) # e is a 2-tuple (u, v)
  637. True
  638. >>> G.add_edge(0, 1, key="a")
  639. 'a'
  640. >>> G.has_edge(0, 1, key="a") # specify key
  641. True
  642. >>> G.has_edge(1, 0, key="a") # edges aren't directed
  643. True
  644. >>> e = (0, 1, "a")
  645. >>> G.has_edge(*e) # e is a 3-tuple (u, v, 'a')
  646. True
  647. The following syntax are equivalent:
  648. >>> G.has_edge(0, 1)
  649. True
  650. >>> 1 in G[0] # though this gives :exc:`KeyError` if 0 not in G
  651. True
  652. >>> 0 in G[1] # other order; also gives :exc:`KeyError` if 0 not in G
  653. True
  654. """
  655. try:
  656. if key is None:
  657. return v in self._adj[u]
  658. else:
  659. return key in self._adj[u][v]
  660. except KeyError:
  661. return False
  662. @cached_property
  663. def edges(self):
  664. """Returns an iterator over the edges.
  665. edges(self, nbunch=None, data=False, keys=False, default=None)
  666. The MultiEdgeView provides set-like operations on the edge-tuples
  667. as well as edge attribute lookup. When called, it also provides
  668. an EdgeDataView object which allows control of access to edge
  669. attributes (but does not provide set-like operations).
  670. Hence, ``G.edges[u, v, k]['color']`` provides the value of the color
  671. attribute for the edge from ``u`` to ``v`` with key ``k`` while
  672. ``for (u, v, k, c) in G.edges(data='color', keys=True, default="red"):``
  673. iterates through all the edges yielding the color attribute with
  674. default `'red'` if no color attribute exists.
  675. Edges are returned as tuples with optional data and keys
  676. in the order (node, neighbor, key, data). If ``keys=True`` is not
  677. provided, the tuples will just be (node, neighbor, data), but
  678. multiple tuples with the same node and neighbor will be generated
  679. when multiple edges exist between two nodes.
  680. Parameters
  681. ----------
  682. nbunch : single node, container, or all nodes (default= all nodes)
  683. The view will only report edges from these nodes.
  684. data : string or bool, optional (default=False)
  685. The edge attribute returned in 3-tuple (u, v, ddict[data]).
  686. If True, return edge attribute dict in 3-tuple (u, v, ddict).
  687. If False, return 2-tuple (u, v).
  688. keys : bool, optional (default=False)
  689. If True, return edge keys with each edge, creating (u, v, k)
  690. tuples or (u, v, k, d) tuples if data is also requested.
  691. default : value, optional (default=None)
  692. Value used for edges that don't have the requested attribute.
  693. Only relevant if data is not True or False.
  694. Returns
  695. -------
  696. edges : MultiEdgeView
  697. A view of edge attributes, usually it iterates over (u, v)
  698. (u, v, k) or (u, v, k, d) tuples of edges, but can also be
  699. used for attribute lookup as ``edges[u, v, k]['foo']``.
  700. Notes
  701. -----
  702. Nodes in nbunch that are not in the graph will be (quietly) ignored.
  703. For directed graphs this returns the out-edges.
  704. Examples
  705. --------
  706. >>> G = nx.MultiGraph()
  707. >>> nx.add_path(G, [0, 1, 2])
  708. >>> key = G.add_edge(2, 3, weight=5)
  709. >>> key2 = G.add_edge(2, 1, weight=2) # multi-edge
  710. >>> [e for e in G.edges()]
  711. [(0, 1), (1, 2), (1, 2), (2, 3)]
  712. >>> G.edges.data() # default data is {} (empty dict)
  713. MultiEdgeDataView([(0, 1, {}), (1, 2, {}), (1, 2, {'weight': 2}), (2, 3, {'weight': 5})])
  714. >>> G.edges.data("weight", default=1)
  715. MultiEdgeDataView([(0, 1, 1), (1, 2, 1), (1, 2, 2), (2, 3, 5)])
  716. >>> G.edges(keys=True) # default keys are integers
  717. MultiEdgeView([(0, 1, 0), (1, 2, 0), (1, 2, 1), (2, 3, 0)])
  718. >>> G.edges.data(keys=True)
  719. MultiEdgeDataView([(0, 1, 0, {}), (1, 2, 0, {}), (1, 2, 1, {'weight': 2}), (2, 3, 0, {'weight': 5})])
  720. >>> G.edges.data("weight", default=1, keys=True)
  721. MultiEdgeDataView([(0, 1, 0, 1), (1, 2, 0, 1), (1, 2, 1, 2), (2, 3, 0, 5)])
  722. >>> G.edges([0, 3]) # Note ordering of tuples from listed sources
  723. MultiEdgeDataView([(0, 1), (3, 2)])
  724. >>> G.edges([0, 3, 2, 1]) # Note ordering of tuples
  725. MultiEdgeDataView([(0, 1), (3, 2), (2, 1), (2, 1)])
  726. >>> G.edges(0)
  727. MultiEdgeDataView([(0, 1)])
  728. """
  729. return MultiEdgeView(self)
  730. def get_edge_data(self, u, v, key=None, default=None):
  731. """Returns the attribute dictionary associated with edge (u, v,
  732. key).
  733. If a key is not provided, returns a dictionary mapping edge keys
  734. to attribute dictionaries for each edge between u and v.
  735. This is identical to `G[u][v][key]` except the default is returned
  736. instead of an exception is the edge doesn't exist.
  737. Parameters
  738. ----------
  739. u, v : nodes
  740. default : any Python object (default=None)
  741. Value to return if the specific edge (u, v, key) is not
  742. found, OR if there are no edges between u and v and no key
  743. is specified.
  744. key : hashable identifier, optional (default=None)
  745. Return data only for the edge with specified key, as an
  746. attribute dictionary (rather than a dictionary mapping keys
  747. to attribute dictionaries).
  748. Returns
  749. -------
  750. edge_dict : dictionary
  751. The edge attribute dictionary, OR a dictionary mapping edge
  752. keys to attribute dictionaries for each of those edges if no
  753. specific key is provided (even if there's only one edge
  754. between u and v).
  755. Examples
  756. --------
  757. >>> G = nx.MultiGraph() # or MultiDiGraph
  758. >>> key = G.add_edge(0, 1, key="a", weight=7)
  759. >>> G[0][1]["a"] # key='a'
  760. {'weight': 7}
  761. >>> G.edges[0, 1, "a"] # key='a'
  762. {'weight': 7}
  763. Warning: we protect the graph data structure by making
  764. `G.edges` and `G[1][2]` read-only dict-like structures.
  765. However, you can assign values to attributes in e.g.
  766. `G.edges[1, 2, 'a']` or `G[1][2]['a']` using an additional
  767. bracket as shown next. You need to specify all edge info
  768. to assign to the edge data associated with an edge.
  769. >>> G[0][1]["a"]["weight"] = 10
  770. >>> G.edges[0, 1, "a"]["weight"] = 10
  771. >>> G[0][1]["a"]["weight"]
  772. 10
  773. >>> G.edges[1, 0, "a"]["weight"]
  774. 10
  775. >>> G = nx.MultiGraph() # or MultiDiGraph
  776. >>> nx.add_path(G, [0, 1, 2, 3])
  777. >>> G.edges[0, 1, 0]["weight"] = 5
  778. >>> G.get_edge_data(0, 1)
  779. {0: {'weight': 5}}
  780. >>> e = (0, 1)
  781. >>> G.get_edge_data(*e) # tuple form
  782. {0: {'weight': 5}}
  783. >>> G.get_edge_data(3, 0) # edge not in graph, returns None
  784. >>> G.get_edge_data(3, 0, default=0) # edge not in graph, return default
  785. 0
  786. >>> G.get_edge_data(1, 0, 0) # specific key gives back
  787. {'weight': 5}
  788. """
  789. try:
  790. if key is None:
  791. return self._adj[u][v]
  792. else:
  793. return self._adj[u][v][key]
  794. except KeyError:
  795. return default
  796. @cached_property
  797. def degree(self):
  798. """A DegreeView for the Graph as G.degree or G.degree().
  799. The node degree is the number of edges adjacent to the node.
  800. The weighted node degree is the sum of the edge weights for
  801. edges incident to that node.
  802. This object provides an iterator for (node, degree) as well as
  803. lookup for the degree for a single node.
  804. Parameters
  805. ----------
  806. nbunch : single node, container, or all nodes (default= all nodes)
  807. The view will only report edges incident to these nodes.
  808. weight : string or None, optional (default=None)
  809. The name of an edge attribute that holds the numerical value used
  810. as a weight. If None, then each edge has weight 1.
  811. The degree is the sum of the edge weights adjacent to the node.
  812. Returns
  813. -------
  814. MultiDegreeView or int
  815. If multiple nodes are requested (the default), returns a `MultiDegreeView`
  816. mapping nodes to their degree.
  817. If a single node is requested, returns the degree of the node as an integer.
  818. Examples
  819. --------
  820. >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
  821. >>> nx.add_path(G, [0, 1, 2, 3])
  822. >>> G.degree(0) # node 0 with degree 1
  823. 1
  824. >>> list(G.degree([0, 1]))
  825. [(0, 1), (1, 2)]
  826. """
  827. return MultiDegreeView(self)
  828. def is_multigraph(self):
  829. """Returns True if graph is a multigraph, False otherwise."""
  830. return True
  831. def is_directed(self):
  832. """Returns True if graph is directed, False otherwise."""
  833. return False
  834. def copy(self, as_view=False):
  835. """Returns a copy of the graph.
  836. The copy method by default returns an independent shallow copy
  837. of the graph and attributes. That is, if an attribute is a
  838. container, that container is shared by the original an the copy.
  839. Use Python's `copy.deepcopy` for new containers.
  840. If `as_view` is True then a view is returned instead of a copy.
  841. Notes
  842. -----
  843. All copies reproduce the graph structure, but data attributes
  844. may be handled in different ways. There are four types of copies
  845. of a graph that people might want.
  846. Deepcopy -- A "deepcopy" copies the graph structure as well as
  847. all data attributes and any objects they might contain.
  848. The entire graph object is new so that changes in the copy
  849. do not affect the original object. (see Python's copy.deepcopy)
  850. Data Reference (Shallow) -- For a shallow copy the graph structure
  851. is copied but the edge, node and graph attribute dicts are
  852. references to those in the original graph. This saves
  853. time and memory but could cause confusion if you change an attribute
  854. in one graph and it changes the attribute in the other.
  855. NetworkX does not provide this level of shallow copy.
  856. Independent Shallow -- This copy creates new independent attribute
  857. dicts and then does a shallow copy of the attributes. That is, any
  858. attributes that are containers are shared between the new graph
  859. and the original. This is exactly what `dict.copy()` provides.
  860. You can obtain this style copy using:
  861. >>> G = nx.path_graph(5)
  862. >>> H = G.copy()
  863. >>> H = G.copy(as_view=False)
  864. >>> H = nx.Graph(G)
  865. >>> H = G.__class__(G)
  866. Fresh Data -- For fresh data, the graph structure is copied while
  867. new empty data attribute dicts are created. The resulting graph
  868. is independent of the original and it has no edge, node or graph
  869. attributes. Fresh copies are not enabled. Instead use:
  870. >>> H = G.__class__()
  871. >>> H.add_nodes_from(G)
  872. >>> H.add_edges_from(G.edges)
  873. View -- Inspired by dict-views, graph-views act like read-only
  874. versions of the original graph, providing a copy of the original
  875. structure without requiring any memory for copying the information.
  876. See the Python copy module for more information on shallow
  877. and deep copies, https://docs.python.org/3/library/copy.html.
  878. Parameters
  879. ----------
  880. as_view : bool, optional (default=False)
  881. If True, the returned graph-view provides a read-only view
  882. of the original graph without actually copying any data.
  883. Returns
  884. -------
  885. G : Graph
  886. A copy of the graph.
  887. See Also
  888. --------
  889. to_directed: return a directed copy of the graph.
  890. Examples
  891. --------
  892. >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
  893. >>> H = G.copy()
  894. """
  895. if as_view is True:
  896. return nx.graphviews.generic_graph_view(self)
  897. G = self.__class__()
  898. G.graph.update(self.graph)
  899. G.add_nodes_from((n, d.copy()) for n, d in self._node.items())
  900. G.add_edges_from(
  901. (u, v, key, datadict.copy())
  902. for u, nbrs in self._adj.items()
  903. for v, keydict in nbrs.items()
  904. for key, datadict in keydict.items()
  905. )
  906. return G
  907. def to_directed(self, as_view=False):
  908. """Returns a directed representation of the graph.
  909. Returns
  910. -------
  911. G : MultiDiGraph
  912. A directed graph with the same name, same nodes, and with
  913. each edge (u, v, k, data) replaced by two directed edges
  914. (u, v, k, data) and (v, u, k, data).
  915. Notes
  916. -----
  917. This returns a "deepcopy" of the edge, node, and
  918. graph attributes which attempts to completely copy
  919. all of the data and references.
  920. This is in contrast to the similar D=MultiDiGraph(G) which
  921. returns a shallow copy of the data.
  922. See the Python copy module for more information on shallow
  923. and deep copies, https://docs.python.org/3/library/copy.html.
  924. Warning: If you have subclassed MultiGraph to use dict-like objects
  925. in the data structure, those changes do not transfer to the
  926. MultiDiGraph created by this method.
  927. Examples
  928. --------
  929. >>> G = nx.MultiGraph()
  930. >>> G.add_edge(0, 1)
  931. 0
  932. >>> G.add_edge(0, 1)
  933. 1
  934. >>> H = G.to_directed()
  935. >>> list(H.edges)
  936. [(0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1)]
  937. If already directed, return a (deep) copy
  938. >>> G = nx.MultiDiGraph()
  939. >>> G.add_edge(0, 1)
  940. 0
  941. >>> H = G.to_directed()
  942. >>> list(H.edges)
  943. [(0, 1, 0)]
  944. """
  945. graph_class = self.to_directed_class()
  946. if as_view is True:
  947. return nx.graphviews.generic_graph_view(self, graph_class)
  948. # deepcopy when not a view
  949. G = graph_class()
  950. G.graph.update(deepcopy(self.graph))
  951. G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
  952. G.add_edges_from(
  953. (u, v, key, deepcopy(datadict))
  954. for u, nbrs in self.adj.items()
  955. for v, keydict in nbrs.items()
  956. for key, datadict in keydict.items()
  957. )
  958. return G
  959. def to_undirected(self, as_view=False):
  960. """Returns an undirected copy of the graph.
  961. Returns
  962. -------
  963. G : Graph/MultiGraph
  964. A deepcopy of the graph.
  965. See Also
  966. --------
  967. copy, add_edge, add_edges_from
  968. Notes
  969. -----
  970. This returns a "deepcopy" of the edge, node, and
  971. graph attributes which attempts to completely copy
  972. all of the data and references.
  973. This is in contrast to the similar `G = nx.MultiGraph(D)`
  974. which returns a shallow copy of the data.
  975. See the Python copy module for more information on shallow
  976. and deep copies, https://docs.python.org/3/library/copy.html.
  977. Warning: If you have subclassed MultiGraph to use dict-like
  978. objects in the data structure, those changes do not transfer
  979. to the MultiGraph created by this method.
  980. Examples
  981. --------
  982. >>> G = nx.MultiGraph([(0, 1), (0, 1), (1, 2)])
  983. >>> H = G.to_directed()
  984. >>> list(H.edges)
  985. [(0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 2, 0), (2, 1, 0)]
  986. >>> G2 = H.to_undirected()
  987. >>> list(G2.edges)
  988. [(0, 1, 0), (0, 1, 1), (1, 2, 0)]
  989. """
  990. graph_class = self.to_undirected_class()
  991. if as_view is True:
  992. return nx.graphviews.generic_graph_view(self, graph_class)
  993. # deepcopy when not a view
  994. G = graph_class()
  995. G.graph.update(deepcopy(self.graph))
  996. G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
  997. G.add_edges_from(
  998. (u, v, key, deepcopy(datadict))
  999. for u, nbrs in self._adj.items()
  1000. for v, keydict in nbrs.items()
  1001. for key, datadict in keydict.items()
  1002. )
  1003. return G
  1004. def number_of_edges(self, u=None, v=None):
  1005. """Returns the number of edges between two nodes.
  1006. Parameters
  1007. ----------
  1008. u, v : nodes, optional (Gefault=all edges)
  1009. If u and v are specified, return the number of edges between
  1010. u and v. Otherwise return the total number of all edges.
  1011. Returns
  1012. -------
  1013. nedges : int
  1014. The number of edges in the graph. If nodes `u` and `v` are
  1015. specified return the number of edges between those nodes. If
  1016. the graph is directed, this only returns the number of edges
  1017. from `u` to `v`.
  1018. See Also
  1019. --------
  1020. size
  1021. Examples
  1022. --------
  1023. For undirected multigraphs, this method counts the total number
  1024. of edges in the graph::
  1025. >>> G = nx.MultiGraph()
  1026. >>> G.add_edges_from([(0, 1), (0, 1), (1, 2)])
  1027. [0, 1, 0]
  1028. >>> G.number_of_edges()
  1029. 3
  1030. If you specify two nodes, this counts the total number of edges
  1031. joining the two nodes::
  1032. >>> G.number_of_edges(0, 1)
  1033. 2
  1034. For directed multigraphs, this method can count the total number
  1035. of directed edges from `u` to `v`::
  1036. >>> G = nx.MultiDiGraph()
  1037. >>> G.add_edges_from([(0, 1), (0, 1), (1, 0)])
  1038. [0, 1, 0]
  1039. >>> G.number_of_edges(0, 1)
  1040. 2
  1041. >>> G.number_of_edges(1, 0)
  1042. 1
  1043. """
  1044. if u is None:
  1045. return self.size()
  1046. try:
  1047. edgedata = self._adj[u][v]
  1048. except KeyError:
  1049. return 0 # no such edge
  1050. return len(edgedata)