Unverified Commit 274e1082 authored by Lingfan Yu's avatar Lingfan Yu Committed by GitHub
Browse files

[Doc] API doc string for many components (#245)

* builtin function docstring

* init docstring

* view docstring

* add init to index and fix

* node /edge feature

* Example -> Examples

* fix func hyperlink

* traversal

* fix

* from/to_networkx docstring

* minor

* fix duplicate label

* comment about tensor framework

* from scipy sparse matrix

* fix format errors
parent 7cca5007
...@@ -12,7 +12,6 @@ Adding nodes and edges ...@@ -12,7 +12,6 @@ Adding nodes and edges
.. autosummary:: .. autosummary::
:toctree: ../../generated/ :toctree: ../../generated/
DGLGraph.__init__
DGLGraph.add_nodes DGLGraph.add_nodes
DGLGraph.add_edge DGLGraph.add_edge
DGLGraph.add_edges DGLGraph.add_edges
......
...@@ -5,6 +5,7 @@ API Reference ...@@ -5,6 +5,7 @@ API Reference
:maxdepth: 2 :maxdepth: 2
graph graph
init
batch batch
function function
traversal traversal
......
.. _apiinit:
Feature Initializer
===================
.. automodule:: dgl.init
.. autosummary::
:toctree: ../../generated/
base_initializer
zero_initializer
...@@ -56,13 +56,13 @@ class RGCNEntityDataset(object): ...@@ -56,13 +56,13 @@ class RGCNEntityDataset(object):
test_idx: numpy.array test_idx: numpy.array
ids of entities used for testing ids of entities used for testing
Usage Usually, users don't need to directly use this class. Instead, DGL provides
-----
Usually, user don't need to directly use this class. Instead, DGL provides
wrapper function to load data (see example below). wrapper function to load data (see example below).
When loading data, besides specifying dataset name, user can provide two When loading data, besides specifying dataset name, user can provide two
optional arguments: optional arguments:
Parameters
----------
bfs_level: int bfs_level: int
prune out nodes that are more than ``bfs_level`` hops away from prune out nodes that are more than ``bfs_level`` hops away from
labeled nodes, i.e., nodes won't be touched during propagation. If set labeled nodes, i.e., nodes won't be touched during propagation. If set
...@@ -71,8 +71,8 @@ class RGCNEntityDataset(object): ...@@ -71,8 +71,8 @@ class RGCNEntityDataset(object):
After pruning, whether or not to relabel all nodes with consecutive After pruning, whether or not to relabel all nodes with consecutive
node ids node ids
Example Examples
------- --------
Load aifb dataset, prune out nodes that are more than 3 hops away from Load aifb dataset, prune out nodes that are more than 3 hops away from
labeled nodes, and relabel the remaining nodes with consecutive ids labeled nodes, and relabel the remaining nodes with consecutive ids
...@@ -157,13 +157,11 @@ class RGCNLinkDataset(object): ...@@ -157,13 +157,11 @@ class RGCNLinkDataset(object):
test: numpy.array test: numpy.array
all relation triplets (src, rel, dst) for testing all relation triplets (src, rel, dst) for testing
Usage
-----
Usually, user don't need to directly use this class. Instead, DGL provides Usually, user don't need to directly use this class. Instead, DGL provides
wrapper function to load data (see example below). wrapper function to load data (see example below).
Example Examples
------- --------
Load FB15k-237 dataset Load FB15k-237 dataset
>>> from dgl.contrib.data import load_data >>> from dgl.contrib.data import load_data
......
...@@ -113,17 +113,27 @@ class CopyEdgeMessageFunction(MessageFunction): ...@@ -113,17 +113,27 @@ class CopyEdgeMessageFunction(MessageFunction):
def src_mul_edge(src, edge, out): def src_mul_edge(src, edge, out):
"""Builtin message function that computes message by multiplying source node features """Builtin message function that computes message by multiplying source
with edge features. node features with edge features.
Parameters Parameters
---------- ----------
src : str src : str
The source feature name. The source feature field.
edge : str edge : str
The edge feature name. The edge feature field.
out : str out : str
The output message name. The output message field.
Examples
--------
>>> import dgl
>>> message_func = dgl.function.src_mul_edge(src='h', edge='w', out='m')
The above example is equivalent to the following user defined function:
>>> def message_func(edges):
>>> return {'m': edges.src['h'] * edges.data['w']}
""" """
return SrcMulEdgeMessageFunction(operator.mul, src, edge, out) return SrcMulEdgeMessageFunction(operator.mul, src, edge, out)
...@@ -133,9 +143,19 @@ def copy_src(src, out): ...@@ -133,9 +143,19 @@ def copy_src(src, out):
Parameters Parameters
---------- ----------
src : str src : str
The source feature name. The source feature field.
out : str out : str
The output message name. The output message field.
Examples
--------
>>> import dgl
>>> message_func = dgl.function.copy_src(src='h', out='m')
The above example is equivalent to the following user defined function:
>>> def message_func(edges):
>>> return {'m': edges.src['h']}
""" """
return CopySrcMessageFunction(src, out) return CopySrcMessageFunction(src, out)
...@@ -145,8 +165,18 @@ def copy_edge(edge, out): ...@@ -145,8 +165,18 @@ def copy_edge(edge, out):
Parameters Parameters
---------- ----------
edge : str edge : str
The edge feature name. The edge feature field.
out : str out : str
The output message name. The output message field.
Examples
--------
>>> import dgl
>>> message_func = dgl.function.copy_edge(edge='h', out='m')
The above example is equivalent to the following user defined function:
>>> def message_func(edges):
>>> return {'m': edges.data['h']}
""" """
return CopyEdgeMessageFunction(edge, out) return CopyEdgeMessageFunction(edge, out)
...@@ -52,9 +52,20 @@ def sum(msg, out): ...@@ -52,9 +52,20 @@ def sum(msg, out):
Parameters Parameters
---------- ----------
msg : str msg : str
The message name. The message field.
out : str out : str
The output node feature name. The output node feature field.
Examples
--------
>>> import dgl
>>> reduce_func = dgl.function.sum(msg='m', out='h')
The above example is equivalent to the following user defined function
(if using PyTorch):
>>> import torch
>>> def reduce_func(nodes):
>>> return {'h': torch.sum(nodes.mailbox['m'], dim=1)}
""" """
return SimpleReduceFunction("sum", F.sum, msg, out) return SimpleReduceFunction("sum", F.sum, msg, out)
...@@ -64,8 +75,20 @@ def max(msg, out): ...@@ -64,8 +75,20 @@ def max(msg, out):
Parameters Parameters
---------- ----------
msg : str msg : str
The message name. The message field.
out : str out : str
The output node feature name. The output node feature field.
Examples
--------
>>> import dgl
>>> reduce_func = dgl.function.max(msg='m', out='h')
The above example is equivalent to the following user defined function
(if using PyTorch):
>>> import torch
>>> def reduce_func(nodes):
>>> return {'h': torch.max(nodes.mailbox['m'], dim=1)}
""" """
return SimpleReduceFunction("max", F.max, msg, out) return SimpleReduceFunction("max", F.max, msg, out)
...@@ -272,6 +272,7 @@ class DGLGraph(object): ...@@ -272,6 +272,7 @@ class DGLGraph(object):
Examples Examples
-------- --------
The following example uses PyTorch backend. The following example uses PyTorch backend.
>>> G = dgl.DGLGraph() >>> G = dgl.DGLGraph()
>>> G.add_nodes(3) >>> G.add_nodes(3)
>>> G.add_edge(0, 1) >>> G.add_edge(0, 1)
...@@ -326,6 +327,7 @@ class DGLGraph(object): ...@@ -326,6 +327,7 @@ class DGLGraph(object):
Examples Examples
-------- --------
The following example uses PyTorch backend. The following example uses PyTorch backend.
>>> G = dgl.DGLGraph() >>> G = dgl.DGLGraph()
>>> G.add_nodes(4) >>> G.add_nodes(4)
>>> G.add_edges([0, 2], [1, 3]) # add edges (0, 1) and (2, 3) >>> G.add_edges([0, 2], [1, 3]) # add edges (0, 1) and (2, 3)
...@@ -444,6 +446,7 @@ class DGLGraph(object): ...@@ -444,6 +446,7 @@ class DGLGraph(object):
False False
Equivalently, Equivalently,
>>> 0 in G >>> 0 in G
True True
...@@ -466,9 +469,9 @@ class DGLGraph(object): ...@@ -466,9 +469,9 @@ class DGLGraph(object):
return self._graph.has_node(vid) return self._graph.has_node(vid)
def has_nodes(self, vids): def has_nodes(self, vids):
"""Return a 0-1 array `a` given the node ID array `vids`. """Return a 0-1 array ``a`` given the node ID array ``vids``.
`a[i]` is 1 if the graph contains node `vids[i]`, 0 otherwise. ``a[i]`` is 1 if the graph contains node ``vids[i]``, 0 otherwise.
Parameters Parameters
---------- ----------
...@@ -483,6 +486,7 @@ class DGLGraph(object): ...@@ -483,6 +486,7 @@ class DGLGraph(object):
Examples Examples
-------- --------
The following example uses PyTorch backend. The following example uses PyTorch backend.
>>> G = dgl.DGLGraph() >>> G = dgl.DGLGraph()
>>> G.add_nodes(3) >>> G.add_nodes(3)
>>> G.has_nodes([0, 1, 2, 3, 4]) >>> G.has_nodes([0, 1, 2, 3, 4])
...@@ -548,11 +552,13 @@ class DGLGraph(object): ...@@ -548,11 +552,13 @@ class DGLGraph(object):
Examples Examples
-------- --------
The following example uses PyTorch backend. The following example uses PyTorch backend.
>>> G = dgl.DGLGraph() >>> G = dgl.DGLGraph()
>>> G.add_nodes(3) >>> G.add_nodes(3)
>>> G.add_edges([0, 0], [1, 2]) # (0, 1), (0, 2) >>> G.add_edges([0, 0], [1, 2]) # (0, 1), (0, 2)
Check if (0, 1), (0, 2), (1, 0), (2, 0) exist in the graph above: Check if (0, 1), (0, 2), (1, 0), (2, 0) exist in the graph above:
>>> G.has_edges_between([0, 0, 1, 2], [1, 2, 0, 0]) >>> G.has_edges_between([0, 0, 1, 2], [1, 2, 0, 0])
tensor([1, 1, 0, 0]) tensor([1, 1, 0, 0])
...@@ -584,6 +590,7 @@ class DGLGraph(object): ...@@ -584,6 +590,7 @@ class DGLGraph(object):
Examples Examples
-------- --------
The following example uses PyTorch backend. The following example uses PyTorch backend.
>>> G = dgl.DGLGraph() >>> G = dgl.DGLGraph()
>>> G.add_nodes(3) >>> G.add_nodes(3)
>>> G.add_edges([1, 2], [0, 0]) # (1, 0), (2, 0) >>> G.add_edges([1, 2], [0, 0]) # (1, 0), (2, 0)
...@@ -615,6 +622,7 @@ class DGLGraph(object): ...@@ -615,6 +622,7 @@ class DGLGraph(object):
Examples Examples
-------- --------
The following example uses PyTorch backend. The following example uses PyTorch backend.
>>> G = dgl.DGLGraph() >>> G = dgl.DGLGraph()
>>> G.add_nodes(3) >>> G.add_nodes(3)
>>> G.add_edges([0, 0], [1, 2]) # (0, 1), (0, 2) >>> G.add_edges([0, 0], [1, 2]) # (0, 1), (0, 2)
...@@ -652,6 +660,7 @@ class DGLGraph(object): ...@@ -652,6 +660,7 @@ class DGLGraph(object):
The following example uses PyTorch backend. The following example uses PyTorch backend.
For simple graphs: For simple graphs:
>>> G = dgl.DGLGraph() >>> G = dgl.DGLGraph()
>>> G.add_node(3) >>> G.add_node(3)
>>> G.add_edges([0, 0], [1, 2]) # (0, 1), (0, 2) >>> G.add_edges([0, 0], [1, 2]) # (0, 1), (0, 2)
...@@ -661,11 +670,13 @@ class DGLGraph(object): ...@@ -661,11 +670,13 @@ class DGLGraph(object):
0 0
For multigraphs: For multigraphs:
>>> G = dgl.DGLGraph(multigraph=True) >>> G = dgl.DGLGraph(multigraph=True)
>>> G.add_nodes(3) >>> G.add_nodes(3)
Adding edges (0, 1), (0, 2), (0, 1), (0, 2), so edge ID 0 and 2 both Adding edges (0, 1), (0, 2), (0, 1), (0, 2), so edge ID 0 and 2 both
connect from 0 and 1, while edge ID 1 and 3 both connect from 0 and 2. connect from 0 and 1, while edge ID 1 and 3 both connect from 0 and 2.
>>> G.add_edges([0, 0, 0, 0], [1, 2, 1, 2]) >>> G.add_edges([0, 0, 0, 0], [1, 2, 1, 2])
>>> G.edge_id(0, 1) >>> G.edge_id(0, 1)
tensor([0, 2]) tensor([0, 2])
...@@ -710,6 +721,7 @@ class DGLGraph(object): ...@@ -710,6 +721,7 @@ class DGLGraph(object):
The following example uses PyTorch backend. The following example uses PyTorch backend.
For simple graphs: For simple graphs:
>>> G = dgl.DGLGraph() >>> G = dgl.DGLGraph()
>>> G.add_nodes(3) >>> G.add_nodes(3)
>>> G.add_edges([0, 0], [1, 2]) # (0, 1), (0, 2) >>> G.add_edges([0, 0], [1, 2]) # (0, 1), (0, 2)
...@@ -718,12 +730,14 @@ class DGLGraph(object): ...@@ -718,12 +730,14 @@ class DGLGraph(object):
tensor([1, 0]) tensor([1, 0])
For multigraphs For multigraphs
>>> G = dgl.DGLGraph(multigraph=True) >>> G = dgl.DGLGraph(multigraph=True)
>>> G.add_nodes(4) >>> G.add_nodes(4)
>>> G.add_edges([0, 0, 0], [1, 1, 2]) # (0, 1), (0, 1), (0, 2) >>> G.add_edges([0, 0, 0], [1, 1, 2]) # (0, 1), (0, 1), (0, 2)
Get all edges between (0, 1), (0, 2), (0, 3). Note that there is no Get all edges between (0, 1), (0, 2), (0, 3). Note that there is no
edge between 0 and 3: edge between 0 and 3:
>>> G.edge_ids([0, 0, 0], [1, 2, 3]) >>> G.edge_ids([0, 0, 0], [1, 2, 3])
(tensor([0, 0, 0]), tensor([1, 1, 2]), tensor([0, 1, 2])) (tensor([0, 0, 0]), tensor([1, 1, 2]), tensor([0, 1, 2]))
...@@ -779,29 +793,32 @@ class DGLGraph(object): ...@@ -779,29 +793,32 @@ class DGLGraph(object):
The node(s). The node(s).
form : str, optional form : str, optional
The return form. Currently support: The return form. Currently support:
- 'all' : a tuple (u, v, eid) - 'all' : a tuple (u, v, eid)
- 'uv' : a pair (u, v), default - 'uv' : a pair (u, v), default
- 'eid' : one eid tensor - 'eid' : one eid tensor
Returns Returns
------- -------
A tuple of Tensors `(eu, ev, eid)` if `form == 'all'`. A tuple of Tensors ``(eu, ev, eid)`` if ``form == 'all'``.
`eid[i]` is the ID of an inbound edge to `ev[i]` from `eu[i]`. ``eid[i]`` is the ID of an inbound edge to ``ev[i]`` from ``eu[i]``.
All inbound edges to `v` are returned. All inbound edges to ``v`` are returned.
A pair of Tensors (eu, ev) if form == 'uv' A pair of Tensors (eu, ev) if form == 'uv'
`eu[i]` is the source node of an inbound edge to `ev[i]`. ``eu[i]`` is the source node of an inbound edge to ``ev[i]``.
All inbound edges to `v` are returned. All inbound edges to ``v`` are returned.
One Tensor if form == 'eid' One Tensor if form == 'eid'
`eid[i]` is ID of an inbound edge to any of the nodes in `v`. ``eid[i]`` is ID of an inbound edge to any of the nodes in ``v``.
Examples Examples
-------- --------
The following example uses PyTorch backend. The following example uses PyTorch backend.
>>> G = dgl.DGLGraph() >>> G = dgl.DGLGraph()
>>> G.add_nodes(3) >>> G.add_nodes(3)
>>> G.add_edges([0, 0, 1], [1, 2, 2]) # (0, 1), (0, 2), (1, 2) >>> G.add_edges([0, 0, 1], [1, 2, 2]) # (0, 1), (0, 2), (1, 2)
For a single node: For a single node:
>>> G.in_edges(2) >>> G.in_edges(2)
(tensor([0, 1]), tensor([2, 2])) (tensor([0, 1]), tensor([2, 2]))
>>> G.in_edges(2, 'all') >>> G.in_edges(2, 'all')
...@@ -810,6 +827,7 @@ class DGLGraph(object): ...@@ -810,6 +827,7 @@ class DGLGraph(object):
tensor([1, 2]) tensor([1, 2])
For multiple nodes: For multiple nodes:
>>> G.in_edges([1, 2]) >>> G.in_edges([1, 2])
(tensor([0, 0, 1]), tensor([1, 2, 2])) (tensor([0, 0, 1]), tensor([1, 2, 2]))
>>> G.in_edges([1, 2], 'all') >>> G.in_edges([1, 2], 'all')
...@@ -835,29 +853,32 @@ class DGLGraph(object): ...@@ -835,29 +853,32 @@ class DGLGraph(object):
The node(s). The node(s).
form : str, optional form : str, optional
The return form. Currently support: The return form. Currently support:
- 'all' : a tuple (u, v, eid) - 'all' : a tuple (u, v, eid)
- 'uv' : a pair (u, v), default - 'uv' : a pair (u, v), default
- 'eid' : one eid tensor - 'eid' : one eid tensor
Returns Returns
------- -------
A tuple of Tensors `(eu, ev, eid)` if `form == 'all'`. A tuple of Tensors ``(eu, ev, eid)`` if ``form == 'all'``.
`eid[i]` is the ID of an outbound edge from `eu[i]` from `ev[i]`. ``eid[i]`` is the ID of an outbound edge from ``eu[i]`` from ``ev[i]``.
All outbound edges from `v` are returned. All outbound edges from ``v`` are returned.
A pair of Tensors (eu, ev) if form == 'uv' A pair of Tensors (eu, ev) if form == 'uv'
`ev[i]` is the destination node of an outbound edge from `eu[i]`. ``ev[i]`` is the destination node of an outbound edge from ``eu[i]``.
All outbound edges from `v` are returned. All outbound edges from ``v`` are returned.
One Tensor if form == 'eid' One Tensor if form == 'eid'
`eid[i]` is ID of an outbound edge from any of the nodes in `v`. ``eid[i]`` is ID of an outbound edge from any of the nodes in ``v``.
Examples Examples
-------- --------
The following example uses PyTorch backend. The following example uses PyTorch backend.
>>> G = dgl.DGLGraph() >>> G = dgl.DGLGraph()
>>> G.add_nodes(3) >>> G.add_nodes(3)
>>> G.add_edges([0, 0, 1], [1, 2, 2]) # (0, 1), (0, 2), (1, 2) >>> G.add_edges([0, 0, 1], [1, 2, 2]) # (0, 1), (0, 2), (1, 2)
For a single node: For a single node:
>>> G.out_edges(0) >>> G.out_edges(0)
(tensor([0, 0]), tensor([1, 2])) (tensor([0, 0]), tensor([1, 2]))
>>> G.out_edges(0, 'all') >>> G.out_edges(0, 'all')
...@@ -866,6 +887,7 @@ class DGLGraph(object): ...@@ -866,6 +887,7 @@ class DGLGraph(object):
tensor([0, 1]) tensor([0, 1])
For multiple nodes: For multiple nodes:
>>> G.out_edges([0, 1]) >>> G.out_edges([0, 1])
(tensor([0, 0, 1]), tensor([1, 2, 2])) (tensor([0, 0, 1]), tensor([1, 2, 2]))
>>> G.out_edges([0, 1], 'all') >>> G.out_edges([0, 1], 'all')
...@@ -889,6 +911,7 @@ class DGLGraph(object): ...@@ -889,6 +911,7 @@ class DGLGraph(object):
---------- ----------
form : str, optional form : str, optional
The return form. Currently support: The return form. Currently support:
- 'all' : a tuple (u, v, eid) - 'all' : a tuple (u, v, eid)
- 'uv' : a pair (u, v), default - 'uv' : a pair (u, v), default
- 'eid' : one eid tensor - 'eid' : one eid tensor
...@@ -898,18 +921,19 @@ class DGLGraph(object): ...@@ -898,18 +921,19 @@ class DGLGraph(object):
Returns Returns
------- -------
A tuple of Tensors (u, v, eid) if form == 'all' A tuple of Tensors (u, v, eid) if form == 'all'
`eid[i]` is the ID of an edge between `u[i]` and `v[i]`. ``eid[i]`` is the ID of an edge between ``u[i]`` and ``v[i]``.
All edges are returned. All edges are returned.
A pair of Tensors (u, v) if form == 'uv' A pair of Tensors (u, v) if form == 'uv'
An edge exists between `u[i]` and `v[i]`. An edge exists between ``u[i]`` and ``v[i]``.
If `n` edges exist between `u` and `v`, then `u` and `v` as a pair If ``n`` edges exist between ``u`` and ``v``, then ``u`` and ``v`` as a pair
will appear `n` times. will appear ``n`` times.
One Tensor if form == 'eid' One Tensor if form == 'eid'
`eid[i]` is the ID of an edge in the graph. ``eid[i]`` is the ID of an edge in the graph.
Examples Examples
-------- --------
The following example uses PyTorch backend. The following example uses PyTorch backend.
>>> G = dgl.DGLGraph() >>> G = dgl.DGLGraph()
>>> G.add_nodes(3) >>> G.add_nodes(3)
>>> G.add_edges([0, 0, 1], [1, 2, 2]) # (0, 1), (0, 2), (1, 2) >>> G.add_edges([0, 0, 1], [1, 2, 2]) # (0, 1), (0, 2), (1, 2)
...@@ -929,7 +953,7 @@ class DGLGraph(object): ...@@ -929,7 +953,7 @@ class DGLGraph(object):
raise DGLError('Invalid form:', form) raise DGLError('Invalid form:', form)
def in_degree(self, v): def in_degree(self, v):
"""Return the in-degree of node `v`. """Return the in-degree of node ``v``.
Parameters Parameters
---------- ----------
...@@ -973,6 +997,7 @@ class DGLGraph(object): ...@@ -973,6 +997,7 @@ class DGLGraph(object):
Examples Examples
-------- --------
The following example uses PyTorch backend. The following example uses PyTorch backend.
>>> G = dgl.DGLGraph() >>> G = dgl.DGLGraph()
>>> G.add_nodes(3) >>> G.add_nodes(3)
>>> G.add_edges([0, 0, 1], [1, 2, 2]) # (0, 1), (0, 2), (1, 2) >>> G.add_edges([0, 0, 1], [1, 2, 2]) # (0, 1), (0, 2), (1, 2)
...@@ -1034,6 +1059,7 @@ class DGLGraph(object): ...@@ -1034,6 +1059,7 @@ class DGLGraph(object):
Examples Examples
-------- --------
The following example uses PyTorch backend. The following example uses PyTorch backend.
>>> G = dgl.DGLGraph() >>> G = dgl.DGLGraph()
>>> G.add_nodes(3) >>> G.add_nodes(3)
>>> G.add_edges([0, 0, 1], [1, 2, 2]) # (0, 1), (0, 2), (1, 2) >>> G.add_edges([0, 0, 1], [1, 2, 2]) # (0, 1), (0, 2), (1, 2)
...@@ -1066,6 +1092,19 @@ class DGLGraph(object): ...@@ -1066,6 +1092,19 @@ class DGLGraph(object):
------- -------
networkx.DiGraph networkx.DiGraph
The nx graph The nx graph
Examples
--------
.. note:: Here we use pytorch syntax for demo. The general idea applies
to other frameworks with minor syntax change (e.g. replace
``torch.tensor`` with ``mxnet.ndarray``).
>>> import torch as th
>>> g = DGLGraph()
>>> g.add_nodes(5, {'n1': th.randn(5, 10)})
>>> g.add_edges([0,1,3,4], [2,4,0,3], {'e1': th.randn(4, 6)})
>>> nxg = g.to_networkx(node_attrs=['n1'], edge_attrs=['e1'])
""" """
nx_graph = self._graph.to_networkx() nx_graph = self._graph.to_networkx()
if node_attrs is not None: if node_attrs is not None:
...@@ -1093,6 +1132,28 @@ class DGLGraph(object): ...@@ -1093,6 +1132,28 @@ class DGLGraph(object):
The node attributes needs to be copied. The node attributes needs to be copied.
edge_attrs : iterable of str, optional edge_attrs : iterable of str, optional
The edge attributes needs to be copied. The edge attributes needs to be copied.
Examples
--------
.. note:: Here we use pytorch syntax for demo. The general idea applies
to other frameworks with minor syntax change (e.g. replace
``torch.tensor`` with ``mxnet.ndarray``).
>>> import torch as th
>>> import networkx as nx
>>> nxg = nx.DiGraph()
>>> nxg.add_edge(0, 1, id=0, e1=5, e2=th.zeros(4))
>>> nxg.add_edge(2, 3, id=2, e1=6, e2=th.ones(4))
>>> nxg.add_edge(1, 2, id=1, e1=2, e2=th.full((4,), 2))
>>> g = dgl.DGLGraph()
>>> g.from_networkx(nxg, edge_attrs=['e1', 'e2'])
>>> g.edata['e1']
tensor([5, 2, 6])
>>> g.edata['e2']
tensor([[0., 0., 0., 0.],
[2., 2., 2., 2.],
[1., 1., 1., 1.]])
""" """
self.clear() self.clear()
self._graph.from_networkx(nx_graph) self._graph.from_networkx(nx_graph)
...@@ -1116,7 +1177,7 @@ class DGLGraph(object): ...@@ -1116,7 +1177,7 @@ class DGLGraph(object):
has_edge_id = 'id' in next(iter(nx_graph.edges(data=True)))[-1] has_edge_id = 'id' in next(iter(nx_graph.edges(data=True)))[-1]
attr_dict = defaultdict(lambda: [None] * self.number_of_edges()) attr_dict = defaultdict(lambda: [None] * self.number_of_edges())
if has_edge_id: if has_edge_id:
for u, v, attrs in nx_graph.edges(data=True): for _, _, attrs in nx_graph.edges(data=True):
for key in edge_attrs: for key in edge_attrs:
attr_dict[key][attrs['id']] = attrs[key] attr_dict[key][attrs['id']] = attrs[key]
else: else:
...@@ -1134,6 +1195,16 @@ class DGLGraph(object): ...@@ -1134,6 +1195,16 @@ class DGLGraph(object):
---------- ----------
a : scipy sparse matrix a : scipy sparse matrix
The graph's adjacency matrix The graph's adjacency matrix
Examples
--------
>>> from scipy.sparse import coo_matrix
>>> row = np.array([0, 3, 1, 0])
>>> col = np.array([0, 3, 1, 2])
>>> data = np.array([4, 5, 7, 9])
>>> a = coo_matrix((data, (row, col)), shape=(4, 4))
>>> g = dgl.DGLGraph()
>>> g.from_scipy_sparse_matrix(a)
""" """
self.clear() self.clear()
self._graph.from_scipy_sparse_matrix(a) self._graph.from_scipy_sparse_matrix(a)
...@@ -1144,20 +1215,49 @@ class DGLGraph(object): ...@@ -1144,20 +1215,49 @@ class DGLGraph(object):
def node_attr_schemes(self): def node_attr_schemes(self):
"""Return the node feature schemes. """Return the node feature schemes.
Each feature scheme is a named tuple that stores the shape and data type
of the node feature
Returns Returns
------- -------
dict of str to schemes dict of str to schemes
The schemes of node feature columns. The schemes of node feature columns.
Examples
--------
>>> G = dgl.DGLGraph()
>>> G.add_nodes(3)
>>> G.ndata['x'] = torch.zeros((3,5))
>>> G.node_attr_schemes()
{'x': Scheme(shape=(5,), dtype=torch.float32)}
""" """
return self._node_frame.schemes return self._node_frame.schemes
def edge_attr_schemes(self): def edge_attr_schemes(self):
"""Return the edge feature schemes. """Return the edge feature schemes.
Each feature scheme is a named tuple that stores the shape and data type
of the node feature
Returns Returns
------- -------
dict of str to schemes dict of str to schemes
The schemes of edge feature columns. The schemes of edge feature columns.
Examples
--------
.. note:: Here we use pytorch syntax for demo. The general idea applies
to other frameworks with minor syntax change (e.g. replace
``torch.tensor`` with ``mxnet.ndarray``).
>>> import torch as th
>>> G = dgl.DGLGraph()
>>> G.add_nodes(3)
>>> G.add_edges([0, 1], 2) # 0->2, 1->2
>>> G.edata['y'] = th.zeros((2, 4))
>>> G.edge_attr_schemes()
{'y': Scheme(shape=(4,), dtype=torch.float32)}
""" """
return self._edge_frame.schemes return self._edge_frame.schemes
...@@ -1167,6 +1267,9 @@ class DGLGraph(object): ...@@ -1167,6 +1267,9 @@ class DGLGraph(object):
Initializer is a callable that returns a tensor given the shape, data type Initializer is a callable that returns a tensor given the shape, data type
and device context. and device context.
When a subset of the nodes are assigned a new feature, initializer is
used to create feature for rest of the nodes.
Parameters Parameters
---------- ----------
initializer : callable initializer : callable
...@@ -1175,17 +1278,45 @@ class DGLGraph(object): ...@@ -1175,17 +1278,45 @@ class DGLGraph(object):
The feature field name. Default is set an initializer for all the The feature field name. Default is set an initializer for all the
feature fields. feature fields.
See Also Examples
-------- --------
dgl.init.base_initializer
.. note:: Here we use pytorch syntax for demo. The general idea applies
to other frameworks with minor syntax change (e.g. replace
``torch.tensor`` with ``mxnet.ndarray``).
>>> import torch as th
>>> G = dgl.DGLGraph()
>>> G.add_nodes(3)
Set initializer for all node features
>>> G.set_n_initializer(dgl.init.zero_initializer)
Set feature for partial nodes
>>> G.nodes[[0, 2]].data['x'] = th.ones((2, 5))
>>> G.ndata
{'x' : tensor([[1., 1., 1., 1., 1.],
[0., 0., 0., 0., 0.],
[1., 1., 1., 1., 1.]])}
Note
-----
User defined initializer must follow the signature of
:func:`dgl.init.base_initializer() <dgl.init.base_initializer>`
""" """
self._node_frame.set_initializer(initializer, field) self._node_frame.set_initializer(initializer, field)
def set_e_initializer(self, initializer, field=None): def set_e_initializer(self, initializer, field=None):
"""Set the initializer for empty edge features. """Set the initializer for empty edge features.
Initializer is a callable that returns a tensor given the shape, data type Initializer is a callable that returns a tensor given the shape, data
and device context. type and device context.
When a subset of the edges are assigned a new feature, initializer is
used to create feature for rest of the edges.
Parameters Parameters
---------- ----------
...@@ -1195,30 +1326,159 @@ class DGLGraph(object): ...@@ -1195,30 +1326,159 @@ class DGLGraph(object):
The feature field name. Default is set an initializer for all the The feature field name. Default is set an initializer for all the
feature fields. feature fields.
See Also Examples
-------- --------
dgl.init.base_initializer
.. note:: Here we use pytorch syntax for demo. The general idea applies
to other frameworks with minor syntax change (e.g. replace
``torch.tensor`` with ``mxnet.ndarray``).
>>> import torch as th
>>> G = dgl.DGLGraph()
>>> G.add_nodes(3)
>>> G.add_edges([0, 1], 2) # 0->2, 1->2
Set initializer for edge features
>>> G.set_e_initializer(dgl.init.zero_initializer)
Set feature for partial edges
>>> G.edges[1, 2].data['y'] = th.ones((1, 4))
>>> G.edata
{'y' : tensor([[0., 0., 0., 0.],
[1., 1., 1., 1.]])}
Note
-----
User defined initializer must follow the signature of
:func:`dgl.init.base_initializer() <dgl.init.base_initializer>`
""" """
self._edge_frame.set_initializer(initializer, field) self._edge_frame.set_initializer(initializer, field)
@property @property
def nodes(self): def nodes(self):
"""Return a node view that can used to set/get feature data.""" """Return a node view that can used to set/get feature data.
Examples
--------
>>> G = dgl.DGLGraph()
>>> G.add_nodes(3)
Get nodes in graph G:
>>> G.nodes()
tensor([0, 1, 2])
Get feature dictionary of all nodes:
>>> G.nodes[:].data
{}
The above can be abbreviated as
>>> G.ndata
{}
Init all 3 nodes with zero vector(len=5)
.. note:: Here we use pytorch syntax for demo. The general idea applies
to other frameworks with minor syntax change (e.g. replace
``torch.tensor`` with ``mxnet.ndarray``).
>>> import torch as th
>>> G.ndata['x'] = th.zeros((3, 5))
>>> G.ndata['x']
{'x' : tensor([[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.]])}
Use G.nodes to get/set features for some nodes.
>>> G.nodes[[0, 2]].data['x'] = th.ones((2, 5))
>>> G.ndata
{'x' : tensor([[1., 1., 1., 1., 1.],
[0., 0., 0., 0., 0.],
[1., 1., 1., 1., 1.]])}
See Also
--------
dgl.DGLGraph.ndata
"""
return NodeView(self) return NodeView(self)
@property @property
def ndata(self): def ndata(self):
"""Return the data view of all the nodes.""" """Return the data view of all the nodes.
DGLGraph.ndata is an abbreviation of DGLGraph.nodes[:].data
See Also
--------
dgl.DGLGraph.nodes
"""
return self.nodes[:].data return self.nodes[:].data
@property @property
def edges(self): def edges(self):
"""Return a edges view that can used to set/get feature data.""" """Return a edges view that can used to set/get feature data.
>>> G = dgl.DGLGraph()
>>> G.add_nodes(3)
>>> G.add_edges([0, 1], 2) # 0->2, 1->2
Get edges in graph G:
>>> G.edges()
(tensor([0, 1]), tensor([2, 2]))
Get feature dictionary of all edges:
>>> G.edges[:].data
{}
The above can be abbreviated as
>>> G.edata
{}
Init 2 edges with zero vector(len=4)
.. note:: Here we use pytorch syntax for demo. The general idea applies
to other frameworks with minor syntax change (e.g. replace
``torch.tensor`` with ``mxnet.ndarray``).
>>> import torch as th
>>> G.edata['y'] = th.zeros((2, 4))
>>> G.edata
{'y' : tensor([[0., 0., 0., 0.],
[0., 0., 0., 0.]])}
Use G.edges to get/set features for some edges.
>>> G.edges[1, 2].data['y'] = th.ones((1, 4))
>>> G.edata
{'y' : tensor([[0., 0., 0., 0.],
[1., 1., 1., 1.]])}
See Also
--------
dgl.DGLGraph.edata
"""
return EdgeView(self) return EdgeView(self)
@property @property
def edata(self): def edata(self):
"""Return the data view of all the edges.""" """Return the data view of all the edges.
DGLGraph.data is an abbreviation of DGLGraph.edges[:].data
See Also
--------
dgl.DGLGraph.edges
"""
return self.edges[:].data return self.edges[:].data
def set_n_repr(self, hu, u=ALL, inplace=False): def set_n_repr(self, hu, u=ALL, inplace=False):
...@@ -1516,9 +1776,7 @@ class DGLGraph(object): ...@@ -1516,9 +1776,7 @@ class DGLGraph(object):
to other frameworks with minor syntax change (e.g. replace to other frameworks with minor syntax change (e.g. replace
``torch.tensor`` with ``mxnet.ndarray``). ``torch.tensor`` with ``mxnet.ndarray``).
>>> import dgl
>>> import torch as th >>> import torch as th
>>> g = dgl.DGLGraph() >>> g = dgl.DGLGraph()
>>> g.add_nodes(3) >>> g.add_nodes(3)
>>> g.ndata['x'] = th.ones(3, 1) >>> g.ndata['x'] = th.ones(3, 1)
...@@ -1577,7 +1835,6 @@ class DGLGraph(object): ...@@ -1577,7 +1835,6 @@ class DGLGraph(object):
to other frameworks with minor syntax change (e.g. replace to other frameworks with minor syntax change (e.g. replace
``torch.tensor`` with ``mxnet.ndarray``). ``torch.tensor`` with ``mxnet.ndarray``).
>>> import dgl
>>> import torch as th >>> import torch as th
>>> g = dgl.DGLGraph() >>> g = dgl.DGLGraph()
...@@ -1725,7 +1982,6 @@ class DGLGraph(object): ...@@ -1725,7 +1982,6 @@ class DGLGraph(object):
to other frameworks with minor syntax change (e.g. replace to other frameworks with minor syntax change (e.g. replace
``torch.tensor`` with ``mxnet.ndarray``). ``torch.tensor`` with ``mxnet.ndarray``).
>>> import dgl
>>> import torch as th >>> import torch as th
>>> g = dgl.DGLGraph() >>> g = dgl.DGLGraph()
>>> g.add_nodes(3) >>> g.add_nodes(3)
...@@ -1831,7 +2087,6 @@ class DGLGraph(object): ...@@ -1831,7 +2087,6 @@ class DGLGraph(object):
to other frameworks with minor syntax change (e.g. replace to other frameworks with minor syntax change (e.g. replace
``torch.tensor`` with ``mxnet.ndarray``). ``torch.tensor`` with ``mxnet.ndarray``).
>>> import dgl
>>> import torch as th >>> import torch as th
>>> g = dgl.DGLGraph() >>> g = dgl.DGLGraph()
>>> g.add_nodes(3) >>> g.add_nodes(3)
...@@ -1936,13 +2191,12 @@ class DGLGraph(object): ...@@ -1936,13 +2191,12 @@ class DGLGraph(object):
Examples Examples
-------- --------
Create a graph for demo.
.. note:: Here we use pytorch syntax for demo. The general idea applies .. note:: Here we use pytorch syntax for demo. The general idea applies
to other frameworks with minor syntax change (e.g. replace to other frameworks with minor syntax change (e.g. replace
``torch.tensor`` with ``mxnet.ndarray``). ``torch.tensor`` with ``mxnet.ndarray``).
Create a graph for demo.
>>> import dgl
>>> import torch as th >>> import torch as th
>>> g = dgl.DGLGraph() >>> g = dgl.DGLGraph()
>>> g.add_nodes(3) >>> g.add_nodes(3)
...@@ -2034,13 +2288,12 @@ class DGLGraph(object): ...@@ -2034,13 +2288,12 @@ class DGLGraph(object):
Examples Examples
-------- --------
Create a graph for demo.
.. note:: Here we use pytorch syntax for demo. The general idea applies .. note:: Here we use pytorch syntax for demo. The general idea applies
to other frameworks with minor syntax change (e.g. replace to other frameworks with minor syntax change (e.g. replace
``torch.tensor`` with ``mxnet.ndarray``). ``torch.tensor`` with ``mxnet.ndarray``).
Create a graph for demo.
>>> import dgl
>>> import torch as th >>> import torch as th
>>> g = dgl.DGLGraph() >>> g = dgl.DGLGraph()
>>> g.add_nodes(3) >>> g.add_nodes(3)
...@@ -2179,13 +2432,12 @@ class DGLGraph(object): ...@@ -2179,13 +2432,12 @@ class DGLGraph(object):
Examples Examples
-------- --------
Create a graph for demo.
.. note:: Here we use pytorch syntax for demo. The general idea applies .. note:: Here we use pytorch syntax for demo. The general idea applies
to other frameworks with minor syntax change (e.g. replace to other frameworks with minor syntax change (e.g. replace
``torch.tensor`` with ``mxnet.ndarray``). ``torch.tensor`` with ``mxnet.ndarray``).
Create a graph for demo.
>>> import dgl
>>> import torch as th >>> import torch as th
>>> g = dgl.DGLGraph() >>> g = dgl.DGLGraph()
>>> g.add_nodes(4) >>> g.add_nodes(4)
...@@ -2258,13 +2510,12 @@ class DGLGraph(object): ...@@ -2258,13 +2510,12 @@ class DGLGraph(object):
Examples Examples
-------- --------
Create a graph for demo.
.. note:: Here we use pytorch syntax for demo. The general idea applies .. note:: Here we use pytorch syntax for demo. The general idea applies
to other frameworks with minor syntax change (e.g. replace to other frameworks with minor syntax change (e.g. replace
``torch.tensor`` with ``mxnet.ndarray``). ``torch.tensor`` with ``mxnet.ndarray``).
Create a graph for demo.
>>> import dgl
>>> import torch as th >>> import torch as th
>>> g = dgl.DGLGraph() >>> g = dgl.DGLGraph()
>>> g.add_nodes(4) >>> g.add_nodes(4)
...@@ -2333,6 +2584,7 @@ class DGLGraph(object): ...@@ -2333,6 +2584,7 @@ class DGLGraph(object):
Examples Examples
-------- --------
The following example uses PyTorch backend. The following example uses PyTorch backend.
>>> G = dgl.DGLGraph() >>> G = dgl.DGLGraph()
>>> G.add_nodes(5) >>> G.add_nodes(5)
>>> G.add_edges([0, 1, 2, 3, 4], [1, 2, 3, 4, 0]) # 5-node cycle >>> G.add_edges([0, 1, 2, 3, 4], [1, 2, 3, 4, 0]) # 5-node cycle
...@@ -2361,9 +2613,7 @@ class DGLGraph(object): ...@@ -2361,9 +2613,7 @@ class DGLGraph(object):
nodes in the list. nodes in the list.
Equivalent to Equivalent to
`` ``[self.subgraph(nodes_list) for nodes_list in nodes]``
[self.subgraph(nodes_list) for nodes_list in nodes]
``
Parameters Parameters
---------- ----------
...@@ -2409,6 +2659,7 @@ class DGLGraph(object): ...@@ -2409,6 +2659,7 @@ class DGLGraph(object):
Examples Examples
-------- --------
The following example uses PyTorch backend. The following example uses PyTorch backend.
>>> G = dgl.DGLGraph() >>> G = dgl.DGLGraph()
>>> G.add_nodes(5) >>> G.add_nodes(5)
>>> G.add_edges([0, 1, 2, 3, 4], [1, 2, 3, 4, 0]) # 5-node cycle >>> G.add_edges([0, 1, 2, 3, 4], [1, 2, 3, 4, 0]) # 5-node cycle
...@@ -2434,16 +2685,16 @@ class DGLGraph(object): ...@@ -2434,16 +2685,16 @@ class DGLGraph(object):
def adjacency_matrix(self, transpose=False, ctx=F.cpu()): def adjacency_matrix(self, transpose=False, ctx=F.cpu()):
"""Return the adjacency matrix representation of this graph. """Return the adjacency matrix representation of this graph.
By default, a row of returned adjacency matrix represents the destination By default, a row of returned adjacency matrix represents the
of an edge and the column represents the source. destination of an edge and the column represents the source.
When transpose is True, a row represents the source and a column represents When transpose is True, a row represents the source and a column
a destination. represents a destination.
Parameters Parameters
---------- ----------
transpose : bool, optional (default=False) transpose : bool, optional (default=False)
A flag to tranpose the returned adjacency matrix. A flag to transpose the returned adjacency matrix.
ctx : context, optional (default=cpu) ctx : context, optional (default=cpu)
The context of returned adjacency matrix. The context of returned adjacency matrix.
...@@ -2537,13 +2788,12 @@ class DGLGraph(object): ...@@ -2537,13 +2788,12 @@ class DGLGraph(object):
Examples Examples
-------- --------
Construct a graph object for demo.
.. note:: Here we use pytorch syntax for demo. The general idea applies .. note:: Here we use pytorch syntax for demo. The general idea applies
to other frameworks with minor syntax change (e.g. replace to other frameworks with minor syntax change (e.g. replace
``torch.tensor`` with ``mxnet.ndarray``). ``torch.tensor`` with ``mxnet.ndarray``).
Construct a graph object for demo.
>>> import dgl
>>> import torch as th >>> import torch as th
>>> g = dgl.DGLGraph() >>> g = dgl.DGLGraph()
>>> g.add_nodes(3) >>> g.add_nodes(3)
...@@ -2599,13 +2849,12 @@ class DGLGraph(object): ...@@ -2599,13 +2849,12 @@ class DGLGraph(object):
Examples Examples
-------- --------
Construct a graph object for demo.
.. note:: Here we use pytorch syntax for demo. The general idea applies .. note:: Here we use pytorch syntax for demo. The general idea applies
to other frameworks with minor syntax change (e.g. replace to other frameworks with minor syntax change (e.g. replace
``torch.tensor`` with ``mxnet.ndarray``). ``torch.tensor`` with ``mxnet.ndarray``).
Construct a graph object for demo.
>>> import dgl
>>> import torch as th >>> import torch as th
>>> g = dgl.DGLGraph() >>> g = dgl.DGLGraph()
>>> g.add_nodes(3) >>> g.add_nodes(3)
......
...@@ -8,6 +8,9 @@ __all__ = ['base_initializer', 'zero_initializer'] ...@@ -8,6 +8,9 @@ __all__ = ['base_initializer', 'zero_initializer']
def base_initializer(shape, dtype, ctx, range): def base_initializer(shape, dtype, ctx, range):
"""The function signature for feature initializer. """The function signature for feature initializer.
Any customized feature initializer should follow this signature (see
example below).
Parameters Parameters
---------- ----------
shape : tuple of int shape : tuple of int
...@@ -21,9 +24,38 @@ def base_initializer(shape, dtype, ctx, range): ...@@ -21,9 +24,38 @@ def base_initializer(shape, dtype, ctx, range):
The start id and the end id of the features to be initialized. The start id and the end id of the features to be initialized.
The id could be node or edge id depending on the scenario. The id could be node or edge id depending on the scenario.
Note that the step is always None. Note that the step is always None.
Examples
--------
If PyTorch is used as backend, the following code defines an feature
initializer that initializes tensor value to 1
>>> import torch
>>> import dgl
>>> def initializer(shape, dtype, ctx, range):
>>> return torch.ones(shape, dtype=dtype, device=ctx)
>>> g = dgl.DGLGraph()
>>> g.set_n_initializer(initializer)
See Also
--------
dgl.DGLGraph.set_n_initializer
dgl.DGLGraph.set_e_initializer
""" """
raise NotImplementedError raise NotImplementedError
def zero_initializer(shape, dtype, ctx, range): def zero_initializer(shape, dtype, ctx, range):
"""Initialize zero-value features.""" """Zero feature initializer
Examples
--------
>>> import dgl
>>> g = dgl.DGLGraph()
>>> g.set_n_initializer(dgl.init.zero_initializer)
See Also
--------
dgl.DGLGraph.set_n_initializer
dgl.DGLGraph.set_e_initializer
"""
return F.zeros(shape, dtype, ctx) return F.zeros(shape, dtype, ctx)
...@@ -19,12 +19,12 @@ def bfs_nodes_generator(graph, source, reversed=False): ...@@ -19,12 +19,12 @@ def bfs_nodes_generator(graph, source, reversed=False):
source : list, tensor of nodes source : list, tensor of nodes
Source nodes. Source nodes.
reversed : bool, default False reversed : bool, default False
If true, traverse following the in-edge direction. If True, traverse following the in-edge direction.
Returns Returns
------- -------
list of node frontiers list of node frontiers
Each node frontier is a list, tensor of nodes. Each node frontier is a list or tensor of node ids.
Examples Examples
-------- --------
...@@ -32,10 +32,10 @@ def bfs_nodes_generator(graph, source, reversed=False): ...@@ -32,10 +32,10 @@ def bfs_nodes_generator(graph, source, reversed=False):
:: ::
2 - 4 2 - 4
/ \ / \\
0 - 1 - 3 - 5 0 - 1 - 3 - 5
>>> g = ... # the graph above >>> g = dgl.DGLGraph([(0, 1), (1, 2), (1, 3), (2, 3), (2, 4), (3, 5)])
>>> list(dgl.bfs_nodes_generator(g, 0)) >>> list(dgl.bfs_nodes_generator(g, 0))
[tensor([0]), tensor([1]), tensor([2, 3]), tensor([4, 5])] [tensor([0]), tensor([1]), tensor([2, 3]), tensor([4, 5])]
""" """
...@@ -58,12 +58,12 @@ def bfs_edges_generator(graph, source, reversed=False): ...@@ -58,12 +58,12 @@ def bfs_edges_generator(graph, source, reversed=False):
source : list, tensor of nodes source : list, tensor of nodes
Source nodes. Source nodes.
reversed : bool, default False reversed : bool, default False
If true, traverse following the in-edge direction. If True, traverse following the in-edge direction.
Returns Returns
------- -------
list of edge frontiers list of edge frontiers
Each edge frontier is a list, tensor of edges. Each edge frontier is a list or tensor of edge ids.
Examples Examples
-------- --------
...@@ -72,10 +72,10 @@ def bfs_edges_generator(graph, source, reversed=False): ...@@ -72,10 +72,10 @@ def bfs_edges_generator(graph, source, reversed=False):
:: ::
2 - 4 2 - 4
/ \ / \\
0 - 1 - 3 - 5 0 - 1 - 3 - 5
>>> g = ... # the graph above >>> g = dgl.DGLGraph([(0, 1), (1, 2), (1, 3), (2, 3), (2, 4), (3, 5)])
>>> list(dgl.bfs_edges_generator(g, 0)) >>> list(dgl.bfs_edges_generator(g, 0))
[tensor([0]), tensor([1, 2]), tensor([4, 5])] [tensor([0]), tensor([1, 2]), tensor([4, 5])]
""" """
...@@ -96,12 +96,12 @@ def topological_nodes_generator(graph, reversed=False): ...@@ -96,12 +96,12 @@ def topological_nodes_generator(graph, reversed=False):
graph : DGLGraph graph : DGLGraph
The graph object. The graph object.
reversed : bool, optional reversed : bool, optional
If true, traverse following the in-edge direction. If True, traverse following the in-edge direction.
Returns Returns
------- -------
list of node frontiers list of node frontiers
Each node frontier is a list, tensor of nodes. Each node frontier is a list or tensor of node ids.
Examples Examples
-------- --------
...@@ -109,10 +109,10 @@ def topological_nodes_generator(graph, reversed=False): ...@@ -109,10 +109,10 @@ def topological_nodes_generator(graph, reversed=False):
:: ::
2 - 4 2 - 4
/ \ / \\
0 - 1 - 3 - 5 0 - 1 - 3 - 5
>>> g = ... # the graph above >>> g = dgl.DGLGraph([(0, 1), (1, 2), (1, 3), (2, 3), (2, 4), (3, 5)])
>>> list(dgl.topological_nodes_generator(g)) >>> list(dgl.topological_nodes_generator(g))
[tensor([0]), tensor([1]), tensor([2]), tensor([3, 4]), tensor([5])] [tensor([0]), tensor([1]), tensor([2]), tensor([3, 4]), tensor([5])]
""" """
...@@ -138,12 +138,12 @@ def dfs_edges_generator(graph, source, reversed=False): ...@@ -138,12 +138,12 @@ def dfs_edges_generator(graph, source, reversed=False):
source : list, tensor of nodes source : list, tensor of nodes
Source nodes. Source nodes.
reversed : bool, optional reversed : bool, optional
If true, traverse following the in-edge direction. If True, traverse following the in-edge direction.
Returns Returns
------- -------
list of edge frontiers list of edge frontiers
Each edge frontier is a list, tensor of edges. Each edge frontier is a list or tensor of edge ids.
Examples Examples
-------- --------
...@@ -151,14 +151,14 @@ def dfs_edges_generator(graph, source, reversed=False): ...@@ -151,14 +151,14 @@ def dfs_edges_generator(graph, source, reversed=False):
:: ::
2 - 4 2 - 4
/ \ / \\
0 - 1 - 3 - 5 0 - 1 - 3 - 5
Edge addition order [(0, 1), (1, 2), (1, 3), (2, 3), (2, 4), (3, 5)] Edge addition order [(0, 1), (1, 2), (1, 3), (2, 3), (2, 4), (3, 5)]
>>> g = ... # the graph above >>> g = dgl.DGLGraph([(0, 1), (1, 2), (1, 3), (2, 3), (2, 4), (3, 5)])
>>> list(dgl.dfs_edges_generator(g)) >>> list(dgl.dfs_edges_generator(g, 0))
[tensor([0]), tensor([1]), tensor([4]), tensor([3]), tensor([5]), tensor([2])] [tensor([0]), tensor([1]), tensor([3]), tensor([5]), tensor([4])]
""" """
ghandle = graph._graph._handle ghandle = graph._graph._handle
source = utils.toindex(source).todgltensor() source = utils.toindex(source).todgltensor()
...@@ -179,10 +179,10 @@ def dfs_labeled_edges_generator( ...@@ -179,10 +179,10 @@ def dfs_labeled_edges_generator(
There are three labels: FORWARD(0), REVERSE(1), NONTREE(2) There are three labels: FORWARD(0), REVERSE(1), NONTREE(2)
A FORWARD edge is one in which `u` has been visisted but `v` has not. A A FORWARD edge is one in which `u` has been visised but `v` has not. A
REVERSE edge is one in which both `u` and `v` have been visisted and the REVERSE edge is one in which both `u` and `v` have been visited and the
edge is in the DFS tree. A NONTREE edge is one in which both `u` and `v` edge is in the DFS tree. A NONTREE edge is one in which both `u` and `v`
have been visisted but the edge is NOT in the DFS tree. have been visited but the edge is NOT in the DFS tree.
See ``networkx``'s :func:`dfs_labeled_edges See ``networkx``'s :func:`dfs_labeled_edges
<networkx.algorithms.traversal.depth_first_search.dfs_labeled_edges>` <networkx.algorithms.traversal.depth_first_search.dfs_labeled_edges>`
...@@ -211,9 +211,25 @@ def dfs_labeled_edges_generator( ...@@ -211,9 +211,25 @@ def dfs_labeled_edges_generator(
Returns Returns
------- -------
list of edge frontiers list of edge frontiers
Each edge frontier is a list, tensor of edges. Each edge frontier is a list or tensor of edge ids.
list of list of int list of list of int
Label of each edge, organized in the same as the edge frontiers. Label of each edge, organized in the same order as the edge frontiers.
Examples
--------
Given a graph (directed, edges from small node id to large):
::
2 - 4
/ \\
0 - 1 - 3 - 5
Edge addition order [(0, 1), (1, 2), (1, 3), (2, 3), (2, 4), (3, 5)]
>>> g = dgl.DGLGraph([(0, 1), (1, 2), (1, 3), (2, 3), (2, 4), (3, 5)])
>>> list(dgl.dfs_labeled_edges_generator(g, 0, has_nontree_edge=True))
(tensor([0]), tensor([1]), tensor([3]), tensor([5]), tensor([4]), tensor([2])),
(tensor([0]), tensor([0]), tensor([0]), tensor([0]), tensor([0]), tensor([2]))
""" """
ghandle = graph._graph._handle ghandle = graph._graph._handle
source = utils.toindex(source).todgltensor() source = utils.toindex(source).todgltensor()
......
...@@ -12,18 +12,11 @@ NodeSpace = namedtuple('NodeSpace', ['data']) ...@@ -12,18 +12,11 @@ NodeSpace = namedtuple('NodeSpace', ['data'])
class NodeView(object): class NodeView(object):
"""A NodeView class to act as G.nodes for a DGLGraph. """A NodeView class to act as G.nodes for a DGLGraph.
Compared with networkx's NodeView, DGL's NodeView is not Can be used to get a list of current nodes and get and set node data.
a map. DGL's NodeView supports creating data view from
a given list of nodes.
Parameters See Also
----------
graph : DGLGraph
The graph.
Examples
-------- --------
TBD dgl.DGLGraph.nodes
""" """
__slots__ = ['_graph'] __slots__ = ['_graph']
...@@ -79,6 +72,14 @@ class NodeDataView(MutableMapping): ...@@ -79,6 +72,14 @@ class NodeDataView(MutableMapping):
EdgeSpace = namedtuple('EdgeSpace', ['data']) EdgeSpace = namedtuple('EdgeSpace', ['data'])
class EdgeView(object): class EdgeView(object):
"""A EdgeView class to act as G.edges for a DGLGraph.
Can be used to get a list of current edges and get and set edge data.
See Also
--------
dgl.DGLGraph.edges
"""
__slots__ = ['_graph'] __slots__ = ['_graph']
def __init__(self, graph): def __init__(self, graph):
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment