dgl.add_edgesο
- dgl.add_edges(g, u, v, data=None, etype=None)[source]ο
Add the edges to the graph and return a new graph.
The i-th new edge will be from
u[i]
tov[i]
. The IDs of the new edges will start fromg.num_edges(etype)
.- Parameters:
u (int, Tensor or iterable[int]) β Source node IDs,
u[i]
gives the source node for the i-th new edge.v (int, Tensor or iterable[int]) β Destination node IDs,
v[i]
gives the destination node for the i-th new edge.data (dict[str, Tensor], optional) β Feature data of the added edges. The keys are feature names while the values are feature data.
etype (str or (str, str, str), optional) β
The type names of the edges. The allowed type name formats are:
(str, str, str)
for source node type, edge type and destination node type.or one
str
edge type name if the name can uniquely identify a triplet format in the graph.
Can be omitted if the graph has only one type of edges.
- Returns:
The graph with newly added edges.
- Return type:
Notes
If the end nodes of the given edges do not exist in
g
,dgl.add_nodes()
is invoked to add those nodes. The node features of the new nodes will be filled with zeros.For features in
g
but not indata
, DGL assigns zero features for the newly added nodes.For feature in
data
but not ing
, DGL assigns zero features for the existing nodes in the graph.This function discards the batch information. Please use
dgl.DGLGraph.set_batch_num_nodes()
anddgl.DGLGraph.set_batch_num_edges()
on the transformed graph to maintain the information.
Examples
The following example uses PyTorch backend.
>>> import dgl >>> import torch
Homogeneous Graphs
>>> g = dgl.graph((torch.tensor([0, 1]), torch.tensor([1, 2]))) >>> g.num_edges() 2 >>> g = dgl.add_edges(g, torch.tensor([1, 3]), torch.tensor([0, 1])) >>> g.num_edges() 4
Since
u
orv
contains a non-existing node ID, the nodes are added implicitly.>>> g.num_nodes() 4
If the graph has some edge features and new edges are added without features, their features will be filled with zeros.
>>> g.edata['h'] = torch.ones(4, 1) >>> g = dgl.add_edges(g, torch.tensor([1]), torch.tensor([1])) >>> g.edata['h'] tensor([[1.], [1.], [1.], [1.], [0.]])
You can also assign features for the new edges in adding new edges.
>>> g = dgl.add_edges(g, torch.tensor([0, 0]), torch.tensor([2, 2]), ... {'h': torch.tensor([[1.], [2.]]), 'w': torch.ones(2, 1)}) >>> g.edata['h'] tensor([[1.], [1.], [1.], [1.], [0.], [1.], [2.]])
Since
data
contains new feature fields, the features for old edges will be filled with zeros.>>> g.edata['w'] tensor([[0.], [0.], [0.], [0.], [0.], [1.], [1.]])
Heterogeneous Graphs
>>> g = dgl.heterograph({ ... ('user', 'plays', 'game'): (torch.tensor([0, 1, 1, 2]), ... torch.tensor([0, 0, 1, 1])), ... ('developer', 'develops', 'game'): (torch.tensor([0, 1]), ... torch.tensor([0, 1])) ... }) >>> g.num_edges('plays') 4 >>> g = dgl.add_edges(g, torch.tensor([3]), torch.tensor([3]), etype='plays') >>> g.num_edges('plays') 5
See also