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)
This diff is collapsed.
...@@ -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