easygraph.classes package
Submodules
easygraph.classes.base module
- class easygraph.classes.base.BaseHypergraph(num_v: int, e_list_v2e: List[int] | List[List[int]] | None = None, e_list_e2v: List[int] | List[List[int]] | None = None, w_list_v2e: List[float] | List[List[float]] | None = None, w_list_e2v: List[float] | List[List[float]] | None = None, e_weight: float | List[float] | None = None, v_weight: List[float] | None = None, device: device = device(type='cpu'))[source]
Bases:
object
The
BaseHypergraph
class is the base class for all hypergraph structures.- Parameters:
num_v (
int
) – The number of vertices in the hypergraph.e_list_v2e (
Union[List[int], List[List[int]]]
, optional) – A list of hyperedges describes how the vertices point to the hyperedges. Defaults toNone
.e_list_e2v (
Union[List[int], List[List[int]]]
, optional) – A list of hyperedges describes how the hyperedges point to the vertices. Defaults toNone
.w_list_v2e (
Union[List[float], List[List[float]]]
, optional) – The weights are attached to the connections from vertices to hyperedges, which has the same shape ase_list_v2e
. If set toNone
, the value1
is used for all connections. Defaults toNone
.w_list_e2v (
Union[List[float], List[List[float]]]
, optional) – The weights are attached to the connections from the hyperedges to the vertices, which has the same shape toe_list_e2v
. If set toNone
, the value1
is used for all connections. Defaults toNone
.e_weight (
Union[float, List[float]]
, optional) – A list of weights for hyperedges. If set toNone
, the value1
is used for all hyperedges. Defaults toNone
.v_weight (
Union[float, List[float]]
, optional) – Weights for vertices. If set toNone
, the value1
is used for all vertices. Defaults toNone
.device (
torch.device
, optional) – The device to store the hypergraph. Defaults totorch.device('cpu')
.
- abstract property H: Tensor
Return the hypergraph incidence matrix.
- property H_e2v: Tensor
Return the hypergraph incidence matrix with
sparse matrix
format.
- H_e2v_of_group(group_name: str) Tensor [source]
Return the hypergraph incidence matrix with
sparse matrix
format in the specified hyperedge group.- Parameters:
group_name (
str
) – The name of the specified hyperedge group.
- abstract property H_of_group: Tensor
Return the hypergraph incidence matrix in the specified hyperedge group.
- Parameters:
group_name (
str
) – The name of the specified hyperedge group.
- property H_v2e: Tensor
Return the hypergraph incidence matrix with
sparse matrix
format.
- H_v2e_of_group(group_name: str) Tensor [source]
Return the hypergraph incidence matrix with
sparse matrix
format in the specified hyperedge group.- Parameters:
group_name (
str
) – The name of the specified hyperedge group.
- property R_e2v: Tensor
Return the weight matrix of connections (hyperedges point to vertices) with
sparse matrix
format.
- R_e2v_of_group(group_name: str) Tensor [source]
Return the weight matrix of connections (hyperedges point to vertices) with
sparse matrix
format in the specified hyperedge group.- Parameters:
group_name (
str
) – The name of the specified hyperedge group.
- property R_v2e: Tensor
Return the weight matrix of connections (vertices point to hyperedges) with
sparse matrix
format.
- R_v2e_of_group(group_name: str) Tensor [source]
Return the weight matrix of connections (vertices point to hyperedges) with
sparse matrix
format in the specified hyperedge group.- Parameters:
group_name (
str
) – The name of the specified hyperedge group.
- property W_e: Tensor
Return the hyperedge weight matrix of the hypergraph.
- W_e_of_group(group_name: str) Tensor [source]
Return the hyperedge weight matrix of the specified hyperedge group.
- Parameters:
group_name (
str
) – The name of the specified hyperedge group.
- property W_v: Tensor
Return the vertex weight matrix of the hypergraph.
- add_hyperedges(e_list_v2e: List[int] | List[List[int]], e_list_e2v: List[int] | List[List[int]], w_list_v2e: List[float] | List[List[float]] | None = None, w_list_e2v: List[float] | List[List[float]] | None = None, e_weight: float | List[float] | None = None, merge_op: str = 'mean', group_name: str = 'main')[source]
Add hyperedges to the hypergraph. If the
group_name
is not specified, the hyperedges will be added to the defaultmain
hyperedge group.- Parameters:
num_v (
int
) – The number of vertices in the hypergraph.e_list_v2e (
Union[List[int], List[List[int]]]
) – A list of hyperedges describes how the vertices point to the hyperedges.e_list_e2v (
Union[List[int], List[List[int]]]
) – A list of hyperedges describes how the hyperedges point to the vertices.w_list_v2e (
Union[List[float], List[List[float]]]
, optional) – The weights are attached to the connections from vertices to hyperedges, which has the same shape ase_list_v2e
. If set toNone
, the value1
is used for all connections. Defaults toNone
.w_list_e2v (
Union[List[float], List[List[float]]]
, optional) – The weights are attached to the connections from the hyperedges to the vertices, which has the same shape toe_list_e2v
. If set toNone
, the value1
is used for all connections. Defaults toNone
.e_weight (
Union[float, List[float]]
, optional) – A list of weights for hyperedges. If set toNone
, the value1
is used for all hyperedges. Defaults toNone
.merge_op (
str
) – The merge operation for the conflicting hyperedges. The possible values aremean
,sum
,max
, andmin
. Defaults tomean
.group_name (
str
, optional) – The target hyperedge group to add these hyperedges. Defaults to themain
hyperedge group.
- abstract clone() BaseHypergraph [source]
Return a copy of this type of hypergraph.
- abstract drop_hyperedges(drop_rate: float, ord='uniform')[source]
Randomly drop hyperedges from the hypergraph. This function will return a new hypergraph with non-dropped hyperedges.
- Parameters:
drop_rate (
float
) – The drop rate of hyperedges.ord (
str
) – The order of dropping edges. Currently, only'uniform'
is supported. Defaults touniform
.
- abstract drop_hyperedges_of_group(group_name: str, drop_rate: float, ord='uniform')[source]
Randomly drop hyperedges from the specified hyperedge group. This function will return a new hypergraph with non-dropped hyperedges.
- Parameters:
group_name (
str
) – The name of the hyperedge group.drop_rate (
float
) – The drop rate of hyperedges.ord (
str
) – The order of dropping edges. Currently, only'uniform'
is supported. Defaults touniform
.
- abstract property e: Tuple[List[List[int]], List[float]]
Return all hyperedges and weights in the hypergraph.
- abstract e2v(X: Tensor, aggr: str = 'mean', e2v_weight: Tensor | None = None, v_weight: Tensor | None = None)[source]
Message passing of
hyperedges to vertices
. The combination ofe2v_aggregation
ande2v_update
.- Parameters:
X (
torch.Tensor
) – Hyperedge feature matrix. Size \((|\mathcal{E}|, C)\).aggr (
str
) – The aggregation method. Can be'mean'
,'sum'
and'softmax_then_sum'
.e2v_weight (
torch.Tensor
, optional) – The weight vector attached to connections (hyperedges point to vertices). If not specified, the function will use the weights specified in hypergraph construction. Defaults toNone
.v_weight (
torch.Tensor
, optional) – The vertex weight vector. If not specified, the function will use the weights specified in hypergraph construction. Defaults toNone
.
- abstract e2v_aggregation(X: Tensor, aggr: str = 'mean', e2v_weight: Tensor | None = None)[source]
Message aggregation step of
hyperedges to vertices
.- Parameters:
X (
torch.Tensor
) – Hyperedge feature matrix. Size \((|\mathcal{E}|, C)\).aggr (
str
) – The aggregation method. Can be'mean'
,'sum'
and'softmax_then_sum'
.e2v_weight (
torch.Tensor
, optional) – The weight vector attached to connections (hyperedges point to vertices). If not specified, the function will use the weights specified in hypergraph construction. Defaults toNone
.
- abstract e2v_aggregation_of_group(group_name: str, X: Tensor, aggr: str = 'mean', e2v_weight: Tensor | None = None)[source]
Message aggregation step of
hyperedges to vertices
in specified hyperedge group.- Parameters:
group_name (
str
) – The specified hyperedge group.X (
torch.Tensor
) – Hyperedge feature matrix. Size \((|\mathcal{E}|, C)\).aggr (
str
) – The aggregation method. Can be'mean'
,'sum'
and'softmax_then_sum'
.e2v_weight (
torch.Tensor
, optional) – The weight vector attached to connections (hyperedges point to vertices). If not specified, the function will use the weights specified in hypergraph construction. Defaults toNone
.
- abstract e2v_of_group(group_name: str, X: Tensor, aggr: str = 'mean', e2v_weight: Tensor | None = None, v_weight: Tensor | None = None)[source]
Message passing of
hyperedges to vertices
in specified hyperedge group. The combination ofe2v_aggregation_of_group
ande2v_update_of_group
.- Parameters:
group_name (
str
) – The specified hyperedge group.X (
torch.Tensor
) – Hyperedge feature matrix. Size \((|\mathcal{E}|, C)\).aggr (
str
) – The aggregation method. Can be'mean'
,'sum'
and'softmax_then_sum'
.e2v_weight (
torch.Tensor
, optional) – The weight vector attached to connections (hyperedges point to vertices). If not specified, the function will use the weights specified in hypergraph construction. Defaults toNone
.v_weight (
torch.Tensor
, optional) – The vertex weight vector. If not specified, the function will use the weights specified in hypergraph construction. Defaults toNone
.
- abstract e2v_update(X: Tensor, v_weight: Tensor | None = None)[source]
Message update step of
hyperedges to vertices
.- Parameters:
X (
torch.Tensor
) – Vertex feature matrix. Size \((|\mathcal{V}|, C)\).v_weight (
torch.Tensor
, optional) – The vertex weight vector. If not specified, the function will use the weights specified in hypergraph construction. Defaults toNone
.
- abstract e2v_update_of_group(group_name: str, X: Tensor, v_weight: Tensor | None = None)[source]
Message update step of
hyperedges to vertices
in specified hyperedge group.- Parameters:
group_name (
str
) – The specified hyperedge group.X (
torch.Tensor
) – Vertex feature matrix. Size \((|\mathcal{V}|, C)\).v_weight (
torch.Tensor
, optional) – The vertex weight vector. If not specified, the function will use the weights specified in hypergraph construction. Defaults toNone
.
- abstract e_of_group(group_name: str) Tuple[List[List[int]], List[float]] [source]
Return all hyperedges and weights in the specified hyperedge group.
- Parameters:
group_name (
str
) – The name of the specified hyperedge group.
- abstract static from_state_dict(state_dict: dict)[source]
Load the DHG’s hypergraph structure from the state dict.
- Parameters:
state_dict (
dict
) – The state dict to load the DHG’s hypergraph.
- property group_names: List[str]
Return the names of hyperedge groups in the hypergraph.
- abstract static load(file_path: str | Path)[source]
Load the DHG’s hypergraph structure from a file.
- Parameters:
file_path (
str
) – The file path to load the DHG’s hypergraph structure.
- property num_e: int
Return the number of hyperedges in the hypergraph.
- num_e_of_group(group_name: str) int [source]
Return the number of hyperedges in the specified hyperedge group.
- Parameters:
group_name (
str
) – The name of the specified hyperedge group.
- property num_groups: int
Return the number of hyperedge groups in the hypergraph.
- property num_v: int
Return the number of vertices in the hypergraph.
- remove_hyperedges(e_list_v2e: List[int] | List[List[int]], e_list_e2v: List[int] | List[List[int]], group_name: str | None = None)[source]
Remove the specified hyperedges from the hypergraph.
- Parameters:
e_list_v2e (
Union[List[int], List[List[int]]]
) – A list of hyperedges describes how the vertices point to the hyperedges.e_list_e2v (
Union[List[int], List[List[int]]]
) – A list of hyperedges describes how the hyperedges point to the vertices.group_name (
str
, optional) – Remove these hyperedges from the specified hyperedge group. If not specified, the function will remove those hyperedges from all hyperedge groups. Defaults to theNone
.
- abstract save(file_path: str | Path)[source]
Save the DHG’s hypergraph structure to a file.
- Parameters:
file_path (
str
) – The file_path to store the DHG’s hypergraph structure.
- smoothing(X: Tensor, L: Tensor, lamb: float) Tensor [source]
Spectral-based smoothing.
\[X_{smoothed} = X + \lambda \mathcal{L} X\]- Parameters:
X (
torch.Tensor
) – The vertex feature matrix. Size \((|\mathcal{V}|, C)\).L (
torch.Tensor
) – The Laplacian matrix withtorch.sparse_coo_tensor
format. Size \((|\mathcal{V}|, |\mathcal{V}|)\).lamb (
float
) – \(\lambda\), the strength of smoothing.
- abstract property state_dict: Dict[str, Any]
Get the state dict of the hypergraph.
- to(device: device)[source]
Move the hypergraph to the specified device.
- Parameters:
device (
torch.device
) – The device to store the hypergraph.
- property v: List[int]
Return the list of vertices.
- abstract v2e(X: Tensor, aggr: str = 'mean', v2e_weight: Tensor | None = None, e_weight: Tensor | None = None)[source]
Message passing of
vertices to hyperedges
. The combination ofv2e_aggregation
andv2e_update
.- Parameters:
X (
torch.Tensor
) – Vertex feature matrix. Size \((|\mathcal{V}|, C)\).aggr (
str
) – The aggregation method. Can be'mean'
,'sum'
and'softmax_then_sum'
.v2e_weight (
torch.Tensor
, optional) – The weight vector attached to connections (vertices point to hyepredges). If not specified, the function will use the weights specified in hypergraph construction. Defaults toNone
.e_weight (
torch.Tensor
, optional) – The hyperedge weight vector. If not specified, the function will use the weights specified in hypergraph construction. Defaults toNone
.
- abstract v2e_aggregation(X: Tensor, aggr: str = 'mean', v2e_weight: Tensor | None = None, drop_rate: float = 0.0)[source]
Message aggretation step of
vertices to hyperedges
.- Parameters:
X (
torch.Tensor
) – Vertex feature matrix. Size \((|\mathcal{V}|, C)\).aggr (
str
) – The aggregation method. Can be'mean'
,'sum'
and'softmax_then_sum'
.v2e_weight (
torch.Tensor
, optional) – The weight vector attached to connections (vertices point to hyepredges). If not specified, the function will use the weights specified in hypergraph construction. Defaults toNone
.
- abstract v2e_aggregation_of_group(group_name: str, X: Tensor, aggr: str = 'mean', v2e_weight: Tensor | None = None, drop_rate: float = 0.0)[source]
Message aggregation step of
vertices to hyperedges
in specified hyperedge group.- Parameters:
group_name (
str
) – The specified hyperedge group.X (
torch.Tensor
) – Vertex feature matrix. Size \((|\mathcal{V}|, C)\).aggr (
str
) – The aggregation method. Can be'mean'
,'sum'
and'softmax_then_sum'
.v2e_weight (
torch.Tensor
, optional) – The weight vector attached to connections (vertices point to hyepredges). If not specified, the function will use the weights specified in hypergraph construction. Defaults toNone
.
- abstract v2e_of_group(group_name: str, X: Tensor, aggr: str = 'mean', v2e_weight: Tensor | None = None, e_weight: Tensor | None = None)[source]
Message passing of
vertices to hyperedges
in specified hyperedge group. The combination ofe2v_aggregation_of_group
ande2v_update_of_group
.- Parameters:
group_name (
str
) – The specified hyperedge group.X (
torch.Tensor
) – Vertex feature matrix. Size \((|\mathcal{V}|, C)\).aggr (
str
) – The aggregation method. Can be'mean'
,'sum'
and'softmax_then_sum'
.v2e_weight (
torch.Tensor
, optional) – The weight vector attached to connections (vertices point to hyepredges). If not specified, the function will use the weights specified in hypergraph construction. Defaults toNone
.e_weight (
torch.Tensor
, optional) – The hyperedge weight vector. If not specified, the function will use the weights specified in hypergraph construction. Defaults toNone
.
- abstract v2e_update(X: Tensor, e_weight: Tensor | None = None)[source]
Message update step of
vertices to hyperedges
.- Parameters:
X (
torch.Tensor
) – Hyperedge feature matrix. Size \((|\mathcal{E}|, C)\).e_weight (
torch.Tensor
, optional) – The hyperedge weight vector. If not specified, the function will use the weights specified in hypergraph construction. Defaults toNone
.
- abstract v2e_update_of_group(group_name: str, X: Tensor, e_weight: Tensor | None = None)[source]
Message update step of
vertices to hyperedges
in specified hyperedge group.- Parameters:
group_name (
str
) – The specified hyperedge group.X (
torch.Tensor
) – Hyperedge feature matrix. Size \((|\mathcal{E}|, C)\).e_weight (
torch.Tensor
, optional) – The hyperedge weight vector. If not specified, the function will use the weights specified in hypergraph construction. Defaults toNone
.
- abstract v2v(X: Tensor, aggr: str = 'mean', v2e_aggr: str | None = None, v2e_weight: Tensor | None = None, e_weight: Tensor | None = None, e2v_aggr: str | None = None, e2v_weight: Tensor | None = None, v_weight: Tensor | None = None)[source]
Message passing of
vertices to vertices
. The combination ofv2e
ande2v
.- Parameters:
X (
torch.Tensor
) – Vertex feature matrix. Size \((|\mathcal{V}|, C)\).aggr (
str
) – The aggregation method. Can be'mean'
,'sum'
and'softmax_then_sum'
. If specified, thisaggr
will be used to bothv2e
ande2v
.v2e_aggr (
str
, optional) – The aggregation method for hyperedges to vertices. Can be'mean'
,'sum'
and'softmax_then_sum'
. If specified, it will override theaggr
ine2v
.v2e_weight (
torch.Tensor
, optional) – The weight vector attached to connections (vertices point to hyepredges). If not specified, the function will use the weights specified in hypergraph construction. Defaults toNone
.e_weight (
torch.Tensor
, optional) – The hyperedge weight vector. If not specified, the function will use the weights specified in hypergraph construction. Defaults toNone
.e2v_aggr (
str
, optional) – The aggregation method for vertices to hyperedges. Can be'mean'
,'sum'
and'softmax_then_sum'
. If specified, it will override theaggr
inv2e
.e2v_weight (
torch.Tensor
, optional) – The weight vector attached to connections (hyperedges point to vertices). If not specified, the function will use the weights specified in hypergraph construction. Defaults toNone
.v_weight (
torch.Tensor
, optional) – The vertex weight vector. If not specified, the function will use the weights specified in hypergraph construction. Defaults toNone
.
- abstract v2v_of_group(group_name: str, X: Tensor, aggr: str = 'mean', v2e_aggr: str | None = None, v2e_weight: Tensor | None = None, e_weight: Tensor | None = None, e2v_aggr: str | None = None, e2v_weight: Tensor | None = None, v_weight: Tensor | None = None)[source]
Message passing of
vertices to vertices
in specified hyperedge group. The combination ofv2e_of_group
ande2v_of_group
.- Parameters:
group_name (
str
) – The specified hyperedge group.X (
torch.Tensor
) – Vertex feature matrix. Size \((|\mathcal{V}|, C)\).aggr (
str
) – The aggregation method. Can be'mean'
,'sum'
and'softmax_then_sum'
. If specified, thisaggr
will be used to bothv2e_of_group
ande2v_of_group
.v2e_aggr (
str
, optional) – The aggregation method for hyperedges to vertices. Can be'mean'
,'sum'
and'softmax_then_sum'
. If specified, it will override theaggr
ine2v_of_group
.v2e_weight (
torch.Tensor
, optional) – The weight vector attached to connections (vertices point to hyepredges). If not specified, the function will use the weights specified in hypergraph construction. Defaults toNone
.e_weight (
torch.Tensor
, optional) – The hyperedge weight vector. If not specified, the function will use the weights specified in hypergraph construction. Defaults toNone
.e2v_aggr (
str
, optional) – The aggregation method for vertices to hyperedges. Can be'mean'
,'sum'
and'softmax_then_sum'
. If specified, it will override theaggr
inv2e_of_group
.e2v_weight (
torch.Tensor
, optional) – The weight vector attached to connections (hyperedges point to vertices). If not specified, the function will use the weights specified in hypergraph construction. Defaults toNone
.v_weight (
torch.Tensor
, optional) – The vertex weight vector. If not specified, the function will use the weights specified in hypergraph construction. Defaults toNone
.
- property v_weight: List[float]
Return the vertex weights of the hypergraph.
- abstract property vars_for_DL: List[str]
Return a name list of available variables for deep learning in this type of hypergraph.
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.Graph()
Create a deep copy graph G2 from existing Graph G1.
>>> G2 = G1.copy()
Create an graph with attributes.
>>> G = eg.Graph(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
- 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
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
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
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
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
- property adj
- 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()
- 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
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
- 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
- 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
Examples
>>> G.in_degree(weight='weight')
- 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, aEasyGraphError
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 nodes
- 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
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.
Examples
>>> G.out_degree(weight='weight')
- property pred
- 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
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
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
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
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()
easygraph.classes.directed_multigraph module
- class easygraph.classes.directed_multigraph.MultiDiGraph(incoming_graph_data=None, multigraph_input=None, **attr)[source]
Bases:
MultiGraph
,DiGraph
- add_edge(u_for_edge, v_for_edge, key=None, **attr)[source]
Add an edge between u and v.
The nodes u and v will be automatically added if they are not already in the graph.
Edge attributes can be specified with keywords or by directly accessing the edge’s attribute dictionary. See examples below.
- Parameters:
u_for_edge (nodes) – Nodes can be, for example, strings or numbers. Nodes must be hashable (and not None) Python objects.
v_for_edge (nodes) – Nodes can be, for example, strings or numbers. Nodes must be hashable (and not None) Python objects.
key (hashable identifier, optional (default=lowest unused integer)) – Used to distinguish multiedges between a pair of nodes.
attr (keyword arguments, optional) – Edge data (or labels or objects) can be assigned using keyword arguments.
- Return type:
The edge key assigned to the edge.
See also
add_edges_from
add a collection of edges
Notes
To replace/update edge data, use the optional key argument to identify a unique edge. Otherwise a new edge will be created.
EasyGraph algorithms designed for weighted graphs cannot use multigraphs directly because it is not clear how to handle multiedge weights. Convert to Graph using edge attribute ‘weight’ to enable weighted graph algorithms.
Default keys are generated using the method new_edge_key(). This method can be overridden by subclassing the base class and providing a custom new_edge_key() method.
Examples
The following all add the edge e=(1, 2) to graph G:
>>> G = eg.MultiDiGraph() >>> e = (1, 2) >>> key = G.add_edge(1, 2) # explicit two-node form >>> G.add_edge(*e) # single edge as tuple of two nodes 1 >>> G.add_edges_from([(1, 2)]) # add edges from iterable container [2]
Associate data to edges using keywords:
>>> key = G.add_edge(1, 2, weight=3) >>> key = G.add_edge(1, 2, key=0, weight=4) # update data for key=0 >>> key = G.add_edge(1, 3, weight=7, capacity=15, length=342.7)
For non-string attribute keys, use subscript notation.
>>> ekey = G.add_edge(1, 2) >>> G[1][2][0].update({0: 5}) >>> G.edges[1, 2, 0].update({0: 5})
- property degree
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
Examples
>>> G.degree() >>> G.degree(weight='weight')
or you can customize the weight key
>>> G.degree(weight='weight_1')
- edge_key_dict_factory
alias of
dict
- property edges
- property in_degree
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
Examples
>>> G.in_degree(weight='weight')
- property in_edges
- property out_degree
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.
Examples
>>> G.out_degree(weight='weight')
- property out_edges
- remove_edge(u, v, key=None)[source]
Remove an edge between u and v.
- Parameters:
u (nodes) – Remove an edge between nodes u and v.
v (nodes) – Remove an edge between nodes u and v.
key (hashable identifier, optional (default=None)) – Used to distinguish multiple edges between a pair of nodes. If None remove a single (arbitrary) edge between u and v.
- Raises:
EasyGraphError – If there is not an edge between u and v, or if there is no edge with the specified key.
See also
remove_edges_from
remove a collection of edges
Examples
>>> G = eg.MultiDiGraph() >>> G.add_edges_from([(1, 2), (1, 2), (1, 2)]) # key_list returned [0, 1, 2] >>> G.remove_edge(1, 2) # remove a single (arbitrary) edge
For edges with keys
>>> G = eg.MultiDiGraph() >>> G.add_edge(1, 2, key="first") 'first' >>> G.add_edge(1, 2, key="second") 'second' >>> G.remove_edge(1, 2, key="second")
- reverse(copy=True)[source]
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:
copy (bool 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(reciprocal=False)[source]
Returns an undirected representation of the multidigraph.
- Parameters:
reciprocal (bool (optional)) – If True only keep edges that appear in both directions in the original digraph.
- Returns:
G – An undirected graph with the same name and nodes and with edge (u, v, data) if either (u, v, data) or (v, u, data) is in the digraph. If both edges exist in digraph and their edge data is different, only one edge is created with an arbitrary choice of which edge data to use. You must check and correct for this manually if desired.
- Return type:
See also
MultiGraph
,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 D=MultiDiGraph(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 MultiDiGraph to use dict-like objects in the data structure, those changes do not transfer to the MultiGraph created by this method.
Examples
>>> G = eg.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)]
easygraph.classes.graph module
- class easygraph.classes.graph.Graph(incoming_graph_data=None, extra_selfloop=False, **graph_attr)[source]
Bases:
object
Base class for undirected 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
DiGraph
Examples
Create an empty undirected graph with no nodes and edges.
>>> G = eg.Graph()
Create a deep copy graph G2 from existing Graph G1.
>>> G2 = G1.copy()
Create an graph with attributes.
>>> G = eg.Graph(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
- property A
- property D_v
- property D_v_neg_1_2
- property L_GCN
Return the GCN Laplacian matrix \(\mathcal{L}_{GCN}\) of the graph with
torch.sparse_coo_tensor
format. Size \((|\mathcal{V}|, |\mathcal{V}|)\).\[\mathcal{L}_{GCN} = \mathbf{\hat{D}}_v^{-\frac{1}{2}} \mathbf{\hat{A}} \mathbf{\hat{D}}_v^{-\frac{1}{2}}\]
- N_v(v_idx: int) Tuple[List[int], List[float]] [source]
Return the neighbors of the vertex
v_idx
withtorch.Tensor
format.- Parameters:
v_idx (
int
) – The index of the vertex.
- add_edge(u_of_edge, v_of_edge, **edge_attr)[source]
Add one edge.
- Parameters:
u_of_edge (object) – One end of this edge
v_of_edge (object) – The other one 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
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 two ends of the edge.
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
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
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
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_edges_from(ebunch_to_add, weight='weight', **attr)[source]
Add weighted edges in ebunch_to_add with specified weight attr
- Parameters:
ebunch_to_add (container of edges) – Each edge given in the list or container will be added to the graph. The edges must be given as 3-tuples (u, v, w) where w is a number.
weight (string, optional (default= 'weight')) – The attribute name for the edge weights to be added.
attr (keyword arguments, optional (default= no attributes)) – Edge attributes to add/update for all edges.
See also
add_edge
add a single edge
add_edges_from
add multiple edges
Notes
Adding the same edge twice for Graph/DiGraph simply updates the edge data. For MultiGraph/MultiDiGraph, duplicate edges are stored.
Examples
>>> G = eg.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.add_weighted_edges_from([(0, 1, 3.0), (1, 2, 7.5)])
- property adj
- 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.
- Parameters:
node (Hashable) – The target node.
- Returns:
neighbors – An iterator of a node’s neighbors.
- 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)
- copy()[source]
Return a deep copy of the graph.
- Returns:
copy – A deep copy of the original graph.
- Return type:
easygraph.Graph
Examples
G2 is a deep copy of G1
>>> G2 = G1.copy()
- degree(weight='weight')[source]
Returns the weighted degree of of each node.
- Parameters:
weight (string, optional (default: 'weight')) – Weight key of the original weighted graph.
- Returns:
degree – Each node’s (key) weighted degree (value).
- Return type:
dict
Notes
If the graph is not weighted, all the weights will be regarded as 1.
Examples
You can call with no attributes, if ‘weight’ is the weight key:
>>> G.degree()
if you have customized weight key ‘weight_1’.
>>> G.degree(weight='weight_1')
- property e: Tuple[List[List[int]], List[float]]
Return the edge list and weight list in the graph.
- property e_both_side: Tuple[List[List], List[float]]
- edge_attr_dict_factory
alias of
dict
- property edges
- 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')
- static from_hypergraph_hypergcn(hypergraph, feature, with_mediator=False, remove_selfloop=True)[source]
- gnn_data_dict_factory
alias of
dict
- graph_attr_dict_factory
alias of
dict
- 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.
- nbr_v(v_idx: int) Tuple[List[int], List[float]] [source]
Return a vertex list of the neighbors of the vertex
v_idx
.- Parameters:
v_idx (
int
) – The index of the vertex.
- 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, aEasyGraphError
is raised.
- property ndata
- neighbors(node)[source]
Returns an iterator of a node’s neighbors.
- Parameters:
node (Hashable) – The target node.
- Returns:
neighbors – An iterator of a node’s neighbors.
- 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)
- property node2index
- node_attr_dict_factory
alias of
dict
- node_dict_factory
alias of
dict
- property node_index
- node_index_dict
alias of
dict
- property nodes
- 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
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
- order()[source]
Returns the number of nodes in the graph.
- Returns:
nnodes – The number of nodes in the graph.
- Return type:
int
See also
number_of_nodes
identical method
__len__
identical method
Examples
>>> G = eg.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.order() 3
- raw_selfloop_dict
alias of
dict
- remove_edge(u, v)[source]
Remove one edge from your graph.
- Parameters:
u (object) – One end of the edge.
v (object) – The other end of the edge.
See also
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 two ends of the edge.
See also
Examples
Remove the edges (‘Jack’, ‘Mary’) amd (‘Mary’, ‘Tom’) from G
>>> G.remove_edge([ ... ('Jack', 'Mary'), ... ('Mary', 'Tom') ... ])
- 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
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
Examples
Remove node [1, 2, ‘a’, ‘b’] from G
>>> G.remove_nodes([1, 2, 'a', 'b'])
- remove_nodes_from(nodes)[source]
Remove multiple nodes.
- Parameters:
nodes (iterable 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
Examples
>>> G = eg.path_graph(3) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> e = list(G.nodes) >>> e [0, 1, 2] >>> G.remove_nodes_from(e) >>> list(G.nodes) []
- 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')
- smoothing_with_GCN(X, drop_rate=0.0)[source]
Return the smoothed feature matrix with GCN Laplacian matrix \(\mathcal{L}_{GCN}\).
- Parameters:
X (
torch.Tensor
) – Vertex feature matrix. Size \((|\mathcal{V}|, C)\).drop_rate (
float
) – Dropout rate. Randomly dropout the connections in adjacency matrix with probabilitydrop_rate
. Default:0.0
.
- to_directed()[source]
Returns a directed representation of the graph.
- Returns:
G – 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).
- Return type:
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 = eg.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 = eg.DiGraph() # or MultiDiGraph, etc >>> G.add_edge(0, 1) >>> H = G.to_directed() >>> list(H.edges) [(0, 1)]
- to_directed_class()[source]
Returns the class to use for empty directed copies.
If you subclass the base classes, use this to designate what directed class to use for to_directed() copies.
- 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()
easygraph.classes.graphviews module
easygraph.classes.hypergraph module
- class easygraph.classes.hypergraph.Hypergraph(num_v: int, e_list: List[int] | List[List[int]] | None = None, e_weight: float | List[float] | None = None, merge_op: str = 'mean', device: device = device(type='cpu'))[source]
Bases:
BaseHypergraph
The
Hypergraph
class is developed for hypergraph structures.- Parameters:
num_v (
int
) – The number of vertices in the hypergraph.e_list (
Union[List[int], List[List[int]]]
, optional) – A list of hyperedges describes how the vertices point to the hyperedges. Defaults toNone
.e_weight (
Union[float, List[float]]
, optional) – A list of weights for hyperedges. If set toNone
, the value1
is used for all hyperedges. Defaults toNone
.merge_op (
str
) – The operation to merge those conflicting hyperedges in the same hyperedge group, which can be'mean'
,'sum'
or'max'
. Defaults to'mean'
.device (
torch.device
, optional) – The device to store the hypergraph. Defaults totorch.device('cpu')
.
- property D_e: Tensor
Return the hyperedge degree matrix \(\mathbf{D}_e\) with
torch.sparse_coo_tensor
format.
- property D_e_neg_1: Tensor
Return the hyperedge degree matrix \(\mathbf{D}_e^{-1}\) with
torch.sparse_coo_tensor
format.
- D_e_neg_1_of_group(group_name: str) Tensor [source]
Return the hyperedge degree matrix \(\mathbf{D}_e^{-1}\) of the specified hyperedge group with
torch.sparse_coo_tensor
format.- Parameters:
group_name (
str
) – The name of the specified hyperedge group.
- D_e_of_group(group_name: str) Tensor [source]
Return the hyperedge degree matrix \(\mathbf{D}_e\) of the specified hyperedge group with
torch.sparse_coo_tensor
format.- Parameters:
group_name (
str
) – The name of the specified hyperedge group.
- property D_v: Tensor
Return the vertex degree matrix \(\mathbf{D}_v\) with
torch.sparse_coo_tensor
format.
- property D_v_neg_1: Tensor
Return the vertex degree matrix \(\mathbf{D}_v^{-1}\) with
torch.sparse_coo_tensor
format.
- property D_v_neg_1_2: Tensor
Return the vertex degree matrix \(\mathbf{D}_v^{-\frac{1}{2}}\) with
torch.sparse_coo_tensor
format.
- D_v_neg_1_2_of_group(group_name: str) Tensor [source]
Return the vertex degree matrix \(\mathbf{D}_v^{-\frac{1}{2}}\) of the specified hyperedge group with
torch.sparse_coo_tensor
format.- Parameters:
group_name (
str
) – The name of the specified hyperedge group.
- D_v_neg_1_of_group(group_name: str) Tensor [source]
Return the vertex degree matrix \(\mathbf{D}_v^{-1}\) of the specified hyperedge group with
torch.sparse_coo_tensor
format.- Parameters:
group_name (
str
) – The name of the specified hyperedge group.
- D_v_of_group(group_name: str) Tensor [source]
Return the vertex degree matrix \(\mathbf{D}_v\) of the specified hyperedge group with
torch.sparse_coo_tensor
format.- Parameters:
group_name (
str
) – The name of the specified hyperedge group.
- property H: Tensor
Return the hypergraph incidence matrix \(\mathbf{H}\) with
torch.Tensor
format.
- property H_T: Tensor
Return the transpose of the hypergraph incidence matrix \(\mathbf{H}^\top\) with
torch.Tensor
format.
- H_T_of_group(group_name: str) Tensor [source]
Return the transpose of the hypergraph incidence matrix \(\mathbf{H}^\top\) of the specified hyperedge group with
torch.Tensor
format.- Parameters:
group_name (
str
) – The name of the specified hyperedge group.
- H_of_group(group_name: str) Tensor [source]
Return the hypergraph incidence matrix \(\mathbf{H}\) of the specified hyperedge group with
torch.Tensor
format.- Parameters:
group_name (
str
) – The name of the specified hyperedge group.
- property L_HGNN: Tensor
Return the HGNN Laplacian matrix \(\mathcal{L}_{HGNN}\) of the hypergraph with
torch.sparse_coo_tensor
format.\[\mathcal{L}_{HGNN} = \mathbf{D}_v^{-\frac{1}{2}} \mathbf{H} \mathbf{W}_e \mathbf{D}_e^{-1} \mathbf{H}^\top \mathbf{D}_v^{-\frac{1}{2}}\]
- L_HGNN_of_group(group_name: str) Tensor [source]
Return the HGNN Laplacian matrix \(\mathcal{L}_{HGNN}\) of the specified hyperedge group with
torch.sparse_coo_tensor
format.\[\mathcal{L}_{HGNN} = \mathbf{D}_v^{-\frac{1}{2}} \mathbf{H} \mathbf{W}_e \mathbf{D}_e^{-1} \mathbf{H}^\top \mathbf{D}_v^{-\frac{1}{2}}\]- Parameters:
group_name (
str
) – The name of the specified hyperedge group.
- property L_rw: Tensor
Return the random walk Laplacian matrix \(\mathcal{L}_{rw}\) of the hypergraph with
torch.sparse_coo_tensor
format.\[\mathcal{L}_{rw} = \mathbf{I} - \mathbf{D}_v^{-1} \mathbf{H} \mathbf{W}_e \mathbf{D}_e^{-1} \mathbf{H}^\top\]
- L_rw_of_group(group_name: str) Tensor [source]
Return the random walk Laplacian matrix \(\mathcal{L}_{rw}\) of the specified hyperedge group with
torch.sparse_coo_tensor
format.\[\mathcal{L}_{rw} = \mathbf{I} - \mathbf{D}_v^{-1} \mathbf{H} \mathbf{W}_e \mathbf{D}_e^{-1} \mathbf{H}^\top\]- Parameters:
group_name (
str
) – The name of the specified hyperedge group.
- property L_sym: Tensor
Return the symmetric Laplacian matrix \(\mathcal{L}_{sym}\) of the hypergraph with
torch.sparse_coo_tensor
format.\[\mathcal{L}_{sym} = \mathbf{I} - \mathbf{D}_v^{-\frac{1}{2}} \mathbf{H} \mathbf{W}_e \mathbf{D}_e^{-1} \mathbf{H}^\top \mathbf{D}_v^{-\frac{1}{2}}\]
- L_sym_of_group(group_name: str) Tensor [source]
Return the symmetric Laplacian matrix \(\mathcal{L}_{sym}\) of the specified hyperedge group with
torch.sparse_coo_tensor
format.\[\mathcal{L}_{sym} = \mathbf{I} - \mathbf{D}_v^{-\frac{1}{2}} \mathbf{H} \mathbf{W}_e \mathbf{D}_e^{-1} \mathbf{H}^\top \mathbf{D}_v^{-\frac{1}{2}}\]- Parameters:
group_name (
str
) – The name of the specified hyperedge group.
- N_e(v_idx: int) Tensor [source]
Return the neighbor hyperedges of the specified vertex with
torch.Tensor
format.Note
The
v_idx
must be in the range of [0,num_v
).- Parameters:
v_idx (
int
) – The index of the vertex.
- N_e_of_group(v_idx: int, group_name: str) Tensor [source]
Return the neighbor hyperedges of the specified vertex of the specified hyperedge group with
torch.Tensor
format.Note
The
v_idx
must be in the range of [0,num_v
).- Parameters:
v_idx (
int
) – The index of the vertex.group_name (
str
) – The name of the specified hyperedge group.
- N_v(e_idx: int) Tensor [source]
Return the neighbor vertices of the specified hyperedge with
torch.Tensor
format.Note
The
e_idx
must be in the range of [0,num_e
).- Parameters:
e_idx (
int
) – The index of the hyperedge.
- N_v_of_group(e_idx: int, group_name: str) Tensor [source]
Return the neighbor vertices of the specified hyperedge of the specified hyperedge group with
torch.Tensor
format.Note
The
e_idx
must be in the range of [0,num_e_of_group()
).- Parameters:
e_idx (
int
) – The index of the hyperedge.group_name (
str
) – The name of the specified hyperedge group.
- property W_e: Tensor
Return the weight matrix \(\mathbf{W}_e\) of hyperedges with
torch.Tensor
format.
- W_e_of_group(group_name: str) Tensor [source]
Return the weight matrix \(\mathbf{W}_e\) of hyperedges of the specified hyperedge group with
torch.Tensor
format.- Parameters:
group_name (
str
) – The name of the specified hyperedge group.
- add_hyperedges(e_list: List[int] | List[List[int]], e_weight: float | List[float] | None = None, merge_op: str = 'mean', group_name: str = 'main')[source]
Add hyperedges to the hypergraph. If the
group_name
is not specified, the hyperedges will be added to the defaultmain
hyperedge group.- Parameters:
num_v (
int
) – The number of vertices in the hypergraph.e_list (
Union[List[int], List[List[int]]]
) – A list of hyperedges describes how the vertices point to the hyperedges.e_weight (
Union[float, List[float]]
, optional) – A list of weights for hyperedges. If set toNone
, the value1
is used for all hyperedges. Defaults toNone
.merge_op (
str
) – The merge operation for the conflicting hyperedges. The possible values are"mean"
,"sum"
, and"max"
. Defaults to"mean"
.group_name (
str
, optional) – The target hyperedge group to add these hyperedges. Defaults to themain
hyperedge group.
- add_hyperedges_from_feature_kNN(feature: Tensor, k: int, group_name: str = 'main')[source]
Add hyperedges from the feature matrix by k-NN. Each hyperedge is constructed by the central vertex and its \(k\)-Nearest Neighbor vertices.
- Parameters:
features (
torch.Tensor
) – The feature matrix.k (
int
) – The number of nearest neighbors.group_name (
str
, optional) – The target hyperedge group to add these hyperedges. Defaults to themain
hyperedge group.
- add_hyperedges_from_graph(graph, group_name: str = 'main')[source]
Add hyperedges from edges in the graph. Each edge in the graph is treated as a hyperedge.
- Parameters:
graph (
eg.Graph
) – The graph to join the hypergraph.group_name (
str
, optional) – The target hyperedge group to add these hyperedges. Defaults to themain
hyperedge group.
- add_hyperedges_from_graph_kHop(graph, k: int, only_kHop: bool = False, group_name: str = 'main')[source]
Add hyperedges from vertices and its k-Hop neighbors in the graph. Each hyperedge in the hypergraph is constructed by the central vertex and its \(k\)-Hop neighbor vertices.
Note
If the graph have \(|\mathcal{V}|\) vertices, the constructed hypergraph will have \(|\mathcal{V}|\) vertices and equal to or less than \(|\mathcal{V}|\) hyperedges.
- Parameters:
graph (
eg.Graph
) – The graph to join the hypergraph.k (
int
) – The number of hop neighbors.only_kHop (
bool
) – If set toTrue
, only the central vertex and its \(k\)-th Hop neighbors are used to construct the hyperedges. By default, the constructed hyperedge will include the central vertex and its [ \(1\)-th, \(2\)-th, \(\cdots\), \(k\)-th ] Hop neighbors. Defaults toFalse
.group_name (
str
, optional) – The target hyperedge group to add these hyperedges. Defaults to themain
hyperedge group.
- clone() Hypergraph [source]
Return a copy of the hypergraph.
- property deg_e: List[int]
Return the degree list of each hyperedge.
- deg_e_of_group(group_name: str) List[int] [source]
Return the degree list of each hyperedge of the specified hyperedge group.
- Parameters:
group_name (
str
) – The name of the specified hyperedge group.
- property deg_v: List[int]
Return the degree list of each vertex.
- deg_v_of_group(group_name: str) List[int] [source]
Return the degree list of each vertex of the specified hyperedge group.
- Parameters:
group_name (
str
) – The name of the specified hyperedge group.
- draw(e_style: str = 'circle', v_label: List[str] | None = None, v_size: float | list = 1.0, v_color: str | list = 'r', v_line_width: str | list = 1.0, e_color: str | list = 'gray', e_fill_color: str | list = 'whitesmoke', e_line_width: str | list = 1.0, font_size: float = 1.0, font_family: str = 'sans-serif', push_v_strength: float = 1.0, push_e_strength: float = 1.0, pull_e_strength: float = 1.0, pull_center_strength: float = 1.0)[source]
Draw the hypergraph structure.
- Parameters:
e_style (
str
) – The style of hyperedges. The available styles are only'circle'
. Defaults to'circle'
.v_label (
list
) – The labels of vertices. Defaults toNone
.v_size (
float
orlist
) – The size of vertices. Defaults to1.0
.v_color (
str
orlist
) – The color of vertices. Defaults to'r'
.v_line_width (
float
orlist
) – The line width of vertices. Defaults to1.0
.e_color (
str
orlist
) –The color of hyperedges. Defaults to
'gray'
.e_fill_color (
str
orlist
) –The fill color of hyperedges. Defaults to
'whitesmoke'
.e_line_width (
float
orlist
) – The line width of hyperedges. Defaults to1.0
.font_size (
float
) – The font size of labels. Defaults to1.0
.font_family (
str
) – The font family of labels. Defaults to'sans-serif'
.push_v_strength (
float
) – The strength of pushing vertices. Defaults to1.0
.push_e_strength (
float
) – The strength of pushing hyperedges. Defaults to1.0
.pull_e_strength (
float
) – The strength of pulling hyperedges. Defaults to1.0
.pull_center_strength (
float
) – The strength of pulling vertices to the center. Defaults to1.0
.
- drop_hyperedges(drop_rate: float, ord='uniform')[source]
Randomly drop hyperedges from the hypergraph. This function will return a new hypergraph with non-dropped hyperedges.
- Parameters:
drop_rate (
float
) – The drop rate of hyperedges.ord (
str
) – The order of dropping edges. Currently, only'uniform'
is supported. Defaults touniform
.
- drop_hyperedges_of_group(group_name: str, drop_rate: float, ord='uniform')[source]
Randomly drop hyperedges from the specified hyperedge group. This function will return a new hypergraph with non-dropped hyperedges.
- Parameters:
group_name (
str
) – The name of the hyperedge group.drop_rate (
float
) – The drop rate of hyperedges.ord (
str
) – The order of dropping edges. Currently, only'uniform'
is supported. Defaults touniform
.
- property e: Tuple[List[List[int]], List[float]]
Return all hyperedges and weights in the hypergraph.
- e2v(X: Tensor, aggr: str = 'mean', e2v_weight: Tensor | None = None, drop_rate: float = 0.0)[source]
Message passing of
hyperedges to vertices
. The combination ofe2v_aggregation
ande2v_update
.- Parameters:
X (
torch.Tensor
) – Hyperedge feature matrix. Size \((|\mathcal{E}|, C)\).aggr (
str
) – The aggregation method. Can be'mean'
,'sum'
and'softmax_then_sum'
.e2v_weight (
torch.Tensor
, optional) – The weight vector attached to connections (hyperedges point to vertices). If not specified, the function will use the weights specified in hypergraph construction. Defaults toNone
.drop_rate (
float
) – Dropout rate. Randomly dropout the connections in incidence matrix with probabilitydrop_rate
. Default:0.0
.
- e2v_aggregation(X: Tensor, aggr: str = 'mean', e2v_weight: Tensor | None = None, drop_rate: float = 0.0)[source]
Message aggregation step of
hyperedges to vertices
.- Parameters:
X (
torch.Tensor
) – Hyperedge feature matrix. Size \((|\mathcal{E}|, C)\).aggr (
str
) – The aggregation method. Can be'mean'
,'sum'
and'softmax_then_sum'
.e2v_weight (
torch.Tensor
, optional) – The weight vector attached to connections (hyperedges point to vertices). If not specified, the function will use the weights specified in hypergraph construction. Defaults toNone
.drop_rate (
float
) – Dropout rate. Randomly dropout the connections in incidence matrix with probabilitydrop_rate
. Default:0.0
.
- e2v_aggregation_of_group(group_name: str, X: Tensor, aggr: str = 'mean', e2v_weight: Tensor | None = None, drop_rate: float = 0.0)[source]
Message aggregation step of
hyperedges to vertices
in specified hyperedge group.- Parameters:
group_name (
str
) – The specified hyperedge group.X (
torch.Tensor
) – Hyperedge feature matrix. Size \((|\mathcal{E}|, C)\).aggr (
str
) – The aggregation method. Can be'mean'
,'sum'
and'softmax_then_sum'
.e2v_weight (
torch.Tensor
, optional) – The weight vector attached to connections (hyperedges point to vertices). If not specified, the function will use the weights specified in hypergraph construction. Defaults toNone
.drop_rate (
float
) – Dropout rate. Randomly dropout the connections in incidence matrix with probabilitydrop_rate
. Default:0.0
.
- property e2v_dst: Tensor
Return the destination vertex index vector \(\overrightarrow{e2v}_{dst}\) of the connections (hyperedges point to vertices) in the hypergraph.
- e2v_dst_of_group(group_name: str) Tensor [source]
Return the destination vertex index vector \(\overrightarrow{e2v}_{dst}\) of the connections (hyperedges point to vertices) in the specified hyperedge group.
- Parameters:
group_name (
str
) – The name of the specified hyperedge group.
- e2v_of_group(group_name: str, X: Tensor, aggr: str = 'mean', e2v_weight: Tensor | None = None, drop_rate: float = 0.0)[source]
Message passing of
hyperedges to vertices
in specified hyperedge group. The combination ofe2v_aggregation_of_group
ande2v_update_of_group
.- Parameters:
group_name (
str
) – The specified hyperedge group.X (
torch.Tensor
) – Hyperedge feature matrix. Size \((|\mathcal{E}|, C)\).aggr (
str
) – The aggregation method. Can be'mean'
,'sum'
and'softmax_then_sum'
.e2v_weight (
torch.Tensor
, optional) – The weight vector attached to connections (hyperedges point to vertices). If not specified, the function will use the weights specified in hypergraph construction. Defaults toNone
.drop_rate (
float
) – Dropout rate. Randomly dropout the connections in incidence matrix with probabilitydrop_rate
. Default:0.0
.
- property e2v_src: Tensor
Return the source hyperedge index vector \(\overrightarrow{e2v}_{src}\) of the connections (hyperedges point to vertices) in the hypergraph.
- e2v_src_of_group(group_name: str) Tensor [source]
Return the source hyperedge index vector \(\overrightarrow{e2v}_{src}\) of the connections (hyperedges point to vertices) in the specified hyperedge group.
- Parameters:
group_name (
str
) – The name of the specified hyperedge group.
- e2v_update(X: Tensor)[source]
Message update step of
hyperedges to vertices
.- Parameters:
X (
torch.Tensor
) – Vertex feature matrix. Size \((|\mathcal{V}|, C)\).
- e2v_update_of_group(group_name: str, X: Tensor)[source]
Message update step of
hyperedges to vertices
in specified hyperedge group.- Parameters:
group_name (
str
) – The specified hyperedge group.X (
torch.Tensor
) – Vertex feature matrix. Size \((|\mathcal{V}|, C)\).
- property e2v_weight: Tensor
Return the weight vector \(\overrightarrow{e2v}_{weight}\) of the connections (hyperedges point to vertices) in the hypergraph.
- e2v_weight_of_group(group_name: str) Tensor [source]
Return the weight vector \(\overrightarrow{e2v}_{weight}\) of the connections (hyperedges point to vertices) in the specified hyperedge group.
- Parameters:
group_name (
str
) – The name of the specified hyperedge group.
- e_of_group(group_name: str) Tuple[List[List[int]], List[float]] [source]
Return all hyperedges and weights of the specified hyperedge group.
- Parameters:
group_name (
str
) – The name of the specified hyperedge group.
- static from_feature_kNN(features: Tensor, k: int, device: device = device(type='cpu'))[source]
Construct the hypergraph from the feature matrix. Each hyperedge in the hypergraph is constructed by the central vertex ans its \(k-1\) neighbor vertices.
Note
The constructed hypergraph is a k-uniform hypergraph. If the feature matrix has the size \(N \times C\), the number of vertices and hyperedges of the constructed hypergraph are both \(N\).
- Parameters:
features (
torch.Tensor
) – The feature matrix.k (
int
) – The number of nearest neighbors.device (
torch.device
, optional) – The device to store the hypergraph. Defaults totorch.device('cpu')
.
- static from_graph(graph, device: device = device(type='cpu')) Hypergraph [source]
Construct the hypergraph from the graph. Each edge in the graph is treated as a hyperedge in the constructed hypergraph.
Note
The construsted hypergraph is a 2-uniform hypergraph, and has the same number of vertices and edges/hyperedges as the graph.
- Parameters:
graph (
eg.Graph
) – The graph to construct the hypergraph.device (
torch.device
, optional) – The device to store the hypergraph. Defaults totorch.device('cpu')
.
- static from_graph_kHop(graph, k: int, only_kHop: bool = False, device: device = device(type='cpu')) Hypergraph [source]
Construct the hypergraph from the graph by k-Hop neighbors. Each hyperedge in the hypergraph is constructed by the central vertex and its \(k\)-Hop neighbor vertices.
Note
If the graph have \(|\mathcal{V}|\) vertices, the constructed hypergraph will have \(|\mathcal{V}|\) vertices and equal to or less than \(|\mathcal{V}|\) hyperedges.
- Parameters:
graph (
eg.Graph
) – The graph to construct the hypergraph.k (
int
) – The number of hop neighbors.only_kHop (
bool
) – If set toTrue
, only the central vertex and its \(k\)-th Hop neighbors are used to construct the hyperedges. By default, the constructed hyperedge will include the central vertex and its [ \(1\)-th, \(2\)-th, \(\cdots\), \(k\)-th ] Hop neighbors. Defaults toFalse
.device (
torch.device
, optional) – The device to store the hypergraph. Defaults totorch.device('cpu')
.
- static from_state_dict(state_dict: dict)[source]
Load the hypergraph from the state dict.
- Parameters:
state_dict (
dict
) – The state dict to load the hypergraph.
- property group_names: List[str]
Return the names of all hyperedge groups in the hypergraph.
- static load(file_path: str | Path)[source]
Load the DHG’s hypergraph structure from a file.
- Parameters:
file_path (
Union[str, Path]
) – The file path to load the DHG’s hypergraph structure.
- nbr_e(v_idx: int) List[int] [source]
Return the neighbor hyperedge list of the specified vertex.
- Parameters:
v_idx (
int
) – The index of the vertex.
- nbr_e_of_group(v_idx: int, group_name: str) List[int] [source]
Return the neighbor hyperedge list of the specified vertex of the specified hyperedge group.
- Parameters:
v_idx (
int
) – The index of the vertex.group_name (
str
) – The name of the specified hyperedge group.
- nbr_v(e_idx: int) List[int] [source]
Return the neighbor vertex list of the specified hyperedge.
- Parameters:
e_idx (
int
) – The index of the hyperedge.
- nbr_v_of_group(e_idx: int, group_name: str) List[int] [source]
Return the neighbor vertex list of the specified hyperedge of the specified hyperedge group.
- Parameters:
e_idx (
int
) – The index of the hyperedge.group_name (
str
) – The name of the specified hyperedge group.
- property num_e: int
Return the number of hyperedges in the hypergraph.
- num_e_of_group(group_name: str) int [source]
Return the number of hyperedges of the specified hyperedge group.
- Parameters:
group_name (
str
) – The name of the specified hyperedge group.
- property num_groups: int
Return the number of hyperedge groups in the hypergraph.
- property num_v: int
Return the number of vertices in the hypergraph.
- remove_group(group_name: str)[source]
Remove the specified hyperedge group from the hypergraph.
- Parameters:
group_name (
str
) – The name of the hyperedge group to remove.
- remove_hyperedges(e_list: List[int] | List[List[int]], group_name: str | None = None)[source]
Remove the specified hyperedges from the hypergraph.
- Parameters:
e_list (
Union[List[int], List[List[int]]]
) – A list of hyperedges describes how the vertices point to the hyperedges.group_name (
str
, optional) – Remove these hyperedges from the specified hyperedge group. If not specified, the function will remove those hyperedges from all hyperedge groups. Defaults to theNone
.
- save(file_path: str | Path)[source]
Save the DHG’s hypergraph structure a file.
- Parameters:
file_path (
Union[str, Path]
) – The file path to store the DHG’s hypergraph structure.
- smoothing(X: Tensor, L: Tensor, lamb: float) Tensor [source]
Spectral-based smoothing.
\[X_{smoothed} = X + \lambda \mathcal{L} X\]- Parameters:
X (
torch.Tensor
) – The vertex feature matrix. Size \((|\mathcal{V}|, C)\).L (
torch.Tensor
) – The Laplacian matrix withtorch.sparse_coo_tensor
format. Size \((|\mathcal{V}|, |\mathcal{V}|)\).lamb (
float
) – \(\lambda\), the strength of smoothing.
- smoothing_with_HGNN(X: Tensor, drop_rate: float = 0.0) Tensor [source]
Return the smoothed feature matrix with the HGNN Laplacian matrix \(\mathcal{L}_{HGNN}\).
\[\mathbf{X} = \mathbf{D}_v^{-\frac{1}{2}} \mathbf{H} \mathbf{W}_e \mathbf{D}_e^{-1} \mathbf{H}^\top \mathbf{D}_v^{-\frac{1}{2}} \mathbf{X}\]- Parameters:
X (
torch.Tensor
) – The feature matrix. Size \((|\mathcal{V}|, C)\).drop_rate (
float
) – Dropout rate. Randomly dropout the connections in incidence matrix with probabilitydrop_rate
. Default:0.0
.
- smoothing_with_HGNN_of_group(group_name: str, X: Tensor, drop_rate: float = 0.0) Tensor [source]
Return the smoothed feature matrix with the HGNN Laplacian matrix \(\mathcal{L}_{HGNN}\).
\[\mathbf{X} = \mathbf{D}_v^{-\frac{1}{2}} \mathbf{H} \mathbf{W}_e \mathbf{D}_e^{-1} \mathbf{H}^\top \mathbf{D}_v^{-\frac{1}{2}} \mathbf{X}\]- Parameters:
group_name (
str
) – The name of the specified hyperedge group.X (
torch.Tensor
) – The feature matrix. Size \((|\mathcal{V}|, C)\).drop_rate (
float
) – Dropout rate. Randomly dropout the connections in incidence matrix with probabilitydrop_rate
. Default:0.0
.
- property state_dict: Dict[str, Any]
Get the state dict of the hypergraph.
- to(device: device)[source]
Move the hypergraph to the specified device.
- Parameters:
device (
torch.device
) – The target device.
- property v: List[int]
Return the list of vertices.
- v2e(X: Tensor, aggr: str = 'mean', v2e_weight: Tensor | None = None, e_weight: Tensor | None = None, drop_rate: float = 0.0)[source]
Message passing of
vertices to hyperedges
. The combination ofv2e_aggregation
andv2e_update
.- Parameters:
X (
torch.Tensor
) – Vertex feature matrix. Size \((|\mathcal{V}|, C)\).aggr (
str
) – The aggregation method. Can be'mean'
,'sum'
and'softmax_then_sum'
.v2e_weight (
torch.Tensor
, optional) – The weight vector attached to connections (vertices point to hyepredges). If not specified, the function will use the weights specified in hypergraph construction. Defaults toNone
.e_weight (
torch.Tensor
, optional) – The hyperedge weight vector. If not specified, the function will use the weights specified in hypergraph construction. Defaults toNone
.drop_rate (
float
) – Dropout rate. Randomly dropout the connections in incidence matrix with probabilitydrop_rate
. Default:0.0
.
- v2e_aggregation(X: Tensor, aggr: str = 'mean', v2e_weight: Tensor | None = None, drop_rate: float = 0.0)[source]
Message aggretation step of
vertices to hyperedges
.- Parameters:
X (
torch.Tensor
) – Vertex feature matrix. Size \((|\mathcal{V}|, C)\).aggr (
str
) – The aggregation method. Can be'mean'
,'sum'
and'softmax_then_sum'
.v2e_weight (
torch.Tensor
, optional) – The weight vector attached to connections (vertices point to hyepredges). If not specified, the function will use the weights specified in hypergraph construction. Defaults toNone
.drop_rate (
float
) – Dropout rate. Randomly dropout the connections in incidence matrix with probabilitydrop_rate
. Default:0.0
.
- v2e_aggregation_of_group(group_name: str, X: Tensor, aggr: str = 'mean', v2e_weight: Tensor | None = None, drop_rate: float = 0.0)[source]
Message aggregation step of
vertices to hyperedges
in specified hyperedge group.- Parameters:
group_name (
str
) – The specified hyperedge group.X (
torch.Tensor
) – Vertex feature matrix. Size \((|\mathcal{V}|, C)\).aggr (
str
) – The aggregation method. Can be'mean'
,'sum'
and'softmax_then_sum'
.v2e_weight (
torch.Tensor
, optional) – The weight vector attached to connections (vertices point to hyepredges). If not specified, the function will use the weights specified in hypergraph construction. Defaults toNone
.drop_rate (
float
) – Dropout rate. Randomly dropout the connections in incidence matrix with probabilitydrop_rate
. Default:0.0
.
- property v2e_dst: Tensor
Return the destination hyperedge index vector \(\overrightarrow{v2e}_{dst}\) of the connections (vertices point to hyperedges) in the hypergraph.
- v2e_dst_of_group(group_name: str) Tensor [source]
Return the destination hyperedge index vector \(\overrightarrow{v2e}_{dst}\) of the connections (vertices point to hyperedges) in the specified hyperedge group.
- Parameters:
group_name (
str
) – The name of the specified hyperedge group.
- v2e_of_group(group_name: str, X: Tensor, aggr: str = 'mean', v2e_weight: Tensor | None = None, e_weight: Tensor | None = None, drop_rate: float = 0.0)[source]
Message passing of
vertices to hyperedges
in specified hyperedge group. The combination ofe2v_aggregation_of_group
ande2v_update_of_group
.- Parameters:
group_name (
str
) – The specified hyperedge group.X (
torch.Tensor
) – Vertex feature matrix. Size \((|\mathcal{V}|, C)\).aggr (
str
) – The aggregation method. Can be'mean'
,'sum'
and'softmax_then_sum'
.v2e_weight (
torch.Tensor
, optional) – The weight vector attached to connections (vertices point to hyepredges). If not specified, the function will use the weights specified in hypergraph construction. Defaults toNone
.e_weight (
torch.Tensor
, optional) – The hyperedge weight vector. If not specified, the function will use the weights specified in hypergraph construction. Defaults toNone
.drop_rate (
float
) – Dropout rate. Randomly dropout the connections in incidence matrix with probabilitydrop_rate
. Default:0.0
.
- property v2e_src: Tensor
Return the source vertex index vector \(\overrightarrow{v2e}_{src}\) of the connections (vertices point to hyperedges) in the hypergraph.
- v2e_src_of_group(group_name: str) Tensor [source]
Return the source vertex index vector \(\overrightarrow{v2e}_{src}\) of the connections (vertices point to hyperedges) in the specified hyperedge group.
- Parameters:
group_name (
str
) – The name of the specified hyperedge group.
- v2e_update(X: Tensor, e_weight: Tensor | None = None)[source]
Message update step of
vertices to hyperedges
.- Parameters:
X (
torch.Tensor
) – Hyperedge feature matrix. Size \((|\mathcal{E}|, C)\).e_weight (
torch.Tensor
, optional) – The hyperedge weight vector. If not specified, the function will use the weights specified in hypergraph construction. Defaults toNone
.
- v2e_update_of_group(group_name: str, X: Tensor, e_weight: Tensor | None = None)[source]
Message update step of
vertices to hyperedges
in specified hyperedge group.- Parameters:
group_name (
str
) – The specified hyperedge group.X (
torch.Tensor
) – Hyperedge feature matrix. Size \((|\mathcal{E}|, C)\).e_weight (
torch.Tensor
, optional) – The hyperedge weight vector. If not specified, the function will use the weights specified in hypergraph construction. Defaults toNone
.
- property v2e_weight: Tensor
Return the weight vector \(\overrightarrow{v2e}_{weight}\) of the connections (vertices point to hyperedges) in the hypergraph.
- v2e_weight_of_group(group_name: str) Tensor [source]
Return the weight vector \(\overrightarrow{v2e}_{weight}\) of the connections (vertices point to hyperedges) in the specified hyperedge group.
- Parameters:
group_name (
str
) – The name of the specified hyperedge group.
- v2v(X: Tensor, aggr: str = 'mean', drop_rate: float = 0.0, v2e_aggr: str | None = None, v2e_weight: Tensor | None = None, v2e_drop_rate: float | None = None, e_weight: Tensor | None = None, e2v_aggr: str | None = None, e2v_weight: Tensor | None = None, e2v_drop_rate: float | None = None)[source]
Message passing of
vertices to vertices
. The combination ofv2e
ande2v
.- Parameters:
X (
torch.Tensor
) – Vertex feature matrix. Size \((|\mathcal{V}|, C)\).aggr (
str
) – The aggregation method. Can be'mean'
,'sum'
and'softmax_then_sum'
. If specified, thisaggr
will be used to bothv2e
ande2v
.drop_rate (
float
) – Dropout rate. Randomly dropout the connections in incidence matrix with probabilitydrop_rate
. Default:0.0
.v2e_aggr (
str
, optional) – The aggregation method for hyperedges to vertices. Can be'mean'
,'sum'
and'softmax_then_sum'
. If specified, it will override theaggr
ine2v
.v2e_weight (
torch.Tensor
, optional) – The weight vector attached to connections (vertices point to hyepredges). If not specified, the function will use the weights specified in hypergraph construction. Defaults toNone
.v2e_drop_rate (
float
, optional) – Dropout rate for hyperedges to vertices. Randomly dropout the connections in incidence matrix with probabilitydrop_rate
. If specified, it will override thedrop_rate
ine2v
. Default:None
.e_weight (
torch.Tensor
, optional) – The hyperedge weight vector. If not specified, the function will use the weights specified in hypergraph construction. Defaults toNone
.e2v_aggr (
str
, optional) – The aggregation method for vertices to hyperedges. Can be'mean'
,'sum'
and'softmax_then_sum'
. If specified, it will override theaggr
inv2e
.e2v_weight (
torch.Tensor
, optional) – The weight vector attached to connections (hyperedges point to vertices). If not specified, the function will use the weights specified in hypergraph construction. Defaults toNone
.e2v_drop_rate (
float
, optional) – Dropout rate for vertices to hyperedges. Randomly dropout the connections in incidence matrix with probabilitydrop_rate
. If specified, it will override thedrop_rate
inv2e
. Default:None
.
- v2v_of_group(group_name: str, X: Tensor, aggr: str = 'mean', drop_rate: float = 0.0, v2e_aggr: str | None = None, v2e_weight: Tensor | None = None, v2e_drop_rate: float | None = None, e_weight: Tensor | None = None, e2v_aggr: str | None = None, e2v_weight: Tensor | None = None, e2v_drop_rate: float | None = None)[source]
Message passing of
vertices to vertices
in specified hyperedge group. The combination ofv2e_of_group
ande2v_of_group
.- Parameters:
group_name (
str
) – The specified hyperedge group.X (
torch.Tensor
) – Vertex feature matrix. Size \((|\mathcal{V}|, C)\).aggr (
str
) – The aggregation method. Can be'mean'
,'sum'
and'softmax_then_sum'
. If specified, thisaggr
will be used to bothv2e_of_group
ande2v_of_group
.drop_rate (
float
) – Dropout rate. Randomly dropout the connections in incidence matrix with probabilitydrop_rate
. Default:0.0
.v2e_aggr (
str
, optional) – The aggregation method for hyperedges to vertices. Can be'mean'
,'sum'
and'softmax_then_sum'
. If specified, it will override theaggr
ine2v_of_group
.v2e_weight (
torch.Tensor
, optional) – The weight vector attached to connections (vertices point to hyepredges). If not specified, the function will use the weights specified in hypergraph construction. Defaults toNone
.v2e_drop_rate (
float
, optional) – Dropout rate for hyperedges to vertices. Randomly dropout the connections in incidence matrix with probabilitydrop_rate
. If specified, it will override thedrop_rate
ine2v_of_group
. Default:None
.e_weight (
torch.Tensor
, optional) – The hyperedge weight vector. If not specified, the function will use the weights specified in hypergraph construction. Defaults toNone
.e2v_aggr (
str
, optional) – The aggregation method for vertices to hyperedges. Can be'mean'
,'sum'
and'softmax_then_sum'
. If specified, it will override theaggr
inv2e_of_group
.e2v_weight (
torch.Tensor
, optional) – The weight vector attached to connections (hyperedges point to vertices). If not specified, the function will use the weights specified in hypergraph construction. Defaults toNone
.e2v_drop_rate (
float
, optional) – Dropout rate for vertices to hyperedges. Randomly dropout the connections in incidence matrix with probabilitydrop_rate
. If specified, it will override thedrop_rate
inv2e_of_group
. Default:None
.
- property vars_for_DL: List[str]
Return a name list of available variables for deep learning in the hypergraph including
Sparse Matrices:
\[\mathbf{H}, \mathbf{H}^\top, \mathcal{L}_{sym}, \mathcal{L}_{rw} \mathcal{L}_{HGNN},\]Sparse Diagnal Matrices:
\[\mathbf{W}_e, \mathbf{D}_v, \mathbf{D}_v^{-1}, \mathbf{D}_v^{-\frac{1}{2}}, \mathbf{D}_e, \mathbf{D}_e^{-1},\]Vectors:
\[\begin{split}\overrightarrow{v2e}_{src}, \overrightarrow{v2e}_{dst}, \overrightarrow{v2e}_{weight},\\ \overrightarrow{e2v}_{src}, \overrightarrow{e2v}_{dst}, \overrightarrow{e2v}_{weight}\end{split}\]
easygraph.classes.multigraph module
Base class for MultiGraph.
- class easygraph.classes.multigraph.MultiGraph(incoming_graph_data=None, multigraph_input=None, **attr)[source]
Bases:
Graph
- add_edge(u_for_edge, v_for_edge, key=None, **attr)[source]
Add an edge between u and v.
The nodes u and v will be automatically added if they are not already in the graph.
Edge attributes can be specified with keywords or by directly accessing the edge’s attribute dictionary. See examples below.
- Parameters:
u_for_edge (nodes) – Nodes can be, for example, strings or numbers. Nodes must be hashable (and not None) Python objects.
v_for_edge (nodes) – Nodes can be, for example, strings or numbers. Nodes must be hashable (and not None) Python objects.
key (hashable identifier, optional (default=lowest unused integer)) – Used to distinguish multiedges between a pair of nodes.
attr (keyword arguments, optional) – Edge data (or labels or objects) can be assigned using keyword arguments.
- Return type:
The edge key assigned to the edge.
See also
add_edges_from
add a collection of edges
Notes
To replace/update edge data, use the optional key argument to identify a unique edge. Otherwise a new edge will be created.
EasyGraph algorithms designed for weighted graphs cannot use multigraphs directly because it is not clear how to handle multiedge weights. Convert to Graph using edge attribute ‘weight’ to enable weighted graph algorithms.
Default keys are generated using the method new_edge_key(). This method can be overridden by subclassing the base class and providing a custom new_edge_key() method.
Examples
The following all add the edge e=(1, 2) to graph G:
>>> G = eg.MultiGraph() >>> e = (1, 2) >>> ekey = G.add_edge(1, 2) # explicit two-node form >>> G.add_edge(*e) # single edge as tuple of two nodes 1 >>> G.add_edges_from([(1, 2)]) # add edges from iterable container [2]
Associate data to edges using keywords:
>>> ekey = G.add_edge(1, 2, weight=3) >>> ekey = G.add_edge(1, 2, key=0, weight=4) # update data for key=0 >>> ekey = G.add_edge(1, 3, weight=7, capacity=15, length=342.7)
For non-string attribute keys, use subscript notation.
>>> ekey = G.add_edge(1, 2) >>> G[1][2][0].update({0: 5}) >>> G.edges[1, 2, 0].update({0: 5})
- 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 can be:
2-tuples (u, v) or
3-tuples (u, v, d) for an edge data dict d, or
3-tuples (u, v, k) for not iterable key k, or
4-tuples (u, v, k, d) for an edge with data and key k
attr (keyword arguments, optional) – Edge data (or labels or objects) can be assigned using keyword arguments.
- Return type:
A list of edge keys assigned to the edges in ebunch.
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.
Default keys are generated using the method
new_edge_key()
. This method can be overridden by subclassing the base class and providing a customnew_edge_key()
method.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")
- copy()[source]
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.
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. EasyGraph 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 = eg.path_graph(5) >>> H = G.copy() >>> H = eg.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)
See the Python copy module for more information on shallow and deep copies, https://docs.python.org/3/library/copy.html.
- Returns:
G – A copy of the graph.
- Return type:
See also
to_directed
return a directed copy of the graph.
Examples
>>> G = eg.path_graph(4) # or DiGraph, MultiGraph, MultiDiGraph, etc >>> H = G.copy()
- property degree
Returns the weighted degree of of each node.
- Parameters:
weight (string, optional (default: 'weight')) – Weight key of the original weighted graph.
- Returns:
degree – Each node’s (key) weighted degree (value).
- Return type:
dict
Notes
If the graph is not weighted, all the weights will be regarded as 1.
Examples
You can call with no attributes, if ‘weight’ is the weight key:
>>> G.degree()
if you have customized weight key ‘weight_1’.
>>> G.degree(weight='weight_1')
- edge_key_dict_factory
alias of
dict
- property edges
- get_edge_data(u, v, key=None, default=None)[source]
Returns the attribute dictionary associated with edge (u, v).
This is identical to G[u][v][key] except the default is returned instead of an exception is the edge doesn’t exist.
- Parameters:
u (nodes) –
v (nodes) –
default (any Python object (default=None)) – Value to return if the edge (u, v) is not found.
key (hashable identifier, optional (default=None)) – Return data only for the edge with specified key.
- Returns:
edge_dict – The edge attribute dictionary.
- Return type:
dictionary
Examples
>>> G = eg.MultiGraph() # or MultiDiGraph >>> key = G.add_edge(0, 1, key="a", weight=7) >>> G[0][1]["a"] # key='a' {'weight': 7} >>> G.edges[0, 1, "a"] # key='a' {'weight': 7}
Warning: we protect the graph data structure by making G.edges and G[1][2] read-only dict-like structures. However, you can assign values to attributes in e.g. G.edges[1, 2, ‘a’] or G[1][2][‘a’] using an additional bracket as shown next. You need to specify all edge info to assign to the edge data associated with an edge.
>>> G[0][1]["a"]["weight"] = 10 >>> G.edges[0, 1, "a"]["weight"] = 10 >>> G[0][1]["a"]["weight"] 10 >>> G.edges[1, 0, "a"]["weight"] 10
>>> G = eg.MultiGraph() # or MultiDiGraph >>> G = eg.complete_graph(4, create_using=eg.MultiDiGraph) >>> G.get_edge_data(0, 1) {0: {}} >>> e = (0, 1) >>> G.get_edge_data(*e) # tuple form {0: {}} >>> G.get_edge_data("a", "b", default=0) # edge not in graph, return 0 0
- has_edge(u, v, key=None)[source]
Returns True if the graph has an edge between nodes u and v.
This is the same as v in G[u] or key in G[u][v] without KeyError exceptions.
- Parameters:
u (nodes) – Nodes can be, for example, strings or numbers.
v (nodes) – Nodes can be, for example, strings or numbers.
key (hashable identifier, optional (default=None)) – If specified return True only if the edge with key is found.
- Returns:
edge_ind – True if edge is in the graph, False otherwise.
- Return type:
bool
Examples
Can be called either using two nodes u, v, an edge tuple (u, v), or an edge tuple (u, v, key).
>>> G = eg.MultiGraph() # or MultiDiGraph >>> G = eg.complete_graph(4, create_using=eg.MultiDiGraph) >>> G.has_edge(0, 1) # using two nodes True >>> e = (0, 1) >>> G.has_edge(*e) # e is a 2-tuple (u, v) True >>> G.add_edge(0, 1, key="a") 'a' >>> G.has_edge(0, 1, key="a") # specify key True >>> e = (0, 1, "a") >>> G.has_edge(*e) # e is a 3-tuple (u, v, 'a') True
The following syntax are equivalent:
>>> G.has_edge(0, 1) True >>> 1 in G[0] # though this gives :exc:`KeyError` if 0 not in G True
- new_edge_key(u, v)[source]
Returns an unused key for edges between nodes u and v.
The nodes u and v do not need to be already in the graph.
Notes
In the standard MultiGraph class the new key is the number of existing edges between u and v (increased if necessary to ensure unused). The first edge will have key 0, then 1, etc. If an edge is removed further new_edge_keys may not be in this order.
- Parameters:
u (nodes) –
v (nodes) –
- Returns:
key
- Return type:
int
- number_of_edges(u=None, v=None)[source]
Returns the number of edges between two nodes.
- Parameters:
u (nodes, optional (Gefault=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 (Gefault=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 multigraphs, this method counts the total number of edges in the graph:
>>> G = eg.MultiGraph() >>> G.add_edges_from([(0, 1), (0, 1), (1, 2)]) [0, 1, 0] >>> 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) 2
For directed multigraphs, this method can count the total number of directed edges from u to v:
>>> G = eg.MultiDiGraph() >>> G.add_edges_from([(0, 1), (0, 1), (1, 0)]) [0, 1, 0] >>> G.number_of_edges(0, 1) 2 >>> G.number_of_edges(1, 0) 1
- remove_edge(u, v, key=None)[source]
Remove an edge between u and v.
- Parameters:
u (nodes) – Remove an edge between nodes u and v.
v (nodes) – Remove an edge between nodes u and v.
key (hashable identifier, optional (default=None)) – Used to distinguish multiple edges between a pair of nodes. If None remove a single (arbitrary) edge between u and v.
- Raises:
EasyGraphError – If there is not an edge between u and v, or if there is no edge with the specified key.
See also
remove_edges_from
remove a collection of edges
Examples
For multiple edges
>>> G = eg.MultiGraph() # or MultiDiGraph, etc >>> G.add_edges_from([(1, 2), (1, 2), (1, 2)]) # key_list returned [0, 1, 2] >>> G.remove_edge(1, 2) # remove a single (arbitrary) edge
For edges with keys
>>> G = eg.MultiGraph() # or MultiDiGraph, etc >>> G.add_edge(1, 2, key="first") 'first' >>> G.add_edge(1, 2, key="second") 'second' >>> G.remove_edge(1, 2, key="second")
- 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) All edges between u and v are removed.
3-tuples (u, v, key) The edge identified by key is removed.
4-tuples (u, v, key, data) where data 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
Removing multiple copies of edges
>>> G = eg.MultiGraph() >>> keys = G.add_edges_from([(1, 2), (1, 2), (1, 2)]) >>> G.remove_edges_from([(1, 2), (1, 2)]) >>> list(G.edges()) [(1, 2)] >>> G.remove_edges_from([(1, 2), (1, 2)]) # silently ignore extra copy >>> list(G.edges) # now empty graph []
- to_directed()[source]
Returns a directed representation of the graph.
- Returns:
G – 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).
- Return type:
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 MultiGraph to use dict-like objects in the data structure, those changes do not transfer to the MultiDiGraph created by this method.
Examples
>>> G = eg.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 = eg.DiGraph() # or MultiDiGraph, etc >>> G.add_edge(0, 1) >>> H = G.to_directed() >>> list(H.edges) [(0, 1)]
easygraph.classes.operation module
- easygraph.classes.operation.add_path(G_to_add_to, nodes_for_path, **attr)[source]
Add a path to the Graph G_to_add_to.
- Parameters:
G_to_add_to (graph) – A EasyGraph graph
nodes_for_path (iterable container) – A container of nodes. A path will be constructed from the nodes (in order) and added to the graph.
attr (keyword arguments, optional (default= no attributes)) – Attributes to add to every edge in path.
See also
add_star
,add_cycle
Examples
>>> G = eg.Graph() >>> eg.add_path(G, [0, 1, 2, 3]) >>> eg.add_path(G, [10, 11, 12], weight=7)
- easygraph.classes.operation.density(*args, **kwargs)
- easygraph.classes.operation.number_of_selfloops(G)[source]
Returns the number of selfloop edges.
A selfloop edge has the same node at both ends.
- Returns:
nloops – The number of selfloops.
- Return type:
int
See also
nodes_with_selfloops
,selfloop_edges
Examples
>>> G = eg.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.add_edge(1, 1) >>> G.add_edge(1, 2) >>> eg.number_of_selfloops(G) 1
- easygraph.classes.operation.selfloop_edges(G, data=False, keys=False, default=None)[source]
Returns an iterator over selfloop edges.
A selfloop edge has the same node at both ends.
- Parameters:
G (graph) – A EasyGraph graph.
data (string or bool, optional (default=False)) – Return selfloop edges as two tuples (u, v) (data=False) or three-tuples (u, v, datadict) (data=True) or three-tuples (u, v, datavalue) (data=’attrname’)
keys (bool, optional (default=False)) – If True, return edge keys with each edge.
default (value, optional (default=None)) – Value used for edges that don’t have the requested attribute. Only relevant if data is not True or False.
- Returns:
edgeiter – An iterator over all selfloop edges.
- Return type:
iterator over edge tuples
See also
nodes_with_selfloops
,number_of_selfloops
Examples
>>> G = eg.MultiGraph() # or Graph, DiGraph, MultiDiGraph, etc >>> ekey = G.add_edge(1, 1) >>> ekey = G.add_edge(1, 2) >>> list(eg.selfloop_edges(G)) [(1, 1)] >>> list(eg.selfloop_edges(G, data=True)) [(1, 1, {})] >>> list(eg.selfloop_edges(G, keys=True)) [(1, 1, 0)] >>> list(eg.selfloop_edges(G, keys=True, data=True)) [(1, 1, 0, {})]
- easygraph.classes.operation.set_edge_attributes(G, values, name=None)[source]
Sets edge attributes from a given value or dictionary of values.
Warning
The call order of arguments values and name switched between v1.x & v2.x.
- Parameters:
G (EasyGraph Graph) –
values (scalar value, dict-like) –
What the edge attribute should be set to. If values is not a dictionary, then it is treated as a single attribute value that is then applied to every edge in G. This means that if you provide a mutable object, like a list, updates to that object will be reflected in the edge attribute for each edge. The attribute name will be name.
If values is a dict or a dict of dict, it should be keyed by edge tuple to either an attribute value or a dict of attribute key/value pairs used to update the edge’s attributes. For multigraphs, the edge tuples must be of the form
(u, v, key)
, where u and v are nodes and key is the edge key. For non-multigraphs, the keys must be tuples of the form(u, v)
.name (string (optional, default=None)) – Name of the edge attribute to set if values is a scalar.
Examples
After computing some property of the edges of a graph, you may want to assign a edge attribute to store the value of that property for each edge:
>>> G = eg.path_graph(3) >>> bb = eg.edge_betweenness_centrality(G, normalized=False) >>> eg.set_edge_attributes(G, bb, "betweenness") >>> G.edges[1, 2]["betweenness"] 2.0
If you provide a list as the second argument, updates to the list will be reflected in the edge attribute for each edge:
>>> labels = [] >>> eg.set_edge_attributes(G, labels, "labels") >>> labels.append("foo") >>> G.edges[0, 1]["labels"] ['foo'] >>> G.edges[1, 2]["labels"] ['foo']
If you provide a dictionary of dictionaries as the second argument, the entire dictionary will be used to update edge attributes:
>>> G = eg.path_graph(3) >>> attrs = {(0, 1): {"attr1": 20, "attr2": "nothing"}, (1, 2): {"attr2": 3}} >>> eg.set_edge_attributes(G, attrs) >>> G[0][1]["attr1"] 20 >>> G[0][1]["attr2"] 'nothing' >>> G[1][2]["attr2"] 3
Note that if the dict contains edges that are not in G, they are silently ignored:
>>> G = eg.Graph([(0, 1)]) >>> eg.set_edge_attributes(G, {(1, 2): {"weight": 2.0}}) >>> (1, 2) in G.edges() False
- easygraph.classes.operation.set_node_attributes(G, values, name=None)[source]
Sets node attributes from a given value or dictionary of values.
Warning
The call order of arguments values and name switched between v1.x & v2.x.
- Parameters:
G (EasyGraph Graph) –
values (scalar value, dict-like) –
What the node attribute should be set to. If values is not a dictionary, then it is treated as a single attribute value that is then applied to every node in G. This means that if you provide a mutable object, like a list, updates to that object will be reflected in the node attribute for every node. The attribute name will be name.
If values is a dict or a dict of dict, it should be keyed by node to either an attribute value or a dict of attribute key/value pairs used to update the node’s attributes.
name (string (optional, default=None)) – Name of the node attribute to set if values is a scalar.
Examples
After computing some property of the nodes of a graph, you may want to assign a node attribute to store the value of that property for each node:
>>> G = eg.path_graph(3) >>> bb = eg.betweenness_centrality(G) >>> isinstance(bb, dict) True >>> eg.set_node_attributes(G, bb, "betweenness") >>> G.nodes[1]["betweenness"] 1.0
If you provide a list as the second argument, updates to the list will be reflected in the node attribute for each node:
>>> G = eg.path_graph(3) >>> labels = [] >>> eg.set_node_attributes(G, labels, "labels") >>> labels.append("foo") >>> G.nodes[0]["labels"] ['foo'] >>> G.nodes[1]["labels"] ['foo'] >>> G.nodes[2]["labels"] ['foo']
If you provide a dictionary of dictionaries as the second argument, the outer dictionary is assumed to be keyed by node to an inner dictionary of node attributes for that node:
>>> G = eg.path_graph(3) >>> attrs = {0: {"attr1": 20, "attr2": "nothing"}, 1: {"attr2": 3}} >>> eg.set_node_attributes(G, attrs) >>> G.nodes[0]["attr1"] 20 >>> G.nodes[0]["attr2"] 'nothing' >>> G.nodes[1]["attr2"] 3 >>> G.nodes[2] {}
Note that if the dictionary contains nodes that are not in G, the values are silently ignored:
>>> G = eg.Graph() >>> G.add_node(0) >>> eg.set_node_attributes(G, {0: "red", 1: "blue"}, name="color") >>> G.nodes[0]["color"] 'red' >>> 1 in G.nodes False