Name | adbpyg-adapter JSON |
Version |
1.1.3
JSON |
| download |
home_page | |
Summary | Convert ArangoDB graphs to PyG & vice-versa. |
upload_time | 2024-02-09 14:33:32 |
maintainer | |
docs_url | None |
author | |
requires_python | >=3.8 |
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. |
keywords |
arangodb
pyg
pytorch
pytorch geometric
adapter
|
VCS |
|
bugtrack_url |
|
requirements |
No requirements were recorded.
|
Travis-CI |
No Travis.
|
coveralls test coverage |
No coveralls.
|
# ArangoDB-PyG Adapter
[![build](https://github.com/arangoml/pyg-adapter/actions/workflows/build.yml/badge.svg?branch=master)](https://github.com/arangoml/pyg-adapter/actions/workflows/build.yml)
[![CodeQL](https://github.com/arangoml/pyg-adapter/actions/workflows/analyze.yml/badge.svg?branch=master)](https://github.com/arangoml/pyg-adapter/actions/workflows/analyze.yml)
[![Coverage Status](https://coveralls.io/repos/github/arangoml/pyg-adapter/badge.svg?branch=master)](https://coveralls.io/github/arangoml/pyg-adapter)
[![Last commit](https://img.shields.io/github/last-commit/arangoml/pyg-adapter)](https://github.com/arangoml/pyg-adapter/commits/master)
[![PyPI version badge](https://img.shields.io/pypi/v/adbpyg-adapter?color=3775A9&style=for-the-badge&logo=pypi&logoColor=FFD43B)](https://pypi.org/project/adbpyg-adapter/)
[![Python versions badge](https://img.shields.io/pypi/pyversions/adbpyg-adapter?color=3776AB&style=for-the-badge&logo=python&logoColor=FFD43B)](https://pypi.org/project/adbpyg-adapter/)
[![License](https://img.shields.io/github/license/arangoml/pyg-adapter?color=9E2165&style=for-the-badge)](https://github.com/arangoml/pyg-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/adbpyg-adapter?style=for-the-badge&color=282661
)](https://pepy.tech/project/adbpyg-adapter)
<a href="https://www.arangodb.com/" rel="arangodb.com">![](https://raw.githubusercontent.com/arangoml/pyg-adapter/master/examples/assets/adb_logo.png)</a>
<a href="https://www.pyg.org/" rel="pyg.org"><img src="https://raw.githubusercontent.com/pyg-team/pyg_sphinx_theme/master/pyg_sphinx_theme/static/img/pyg_logo_text.svg?sanitize=true" width=40% /></a>
The ArangoDB-PyG Adapter exports Graphs from ArangoDB, the multi-model database for graph & beyond, into PyTorch Geometric (PyG), a PyTorch-based Graph Neural Network library, and vice-versa.
## About PyG
**PyG** *(PyTorch Geometric)* is a library built upon [PyTorch](https://pytorch.org/) to easily write and train Graph Neural Networks (GNNs) for a wide range of applications related to structured data.
It consists of various methods for deep learning on graphs and other irregular structures, also known as *[geometric deep learning](http://geometricdeeplearning.com/)*, from a variety of published papers.
In addition, it consists of easy-to-use mini-batch loaders for operating on many small and single giant graphs, [multi GPU-support](https://github.com/pyg-team/pytorch_geometric/tree/master/examples/multi_gpu), [`DataPipe` support](https://github.com/pyg-team/pytorch_geometric/blob/master/examples/datapipe.py), distributed graph learning via [Quiver](https://github.com/pyg-team/pytorch_geometric/tree/master/examples/quiver), a large number of common benchmark datasets (based on simple interfaces to create your own), the [GraphGym](https://pytorch-geometric.readthedocs.io/en/latest/notes/graphgym.html) experiment manager, and helpful transforms, both for learning on arbitrary graphs as well as on 3D meshes or point clouds.
## Installation
#### Latest Release
```
pip install torch
pip install adbpyg-adapter
```
#### Current State
```
pip install torch
pip install git+https://github.com/arangoml/pyg-adapter.git
```
## Quickstart
[![Open In Collab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/arangoml/pyg-adapter/blob/master/examples/ArangoDB_PyG_Adapter.ipynb)
Also available as an ArangoDB Lunch & Learn session on YouTube: [Graph & Beyond Course: ArangoDB-PyG Adapter](https://www.youtube.com/watch?v=QtGR95NN8bA)
```py
import torch
import pandas
from torch_geometric.datasets import FakeHeteroDataset
from arango import ArangoClient
from adbpyg_adapter import ADBPyG_Adapter, ADBPyG_Controller
from adbpyg_adapter.encoders import IdentityEncoder, CategoricalEncoder
# Connect to ArangoDB
db = ArangoClient().db()
# Instantiate the adapter
adbpyg_adapter = ADBPyG_Adapter(db)
# Create a PyG Heterogeneous Graph
data = FakeHeteroDataset(
num_node_types=2,
num_edge_types=3,
avg_num_nodes=20,
avg_num_channels=3, # avg number of features per node
edge_dim=2, # number of features per edge
num_classes=3, # number of unique label values
)[0]
```
### PyG to ArangoDB
Note: If the PyG graph contains `_key`, `_v_key`, or `_e_key` properties for any node / edge types, the adapter will assume to persist those values as [ArangoDB document keys](https://www.arangodb.com/docs/stable/data-modeling-naming-conventions-document-keys.html). See the `Full Cycle (ArangoDB -> PyG -> ArangoDB)` section below for an example.
```py
#############################
# 1.1: without a Metagraph #
#############################
adb_g = adbpyg_adapter.pyg_to_arangodb("FakeData", data)
#########################
# 1.2: with a Metagraph #
#########################
# Specifying a Metagraph provides customized adapter behaviour
metagraph = {
"nodeTypes": {
"v0": {
"x": "features", # 1) You can specify a string value if you want to rename your PyG data when stored in ArangoDB
"y": y_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 PyG attribute names for the node/edge type
"v1": {"x"} # this is equivalent to {"x": "x"}
},
"edgeTypes": {
("v0", "e0", "v0"): {
# 4) You can specify a list of strings for tensor dissasembly (if you know the number of node/edge features in advance)
"edge_attr": [ "a", "b"]
},
},
}
def y_tensor_to_2_column_dataframe(pyg_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 pyg_tensor: The PyG Tensor containing the data
:type pyg_tensor: torch.Tensor
:param adb_df: The ArangoDB DataFrame to populate, whose
size is preset to the length of **pyg_tensor**.
:type adb_df: pandas.DataFrame
:return: The populated ArangoDB DataFrame
:rtype: pandas.DataFrame
"""
label_map = {0: "Kiwi", 1: "Blueberry", 2: "Avocado"}
adb_df["label_num"] = pyg_tensor.tolist()
adb_df["label_str"] = adb_df["label_num"].map(label_map)
return adb_df
adb_g = adbpyg_adapter.pyg_to_arangodb("FakeData", data, 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 = adbpyg_adapter.pyg_to_arangodb("FakeData", data, metagraph, explicit_metagraph=True)
########################################
# 1.4: with a custom ADBPyG Controller #
########################################
class Custom_ADBPyG_Controller(ADBPyG_Controller):
def _prepare_pyg_node(self, pyg_node: dict, node_type: str) -> dict:
"""Optionally modify a PyG node object before it gets inserted into its designated ArangoDB collection.
:param pyg_node: The PyG node object to (optionally) modify.
:param node_type: The PyG Node Type of the node.
:return: The PyG Node object
"""
pyg_node["foo"] = "bar"
return pyg_node
def _prepare_pyg_edge(self, pyg_edge: dict, edge_type: tuple) -> dict:
"""Optionally modify a PyG edge object before it gets inserted into its designated ArangoDB collection.
:param pyg_edge: The PyG edge object to (optionally) modify.
:param edge_type: The Edge Type of the PyG edge. Formatted
as (from_collection, edge_collection, to_collection)
:return: The PyG Edge object
"""
pyg_edge["bar"] = "foo"
return pyg_edge
adb_g = ADBPyG_Adapter(db, Custom_ADBPyG_Controller()).pyg_to_arangodb("FakeData", data)
```
### ArangoDB to PyG
```py
# Start from scratch!
db.delete_graph("FakeData", drop_collections=True, ignore_missing=True)
adbpyg_adapter.pyg_to_arangodb("FakeData", data)
#######################
# 2.1: via Graph name #
#######################
# Due to risk of ambiguity, this method does not transfer attributes
pyg_g = adbpyg_adapter.arangodb_graph_to_pyg("FakeData")
#############################
# 2.2: via Collection names #
#############################
# Due to risk of ambiguity, this method does not transfer attributes
pyg_g = adbpyg_adapter.arangodb_collections_to_pyg("FakeData", v_cols={"v0", "v1"}, e_cols={"e0"})
######################
# 2.3: via Metagraph #
######################
# Transfers attributes "as is", meaning they are already formatted to PyG data standards.
metagraph_v1 = {
"vertexCollections": {
# Move the "x" & "y" ArangoDB attributes to PyG as "x" & "y" Tensors
"v0": {"x", "y"}, # equivalent to {"x": "x", "y": "y"}
"v1": {"v1_x": "x"}, # store the 'x' feature matrix as 'v1_x' in PyG
},
"edgeCollections": {
"e0": {"edge_attr"},
},
}
pyg_g = adbpyg_adapter.arangodb_to_pyg("FakeData", metagraph_v1)
#################################################
# 2.4: via Metagraph with user-defined encoders #
#################################################
# Transforms attributes via user-defined encoders
# For more info on user-defined encoders in PyG, see https://pytorch-geometric.readthedocs.io/en/latest/notes/load_csv.html
metagraph_v2 = {
"vertexCollections": {
"Movies": {
"x": { # Build a feature matrix from the "Action" & "Drama" document attributes
"Action": IdentityEncoder(dtype=torch.long),
"Drama": IdentityEncoder(dtype=torch.long),
},
"y": "Comedy",
},
"Users": {
"x": {
"Gender": CategoricalEncoder(mapping={"M": 0, "F": 1}),
"Age": IdentityEncoder(dtype=torch.long),
}
},
},
"edgeCollections": {
"Ratings": { "edge_weight": "Rating" } # Use the 'Rating' attribute for the PyG 'edge_weight' property
},
}
pyg_g = adbpyg_adapter.arangodb_to_pyg("imdb", metagraph_v2)
##################################################
# 2.5: via Metagraph with user-defined functions #
##################################################
# Transforms attributes via user-defined functions
metagraph_v3 = {
"vertexCollections": {
"v0": {
"x": udf_v0_x, # supports named functions
"y": lambda df: torch.tensor(df["y"].to_list()), # also supports lambda functions
},
"v1": {"x": udf_v1_x},
},
"edgeCollections": {
"e0": {"edge_attr": (lambda df: torch.tensor(df["edge_attr"].to_list()))},
},
}
def udf_v0_x(v0_df: pandas.DataFrame) -> torch.Tensor:
# v0_df["x"] = ...
return torch.tensor(v0_df["x"].to_list())
def udf_v1_x(v1_df: pandas.DataFrame) -> torch.Tensor:
# v1_df["x"] = ...
return torch.tensor(v1_df["x"].to_list())
pyg_g = adbpyg_adapter.arangodb_to_pyg("FakeData", metagraph_v3)
```
### Full Cycle (ArangoDB -> PyG -> ArangoDB)
```py
# With `preserve_adb_keys=True`, the adapter will preserve the ArangoDB vertex & edge _key values into the (newly created) PyG graph.
# Users can then re-import their PyG graph into ArangoDB using the same _key values
pyg_g = adbpyg_adapter.arangodb_graph_to_pyg("imdb", preserve_adb_keys=True)
# pyg_g["Movies"]["_key"] --> ["1", "2", ..., "1682"]
# pyg_g["Users"]["_key"] --> ["1", "2", ..., "943"]
# pyg_g[("Users", "Ratings", "Movies")]["_key"] --> ["2732620466", ..., "2730643624"]
# Let's add a new PyG User Node by updating the _key property
pyg_g["Users"]["_key"].append("new-user-here-944")
# Note: Prior to the re-import, we must manually set the number of nodes in the PyG graph, since the `arangodb_graph_to_pyg` API creates featureless node data
pyg_g["Movies"].num_nodes = len(pyg_g["Movies"]["_key"]) # 1682
pyg_g["Users"].num_nodes = len(pyg_g["Users"]["_key"]) # 944 (prev. 943)
# Re-import PyG graph into ArangoDB
adbpyg_adapter.pyg_to_arangodb("imdb", pyg_g, on_duplicate="update")
```
## Development & Testing
Prerequisite: `arangorestore`
1. `git clone https://github.com/arangoml/pyg-adapter.git`
2. `cd pyg-adapter`
3. (create virtual environment of choice)
4. `pip install torch`
5. `pip install -e .[dev]`
6. (create an ArangoDB instance with method of choice)
7. `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": "adbpyg-adapter",
"maintainer": "",
"docs_url": null,
"requires_python": ">=3.8",
"maintainer_email": "",
"keywords": "arangodb,pyg,pytorch,pytorch geometric,adapter",
"author": "",
"author_email": "Anthony Mahanna <anthony.mahanna@arangodb.com>",
"download_url": "https://files.pythonhosted.org/packages/6e/a3/a5651e13516a0745fe859cd0c11a3f045602cd3190674f65c71117bda1f5/adbpyg_adapter-1.1.3.tar.gz",
"platform": null,
"description": "# ArangoDB-PyG Adapter\n\n[![build](https://github.com/arangoml/pyg-adapter/actions/workflows/build.yml/badge.svg?branch=master)](https://github.com/arangoml/pyg-adapter/actions/workflows/build.yml)\n[![CodeQL](https://github.com/arangoml/pyg-adapter/actions/workflows/analyze.yml/badge.svg?branch=master)](https://github.com/arangoml/pyg-adapter/actions/workflows/analyze.yml)\n[![Coverage Status](https://coveralls.io/repos/github/arangoml/pyg-adapter/badge.svg?branch=master)](https://coveralls.io/github/arangoml/pyg-adapter)\n[![Last commit](https://img.shields.io/github/last-commit/arangoml/pyg-adapter)](https://github.com/arangoml/pyg-adapter/commits/master)\n\n[![PyPI version badge](https://img.shields.io/pypi/v/adbpyg-adapter?color=3775A9&style=for-the-badge&logo=pypi&logoColor=FFD43B)](https://pypi.org/project/adbpyg-adapter/)\n[![Python versions badge](https://img.shields.io/pypi/pyversions/adbpyg-adapter?color=3776AB&style=for-the-badge&logo=python&logoColor=FFD43B)](https://pypi.org/project/adbpyg-adapter/)\n\n[![License](https://img.shields.io/github/license/arangoml/pyg-adapter?color=9E2165&style=for-the-badge)](https://github.com/arangoml/pyg-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/adbpyg-adapter?style=for-the-badge&color=282661\n)](https://pepy.tech/project/adbpyg-adapter)\n\n\n<a href=\"https://www.arangodb.com/\" rel=\"arangodb.com\">![](https://raw.githubusercontent.com/arangoml/pyg-adapter/master/examples/assets/adb_logo.png)</a>\n<a href=\"https://www.pyg.org/\" rel=\"pyg.org\"><img src=\"https://raw.githubusercontent.com/pyg-team/pyg_sphinx_theme/master/pyg_sphinx_theme/static/img/pyg_logo_text.svg?sanitize=true\" width=40% /></a>\n\nThe ArangoDB-PyG Adapter exports Graphs from ArangoDB, the multi-model database for graph & beyond, into PyTorch Geometric (PyG), a PyTorch-based Graph Neural Network library, and vice-versa.\n\n## About PyG\n\n**PyG** *(PyTorch Geometric)* is a library built upon [PyTorch](https://pytorch.org/) to easily write and train Graph Neural Networks (GNNs) for a wide range of applications related to structured data.\n\nIt consists of various methods for deep learning on graphs and other irregular structures, also known as *[geometric deep learning](http://geometricdeeplearning.com/)*, from a variety of published papers.\nIn addition, it consists of easy-to-use mini-batch loaders for operating on many small and single giant graphs, [multi GPU-support](https://github.com/pyg-team/pytorch_geometric/tree/master/examples/multi_gpu), [`DataPipe` support](https://github.com/pyg-team/pytorch_geometric/blob/master/examples/datapipe.py), distributed graph learning via [Quiver](https://github.com/pyg-team/pytorch_geometric/tree/master/examples/quiver), a large number of common benchmark datasets (based on simple interfaces to create your own), the [GraphGym](https://pytorch-geometric.readthedocs.io/en/latest/notes/graphgym.html) experiment manager, and helpful transforms, both for learning on arbitrary graphs as well as on 3D meshes or point clouds.\n\n## Installation\n\n#### Latest Release\n```\npip install torch\npip install adbpyg-adapter\n```\n#### Current State\n```\npip install torch\npip install git+https://github.com/arangoml/pyg-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/pyg-adapter/blob/master/examples/ArangoDB_PyG_Adapter.ipynb)\n\nAlso available as an ArangoDB Lunch & Learn session on YouTube: [Graph & Beyond Course: ArangoDB-PyG Adapter](https://www.youtube.com/watch?v=QtGR95NN8bA)\n\n```py\nimport torch\nimport pandas\nfrom torch_geometric.datasets import FakeHeteroDataset\n\nfrom arango import ArangoClient\nfrom adbpyg_adapter import ADBPyG_Adapter, ADBPyG_Controller\nfrom adbpyg_adapter.encoders import IdentityEncoder, CategoricalEncoder\n\n# Connect to ArangoDB\ndb = ArangoClient().db()\n\n# Instantiate the adapter\nadbpyg_adapter = ADBPyG_Adapter(db)\n\n# Create a PyG Heterogeneous Graph\ndata = FakeHeteroDataset(\n num_node_types=2,\n num_edge_types=3,\n avg_num_nodes=20,\n avg_num_channels=3, # avg number of features per node\n edge_dim=2, # number of features per edge\n num_classes=3, # number of unique label values\n)[0]\n```\n\n### PyG to ArangoDB\n\nNote: If the PyG graph contains `_key`, `_v_key`, or `_e_key` properties for any node / edge types, the adapter will assume to persist those values as [ArangoDB document keys](https://www.arangodb.com/docs/stable/data-modeling-naming-conventions-document-keys.html). See the `Full Cycle (ArangoDB -> PyG -> ArangoDB)` section below for an example.\n\n```py\n#############################\n# 1.1: without a Metagraph #\n#############################\n\nadb_g = adbpyg_adapter.pyg_to_arangodb(\"FakeData\", data)\n\n#########################\n# 1.2: with a Metagraph #\n#########################\n\n# Specifying a Metagraph provides customized adapter behaviour\nmetagraph = {\n \"nodeTypes\": {\n \"v0\": {\n \"x\": \"features\", # 1) You can specify a string value if you want to rename your PyG data when stored in ArangoDB\n \"y\": y_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 PyG attribute names for the node/edge type\n \"v1\": {\"x\"} # this is equivalent to {\"x\": \"x\"}\n },\n \"edgeTypes\": {\n (\"v0\", \"e0\", \"v0\"): {\n # 4) You can specify a list of strings for tensor dissasembly (if you know the number of node/edge features in advance)\n \"edge_attr\": [ \"a\", \"b\"] \n },\n },\n}\n\ndef y_tensor_to_2_column_dataframe(pyg_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 pyg_tensor: The PyG Tensor containing the data\n :type pyg_tensor: torch.Tensor\n :param adb_df: The ArangoDB DataFrame to populate, whose\n size is preset to the length of **pyg_tensor**.\n :type adb_df: pandas.DataFrame\n :return: The populated ArangoDB DataFrame\n :rtype: pandas.DataFrame\n \"\"\"\n label_map = {0: \"Kiwi\", 1: \"Blueberry\", 2: \"Avocado\"}\n\n adb_df[\"label_num\"] = pyg_tensor.tolist()\n adb_df[\"label_str\"] = adb_df[\"label_num\"].map(label_map)\n\n return adb_df\n\n\nadb_g = adbpyg_adapter.pyg_to_arangodb(\"FakeData\", data, 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 = adbpyg_adapter.pyg_to_arangodb(\"FakeData\", data, metagraph, explicit_metagraph=True)\n\n########################################\n# 1.4: with a custom ADBPyG Controller #\n########################################\n\nclass Custom_ADBPyG_Controller(ADBPyG_Controller):\n def _prepare_pyg_node(self, pyg_node: dict, node_type: str) -> dict:\n \"\"\"Optionally modify a PyG node object before it gets inserted into its designated ArangoDB collection.\n\n :param pyg_node: The PyG node object to (optionally) modify.\n :param node_type: The PyG Node Type of the node.\n :return: The PyG Node object\n \"\"\"\n pyg_node[\"foo\"] = \"bar\"\n return pyg_node\n\n def _prepare_pyg_edge(self, pyg_edge: dict, edge_type: tuple) -> dict:\n \"\"\"Optionally modify a PyG edge object before it gets inserted into its designated ArangoDB collection.\n\n :param pyg_edge: The PyG edge object to (optionally) modify.\n :param edge_type: The Edge Type of the PyG edge. Formatted\n as (from_collection, edge_collection, to_collection)\n :return: The PyG Edge object\n \"\"\"\n pyg_edge[\"bar\"] = \"foo\"\n return pyg_edge\n\n\nadb_g = ADBPyG_Adapter(db, Custom_ADBPyG_Controller()).pyg_to_arangodb(\"FakeData\", data)\n```\n\n### ArangoDB to PyG\n```py\n# Start from scratch!\ndb.delete_graph(\"FakeData\", drop_collections=True, ignore_missing=True)\nadbpyg_adapter.pyg_to_arangodb(\"FakeData\", data)\n\n#######################\n# 2.1: via Graph name #\n#######################\n\n# Due to risk of ambiguity, this method does not transfer attributes\npyg_g = adbpyg_adapter.arangodb_graph_to_pyg(\"FakeData\")\n\n#############################\n# 2.2: via Collection names #\n#############################\n\n# Due to risk of ambiguity, this method does not transfer attributes\npyg_g = adbpyg_adapter.arangodb_collections_to_pyg(\"FakeData\", v_cols={\"v0\", \"v1\"}, e_cols={\"e0\"})\n\n######################\n# 2.3: via Metagraph #\n######################\n\n# Transfers attributes \"as is\", meaning they are already formatted to PyG data standards.\nmetagraph_v1 = {\n \"vertexCollections\": {\n # Move the \"x\" & \"y\" ArangoDB attributes to PyG as \"x\" & \"y\" Tensors\n \"v0\": {\"x\", \"y\"}, # equivalent to {\"x\": \"x\", \"y\": \"y\"}\n \"v1\": {\"v1_x\": \"x\"}, # store the 'x' feature matrix as 'v1_x' in PyG\n },\n \"edgeCollections\": {\n \"e0\": {\"edge_attr\"},\n },\n}\n\npyg_g = adbpyg_adapter.arangodb_to_pyg(\"FakeData\", metagraph_v1)\n\n#################################################\n# 2.4: via Metagraph with user-defined encoders #\n#################################################\n\n# Transforms attributes via user-defined encoders\n# For more info on user-defined encoders in PyG, see https://pytorch-geometric.readthedocs.io/en/latest/notes/load_csv.html\nmetagraph_v2 = {\n \"vertexCollections\": {\n \"Movies\": {\n \"x\": { # Build a feature matrix from the \"Action\" & \"Drama\" document attributes\n \"Action\": IdentityEncoder(dtype=torch.long),\n \"Drama\": IdentityEncoder(dtype=torch.long),\n },\n \"y\": \"Comedy\",\n },\n \"Users\": {\n \"x\": {\n \"Gender\": CategoricalEncoder(mapping={\"M\": 0, \"F\": 1}),\n \"Age\": IdentityEncoder(dtype=torch.long),\n }\n },\n },\n \"edgeCollections\": {\n \"Ratings\": { \"edge_weight\": \"Rating\" } # Use the 'Rating' attribute for the PyG 'edge_weight' property\n },\n}\n\npyg_g = adbpyg_adapter.arangodb_to_pyg(\"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 \"v0\": {\n \"x\": udf_v0_x, # supports named functions\n \"y\": lambda df: torch.tensor(df[\"y\"].to_list()), # also supports lambda functions\n },\n \"v1\": {\"x\": udf_v1_x},\n },\n \"edgeCollections\": {\n \"e0\": {\"edge_attr\": (lambda df: torch.tensor(df[\"edge_attr\"].to_list()))},\n },\n}\n\ndef udf_v0_x(v0_df: pandas.DataFrame) -> torch.Tensor:\n # v0_df[\"x\"] = ...\n return torch.tensor(v0_df[\"x\"].to_list())\n\n\ndef udf_v1_x(v1_df: pandas.DataFrame) -> torch.Tensor:\n # v1_df[\"x\"] = ...\n return torch.tensor(v1_df[\"x\"].to_list())\n\npyg_g = adbpyg_adapter.arangodb_to_pyg(\"FakeData\", metagraph_v3)\n```\n\n### Full Cycle (ArangoDB -> PyG -> ArangoDB)\n```py\n# With `preserve_adb_keys=True`, the adapter will preserve the ArangoDB vertex & edge _key values into the (newly created) PyG graph.\n# Users can then re-import their PyG graph into ArangoDB using the same _key values \npyg_g = adbpyg_adapter.arangodb_graph_to_pyg(\"imdb\", preserve_adb_keys=True)\n\n# pyg_g[\"Movies\"][\"_key\"] --> [\"1\", \"2\", ..., \"1682\"]\n# pyg_g[\"Users\"][\"_key\"] --> [\"1\", \"2\", ..., \"943\"]\n# pyg_g[(\"Users\", \"Ratings\", \"Movies\")][\"_key\"] --> [\"2732620466\", ..., \"2730643624\"]\n\n# Let's add a new PyG User Node by updating the _key property\npyg_g[\"Users\"][\"_key\"].append(\"new-user-here-944\")\n\n# Note: Prior to the re-import, we must manually set the number of nodes in the PyG graph, since the `arangodb_graph_to_pyg` API creates featureless node data\npyg_g[\"Movies\"].num_nodes = len(pyg_g[\"Movies\"][\"_key\"]) # 1682\npyg_g[\"Users\"].num_nodes = len(pyg_g[\"Users\"][\"_key\"]) # 944 (prev. 943)\n\n# Re-import PyG graph into ArangoDB\nadbpyg_adapter.pyg_to_arangodb(\"imdb\", pyg_g, on_duplicate=\"update\")\n```\n\n## Development & Testing\n\nPrerequisite: `arangorestore`\n\n1. `git clone https://github.com/arangoml/pyg-adapter.git`\n2. `cd pyg-adapter`\n3. (create virtual environment of choice)\n4. `pip install torch`\n5. `pip install -e .[dev]`\n6. (create an ArangoDB instance with method of choice)\n7. `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 PyG & vice-versa.",
"version": "1.1.3",
"project_urls": {
"Homepage": "https://github.com/arangoml/pyg-adapter"
},
"split_keywords": [
"arangodb",
"pyg",
"pytorch",
"pytorch geometric",
"adapter"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "245b2f00bcc770d250f91c49cc05f2b26f1d00c47e07b24afab36f905021eb69",
"md5": "24fce52130b2241a9f4d7d3f905dda1e",
"sha256": "1c9ff245774c094942910c0b67ab7e1d8ead98e2bdf4395d6313ba5442bb36b0"
},
"downloads": -1,
"filename": "adbpyg_adapter-1.1.3-py3-none-any.whl",
"has_sig": false,
"md5_digest": "24fce52130b2241a9f4d7d3f905dda1e",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.8",
"size": 30584,
"upload_time": "2024-02-09T14:33:31",
"upload_time_iso_8601": "2024-02-09T14:33:31.024672Z",
"url": "https://files.pythonhosted.org/packages/24/5b/2f00bcc770d250f91c49cc05f2b26f1d00c47e07b24afab36f905021eb69/adbpyg_adapter-1.1.3-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "6ea3a5651e13516a0745fe859cd0c11a3f045602cd3190674f65c71117bda1f5",
"md5": "f86e7a19a6956d71a88e4a1bb300116f",
"sha256": "64d67aeea9f174866eb4f58715557deb6ffe5073f1e338dc1b6dbbf9de8b9e4c"
},
"downloads": -1,
"filename": "adbpyg_adapter-1.1.3.tar.gz",
"has_sig": false,
"md5_digest": "f86e7a19a6956d71a88e4a1bb300116f",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.8",
"size": 42983,
"upload_time": "2024-02-09T14:33:32",
"upload_time_iso_8601": "2024-02-09T14:33:32.363697Z",
"url": "https://files.pythonhosted.org/packages/6e/a3/a5651e13516a0745fe859cd0c11a3f045602cd3190674f65c71117bda1f5/adbpyg_adapter-1.1.3.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-02-09 14:33:32",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "arangoml",
"github_project": "pyg-adapter",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"lcname": "adbpyg-adapter"
}