Introduction

The main entry point to NetworkDisk are the Graph and DiGraph classes.

Graph

class networkdisk.sql.Graph(incoming_graph_data=None, db=None, sql_logger=<networkdisk.utils.constants.NotProvidedArg object>, autocommit=False, schema=None, create=None, insert_schema=None, lazy=None, static=False, node_cache_level=None, edge_cache_level=None, cache_level=0, masterid=None, name=None, **attr)

SQL abstract Graph class

The class inherit from nx.Graph class and override some of the methods for performance purpose. Two constructors are possible to obtain a SQL Graph: __load_graph_init__() and __create_graph_init__() depending on whether the graph has to be created on disk or simply loaded from the database.

Depending on the chosen parameters for initializing the graph, the first or second methods will be called.

Parameters:
incoming_graph_datagraph data or None, default=None

Possibly, graph data to import, as for NetworkX graphs.

dbMasterGraphs or Helper or DB connect information or None, default=None

The DB connector specification. Connect information format depends on backend.

sql_loggercallable or bool or None or notProvidedArg, default=notProvidedArg

Whether and how to log SQL queries. Value None means “do not log anything”, value True means “use a fresh instance of the default logger and set it active”, value False means “use a fresh instance of the default logger and set it inactive”, value notProvidedArg means “use the shared instance of the default logger”, and callable values allow to set the logger to a user-defined logger.

autocommitbool, default=True

Whether to connect to the db with autocommit flag (ignored if db is an already connected object).

schemaGraphSchema or bool or mapping or None, default=None

The GraphSchema to use for the graph. True indicates that the default schema should be generated through according to the default_schema property, while False enforces to load the schema from DB. If a mapping, the schema is generated (as with True) using the mapping items as keyworded parameters for the generation. In particular, the key method indicates which function should be used to generate the schema (default_schema is used if missing). The value associated with the method key should be a key of the sub-dialect dialect.schemata. Finally, if the parameter has value None, a default behavior is chosen according to the other parameters and the contents of the master table of the connected DB, if present.

insert_schemabool or None, default=None

Whether to insert the schema in the master table. If None the value is determined according to the given parameters in a very smart way.

lazybool or None, default=None

Whether the tupledicts living in the graph schema should be lazy or not for increasing performance. Graph with lazy attributes set to True will not raise KeyError in some situation where normal networkx.Graph would. See TupleDict documentation for details.

staticbool, default=False

Whether the graph is assumed to be static. Declaring a graph as static has two effects: (1) the graph schema is automatically turn into the corresponding read-only schema; (2) node/edge caching (see parameters node_cache_level and edge_cache_level below) is allowed. It is up to the programmer to ensure that the graph backend is not altered.

node_cache_level: None or integer, default=None

A value indicating how deep should node caching be performed. Value 0 means that no caching is performed. Caching is allowed only if the graph has been declared as static (see static parameter above) — an error is raised otherwise. If None, then the value is set to the value of the cache_level parameter (see below).

edge_cache_level: None or integer, default=None

A value indicating how deep should edge caching be performed. Value 0 means that no caching is performed. Caching is allowed only if the graph has been declared as static (see static parameter above) — an error is raised otherwise. If None, then the value is set to the value of the cache_level parameter (see below).

cache_level: integer, default=0

A value for both node_cache_level and edge_cache_level, which both take precedence over cache_level in case they are given.

masteridstr or None, default=None

If given with one of schema, or insert_schema, then set the Graph masterid to masterid. Otherwise, load the graph schema of the graph of masterid masterid from master table. In the latter case, an error is raised if no such graph is found.

namestr or None, default=None

Without schema and insert_schema parameters, attempt to load a name-named graph from the master table. If failing, or with schema or insert_schema parameters, set the graph name.

attrmapping

Additional data to add to the graph (as for NetworkX graphs).

__create_graph_init__(*args, schema=True, lazy=None, create=None, insert_schema=None, masterid=None, name=None, static=False, node_cache_level=0, edge_cache_level=0, **kwargs)

An SQL Graph constructor.

Parameters:
schema: GraphSchema or True or mapping

The GraphSchema to use or how to generate it. If True, the default graph schema is generated according to self.default_schema. If a mapping, then the generation is controlled by the mapping items, namely, the value of the special key method indicate which schema generating function to use (the self.default_schema one if missing) and the other parameters are passed as keyworded parameters to the specified function. Hence, an empty mapping is equivalent to True. The value associated with the method special key should be a key of the sub-dialect self.dialect.schemata.

lazy: bool or None

a Boolean setting tupleDicts lazyness, or None for the default lazyness.

create: bool or None

a Boolean or None (default) indicating whether to create the graph structure (TABLE, VIEW, INDEX, TRIGGER) within DB or not. If False each structure occurring within the (possibly generated) schema, is assumed to exist. If None then the flag takes the value True if the schema has been generated (namely, if the schema argument was not a GraphSchema instance) and False otherwise.

insert_schema: bool or None

a Boolean or None (default) indicating whether to save the schema in the master table (for future importation) or not. If None, then the parameter takes the value True if the schema is created and False otherwise (c.f. create parameter documentation above).

name:

one of the graph data, namely its name, that is stored in the master table when the graph is inserted.

argstuple
kwargsdict

further ignored parameters to be passed in the initialization pipe.

The master table is **created when it does not exist and**
`insert_schema` is `True` or is changed from `None` to `True`
as above explained.
__load_graph_init__(*args, create=False, lazy=None, masterid=None, name=None, schema=None, static=False, node_cache_level=0, edge_cache_level=0, **kwargs)

Load a graph from database.

  • incoming_graph_data:

  • db: either a DB helper, or a DB file path (str). The default value None will result in an error.

  • sql_logger, autocommit: c.f. set_helper method.

  • create: a Boolean (default is False) indicating whether the found graph schema structure should be created. In a common situation, a graph schema which has been saved in the master table, is an existing schema, namely, its structure (TABLE, VIEW…) exists within the database whence the default parameter value False should be used. However, in some cases, a graph schema whose structure does not exist in the database could have been saved in the master table. In which case, one might want to specify create=True so that the structure is created.

  • lazy: a Boolean or None indicating the tupledict lazyness. If None the default value is taken.

  • name: the name of the graph to find, or None.

  • masterid: the id of the graph to find, or None.

  • schema: the graph schema to load. If provided together with masterid, then it used without reading the master table.

  • attr:

add_edge(u_of_edge, v_of_edge, refresh_nodes=True, **attr)

Overload networkx.Graph.add_edge. + u_of_edge: source of edge + v_of_edge: target of edge + attr: keyworded list of additional edge attributes

Should update edge (u,v) with attributes from attr, after, possibly, inserting the edge (u,v).

Actually reduce to add_edges_from for code simplicity.

add_edge_data_from(ebunch_to_add, **attr)
Parameters:
ebunch_to_add:

iterator of tuple of length 2 (u,v) or 3 (u, v, d) with (u,v) an existing edge of the graph, and d a dictionary to update the edge data.

**attr:

a keyworded list of optional arguments, to be added to all edge data from ebunch_to_add.

add_edges_from(ebunch_to_add, refresh_nodes=True, **attr)

Add edges in bulk to self

Respect the NetworkX signature.

Notes

Using the networkx implementation of the method is correct, but for optimization purpose, it is better to overload it. For better performance, one should drop and add triggers. We perform two different strategy depending on whether the argument ebunch_to_add is an ‘Iterable’ or an ‘Iterator’. The case is determined determined by testing the pointer equality of iter(ebunch_to_add) to ebunch_to_add. If the two object are the same, then ebunch_to_add is assumed to be an ‘Iterator’ over which only one pass is allowed. In this case, edges and their associated data will be inserted simultaneously, while nodes are inserted after using the refresh_nodes method. It requires to perform many queries. In this other case, ebunch_to_add is assumed to be an ‘Iterable’ over which several passes are possible. Hence, a more efficient implementation is used, in which first edges are inserted, and then their data. Performance are vastly improve.

add_edges_without_data_from(ebunch_to_add, refresh_nodes=True)

Add edges without data

Notes

Add edges from iterable ebunch_to_add of tuples. Each tuple should have length 2 or 3. In the latter case, the third component, which typically stores data of the edge, is dropped.

add_node(node_for_adding, **attr)

For code concision and optimization we reduce to add_nodes_from. nx version work but perform unnecessary operation.

add_node_data(u, **attr)

Add data from attr (update) to node u which is supposed to exist, but never checked. If u is not a vertex of self, then nothing is inserted silently.

add_nodes_from(nodes_for_adding, **attr)

Add nodes to the graph

Respect the NetworkX variant but optimize.

Notes

Using the networkx implementation of the method is correct, but for optimization purpose, it is better to overload it. Two algorithms will be performed depending if nodes_for_adding is an iterator or an iterable which is not an iterator. In the first case, we assume only one pass over the data is possible and will perform many more queries to update the database to insert data values. In the later we will first do one pass to insert nodes and then another to insert their data values. The algorithm is choose by testing if iter(nodes_for_adding) is nodes_for_adding.

property adj

Graph adjacency object holding the neighbors of each node.

This object is a read-only dict-like structure with node keys and neighbor-dict values. The neighbor-dict is keyed by neighbor to the edge-data-dict. So G.adj[3][2][‘color’] = ‘blue’ sets the color of the edge (3, 2) to “blue”.

Iterating over G.adj behaves like a dict. Useful idioms include for nbr, datadict in G.adj[n].items():.

The neighbor information is also provided by subscripting the graph. So for nbr, foovalue in G[node].data(‘foo’, default=1): works.

For directed graphs, G.adj holds outgoing (successor) info.

clear_edges()

Remove all edges from the graph without altering nodes.

Examples

>>> G = nx.path_graph(4)  # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> G.clear_edges()
>>> list(G.nodes)
[0, 1, 2, 3]
>>> list(G.edges)
[]
copy(as_view=False)

Returns a copy of the graph.

The copy method by default returns an independent shallow copy of the graph and attributes. That is, if an attribute is a container, that container is shared by the original an the copy. Use Python’s copy.deepcopy for new containers.

If as_view is True then a view is returned instead of a copy.

Parameters:
as_viewbool, optional (default=False)

If True, the returned graph-view provides a read-only view of the original graph without actually copying any data.

Returns:
GGraph

A copy of the graph.

See also

to_directed

return a directed copy of the graph.

Notes

All copies reproduce the graph structure, but data attributes may be handled in different ways. There are four types of copies of a graph that people might want.

Deepcopy – A “deepcopy” copies the graph structure as well as all data attributes and any objects they might contain. The entire graph object is new so that changes in the copy do not affect the original object. (see Python’s copy.deepcopy)

Data Reference (Shallow) – For a shallow copy the graph structure is copied but the edge, node and graph attribute dicts are references to those in the original graph. This saves time and memory but could cause confusion if you change an attribute in one graph and it changes the attribute in the other. NetworkX does not provide this level of shallow copy.

Independent Shallow – This copy creates new independent attribute dicts and then does a shallow copy of the attributes. That is, any attributes that are containers are shared between the new graph and the original. This is exactly what dict.copy() provides. You can obtain this style copy using:

>>> G = nx.path_graph(5)
>>> H = G.copy()
>>> H = G.copy(as_view=False)
>>> H = nx.Graph(G)
>>> H = G.__class__(G)

Fresh Data – For fresh data, the graph structure is copied while new empty data attribute dicts are created. The resulting graph is independent of the original and it has no edge, node or graph attributes. Fresh copies are not enabled. Instead use:

>>> H = G.__class__()
>>> H.add_nodes_from(G)
>>> H.add_edges_from(G.edges)

View – Inspired by dict-views, graph-views act like read-only versions of the original graph, providing a copy of the original structure without requiring any memory for copying the information.

See the Python copy module for more information on shallow and deep copies, https://docs.python.org/3/library/copy.html.

Examples

>>> G = nx.path_graph(4)  # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> H = G.copy()
classmethod create_graph(*args, schema=True, lazy=None, create=None, insert_schema=None, masterid=None, name=None, static=False, node_cache_level=0, edge_cache_level=0, **kwargs)

An SQL Graph constructor.

Parameters:
schema: GraphSchema or True or mapping

The GraphSchema to use or how to generate it. If True, the default graph schema is generated according to self.default_schema. If a mapping, then the generation is controlled by the mapping items, namely, the value of the special key method indicate which schema generating function to use (the self.default_schema one if missing) and the other parameters are passed as keyworded parameters to the specified function. Hence, an empty mapping is equivalent to True. The value associated with the method special key should be a key of the sub-dialect self.dialect.schemata.

lazy: bool or None

a Boolean setting tupleDicts lazyness, or None for the default lazyness.

create: bool or None

a Boolean or None (default) indicating whether to create the graph structure (TABLE, VIEW, INDEX, TRIGGER) within DB or not. If False each structure occurring within the (possibly generated) schema, is assumed to exist. If None then the flag takes the value True if the schema has been generated (namely, if the schema argument was not a GraphSchema instance) and False otherwise.

insert_schema: bool or None

a Boolean or None (default) indicating whether to save the schema in the master table (for future importation) or not. If None, then the parameter takes the value True if the schema is created and False otherwise (c.f. create parameter documentation above).

name:

one of the graph data, namely its name, that is stored in the master table when the graph is inserted.

argstuple
kwargsdict

further ignored parameters to be passed in the initialization pipe.

The master table is **created when it does not exist and**
`insert_schema` is `True` or is changed from `None` to `True`
as above explained.
property degree

A DegreeView for the Graph as G.degree or G.degree().

The node degree is the number of edges adjacent to the node. The weighted node degree is the sum of the edge weights for edges incident to that node.

This object provides an iterator for (node, degree) as well as lookup for the degree for a single node.

Parameters:
nbunchsingle node, container, or all nodes (default= all nodes)

The view will only report edges incident to these nodes.

weightstring or None, optional (default=None)

The name of an edge attribute that holds the numerical value used as a weight. If None, then each edge has weight 1. The degree is the sum of the edge weights adjacent to the node.

Returns:
If a single node is requested
degint

Degree of the node

OR if multiple nodes are requested
nd_viewA DegreeView object capable of iterating (node, degree) pairs

Examples

>>> G = nx.path_graph(4)  # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> G.degree[0]  # node 0 has degree 1
1
>>> list(G.degree([0, 1, 2]))
[(0, 1), (1, 2), (2, 2)]
drop_index()

Remove indexation. Can be useful in case of bulk insert where reindexing post insertion is faster than indexing during insertion.

ebunch_iter(ebunch=None, *mandatory_keys, data=False, default=None, condition=None, **if_key_then_value)

Iter over edges according to filtering conditions

Parameters:
ebunch: iterable or None or Graph edge

either a Graph edge, or an iterable of elements. If in the former case, an iterator-query with ebunch as unique element is returned. Otherwise (in the latter case), an iterable query with all nodes of self that belong to the iterable ebunch are returned. Alternatively, the parameter can be set to None (default), in which case, all the graph edges are taken.

mandatory_keys: tuple[mapping or key]

Intuitively, the list of keys that selected edges should have. Yet, some of the items may be mappings. These mapping items are initially extracted from the list, and use to populate the if_key_then_value mapping, not overwriting already specified items. In this way, it is possible to specify if_key_then_value keys that are not keywordable (e.g., True or ‘a key with spaces’), as well as keys that are reserved keywords of the function (e.g., ‘data’ or ‘condition’).

data: bool or str

If False (the default), then edges are returned without data. If True, then they are returned with data. If a string, then triples (s, t, d) are returned where s, t is a selected edge and d is either the value associated with key data, if any, or default, otherwise.

default: any

The default data to return if data is a key (str), for edges not having this so-specified key.

if_key_then_value: mapping

a k/v mapping. An edge is taken if and only if one of the two following condition is met: either the edge does not have the given key k, or the value associated with the given key k matches v. Notice that the former condition is avoided by giving the same key within the mandatory_keys tuple. Concerning the latter condition, the matching is defined as follows. If v is callable, then it should take one column parameter and return a condition. In this case the condition obtained by its call on the node value column is taken. Otherwise, v is considered as a value, and the equality condition with the value v is taken instead. Therefore, passing key=3 is equivalent to passing key=lambda c: c.eq(3).

condition: condition or None

a condition to add in every filter.

Returns:
An iterable query representing the selected edges. The iterable
elements may be edges (s, t) (if data is False), or triples
(s, t, d) with d the value associated with key data (if a string)
in the data of edge s, t, or quadruples (s, t, k, v) with k/v
be pairs key/value of the data of edge s, t (if data is True).
edge_subgraph(edges, restrict_node_domain=True, temporary_table=False)

Returns a view of the subgraph induced by the specified edges.

The induced subgraph of the graph contains the edges in edges. By default, only nodes that are incident to some of these edges are in the induced subgraph.

Parameters:
edges: iterable

The edges to select.

restrict_node_domain: bool, default=True

Whether to filter nodes so that only nodes incident to some selected edges are kept. The default behavior is the networkx.edge_subgraph behavior.

temporary_table: bool, default=False

If True, then the selected nodes will be stored in a temporary table on disk. It will have much better performance but will not provide a view but a semi-static subgraph instead (edges are maintained but not nodes). Ignored if filter_node is False.

Returns:
A networkdisk (Di)Graph view based on the same helper than self
(DB-connection) and exposing the desired subgraph.

Examples

>>> G = nd.sqlite.Graph()
>>> G.add_edges_from([(0, 1), (1, 2), (2, 3)])
>>> K = G.edge_subgraph([(1, 2), (2, 3)])
>>> sorted(K.edges)
[(1, 2), (2, 3)]
>>> sorted(K.nodes)
[1, 2, 3]

We can choose to keep all nodes: >>> H = G.edge_subgraph([(0, 1), (1, 2), (2, 3)], restrict_node_domain=False) >>> sorted(H.edges) [(1, 2), (2, 3)] >>> sorted(H.nodes) [0, 1, 2, 3]

To increase performance, we can use temporary table for storing the node domain on disk: >>> J = G.edge_subgraph([(0, 1), (1, 2), (2, 3)], temporary_table=True) >>> sorted(J.edges) [(1, 2), (2, 3)] >>> sorted(J.nodes) [1, 2, 3]

But J is not a view anylonger, K is a view: >>> G.remove_edge(2, 3) >>> sorted(J.edges) [(1, 2)] >>> sorted(J.nodes) [1, 2, 3] >>> sorted(K.edges) [(1, 2)] >>> sorted(K.nodes) [1, 2]

property edges

An EdgeView of the Graph as G.edges or G.edges().

edges(self, nbunch=None, data=False, default=None)

The EdgeView provides set-like operations on the edge-tuples as well as edge attribute lookup. When called, it also provides an EdgeDataView object which allows control of access to edge attributes (but does not provide set-like operations). Hence, G.edges[u, v][‘color’] provides the value of the color attribute for edge (u, v) while for (u, v, c) in G.edges.data(‘color’, default=’red’): iterates through all the edges yielding the color attribute with default ‘red’ if no color attribute exists.

Parameters:
nbunchsingle node, container, or all nodes (default= all nodes)

The view will only report edges from these nodes.

datastring or bool, optional (default=False)

The edge attribute returned in 3-tuple (u, v, ddict[data]). If True, return edge attribute dict in 3-tuple (u, v, ddict). If False, return 2-tuple (u, v).

defaultvalue, optional (default=None)

Value used for edges that don’t have the requested attribute. Only relevant if data is not True or False.

Returns:
edgesEdgeView

A view of edge attributes, usually it iterates over (u, v) or (u, v, d) tuples of edges, but can also be used for attribute lookup as edges[u, v][‘foo’].

Notes

Nodes in nbunch that are not in the graph will be (quietly) ignored. For directed graphs this returns the out-edges.

Examples

>>> G = nx.path_graph(3)  # or MultiGraph, etc
>>> G.add_edge(2, 3, weight=5)
>>> [e for e in G.edges]
[(0, 1), (1, 2), (2, 3)]
>>> G.edges.data()  # default data is {} (empty dict)
EdgeDataView([(0, 1, {}), (1, 2, {}), (2, 3, {'weight': 5})])
>>> G.edges.data("weight", default=1)
EdgeDataView([(0, 1, 1), (1, 2, 1), (2, 3, 5)])
>>> G.edges([0, 3])  # only edges from these nodes
EdgeDataView([(0, 1), (3, 2)])
>>> G.edges(0)  # only edges from node 0
EdgeDataView([(0, 1)])
edges_satisfying_condition(key, value=<networkdisk.utils.constants.NotProvidedArg object>, strict=True)

Simple builder of condition on edge data.

Parameters:
key: str or callable

The edge data key to filter. If callable, then it is expected to return a condition when called with a column parameter. In that case the ‘key-condition’ is the condition returned when the column parameter is the edge data key column. Otherwise, it is the key name to filter against equality. E.g., key=3 is equivalent to key=lambda c: c.eq(3).

value: any

If provided, a condition is built in addition to the one resulting from the treatment of the key parameter, as follows. If the given value is callable, then it is expected to take one column argument, namely the edge data value column, and return a condition. Otherwise it is considered as a (any-type but callable) value indicating the value to be matched by the edge data value column. E.g., value=3 is equivalent to value=lambda c: c.eq(3).

strict: Boolean = True

This flag is aimed for internal use only. It allows to construct a different condition when the intention is to filter only edges that do admit the corresponding key key, thus keeping all edges not admitting it.

Returns:
Return an object representing the condition adapted to the graph schema.
find_all_edges(*mandatory_keys, condition=None, **if_key_then_value)

A wrapper of ebunch_iter, to filter edges by condition but not by bunch.

Examples

>>> G = nd.sqlite.DiGraph()
>>> G.add_edge(0, 1, foo="bar", color="red", shape="circle")
>>> G.add_edge(1, 2, foo="bar", color="yellow", shape="rectangle")
>>> G.add_edge(2, 3, foo="not bar", color="brown", shape="circle")
>>> G.add_edge(3, 4, foo="bar", shape="diamond")
>>> G.add_edge(4, 0, color="purple")
>>> sorted(G.find_all_edges("foo"))
[(0, 1), (1, 2), (2, 3), (3, 4)]
>>> sorted(G.find_all_edges(foo="bar")) #observe that (4, 0) is listed
[(0, 1), (1, 2), (3, 4), (4, 0)]
>>> sorted(G.find_all_edges("foo", foo="bar")) #combining both thus avoiding (0, 4)
[(0, 1), (1, 2), (3, 4)]
>>> sorted(G.find_all_edges("foo", "color", foo="bar"))
[(0, 1), (1, 2)]
>>> sorted(G.find_all_edges("color", foo="bar"))
[(0, 1), (1, 2), (4, 0)]
>>> sorted(G.find_all_edges("color", color=lambda c: c.gt("purple")))
[(0, 1), (1, 2)]
>>> G = nd.sqlite.Graph()
>>> G.add_edge(0, 1, foo="bar", color="red", shape="circle")
>>> G.add_edge(1, 2, foo="bar", color="yellow", shape="rectangle")
>>> G.add_edge(2, 3, foo="not bar", color="brown", shape="circle")
>>> G.add_edge(3, 4, foo="bar", shape="diamond")
>>> G.add_edge(4, 0, color="purple")
>>> sorted(G.find_all_edges("foo"))
[(0, 1), (1, 2), (2, 3), (3, 4)]
>>> sorted(map(tuple, map(sorted, G.find_all_edges(foo="bar")))) #observe that (0, 4) is listed
[(0, 1), (0, 4), (1, 2), (3, 4)]
>>> sorted(map(tuple, map(sorted, G.find_all_edges("foo", foo="bar")))) #combining both thus avoiding (0, 4)
[(0, 1), (1, 2), (3, 4)]
>>> sorted(map(tuple, map(sorted, G.find_all_edges("foo", "color", foo="bar"))))
[(0, 1), (1, 2)]
>>> sorted(map(tuple, map(sorted, G.find_all_edges("color", foo="bar"))))
[(0, 1), (0, 4), (1, 2)]
>>> sorted(map(tuple, map(sorted, G.find_all_edges("color", color=lambda c: c.gt("purple")))))
[(0, 1), (1, 2)]
find_all_nodes(*mandatory_keys, condition=None, **if_key_then_value)

A wrapper of nbunch_iter, to filter node by condition but not by bunch.

Examples

>>> G = nd.sqlite.Graph()
>>> G.add_node(0, foo="bar", color="red", shape="circle")
>>> G.add_node(1, foo="bar", color="yellow", shape="rectangle")
>>> G.add_node(2, foo="not bar", color="brown", shape="circle")
>>> G.add_node(3, foo="bar", shape="diamond")
>>> G.add_node(4, color="purple")
>>> sorted(G.find_all_nodes("foo"))
[0, 1, 2, 3]
>>> sorted(G.find_all_nodes(foo="bar")) #observe that 4 is listed
[0, 1, 3, 4]
>>> sorted(G.find_all_nodes("foo", foo="bar")) #combining both
[0, 1, 3]
>>> sorted(G.find_all_nodes("foo", "color", foo="bar"))
[0, 1]
>>> sorted(G.find_all_nodes("color", foo="bar"))
[0, 1, 4]
>>> sorted(G.find_all_nodes("color", color=lambda c: c.gt("purple")))
[0, 1]
find_one_node(*args, condition=None, **kwargs)

Find one node satisfying some condition. This is a wrapper of find_all_nodes method.

get_edge_data(u, v, default=None, lazy=False)

Returns the attribute dictionary associated with edge (u, v).

This is identical to G[u][v] except the default is returned instead of an exception if the edge doesn’t exist.

Parameters:
u, vnodes
default: any Python object (default=None)

Value to return if the edge (u, v) is not found.

Returns:
edge_dictdictionary

The edge attribute dictionary.

Examples

>>> G = nx.path_graph(4)  # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> G[0][1]
{}

Warning: Assigning to G[u][v] is not permitted. But it is safe to assign attributes G[u][v][‘foo’]

>>> G[0][1]["weight"] = 7
>>> G[0][1]["weight"]
7
>>> G[1][0]["weight"]
7
>>> G = nx.path_graph(4)  # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> G.get_edge_data(0, 1)  # default edge data is {}
{}
>>> e = (0, 1)
>>> G.get_edge_data(*e)  # tuple form
{}
>>> G.get_edge_data("a", "b", default=0)  # edge not in graph, return 0
0
classmethod load_graph(*args, create=False, lazy=None, masterid=None, name=None, schema=None, static=False, node_cache_level=0, edge_cache_level=0, **kwargs)

Load a graph from database.

  • incoming_graph_data:

  • db: either a DB helper, or a DB file path (str). The default value None will result in an error.

  • sql_logger, autocommit: c.f. set_helper method.

  • create: a Boolean (default is False) indicating whether the found graph schema structure should be created. In a common situation, a graph schema which has been saved in the master table, is an existing schema, namely, its structure (TABLE, VIEW…) exists within the database whence the default parameter value False should be used. However, in some cases, a graph schema whose structure does not exist in the database could have been saved in the master table. In which case, one might want to specify create=True so that the structure is created.

  • lazy: a Boolean or None indicating the tupledict lazyness. If None the default value is taken.

  • name: the name of the graph to find, or None.

  • masterid: the id of the graph to find, or None.

  • schema: the graph schema to load. If provided together with masterid, then it used without reading the master table.

  • attr:

property name

String identifier of the graph.

This graph attribute appears in the attribute dict G.graph keyed by the string “name”. as well as an attribute (technically a property) G.name. This is entirely user controlled.

nbunch_iter(nbunch=None, *mandatory_keys, data=False, default=None, condition=None, **if_key_then_value)

Iter over nodes according to filtering conditions

Parameters:
nbunch: iterable or None or Graph node

either a Graph node, or an iterable of elements. If in the former case, an iterator-query with nbunch as unique element is returned. Otherwise (in the latter case), an iterable query with all nodes of self that belong to the iterable nbunch are returned. Alternatively, the parameter can be set to None (default), in which case, all the graph nodes are taken.

mandatory_keys: tuple[mapping or key]

Intuitively, the list of keys that selected nodes should have. Yet, some of the items may be mappings. These mapping items are initially extracted from the list, and use to populate the if_key_then_value mapping, not overwriting already specified items. In this way, it is possible to specify if_key_then_value keys that are not keywordable (e.g., True or ‘a key with spaces’), as well as keys that are reserved keywords of the function (e.g., ‘data’ or ‘condition’).

data: bool or str

If False (the default), then nodes are returned without data. If True, then they are returned with data. If a string, then pairs (n, d) are returned where n is a selected node and d is either the value associated with key data, if any, or default, otherwise.

default: any

The default data to return if data is a key (str), for nodes not having this key.

if_key_then_value: mapping

a k/v mapping. A node is taken if and only if one of the two following condition is met: either the node does not have the given key k, or the value associated with the given key k matches v. Notice that the former condition is avoided by giving the same key within the mandatory_keys tuple. Concerning the latter condition, the matching is defined as follows. If v is callable, then it should take one column parameter and return a condition. In this case the condition obtained by its call on the node value column is taken. Otherwise, v is considered as a value, and the equality condition with the value v is taken instead. Therefore, passing key=3 is equivalent to passing key=lambda c: c.eq(3).

condition: condition or None

a condition to add in every filter.

Returns:
An iterable query representing the selected nodes. The iterable
elements may be nodes v (if data is False), or pairs (n, d)
with d the value associated with key data (if a string) in the data
of node n, or triples (n, k, v) with k/v be pairs key/value of
the data of node n (if data is True).
property nodes

A NodeView of the Graph as G.nodes or G.nodes().

Can be used as G.nodes for data lookup and for set-like operations. Can also be used as G.nodes(data=’color’, default=None) to return a NodeDataView which reports specific node data but no set operations. It presents a dict-like interface as well with G.nodes.items() iterating over (node, nodedata) 2-tuples and G.nodes[3][‘foo’] providing the value of the foo attribute for node 3. In addition, a view G.nodes.data(‘foo’) provides a dict-like interface to the foo attribute of each node. G.nodes.data(‘foo’, default=1) provides a default for nodes that do not have attribute foo.

Parameters:
datastring or bool, optional (default=False)

The node attribute returned in 2-tuple (n, ddict[data]). If True, return entire node attribute dict as (n, ddict). If False, return just the nodes n.

defaultvalue, optional (default=None)

Value used for nodes that don’t have the requested attribute. Only relevant if data is not True or False.

Returns:
NodeView

Allows set-like operations over the nodes as well as node attribute dict lookup and calling to get a NodeDataView. A NodeDataView iterates over (n, data) and has no set operations. A NodeView iterates over n and includes set operations.

When called, if data is False, an iterator over nodes. Otherwise an iterator of 2-tuples (node, attribute value) where the attribute is specified in data. If data is True then the attribute becomes the entire data dictionary.

Notes

If your node data is not needed, it is simpler and equivalent to use the expression for n in G, or list(G).

Examples

There are two simple ways of getting a list of all nodes in the graph:

>>> G = nx.path_graph(3)
>>> list(G.nodes)
[0, 1, 2]
>>> list(G)
[0, 1, 2]

To get the node data along with the nodes:

>>> G.add_node(1, time="5pm")
>>> G.nodes[0]["foo"] = "bar"
>>> list(G.nodes(data=True))
[(0, {'foo': 'bar'}), (1, {'time': '5pm'}), (2, {})]
>>> list(G.nodes.data())
[(0, {'foo': 'bar'}), (1, {'time': '5pm'}), (2, {})]
>>> list(G.nodes(data="foo"))
[(0, 'bar'), (1, None), (2, None)]
>>> list(G.nodes.data("foo"))
[(0, 'bar'), (1, None), (2, None)]
>>> list(G.nodes(data="time"))
[(0, None), (1, '5pm'), (2, None)]
>>> list(G.nodes.data("time"))
[(0, None), (1, '5pm'), (2, None)]
>>> list(G.nodes(data="time", default="Not Available"))
[(0, 'Not Available'), (1, '5pm'), (2, 'Not Available')]
>>> list(G.nodes.data("time", default="Not Available"))
[(0, 'Not Available'), (1, '5pm'), (2, 'Not Available')]

If some of your nodes have an attribute and the rest are assumed to have a default attribute value you can create a dictionary from node/attribute pairs using the default keyword argument to guarantee the value is never None:

>>> G = nx.Graph()
>>> G.add_node(0)
>>> G.add_node(1, weight=2)
>>> G.add_node(2, weight=3)
>>> dict(G.nodes(data="weight", default=1))
{0: 1, 1: 2, 2: 3}
nodes_satisfying_condition(key, value=<networkdisk.utils.constants.NotProvidedArg object>, strict=True)

Simple builder of condition on node data.

Parameters:
key: str or callable

The node data key to filter. If callable, then it is expected to return a condition when called with a column parameter. In that case the ‘key-condition’ is the condition returned when the column parameter is the node data key column. Otherwise, it is the key name to filter against equality. E.g., key=3 is equivalent to key=lambda c: c.eq(3).

value: any

If provided, a condition is built in addition to the one resulting from the treatment of the key parameter, as follows. If the given value is callable, then it is expected to take one column argument, namely the node data value column, and return a condition. Otherwise it is considered as a (any-type but callable) value indicating the value to be matched by the node data value column. E.g., value=3 is equivalent to value=lambda c: c.eq(3).

strict: Boolean = True

This flag is aimed for internal use only. It allows to construct a different condition when the intention is to filter only nodes that do admit the corresponding key key, thus keeping all nodes not admitting it.

nx_variant

alias of Graph

reindex()

Restore indices present in the schema.

remove_edge(u, v)

Remove the edge between u and v.

Parameters:
u, vnodes

Remove the edge between nodes u and v.

Raises:
NetworkXError

If there is not an edge between u and v.

See also

remove_edges_from

remove a collection of edges

Examples

>>> G = nx.path_graph(4)  # or DiGraph, etc
>>> G.remove_edge(0, 1)
>>> e = (1, 2)
>>> G.remove_edge(*e)  # unpacks e from an edge tuple
>>> e = (2, 3, {"weight": 7})  # an edge with attribute data
>>> G.remove_edge(*e[:2])  # select first part of edge tuple
remove_edges_from(ebunch)

Remove all edges specified in ebunch.

Parameters:
ebunch: list or container of edge tuples

Each edge given in the list or container will be removed from the graph. The edges can be:

  • 2-tuples (u, v) edge between u and v.

  • 3-tuples (u, v, k) where k is ignored.

See also

remove_edge

remove a single edge

Notes

Will fail silently if an edge in ebunch is not in the graph.

Examples

>>> G = nx.path_graph(4)  # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> ebunch = [(1, 2), (2, 3)]
>>> G.remove_edges_from(ebunch)
remove_node(node, cascade=None)

Remove a node.

If cascade is True, suppose edges refering to nodes have the “ON DELETE CASCADE”. Hence, constraints are done on SQLite side. If cascade is False, we user the nx version to ensure structure.

remove_nodes_from(nodes, cascade=None)

Remove multiple nodes.

If cascade is True, suppose edges refering to nodes have the “ON DELETE CASCADE”. Hence, constraints are done on SQLite side. If cascade is False, we user the nx version to ensure structure.

Parameters:
nodesiterable container

A container of nodes (list, dict, set, etc.). If a node in the container is not in the graph it is silently ignored.

See also

remove_node
setsignature(schema, masterid, lazy=None, create=None, static=False, node_cache_level=0, edge_cache_level=0)

Internal initialization of Graph.

Parameters:
schema: GraphSchema

The graph schema to use.

masterid: int or None

The graph id in master table if any, or None otherwise.

lazy: bool or None, default=None

The underlying tupledicts lazyness.

create: bool or None, default=None

Whether the creation script of the given schema (that creates the schema tables, views, index, and triggers) should be executed or not. If None, then it is executed with the SQL IF NOT EXISTS flag.

size(weight=None, default=1.0)

Returns the number of edges or total of all edge weights.

Parameters:
weightstring or None, optional (default=None)

The edge attribute that holds the numerical value used as a weight. If None, then each edge has weight 1.

Returns:
sizenumeric

The number of edges or (if weight keyword is provided) the total weight sum.

If weight is None, returns an int. Otherwise a float (or more general numeric if the weights are more general).

See also

number_of_edges

Examples

>>> G = nx.path_graph(4)  # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> G.size()
3
>>> G = nx.Graph()  # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> G.add_edge("a", "b", weight=2)
>>> G.add_edge("b", "c", weight=4)
>>> G.size()
2
>>> G.size(weight="weight")
6.0
subgraph(nodes, temporary_table=False)

Return a subgraph view or a static subgraph of the subgraph induced by nodes

The induced subgraph of the graph contains the nodes in nodes and the edges between those nodes.

Parameters:
nodes: iterable or node or condition

The nodes to select for the subgraph. If an IterableQuery, a specific optimized condition is built. If a condition, it should be a filter_node condition as accepted by the function nd.sql.classes.subgraph_view.

temporary_table: bool, default=False

If True, then the selected nodes will be stored in a temporary table on disk. It will have much better performance but will not provide a view but a semi-static subgraph instead (edges are maintained but not nodes). Ignored if filter_node is False.

Returns:
A networkdisk Graph based on the same helper than self (DB-connector) and exposing the desired subgraph.

Examples

>>> G = nd.sqlite.Graph()
>>> G.add_edges_from([(0, 1), (1, 2), (2, 3)])
>>> K = G.subgraph([1, 2, 3])
>>> sorted(K.edges)
[(1, 2), (2, 3)]
>>> sorted(K.nodes)
[1, 2, 3]

To increase performance, we can use temporary table for storing the node domain on disk: >>> J = G.subgraph([1, 2, 3], temporary_table=True) >>> sorted(J.edges) [(1, 2), (2, 3)] >>> sorted(J.nodes) [1, 2, 3]

But J is not a view anylonger, K is a view: >>> G.remove_node(3) >>> sorted(K.nodes) [1, 2] >>> sorted(J.nodes) [1, 2, 3]

However, J does follows correctly edges of G: >>> sorted(J.edges) [(1, 2)] >>> sorted(K.edges) [(1, 2)]

to_directed(as_view=False)

Returns a directed representation of the graph.

Returns:
GDiGraph

A directed graph with the same name, same nodes, and with each edge (u, v, data) replaced by two directed edges (u, v, data) and (v, u, data).

Notes

This returns a “deepcopy” of the edge, node, and graph attributes which attempts to completely copy all of the data and references.

This is in contrast to the similar D=DiGraph(G) which returns a shallow copy of the data.

See the Python copy module for more information on shallow and deep copies, https://docs.python.org/3/library/copy.html.

Warning: If you have subclassed Graph to use dict-like objects in the data structure, those changes do not transfer to the DiGraph created by this method.

Examples

>>> G = nx.Graph()  # or MultiGraph, etc
>>> G.add_edge(0, 1)
>>> H = G.to_directed()
>>> list(H.edges)
[(0, 1), (1, 0)]

If already directed, return a (deep) copy

>>> G = nx.DiGraph()  # or MultiDiGraph, etc
>>> G.add_edge(0, 1)
>>> H = G.to_directed()
>>> list(H.edges)
[(0, 1)]
to_undirected(as_view=False)

Returns an undirected copy of the graph.

Parameters:
as_viewbool (optional, default=False)

If True return a view of the original undirected graph.

Returns:
GGraph/MultiGraph

A deepcopy of the graph.

Notes

This returns a “deepcopy” of the edge, node, and graph attributes which attempts to completely copy all of the data and references.

This is in contrast to the similar G = nx.DiGraph(D) which returns a shallow copy of the data.

See the Python copy module for more information on shallow and deep copies, https://docs.python.org/3/library/copy.html.

Warning: If you have subclassed DiGraph to use dict-like objects in the data structure, those changes do not transfer to the Graph created by this method.

Examples

>>> G = nx.path_graph(2)  # or MultiGraph, etc
>>> H = G.to_directed()
>>> list(H.edges)
[(0, 1), (1, 0)]
>>> G2 = H.to_undirected()
>>> list(G2.edges)
[(0, 1)]
class networkdisk.sqlite.Graph(incoming_graph_data=None, db=None, sql_logger=<networkdisk.utils.constants.NotProvidedArg object>, autocommit=False, schema=None, create=None, insert_schema=None, lazy=None, static=False, node_cache_level=None, edge_cache_level=None, cache_level=0, masterid=None, name=None, **attr)
copy(as_view=False)

Returns a copy of the graph.

The copy method by default returns an independent shallow copy of the graph and attributes. That is, if an attribute is a container, that container is shared by the original an the copy. Use Python’s copy.deepcopy for new containers.

If as_view is True then a view is returned instead of a copy.

Parameters:
as_viewbool, optional (default=False)

If True, the returned graph-view provides a read-only view of the original graph without actually copying any data.

Returns:
GGraph

A copy of the graph.

See also

to_directed

return a directed copy of the graph.

Notes

All copies reproduce the graph structure, but data attributes may be handled in different ways. There are four types of copies of a graph that people might want.

Deepcopy – A “deepcopy” copies the graph structure as well as all data attributes and any objects they might contain. The entire graph object is new so that changes in the copy do not affect the original object. (see Python’s copy.deepcopy)

Data Reference (Shallow) – For a shallow copy the graph structure is copied but the edge, node and graph attribute dicts are references to those in the original graph. This saves time and memory but could cause confusion if you change an attribute in one graph and it changes the attribute in the other. NetworkX does not provide this level of shallow copy.

Independent Shallow – This copy creates new independent attribute dicts and then does a shallow copy of the attributes. That is, any attributes that are containers are shared between the new graph and the original. This is exactly what dict.copy() provides. You can obtain this style copy using:

>>> G = nx.path_graph(5)
>>> H = G.copy()
>>> H = G.copy(as_view=False)
>>> H = nx.Graph(G)
>>> H = G.__class__(G)

Fresh Data – For fresh data, the graph structure is copied while new empty data attribute dicts are created. The resulting graph is independent of the original and it has no edge, node or graph attributes. Fresh copies are not enabled. Instead use:

>>> H = G.__class__()
>>> H.add_nodes_from(G)
>>> H.add_edges_from(G.edges)

View – Inspired by dict-views, graph-views act like read-only versions of the original graph, providing a copy of the original structure without requiring any memory for copying the information.

See the Python copy module for more information on shallow and deep copies, https://docs.python.org/3/library/copy.html.

Examples

>>> G = nx.path_graph(4)  # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> H = G.copy()

DiGraph

class networkdisk.sql.DiGraph(incoming_graph_data=None, db=None, sql_logger=<networkdisk.utils.constants.NotProvidedArg object>, autocommit=False, schema=None, create=None, insert_schema=None, lazy=None, static=False, node_cache_level=None, edge_cache_level=None, cache_level=0, masterid=None, name=None, **attr)
property degree

A DegreeView for the Graph as G.degree or G.degree().

The node degree is the number of edges adjacent to the node. The weighted node degree is the sum of the edge weights for edges incident to that node.

This object provides an iterator for (node, degree) as well as lookup for the degree for a single node.

Parameters:
nbunchsingle node, container, or all nodes (default= all nodes)

The view will only report edges incident to these nodes.

weightstring or None, optional (default=None)

The name of an edge attribute that holds the numerical value used as a weight. If None, then each edge has weight 1. The degree is the sum of the edge weights adjacent to the node.

Returns:
If a single node is requested
degint

Degree of the node

OR if multiple nodes are requested
nd_iteriterator

The iterator returns two-tuples of (node, degree).

See also

in_degree, out_degree

Examples

>>> G = nx.DiGraph()  # or MultiDiGraph
>>> nx.add_path(G, [0, 1, 2, 3])
>>> G.degree(0)  # node 0 with degree 1
1
>>> list(G.degree([0, 1, 2]))
[(0, 1), (1, 2), (2, 2)]
property edges

An OutEdgeView of the DiGraph as G.edges or G.edges().

edges(self, nbunch=None, data=False, default=None)

The OutEdgeView provides set-like operations on the edge-tuples as well as edge attribute lookup. When called, it also provides an EdgeDataView object which allows control of access to edge attributes (but does not provide set-like operations). Hence, G.edges[u, v][‘color’] provides the value of the color attribute for edge (u, v) while for (u, v, c) in G.edges.data(‘color’, default=’red’): iterates through all the edges yielding the color attribute with default ‘red’ if no color attribute exists.

Parameters:
nbunchsingle node, container, or all nodes (default= all nodes)

The view will only report edges from these nodes.

datastring or bool, optional (default=False)

The edge attribute returned in 3-tuple (u, v, ddict[data]). If True, return edge attribute dict in 3-tuple (u, v, ddict). If False, return 2-tuple (u, v).

defaultvalue, optional (default=None)

Value used for edges that don’t have the requested attribute. Only relevant if data is not True or False.

Returns:
edgesOutEdgeView

A view of edge attributes, usually it iterates over (u, v) or (u, v, d) tuples of edges, but can also be used for attribute lookup as edges[u, v][‘foo’].

See also

in_edges, out_edges

Notes

Nodes in nbunch that are not in the graph will be (quietly) ignored. For directed graphs this returns the out-edges.

Examples

>>> G = nx.DiGraph()  # or MultiDiGraph, etc
>>> nx.add_path(G, [0, 1, 2])
>>> G.add_edge(2, 3, weight=5)
>>> [e for e in G.edges]
[(0, 1), (1, 2), (2, 3)]
>>> G.edges.data()  # default data is {} (empty dict)
OutEdgeDataView([(0, 1, {}), (1, 2, {}), (2, 3, {'weight': 5})])
>>> G.edges.data("weight", default=1)
OutEdgeDataView([(0, 1, 1), (1, 2, 1), (2, 3, 5)])
>>> G.edges([0, 2])  # only edges originating from these nodes
OutEdgeDataView([(0, 1), (2, 3)])
>>> G.edges(0)  # only edges from node 0
OutEdgeDataView([(0, 1)])
property in_degree

An InDegreeView for (node, in_degree) or in_degree for single node.

The node in_degree is the number of edges pointing to the node. The weighted node degree is the sum of the edge weights for edges incident to that node.

This object provides an iteration over (node, in_degree) as well as lookup for the degree for a single node.

Parameters:
nbunchsingle node, container, or all nodes (default= all nodes)

The view will only report edges incident to these nodes.

weightstring or None, optional (default=None)

The name of an edge attribute that holds the numerical value used as a weight. If None, then each edge has weight 1. The degree is the sum of the edge weights adjacent to the node.

Returns:
If a single node is requested
degint

In-degree of the node

OR if multiple nodes are requested
nd_iteriterator

The iterator returns two-tuples of (node, in-degree).

See also

degree, out_degree

Examples

>>> G = nx.DiGraph()
>>> nx.add_path(G, [0, 1, 2, 3])
>>> G.in_degree(0)  # node 0 with degree 0
0
>>> list(G.in_degree([0, 1, 2]))
[(0, 0), (1, 1), (2, 1)]
property in_edges

An InEdgeView of the Graph as G.in_edges or G.in_edges().

in_edges(self, nbunch=None, data=False, default=None):

Parameters:
nbunchsingle node, container, or all nodes (default= all nodes)

The view will only report edges incident to these nodes.

datastring or bool, optional (default=False)

The edge attribute returned in 3-tuple (u, v, ddict[data]). If True, return edge attribute dict in 3-tuple (u, v, ddict). If False, return 2-tuple (u, v).

defaultvalue, optional (default=None)

Value used for edges that don’t have the requested attribute. Only relevant if data is not True or False.

Returns:
in_edgesInEdgeView

A view of edge attributes, usually it iterates over (u, v) or (u, v, d) tuples of edges, but can also be used for attribute lookup as edges[u, v][‘foo’].

See also

edges
nx_variant

alias of DiGraph

property out_degree

An OutDegreeView for (node, out_degree)

The node out_degree is the number of edges pointing out of the node. The weighted node degree is the sum of the edge weights for edges incident to that node.

This object provides an iterator over (node, out_degree) as well as lookup for the degree for a single node.

Parameters:
nbunchsingle node, container, or all nodes (default= all nodes)

The view will only report edges incident to these nodes.

weightstring or None, optional (default=None)

The name of an edge attribute that holds the numerical value used as a weight. If None, then each edge has weight 1. The degree is the sum of the edge weights adjacent to the node.

Returns:
If a single node is requested
degint

Out-degree of the node

OR if multiple nodes are requested
nd_iteriterator

The iterator returns two-tuples of (node, out-degree).

See also

degree, in_degree

Examples

>>> G = nx.DiGraph()
>>> nx.add_path(G, [0, 1, 2, 3])
>>> G.out_degree(0)  # node 0 with degree 1
1
>>> list(G.out_degree([0, 1, 2]))
[(0, 1), (1, 1), (2, 1)]
property out_edges

An OutEdgeView of the DiGraph as G.edges or G.edges().

edges(self, nbunch=None, data=False, default=None)

The OutEdgeView provides set-like operations on the edge-tuples as well as edge attribute lookup. When called, it also provides an EdgeDataView object which allows control of access to edge attributes (but does not provide set-like operations). Hence, G.edges[u, v][‘color’] provides the value of the color attribute for edge (u, v) while for (u, v, c) in G.edges.data(‘color’, default=’red’): iterates through all the edges yielding the color attribute with default ‘red’ if no color attribute exists.

Parameters:
nbunchsingle node, container, or all nodes (default= all nodes)

The view will only report edges from these nodes.

datastring or bool, optional (default=False)

The edge attribute returned in 3-tuple (u, v, ddict[data]). If True, return edge attribute dict in 3-tuple (u, v, ddict). If False, return 2-tuple (u, v).

defaultvalue, optional (default=None)

Value used for edges that don’t have the requested attribute. Only relevant if data is not True or False.

Returns:
edgesOutEdgeView

A view of edge attributes, usually it iterates over (u, v) or (u, v, d) tuples of edges, but can also be used for attribute lookup as edges[u, v][‘foo’].

See also

in_edges, out_edges

Notes

Nodes in nbunch that are not in the graph will be (quietly) ignored. For directed graphs this returns the out-edges.

Examples

>>> G = nx.DiGraph()  # or MultiDiGraph, etc
>>> nx.add_path(G, [0, 1, 2])
>>> G.add_edge(2, 3, weight=5)
>>> [e for e in G.edges]
[(0, 1), (1, 2), (2, 3)]
>>> G.edges.data()  # default data is {} (empty dict)
OutEdgeDataView([(0, 1, {}), (1, 2, {}), (2, 3, {'weight': 5})])
>>> G.edges.data("weight", default=1)
OutEdgeDataView([(0, 1, 1), (1, 2, 1), (2, 3, 5)])
>>> G.edges([0, 2])  # only edges originating from these nodes
OutEdgeDataView([(0, 1), (2, 3)])
>>> G.edges(0)  # only edges from node 0
OutEdgeDataView([(0, 1)])
reverse(copy=False)

Returns the reverse of the graph.

The reverse is a graph with the same nodes and edges but with the directions of the edges reversed.

Parameters:
copybool optional (default=True)

If True, return a new DiGraph holding the reversed edges. If False, the reverse graph is created using a view of the original graph.

to_undirected(as_view=True, reciprocal=False)

Returns an undirected copy of the graph.

Parameters:
as_viewbool (optional, default=False)

If True return a view of the original undirected graph.

Returns:
GGraph/MultiGraph

A deepcopy of the graph.

See also

Graph, copy, add_edge, add_edges_from

Notes

This returns a “deepcopy” of the edge, node, and graph attributes which attempts to completely copy all of the data and references.

This is in contrast to the similar G = nx.DiGraph(D) which returns a shallow copy of the data.

See the Python copy module for more information on shallow and deep copies, https://docs.python.org/3/library/copy.html.

Warning: If you have subclassed DiGraph to use dict-like objects in the data structure, those changes do not transfer to the Graph created by this method.

Examples

>>> G = nx.path_graph(2)  # or MultiGraph, etc
>>> H = G.to_directed()
>>> list(H.edges)
[(0, 1), (1, 0)]
>>> G2 = H.to_undirected()
>>> list(G2.edges)
[(0, 1)]
class networkdisk.sqlite.DiGraph(incoming_graph_data=None, db=None, sql_logger=<networkdisk.utils.constants.NotProvidedArg object>, autocommit=False, schema=None, create=None, insert_schema=None, lazy=None, static=False, node_cache_level=None, edge_cache_level=None, cache_level=0, masterid=None, name=None, **attr)