diff --git a/.gitignore b/.gitignore index 0d20b6487c61..19a9621496eb 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,107 @@ -*.pyc +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ + +*.swp +*.swo diff --git a/LICENSE b/LICENSE new file mode 100644 index 000000000000..261eeb9e9f8b --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/mxnet/util.py b/examples/mxnet/util.py similarity index 100% rename from mxnet/util.py rename to examples/mxnet/util.py diff --git a/pytorch/gan.py b/examples/pytorch/gan.py similarity index 100% rename from pytorch/gan.py rename to examples/pytorch/gan.py diff --git a/pytorch/gcn.py b/examples/pytorch/gcn.py similarity index 100% rename from pytorch/gcn.py rename to examples/pytorch/gcn.py diff --git a/pytorch/model.py b/examples/pytorch/model.py similarity index 100% rename from pytorch/model.py rename to examples/pytorch/model.py diff --git a/pytorch/test.py b/examples/pytorch/test.py similarity index 100% rename from pytorch/test.py rename to examples/pytorch/test.py diff --git a/pytorch/treernn.py b/examples/pytorch/treernn.py similarity index 100% rename from pytorch/treernn.py rename to examples/pytorch/treernn.py diff --git a/pytorch/util.py b/examples/pytorch/util.py similarity index 100% rename from pytorch/util.py rename to examples/pytorch/util.py diff --git a/graph.py b/graph.py deleted file mode 100644 index 0bcb17336b81..000000000000 --- a/graph.py +++ /dev/null @@ -1,125 +0,0 @@ -import networkx as nx -from networkx.classes.digraph import DiGraph - -class dgl_Graph(DiGraph): - ''' - Functions: - - m_func: per edge (u, v), default is u['state'] - - u_func: per node u, default is RNN(m, u['state']) - ''' - def __init__(self, *args, **kargs): - super(dgl_Graph, self).__init__(*args, **kargs) - self.m_func = DefaultMessageModule() - self.u_func = DefaultUpdateModule() - self.readout_func = DefaultReadoutModule() - self.init_reprs() - - def init_reprs(self, h_init=None): - for n in self.nodes: - self.set_repr(n, h_init) - - def set_repr(self, u, h_u, name='state'): - assert u in self.nodes - kwarg = {name: h_u} - self.add_node(u, **kwarg) - - def get_repr(self, u, name='state'): - assert u in self.nodes - return self.nodes[u][name] - - def _nodes_or_all(self, nodes='all'): - return self.nodes() if nodes == 'all' else nodes - - def _edges_or_all(self, edges='all'): - return self.edges() if edges == 'all' else edges - - def register_message_func(self, message_func, edges='all', batched=False): - if edges == 'all': - self.m_func = message_func - else: - for e in self.edges: - self.edges[e]['m_func'] = message_func - - def register_update_func(self, update_func, nodes='all', batched=False): - if nodes == 'all': - self.u_func = update_func - else: - for n in nodes: - self.node[n]['u_func'] = update_func - - def register_readout_func(self, readout_func): - self.readout_func = readout_func - - def readout(self, nodes='all', **kwargs): - nodes_state = [] - nodes = self._nodes_or_all(nodes) - for n in nodes: - nodes_state.append(self.get_repr(n)) - return self.readout_func(nodes_state, **kwargs) - - def sendto(self, u, v): - """Compute message on edge u->v - Args: - u: source node - v: destination node - """ - f_msg = self.edges[(u, v)].get('m_func', self.m_func) - m = f_msg(self.get_repr(u)) - self.edges[(u, v)]['msg'] = m - - def sendto_ebunch(self, ebunch): - """Compute message on edge u->v - Args: - ebunch: a bunch of edges - """ - #TODO: simplify the logics - for u, v in ebunch: - f_msg = self.edges[(u, v)].get('m_func', self.m_func) - m = f_msg(self.get_repr(u)) - self.edges[(u, v)]['msg'] = m - - def recvfrom(self, u, nodes): - """Update u by nodes - Args: - u: node to be updated - nodes: nodes with pre-computed messages to u - """ - m = [self.edges[(v, u)]['msg'] for v in nodes] - f_update = self.nodes[u].get('u_func', self.u_func) - x_new = f_update(self.get_repr(u), m) - self.set_repr(u, x_new) - - def update_by_edge(self, e): - u, v = e - self.sendto(u, v) - self.recvfrom(v, [u]) - - def update_to(self, u): - """Pull messages from 1-step away neighbors of u""" - assert u in self.nodes - - for v in self.pred[u]: - self.sendto(v, u) - self.recvfrom(u, list(self.pred[u])) - - def update_from(self, u): - """Update u's 1-step away neighbors""" - assert u in self.nodes - for v in self.succ[u]: - self.update_to(v) - - def update_all_step(self): - self.sendto_ebunch(self.edges) - for u in self.nodes: - self.recvfrom(u, list(self.pred[u])) - - def draw(self): - from networkx.drawing.nx_agraph import graphviz_layout - - pos = graphviz_layout(self, prog='dot') - nx.draw(self, pos, with_labels=True) - - def print_all(self): - for n in self.nodes: - print(n, self.nodes[n]) - print() diff --git a/python/dgl/__init__.py b/python/dgl/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/python/dgl/backend/__init__.py b/python/dgl/backend/__init__.py new file mode 100644 index 000000000000..84618e61deff --- /dev/null +++ b/python/dgl/backend/__init__.py @@ -0,0 +1,2 @@ +__backend__ = 'numpy' +from dgl.backend.numpy import * diff --git a/python/dgl/backend/numpy.py b/python/dgl/backend/numpy.py new file mode 100644 index 000000000000..09c723d0554c --- /dev/null +++ b/python/dgl/backend/numpy.py @@ -0,0 +1,10 @@ +from __future__ import absolute_import + +import numpy as np +import scipy as sp + +Tensor = np.ndarray +SparseTensor = sp.sparse.spmatrix + +def asnumpy(a): + return a diff --git a/python/dgl/graph.py b/python/dgl/graph.py new file mode 100644 index 000000000000..10b80038fcf1 --- /dev/null +++ b/python/dgl/graph.py @@ -0,0 +1,322 @@ +"""Base graph class specialized for neural networks on graphs. +""" + +import networkx as nx +from networkx.classes.digraph import DiGraph + +import dgl.backend as F +from dgl.backend import Tensor +import dgl.utils as utils + +__MSG__ = "__msg__" +__REPR__ = "__repr__" +__MFUNC__ = "__mfunc__" +__UFUNC__ = "__ufunc__" + +class DGLGraph(DiGraph): + """Base graph class specialized for neural networks on graphs. + + TODO(minjie): document of multi-node and multi-edge syntax. + + Parameters + ---------- + data : graph data + Data to initialize graph. Same as networkx's semantics. + attr : keyword arguments, optional + Attributes to add to graph as key=value pairs. + """ + def __init__(self, graph_data=None, **attr): + super(DGLGraph, self).__init__(graph_data, **attr) + self.m_func = None + self.u_func = None + self.readout_func = None + + def init_reprs(self, h_init=None): + print("[DEPRECATED]: please directly set node attrs " + "(e.g. g.nodes[node]['x'] = val).") + for n in self.nodes: + self.set_repr(n, h_init) + + def set_repr(self, u, h_u, name=__REPR__): + print("[DEPRECATED]: please directly set node attrs " + "(e.g. g.nodes[node]['x'] = val).") + assert u in self.nodes + kwarg = {name: h_u} + self.add_node(u, **kwarg) + + def get_repr(self, u, name=__REPR__): + print("[DEPRECATED]: please directly get node attrs " + "(e.g. g.nodes[node]['x']).") + assert u in self.nodes + return self.nodes[u][name] + + def register_message_func(self, message_func, edges='all', batchable=False): + """Register computation on edges. + + The message function should be compatible with following signature: + + (node_reprs, node_reprs, edge_reprs) -> edge_reprs + + It computes the new edge representations (the same concept as messages) + using the representations of the source node, target node and the edge + itself. All node_reprs and edge_reprs are dictionaries. + + Parameters + ---------- + message_func : callable + Message function on the edge. + edges : str, pair of nodes, pair of containers, pair of tensors + The edges for which the message function is registered. Default is + registering for all the edges. Registering for multiple edges is + supported. + batchable : bool + Whether the provided message function allows batch computing. + + Examples + -------- + + Register for all edges. + >>> g.register_message_func(mfunc) + + Register for a specific edge. + >>> g.register_message_func(mfunc, (u, v)) + + Register for multiple edges. + >>> u = [u1, u2, u3, ...] + >>> v = [v1, v2, v3, ...] + >>> g.register_message_func(mfunc, (u, v)) + """ + if edges == 'all': + self.m_func = message_func + else: + for e in edges: + self.edges[e][__MFUNC__] = message_func + + def register_update_func(self, update_func, nodes='all', batchable=False): + """Register computation on nodes. + + The update function should be compatible with following signature: + + (edge_reprs, node_reprs) -> node_reprs + + It computes the new node representations using the representations + of the in-coming edges (the same concept as messages) and the node + itself. All node_reprs and edge_reprs are dictionaries. + + Parameters + ---------- + update_func : callable + Update function on the node. + nodes : str, node, container or tensor + The nodes for which the update function is registered. Default is + registering for all the nodes. Registering for multiple nodes is + supported. + batchable : bool + Whether the provided update function allows batch computing. + + Examples + -------- + + Register for all nodes. + >>> g.register_update_func(ufunc) + + Register for a specific node. + >>> g.register_update_func(ufunc, u) + + Register for multiple nodes. + >>> u = [u1, u2, u3, ...] + >>> g.register_update_func(ufunc, u) + """ + if nodes == 'all': + self.u_func = update_func + else: + for n in nodes: + self.nodes[n][__UFUNC__] = update_func + + def register_readout_func(self, readout_func): + """Register computation on the whole graph. + + The readout_func should be compatible with following signature: + + (node_reprs, edge_reprs) -> any + + It takes the representations of selected nodes and edges and + returns readout values. + + NOTE: readout function can be implemented outside of DGLGraph. + One can simple get the node/edge reprs of the graph and perform + arbitrary computation. + + Parameters + ---------- + readout_func : callable + The readout function. + + See Also + -------- + readout + """ + self.readout_func = readout_func + + def readout(self, nodes='all', edges='all'): + """Trigger the readout function on the specified nodes/edges. + + Parameters + ---------- + nodes : str, node, container or tensor + The nodes to get reprs from. + edges : str, pair of nodes, pair of containers or pair of tensors + The edges to get reprs from. + """ + nodes = self._nodes_or_all(nodes) + edges = self._nodes_or_all(nodes) + assert self.readout_func is not None, + "Readout function is not registered." + # TODO(minjie): tensorize following loop. + nstates = [self.nodes[n] for n in nodes] + estates = [self.edges[e] for e in edges] + return self.readout_func(nstates, estates) + + def sendto(self, u, v): + """Trigger the message function on edge u->v + + Parameters + ---------- + u : node, container or tensor + The source node(s). + v : node, container or tensor + The destination node(s). + """ + # TODO(minjie): tensorize the loop. + for uu, vv in utils.edge_iter(u, v): + f_msg = self.edges[uu, vv].get(__MFUNC__, self.m_func) + assert f_msg is not None, + "message function not registered for edge (%s->%s)" % (uu, vv) + m = f_msg(self.nodes[uu], self.nodes[vv], self.edges[uu, vv]) + self.edges[uu, vv][__MSG__] = m + + def recvfrom(self, u, preds=None): + """Trigger the update function on node u. + + It computes the new node state using the messages and edge + states from preds->u. If `u` is one node, `preds` is a list + of predecessors. If `u` is a container or tensor of nodes, + then `preds[i]` should be the predecessors of `u[i]`. + + Parameters + ---------- + u : node, container or tensor + The node to be updated. + preds : container + Nodes with pre-computed messages to u. Default is all + the predecessors. + """ + u_is_container = type(u) in (list, tuple) + u_is_tensor = isinstance(u, Tensor) + # TODO(minjie): tensorize the loop. + for i, uu in enumerate(utils.node_iter(u)): + if preds is None: + v = list(self.pred[uu]) + elif u_is_container or u_is_tensor: + v = preds[i] + else: + v = preds + # TODO(minjie): tensorize the message batching + m = [self.edges[vv, uu][__MSG__] for vv in v] + f_update = self.nodes[uu].get(__UFUNC__, self.u_func) + assert f_update is not None, + "Update function not registered for node %s" % uu + self.nodes[uu] = f_update(self.nodes[uu], m) + + def update_by_edge(self, u, v): + """Trigger the message function on u->v and update v. + + Parameters + ---------- + u : node, container or tensor + The source node(s). + v : node, container or tensor + The destination node(s). + """ + self.sendto(u, v) + # TODO(minjie): tensorize the following loops. + preds = defaultdict(list) + for uu, vv in utils.edge_iter(u, v): + preds[vv].append(uu) + dst = preds.keys() + src = [preds[d] for d in dst] + self.recvfrom(dst, src) + + def update_to(self, u): + """Pull messages from the node's predecessors and then update it. + + Parameters + ---------- + u : node, container or tensor + The node to be updated. + """ + # TODO(minjie): tensorize the following code. + for uu in utils.node_iter(u): + assert uu in self.nodes + preds = list(self.pred[uu]) + self.sendto(preds, uu) + self.recvfrom(uu, preds) + + def update_from(self, u): + """Send message from the node to its successors and update them. + + Parameters + ---------- + u : node, container or tensor + The node that sends out messages. + """ + # TODO(minjie): tensorize the following code. + for uu in utils.node_iter(u): + assert uu in self.nodes + for v in self.succ[uu]: + self.update_by_edge(uu, v) + + def update_all(self): + """Send messages through all the edges and update all nodes. + """ + # TODO(minjie): tensorize the following code. + u = [uu for uu, _ in self.edges] + v = [vv for _, vv in self.edges] + self.sendto(u, v) + self.recvfrom(v) + + def propagate(self, iterator='bfs'): + """Propagate messages and update nodes using iterator. + + A convenient function for passing messages and updating + nodes according to the iterator. The iterator can be + any of the pre-defined iterators ('bfs', 'dfs', 'pre-order', + 'mid-order', 'post-order'). The computation will be unrolled + in the backend efficiently. User can also provide custom + iterator that generates the edges and nodes. + + Parameters + ---------- + iterator : str or generator of steps. + The iterator of the graph. + """ + if isinstance(iterator, str): + # TODO Call pre-defined routine to unroll the computation. + raise RuntimeError('Not implemented.') + else: + # NOTE: the iteration can return multiple edges at each step. + for u, v in iterator: + self.update_by_edge(u, v) + + def draw(self): + """Plot the graph using dot.""" + from networkx.drawing.nx_agraph import graphviz_layout + + pos = graphviz_layout(self, prog='dot') + nx.draw(self, pos, with_labels=True) + + def _nodes_or_all(self, nodes='all'): + return self.nodes() if nodes == 'all' else nodes + + def _edges_or_all(self, edges='all'): + return self.edges() if edges == 'all' else edges diff --git a/python/dgl/utils.py b/python/dgl/utils.py new file mode 100644 index 000000000000..9fbaee732b32 --- /dev/null +++ b/python/dgl/utils.py @@ -0,0 +1,43 @@ +import dgl.backend as F +from dgl.backend import Tensor + +def node_iter(n): + n_is_container = type(n) in (list, tuple) + n_is_tensor = isinstance(n, Tensor) + if n_is_tensor: + n = F.asnumpy(n) + n_is_tensor = False + n_is_container = True + if n_is_container: + for nn in n: + yield nn + else: + yield n + +def edge_iter(u, v): + u_is_container = type(u) in (list, tuple) + v_is_container = type(v) in (list, tuple) + u_is_tensor = isinstance(u, Tensor) + v_is_tensor = isinstance(v, Tensor) + if u_is_tensor: + u = F.asnumpy(u) + u_is_tensor = False + u_is_container = True + if v_is_tensor: + v = F.asnumpy(v) + v_is_tensor = False + v_is_container = True + if u_is_container and v_is_container: + # many-many + for uu, vv in zip(u, v): + yield uu, vv + elif u_is_container and not v_is_container: + # many-one + for uu in u: + yield uu, v + elif not u_is_container and v_is_container: + # one-many + for vv in v: + yield u, vv + else: + yield u, v