Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.9/dist-packages/networkx/classes/multidigraph.py: 58%
117 statements
« prev ^ index » next coverage.py v7.3.2, created at 2023-10-20 07:00 +0000
« prev ^ index » next coverage.py v7.3.2, created at 2023-10-20 07:00 +0000
1"""Base class for MultiDiGraph."""
2from copy import deepcopy
3from functools import cached_property
5import networkx as nx
6from networkx import convert
7from networkx.classes.coreviews import MultiAdjacencyView
8from networkx.classes.digraph import DiGraph
9from networkx.classes.multigraph import MultiGraph
10from networkx.classes.reportviews import (
11 DiMultiDegreeView,
12 InMultiDegreeView,
13 InMultiEdgeView,
14 OutMultiDegreeView,
15 OutMultiEdgeView,
16)
17from networkx.exception import NetworkXError
19__all__ = ["MultiDiGraph"]
22class MultiDiGraph(MultiGraph, DiGraph):
23 """A directed graph class that can store multiedges.
25 Multiedges are multiple edges between two nodes. Each edge
26 can hold optional data or attributes.
28 A MultiDiGraph holds directed edges. Self loops are allowed.
30 Nodes can be arbitrary (hashable) Python objects with optional
31 key/value attributes. By convention `None` is not used as a node.
33 Edges are represented as links between nodes with optional
34 key/value attributes.
36 Parameters
37 ----------
38 incoming_graph_data : input graph (optional, default: None)
39 Data to initialize graph. If None (default) an empty
40 graph is created. The data can be any format that is supported
41 by the to_networkx_graph() function, currently including edge list,
42 dict of dicts, dict of lists, NetworkX graph, 2D NumPy array, SciPy
43 sparse matrix, or PyGraphviz graph.
45 multigraph_input : bool or None (default None)
46 Note: Only used when `incoming_graph_data` is a dict.
47 If True, `incoming_graph_data` is assumed to be a
48 dict-of-dict-of-dict-of-dict structure keyed by
49 node to neighbor to edge keys to edge data for multi-edges.
50 A NetworkXError is raised if this is not the case.
51 If False, :func:`to_networkx_graph` is used to try to determine
52 the dict's graph data structure as either a dict-of-dict-of-dict
53 keyed by node to neighbor to edge data, or a dict-of-iterable
54 keyed by node to neighbors.
55 If None, the treatment for True is tried, but if it fails,
56 the treatment for False is tried.
58 attr : keyword arguments, optional (default= no attributes)
59 Attributes to add to graph as key=value pairs.
61 See Also
62 --------
63 Graph
64 DiGraph
65 MultiGraph
67 Examples
68 --------
69 Create an empty graph structure (a "null graph") with no nodes and
70 no edges.
72 >>> G = nx.MultiDiGraph()
74 G can be grown in several ways.
76 **Nodes:**
78 Add one node at a time:
80 >>> G.add_node(1)
82 Add the nodes from any container (a list, dict, set or
83 even the lines from a file or the nodes from another graph).
85 >>> G.add_nodes_from([2, 3])
86 >>> G.add_nodes_from(range(100, 110))
87 >>> H = nx.path_graph(10)
88 >>> G.add_nodes_from(H)
90 In addition to strings and integers any hashable Python object
91 (except None) can represent a node, e.g. a customized node object,
92 or even another Graph.
94 >>> G.add_node(H)
96 **Edges:**
98 G can also be grown by adding edges.
100 Add one edge,
102 >>> key = G.add_edge(1, 2)
104 a list of edges,
106 >>> keys = G.add_edges_from([(1, 2), (1, 3)])
108 or a collection of edges,
110 >>> keys = G.add_edges_from(H.edges)
112 If some edges connect nodes not yet in the graph, the nodes
113 are added automatically. If an edge already exists, an additional
114 edge is created and stored using a key to identify the edge.
115 By default the key is the lowest unused integer.
117 >>> keys = G.add_edges_from([(4, 5, dict(route=282)), (4, 5, dict(route=37))])
118 >>> G[4]
119 AdjacencyView({5: {0: {}, 1: {'route': 282}, 2: {'route': 37}}})
121 **Attributes:**
123 Each graph, node, and edge can hold key/value attribute pairs
124 in an associated attribute dictionary (the keys must be hashable).
125 By default these are empty, but can be added or changed using
126 add_edge, add_node or direct manipulation of the attribute
127 dictionaries named graph, node and edge respectively.
129 >>> G = nx.MultiDiGraph(day="Friday")
130 >>> G.graph
131 {'day': 'Friday'}
133 Add node attributes using add_node(), add_nodes_from() or G.nodes
135 >>> G.add_node(1, time="5pm")
136 >>> G.add_nodes_from([3], time="2pm")
137 >>> G.nodes[1]
138 {'time': '5pm'}
139 >>> G.nodes[1]["room"] = 714
140 >>> del G.nodes[1]["room"] # remove attribute
141 >>> list(G.nodes(data=True))
142 [(1, {'time': '5pm'}), (3, {'time': '2pm'})]
144 Add edge attributes using add_edge(), add_edges_from(), subscript
145 notation, or G.edges.
147 >>> key = G.add_edge(1, 2, weight=4.7)
148 >>> keys = G.add_edges_from([(3, 4), (4, 5)], color="red")
149 >>> keys = G.add_edges_from([(1, 2, {"color": "blue"}), (2, 3, {"weight": 8})])
150 >>> G[1][2][0]["weight"] = 4.7
151 >>> G.edges[1, 2, 0]["weight"] = 4
153 Warning: we protect the graph data structure by making `G.edges[1,
154 2, 0]` a read-only dict-like structure. However, you can assign to
155 attributes in e.g. `G.edges[1, 2, 0]`. Thus, use 2 sets of brackets
156 to add/change data attributes: `G.edges[1, 2, 0]['weight'] = 4`
157 (for multigraphs the edge key is required: `MG.edges[u, v,
158 key][name] = value`).
160 **Shortcuts:**
162 Many common graph features allow python syntax to speed reporting.
164 >>> 1 in G # check if node in graph
165 True
166 >>> [n for n in G if n < 3] # iterate through nodes
167 [1, 2]
168 >>> len(G) # number of nodes in graph
169 5
170 >>> G[1] # adjacency dict-like view mapping neighbor -> edge key -> edge attributes
171 AdjacencyView({2: {0: {'weight': 4}, 1: {'color': 'blue'}}})
173 Often the best way to traverse all edges of a graph is via the neighbors.
174 The neighbors are available as an adjacency-view `G.adj` object or via
175 the method `G.adjacency()`.
177 >>> for n, nbrsdict in G.adjacency():
178 ... for nbr, keydict in nbrsdict.items():
179 ... for key, eattr in keydict.items():
180 ... if "weight" in eattr:
181 ... # Do something useful with the edges
182 ... pass
184 But the edges() method is often more convenient:
186 >>> for u, v, keys, weight in G.edges(data="weight", keys=True):
187 ... if weight is not None:
188 ... # Do something useful with the edges
189 ... pass
191 **Reporting:**
193 Simple graph information is obtained using methods and object-attributes.
194 Reporting usually provides views instead of containers to reduce memory
195 usage. The views update as the graph is updated similarly to dict-views.
196 The objects `nodes`, `edges` and `adj` provide access to data attributes
197 via lookup (e.g. `nodes[n]`, `edges[u, v, k]`, `adj[u][v]`) and iteration
198 (e.g. `nodes.items()`, `nodes.data('color')`,
199 `nodes.data('color', default='blue')` and similarly for `edges`)
200 Views exist for `nodes`, `edges`, `neighbors()`/`adj` and `degree`.
202 For details on these and other miscellaneous methods, see below.
204 **Subclasses (Advanced):**
206 The MultiDiGraph class uses a dict-of-dict-of-dict-of-dict structure.
207 The outer dict (node_dict) holds adjacency information keyed by node.
208 The next dict (adjlist_dict) represents the adjacency information
209 and holds edge_key dicts keyed by neighbor. The edge_key dict holds
210 each edge_attr dict keyed by edge key. The inner dict
211 (edge_attr_dict) represents the edge data and holds edge attribute
212 values keyed by attribute names.
214 Each of these four dicts in the dict-of-dict-of-dict-of-dict
215 structure can be replaced by a user defined dict-like object.
216 In general, the dict-like features should be maintained but
217 extra features can be added. To replace one of the dicts create
218 a new graph class by changing the class(!) variable holding the
219 factory for that dict-like structure. The variable names are
220 node_dict_factory, node_attr_dict_factory, adjlist_inner_dict_factory,
221 adjlist_outer_dict_factory, edge_key_dict_factory, edge_attr_dict_factory
222 and graph_attr_dict_factory.
224 node_dict_factory : function, (default: dict)
225 Factory function to be used to create the dict containing node
226 attributes, keyed by node id.
227 It should require no arguments and return a dict-like object
229 node_attr_dict_factory: function, (default: dict)
230 Factory function to be used to create the node attribute
231 dict which holds attribute values keyed by attribute name.
232 It should require no arguments and return a dict-like object
234 adjlist_outer_dict_factory : function, (default: dict)
235 Factory function to be used to create the outer-most dict
236 in the data structure that holds adjacency info keyed by node.
237 It should require no arguments and return a dict-like object.
239 adjlist_inner_dict_factory : function, (default: dict)
240 Factory function to be used to create the adjacency list
241 dict which holds multiedge key dicts keyed by neighbor.
242 It should require no arguments and return a dict-like object.
244 edge_key_dict_factory : function, (default: dict)
245 Factory function to be used to create the edge key dict
246 which holds edge data keyed by edge key.
247 It should require no arguments and return a dict-like object.
249 edge_attr_dict_factory : function, (default: dict)
250 Factory function to be used to create the edge attribute
251 dict which holds attribute values keyed by attribute name.
252 It should require no arguments and return a dict-like object.
254 graph_attr_dict_factory : function, (default: dict)
255 Factory function to be used to create the graph attribute
256 dict which holds attribute values keyed by attribute name.
257 It should require no arguments and return a dict-like object.
259 Typically, if your extension doesn't impact the data structure all
260 methods will inherited without issue except: `to_directed/to_undirected`.
261 By default these methods create a DiGraph/Graph class and you probably
262 want them to create your extension of a DiGraph/Graph. To facilitate
263 this we define two class variables that you can set in your subclass.
265 to_directed_class : callable, (default: DiGraph or MultiDiGraph)
266 Class to create a new graph structure in the `to_directed` method.
267 If `None`, a NetworkX class (DiGraph or MultiDiGraph) is used.
269 to_undirected_class : callable, (default: Graph or MultiGraph)
270 Class to create a new graph structure in the `to_undirected` method.
271 If `None`, a NetworkX class (Graph or MultiGraph) is used.
273 **Subclassing Example**
275 Create a low memory graph class that effectively disallows edge
276 attributes by using a single attribute dict for all edges.
277 This reduces the memory used, but you lose edge attributes.
279 >>> class ThinGraph(nx.Graph):
280 ... all_edge_dict = {"weight": 1}
281 ...
282 ... def single_edge_dict(self):
283 ... return self.all_edge_dict
284 ...
285 ... edge_attr_dict_factory = single_edge_dict
286 >>> G = ThinGraph()
287 >>> G.add_edge(2, 1)
288 >>> G[2][1]
289 {'weight': 1}
290 >>> G.add_edge(2, 2)
291 >>> G[2][1] is G[2][2]
292 True
293 """
295 # node_dict_factory = dict # already assigned in Graph
296 # adjlist_outer_dict_factory = dict
297 # adjlist_inner_dict_factory = dict
298 edge_key_dict_factory = dict
299 # edge_attr_dict_factory = dict
301 def __init__(self, incoming_graph_data=None, multigraph_input=None, **attr):
302 """Initialize a graph with edges, name, or graph attributes.
304 Parameters
305 ----------
306 incoming_graph_data : input graph
307 Data to initialize graph. If incoming_graph_data=None (default)
308 an empty graph is created. The data can be an edge list, or any
309 NetworkX graph object. If the corresponding optional Python
310 packages are installed the data can also be a 2D NumPy array, a
311 SciPy sparse array, or a PyGraphviz graph.
313 multigraph_input : bool or None (default None)
314 Note: Only used when `incoming_graph_data` is a dict.
315 If True, `incoming_graph_data` is assumed to be a
316 dict-of-dict-of-dict-of-dict structure keyed by
317 node to neighbor to edge keys to edge data for multi-edges.
318 A NetworkXError is raised if this is not the case.
319 If False, :func:`to_networkx_graph` is used to try to determine
320 the dict's graph data structure as either a dict-of-dict-of-dict
321 keyed by node to neighbor to edge data, or a dict-of-iterable
322 keyed by node to neighbors.
323 If None, the treatment for True is tried, but if it fails,
324 the treatment for False is tried.
326 attr : keyword arguments, optional (default= no attributes)
327 Attributes to add to graph as key=value pairs.
329 See Also
330 --------
331 convert
333 Examples
334 --------
335 >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc
336 >>> G = nx.Graph(name="my graph")
337 >>> e = [(1, 2), (2, 3), (3, 4)] # list of edges
338 >>> G = nx.Graph(e)
340 Arbitrary graph attribute pairs (key=value) may be assigned
342 >>> G = nx.Graph(e, day="Friday")
343 >>> G.graph
344 {'day': 'Friday'}
346 """
347 # multigraph_input can be None/True/False. So check "is not False"
348 if isinstance(incoming_graph_data, dict) and multigraph_input is not False:
349 DiGraph.__init__(self)
350 try:
351 convert.from_dict_of_dicts(
352 incoming_graph_data, create_using=self, multigraph_input=True
353 )
354 self.graph.update(attr)
355 except Exception as err:
356 if multigraph_input is True:
357 raise nx.NetworkXError(
358 f"converting multigraph_input raised:\n{type(err)}: {err}"
359 )
360 DiGraph.__init__(self, incoming_graph_data, **attr)
361 else:
362 DiGraph.__init__(self, incoming_graph_data, **attr)
364 @cached_property
365 def adj(self):
366 """Graph adjacency object holding the neighbors of each node.
368 This object is a read-only dict-like structure with node keys
369 and neighbor-dict values. The neighbor-dict is keyed by neighbor
370 to the edgekey-dict. So `G.adj[3][2][0]['color'] = 'blue'` sets
371 the color of the edge `(3, 2, 0)` to `"blue"`.
373 Iterating over G.adj behaves like a dict. Useful idioms include
374 `for nbr, datadict in G.adj[n].items():`.
376 The neighbor information is also provided by subscripting the graph.
377 So `for nbr, foovalue in G[node].data('foo', default=1):` works.
379 For directed graphs, `G.adj` holds outgoing (successor) info.
380 """
381 return MultiAdjacencyView(self._succ)
383 @cached_property
384 def succ(self):
385 """Graph adjacency object holding the successors of each node.
387 This object is a read-only dict-like structure with node keys
388 and neighbor-dict values. The neighbor-dict is keyed by neighbor
389 to the edgekey-dict. So `G.adj[3][2][0]['color'] = 'blue'` sets
390 the color of the edge `(3, 2, 0)` to `"blue"`.
392 Iterating over G.adj behaves like a dict. Useful idioms include
393 `for nbr, datadict in G.adj[n].items():`.
395 The neighbor information is also provided by subscripting the graph.
396 So `for nbr, foovalue in G[node].data('foo', default=1):` works.
398 For directed graphs, `G.succ` is identical to `G.adj`.
399 """
400 return MultiAdjacencyView(self._succ)
402 @cached_property
403 def pred(self):
404 """Graph adjacency object holding the predecessors of each node.
406 This object is a read-only dict-like structure with node keys
407 and neighbor-dict values. The neighbor-dict is keyed by neighbor
408 to the edgekey-dict. So `G.adj[3][2][0]['color'] = 'blue'` sets
409 the color of the edge `(3, 2, 0)` to `"blue"`.
411 Iterating over G.adj behaves like a dict. Useful idioms include
412 `for nbr, datadict in G.adj[n].items():`.
413 """
414 return MultiAdjacencyView(self._pred)
416 def add_edge(self, u_for_edge, v_for_edge, key=None, **attr):
417 """Add an edge between u and v.
419 The nodes u and v will be automatically added if they are
420 not already in the graph.
422 Edge attributes can be specified with keywords or by directly
423 accessing the edge's attribute dictionary. See examples below.
425 Parameters
426 ----------
427 u_for_edge, v_for_edge : nodes
428 Nodes can be, for example, strings or numbers.
429 Nodes must be hashable (and not None) Python objects.
430 key : hashable identifier, optional (default=lowest unused integer)
431 Used to distinguish multiedges between a pair of nodes.
432 attr : keyword arguments, optional
433 Edge data (or labels or objects) can be assigned using
434 keyword arguments.
436 Returns
437 -------
438 The edge key assigned to the edge.
440 See Also
441 --------
442 add_edges_from : add a collection of edges
444 Notes
445 -----
446 To replace/update edge data, use the optional key argument
447 to identify a unique edge. Otherwise a new edge will be created.
449 NetworkX algorithms designed for weighted graphs cannot use
450 multigraphs directly because it is not clear how to handle
451 multiedge weights. Convert to Graph using edge attribute
452 'weight' to enable weighted graph algorithms.
454 Default keys are generated using the method `new_edge_key()`.
455 This method can be overridden by subclassing the base class and
456 providing a custom `new_edge_key()` method.
458 Examples
459 --------
460 The following all add the edge e=(1, 2) to graph G:
462 >>> G = nx.MultiDiGraph()
463 >>> e = (1, 2)
464 >>> key = G.add_edge(1, 2) # explicit two-node form
465 >>> G.add_edge(*e) # single edge as tuple of two nodes
466 1
467 >>> G.add_edges_from([(1, 2)]) # add edges from iterable container
468 [2]
470 Associate data to edges using keywords:
472 >>> key = G.add_edge(1, 2, weight=3)
473 >>> key = G.add_edge(1, 2, key=0, weight=4) # update data for key=0
474 >>> key = G.add_edge(1, 3, weight=7, capacity=15, length=342.7)
476 For non-string attribute keys, use subscript notation.
478 >>> ekey = G.add_edge(1, 2)
479 >>> G[1][2][0].update({0: 5})
480 >>> G.edges[1, 2, 0].update({0: 5})
481 """
482 u, v = u_for_edge, v_for_edge
483 # add nodes
484 if u not in self._succ:
485 if u is None:
486 raise ValueError("None cannot be a node")
487 self._succ[u] = self.adjlist_inner_dict_factory()
488 self._pred[u] = self.adjlist_inner_dict_factory()
489 self._node[u] = self.node_attr_dict_factory()
490 if v not in self._succ:
491 if v is None:
492 raise ValueError("None cannot be a node")
493 self._succ[v] = self.adjlist_inner_dict_factory()
494 self._pred[v] = self.adjlist_inner_dict_factory()
495 self._node[v] = self.node_attr_dict_factory()
496 if key is None:
497 key = self.new_edge_key(u, v)
498 if v in self._succ[u]:
499 keydict = self._adj[u][v]
500 datadict = keydict.get(key, self.edge_attr_dict_factory())
501 datadict.update(attr)
502 keydict[key] = datadict
503 else:
504 # selfloops work this way without special treatment
505 datadict = self.edge_attr_dict_factory()
506 datadict.update(attr)
507 keydict = self.edge_key_dict_factory()
508 keydict[key] = datadict
509 self._succ[u][v] = keydict
510 self._pred[v][u] = keydict
511 return key
513 def remove_edge(self, u, v, key=None):
514 """Remove an edge between u and v.
516 Parameters
517 ----------
518 u, v : nodes
519 Remove an edge between nodes u and v.
520 key : hashable identifier, optional (default=None)
521 Used to distinguish multiple edges between a pair of nodes.
522 If None, remove a single edge between u and v. If there are
523 multiple edges, removes the last edge added in terms of
524 insertion order.
526 Raises
527 ------
528 NetworkXError
529 If there is not an edge between u and v, or
530 if there is no edge with the specified key.
532 See Also
533 --------
534 remove_edges_from : remove a collection of edges
536 Examples
537 --------
538 >>> G = nx.MultiDiGraph()
539 >>> nx.add_path(G, [0, 1, 2, 3])
540 >>> G.remove_edge(0, 1)
541 >>> e = (1, 2)
542 >>> G.remove_edge(*e) # unpacks e from an edge tuple
544 For multiple edges
546 >>> G = nx.MultiDiGraph()
547 >>> G.add_edges_from([(1, 2), (1, 2), (1, 2)]) # key_list returned
548 [0, 1, 2]
550 When ``key=None`` (the default), edges are removed in the opposite
551 order that they were added:
553 >>> G.remove_edge(1, 2)
554 >>> G.edges(keys=True)
555 OutMultiEdgeView([(1, 2, 0), (1, 2, 1)])
557 For edges with keys
559 >>> G = nx.MultiDiGraph()
560 >>> G.add_edge(1, 2, key="first")
561 'first'
562 >>> G.add_edge(1, 2, key="second")
563 'second'
564 >>> G.remove_edge(1, 2, key="first")
565 >>> G.edges(keys=True)
566 OutMultiEdgeView([(1, 2, 'second')])
568 """
569 try:
570 d = self._adj[u][v]
571 except KeyError as err:
572 raise NetworkXError(f"The edge {u}-{v} is not in the graph.") from err
573 # remove the edge with specified data
574 if key is None:
575 d.popitem()
576 else:
577 try:
578 del d[key]
579 except KeyError as err:
580 msg = f"The edge {u}-{v} with key {key} is not in the graph."
581 raise NetworkXError(msg) from err
582 if len(d) == 0:
583 # remove the key entries if last edge
584 del self._succ[u][v]
585 del self._pred[v][u]
587 @cached_property
588 def edges(self):
589 """An OutMultiEdgeView of the Graph as G.edges or G.edges().
591 edges(self, nbunch=None, data=False, keys=False, default=None)
593 The OutMultiEdgeView provides set-like operations on the edge-tuples
594 as well as edge attribute lookup. When called, it also provides
595 an EdgeDataView object which allows control of access to edge
596 attributes (but does not provide set-like operations).
597 Hence, ``G.edges[u, v, k]['color']`` provides the value of the color
598 attribute for the edge from ``u`` to ``v`` with key ``k`` while
599 ``for (u, v, k, c) in G.edges(data='color', default='red', keys=True):``
600 iterates through all the edges yielding the color attribute with
601 default `'red'` if no color attribute exists.
603 Edges are returned as tuples with optional data and keys
604 in the order (node, neighbor, key, data). If ``keys=True`` is not
605 provided, the tuples will just be (node, neighbor, data), but
606 multiple tuples with the same node and neighbor will be
607 generated when multiple edges between two nodes exist.
609 Parameters
610 ----------
611 nbunch : single node, container, or all nodes (default= all nodes)
612 The view will only report edges from these nodes.
613 data : string or bool, optional (default=False)
614 The edge attribute returned in 3-tuple (u, v, ddict[data]).
615 If True, return edge attribute dict in 3-tuple (u, v, ddict).
616 If False, return 2-tuple (u, v).
617 keys : bool, optional (default=False)
618 If True, return edge keys with each edge, creating (u, v, k,
619 d) tuples when data is also requested (the default) and (u,
620 v, k) tuples when data is not requested.
621 default : value, optional (default=None)
622 Value used for edges that don't have the requested attribute.
623 Only relevant if data is not True or False.
625 Returns
626 -------
627 edges : OutMultiEdgeView
628 A view of edge attributes, usually it iterates over (u, v)
629 (u, v, k) or (u, v, k, d) tuples of edges, but can also be
630 used for attribute lookup as ``edges[u, v, k]['foo']``.
632 Notes
633 -----
634 Nodes in nbunch that are not in the graph will be (quietly) ignored.
635 For directed graphs this returns the out-edges.
637 Examples
638 --------
639 >>> G = nx.MultiDiGraph()
640 >>> nx.add_path(G, [0, 1, 2])
641 >>> key = G.add_edge(2, 3, weight=5)
642 >>> key2 = G.add_edge(1, 2) # second edge between these nodes
643 >>> [e for e in G.edges()]
644 [(0, 1), (1, 2), (1, 2), (2, 3)]
645 >>> list(G.edges(data=True)) # default data is {} (empty dict)
646 [(0, 1, {}), (1, 2, {}), (1, 2, {}), (2, 3, {'weight': 5})]
647 >>> list(G.edges(data="weight", default=1))
648 [(0, 1, 1), (1, 2, 1), (1, 2, 1), (2, 3, 5)]
649 >>> list(G.edges(keys=True)) # default keys are integers
650 [(0, 1, 0), (1, 2, 0), (1, 2, 1), (2, 3, 0)]
651 >>> list(G.edges(data=True, keys=True))
652 [(0, 1, 0, {}), (1, 2, 0, {}), (1, 2, 1, {}), (2, 3, 0, {'weight': 5})]
653 >>> list(G.edges(data="weight", default=1, keys=True))
654 [(0, 1, 0, 1), (1, 2, 0, 1), (1, 2, 1, 1), (2, 3, 0, 5)]
655 >>> list(G.edges([0, 2]))
656 [(0, 1), (2, 3)]
657 >>> list(G.edges(0))
658 [(0, 1)]
659 >>> list(G.edges(1))
660 [(1, 2), (1, 2)]
662 See Also
663 --------
664 in_edges, out_edges
665 """
666 return OutMultiEdgeView(self)
668 # alias out_edges to edges
669 @cached_property
670 def out_edges(self):
671 return OutMultiEdgeView(self)
673 out_edges.__doc__ = edges.__doc__
675 @cached_property
676 def in_edges(self):
677 """A view of the in edges of the graph as G.in_edges or G.in_edges().
679 in_edges(self, nbunch=None, data=False, keys=False, default=None)
681 Parameters
682 ----------
683 nbunch : single node, container, or all nodes (default= all nodes)
684 The view will only report edges incident to these nodes.
685 data : string or bool, optional (default=False)
686 The edge attribute returned in 3-tuple (u, v, ddict[data]).
687 If True, return edge attribute dict in 3-tuple (u, v, ddict).
688 If False, return 2-tuple (u, v).
689 keys : bool, optional (default=False)
690 If True, return edge keys with each edge, creating 3-tuples
691 (u, v, k) or with data, 4-tuples (u, v, k, d).
692 default : value, optional (default=None)
693 Value used for edges that don't have the requested attribute.
694 Only relevant if data is not True or False.
696 Returns
697 -------
698 in_edges : InMultiEdgeView or InMultiEdgeDataView
699 A view of edge attributes, usually it iterates over (u, v)
700 or (u, v, k) or (u, v, k, d) tuples of edges, but can also be
701 used for attribute lookup as `edges[u, v, k]['foo']`.
703 See Also
704 --------
705 edges
706 """
707 return InMultiEdgeView(self)
709 @cached_property
710 def degree(self):
711 """A DegreeView for the Graph as G.degree or G.degree().
713 The node degree is the number of edges adjacent to the node.
714 The weighted node degree is the sum of the edge weights for
715 edges incident to that node.
717 This object provides an iterator for (node, degree) as well as
718 lookup for the degree for a single node.
720 Parameters
721 ----------
722 nbunch : single node, container, or all nodes (default= all nodes)
723 The view will only report edges incident to these nodes.
725 weight : string or None, optional (default=None)
726 The name of an edge attribute that holds the numerical value used
727 as a weight. If None, then each edge has weight 1.
728 The degree is the sum of the edge weights adjacent to the node.
730 Returns
731 -------
732 DiMultiDegreeView or int
733 If multiple nodes are requested (the default), returns a `DiMultiDegreeView`
734 mapping nodes to their degree.
735 If a single node is requested, returns the degree of the node as an integer.
737 See Also
738 --------
739 out_degree, in_degree
741 Examples
742 --------
743 >>> G = nx.MultiDiGraph()
744 >>> nx.add_path(G, [0, 1, 2, 3])
745 >>> G.degree(0) # node 0 with degree 1
746 1
747 >>> list(G.degree([0, 1, 2]))
748 [(0, 1), (1, 2), (2, 2)]
749 >>> G.add_edge(0, 1) # parallel edge
750 1
751 >>> list(G.degree([0, 1, 2])) # parallel edges are counted
752 [(0, 2), (1, 3), (2, 2)]
754 """
755 return DiMultiDegreeView(self)
757 @cached_property
758 def in_degree(self):
759 """A DegreeView for (node, in_degree) or in_degree for single node.
761 The node in-degree is the number of edges pointing into the node.
762 The weighted node degree is the sum of the edge weights for
763 edges incident to that node.
765 This object provides an iterator for (node, degree) as well as
766 lookup for the degree for a single node.
768 Parameters
769 ----------
770 nbunch : single node, container, or all nodes (default= all nodes)
771 The view will only report edges incident to these nodes.
773 weight : string or None, optional (default=None)
774 The edge attribute that holds the numerical value used
775 as a weight. If None, then each edge has weight 1.
776 The degree is the sum of the edge weights adjacent to the node.
778 Returns
779 -------
780 If a single node is requested
781 deg : int
782 Degree of the node
784 OR if multiple nodes are requested
785 nd_iter : iterator
786 The iterator returns two-tuples of (node, in-degree).
788 See Also
789 --------
790 degree, out_degree
792 Examples
793 --------
794 >>> G = nx.MultiDiGraph()
795 >>> nx.add_path(G, [0, 1, 2, 3])
796 >>> G.in_degree(0) # node 0 with degree 0
797 0
798 >>> list(G.in_degree([0, 1, 2]))
799 [(0, 0), (1, 1), (2, 1)]
800 >>> G.add_edge(0, 1) # parallel edge
801 1
802 >>> list(G.in_degree([0, 1, 2])) # parallel edges counted
803 [(0, 0), (1, 2), (2, 1)]
805 """
806 return InMultiDegreeView(self)
808 @cached_property
809 def out_degree(self):
810 """Returns an iterator for (node, out-degree) or out-degree for single node.
812 out_degree(self, nbunch=None, weight=None)
814 The node out-degree is the number of edges pointing out of the node.
815 This function returns the out-degree for a single node or an iterator
816 for a bunch of nodes or if nothing is passed as argument.
818 Parameters
819 ----------
820 nbunch : single node, container, or all nodes (default= all nodes)
821 The view will only report edges incident to these nodes.
823 weight : string or None, optional (default=None)
824 The edge attribute that holds the numerical value used
825 as a weight. If None, then each edge has weight 1.
826 The degree is the sum of the edge weights.
828 Returns
829 -------
830 If a single node is requested
831 deg : int
832 Degree of the node
834 OR if multiple nodes are requested
835 nd_iter : iterator
836 The iterator returns two-tuples of (node, out-degree).
838 See Also
839 --------
840 degree, in_degree
842 Examples
843 --------
844 >>> G = nx.MultiDiGraph()
845 >>> nx.add_path(G, [0, 1, 2, 3])
846 >>> G.out_degree(0) # node 0 with degree 1
847 1
848 >>> list(G.out_degree([0, 1, 2]))
849 [(0, 1), (1, 1), (2, 1)]
850 >>> G.add_edge(0, 1) # parallel edge
851 1
852 >>> list(G.out_degree([0, 1, 2])) # counts parallel edges
853 [(0, 2), (1, 1), (2, 1)]
855 """
856 return OutMultiDegreeView(self)
858 def is_multigraph(self):
859 """Returns True if graph is a multigraph, False otherwise."""
860 return True
862 def is_directed(self):
863 """Returns True if graph is directed, False otherwise."""
864 return True
866 def to_undirected(self, reciprocal=False, as_view=False):
867 """Returns an undirected representation of the digraph.
869 Parameters
870 ----------
871 reciprocal : bool (optional)
872 If True only keep edges that appear in both directions
873 in the original digraph.
874 as_view : bool (optional, default=False)
875 If True return an undirected view of the original directed graph.
877 Returns
878 -------
879 G : MultiGraph
880 An undirected graph with the same name and nodes and
881 with edge (u, v, data) if either (u, v, data) or (v, u, data)
882 is in the digraph. If both edges exist in digraph and
883 their edge data is different, only one edge is created
884 with an arbitrary choice of which edge data to use.
885 You must check and correct for this manually if desired.
887 See Also
888 --------
889 MultiGraph, copy, add_edge, add_edges_from
891 Notes
892 -----
893 This returns a "deepcopy" of the edge, node, and
894 graph attributes which attempts to completely copy
895 all of the data and references.
897 This is in contrast to the similar D=MultiDiGraph(G) which
898 returns a shallow copy of the data.
900 See the Python copy module for more information on shallow
901 and deep copies, https://docs.python.org/3/library/copy.html.
903 Warning: If you have subclassed MultiDiGraph to use dict-like
904 objects in the data structure, those changes do not transfer
905 to the MultiGraph created by this method.
907 Examples
908 --------
909 >>> G = nx.path_graph(2) # or MultiGraph, etc
910 >>> H = G.to_directed()
911 >>> list(H.edges)
912 [(0, 1), (1, 0)]
913 >>> G2 = H.to_undirected()
914 >>> list(G2.edges)
915 [(0, 1)]
916 """
917 graph_class = self.to_undirected_class()
918 if as_view is True:
919 return nx.graphviews.generic_graph_view(self, graph_class)
920 # deepcopy when not a view
921 G = graph_class()
922 G.graph.update(deepcopy(self.graph))
923 G.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
924 if reciprocal is True:
925 G.add_edges_from(
926 (u, v, key, deepcopy(data))
927 for u, nbrs in self._adj.items()
928 for v, keydict in nbrs.items()
929 for key, data in keydict.items()
930 if v in self._pred[u] and key in self._pred[u][v]
931 )
932 else:
933 G.add_edges_from(
934 (u, v, key, deepcopy(data))
935 for u, nbrs in self._adj.items()
936 for v, keydict in nbrs.items()
937 for key, data in keydict.items()
938 )
939 return G
941 def reverse(self, copy=True):
942 """Returns the reverse of the graph.
944 The reverse is a graph with the same nodes and edges
945 but with the directions of the edges reversed.
947 Parameters
948 ----------
949 copy : bool optional (default=True)
950 If True, return a new DiGraph holding the reversed edges.
951 If False, the reverse graph is created using a view of
952 the original graph.
953 """
954 if copy:
955 H = self.__class__()
956 H.graph.update(deepcopy(self.graph))
957 H.add_nodes_from((n, deepcopy(d)) for n, d in self._node.items())
958 H.add_edges_from(
959 (v, u, k, deepcopy(d))
960 for u, v, k, d in self.edges(keys=True, data=True)
961 )
962 return H
963 return nx.reverse_view(self)