graph.py 71 KB

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