adbdgl-adapter


Nameadbdgl-adapter JSON
Version 3.0.1 PyPI version JSON
download
home_page
SummaryConvert ArangoDB graphs to DGL & vice-versa.
upload_time2024-01-19 15:04:43
maintainer
docs_urlNone
author
requires_python>=3.8
licenseApache 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: You must give any other recipients of the Work or Derivative Works a copy of this License; and You must cause any modified files to carry prominent notices stating that You changed the files; and 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 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.
keywords arangodb dgl deep graph library adapter
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # ArangoDB-DGL Adapter

[![build](https://github.com/arangoml/dgl-adapter/actions/workflows/build.yml/badge.svg?branch=master)](https://github.com/arangoml/dgl-adapter/actions/workflows/build.yml)
[![CodeQL](https://github.com/arangoml/dgl-adapter/actions/workflows/analyze.yml/badge.svg?branch=master)](https://github.com/arangoml/dgl-adapter/actions/workflows/analyze.yml)
[![Coverage Status](https://coveralls.io/repos/github/arangoml/dgl-adapter/badge.svg?branch=master)](https://coveralls.io/github/arangoml/dgl-adapter)
[![Last commit](https://img.shields.io/github/last-commit/arangoml/dgl-adapter)](https://github.com/arangoml/dgl-adapter/commits/master)

[![PyPI version badge](https://img.shields.io/pypi/v/adbdgl-adapter?color=3775A9&style=for-the-badge&logo=pypi&logoColor=FFD43B)](https://pypi.org/project/adbdgl-adapter/)
[![Python versions badge](https://img.shields.io/pypi/pyversions/adbdgl-adapter?color=3776AB&style=for-the-badge&logo=python&logoColor=FFD43B)](https://pypi.org/project/adbdgl-adapter/)

[![License](https://img.shields.io/github/license/arangoml/dgl-adapter?color=9E2165&style=for-the-badge)](https://github.com/arangoml/dgl-adapter/blob/master/LICENSE)
[![Code style: black](https://img.shields.io/static/v1?style=for-the-badge&label=code%20style&message=black&color=black)](https://github.com/psf/black)
[![Downloads](https://img.shields.io/pepy/dt/adbdgl-adapter?style=for-the-badge&color=282661
)](https://pepy.tech/project/adbdgl-adapter)


<a href="https://www.arangodb.com/" rel="arangodb.com">![](https://raw.githubusercontent.com/arangoml/dgl-adapter/master/examples/assets/adb_logo.png)</a>
<a href="https://www.dgl.ai/" rel="dgl.ai"><img src="https://raw.githubusercontent.com/arangoml/dgl-adapter/master/examples/assets/dgl_logo.png" width=40% /></a>

The ArangoDB-DGL Adapter exports Graphs from ArangoDB, the multi-model database for graph & beyond, into Deep Graph Library (DGL), a python package for graph neural networks, and vice-versa.

Note: The ArangoDB-DGL Adapter currently only supports the use of PyTorch as the [DGL backend](https://docs.dgl.ai/en/0.8.x/install/#backends). Support for MXNet and Tensorflow will be added in the future.

## About DGL

The Deep Graph Library (DGL) is an easy-to-use, high performance and scalable Python package for deep learning on graphs. DGL is framework agnostic, meaning if a deep graph model is a component of an end-to-end application, the rest of the logics can be implemented in any major frameworks, such as PyTorch, Apache MXNet or TensorFlow.

* [Website](https://www.dgl.ai/)
* [Documentation](https://docs.dgl.ai/)
* [Highlighted Features](https://github.com/dmlc/dgl#highlighted-features)

## Installation

#### Latest Release
```
pip install adbdgl-adapter
```
#### Current State
```
pip install git+https://github.com/arangoml/dgl-adapter.git
```

##  Quickstart

[![Open In Collab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/arangoml/dgl-adapter/blob/master/examples/ArangoDB_DGL_Adapter.ipynb)

Also available as an ArangoDB Lunch & Learn session: [Graph & Beyond Course #2.8](https://www.arangodb.com/resources/lunch-sessions/graph-beyond-lunch-break-2-8-dgl-adapter/)

```py
import dgl
import torch
import pandas

from arango import ArangoClient
from adbdgl_adapter import ADBDGL_Adapter, ADBDGL_Controller
from adbdgl_adapter.encoders import IdentityEncoder, CategoricalEncoder

# Connect to ArangoDB
db = ArangoClient().db()

# Instantiate the adapter
adbdgl_adapter = ADBDGL_Adapter(db)

# Create a DGL Heterogeneous Graph
fake_hetero = dgl.heterograph({
    ("user", "follows", "user"): (torch.tensor([0, 1]), torch.tensor([1, 2])),
    ("user", "follows", "topic"): (torch.tensor([1, 1]), torch.tensor([1, 2])),
    ("user", "plays", "game"): (torch.tensor([0, 3]), torch.tensor([3, 4])),
})
fake_hetero.nodes["user"].data["features"] = torch.tensor([21, 44, 16, 25])
fake_hetero.nodes["user"].data["label"] = torch.tensor([1, 2, 0, 1])
fake_hetero.nodes["game"].data["features"] = torch.tensor([[0, 0], [0, 1], [1, 0], [1, 1], [1, 1]])
fake_hetero.edges[("user", "plays", "game")].data["features"] = torch.tensor([[6, 1], [1000, 0]])
```

### DGL to ArangoDB
```py
############################
# 1.1: without a Metagraph #
############################

adb_g = adbdgl_adapter.dgl_to_arangodb("FakeHetero", fake_hetero)

#########################
# 1.2: with a Metagraph #
#########################

# Specifying a Metagraph provides customized adapter behaviour
metagraph = {
    "nodeTypes": {
        "user": {
            "features": "user_age",  # 1) you can specify a string value for attribute renaming
            "label": label_tensor_to_2_column_dataframe,  # 2) you can specify a function for user-defined handling, as long as the function returns a Pandas DataFrame
        },
        # 3) You can specify set of strings if you want to preserve the same DGL attribute names for the node/edge type
        "game": {"features"} # this is equivalent to {"features": "features"}
    },
    "edgeTypes": {
        ("user", "plays", "game"): {
            # 4) you can specify a list of strings for tensor dissasembly (if you know the number of node/edge features in advance)
            "features": ["hours_played", "is_satisfied_with_game"]
        },
    },
}

def label_tensor_to_2_column_dataframe(dgl_tensor: torch.Tensor, adb_df: pandas.DataFrame) -> pandas.DataFrame:
    """A user-defined function to create two
    ArangoDB attributes out of the 'user' label tensor

    :param dgl_tensor: The DGL Tensor containing the data
    :type dgl_tensor: torch.Tensor
    :param adb_df: The ArangoDB DataFrame to populate, whose
        size is preset to the length of **dgl_tensor**.
    :type adb_df: pandas.DataFrame
    :return: The populated ArangoDB DataFrame
    :rtype: pandas.DataFrame
    """
    label_map = {0: "Class A", 1: "Class B", 2: "Class C"}

    adb_df["label_num"] = dgl_tensor.tolist()
    adb_df["label_str"] = adb_df["label_num"].map(label_map)

    return adb_df


adb_g = adbdgl_adapter.dgl_to_arangodb("FakeHetero", fake_hetero, metagraph, explicit_metagraph=False)

#######################################################
# 1.3: with a Metagraph and `explicit_metagraph=True` #
#######################################################

# With `explicit_metagraph=True`, the node & edge types omitted from the metagraph will NOT be converted to ArangoDB.
adb_g = adbdgl_adapter.dgl_to_arangodb("FakeHetero", fake_hetero, metagraph, explicit_metagraph=True)

########################################
# 1.4: with a custom ADBDGL Controller #
########################################

class Custom_ADBDGL_Controller(ADBDGL_Controller):
    def _prepare_dgl_node(self, dgl_node: dict, node_type: str) -> dict:
        """Optionally modify a DGL node object before it gets inserted into its designated ArangoDB collection.

        :param dgl_node: The DGL node object to (optionally) modify.
        :param node_type: The DGL Node Type of the node.
        :return: The DGL Node object
        """
        dgl_node["foo"] = "bar"
        return dgl_node

    def _prepare_dgl_edge(self, dgl_edge: dict, edge_type: tuple) -> dict:
        """Optionally modify a DGL edge object before it gets inserted into its designated ArangoDB collection.

        :param dgl_edge: The DGL edge object to (optionally) modify.
        :param edge_type: The Edge Type of the DGL edge. Formatted
            as (from_collection, edge_collection, to_collection)
        :return: The DGL Edge object
        """
        dgl_edge["bar"] = "foo"
        return dgl_edge


adb_g = ADBDGL_Adapter(db, Custom_ADBDGL_Controller()).dgl_to_arangodb("FakeHetero", fake_hetero)
```

### ArangoDB to DGL
```py
# Start from scratch!
db.delete_graph("FakeHetero", drop_collections=True, ignore_missing=True)
adbdgl_adapter.dgl_to_arangodb("FakeHetero", fake_hetero)

#######################
# 2.1: via Graph name #
#######################

# Due to risk of ambiguity, this method does not transfer attributes
dgl_g = adbdgl_adapter.arangodb_graph_to_dgl("FakeHetero")

#############################
# 2.2: via Collection names #
#############################

# Due to risk of ambiguity, this method does not transfer attributes
dgl_g = adbdgl_adapter.arangodb_collections_to_dgl("FakeHetero", v_cols={"user", "game"}, e_cols={"plays"})

######################
# 2.3: via Metagraph #
######################

# Transfers attributes "as is", meaning they are already formatted to DGL data standards.
# Learn more about the DGL Data Standards here: https://docs.dgl.ai/guide/graph.html#guide-graph
metagraph_v1 = {
    "vertexCollections": {
        # Move the "features" & "label" ArangoDB attributes to DGL as "features" & "label" Tensors
        "user": {"features", "label"}, # equivalent to {"features": "features", "label": "label"}
        "game": {"dgl_game_features": "features"},
        "topic": {},
    },
    "edgeCollections": {
        "plays": {"dgl_plays_features": "features"}, 
        "follows": {}
    },
}

dgl_g = adbdgl_adapter.arangodb_to_dgl("FakeHetero", metagraph_v1)

#################################################
# 2.4: via Metagraph with user-defined encoders #
#################################################

# Transforms attributes via user-defined encoders
metagraph_v2 = {
    "vertexCollections": {
        "Movies": {
            "features": {  # Build a feature matrix from the "Action" & "Drama" document attributes
                "Action": IdentityEncoder(dtype=torch.long),
                "Drama": IdentityEncoder(dtype=torch.long),
            },
            "label": "Comedy",
        },
        "Users": {
            "features": {
                "Gender": CategoricalEncoder(), # CategoricalEncoder(mapping={"M": 0, "F": 1}),
                "Age": IdentityEncoder(dtype=torch.long),
            }
        },
    },
    "edgeCollections": {"Ratings": {"weight": "Rating"}},
}

dgl_g = adbdgl_adapter.arangodb_to_dgl("imdb", metagraph_v2)

##################################################
# 2.5: via Metagraph with user-defined functions #
##################################################

# Transforms attributes via user-defined functions
metagraph_v3 = {
    "vertexCollections": {
        "user": {
            "features": udf_user_features,  # supports named functions
            "label": lambda df: torch.tensor(df["label"].to_list()),  # also supports lambda functions
        },
        "game": {"features": udf_game_features},
    },
    "edgeCollections": {
        "plays": {"features": (lambda df: torch.tensor(df["features"].to_list()))},
    },
}

def udf_user_features(user_df: pandas.DataFrame) -> torch.Tensor:
   # user_df["features"] = ...
    return torch.tensor(user_df["features"].to_list())


def udf_game_features(game_df: pandas.DataFrame) -> torch.Tensor:
    # game_df["features"] = ...
    return torch.tensor(game_df["features"].to_list())


dgl_g = adbdgl_adapter.arangodb_to_dgl("FakeHetero", metagraph_v3)
```

##  Development & Testing

Prerequisite: `arangorestore`

1. `git clone https://github.com/arangoml/dgl-adapter.git`
2. `cd dgl-adapter`
3. (create virtual environment of choice)
4. `pip install -e .[dev]`
5. (create an ArangoDB instance with method of choice)
6. `pytest --url <> --dbName <> --username <> --password <>`

**Note**: A `pytest` parameter can be omitted if the endpoint is using its default value:
```python
def pytest_addoption(parser):
    parser.addoption("--url", action="store", default="http://localhost:8529")
    parser.addoption("--dbName", action="store", default="_system")
    parser.addoption("--username", action="store", default="root")
    parser.addoption("--password", action="store", default="")
```

            

Raw data

            {
    "_id": null,
    "home_page": "",
    "name": "adbdgl-adapter",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": "",
    "keywords": "arangodb,dgl,deep graph library,adapter",
    "author": "",
    "author_email": "Anthony Mahanna <anthony.mahanna@arangodb.com>",
    "download_url": "https://files.pythonhosted.org/packages/fa/78/74fde3a53cc990a3c3bac203267bbf327e00ab98aac6cd8c1f91b7b47567/adbdgl_adapter-3.0.1.tar.gz",
    "platform": null,
    "description": "# ArangoDB-DGL Adapter\n\n[![build](https://github.com/arangoml/dgl-adapter/actions/workflows/build.yml/badge.svg?branch=master)](https://github.com/arangoml/dgl-adapter/actions/workflows/build.yml)\n[![CodeQL](https://github.com/arangoml/dgl-adapter/actions/workflows/analyze.yml/badge.svg?branch=master)](https://github.com/arangoml/dgl-adapter/actions/workflows/analyze.yml)\n[![Coverage Status](https://coveralls.io/repos/github/arangoml/dgl-adapter/badge.svg?branch=master)](https://coveralls.io/github/arangoml/dgl-adapter)\n[![Last commit](https://img.shields.io/github/last-commit/arangoml/dgl-adapter)](https://github.com/arangoml/dgl-adapter/commits/master)\n\n[![PyPI version badge](https://img.shields.io/pypi/v/adbdgl-adapter?color=3775A9&style=for-the-badge&logo=pypi&logoColor=FFD43B)](https://pypi.org/project/adbdgl-adapter/)\n[![Python versions badge](https://img.shields.io/pypi/pyversions/adbdgl-adapter?color=3776AB&style=for-the-badge&logo=python&logoColor=FFD43B)](https://pypi.org/project/adbdgl-adapter/)\n\n[![License](https://img.shields.io/github/license/arangoml/dgl-adapter?color=9E2165&style=for-the-badge)](https://github.com/arangoml/dgl-adapter/blob/master/LICENSE)\n[![Code style: black](https://img.shields.io/static/v1?style=for-the-badge&label=code%20style&message=black&color=black)](https://github.com/psf/black)\n[![Downloads](https://img.shields.io/pepy/dt/adbdgl-adapter?style=for-the-badge&color=282661\n)](https://pepy.tech/project/adbdgl-adapter)\n\n\n<a href=\"https://www.arangodb.com/\" rel=\"arangodb.com\">![](https://raw.githubusercontent.com/arangoml/dgl-adapter/master/examples/assets/adb_logo.png)</a>\n<a href=\"https://www.dgl.ai/\" rel=\"dgl.ai\"><img src=\"https://raw.githubusercontent.com/arangoml/dgl-adapter/master/examples/assets/dgl_logo.png\" width=40% /></a>\n\nThe ArangoDB-DGL Adapter exports Graphs from ArangoDB, the multi-model database for graph & beyond, into Deep Graph Library (DGL), a python package for graph neural networks, and vice-versa.\n\nNote: The ArangoDB-DGL Adapter currently only supports the use of PyTorch as the [DGL backend](https://docs.dgl.ai/en/0.8.x/install/#backends). Support for MXNet and Tensorflow will be added in the future.\n\n## About DGL\n\nThe Deep Graph Library (DGL) is an easy-to-use, high performance and scalable Python package for deep learning on graphs. DGL is framework agnostic, meaning if a deep graph model is a component of an end-to-end application, the rest of the logics can be implemented in any major frameworks, such as PyTorch, Apache MXNet or TensorFlow.\n\n* [Website](https://www.dgl.ai/)\n* [Documentation](https://docs.dgl.ai/)\n* [Highlighted Features](https://github.com/dmlc/dgl#highlighted-features)\n\n## Installation\n\n#### Latest Release\n```\npip install adbdgl-adapter\n```\n#### Current State\n```\npip install git+https://github.com/arangoml/dgl-adapter.git\n```\n\n##  Quickstart\n\n[![Open In Collab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/arangoml/dgl-adapter/blob/master/examples/ArangoDB_DGL_Adapter.ipynb)\n\nAlso available as an ArangoDB Lunch & Learn session: [Graph & Beyond Course #2.8](https://www.arangodb.com/resources/lunch-sessions/graph-beyond-lunch-break-2-8-dgl-adapter/)\n\n```py\nimport dgl\nimport torch\nimport pandas\n\nfrom arango import ArangoClient\nfrom adbdgl_adapter import ADBDGL_Adapter, ADBDGL_Controller\nfrom adbdgl_adapter.encoders import IdentityEncoder, CategoricalEncoder\n\n# Connect to ArangoDB\ndb = ArangoClient().db()\n\n# Instantiate the adapter\nadbdgl_adapter = ADBDGL_Adapter(db)\n\n# Create a DGL Heterogeneous Graph\nfake_hetero = dgl.heterograph({\n    (\"user\", \"follows\", \"user\"): (torch.tensor([0, 1]), torch.tensor([1, 2])),\n    (\"user\", \"follows\", \"topic\"): (torch.tensor([1, 1]), torch.tensor([1, 2])),\n    (\"user\", \"plays\", \"game\"): (torch.tensor([0, 3]), torch.tensor([3, 4])),\n})\nfake_hetero.nodes[\"user\"].data[\"features\"] = torch.tensor([21, 44, 16, 25])\nfake_hetero.nodes[\"user\"].data[\"label\"] = torch.tensor([1, 2, 0, 1])\nfake_hetero.nodes[\"game\"].data[\"features\"] = torch.tensor([[0, 0], [0, 1], [1, 0], [1, 1], [1, 1]])\nfake_hetero.edges[(\"user\", \"plays\", \"game\")].data[\"features\"] = torch.tensor([[6, 1], [1000, 0]])\n```\n\n### DGL to ArangoDB\n```py\n############################\n# 1.1: without a Metagraph #\n############################\n\nadb_g = adbdgl_adapter.dgl_to_arangodb(\"FakeHetero\", fake_hetero)\n\n#########################\n# 1.2: with a Metagraph #\n#########################\n\n# Specifying a Metagraph provides customized adapter behaviour\nmetagraph = {\n    \"nodeTypes\": {\n        \"user\": {\n            \"features\": \"user_age\",  # 1) you can specify a string value for attribute renaming\n            \"label\": label_tensor_to_2_column_dataframe,  # 2) you can specify a function for user-defined handling, as long as the function returns a Pandas DataFrame\n        },\n        # 3) You can specify set of strings if you want to preserve the same DGL attribute names for the node/edge type\n        \"game\": {\"features\"} # this is equivalent to {\"features\": \"features\"}\n    },\n    \"edgeTypes\": {\n        (\"user\", \"plays\", \"game\"): {\n            # 4) you can specify a list of strings for tensor dissasembly (if you know the number of node/edge features in advance)\n            \"features\": [\"hours_played\", \"is_satisfied_with_game\"]\n        },\n    },\n}\n\ndef label_tensor_to_2_column_dataframe(dgl_tensor: torch.Tensor, adb_df: pandas.DataFrame) -> pandas.DataFrame:\n    \"\"\"A user-defined function to create two\n    ArangoDB attributes out of the 'user' label tensor\n\n    :param dgl_tensor: The DGL Tensor containing the data\n    :type dgl_tensor: torch.Tensor\n    :param adb_df: The ArangoDB DataFrame to populate, whose\n        size is preset to the length of **dgl_tensor**.\n    :type adb_df: pandas.DataFrame\n    :return: The populated ArangoDB DataFrame\n    :rtype: pandas.DataFrame\n    \"\"\"\n    label_map = {0: \"Class A\", 1: \"Class B\", 2: \"Class C\"}\n\n    adb_df[\"label_num\"] = dgl_tensor.tolist()\n    adb_df[\"label_str\"] = adb_df[\"label_num\"].map(label_map)\n\n    return adb_df\n\n\nadb_g = adbdgl_adapter.dgl_to_arangodb(\"FakeHetero\", fake_hetero, metagraph, explicit_metagraph=False)\n\n#######################################################\n# 1.3: with a Metagraph and `explicit_metagraph=True` #\n#######################################################\n\n# With `explicit_metagraph=True`, the node & edge types omitted from the metagraph will NOT be converted to ArangoDB.\nadb_g = adbdgl_adapter.dgl_to_arangodb(\"FakeHetero\", fake_hetero, metagraph, explicit_metagraph=True)\n\n########################################\n# 1.4: with a custom ADBDGL Controller #\n########################################\n\nclass Custom_ADBDGL_Controller(ADBDGL_Controller):\n    def _prepare_dgl_node(self, dgl_node: dict, node_type: str) -> dict:\n        \"\"\"Optionally modify a DGL node object before it gets inserted into its designated ArangoDB collection.\n\n        :param dgl_node: The DGL node object to (optionally) modify.\n        :param node_type: The DGL Node Type of the node.\n        :return: The DGL Node object\n        \"\"\"\n        dgl_node[\"foo\"] = \"bar\"\n        return dgl_node\n\n    def _prepare_dgl_edge(self, dgl_edge: dict, edge_type: tuple) -> dict:\n        \"\"\"Optionally modify a DGL edge object before it gets inserted into its designated ArangoDB collection.\n\n        :param dgl_edge: The DGL edge object to (optionally) modify.\n        :param edge_type: The Edge Type of the DGL edge. Formatted\n            as (from_collection, edge_collection, to_collection)\n        :return: The DGL Edge object\n        \"\"\"\n        dgl_edge[\"bar\"] = \"foo\"\n        return dgl_edge\n\n\nadb_g = ADBDGL_Adapter(db, Custom_ADBDGL_Controller()).dgl_to_arangodb(\"FakeHetero\", fake_hetero)\n```\n\n### ArangoDB to DGL\n```py\n# Start from scratch!\ndb.delete_graph(\"FakeHetero\", drop_collections=True, ignore_missing=True)\nadbdgl_adapter.dgl_to_arangodb(\"FakeHetero\", fake_hetero)\n\n#######################\n# 2.1: via Graph name #\n#######################\n\n# Due to risk of ambiguity, this method does not transfer attributes\ndgl_g = adbdgl_adapter.arangodb_graph_to_dgl(\"FakeHetero\")\n\n#############################\n# 2.2: via Collection names #\n#############################\n\n# Due to risk of ambiguity, this method does not transfer attributes\ndgl_g = adbdgl_adapter.arangodb_collections_to_dgl(\"FakeHetero\", v_cols={\"user\", \"game\"}, e_cols={\"plays\"})\n\n######################\n# 2.3: via Metagraph #\n######################\n\n# Transfers attributes \"as is\", meaning they are already formatted to DGL data standards.\n# Learn more about the DGL Data Standards here: https://docs.dgl.ai/guide/graph.html#guide-graph\nmetagraph_v1 = {\n    \"vertexCollections\": {\n        # Move the \"features\" & \"label\" ArangoDB attributes to DGL as \"features\" & \"label\" Tensors\n        \"user\": {\"features\", \"label\"}, # equivalent to {\"features\": \"features\", \"label\": \"label\"}\n        \"game\": {\"dgl_game_features\": \"features\"},\n        \"topic\": {},\n    },\n    \"edgeCollections\": {\n        \"plays\": {\"dgl_plays_features\": \"features\"}, \n        \"follows\": {}\n    },\n}\n\ndgl_g = adbdgl_adapter.arangodb_to_dgl(\"FakeHetero\", metagraph_v1)\n\n#################################################\n# 2.4: via Metagraph with user-defined encoders #\n#################################################\n\n# Transforms attributes via user-defined encoders\nmetagraph_v2 = {\n    \"vertexCollections\": {\n        \"Movies\": {\n            \"features\": {  # Build a feature matrix from the \"Action\" & \"Drama\" document attributes\n                \"Action\": IdentityEncoder(dtype=torch.long),\n                \"Drama\": IdentityEncoder(dtype=torch.long),\n            },\n            \"label\": \"Comedy\",\n        },\n        \"Users\": {\n            \"features\": {\n                \"Gender\": CategoricalEncoder(), # CategoricalEncoder(mapping={\"M\": 0, \"F\": 1}),\n                \"Age\": IdentityEncoder(dtype=torch.long),\n            }\n        },\n    },\n    \"edgeCollections\": {\"Ratings\": {\"weight\": \"Rating\"}},\n}\n\ndgl_g = adbdgl_adapter.arangodb_to_dgl(\"imdb\", metagraph_v2)\n\n##################################################\n# 2.5: via Metagraph with user-defined functions #\n##################################################\n\n# Transforms attributes via user-defined functions\nmetagraph_v3 = {\n    \"vertexCollections\": {\n        \"user\": {\n            \"features\": udf_user_features,  # supports named functions\n            \"label\": lambda df: torch.tensor(df[\"label\"].to_list()),  # also supports lambda functions\n        },\n        \"game\": {\"features\": udf_game_features},\n    },\n    \"edgeCollections\": {\n        \"plays\": {\"features\": (lambda df: torch.tensor(df[\"features\"].to_list()))},\n    },\n}\n\ndef udf_user_features(user_df: pandas.DataFrame) -> torch.Tensor:\n   # user_df[\"features\"] = ...\n    return torch.tensor(user_df[\"features\"].to_list())\n\n\ndef udf_game_features(game_df: pandas.DataFrame) -> torch.Tensor:\n    # game_df[\"features\"] = ...\n    return torch.tensor(game_df[\"features\"].to_list())\n\n\ndgl_g = adbdgl_adapter.arangodb_to_dgl(\"FakeHetero\", metagraph_v3)\n```\n\n##  Development & Testing\n\nPrerequisite: `arangorestore`\n\n1. `git clone https://github.com/arangoml/dgl-adapter.git`\n2. `cd dgl-adapter`\n3. (create virtual environment of choice)\n4. `pip install -e .[dev]`\n5. (create an ArangoDB instance with method of choice)\n6. `pytest --url <> --dbName <> --username <> --password <>`\n\n**Note**: A `pytest` parameter can be omitted if the endpoint is using its default value:\n```python\ndef pytest_addoption(parser):\n    parser.addoption(\"--url\", action=\"store\", default=\"http://localhost:8529\")\n    parser.addoption(\"--dbName\", action=\"store\", default=\"_system\")\n    parser.addoption(\"--username\", action=\"store\", default=\"root\")\n    parser.addoption(\"--password\", action=\"store\", default=\"\")\n```\n",
    "bugtrack_url": null,
    "license": "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:  You must give any other recipients of the Work or Derivative Works a copy of this License; and You must cause any modified files to carry prominent notices stating that You changed the files; and 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 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. ",
    "summary": "Convert ArangoDB graphs to DGL & vice-versa.",
    "version": "3.0.1",
    "project_urls": {
        "Homepage": "https://github.com/arangoml/dgl-adapter"
    },
    "split_keywords": [
        "arangodb",
        "dgl",
        "deep graph library",
        "adapter"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "6ff1b82e908a7756dcfbf4b9ab70700964ba2a1f158b69c872e450421e4deaa3",
                "md5": "1ff6c115bf486b6a0c77197bb42d2261",
                "sha256": "770698f054170169001ac7f460e0e1e83377357ed704cd813272a58e57d9f5fb"
            },
            "downloads": -1,
            "filename": "adbdgl_adapter-3.0.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "1ff6c115bf486b6a0c77197bb42d2261",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 29508,
            "upload_time": "2024-01-19T15:04:41",
            "upload_time_iso_8601": "2024-01-19T15:04:41.728362Z",
            "url": "https://files.pythonhosted.org/packages/6f/f1/b82e908a7756dcfbf4b9ab70700964ba2a1f158b69c872e450421e4deaa3/adbdgl_adapter-3.0.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "fa7874fde3a53cc990a3c3bac203267bbf327e00ab98aac6cd8c1f91b7b47567",
                "md5": "80f3ca6b5affcfce739f920ee25eb4a9",
                "sha256": "d68d78d29442dd9f69cd46a9ca68fe0b96eb61ea29e476ee8af16696e7517d07"
            },
            "downloads": -1,
            "filename": "adbdgl_adapter-3.0.1.tar.gz",
            "has_sig": false,
            "md5_digest": "80f3ca6b5affcfce739f920ee25eb4a9",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 41165,
            "upload_time": "2024-01-19T15:04:43",
            "upload_time_iso_8601": "2024-01-19T15:04:43.597230Z",
            "url": "https://files.pythonhosted.org/packages/fa/78/74fde3a53cc990a3c3bac203267bbf327e00ab98aac6cd8c1f91b7b47567/adbdgl_adapter-3.0.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-01-19 15:04:43",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "arangoml",
    "github_project": "dgl-adapter",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "adbdgl-adapter"
}
        
Elapsed time: 0.16842s