easygraph.classes.directed_graph module#

class easygraph.classes.directed_graph.DiGraph(incoming_graph_data=None, **graph_attr)[source]#

Bases: Graph

Base class for directed graphs.

Nodes are allowed for any hashable Python objects, including int, string, dict, etc. Edges are stored as Python dict type, with optional key/value attributes.

Parameters:

graph_attr (keywords arguments, optional (default : None)) – Attributes to add to graph as key=value pairs.

See also

Graph

Examples

Create an empty directed graph with no nodes and edges.

>>> G = eg.DiGraph()

Create a deep copy graph G2 from existing Graph G1.

>>> G2 = G1.copy()

Create an graph with attributes.

>>> G = eg.DiGraph(name='Karate Club', date='2020.08.21')

Attributes:

Returns the adjacency matrix of the graph.

>>> G.adj

Returns all the nodes with their attributes.

>>> G.nodes

Returns all the edges with their attributes.

>>> G.edges
Attributes:
A

Return the adjacency matrix \(\mathbf{A}\) of the sample graph with torch.sparse_coo_tensor format.

D_v

Return the diagonal matrix of vertex degree \(\mathbf{D}_v\) with torch.sparse_coo_tensor format.

D_v_neg_1_2

Return the normalized diagonal matrix of vertex degree \(\mathbf{D}_v^{-\frac{1}{2}}\) with torch.sparse_coo_tensor format.

L_GCN

Return the GCN Laplacian matrix \(\mathcal{L}_{GCN}\) of the graph with torch.sparse_coo_tensor format.

adj

Return the adjacency matrix

e

Return the edge list, weight list and property list in the graph.

e_both_side

Return the list of edges including both directions.

edges

Return an edge list

index2node

Assign an integer index for each node (start from 0)

name

String identifier of the graph.

ndata
node_index

Assign an integer index for each node (start from 0)

nodes

return [node for node in self._node]

pred

Return the pred of each node

Methods

add_edge(u_of_edge, v_of_edge, **edge_attr)

Add a directed edge.

add_edges(edges_for_adding[, edges_attr])

Add a list of edges.

add_edges_from(ebunch_to_add, **attr)

Add all the edges in ebunch_to_add.

add_edges_from_file(file[, weighted])

Added edges from file For example, txt files,

add_extra_selfloop()

Add extra selfloops to the graph.

add_node(node_for_adding, **node_attr)

Add one node

add_nodes(nodes_for_adding[, nodes_attr])

Add nodes with a list of nodes.

add_nodes_from(nodes_for_adding, **attr)

Add multiple nodes.

add_weighted_edge(u_of_edge, v_of_edge, weight)

Add a weighted edge

add_weighted_edges_from(ebunch_to_add[, weight])

Add weighted edges in ebunch_to_add with specified weight attr

adjlist_inner_dict_factory

alias of dict

adjlist_outer_dict_factory

alias of dict

all_neighbors(node)

Returns an iterator of a node's neighbors, including both successors and predecessors.

clone()

Clone the graph.

copy()

Return a deep copy of the graph.

degree([weight])

Returns the weighted degree of each node, i.e. sum of out/in degree.

edge_attr_dict_factory

alias of dict

ego_subgraph(center)

Returns an ego network graph of a node.

gnn_data_dict_factory

alias of dict

graph_attr_dict_factory

alias of dict

has_edge(u, v)

Returns whether an edge exists

has_node(node)

Returns whether a node exists

in_degree([weight])

Returns the weighted in degree of each node.

is_directed()

Returns True if graph is a directed_graph, False otherwise.

is_multigraph()

Returns True if graph is a multigraph, False otherwise.

nbr_v(v_idx)

Return a vertex list of the neighbors of the vertex v_idx.

nbunch_iter([nbunch])

Returns an iterator over nodes contained in nbunch that are also in the graph.

neighbors(node)

Returns an iterator of a node's neighbors (successors).

node_attr_dict_factory

alias of dict

node_dict_factory

alias of dict

node_index_dict

alias of dict

nodes_subgraph(from_nodes)

Returns a subgraph of some nodes

number_of_edges([u, v])

Returns the number of edges between two nodes.

number_of_nodes()

Returns the number of nodes.

order()

Returns the number of nodes in the graph.

out_degree([weight])

Returns the weighted out degree of each node.

predecessors(node)

Returns an iterator of a node's neighbors (predecessors).

raw_selfloop_dict

alias of dict

remove_edge(u, v)

Remove one edge from your graph.

remove_edges(edges_to_remove)

Remove a list of edges from your graph.

remove_edges_from(ebunch)

Remove all edges specified in ebunch.

remove_extra_selfloop()

Remove extra selfloops from the graph.

remove_node(node_to_remove)

Remove one node from your graph.

remove_nodes(nodes_to_remove)

Remove nodes from your graph.

remove_nodes_from(nodes)

Remove multiple nodes.

remove_selfloop()

Remove all selfloops from the graph.

size([weight])

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

smoothing_with_GCN(X[, drop_rate])

Return the smoothed feature matrix with GCN Laplacian matrix \(\mathcal{L}_{GCN}\).

successors(node)

Returns an iterator of a node's neighbors (successors).

to_directed()

Creates and returns a directed graph from self.

to_directed_class()

Returns the class to use for empty directed copies.

to_index_node_graph([begin_index])

Returns a deep copy of graph, with each node switched to its index.

N_v

cpp

add_edge(u_of_edge, v_of_edge, **edge_attr)[source]#

Add a directed edge.

Parameters:
  • u_of_edge (object) – The start end of this edge

  • v_of_edge (object) – The destination end of this edge

  • edge_attr (keywords arguments, optional) – The attribute of the edge.

Notes

Nodes of this edge will be automatically added to the graph, if they do not exist.

See also

add_edges

Examples

>>> G.add_edge(1,2)
>>> G.add_edge('Jack', 'Tom', weight=10)

Add edge with attributes, edge weight, for example,

>>> G.add_edge(1, 2, **{
...     'weight': 20
... })
add_edges(edges_for_adding, edges_attr: List[Dict] = [])[source]#

Add a list of edges.

Parameters:
  • edges_for_adding (list of 2-element tuple) – The edges for adding. Each element is a (u, v) tuple, and u, v are start end and destination end, respectively.

  • edges_attr (list of dict, optional) – The corresponding attributes for each edge in edges_for_adding.

Examples

Add a list of edges into G

>>> G.add_edges([
...     (1, 2),
...     (3, 4),
...     ('Jack', 'Tom')
... ])

Add edge with attributes, for example, edge weight,

>>> G.add_edges([(1,2), (2, 3)], edges_attr=[
...     {
...         'weight': 20
...     },
...     {
...         'weight': 15
...     }
... ])
add_edges_from(ebunch_to_add, **attr)[source]#

Add all the edges in ebunch_to_add.

Parameters:
  • ebunch_to_add (container of edges) – Each edge given in the container will be added to the graph. The edges must be given as 2-tuples (u, v) or 3-tuples (u, v, d) where d is a dictionary containing edge data.

  • attr (keyword arguments, optional) – Edge data (or labels or objects) can be assigned using keyword arguments.

See also

add_edge

add a single edge

add_weighted_edges_from

convenient way to add weighted edges

Notes

Adding the same edge twice has no effect but any edge data will be updated when each duplicate edge is added.

Edge attributes specified in an ebunch take precedence over attributes specified via keyword arguments.

Examples

>>> G = eg.Graph()  # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> G.add_edges_from([(0, 1), (1, 2)])  # using a list of edge tuples
>>> e = zip(range(0, 3), range(1, 4))
>>> G.add_edges_from(e)  # Add the path graph 0-1-2-3

Associate data to edges

>>> G.add_edges_from([(1, 2), (2, 3)], weight=3)
>>> G.add_edges_from([(3, 4), (1, 4)], label="WN2898")
add_edges_from_file(file, weighted=False)[source]#

Added edges from file For example, txt files,

Each line is in form like: a b 23.0 which denotes an edge a → b with weight 23.0.

Parameters:
  • file (string) – The file path.

  • weighted (boolean, optional (default : False)) – If the file consists of weight information, set True. The weight key will be set as ‘weight’.

Examples

If ./club_network.txt is:

Jack Mary 23.0

Mary Tom 15.0

Tom Ben 20.0

Then add them to G

>>> G.add_edges_from_file(file='./club_network.txt', weighted=True)
add_node(node_for_adding, **node_attr)[source]#

Add one node

Add one node, type of which is any hashable Python object, such as int, string, dict, or even Graph itself. You can add with node attributes using Python dict type.

Parameters:
  • node_for_adding (any hashable Python object) – Nodes for adding.

  • node_attr (keywords arguments, optional) – The node attributes. You can customize them with different key-value pairs.

See also

add_nodes

Examples

>>> G.add_node('a')
>>> G.add_node('hello world')
>>> G.add_node('Jack', age=10)
>>> G.add_node('Jack', **{
...     'age': 10,
...     'gender': 'M'
... })
add_nodes(nodes_for_adding: list, nodes_attr: List[Dict] = [])[source]#

Add nodes with a list of nodes.

Parameters:
  • nodes_for_adding (list) –

  • nodes_attr (list of dict) – The corresponding attribute for each of nodes_for_adding.

See also

add_node

Examples

Add nodes with a list of nodes. You can add with node attributes using a list of Python dict type, each of which is the attribute of each node, respectively.

>>> G.add_nodes([1, 2, 'a', 'b'])
>>> G.add_nodes(range(1, 200))
>>> G.add_nodes(['Jack', 'Tom', 'Lily'], nodes_attr=[
...     {
...         'age': 10,
...         'gender': 'M'
...     },
...     {
...         'age': 11,
...         'gender': 'M'
...     },
...     {
...         'age': 10,
...         'gender': 'F'
...     }
... ])
add_nodes_from(nodes_for_adding, **attr)[source]#

Add multiple nodes.

Parameters:
  • nodes_for_adding (iterable container) – A container of nodes (list, dict, set, etc.). OR A container of (node, attribute dict) tuples. Node attributes are updated using the attribute dict.

  • attr (keyword arguments, optional (default= no attributes)) – Update attributes for all nodes in nodes. Node attributes specified in nodes as a tuple take precedence over attributes specified via keyword arguments.

See also

add_node

Examples

>>> G = eg.Graph()  # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> G.add_nodes_from("Hello")
>>> K3 = eg.Graph([(0, 1), (1, 2), (2, 0)])
>>> G.add_nodes_from(K3)
>>> sorted(G.nodes(), key=str)
[0, 1, 2, 'H', 'e', 'l', 'o']

Use keywords to update specific node attributes for every node.

>>> G.add_nodes_from([1, 2], size=10)
>>> G.add_nodes_from([3, 4], weight=0.4)

Use (node, attrdict) tuples to update attributes for specific nodes.

>>> G.add_nodes_from([(1, dict(size=11)), (2, {"color": "blue"})])
>>> G.nodes[1]["size"]
11
>>> H = eg.Graph()
>>> H.add_nodes_from(G.nodes(data=True))
>>> H.nodes[1]["size"]
11
add_weighted_edge(u_of_edge, v_of_edge, weight)[source]#

Add a weighted edge

Parameters:
  • u_of_edge (start node) –

  • v_of_edge (end node) –

  • weight (weight value) –

Examples

Add a weighted edge

>>> G.add_weighted_edge( 1 , 3 , 1.0)
property adj#

Return the adjacency matrix

adjlist_inner_dict_factory#

alias of dict

adjlist_outer_dict_factory#

alias of dict

all_neighbors(node)[source]#

Returns an iterator of a node’s neighbors, including both successors and predecessors.

Parameters:

node (Hashable) – The target node.

Returns:

neighbors – An iterator of a node’s neighbors, including both successors and predecessors.

Return type:

iterator

Examples

>>> G = eg.Graph()
>>> G.add_edges([(1,2), (2,3), (2,4)])
>>> for neighbor in G.all_neighbors(node=2):
...     print(neighbor)
copy()[source]#

Return a deep copy of the graph.

Returns:

copy – A deep copy of the original graph.

Return type:

easygraph.DiGraph

Examples

G2 is a deep copy of G1

>>> G2 = G1.copy()
cpp()[source]#
degree(weight='weight')[source]#

Returns the weighted degree of each node, i.e. sum of out/in degree.

Parameters:

weight (string, optional (default : 'weight')) – Weight key of the original weighted graph.

Returns:

degree – Each node’s (key) weighted in degree (value). For directed graph, it returns the sum of out degree and in degree.

Return type:

dict

Notes

If the graph is not weighted, all the weights will be regarded as 1.

See also

out_degree, in_degree

Examples

>>> G.degree()
>>> G.degree(weight='weight')

or you can customize the weight key

>>> G.degree(weight='weight_1')
edge_attr_dict_factory#

alias of dict

property edges#

Return an edge list

ego_subgraph(center)[source]#

Returns an ego network graph of a node.

Parameters:

center (object) – The center node of the ego network graph

Returns:

ego_subgraph – The ego network graph of center.

Return type:

easygraph.Graph

Examples

>>> G = eg.Graph()
>>> G.add_edges([
...     ('Jack', 'Maria'),
...     ('Maria', 'Andy'),
...     ('Jack', 'Tom')
... ])
>>> G.ego_subgraph(center='Jack')
gnn_data_dict_factory#

alias of dict

graph_attr_dict_factory#

alias of dict

has_edge(u, v)[source]#

Returns whether an edge exists

Parameters:
  • u (start node) –

  • v (end node) –

Returns:

Bool

Return type:

True (exist) or False (not exists)

has_node(node)[source]#

Returns whether a node exists

Parameters:

node

Returns:

Bool

Return type:

True (exist) or False (not exists)

in_degree(weight='weight')[source]#

Returns the weighted in degree of each node.

Parameters:

weight (string, optional (default : 'weight')) – Weight key of the original weighted graph.

Returns:

in_degree – Each node’s (key) weighted in degree (value).

Return type:

dict

Notes

If the graph is not weighted, all the weights will be regarded as 1.

See also

out_degree, degree

Examples

>>> G.in_degree(weight='weight')
property index2node#

Assign an integer index for each node (start from 0)

is_directed()[source]#

Returns True if graph is a directed_graph, False otherwise.

is_multigraph()[source]#

Returns True if graph is a multigraph, False otherwise.

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)[source]#

Returns an iterator over nodes contained in nbunch that are also in the graph.

The nodes in nbunch are checked for membership in the graph and if not are silently ignored.

Parameters:

nbunch (single node, container, or all nodes (default= all nodes)) – The view will only report edges incident to these nodes.

Returns:

niter – An iterator over nodes in nbunch that are also in the graph. If nbunch is None, iterate over all nodes in the graph.

Return type:

iterator

Raises:

EasyGraphError – If nbunch is not a node or sequence of nodes. If a node in nbunch is not hashable.

See also

Graph.__iter__

Notes

When nbunch is an iterator, the returned iterator yields values directly from nbunch, becoming exhausted when nbunch is exhausted.

To test whether nbunch is a single node, one can use “if nbunch in self:”, even after processing with this routine.

If nbunch is not a node or a (possibly empty) sequence/iterator or None, a EasyGraphError is raised. Also, if any object in nbunch is not hashable, a EasyGraphError is raised.

property ndata#
neighbors(node)[source]#

Returns an iterator of a node’s neighbors (successors).

Parameters:

node (Hashable) – The target node.

Returns:

neighbors – An iterator of a node’s neighbors (successors).

Return type:

iterator

Examples

>>> G = eg.Graph()
>>> G.add_edges([(1,2), (2,3), (2,4)])
>>> for neighbor in G.neighbors(node=2):
...     print(neighbor)
node_attr_dict_factory#

alias of dict

node_dict_factory#

alias of dict

property node_index#

Assign an integer index for each node (start from 0)

node_index_dict#

alias of dict

property nodes#

return [node for node in self._node]

nodes_subgraph(from_nodes: list)[source]#

Returns a subgraph of some nodes

Parameters:

from_nodes (list of object) – The nodes in subgraph.

Returns:

nodes_subgraph – The subgraph consisting of from_nodes.

Return type:

easygraph.Graph

Examples

>>> G = eg.Graph()
>>> G.add_edges([(1,2), (2,3), (2,4), (4,5)])
>>> G_sub = G.nodes_subgraph(from_nodes= [1,2,3])
number_of_edges(u=None, v=None)[source]#

Returns the number of edges between two nodes.

Parameters:
  • u (nodes, optional (default=all edges)) – If u and v are specified, return the number of edges between u and v. Otherwise return the total number of all edges.

  • v (nodes, optional (default=all edges)) – If u and v are specified, return the number of edges between u and v. Otherwise return the total number of all edges.

Returns:

nedges – The number of edges in the graph. If nodes u and v are specified return the number of edges between those nodes. If the graph is directed, this only returns the number of edges from u to v.

Return type:

int

See also

size

Examples

For undirected graphs, this method counts the total number of edges in the graph:

>>> G = eg.path_graph(4)
>>> G.number_of_edges()
3

If you specify two nodes, this counts the total number of edges joining the two nodes:

>>> G.number_of_edges(0, 1)
1

For directed graphs, this method can count the total number of directed edges from u to v:

>>> G = eg.DiGraph()
>>> G.add_edge(0, 1)
>>> G.add_edge(1, 0)
>>> G.number_of_edges(0, 1)
1
number_of_nodes()[source]#

Returns the number of nodes.

Returns:

number_of_nodes – The number of nodes.

Return type:

int

out_degree(weight='weight')[source]#

Returns the weighted out degree of each node.

Parameters:

weight (string, optional (default : 'weight')) – Weight key of the original weighted graph.

Returns:

out_degree – Each node’s (key) weighted out degree (value).

Return type:

dict

Notes

If the graph is not weighted, all the weights will be regarded as 1.

See also

in_degree, degree

Examples

>>> G.out_degree(weight='weight')
property pred#

Return the pred of each node

predecessors(node)[source]#

Returns an iterator of a node’s neighbors (predecessors).

Parameters:

node (Hashable) – The target node.

Returns:

neighbors – An iterator of a node’s neighbors (predecessors).

Return type:

iterator

Examples

>>> G = eg.Graph()
>>> G.add_edges([(1,2), (2,3), (2,4)])
>>> for predecessor in G.predecessors(node=2):
...     print(predecessor)
remove_edge(u, v)[source]#

Remove one edge from your graph.

Parameters:
  • u (object) – The start end of the edge.

  • v (object) – The destination end of the edge.

See also

remove_edges

Examples

Remove edge (1,2) from G

>>> G.remove_edge(1,2)
remove_edges(edges_to_remove: [<class 'tuple'>])[source]#

Remove a list of edges from your graph.

Parameters:

edges_to_remove (list of tuple) – The list of edges you want to remove, Each element is (u, v) tuple, which denote the start and destination end of the edge, respectively.

See also

remove_edge

Examples

Remove the edges (‘Jack’, ‘Mary’) amd (‘Mary’, ‘Tom’) from G

>>> G.remove_edge([
...     ('Jack', 'Mary'),
...     ('Mary', 'Tom')
... ])
remove_edges_from(ebunch)[source]#

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 = eg.path_graph(4)  # or DiGraph, MultiGraph, MultiDiGraph, etc
>>> ebunch = [(1, 2), (2, 3)]
>>> G.remove_edges_from(ebunch)
remove_node(node_to_remove)[source]#

Remove one node from your graph.

Parameters:

node_to_remove (object) – The node you want to remove.

See also

remove_nodes

Examples

Remove node Jack from G

>>> G.remove_node('Jack')
remove_nodes(nodes_to_remove: list)[source]#

Remove nodes from your graph.

Parameters:

nodes_to_remove (list of object) – The list of nodes you want to remove.

See also

remove_node

Examples

Remove node [1, 2, ‘a’, ‘b’] from G

>>> G.remove_nodes([1, 2, 'a', 'b'])
size(weight=None)[source]#

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

Parameters:

weight (String or None, optional) – The weight key. If None, it will calculate the number of edges, instead of total of all edge weights.

Returns:

size – The number of edges or total of all edge weights.

Return type:

int or float, optional (default: None)

Examples

Returns the number of edges in G:

>>> G.size()

Returns the total of all edge weights in G:

>>> G.size(weight='weight')
successors(node)#

Returns an iterator of a node’s neighbors (successors).

Parameters:

node (Hashable) – The target node.

Returns:

neighbors – An iterator of a node’s neighbors (successors).

Return type:

iterator

Examples

>>> G = eg.Graph()
>>> G.add_edges([(1,2), (2,3), (2,4)])
>>> for neighbor in G.neighbors(node=2):
...     print(neighbor)
to_index_node_graph(begin_index=0)[source]#

Returns a deep copy of graph, with each node switched to its index.

Considering that the nodes of your graph may be any possible hashable Python object, you can get an isomorphic graph of the original one, with each node switched to its index.

Parameters:

begin_index (int) – The begin index of the index graph.

Returns:

  • G (easygraph.Graph) – Deep copy of graph, with each node switched to its index.

  • index_of_node (dict) – Index of node

  • node_of_index (dict) – Node of index

Examples

The following method returns this isomorphic graph and index-to-node dictionary as well as node-to-index dictionary.

>>> G = eg.Graph()
>>> G.add_edges([
...     ('Jack', 'Maria'),
...     ('Maria', 'Andy'),
...     ('Jack', 'Tom')
... ])
>>> G_index_graph, index_of_node, node_of_index = G.to_index_node_graph()
class easygraph.classes.directed_graph.DiGraphC[source]#

Bases: DiGraph

Attributes:
adj
edges
graph
name
node_index
nodes
pred

Methods

add_edge(*args, **kwargs)

add_edges(self, edges_for_adding[, edges_attr])

add_edges_from(*args, **kwargs)

add_edges_from_file(self, file[, weighted, ...])

add_node(*args, **kwargs)

add_nodes(self, nodes_for_adding[, nodes_attr])

add_nodes_from(*args, **kwargs)

add_weighted_edge(self, u_of_edge, ...)

all_neighbors(self, node)

copy(self)

degree(self[, weight])

ego_subgraph(self, center)

generate_linkgraph(self[, weight])

has_edge(self, u, y)

has_node(self, node)

in_degree(self[, weight])

is_directed(self)

is_multigraph(self)

nbunch_iter(self[, nbunch])

neighbors(self, node)

nodes_subgraph(self, from_nodes)

number_of_edges(self[, u, v])

number_of_nodes(self)

out_degree(self[, weight])

predecessors(self, node)

py(self)

remove_edge(self, u, v)

remove_edges(self, edges_to_remove)

remove_edges_from(self, ebunch)

remove_node(self, node_to_remove)

remove_nodes(self, nodes_to_remove)

size(self[, weight])

successors(self, node)

to_index_node_graph(self[, begin_index])

cflag = 1#