graph.py 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028
  1. """Base class for undirected graphs.
  2. The Graph class allows any hashable object as a node
  3. and can associate key/value attribute pairs with each undirected edge.
  4. Self-loops are allowed but multiple edges are not (see MultiGraph).
  5. For directed graphs see DiGraph and MultiDiGraph.
  6. """
  7. from copy import deepcopy
  8. from functools import cached_property
  9. import networkx as nx
  10. from networkx import convert
  11. from networkx.classes.coreviews import AdjacencyView
  12. from networkx.classes.reportviews import DegreeView, EdgeView, NodeView
  13. from networkx.exception import NetworkXError
  14. __all__ = ["Graph"]
  15. class _CachedPropertyResetterAdj:
  16. """Data Descriptor class for _adj that resets ``adj`` cached_property when needed
  17. This assumes that the ``cached_property`` ``G.adj`` should be reset whenever
  18. ``G._adj`` is set to a new value.
  19. This object sits on a class and ensures that any instance of that
  20. class clears its cached property "adj" whenever the underlying
  21. instance attribute "_adj" is set to a new object. It only affects
  22. the set process of the obj._adj attribute. All get/del operations
  23. act as they normally would.
  24. For info on Data Descriptors see: https://docs.python.org/3/howto/descriptor.html
  25. """
  26. def __set__(self, obj, value):
  27. od = obj.__dict__
  28. od["_adj"] = value
  29. if "adj" in od:
  30. del od["adj"]
  31. class _CachedPropertyResetterNode:
  32. """Data Descriptor class for _node that resets ``nodes`` cached_property when needed
  33. This assumes that the ``cached_property`` ``G.node`` should be reset whenever
  34. ``G._node`` is set to a new value.
  35. This object sits on a class and ensures that any instance of that
  36. class clears its cached property "nodes" whenever the underlying
  37. instance attribute "_node" is set to a new object. It only affects
  38. the set process of the obj._adj attribute. All get/del operations
  39. act as they normally would.
  40. For info on Data Descriptors see: https://docs.python.org/3/howto/descriptor.html
  41. """
  42. def __set__(self, obj, value):
  43. od = obj.__dict__
  44. od["_node"] = value
  45. if "nodes" in od:
  46. del od["nodes"]
  47. class Graph:
  48. """
  49. Base class for undirected graphs.
  50. A Graph stores nodes and edges with optional data, or attributes.
  51. Graphs hold undirected edges. Self loops are allowed but multiple
  52. (parallel) edges are not.
  53. Nodes can be arbitrary (hashable) Python objects with optional
  54. key/value attributes, except that `None` is not allowed as a node.
  55. Edges are represented as links between nodes with optional
  56. key/value attributes.
  57. Parameters
  58. ----------
  59. incoming_graph_data : input graph (optional, default: None)
  60. Data to initialize graph. If None (default) an empty
  61. graph is created. The data can be any format that is supported
  62. by the to_networkx_graph() function, currently including edge list,
  63. dict of dicts, dict of lists, NetworkX graph, 2D NumPy array, SciPy
  64. sparse matrix, or PyGraphviz graph.
  65. attr : keyword arguments, optional (default= no attributes)
  66. Attributes to add to graph as key=value pairs.
  67. See Also
  68. --------
  69. DiGraph
  70. MultiGraph
  71. MultiDiGraph
  72. Examples
  73. --------
  74. Create an empty graph structure (a "null graph") with no nodes and
  75. no edges.
  76. >>> G = nx.Graph()
  77. G can be grown in several ways.
  78. **Nodes:**
  79. Add one node at a time:
  80. >>> G.add_node(1)
  81. Add the nodes from any container (a list, dict, set or
  82. even the lines from a file or the nodes from another graph).
  83. >>> G.add_nodes_from([2, 3])
  84. >>> G.add_nodes_from(range(100, 110))
  85. >>> H = nx.path_graph(10)
  86. >>> G.add_nodes_from(H)
  87. In addition to strings and integers any hashable Python object
  88. (except None) can represent a node, e.g. a customized node object,
  89. or even another Graph.
  90. >>> G.add_node(H)
  91. **Edges:**
  92. G can also be grown by adding edges.
  93. Add one edge,
  94. >>> G.add_edge(1, 2)
  95. a list of edges,
  96. >>> G.add_edges_from([(1, 2), (1, 3)])
  97. or a collection of edges,
  98. >>> G.add_edges_from(H.edges)
  99. If some edges connect nodes not yet in the graph, the nodes
  100. are added automatically. There are no errors when adding
  101. nodes or edges that already exist.
  102. **Attributes:**
  103. Each graph, node, and edge can hold key/value attribute pairs
  104. in an associated attribute dictionary (the keys must be hashable).
  105. By default these are empty, but can be added or changed using
  106. add_edge, add_node or direct manipulation of the attribute
  107. dictionaries named graph, node and edge respectively.
  108. >>> G = nx.Graph(day="Friday")
  109. >>> G.graph
  110. {'day': 'Friday'}
  111. Add node attributes using add_node(), add_nodes_from() or G.nodes
  112. >>> G.add_node(1, time="5pm")
  113. >>> G.add_nodes_from([3], time="2pm")
  114. >>> G.nodes[1]
  115. {'time': '5pm'}
  116. >>> G.nodes[1]["room"] = 714 # node must exist already to use G.nodes
  117. >>> del G.nodes[1]["room"] # remove attribute
  118. >>> list(G.nodes(data=True))
  119. [(1, {'time': '5pm'}), (3, {'time': '2pm'})]
  120. Add edge attributes using add_edge(), add_edges_from(), subscript
  121. notation, or G.edges.
  122. >>> G.add_edge(1, 2, weight=4.7)
  123. >>> G.add_edges_from([(3, 4), (4, 5)], color="red")
  124. >>> G.add_edges_from([(1, 2, {"color": "blue"}), (2, 3, {"weight": 8})])
  125. >>> G[1][2]["weight"] = 4.7
  126. >>> G.edges[1, 2]["weight"] = 4
  127. Warning: we protect the graph data structure by making `G.edges` a
  128. read-only dict-like structure. However, you can assign to attributes
  129. in e.g. `G.edges[1, 2]`. Thus, use 2 sets of brackets to add/change
  130. data attributes: `G.edges[1, 2]['weight'] = 4`
  131. (For multigraphs: `MG.edges[u, v, key][name] = value`).
  132. **Shortcuts:**
  133. Many common graph features allow python syntax to speed reporting.
  134. >>> 1 in G # check if node in graph
  135. True
  136. >>> [n for n in G if n < 3] # iterate through nodes
  137. [1, 2]
  138. >>> len(G) # number of nodes in graph
  139. 5
  140. Often the best way to traverse all edges of a graph is via the neighbors.
  141. The neighbors are reported as an adjacency-dict `G.adj` or `G.adjacency()`
  142. >>> for n, nbrsdict in G.adjacency():
  143. ... for nbr, eattr in nbrsdict.items():
  144. ... if "weight" in eattr:
  145. ... # Do something useful with the edges
  146. ... pass
  147. But the edges() method is often more convenient:
  148. >>> for u, v, weight in G.edges.data("weight"):
  149. ... if weight is not None:
  150. ... # Do something useful with the edges
  151. ... pass
  152. **Reporting:**
  153. Simple graph information is obtained using object-attributes and methods.
  154. Reporting typically provides views instead of containers to reduce memory
  155. usage. The views update as the graph is updated similarly to dict-views.
  156. The objects `nodes`, `edges` and `adj` provide access to data attributes
  157. via lookup (e.g. `nodes[n]`, `edges[u, v]`, `adj[u][v]`) and iteration
  158. (e.g. `nodes.items()`, `nodes.data('color')`,
  159. `nodes.data('color', default='blue')` and similarly for `edges`)
  160. Views exist for `nodes`, `edges`, `neighbors()`/`adj` and `degree`.
  161. For details on these and other miscellaneous methods, see below.
  162. **Subclasses (Advanced):**
  163. The Graph class uses a dict-of-dict-of-dict data structure.
  164. The outer dict (node_dict) holds adjacency information keyed by node.
  165. The next dict (adjlist_dict) represents the adjacency information and holds
  166. edge data keyed by neighbor. The inner dict (edge_attr_dict) represents
  167. the edge data and holds edge attribute values keyed by attribute names.
  168. Each of these three dicts can be replaced in a subclass by a user defined
  169. dict-like object. In general, the dict-like features should be
  170. maintained but extra features can be added. To replace one of the
  171. dicts create a new graph class by changing the class(!) variable
  172. holding the factory for that dict-like structure.
  173. node_dict_factory : function, (default: dict)
  174. Factory function to be used to create the dict containing node
  175. attributes, keyed by node id.
  176. It should require no arguments and return a dict-like object
  177. node_attr_dict_factory: function, (default: dict)
  178. Factory function to be used to create the node attribute
  179. dict which holds attribute values keyed by attribute name.
  180. It should require no arguments and return a dict-like object
  181. adjlist_outer_dict_factory : function, (default: dict)
  182. Factory function to be used to create the outer-most dict
  183. in the data structure that holds adjacency info keyed by node.
  184. It should require no arguments and return a dict-like object.
  185. adjlist_inner_dict_factory : function, (default: dict)
  186. Factory function to be used to create the adjacency list
  187. dict which holds edge data keyed by neighbor.
  188. It should require no arguments and return a dict-like object
  189. edge_attr_dict_factory : function, (default: dict)
  190. Factory function to be used to create the edge attribute
  191. dict which holds attribute values keyed by attribute name.
  192. It should require no arguments and return a dict-like object.
  193. graph_attr_dict_factory : function, (default: dict)
  194. Factory function to be used to create the graph attribute
  195. dict which holds attribute values keyed by attribute name.
  196. It should require no arguments and return a dict-like object.
  197. Typically, if your extension doesn't impact the data structure all
  198. methods will inherit without issue except: `to_directed/to_undirected`.
  199. By default these methods create a DiGraph/Graph class and you probably
  200. want them to create your extension of a DiGraph/Graph. To facilitate
  201. this we define two class variables that you can set in your subclass.
  202. to_directed_class : callable, (default: DiGraph or MultiDiGraph)
  203. Class to create a new graph structure in the `to_directed` method.
  204. If `None`, a NetworkX class (DiGraph or MultiDiGraph) is used.
  205. to_undirected_class : callable, (default: Graph or MultiGraph)
  206. Class to create a new graph structure in the `to_undirected` method.
  207. If `None`, a NetworkX class (Graph or MultiGraph) is used.
  208. **Subclassing Example**
  209. Create a low memory graph class that effectively disallows edge
  210. attributes by using a single attribute dict for all edges.
  211. This reduces the memory used, but you lose edge attributes.
  212. >>> class ThinGraph(nx.Graph):
  213. ... all_edge_dict = {"weight": 1}
  214. ...
  215. ... def single_edge_dict(self):
  216. ... return self.all_edge_dict
  217. ...
  218. ... edge_attr_dict_factory = single_edge_dict
  219. >>> G = ThinGraph()
  220. >>> G.add_edge(2, 1)
  221. >>> G[2][1]
  222. {'weight': 1}
  223. >>> G.add_edge(2, 2)
  224. >>> G[2][1] is G[2][2]
  225. True
  226. """
  227. _adj = _CachedPropertyResetterAdj()
  228. _node = _CachedPropertyResetterNode()
  229. node_dict_factory = dict
  230. node_attr_dict_factory = dict
  231. adjlist_outer_dict_factory = dict
  232. adjlist_inner_dict_factory = dict
  233. edge_attr_dict_factory = dict
  234. graph_attr_dict_factory = dict
  235. def to_directed_class(self):
  236. """Returns the class to use for empty directed copies.
  237. If you subclass the base classes, use this to designate
  238. what directed class to use for `to_directed()` copies.
  239. """
  240. return nx.DiGraph
  241. def to_undirected_class(self):
  242. """Returns the class to use for empty undirected copies.
  243. If you subclass the base classes, use this to designate
  244. what directed class to use for `to_directed()` copies.
  245. """
  246. return Graph
  247. def __init__(self, incoming_graph_data=None, **attr):
  248. """Initialize a graph with edges, name, or graph attributes.
  249. Parameters
  250. ----------
  251. incoming_graph_data : input graph (optional, default: None)
  252. Data to initialize graph. If None (default) an empty
  253. graph is created. The data can be an edge list, or any
  254. NetworkX graph object. If the corresponding optional Python
  255. packages are installed the data can also be a 2D NumPy array, a
  256. SciPy sparse array, or a PyGraphviz graph.
  257. attr : keyword arguments, optional (default= no attributes)
  258. Attributes to add to graph as key=value pairs.
  259. See Also
  260. --------
  261. convert
  262. Examples
  263. --------
  264. >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
  265. >>> G = nx.Graph(name="my graph")
  266. >>> e = [(1, 2), (2, 3), (3, 4)] # list of edges
  267. >>> G = nx.Graph(e)
  268. Arbitrary graph attribute pairs (key=value) may be assigned
  269. >>> G = nx.Graph(e, day="Friday")
  270. >>> G.graph
  271. {'day': 'Friday'}
  272. """
  273. self.graph = self.graph_attr_dict_factory() # dictionary for graph attributes
  274. self._node = self.node_dict_factory() # empty node attribute dict
  275. self._adj = self.adjlist_outer_dict_factory() # empty adjacency dict
  276. # attempt to load graph with data
  277. if incoming_graph_data is not None:
  278. convert.to_networkx_graph(incoming_graph_data, create_using=self)
  279. # load graph attributes (must be after convert)
  280. self.graph.update(attr)
  281. @cached_property
  282. def adj(self):
  283. """Graph adjacency object holding the neighbors of each node.
  284. This object is a read-only dict-like structure with node keys
  285. and neighbor-dict values. The neighbor-dict is keyed by neighbor
  286. to the edge-data-dict. So `G.adj[3][2]['color'] = 'blue'` sets
  287. the color of the edge `(3, 2)` to `"blue"`.
  288. Iterating over G.adj behaves like a dict. Useful idioms include
  289. `for nbr, datadict in G.adj[n].items():`.
  290. The neighbor information is also provided by subscripting the graph.
  291. So `for nbr, foovalue in G[node].data('foo', default=1):` works.
  292. For directed graphs, `G.adj` holds outgoing (successor) info.
  293. """
  294. return AdjacencyView(self._adj)
  295. @property
  296. def name(self):
  297. """String identifier of the graph.
  298. This graph attribute appears in the attribute dict G.graph
  299. keyed by the string `"name"`. as well as an attribute (technically
  300. a property) `G.name`. This is entirely user controlled.
  301. """
  302. return self.graph.get("name", "")
  303. @name.setter
  304. def name(self, s):
  305. self.graph["name"] = s
  306. def __str__(self):
  307. """Returns a short summary of the graph.
  308. Returns
  309. -------
  310. info : string
  311. Graph information including the graph name (if any), graph type, and the
  312. number of nodes and edges.
  313. Examples
  314. --------
  315. >>> G = nx.Graph(name="foo")
  316. >>> str(G)
  317. "Graph named 'foo' with 0 nodes and 0 edges"
  318. >>> G = nx.path_graph(3)
  319. >>> str(G)
  320. 'Graph with 3 nodes and 2 edges'
  321. """
  322. return "".join(
  323. [
  324. type(self).__name__,
  325. f" named {self.name!r}" if self.name else "",
  326. f" with {self.number_of_nodes()} nodes and {self.number_of_edges()} edges",
  327. ]
  328. )
  329. def __iter__(self):
  330. """Iterate over the nodes. Use: 'for n in G'.
  331. Returns
  332. -------
  333. niter : iterator
  334. An iterator over all nodes in the graph.
  335. Examples
  336. --------
  337. >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
  338. >>> [n for n in G]
  339. [0, 1, 2, 3]
  340. >>> list(G)
  341. [0, 1, 2, 3]
  342. """
  343. return iter(self._node)
  344. def __contains__(self, n):
  345. """Returns True if n is a node, False otherwise. Use: 'n in G'.
  346. Examples
  347. --------
  348. >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
  349. >>> 1 in G
  350. True
  351. """
  352. try:
  353. return n in self._node
  354. except TypeError:
  355. return False
  356. def __len__(self):
  357. """Returns the number of nodes in the graph. Use: 'len(G)'.
  358. Returns
  359. -------
  360. nnodes : int
  361. The number of nodes in the graph.
  362. See Also
  363. --------
  364. number_of_nodes: identical method
  365. order: identical method
  366. Examples
  367. --------
  368. >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
  369. >>> len(G)
  370. 4
  371. """
  372. return len(self._node)
  373. def __getitem__(self, n):
  374. """Returns a dict of neighbors of node n. Use: 'G[n]'.
  375. Parameters
  376. ----------
  377. n : node
  378. A node in the graph.
  379. Returns
  380. -------
  381. adj_dict : dictionary
  382. The adjacency dictionary for nodes connected to n.
  383. Notes
  384. -----
  385. G[n] is the same as G.adj[n] and similar to G.neighbors(n)
  386. (which is an iterator over G.adj[n])
  387. Examples
  388. --------
  389. >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
  390. >>> G[0]
  391. AtlasView({1: {}})
  392. """
  393. return self.adj[n]
  394. def add_node(self, node_for_adding, **attr):
  395. """Add a single node `node_for_adding` and update node attributes.
  396. Parameters
  397. ----------
  398. node_for_adding : node
  399. A node can be any hashable Python object except None.
  400. attr : keyword arguments, optional
  401. Set or change node attributes using key=value.
  402. See Also
  403. --------
  404. add_nodes_from
  405. Examples
  406. --------
  407. >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
  408. >>> G.add_node(1)
  409. >>> G.add_node("Hello")
  410. >>> K3 = nx.Graph([(0, 1), (1, 2), (2, 0)])
  411. >>> G.add_node(K3)
  412. >>> G.number_of_nodes()
  413. 3
  414. Use keywords set/change node attributes:
  415. >>> G.add_node(1, size=10)
  416. >>> G.add_node(3, weight=0.4, UTM=("13S", 382871, 3972649))
  417. Notes
  418. -----
  419. A hashable object is one that can be used as a key in a Python
  420. dictionary. This includes strings, numbers, tuples of strings
  421. and numbers, etc.
  422. On many platforms hashable items also include mutables such as
  423. NetworkX Graphs, though one should be careful that the hash
  424. doesn't change on mutables.
  425. """
  426. if node_for_adding not in self._node:
  427. if node_for_adding is None:
  428. raise ValueError("None cannot be a node")
  429. self._adj[node_for_adding] = self.adjlist_inner_dict_factory()
  430. attr_dict = self._node[node_for_adding] = self.node_attr_dict_factory()
  431. attr_dict.update(attr)
  432. else: # update attr even if node already exists
  433. self._node[node_for_adding].update(attr)
  434. def add_nodes_from(self, nodes_for_adding, **attr):
  435. """Add multiple nodes.
  436. Parameters
  437. ----------
  438. nodes_for_adding : iterable container
  439. A container of nodes (list, dict, set, etc.).
  440. OR
  441. A container of (node, attribute dict) tuples.
  442. Node attributes are updated using the attribute dict.
  443. attr : keyword arguments, optional (default= no attributes)
  444. Update attributes for all nodes in nodes.
  445. Node attributes specified in nodes as a tuple take
  446. precedence over attributes specified via keyword arguments.
  447. See Also
  448. --------
  449. add_node
  450. Notes
  451. -----
  452. When adding nodes from an iterator over the graph you are changing,
  453. a `RuntimeError` can be raised with message:
  454. `RuntimeError: dictionary changed size during iteration`. This
  455. happens when the graph's underlying dictionary is modified during
  456. iteration. To avoid this error, evaluate the iterator into a separate
  457. object, e.g. by using `list(iterator_of_nodes)`, and pass this
  458. object to `G.add_nodes_from`.
  459. Examples
  460. --------
  461. >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
  462. >>> G.add_nodes_from("Hello")
  463. >>> K3 = nx.Graph([(0, 1), (1, 2), (2, 0)])
  464. >>> G.add_nodes_from(K3)
  465. >>> sorted(G.nodes(), key=str)
  466. [0, 1, 2, 'H', 'e', 'l', 'o']
  467. Use keywords to update specific node attributes for every node.
  468. >>> G.add_nodes_from([1, 2], size=10)
  469. >>> G.add_nodes_from([3, 4], weight=0.4)
  470. Use (node, attrdict) tuples to update attributes for specific nodes.
  471. >>> G.add_nodes_from([(1, dict(size=11)), (2, {"color": "blue"})])
  472. >>> G.nodes[1]["size"]
  473. 11
  474. >>> H = nx.Graph()
  475. >>> H.add_nodes_from(G.nodes(data=True))
  476. >>> H.nodes[1]["size"]
  477. 11
  478. Evaluate an iterator over a graph if using it to modify the same graph
  479. >>> G = nx.Graph([(0, 1), (1, 2), (3, 4)])
  480. >>> # wrong way - will raise RuntimeError
  481. >>> # G.add_nodes_from(n + 1 for n in G.nodes)
  482. >>> # correct way
  483. >>> G.add_nodes_from(list(n + 1 for n in G.nodes))
  484. """
  485. for n in nodes_for_adding:
  486. try:
  487. newnode = n not in self._node
  488. newdict = attr
  489. except TypeError:
  490. n, ndict = n
  491. newnode = n not in self._node
  492. newdict = attr.copy()
  493. newdict.update(ndict)
  494. if newnode:
  495. if n is None:
  496. raise ValueError("None cannot be a node")
  497. self._adj[n] = self.adjlist_inner_dict_factory()
  498. self._node[n] = self.node_attr_dict_factory()
  499. self._node[n].update(newdict)
  500. def remove_node(self, n):
  501. """Remove node n.
  502. Removes the node n and all adjacent edges.
  503. Attempting to remove a non-existent node will raise an exception.
  504. Parameters
  505. ----------
  506. n : node
  507. A node in the graph
  508. Raises
  509. ------
  510. NetworkXError
  511. If n is not in the graph.
  512. See Also
  513. --------
  514. remove_nodes_from
  515. Examples
  516. --------
  517. >>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc
  518. >>> list(G.edges)
  519. [(0, 1), (1, 2)]
  520. >>> G.remove_node(1)
  521. >>> list(G.edges)
  522. []
  523. """
  524. adj = self._adj
  525. try:
  526. nbrs = list(adj[n]) # list handles self-loops (allows mutation)
  527. del self._node[n]
  528. except KeyError as err: # NetworkXError if n not in self
  529. raise NetworkXError(f"The node {n} is not in the graph.") from err
  530. for u in nbrs:
  531. del adj[u][n] # remove all edges n-u in graph
  532. del adj[n] # now remove node
  533. def remove_nodes_from(self, nodes):
  534. """Remove multiple nodes.
  535. Parameters
  536. ----------
  537. nodes : iterable container
  538. A container of nodes (list, dict, set, etc.). If a node
  539. in the container is not in the graph it is silently
  540. ignored.
  541. See Also
  542. --------
  543. remove_node
  544. Notes
  545. -----
  546. When removing nodes from an iterator over the graph you are changing,
  547. a `RuntimeError` will be raised with message:
  548. `RuntimeError: dictionary changed size during iteration`. This
  549. happens when the graph's underlying dictionary is modified during
  550. iteration. To avoid this error, evaluate the iterator into a separate
  551. object, e.g. by using `list(iterator_of_nodes)`, and pass this
  552. object to `G.remove_nodes_from`.
  553. Examples
  554. --------
  555. >>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc
  556. >>> e = list(G.nodes)
  557. >>> e
  558. [0, 1, 2]
  559. >>> G.remove_nodes_from(e)
  560. >>> list(G.nodes)
  561. []
  562. Evaluate an iterator over a graph if using it to modify the same graph
  563. >>> G = nx.Graph([(0, 1), (1, 2), (3, 4)])
  564. >>> # this command will fail, as the graph's dict is modified during iteration
  565. >>> # G.remove_nodes_from(n for n in G.nodes if n < 2)
  566. >>> # this command will work, since the dictionary underlying graph is not modified
  567. >>> G.remove_nodes_from(list(n for n in G.nodes if n < 2))
  568. """
  569. adj = self._adj
  570. for n in nodes:
  571. try:
  572. del self._node[n]
  573. for u in list(adj[n]): # list handles self-loops
  574. del adj[u][n] # (allows mutation of dict in loop)
  575. del adj[n]
  576. except KeyError:
  577. pass
  578. @cached_property
  579. def nodes(self):
  580. """A NodeView of the Graph as G.nodes or G.nodes().
  581. Can be used as `G.nodes` for data lookup and for set-like operations.
  582. Can also be used as `G.nodes(data='color', default=None)` to return a
  583. NodeDataView which reports specific node data but no set operations.
  584. It presents a dict-like interface as well with `G.nodes.items()`
  585. iterating over `(node, nodedata)` 2-tuples and `G.nodes[3]['foo']`
  586. providing the value of the `foo` attribute for node `3`. In addition,
  587. a view `G.nodes.data('foo')` provides a dict-like interface to the
  588. `foo` attribute of each node. `G.nodes.data('foo', default=1)`
  589. provides a default for nodes that do not have attribute `foo`.
  590. Parameters
  591. ----------
  592. data : string or bool, optional (default=False)
  593. The node attribute returned in 2-tuple (n, ddict[data]).
  594. If True, return entire node attribute dict as (n, ddict).
  595. If False, return just the nodes n.
  596. default : value, optional (default=None)
  597. Value used for nodes that don't have the requested attribute.
  598. Only relevant if data is not True or False.
  599. Returns
  600. -------
  601. NodeView
  602. Allows set-like operations over the nodes as well as node
  603. attribute dict lookup and calling to get a NodeDataView.
  604. A NodeDataView iterates over `(n, data)` and has no set operations.
  605. A NodeView iterates over `n` and includes set operations.
  606. When called, if data is False, an iterator over nodes.
  607. Otherwise an iterator of 2-tuples (node, attribute value)
  608. where the attribute is specified in `data`.
  609. If data is True then the attribute becomes the
  610. entire data dictionary.
  611. Notes
  612. -----
  613. If your node data is not needed, it is simpler and equivalent
  614. to use the expression ``for n in G``, or ``list(G)``.
  615. Examples
  616. --------
  617. There are two simple ways of getting a list of all nodes in the graph:
  618. >>> G = nx.path_graph(3)
  619. >>> list(G.nodes)
  620. [0, 1, 2]
  621. >>> list(G)
  622. [0, 1, 2]
  623. To get the node data along with the nodes:
  624. >>> G.add_node(1, time="5pm")
  625. >>> G.nodes[0]["foo"] = "bar"
  626. >>> list(G.nodes(data=True))
  627. [(0, {'foo': 'bar'}), (1, {'time': '5pm'}), (2, {})]
  628. >>> list(G.nodes.data())
  629. [(0, {'foo': 'bar'}), (1, {'time': '5pm'}), (2, {})]
  630. >>> list(G.nodes(data="foo"))
  631. [(0, 'bar'), (1, None), (2, None)]
  632. >>> list(G.nodes.data("foo"))
  633. [(0, 'bar'), (1, None), (2, None)]
  634. >>> list(G.nodes(data="time"))
  635. [(0, None), (1, '5pm'), (2, None)]
  636. >>> list(G.nodes.data("time"))
  637. [(0, None), (1, '5pm'), (2, None)]
  638. >>> list(G.nodes(data="time", default="Not Available"))
  639. [(0, 'Not Available'), (1, '5pm'), (2, 'Not Available')]
  640. >>> list(G.nodes.data("time", default="Not Available"))
  641. [(0, 'Not Available'), (1, '5pm'), (2, 'Not Available')]
  642. If some of your nodes have an attribute and the rest are assumed
  643. to have a default attribute value you can create a dictionary
  644. from node/attribute pairs using the `default` keyword argument
  645. to guarantee the value is never None::
  646. >>> G = nx.Graph()
  647. >>> G.add_node(0)
  648. >>> G.add_node(1, weight=2)
  649. >>> G.add_node(2, weight=3)
  650. >>> dict(G.nodes(data="weight", default=1))
  651. {0: 1, 1: 2, 2: 3}
  652. """
  653. return NodeView(self)
  654. def number_of_nodes(self):
  655. """Returns the number of nodes in the graph.
  656. Returns
  657. -------
  658. nnodes : int
  659. The number of nodes in the graph.
  660. See Also
  661. --------
  662. order: identical method
  663. __len__: identical method
  664. Examples
  665. --------
  666. >>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc
  667. >>> G.number_of_nodes()
  668. 3
  669. """
  670. return len(self._node)
  671. def order(self):
  672. """Returns the number of nodes in the graph.
  673. Returns
  674. -------
  675. nnodes : int
  676. The number of nodes in the graph.
  677. See Also
  678. --------
  679. number_of_nodes: identical method
  680. __len__: identical method
  681. Examples
  682. --------
  683. >>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc
  684. >>> G.order()
  685. 3
  686. """
  687. return len(self._node)
  688. def has_node(self, n):
  689. """Returns True if the graph contains the node n.
  690. Identical to `n in G`
  691. Parameters
  692. ----------
  693. n : node
  694. Examples
  695. --------
  696. >>> G = nx.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc
  697. >>> G.has_node(0)
  698. True
  699. It is more readable and simpler to use
  700. >>> 0 in G
  701. True
  702. """
  703. try:
  704. return n in self._node
  705. except TypeError:
  706. return False
  707. def add_edge(self, u_of_edge, v_of_edge, **attr):
  708. """Add an edge between u and v.
  709. The nodes u and v will be automatically added if they are
  710. not already in the graph.
  711. Edge attributes can be specified with keywords or by directly
  712. accessing the edge's attribute dictionary. See examples below.
  713. Parameters
  714. ----------
  715. u_of_edge, v_of_edge : nodes
  716. Nodes can be, for example, strings or numbers.
  717. Nodes must be hashable (and not None) Python objects.
  718. attr : keyword arguments, optional
  719. Edge data (or labels or objects) can be assigned using
  720. keyword arguments.
  721. See Also
  722. --------
  723. add_edges_from : add a collection of edges
  724. Notes
  725. -----
  726. Adding an edge that already exists updates the edge data.
  727. Many NetworkX algorithms designed for weighted graphs use
  728. an edge attribute (by default `weight`) to hold a numerical value.
  729. Examples
  730. --------
  731. The following all add the edge e=(1, 2) to graph G:
  732. >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
  733. >>> e = (1, 2)
  734. >>> G.add_edge(1, 2) # explicit two-node form
  735. >>> G.add_edge(*e) # single edge as tuple of two nodes
  736. >>> G.add_edges_from([(1, 2)]) # add edges from iterable container
  737. Associate data to edges using keywords:
  738. >>> G.add_edge(1, 2, weight=3)
  739. >>> G.add_edge(1, 3, weight=7, capacity=15, length=342.7)
  740. For non-string attribute keys, use subscript notation.
  741. >>> G.add_edge(1, 2)
  742. >>> G[1][2].update({0: 5})
  743. >>> G.edges[1, 2].update({0: 5})
  744. """
  745. u, v = u_of_edge, v_of_edge
  746. # add nodes
  747. if u not in self._node:
  748. if u is None:
  749. raise ValueError("None cannot be a node")
  750. self._adj[u] = self.adjlist_inner_dict_factory()
  751. self._node[u] = self.node_attr_dict_factory()
  752. if v not in self._node:
  753. if v is None:
  754. raise ValueError("None cannot be a node")
  755. self._adj[v] = self.adjlist_inner_dict_factory()
  756. self._node[v] = self.node_attr_dict_factory()
  757. # add the edge
  758. datadict = self._adj[u].get(v, self.edge_attr_dict_factory())
  759. datadict.update(attr)
  760. self._adj[u][v] = datadict
  761. self._adj[v][u] = datadict
  762. def add_edges_from(self, ebunch_to_add, **attr):
  763. """Add all the edges in ebunch_to_add.
  764. Parameters
  765. ----------
  766. ebunch_to_add : container of edges
  767. Each edge given in the container will be added to the
  768. graph. The edges must be given as 2-tuples (u, v) or
  769. 3-tuples (u, v, d) where d is a dictionary containing edge data.
  770. attr : keyword arguments, optional
  771. Edge data (or labels or objects) can be assigned using
  772. keyword arguments.
  773. See Also
  774. --------
  775. add_edge : add a single edge
  776. add_weighted_edges_from : convenient way to add weighted edges
  777. Notes
  778. -----
  779. Adding the same edge twice has no effect but any edge data
  780. will be updated when each duplicate edge is added.
  781. Edge attributes specified in an ebunch take precedence over
  782. attributes specified via keyword arguments.
  783. When adding edges from an iterator over the graph you are changing,
  784. a `RuntimeError` can be raised with message:
  785. `RuntimeError: dictionary changed size during iteration`. This
  786. happens when the graph's underlying dictionary is modified during
  787. iteration. To avoid this error, evaluate the iterator into a separate
  788. object, e.g. by using `list(iterator_of_edges)`, and pass this
  789. object to `G.add_edges_from`.
  790. Examples
  791. --------
  792. >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
  793. >>> G.add_edges_from([(0, 1), (1, 2)]) # using a list of edge tuples
  794. >>> e = zip(range(0, 3), range(1, 4))
  795. >>> G.add_edges_from(e) # Add the path graph 0-1-2-3
  796. Associate data to edges
  797. >>> G.add_edges_from([(1, 2), (2, 3)], weight=3)
  798. >>> G.add_edges_from([(3, 4), (1, 4)], label="WN2898")
  799. Evaluate an iterator over a graph if using it to modify the same graph
  800. >>> G = nx.Graph([(1, 2), (2, 3), (3, 4)])
  801. >>> # Grow graph by one new node, adding edges to all existing nodes.
  802. >>> # wrong way - will raise RuntimeError
  803. >>> # G.add_edges_from(((5, n) for n in G.nodes))
  804. >>> # correct way - note that there will be no self-edge for node 5
  805. >>> G.add_edges_from(list((5, n) for n in G.nodes))
  806. """
  807. for e in ebunch_to_add:
  808. ne = len(e)
  809. if ne == 3:
  810. u, v, dd = e
  811. elif ne == 2:
  812. u, v = e
  813. dd = {} # doesn't need edge_attr_dict_factory
  814. else:
  815. raise NetworkXError(f"Edge tuple {e} must be a 2-tuple or 3-tuple.")
  816. if u not in self._node:
  817. if u is None:
  818. raise ValueError("None cannot be a node")
  819. self._adj[u] = self.adjlist_inner_dict_factory()
  820. self._node[u] = self.node_attr_dict_factory()
  821. if v not in self._node:
  822. if v is None:
  823. raise ValueError("None cannot be a node")
  824. self._adj[v] = self.adjlist_inner_dict_factory()
  825. self._node[v] = self.node_attr_dict_factory()
  826. datadict = self._adj[u].get(v, self.edge_attr_dict_factory())
  827. datadict.update(attr)
  828. datadict.update(dd)
  829. self._adj[u][v] = datadict
  830. self._adj[v][u] = datadict
  831. def add_weighted_edges_from(self, ebunch_to_add, weight="weight", **attr):
  832. """Add weighted edges in `ebunch_to_add` with specified weight attr
  833. Parameters
  834. ----------
  835. ebunch_to_add : container of edges
  836. Each edge given in the list or container will be added
  837. to the graph. The edges must be given as 3-tuples (u, v, w)
  838. where w is a number.
  839. weight : string, optional (default= 'weight')
  840. The attribute name for the edge weights to be added.
  841. attr : keyword arguments, optional (default= no attributes)
  842. Edge attributes to add/update for all edges.
  843. See Also
  844. --------
  845. add_edge : add a single edge
  846. add_edges_from : add multiple edges
  847. Notes
  848. -----
  849. Adding the same edge twice for Graph/DiGraph simply updates
  850. the edge data. For MultiGraph/MultiDiGraph, duplicate edges
  851. are stored.
  852. When adding edges from an iterator over the graph you are changing,
  853. a `RuntimeError` can be raised with message:
  854. `RuntimeError: dictionary changed size during iteration`. This
  855. happens when the graph's underlying dictionary is modified during
  856. iteration. To avoid this error, evaluate the iterator into a separate
  857. object, e.g. by using `list(iterator_of_edges)`, and pass this
  858. object to `G.add_weighted_edges_from`.
  859. Examples
  860. --------
  861. >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
  862. >>> G.add_weighted_edges_from([(0, 1, 3.0), (1, 2, 7.5)])
  863. Evaluate an iterator over edges before passing it
  864. >>> G = nx.Graph([(1, 2), (2, 3), (3, 4)])
  865. >>> weight = 0.1
  866. >>> # Grow graph by one new node, adding edges to all existing nodes.
  867. >>> # wrong way - will raise RuntimeError
  868. >>> # G.add_weighted_edges_from(((5, n, weight) for n in G.nodes))
  869. >>> # correct way - note that there will be no self-edge for node 5
  870. >>> G.add_weighted_edges_from(list((5, n, weight) for n in G.nodes))
  871. """
  872. self.add_edges_from(((u, v, {weight: d}) for u, v, d in ebunch_to_add), **attr)
  873. def remove_edge(self, u, v):
  874. """Remove the edge between u and v.
  875. Parameters
  876. ----------
  877. u, v : nodes
  878. Remove the edge between nodes u and v.
  879. Raises
  880. ------
  881. NetworkXError
  882. If there is not an edge between u and v.
  883. See Also
  884. --------
  885. remove_edges_from : remove a collection of edges
  886. Examples
  887. --------
  888. >>> G = nx.path_graph(4) # or DiGraph, etc
  889. >>> G.remove_edge(0, 1)
  890. >>> e = (1, 2)
  891. >>> G.remove_edge(*e) # unpacks e from an edge tuple
  892. >>> e = (2, 3, {"weight": 7}) # an edge with attribute data
  893. >>> G.remove_edge(*e[:2]) # select first part of edge tuple
  894. """
  895. try:
  896. del self._adj[u][v]
  897. if u != v: # self-loop needs only one entry removed
  898. del self._adj[v][u]
  899. except KeyError as err:
  900. raise NetworkXError(f"The edge {u}-{v} is not in the graph") from err
  901. def remove_edges_from(self, ebunch):
  902. """Remove all edges specified in ebunch.
  903. Parameters
  904. ----------
  905. ebunch: list or container of edge tuples
  906. Each edge given in the list or container will be removed
  907. from the graph. The edges can be:
  908. - 2-tuples (u, v) edge between u and v.
  909. - 3-tuples (u, v, k) where k is ignored.
  910. See Also
  911. --------
  912. remove_edge : remove a single edge
  913. Notes
  914. -----
  915. Will fail silently if an edge in ebunch is not in the graph.
  916. Examples
  917. --------
  918. >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
  919. >>> ebunch = [(1, 2), (2, 3)]
  920. >>> G.remove_edges_from(ebunch)
  921. """
  922. adj = self._adj
  923. for e in ebunch:
  924. u, v = e[:2] # ignore edge data if present
  925. if u in adj and v in adj[u]:
  926. del adj[u][v]
  927. if u != v: # self loop needs only one entry removed
  928. del adj[v][u]
  929. def update(self, edges=None, nodes=None):
  930. """Update the graph using nodes/edges/graphs as input.
  931. Like dict.update, this method takes a graph as input, adding the
  932. graph's nodes and edges to this graph. It can also take two inputs:
  933. edges and nodes. Finally it can take either edges or nodes.
  934. To specify only nodes the keyword `nodes` must be used.
  935. The collections of edges and nodes are treated similarly to
  936. the add_edges_from/add_nodes_from methods. When iterated, they
  937. should yield 2-tuples (u, v) or 3-tuples (u, v, datadict).
  938. Parameters
  939. ----------
  940. edges : Graph object, collection of edges, or None
  941. The first parameter can be a graph or some edges. If it has
  942. attributes `nodes` and `edges`, then it is taken to be a
  943. Graph-like object and those attributes are used as collections
  944. of nodes and edges to be added to the graph.
  945. If the first parameter does not have those attributes, it is
  946. treated as a collection of edges and added to the graph.
  947. If the first argument is None, no edges are added.
  948. nodes : collection of nodes, or None
  949. The second parameter is treated as a collection of nodes
  950. to be added to the graph unless it is None.
  951. If `edges is None` and `nodes is None` an exception is raised.
  952. If the first parameter is a Graph, then `nodes` is ignored.
  953. Examples
  954. --------
  955. >>> G = nx.path_graph(5)
  956. >>> G.update(nx.complete_graph(range(4, 10)))
  957. >>> from itertools import combinations
  958. >>> edges = (
  959. ... (u, v, {"power": u * v})
  960. ... for u, v in combinations(range(10, 20), 2)
  961. ... if u * v < 225
  962. ... )
  963. >>> nodes = [1000] # for singleton, use a container
  964. >>> G.update(edges, nodes)
  965. Notes
  966. -----
  967. It you want to update the graph using an adjacency structure
  968. it is straightforward to obtain the edges/nodes from adjacency.
  969. The following examples provide common cases, your adjacency may
  970. be slightly different and require tweaks of these examples::
  971. >>> # dict-of-set/list/tuple
  972. >>> adj = {1: {2, 3}, 2: {1, 3}, 3: {1, 2}}
  973. >>> e = [(u, v) for u, nbrs in adj.items() for v in nbrs]
  974. >>> G.update(edges=e, nodes=adj)
  975. >>> DG = nx.DiGraph()
  976. >>> # dict-of-dict-of-attribute
  977. >>> adj = {1: {2: 1.3, 3: 0.7}, 2: {1: 1.4}, 3: {1: 0.7}}
  978. >>> e = [
  979. ... (u, v, {"weight": d})
  980. ... for u, nbrs in adj.items()
  981. ... for v, d in nbrs.items()
  982. ... ]
  983. >>> DG.update(edges=e, nodes=adj)
  984. >>> # dict-of-dict-of-dict
  985. >>> adj = {1: {2: {"weight": 1.3}, 3: {"color": 0.7, "weight": 1.2}}}
  986. >>> e = [
  987. ... (u, v, {"weight": d})
  988. ... for u, nbrs in adj.items()
  989. ... for v, d in nbrs.items()
  990. ... ]
  991. >>> DG.update(edges=e, nodes=adj)
  992. >>> # predecessor adjacency (dict-of-set)
  993. >>> pred = {1: {2, 3}, 2: {3}, 3: {3}}
  994. >>> e = [(v, u) for u, nbrs in pred.items() for v in nbrs]
  995. >>> # MultiGraph dict-of-dict-of-dict-of-attribute
  996. >>> MDG = nx.MultiDiGraph()
  997. >>> adj = {
  998. ... 1: {2: {0: {"weight": 1.3}, 1: {"weight": 1.2}}},
  999. ... 3: {2: {0: {"weight": 0.7}}},
  1000. ... }
  1001. >>> e = [
  1002. ... (u, v, ekey, d)
  1003. ... for u, nbrs in adj.items()
  1004. ... for v, keydict in nbrs.items()
  1005. ... for ekey, d in keydict.items()
  1006. ... ]
  1007. >>> MDG.update(edges=e)
  1008. See Also
  1009. --------
  1010. add_edges_from: add multiple edges to a graph
  1011. add_nodes_from: add multiple nodes to a graph
  1012. """
  1013. if edges is not None:
  1014. if nodes is not None:
  1015. self.add_nodes_from(nodes)
  1016. self.add_edges_from(edges)
  1017. else:
  1018. # check if edges is a Graph object
  1019. try:
  1020. graph_nodes = edges.nodes
  1021. graph_edges = edges.edges
  1022. except AttributeError:
  1023. # edge not Graph-like
  1024. self.add_edges_from(edges)
  1025. else: # edges is Graph-like
  1026. self.add_nodes_from(graph_nodes.data())
  1027. self.add_edges_from(graph_edges.data())
  1028. self.graph.update(edges.graph)
  1029. elif nodes is not None:
  1030. self.add_nodes_from(nodes)
  1031. else:
  1032. raise NetworkXError("update needs nodes or edges input")
  1033. def has_edge(self, u, v):
  1034. """Returns True if the edge (u, v) is in the graph.
  1035. This is the same as `v in G[u]` without KeyError exceptions.
  1036. Parameters
  1037. ----------
  1038. u, v : nodes
  1039. Nodes can be, for example, strings or numbers.
  1040. Nodes must be hashable (and not None) Python objects.
  1041. Returns
  1042. -------
  1043. edge_ind : bool
  1044. True if edge is in the graph, False otherwise.
  1045. Examples
  1046. --------
  1047. >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
  1048. >>> G.has_edge(0, 1) # using two nodes
  1049. True
  1050. >>> e = (0, 1)
  1051. >>> G.has_edge(*e) # e is a 2-tuple (u, v)
  1052. True
  1053. >>> e = (0, 1, {"weight": 7})
  1054. >>> G.has_edge(*e[:2]) # e is a 3-tuple (u, v, data_dictionary)
  1055. True
  1056. The following syntax are equivalent:
  1057. >>> G.has_edge(0, 1)
  1058. True
  1059. >>> 1 in G[0] # though this gives KeyError if 0 not in G
  1060. True
  1061. """
  1062. try:
  1063. return v in self._adj[u]
  1064. except KeyError:
  1065. return False
  1066. def neighbors(self, n):
  1067. """Returns an iterator over all neighbors of node n.
  1068. This is identical to `iter(G[n])`
  1069. Parameters
  1070. ----------
  1071. n : node
  1072. A node in the graph
  1073. Returns
  1074. -------
  1075. neighbors : iterator
  1076. An iterator over all neighbors of node n
  1077. Raises
  1078. ------
  1079. NetworkXError
  1080. If the node n is not in the graph.
  1081. Examples
  1082. --------
  1083. >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
  1084. >>> [n for n in G.neighbors(0)]
  1085. [1]
  1086. Notes
  1087. -----
  1088. Alternate ways to access the neighbors are ``G.adj[n]`` or ``G[n]``:
  1089. >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
  1090. >>> G.add_edge("a", "b", weight=7)
  1091. >>> G["a"]
  1092. AtlasView({'b': {'weight': 7}})
  1093. >>> G = nx.path_graph(4)
  1094. >>> [n for n in G[0]]
  1095. [1]
  1096. """
  1097. try:
  1098. return iter(self._adj[n])
  1099. except KeyError as err:
  1100. raise NetworkXError(f"The node {n} is not in the graph.") from err
  1101. @cached_property
  1102. def edges(self):
  1103. """An EdgeView of the Graph as G.edges or G.edges().
  1104. edges(self, nbunch=None, data=False, default=None)
  1105. The EdgeView provides set-like operations on the edge-tuples
  1106. as well as edge attribute lookup. When called, it also provides
  1107. an EdgeDataView object which allows control of access to edge
  1108. attributes (but does not provide set-like operations).
  1109. Hence, `G.edges[u, v]['color']` provides the value of the color
  1110. attribute for edge `(u, v)` while
  1111. `for (u, v, c) in G.edges.data('color', default='red'):`
  1112. iterates through all the edges yielding the color attribute
  1113. with default `'red'` if no color attribute exists.
  1114. Parameters
  1115. ----------
  1116. nbunch : single node, container, or all nodes (default= all nodes)
  1117. The view will only report edges from these nodes.
  1118. data : string or bool, optional (default=False)
  1119. The edge attribute returned in 3-tuple (u, v, ddict[data]).
  1120. If True, return edge attribute dict in 3-tuple (u, v, ddict).
  1121. If False, return 2-tuple (u, v).
  1122. default : value, optional (default=None)
  1123. Value used for edges that don't have the requested attribute.
  1124. Only relevant if data is not True or False.
  1125. Returns
  1126. -------
  1127. edges : EdgeView
  1128. A view of edge attributes, usually it iterates over (u, v)
  1129. or (u, v, d) tuples of edges, but can also be used for
  1130. attribute lookup as `edges[u, v]['foo']`.
  1131. Notes
  1132. -----
  1133. Nodes in nbunch that are not in the graph will be (quietly) ignored.
  1134. For directed graphs this returns the out-edges.
  1135. Examples
  1136. --------
  1137. >>> G = nx.path_graph(3) # or MultiGraph, etc
  1138. >>> G.add_edge(2, 3, weight=5)
  1139. >>> [e for e in G.edges]
  1140. [(0, 1), (1, 2), (2, 3)]
  1141. >>> G.edges.data() # default data is {} (empty dict)
  1142. EdgeDataView([(0, 1, {}), (1, 2, {}), (2, 3, {'weight': 5})])
  1143. >>> G.edges.data("weight", default=1)
  1144. EdgeDataView([(0, 1, 1), (1, 2, 1), (2, 3, 5)])
  1145. >>> G.edges([0, 3]) # only edges from these nodes
  1146. EdgeDataView([(0, 1), (3, 2)])
  1147. >>> G.edges(0) # only edges from node 0
  1148. EdgeDataView([(0, 1)])
  1149. """
  1150. return EdgeView(self)
  1151. def get_edge_data(self, u, v, default=None):
  1152. """Returns the attribute dictionary associated with edge (u, v).
  1153. This is identical to `G[u][v]` except the default is returned
  1154. instead of an exception if the edge doesn't exist.
  1155. Parameters
  1156. ----------
  1157. u, v : nodes
  1158. default: any Python object (default=None)
  1159. Value to return if the edge (u, v) is not found.
  1160. Returns
  1161. -------
  1162. edge_dict : dictionary
  1163. The edge attribute dictionary.
  1164. Examples
  1165. --------
  1166. >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
  1167. >>> G[0][1]
  1168. {}
  1169. Warning: Assigning to `G[u][v]` is not permitted.
  1170. But it is safe to assign attributes `G[u][v]['foo']`
  1171. >>> G[0][1]["weight"] = 7
  1172. >>> G[0][1]["weight"]
  1173. 7
  1174. >>> G[1][0]["weight"]
  1175. 7
  1176. >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
  1177. >>> G.get_edge_data(0, 1) # default edge data is {}
  1178. {}
  1179. >>> e = (0, 1)
  1180. >>> G.get_edge_data(*e) # tuple form
  1181. {}
  1182. >>> G.get_edge_data("a", "b", default=0) # edge not in graph, return 0
  1183. 0
  1184. """
  1185. try:
  1186. return self._adj[u][v]
  1187. except KeyError:
  1188. return default
  1189. def adjacency(self):
  1190. """Returns an iterator over (node, adjacency dict) tuples for all nodes.
  1191. For directed graphs, only outgoing neighbors/adjacencies are included.
  1192. Returns
  1193. -------
  1194. adj_iter : iterator
  1195. An iterator over (node, adjacency dictionary) for all nodes in
  1196. the graph.
  1197. Examples
  1198. --------
  1199. >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
  1200. >>> [(n, nbrdict) for n, nbrdict in G.adjacency()]
  1201. [(0, {1: {}}), (1, {0: {}, 2: {}}), (2, {1: {}, 3: {}}), (3, {2: {}})]
  1202. """
  1203. return iter(self._adj.items())
  1204. @cached_property
  1205. def degree(self):
  1206. """A DegreeView for the Graph as G.degree or G.degree().
  1207. The node degree is the number of edges adjacent to the node.
  1208. The weighted node degree is the sum of the edge weights for
  1209. edges incident to that node.
  1210. This object provides an iterator for (node, degree) as well as
  1211. lookup for the degree for a single node.
  1212. Parameters
  1213. ----------
  1214. nbunch : single node, container, or all nodes (default= all nodes)
  1215. The view will only report edges incident to these nodes.
  1216. weight : string or None, optional (default=None)
  1217. The name of an edge attribute that holds the numerical value used
  1218. as a weight. If None, then each edge has weight 1.
  1219. The degree is the sum of the edge weights adjacent to the node.
  1220. Returns
  1221. -------
  1222. DegreeView or int
  1223. If multiple nodes are requested (the default), returns a `DegreeView`
  1224. mapping nodes to their degree.
  1225. If a single node is requested, returns the degree of the node as an integer.
  1226. Examples
  1227. --------
  1228. >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
  1229. >>> G.degree[0] # node 0 has degree 1
  1230. 1
  1231. >>> list(G.degree([0, 1, 2]))
  1232. [(0, 1), (1, 2), (2, 2)]
  1233. """
  1234. return DegreeView(self)
  1235. def clear(self):
  1236. """Remove all nodes and edges from the graph.
  1237. This also removes the name, and all graph, node, and edge attributes.
  1238. Examples
  1239. --------
  1240. >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
  1241. >>> G.clear()
  1242. >>> list(G.nodes)
  1243. []
  1244. >>> list(G.edges)
  1245. []
  1246. """
  1247. self._adj.clear()
  1248. self._node.clear()
  1249. self.graph.clear()
  1250. def clear_edges(self):
  1251. """Remove all edges from the graph without altering nodes.
  1252. Examples
  1253. --------
  1254. >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
  1255. >>> G.clear_edges()
  1256. >>> list(G.nodes)
  1257. [0, 1, 2, 3]
  1258. >>> list(G.edges)
  1259. []
  1260. """
  1261. for neighbours_dict in self._adj.values():
  1262. neighbours_dict.clear()
  1263. def is_multigraph(self):
  1264. """Returns True if graph is a multigraph, False otherwise."""
  1265. return False
  1266. def is_directed(self):
  1267. """Returns True if graph is directed, False otherwise."""
  1268. return False
  1269. def copy(self, as_view=False):
  1270. """Returns a copy of the graph.
  1271. The copy method by default returns an independent shallow copy
  1272. of the graph and attributes. That is, if an attribute is a
  1273. container, that container is shared by the original an the copy.
  1274. Use Python's `copy.deepcopy` for new containers.
  1275. If `as_view` is True then a view is returned instead of a copy.
  1276. Notes
  1277. -----
  1278. All copies reproduce the graph structure, but data attributes
  1279. may be handled in different ways. There are four types of copies
  1280. of a graph that people might want.
  1281. Deepcopy -- A "deepcopy" copies the graph structure as well as
  1282. all data attributes and any objects they might contain.
  1283. The entire graph object is new so that changes in the copy
  1284. do not affect the original object. (see Python's copy.deepcopy)
  1285. Data Reference (Shallow) -- For a shallow copy the graph structure
  1286. is copied but the edge, node and graph attribute dicts are
  1287. references to those in the original graph. This saves
  1288. time and memory but could cause confusion if you change an attribute
  1289. in one graph and it changes the attribute in the other.
  1290. NetworkX does not provide this level of shallow copy.
  1291. Independent Shallow -- This copy creates new independent attribute
  1292. dicts and then does a shallow copy of the attributes. That is, any
  1293. attributes that are containers are shared between the new graph
  1294. and the original. This is exactly what `dict.copy()` provides.
  1295. You can obtain this style copy using:
  1296. >>> G = nx.path_graph(5)
  1297. >>> H = G.copy()
  1298. >>> H = G.copy(as_view=False)
  1299. >>> H = nx.Graph(G)
  1300. >>> H = G.__class__(G)
  1301. Fresh Data -- For fresh data, the graph structure is copied while
  1302. new empty data attribute dicts are created. The resulting graph
  1303. is independent of the original and it has no edge, node or graph
  1304. attributes. Fresh copies are not enabled. Instead use:
  1305. >>> H = G.__class__()
  1306. >>> H.add_nodes_from(G)
  1307. >>> H.add_edges_from(G.edges)
  1308. View -- Inspired by dict-views, graph-views act like read-only
  1309. versions of the original graph, providing a copy of the original
  1310. structure without requiring any memory for copying the information.
  1311. See the Python copy module for more information on shallow
  1312. and deep copies, https://docs.python.org/3/library/copy.html.
  1313. Parameters
  1314. ----------
  1315. as_view : bool, optional (default=False)
  1316. If True, the returned graph-view provides a read-only view
  1317. of the original graph without actually copying any data.
  1318. Returns
  1319. -------
  1320. G : Graph
  1321. A copy of the graph.
  1322. See Also
  1323. --------
  1324. to_directed: return a directed copy of the graph.
  1325. Examples
  1326. --------
  1327. >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
  1328. >>> H = G.copy()
  1329. """
  1330. if as_view is True:
  1331. return nx.graphviews.generic_graph_view(self)
  1332. G = self.__class__()
  1333. G.graph.update(self.graph)
  1334. G.add_nodes_from((n, d.copy()) for n, d in self._node.items())
  1335. G.add_edges_from(
  1336. (u, v, datadict.copy())
  1337. for u, nbrs in self._adj.items()
  1338. for v, datadict in nbrs.items()
  1339. )
  1340. return G
  1341. def to_directed(self, as_view=False):
  1342. """Returns a directed representation of the graph.
  1343. Returns
  1344. -------
  1345. G : DiGraph
  1346. A directed graph with the same name, same nodes, and with
  1347. each edge (u, v, data) replaced by two directed edges
  1348. (u, v, data) and (v, u, data).
  1349. Notes
  1350. -----
  1351. This returns a "deepcopy" of the edge, node, and
  1352. graph attributes which attempts to completely copy
  1353. all of the data and references.
  1354. This is in contrast to the similar D=DiGraph(G) which returns a
  1355. shallow copy of the data.
  1356. See the Python copy module for more information on shallow
  1357. and deep copies, https://docs.python.org/3/library/copy.html.
  1358. Warning: If you have subclassed Graph to use dict-like objects
  1359. in the data structure, those changes do not transfer to the
  1360. DiGraph created by this method.
  1361. Examples
  1362. --------
  1363. >>> G = nx.Graph() # or MultiGraph, etc
  1364. >>> G.add_edge(0, 1)
  1365. >>> H = G.to_directed()
  1366. >>> list(H.edges)
  1367. [(0, 1), (1, 0)]
  1368. If already directed, return a (deep) copy
  1369. >>> G = nx.DiGraph() # or MultiDiGraph, etc
  1370. >>> G.add_edge(0, 1)
  1371. >>> H = G.to_directed()
  1372. >>> list(H.edges)
  1373. [(0, 1)]
  1374. """
  1375. graph_class = self.to_directed_class()
  1376. if as_view is True:
  1377. return nx.graphviews.generic_graph_view(self, graph_class)
  1378. # deepcopy when not a view
  1379. G = graph_class()
  1380. G.graph.update(deepcopy(self.graph))
  1381. G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
  1382. G.add_edges_from(
  1383. (u, v, deepcopy(data))
  1384. for u, nbrs in self._adj.items()
  1385. for v, data in nbrs.items()
  1386. )
  1387. return G
  1388. def to_undirected(self, as_view=False):
  1389. """Returns an undirected copy of the graph.
  1390. Parameters
  1391. ----------
  1392. as_view : bool (optional, default=False)
  1393. If True return a view of the original undirected graph.
  1394. Returns
  1395. -------
  1396. G : Graph/MultiGraph
  1397. A deepcopy of the graph.
  1398. See Also
  1399. --------
  1400. Graph, copy, add_edge, add_edges_from
  1401. Notes
  1402. -----
  1403. This returns a "deepcopy" of the edge, node, and
  1404. graph attributes which attempts to completely copy
  1405. all of the data and references.
  1406. This is in contrast to the similar `G = nx.DiGraph(D)` which returns a
  1407. shallow copy of the data.
  1408. See the Python copy module for more information on shallow
  1409. and deep copies, https://docs.python.org/3/library/copy.html.
  1410. Warning: If you have subclassed DiGraph to use dict-like objects
  1411. in the data structure, those changes do not transfer to the
  1412. Graph created by this method.
  1413. Examples
  1414. --------
  1415. >>> G = nx.path_graph(2) # or MultiGraph, etc
  1416. >>> H = G.to_directed()
  1417. >>> list(H.edges)
  1418. [(0, 1), (1, 0)]
  1419. >>> G2 = H.to_undirected()
  1420. >>> list(G2.edges)
  1421. [(0, 1)]
  1422. """
  1423. graph_class = self.to_undirected_class()
  1424. if as_view is True:
  1425. return nx.graphviews.generic_graph_view(self, graph_class)
  1426. # deepcopy when not a view
  1427. G = graph_class()
  1428. G.graph.update(deepcopy(self.graph))
  1429. G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
  1430. G.add_edges_from(
  1431. (u, v, deepcopy(d))
  1432. for u, nbrs in self._adj.items()
  1433. for v, d in nbrs.items()
  1434. )
  1435. return G
  1436. def subgraph(self, nodes):
  1437. """Returns a SubGraph view of the subgraph induced on `nodes`.
  1438. The induced subgraph of the graph contains the nodes in `nodes`
  1439. and the edges between those nodes.
  1440. Parameters
  1441. ----------
  1442. nodes : list, iterable
  1443. A container of nodes which will be iterated through once.
  1444. Returns
  1445. -------
  1446. G : SubGraph View
  1447. A subgraph view of the graph. The graph structure cannot be
  1448. changed but node/edge attributes can and are shared with the
  1449. original graph.
  1450. Notes
  1451. -----
  1452. The graph, edge and node attributes are shared with the original graph.
  1453. Changes to the graph structure is ruled out by the view, but changes
  1454. to attributes are reflected in the original graph.
  1455. To create a subgraph with its own copy of the edge/node attributes use:
  1456. G.subgraph(nodes).copy()
  1457. For an inplace reduction of a graph to a subgraph you can remove nodes:
  1458. G.remove_nodes_from([n for n in G if n not in set(nodes)])
  1459. Subgraph views are sometimes NOT what you want. In most cases where
  1460. you want to do more than simply look at the induced edges, it makes
  1461. more sense to just create the subgraph as its own graph with code like:
  1462. ::
  1463. # Create a subgraph SG based on a (possibly multigraph) G
  1464. SG = G.__class__()
  1465. SG.add_nodes_from((n, G.nodes[n]) for n in largest_wcc)
  1466. if SG.is_multigraph():
  1467. SG.add_edges_from((n, nbr, key, d)
  1468. for n, nbrs in G.adj.items() if n in largest_wcc
  1469. for nbr, keydict in nbrs.items() if nbr in largest_wcc
  1470. for key, d in keydict.items())
  1471. else:
  1472. SG.add_edges_from((n, nbr, d)
  1473. for n, nbrs in G.adj.items() if n in largest_wcc
  1474. for nbr, d in nbrs.items() if nbr in largest_wcc)
  1475. SG.graph.update(G.graph)
  1476. Examples
  1477. --------
  1478. >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
  1479. >>> H = G.subgraph([0, 1, 2])
  1480. >>> list(H.edges)
  1481. [(0, 1), (1, 2)]
  1482. """
  1483. induced_nodes = nx.filters.show_nodes(self.nbunch_iter(nodes))
  1484. # if already a subgraph, don't make a chain
  1485. subgraph = nx.graphviews.subgraph_view
  1486. if hasattr(self, "_NODE_OK"):
  1487. return subgraph(self._graph, induced_nodes, self._EDGE_OK)
  1488. return subgraph(self, induced_nodes)
  1489. def edge_subgraph(self, edges):
  1490. """Returns the subgraph induced by the specified edges.
  1491. The induced subgraph contains each edge in `edges` and each
  1492. node incident to any one of those edges.
  1493. Parameters
  1494. ----------
  1495. edges : iterable
  1496. An iterable of edges in this graph.
  1497. Returns
  1498. -------
  1499. G : Graph
  1500. An edge-induced subgraph of this graph with the same edge
  1501. attributes.
  1502. Notes
  1503. -----
  1504. The graph, edge, and node attributes in the returned subgraph
  1505. view are references to the corresponding attributes in the original
  1506. graph. The view is read-only.
  1507. To create a full graph version of the subgraph with its own copy
  1508. of the edge or node attributes, use::
  1509. G.edge_subgraph(edges).copy()
  1510. Examples
  1511. --------
  1512. >>> G = nx.path_graph(5)
  1513. >>> H = G.edge_subgraph([(0, 1), (3, 4)])
  1514. >>> list(H.nodes)
  1515. [0, 1, 3, 4]
  1516. >>> list(H.edges)
  1517. [(0, 1), (3, 4)]
  1518. """
  1519. return nx.edge_subgraph(self, edges)
  1520. def size(self, weight=None):
  1521. """Returns the number of edges or total of all edge weights.
  1522. Parameters
  1523. ----------
  1524. weight : string or None, optional (default=None)
  1525. The edge attribute that holds the numerical value used
  1526. as a weight. If None, then each edge has weight 1.
  1527. Returns
  1528. -------
  1529. size : numeric
  1530. The number of edges or
  1531. (if weight keyword is provided) the total weight sum.
  1532. If weight is None, returns an int. Otherwise a float
  1533. (or more general numeric if the weights are more general).
  1534. See Also
  1535. --------
  1536. number_of_edges
  1537. Examples
  1538. --------
  1539. >>> G = nx.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc
  1540. >>> G.size()
  1541. 3
  1542. >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
  1543. >>> G.add_edge("a", "b", weight=2)
  1544. >>> G.add_edge("b", "c", weight=4)
  1545. >>> G.size()
  1546. 2
  1547. >>> G.size(weight="weight")
  1548. 6.0
  1549. """
  1550. s = sum(d for v, d in self.degree(weight=weight))
  1551. # If `weight` is None, the sum of the degrees is guaranteed to be
  1552. # even, so we can perform integer division and hence return an
  1553. # integer. Otherwise, the sum of the weighted degrees is not
  1554. # guaranteed to be an integer, so we perform "real" division.
  1555. return s // 2 if weight is None else s / 2
  1556. def number_of_edges(self, u=None, v=None):
  1557. """Returns the number of edges between two nodes.
  1558. Parameters
  1559. ----------
  1560. u, v : nodes, optional (default=all edges)
  1561. If u and v are specified, return the number of edges between
  1562. u and v. Otherwise return the total number of all edges.
  1563. Returns
  1564. -------
  1565. nedges : int
  1566. The number of edges in the graph. If nodes `u` and `v` are
  1567. specified return the number of edges between those nodes. If
  1568. the graph is directed, this only returns the number of edges
  1569. from `u` to `v`.
  1570. See Also
  1571. --------
  1572. size
  1573. Examples
  1574. --------
  1575. For undirected graphs, this method counts the total number of
  1576. edges in the graph:
  1577. >>> G = nx.path_graph(4)
  1578. >>> G.number_of_edges()
  1579. 3
  1580. If you specify two nodes, this counts the total number of edges
  1581. joining the two nodes:
  1582. >>> G.number_of_edges(0, 1)
  1583. 1
  1584. For directed graphs, this method can count the total number of
  1585. directed edges from `u` to `v`:
  1586. >>> G = nx.DiGraph()
  1587. >>> G.add_edge(0, 1)
  1588. >>> G.add_edge(1, 0)
  1589. >>> G.number_of_edges(0, 1)
  1590. 1
  1591. """
  1592. if u is None:
  1593. return int(self.size())
  1594. if v in self._adj[u]:
  1595. return 1
  1596. return 0
  1597. def nbunch_iter(self, nbunch=None):
  1598. """Returns an iterator over nodes contained in nbunch that are
  1599. also in the graph.
  1600. The nodes in nbunch are checked for membership in the graph
  1601. and if not are silently ignored.
  1602. Parameters
  1603. ----------
  1604. nbunch : single node, container, or all nodes (default= all nodes)
  1605. The view will only report edges incident to these nodes.
  1606. Returns
  1607. -------
  1608. niter : iterator
  1609. An iterator over nodes in nbunch that are also in the graph.
  1610. If nbunch is None, iterate over all nodes in the graph.
  1611. Raises
  1612. ------
  1613. NetworkXError
  1614. If nbunch is not a node or sequence of nodes.
  1615. If a node in nbunch is not hashable.
  1616. See Also
  1617. --------
  1618. Graph.__iter__
  1619. Notes
  1620. -----
  1621. When nbunch is an iterator, the returned iterator yields values
  1622. directly from nbunch, becoming exhausted when nbunch is exhausted.
  1623. To test whether nbunch is a single node, one can use
  1624. "if nbunch in self:", even after processing with this routine.
  1625. If nbunch is not a node or a (possibly empty) sequence/iterator
  1626. or None, a :exc:`NetworkXError` is raised. Also, if any object in
  1627. nbunch is not hashable, a :exc:`NetworkXError` is raised.
  1628. """
  1629. if nbunch is None: # include all nodes via iterator
  1630. bunch = iter(self._adj)
  1631. elif nbunch in self: # if nbunch is a single node
  1632. bunch = iter([nbunch])
  1633. else: # if nbunch is a sequence of nodes
  1634. def bunch_iter(nlist, adj):
  1635. try:
  1636. for n in nlist:
  1637. if n in adj:
  1638. yield n
  1639. except TypeError as err:
  1640. exc, message = err, err.args[0]
  1641. # capture error for non-sequence/iterator nbunch.
  1642. if "iter" in message:
  1643. exc = NetworkXError(
  1644. "nbunch is not a node or a sequence of nodes."
  1645. )
  1646. # capture error for unhashable node.
  1647. if "hashable" in message:
  1648. exc = NetworkXError(
  1649. f"Node {n} in sequence nbunch is not a valid node."
  1650. )
  1651. raise exc
  1652. bunch = bunch_iter(nbunch, self._adj)
  1653. return bunch