pyg-nightly 2.6.0.dev20240511__py3-none-any.whl → 2.7.0.dev20250114__py3-none-any.whl
Sign up to get free protection for your applications and to get access to all the features.
- {pyg_nightly-2.6.0.dev20240511.dist-info → pyg_nightly-2.7.0.dev20250114.dist-info}/METADATA +30 -31
- {pyg_nightly-2.6.0.dev20240511.dist-info → pyg_nightly-2.7.0.dev20250114.dist-info}/RECORD +205 -181
- {pyg_nightly-2.6.0.dev20240511.dist-info → pyg_nightly-2.7.0.dev20250114.dist-info}/WHEEL +1 -1
- torch_geometric/__init__.py +26 -1
- torch_geometric/_compile.py +8 -1
- torch_geometric/_onnx.py +14 -0
- torch_geometric/config_mixin.py +113 -0
- torch_geometric/config_store.py +16 -14
- torch_geometric/data/__init__.py +24 -1
- torch_geometric/data/batch.py +2 -2
- torch_geometric/data/data.py +13 -8
- torch_geometric/data/database.py +15 -7
- torch_geometric/data/dataset.py +14 -6
- torch_geometric/data/feature_store.py +13 -22
- torch_geometric/data/graph_store.py +0 -4
- torch_geometric/data/hetero_data.py +4 -4
- torch_geometric/data/in_memory_dataset.py +2 -4
- torch_geometric/data/large_graph_indexer.py +677 -0
- torch_geometric/data/lightning/datamodule.py +4 -4
- torch_geometric/data/storage.py +15 -5
- torch_geometric/data/summary.py +14 -4
- torch_geometric/data/temporal.py +1 -2
- torch_geometric/datasets/__init__.py +11 -1
- torch_geometric/datasets/actor.py +9 -11
- torch_geometric/datasets/airfrans.py +15 -18
- torch_geometric/datasets/airports.py +10 -12
- torch_geometric/datasets/amazon.py +8 -11
- torch_geometric/datasets/amazon_book.py +9 -10
- torch_geometric/datasets/amazon_products.py +9 -10
- torch_geometric/datasets/aminer.py +8 -9
- torch_geometric/datasets/aqsol.py +10 -13
- torch_geometric/datasets/attributed_graph_dataset.py +10 -12
- torch_geometric/datasets/ba_multi_shapes.py +10 -12
- torch_geometric/datasets/ba_shapes.py +5 -6
- torch_geometric/datasets/bitcoin_otc.py +1 -1
- torch_geometric/datasets/brca_tgca.py +1 -1
- torch_geometric/datasets/dblp.py +2 -1
- torch_geometric/datasets/dbp15k.py +2 -2
- torch_geometric/datasets/fake.py +1 -3
- torch_geometric/datasets/flickr.py +2 -1
- torch_geometric/datasets/freebase.py +1 -1
- torch_geometric/datasets/gdelt_lite.py +3 -2
- torch_geometric/datasets/ged_dataset.py +3 -2
- torch_geometric/datasets/git_mol_dataset.py +263 -0
- torch_geometric/datasets/gnn_benchmark_dataset.py +6 -5
- torch_geometric/datasets/hgb_dataset.py +8 -8
- torch_geometric/datasets/imdb.py +2 -1
- torch_geometric/datasets/last_fm.py +2 -1
- torch_geometric/datasets/linkx_dataset.py +4 -3
- torch_geometric/datasets/lrgb.py +3 -5
- torch_geometric/datasets/malnet_tiny.py +4 -3
- torch_geometric/datasets/mnist_superpixels.py +2 -3
- torch_geometric/datasets/molecule_gpt_dataset.py +485 -0
- torch_geometric/datasets/molecule_net.py +7 -1
- torch_geometric/datasets/motif_generator/base.py +0 -1
- torch_geometric/datasets/neurograph.py +1 -3
- torch_geometric/datasets/ogb_mag.py +1 -1
- torch_geometric/datasets/opf.py +239 -0
- torch_geometric/datasets/ose_gvcs.py +1 -1
- torch_geometric/datasets/pascal_pf.py +1 -1
- torch_geometric/datasets/pcpnet_dataset.py +1 -1
- torch_geometric/datasets/pcqm4m.py +2 -1
- torch_geometric/datasets/ppi.py +1 -1
- torch_geometric/datasets/qm9.py +4 -3
- torch_geometric/datasets/reddit.py +2 -1
- torch_geometric/datasets/reddit2.py +2 -1
- torch_geometric/datasets/rel_link_pred_dataset.py +3 -3
- torch_geometric/datasets/s3dis.py +2 -2
- torch_geometric/datasets/shapenet.py +3 -3
- torch_geometric/datasets/shrec2016.py +2 -2
- torch_geometric/datasets/tag_dataset.py +350 -0
- torch_geometric/datasets/upfd.py +2 -1
- torch_geometric/datasets/web_qsp_dataset.py +246 -0
- torch_geometric/datasets/webkb.py +2 -2
- torch_geometric/datasets/wikics.py +1 -1
- torch_geometric/datasets/wikidata.py +3 -2
- torch_geometric/datasets/wikipedia_network.py +2 -2
- torch_geometric/datasets/word_net.py +2 -2
- torch_geometric/datasets/yelp.py +2 -1
- torch_geometric/datasets/zinc.py +1 -1
- torch_geometric/device.py +42 -0
- torch_geometric/distributed/local_feature_store.py +3 -2
- torch_geometric/distributed/local_graph_store.py +2 -1
- torch_geometric/distributed/partition.py +9 -8
- torch_geometric/edge_index.py +17 -8
- torch_geometric/explain/algorithm/base.py +0 -1
- torch_geometric/explain/algorithm/pg_explainer.py +1 -1
- torch_geometric/explain/explanation.py +2 -2
- torch_geometric/graphgym/checkpoint.py +2 -1
- torch_geometric/graphgym/logger.py +4 -4
- torch_geometric/graphgym/loss.py +1 -1
- torch_geometric/graphgym/utils/agg_runs.py +6 -6
- torch_geometric/index.py +20 -7
- torch_geometric/inspector.py +6 -2
- torch_geometric/io/fs.py +28 -2
- torch_geometric/io/npz.py +2 -1
- torch_geometric/io/off.py +2 -2
- torch_geometric/io/sdf.py +2 -2
- torch_geometric/io/tu.py +2 -3
- torch_geometric/loader/__init__.py +4 -0
- torch_geometric/loader/cluster.py +9 -3
- torch_geometric/loader/graph_saint.py +2 -1
- torch_geometric/loader/ibmb_loader.py +12 -4
- torch_geometric/loader/mixin.py +1 -1
- torch_geometric/loader/neighbor_loader.py +1 -1
- torch_geometric/loader/neighbor_sampler.py +2 -2
- torch_geometric/loader/prefetch.py +1 -1
- torch_geometric/loader/rag_loader.py +107 -0
- torch_geometric/loader/zip_loader.py +10 -0
- torch_geometric/metrics/__init__.py +11 -2
- torch_geometric/metrics/link_pred.py +159 -34
- torch_geometric/nn/aggr/__init__.py +2 -0
- torch_geometric/nn/aggr/attention.py +0 -2
- torch_geometric/nn/aggr/base.py +2 -4
- torch_geometric/nn/aggr/patch_transformer.py +143 -0
- torch_geometric/nn/aggr/set_transformer.py +1 -1
- torch_geometric/nn/attention/__init__.py +5 -1
- torch_geometric/nn/attention/qformer.py +71 -0
- torch_geometric/nn/conv/collect.jinja +6 -3
- torch_geometric/nn/conv/cugraph/base.py +0 -1
- torch_geometric/nn/conv/edge_conv.py +3 -2
- torch_geometric/nn/conv/gat_conv.py +35 -7
- torch_geometric/nn/conv/gatv2_conv.py +36 -6
- torch_geometric/nn/conv/general_conv.py +1 -1
- torch_geometric/nn/conv/gravnet_conv.py +3 -2
- torch_geometric/nn/conv/hetero_conv.py +3 -3
- torch_geometric/nn/conv/hgt_conv.py +1 -1
- torch_geometric/nn/conv/message_passing.py +100 -82
- torch_geometric/nn/conv/mixhop_conv.py +1 -1
- torch_geometric/nn/conv/rgcn_conv.py +2 -1
- torch_geometric/nn/conv/spline_conv.py +4 -4
- torch_geometric/nn/conv/x_conv.py +3 -2
- torch_geometric/nn/dense/linear.py +5 -4
- torch_geometric/nn/fx.py +3 -3
- torch_geometric/nn/model_hub.py +3 -1
- torch_geometric/nn/models/__init__.py +10 -2
- torch_geometric/nn/models/deep_graph_infomax.py +1 -2
- torch_geometric/nn/models/dimenet_utils.py +5 -7
- torch_geometric/nn/models/g_retriever.py +230 -0
- torch_geometric/nn/models/git_mol.py +336 -0
- torch_geometric/nn/models/glem.py +385 -0
- torch_geometric/nn/models/gnnff.py +0 -1
- torch_geometric/nn/models/graph_unet.py +12 -3
- torch_geometric/nn/models/jumping_knowledge.py +63 -4
- torch_geometric/nn/models/lightgcn.py +1 -1
- torch_geometric/nn/models/metapath2vec.py +3 -4
- torch_geometric/nn/models/molecule_gpt.py +222 -0
- torch_geometric/nn/models/node2vec.py +1 -2
- torch_geometric/nn/models/schnet.py +2 -1
- torch_geometric/nn/models/signed_gcn.py +3 -3
- torch_geometric/nn/module_dict.py +2 -2
- torch_geometric/nn/nlp/__init__.py +9 -0
- torch_geometric/nn/nlp/llm.py +322 -0
- torch_geometric/nn/nlp/sentence_transformer.py +134 -0
- torch_geometric/nn/nlp/vision_transformer.py +33 -0
- torch_geometric/nn/norm/batch_norm.py +1 -1
- torch_geometric/nn/parameter_dict.py +2 -2
- torch_geometric/nn/pool/__init__.py +7 -5
- torch_geometric/nn/pool/cluster_pool.py +145 -0
- torch_geometric/nn/pool/connect/base.py +0 -1
- torch_geometric/nn/pool/edge_pool.py +1 -1
- torch_geometric/nn/pool/graclus.py +4 -2
- torch_geometric/nn/pool/select/base.py +0 -1
- torch_geometric/nn/pool/voxel_grid.py +3 -2
- torch_geometric/nn/resolver.py +1 -1
- torch_geometric/nn/sequential.jinja +10 -23
- torch_geometric/nn/sequential.py +203 -77
- torch_geometric/nn/summary.py +1 -1
- torch_geometric/nn/to_hetero_with_bases_transformer.py +19 -19
- torch_geometric/profile/__init__.py +2 -0
- torch_geometric/profile/nvtx.py +66 -0
- torch_geometric/profile/profiler.py +24 -15
- torch_geometric/resolver.py +1 -1
- torch_geometric/sampler/base.py +34 -13
- torch_geometric/sampler/neighbor_sampler.py +11 -10
- torch_geometric/testing/decorators.py +17 -22
- torch_geometric/transforms/__init__.py +2 -0
- torch_geometric/transforms/add_metapaths.py +4 -4
- torch_geometric/transforms/add_positional_encoding.py +1 -1
- torch_geometric/transforms/delaunay.py +65 -14
- torch_geometric/transforms/face_to_edge.py +32 -3
- torch_geometric/transforms/gdc.py +7 -6
- torch_geometric/transforms/laplacian_lambda_max.py +2 -2
- torch_geometric/transforms/mask.py +5 -1
- torch_geometric/transforms/node_property_split.py +1 -2
- torch_geometric/transforms/pad.py +7 -6
- torch_geometric/transforms/random_link_split.py +1 -1
- torch_geometric/transforms/remove_self_loops.py +36 -0
- torch_geometric/transforms/svd_feature_reduction.py +1 -1
- torch_geometric/transforms/virtual_node.py +2 -1
- torch_geometric/typing.py +31 -5
- torch_geometric/utils/__init__.py +5 -1
- torch_geometric/utils/_negative_sampling.py +1 -1
- torch_geometric/utils/_normalize_edge_index.py +46 -0
- torch_geometric/utils/_scatter.py +37 -12
- torch_geometric/utils/_subgraph.py +4 -0
- torch_geometric/utils/_tree_decomposition.py +2 -2
- torch_geometric/utils/augmentation.py +1 -1
- torch_geometric/utils/convert.py +5 -5
- torch_geometric/utils/geodesic.py +24 -22
- torch_geometric/utils/hetero.py +1 -1
- torch_geometric/utils/map.py +1 -1
- torch_geometric/utils/smiles.py +66 -28
- torch_geometric/utils/sparse.py +25 -10
- torch_geometric/visualization/graph.py +3 -4
@@ -2,7 +2,7 @@ import copy
|
|
2
2
|
import math
|
3
3
|
import sys
|
4
4
|
import warnings
|
5
|
-
from typing import Callable, Dict, List, Optional, Tuple, Union
|
5
|
+
from typing import Callable, Dict, List, Literal, Optional, Tuple, Union
|
6
6
|
|
7
7
|
import torch
|
8
8
|
from torch import Tensor
|
@@ -168,7 +168,7 @@ class NeighborSampler(BaseSampler):
|
|
168
168
|
attrs = [attr for attr in feature_store.get_all_tensor_attrs()]
|
169
169
|
|
170
170
|
edge_attrs = graph_store.get_all_edge_attrs()
|
171
|
-
self.edge_types = list(
|
171
|
+
self.edge_types = list({attr.edge_type for attr in edge_attrs})
|
172
172
|
|
173
173
|
if weight_attr is not None:
|
174
174
|
raise NotImplementedError(
|
@@ -593,7 +593,7 @@ def edge_sample(
|
|
593
593
|
src_node_time = node_time
|
594
594
|
|
595
595
|
src_neg = neg_sample(src, neg_sampling, num_src_nodes, src_time,
|
596
|
-
src_node_time)
|
596
|
+
src_node_time, endpoint='src')
|
597
597
|
src = torch.cat([src, src_neg], dim=0)
|
598
598
|
|
599
599
|
if isinstance(node_time, dict):
|
@@ -602,7 +602,7 @@ def edge_sample(
|
|
602
602
|
dst_node_time = node_time
|
603
603
|
|
604
604
|
dst_neg = neg_sample(dst, neg_sampling, num_dst_nodes, dst_time,
|
605
|
-
dst_node_time)
|
605
|
+
dst_node_time, endpoint='dst')
|
606
606
|
dst = torch.cat([dst, dst_neg], dim=0)
|
607
607
|
|
608
608
|
if edge_label is None:
|
@@ -623,7 +623,7 @@ def edge_sample(
|
|
623
623
|
dst_node_time = node_time
|
624
624
|
|
625
625
|
dst_neg = neg_sample(dst, neg_sampling, num_dst_nodes, dst_time,
|
626
|
-
dst_node_time)
|
626
|
+
dst_node_time, endpoint='dst')
|
627
627
|
dst = torch.cat([dst, dst_neg], dim=0)
|
628
628
|
|
629
629
|
assert edge_label is None
|
@@ -631,7 +631,7 @@ def edge_sample(
|
|
631
631
|
if edge_label_time is not None:
|
632
632
|
dst_time = edge_label_time.repeat(1 + neg_sampling.amount)
|
633
633
|
|
634
|
-
#
|
634
|
+
# Heterogeneous Neighborhood Sampling #####################################
|
635
635
|
|
636
636
|
if input_type is not None:
|
637
637
|
seed_time_dict = None
|
@@ -724,7 +724,7 @@ def edge_sample(
|
|
724
724
|
src_time,
|
725
725
|
)
|
726
726
|
|
727
|
-
#
|
727
|
+
# Homogeneous Neighborhood Sampling #######################################
|
728
728
|
|
729
729
|
else:
|
730
730
|
|
@@ -781,12 +781,13 @@ def neg_sample(
|
|
781
781
|
num_nodes: int,
|
782
782
|
seed_time: Optional[Tensor],
|
783
783
|
node_time: Optional[Tensor],
|
784
|
+
endpoint: Literal['str', 'dst'],
|
784
785
|
) -> Tensor:
|
785
786
|
num_neg = math.ceil(seed.numel() * neg_sampling.amount)
|
786
787
|
|
787
788
|
# TODO: Do not sample false negatives.
|
788
789
|
if node_time is None:
|
789
|
-
return neg_sampling.sample(num_neg, num_nodes)
|
790
|
+
return neg_sampling.sample(num_neg, endpoint, num_nodes)
|
790
791
|
|
791
792
|
# If we are in a temporal-sampling scenario, we need to respect the
|
792
793
|
# timestamp of the given nodes we can use as negative examples.
|
@@ -800,7 +801,7 @@ def neg_sample(
|
|
800
801
|
num_samples = math.ceil(neg_sampling.amount)
|
801
802
|
seed_time = seed_time.view(1, -1).expand(num_samples, -1)
|
802
803
|
|
803
|
-
out = neg_sampling.sample(num_samples * seed.numel(), num_nodes)
|
804
|
+
out = neg_sampling.sample(num_samples * seed.numel(), endpoint, num_nodes)
|
804
805
|
out = out.view(num_samples, seed.numel())
|
805
806
|
mask = node_time[out] > seed_time # holds all invalid samples.
|
806
807
|
neg_sampling_complete = False
|
@@ -811,7 +812,7 @@ def neg_sample(
|
|
811
812
|
break
|
812
813
|
|
813
814
|
# Greedily search for alternative negatives.
|
814
|
-
out[mask] = tmp = neg_sampling.sample(num_invalid, num_nodes)
|
815
|
+
out[mask] = tmp = neg_sampling.sample(num_invalid, endpoint, num_nodes)
|
815
816
|
mask[mask.clone()] = node_time[tmp] >= seed_time[mask]
|
816
817
|
|
817
818
|
if not neg_sampling_complete: # pragma: no cover
|
@@ -7,7 +7,9 @@ from typing import Callable
|
|
7
7
|
|
8
8
|
import torch
|
9
9
|
from packaging.requirements import Requirement
|
10
|
+
from packaging.version import Version
|
10
11
|
|
12
|
+
import torch_geometric
|
11
13
|
from torch_geometric.typing import WITH_METIS, WITH_PYG_LIB, WITH_TORCH_SPARSE
|
12
14
|
from torch_geometric.visualization.graph import has_graphviz
|
13
15
|
|
@@ -112,13 +114,8 @@ def onlyCUDA(func: Callable) -> Callable:
|
|
112
114
|
def onlyXPU(func: Callable) -> Callable:
|
113
115
|
r"""A decorator to skip tests if XPU is not found."""
|
114
116
|
import pytest
|
115
|
-
try:
|
116
|
-
import intel_extension_for_pytorch as ipex
|
117
|
-
xpu_available = ipex.xpu.is_available()
|
118
|
-
except ImportError:
|
119
|
-
xpu_available = False
|
120
117
|
return pytest.mark.skipif(
|
121
|
-
not
|
118
|
+
not torch_geometric.is_xpu_available(),
|
122
119
|
reason="XPU not available",
|
123
120
|
)(func)
|
124
121
|
|
@@ -176,24 +173,23 @@ def has_package(package: str) -> bool:
|
|
176
173
|
req = Requirement(package)
|
177
174
|
if find_spec(req.name) is None:
|
178
175
|
return False
|
179
|
-
module = import_module(req.name)
|
180
|
-
if not hasattr(module, '__version__'):
|
181
|
-
return True
|
182
176
|
|
183
|
-
|
184
|
-
|
185
|
-
|
186
|
-
|
187
|
-
version = '.'.join(version.split('.dev')[:-1])
|
177
|
+
try:
|
178
|
+
module = import_module(req.name)
|
179
|
+
if not hasattr(module, '__version__'):
|
180
|
+
return True
|
188
181
|
|
189
|
-
|
182
|
+
version = Version(module.__version__).base_version
|
183
|
+
return version in req.specifier
|
184
|
+
except Exception:
|
185
|
+
return False
|
190
186
|
|
191
187
|
|
192
188
|
def withPackage(*args: str) -> Callable:
|
193
189
|
r"""A decorator to skip tests if certain packages are not installed.
|
194
190
|
Also supports version specification.
|
195
191
|
"""
|
196
|
-
na_packages =
|
192
|
+
na_packages = {package for package in args if not has_package(package)}
|
197
193
|
|
198
194
|
if len(na_packages) == 1:
|
199
195
|
reason = f"Package {list(na_packages)[0]} not found"
|
@@ -227,12 +223,11 @@ def withDevice(func: Callable) -> Callable:
|
|
227
223
|
if torch.cuda.is_available():
|
228
224
|
devices.append(pytest.param(torch.device('cuda:0'), id='cuda:0'))
|
229
225
|
|
230
|
-
if
|
231
|
-
|
232
|
-
|
233
|
-
|
234
|
-
|
235
|
-
pass
|
226
|
+
if torch_geometric.is_mps_available():
|
227
|
+
devices.append(pytest.param(torch.device('mps:0'), id='mps'))
|
228
|
+
|
229
|
+
if torch_geometric.is_xpu_available():
|
230
|
+
devices.append(pytest.param(torch.device('xpu:0'), id='xpu'))
|
236
231
|
|
237
232
|
# Additional devices can be registered through environment variables:
|
238
233
|
device = os.getenv('TORCH_DEVICE')
|
@@ -20,6 +20,7 @@ from .target_indegree import TargetIndegree
|
|
20
20
|
from .local_degree_profile import LocalDegreeProfile
|
21
21
|
from .add_self_loops import AddSelfLoops
|
22
22
|
from .add_remaining_self_loops import AddRemainingSelfLoops
|
23
|
+
from .remove_self_loops import RemoveSelfLoops
|
23
24
|
from .remove_isolated_nodes import RemoveIsolatedNodes
|
24
25
|
from .remove_duplicated_edges import RemoveDuplicatedEdges
|
25
26
|
from .knn_graph import KNNGraph
|
@@ -87,6 +88,7 @@ graph_transforms = [
|
|
87
88
|
'LocalDegreeProfile',
|
88
89
|
'AddSelfLoops',
|
89
90
|
'AddRemainingSelfLoops',
|
91
|
+
'RemoveSelfLoops',
|
90
92
|
'RemoveIsolatedNodes',
|
91
93
|
'RemoveDuplicatedEdges',
|
92
94
|
'KNNGraph',
|
@@ -37,7 +37,7 @@ class AddMetaPaths(BaseTransform):
|
|
37
37
|
:class:`~torch_geometric.data.HeteroData` object as edge type
|
38
38
|
:obj:`(src_node_type, "metapath_*", dst_node_type)`, where
|
39
39
|
:obj:`src_node_type` and :obj:`dst_node_type` denote :math:`\mathcal{V}_1`
|
40
|
-
and :math:`\mathcal{V}_{\ell}`,
|
40
|
+
and :math:`\mathcal{V}_{\ell}`, respectively.
|
41
41
|
|
42
42
|
In addition, a :obj:`metapath_dict` object is added to the
|
43
43
|
:class:`~torch_geometric.data.HeteroData` object which maps the
|
@@ -108,12 +108,12 @@ class AddMetaPaths(BaseTransform):
|
|
108
108
|
**kwargs: bool,
|
109
109
|
) -> None:
|
110
110
|
if 'drop_orig_edges' in kwargs:
|
111
|
-
warnings.warn("'drop_orig_edges' is
|
111
|
+
warnings.warn("'drop_orig_edges' is deprecated. Use "
|
112
112
|
"'drop_orig_edge_types' instead")
|
113
113
|
drop_orig_edge_types = kwargs['drop_orig_edges']
|
114
114
|
|
115
115
|
if 'drop_unconnected_nodes' in kwargs:
|
116
|
-
warnings.warn("'drop_unconnected_nodes' is
|
116
|
+
warnings.warn("'drop_unconnected_nodes' is deprecated. Use "
|
117
117
|
"'drop_unconnected_node_types' instead")
|
118
118
|
drop_unconnected_node_types = kwargs['drop_unconnected_nodes']
|
119
119
|
|
@@ -231,7 +231,7 @@ class AddRandomMetaPaths(BaseTransform):
|
|
231
231
|
will drop node types not connected by any edge type.
|
232
232
|
(default: :obj:`False`)
|
233
233
|
walks_per_node (int, List[int], optional): The number of random walks
|
234
|
-
for each starting node in a
|
234
|
+
for each starting node in a metapath. (default: :obj:`1`)
|
235
235
|
sample_ratio (float, optional): The ratio of source nodes to start
|
236
236
|
random walks from. (default: :obj:`1.0`)
|
237
237
|
"""
|
@@ -92,7 +92,7 @@ class AddLaplacianEigenvectorPE(BaseTransform):
|
|
92
92
|
from numpy.linalg import eig, eigh
|
93
93
|
eig_fn = eig if not self.is_undirected else eigh
|
94
94
|
|
95
|
-
eig_vals, eig_vecs = eig_fn(L.todense())
|
95
|
+
eig_vals, eig_vecs = eig_fn(L.todense())
|
96
96
|
else:
|
97
97
|
from scipy.sparse.linalg import eigs, eigsh
|
98
98
|
eig_fn = eigs if not self.is_undirected else eigsh
|
@@ -1,4 +1,5 @@
|
|
1
|
-
import
|
1
|
+
from typing import List
|
2
|
+
|
2
3
|
import torch
|
3
4
|
|
4
5
|
from torch_geometric.data import Data
|
@@ -6,28 +7,78 @@ from torch_geometric.data.datapipes import functional_transform
|
|
6
7
|
from torch_geometric.transforms import BaseTransform
|
7
8
|
|
8
9
|
|
10
|
+
class _QhullTransform(BaseTransform):
|
11
|
+
r"""Q-hull implementation of delaunay triangulation."""
|
12
|
+
def forward(self, data: Data) -> Data:
|
13
|
+
assert data.pos is not None
|
14
|
+
import scipy.spatial
|
15
|
+
|
16
|
+
pos = data.pos.cpu().numpy()
|
17
|
+
tri = scipy.spatial.Delaunay(pos, qhull_options='QJ')
|
18
|
+
face = torch.from_numpy(tri.simplices)
|
19
|
+
|
20
|
+
data.face = face.t().contiguous().to(data.pos.device, torch.long)
|
21
|
+
return data
|
22
|
+
|
23
|
+
|
24
|
+
class _ShullTransform(BaseTransform):
|
25
|
+
r"""Sweep-hull implementation of delaunay triangulation."""
|
26
|
+
def forward(self, data: Data) -> Data:
|
27
|
+
assert data.pos is not None
|
28
|
+
from torch_delaunay.functional import shull2d
|
29
|
+
|
30
|
+
face = shull2d(data.pos.cpu())
|
31
|
+
data.face = face.t().contiguous().to(data.pos.device)
|
32
|
+
return data
|
33
|
+
|
34
|
+
|
35
|
+
class _SequentialTransform(BaseTransform):
|
36
|
+
r"""Runs the first successful transformation.
|
37
|
+
|
38
|
+
All intermediate exceptions are suppressed except the last.
|
39
|
+
"""
|
40
|
+
def __init__(self, transforms: List[BaseTransform]) -> None:
|
41
|
+
assert len(transforms) > 0
|
42
|
+
self.transforms = transforms
|
43
|
+
|
44
|
+
def forward(self, data: Data) -> Data:
|
45
|
+
for i, transform in enumerate(self.transforms):
|
46
|
+
try:
|
47
|
+
return transform.forward(data)
|
48
|
+
except ImportError as e:
|
49
|
+
if i == len(self.transforms) - 1:
|
50
|
+
raise e
|
51
|
+
return data
|
52
|
+
|
53
|
+
|
9
54
|
@functional_transform('delaunay')
|
10
55
|
class Delaunay(BaseTransform):
|
11
56
|
r"""Computes the delaunay triangulation of a set of points
|
12
57
|
(functional name: :obj:`delaunay`).
|
58
|
+
|
59
|
+
.. hint::
|
60
|
+
Consider installing the
|
61
|
+
`torch_delaunay <https://github.com/ybubnov/torch_delaunay>`_ package
|
62
|
+
to speed up computation.
|
13
63
|
"""
|
64
|
+
def __init__(self) -> None:
|
65
|
+
self._transform = _SequentialTransform([
|
66
|
+
_ShullTransform(),
|
67
|
+
_QhullTransform(),
|
68
|
+
])
|
69
|
+
|
14
70
|
def forward(self, data: Data) -> Data:
|
15
71
|
assert data.pos is not None
|
72
|
+
device = data.pos.device
|
16
73
|
|
17
74
|
if data.pos.size(0) < 2:
|
18
|
-
data.edge_index = torch.
|
19
|
-
|
20
|
-
|
21
|
-
data.edge_index = torch.tensor([[0, 1], [1, 0]],
|
22
|
-
device=data.pos.device)
|
75
|
+
data.edge_index = torch.empty(2, 0, dtype=torch.long,
|
76
|
+
device=device)
|
77
|
+
elif data.pos.size(0) == 2:
|
78
|
+
data.edge_index = torch.tensor([[0, 1], [1, 0]], device=device)
|
23
79
|
elif data.pos.size(0) == 3:
|
24
|
-
data.face = torch.tensor([[0], [1], [2]],
|
25
|
-
|
26
|
-
|
27
|
-
pos = data.pos.cpu().numpy()
|
28
|
-
tri = scipy.spatial.Delaunay(pos, qhull_options='QJ')
|
29
|
-
face = torch.from_numpy(tri.simplices)
|
30
|
-
|
31
|
-
data.face = face.t().contiguous().to(data.pos.device, torch.long)
|
80
|
+
data.face = torch.tensor([[0], [1], [2]], device=device)
|
81
|
+
else:
|
82
|
+
data = self._transform.forward(data)
|
32
83
|
|
33
84
|
return data
|
@@ -8,8 +8,15 @@ from torch_geometric.utils import to_undirected
|
|
8
8
|
|
9
9
|
@functional_transform('face_to_edge')
|
10
10
|
class FaceToEdge(BaseTransform):
|
11
|
-
r"""Converts mesh faces :obj:`[3, num_faces]`
|
12
|
-
:obj:`[
|
11
|
+
r"""Converts mesh faces of shape :obj:`[3, num_faces]` or
|
12
|
+
:obj:`[4, num_faces]` to edge indices of shape :obj:`[2, num_edges]`
|
13
|
+
(functional name: :obj:`face_to_edge`).
|
14
|
+
|
15
|
+
This transform supports both 2D triangular faces, represented by a
|
16
|
+
tensor of shape :obj:`[3, num_faces]`, and 3D tetrahedral mesh faces,
|
17
|
+
represented by a tensor of shape :obj:`[4, num_faces]`. It will convert
|
18
|
+
these faces into edge indices, where each edge is defined by the indices
|
19
|
+
of its two endpoints.
|
13
20
|
|
14
21
|
Args:
|
15
22
|
remove_faces (bool, optional): If set to :obj:`False`, the face tensor
|
@@ -22,7 +29,29 @@ class FaceToEdge(BaseTransform):
|
|
22
29
|
if hasattr(data, 'face'):
|
23
30
|
assert data.face is not None
|
24
31
|
face = data.face
|
25
|
-
|
32
|
+
|
33
|
+
if face.size(0) not in [3, 4]:
|
34
|
+
raise RuntimeError(f"Expected 'face' tensor with shape "
|
35
|
+
f"[3, num_faces] or [4, num_faces] "
|
36
|
+
f"(got {list(face.size())})")
|
37
|
+
|
38
|
+
if face.size()[0] == 3:
|
39
|
+
edge_index = torch.cat([
|
40
|
+
face[:2],
|
41
|
+
face[1:],
|
42
|
+
face[::2],
|
43
|
+
], dim=1)
|
44
|
+
else:
|
45
|
+
assert face.size()[0] == 4
|
46
|
+
edge_index = torch.cat([
|
47
|
+
face[:2],
|
48
|
+
face[1:3],
|
49
|
+
face[2:4],
|
50
|
+
face[::2],
|
51
|
+
face[1::2],
|
52
|
+
face[::3],
|
53
|
+
], dim=1)
|
54
|
+
|
26
55
|
edge_index = to_undirected(edge_index, num_nodes=data.num_nodes)
|
27
56
|
|
28
57
|
data.edge_index = edge_index
|
@@ -2,7 +2,6 @@ from typing import Any, Dict, Tuple
|
|
2
2
|
|
3
3
|
import numpy as np
|
4
4
|
import torch
|
5
|
-
from scipy.linalg import expm
|
6
5
|
from torch import Tensor
|
7
6
|
|
8
7
|
from torch_geometric.data import Data
|
@@ -22,7 +21,7 @@ from torch_geometric.utils import (
|
|
22
21
|
@functional_transform('gdc')
|
23
22
|
class GDC(BaseTransform):
|
24
23
|
r"""Processes the graph via Graph Diffusion Convolution (GDC) from the
|
25
|
-
`"Diffusion Improves Graph Learning" <https://
|
24
|
+
`"Diffusion Improves Graph Learning" <https://arxiv.org/abs/1911.05485>`_
|
26
25
|
paper (functional name: :obj:`gdc`).
|
27
26
|
|
28
27
|
.. note::
|
@@ -338,10 +337,10 @@ class GDC(BaseTransform):
|
|
338
337
|
|
339
338
|
elif method == 'heat':
|
340
339
|
raise NotImplementedError(
|
341
|
-
|
342
|
-
|
343
|
-
|
344
|
-
|
340
|
+
'Currently no fast heat kernel is implemented. You are '
|
341
|
+
'welcome to create one yourself, e.g., based on '
|
342
|
+
'"Kloster and Gleich: Heat kernel based community detection '
|
343
|
+
'(KDD 2014)."')
|
345
344
|
else:
|
346
345
|
raise ValueError(f"Approximate GDC diffusion '{method}' unknown")
|
347
346
|
|
@@ -473,6 +472,8 @@ class GDC(BaseTransform):
|
|
473
472
|
|
474
473
|
:rtype: (:class:`Tensor`)
|
475
474
|
"""
|
475
|
+
from scipy.linalg import expm
|
476
|
+
|
476
477
|
if symmetric:
|
477
478
|
e, V = torch.linalg.eigh(matrix, UPLO='U')
|
478
479
|
diff_mat = V @ torch.diag(e.exp()) @ V.t()
|
@@ -1,7 +1,5 @@
|
|
1
1
|
from typing import Optional
|
2
2
|
|
3
|
-
from scipy.sparse.linalg import eigs, eigsh
|
4
|
-
|
5
3
|
from torch_geometric.data import Data
|
6
4
|
from torch_geometric.data.datapipes import functional_transform
|
7
5
|
from torch_geometric.transforms import BaseTransform
|
@@ -41,6 +39,8 @@ class LaplacianLambdaMax(BaseTransform):
|
|
41
39
|
self.is_undirected = is_undirected
|
42
40
|
|
43
41
|
def forward(self, data: Data) -> Data:
|
42
|
+
from scipy.sparse.linalg import eigs, eigsh
|
43
|
+
|
44
44
|
assert data.edge_index is not None
|
45
45
|
num_nodes = data.num_nodes
|
46
46
|
|
@@ -19,7 +19,11 @@ def get_attrs_with_suffix(
|
|
19
19
|
return [key for key in store.keys() if key.endswith(suffix)]
|
20
20
|
|
21
21
|
|
22
|
-
def get_mask_size(
|
22
|
+
def get_mask_size(
|
23
|
+
attr: str,
|
24
|
+
store: BaseStorage,
|
25
|
+
size: Optional[int],
|
26
|
+
) -> Optional[int]:
|
23
27
|
if size is not None:
|
24
28
|
return size
|
25
29
|
return store.num_edges if store.is_edge_attr(attr) else store.num_nodes
|
@@ -44,7 +44,6 @@ class NodePropertySplit(BaseTransform):
|
|
44
44
|
of the node property, so that nodes with greater values of the
|
45
45
|
property are considered to be OOD (default: :obj:`True`)
|
46
46
|
|
47
|
-
Example:
|
48
47
|
.. code-block:: python
|
49
48
|
|
50
49
|
from torch_geometric.transforms import NodePropertySplit
|
@@ -54,7 +53,7 @@ class NodePropertySplit(BaseTransform):
|
|
54
53
|
|
55
54
|
property_name = 'popularity'
|
56
55
|
ratios = [0.3, 0.1, 0.1, 0.3, 0.2]
|
57
|
-
|
56
|
+
transform = NodePropertySplit(property_name, ratios)
|
58
57
|
|
59
58
|
data = transform(data)
|
60
59
|
"""
|
@@ -262,15 +262,14 @@ class Pad(BaseTransform):
|
|
262
262
|
All the attributes of node types other than :obj:`v0` and :obj:`v1` are
|
263
263
|
padded using a value of :obj:`1.0`.
|
264
264
|
All the attributes of the :obj:`('v0', 'e0', 'v1')` edge type are padded
|
265
|
-
|
265
|
+
using a value of :obj:`3.5`.
|
266
266
|
The :obj:`edge_attr` attributes of the :obj:`('v1', 'e0', 'v0')` edge type
|
267
267
|
are padded using a value of :obj:`-1.5`, and any other attributes of this
|
268
268
|
edge type are padded using a value of :obj:`5.5`.
|
269
269
|
All the attributes of edge types other than these two are padded using a
|
270
270
|
value of :obj:`1.5`.
|
271
271
|
|
272
|
-
|
273
|
-
.. code-block::
|
272
|
+
.. code-block:: python
|
274
273
|
|
275
274
|
num_nodes = {'v0': 10, 'v1': 20, 'v2':30}
|
276
275
|
num_edges = {('v0', 'e0', 'v1'): 80}
|
@@ -467,9 +466,11 @@ class Pad(BaseTransform):
|
|
467
466
|
edge_type: Optional[EdgeType] = None,
|
468
467
|
) -> None:
|
469
468
|
|
470
|
-
attrs_to_pad =
|
471
|
-
attr
|
472
|
-
|
469
|
+
attrs_to_pad = {
|
470
|
+
attr
|
471
|
+
for attr in store.keys()
|
472
|
+
if store.is_edge_attr(attr) and self.__should_pad_edge_attr(attr)
|
473
|
+
}
|
473
474
|
if not attrs_to_pad:
|
474
475
|
return
|
475
476
|
num_target_edges = self.max_num_edges.get_value(edge_type)
|
@@ -0,0 +1,36 @@
|
|
1
|
+
from typing import Union
|
2
|
+
|
3
|
+
from torch_geometric.data import Data, HeteroData
|
4
|
+
from torch_geometric.data.datapipes import functional_transform
|
5
|
+
from torch_geometric.transforms import BaseTransform
|
6
|
+
from torch_geometric.utils import remove_self_loops
|
7
|
+
|
8
|
+
|
9
|
+
@functional_transform('remove_self_loops')
|
10
|
+
class RemoveSelfLoops(BaseTransform):
|
11
|
+
r"""Removes all self-loops in the given homogeneous or heterogeneous
|
12
|
+
graph (functional name: :obj:`remove_self_loops`).
|
13
|
+
|
14
|
+
Args:
|
15
|
+
attr (str, optional): The name of the attribute of edge weights
|
16
|
+
or multi-dimensional edge features to pass to
|
17
|
+
:meth:`torch_geometric.utils.remove_self_loops`.
|
18
|
+
(default: :obj:`"edge_weight"`)
|
19
|
+
"""
|
20
|
+
def __init__(self, attr: str = 'edge_weight') -> None:
|
21
|
+
self.attr = attr
|
22
|
+
|
23
|
+
def forward(
|
24
|
+
self,
|
25
|
+
data: Union[Data, HeteroData],
|
26
|
+
) -> Union[Data, HeteroData]:
|
27
|
+
for store in data.edge_stores:
|
28
|
+
if store.is_bipartite() or 'edge_index' not in store:
|
29
|
+
continue
|
30
|
+
|
31
|
+
store.edge_index, store[self.attr] = remove_self_loops(
|
32
|
+
store.edge_index,
|
33
|
+
edge_attr=store.get(self.attr, None),
|
34
|
+
)
|
35
|
+
|
36
|
+
return data
|
@@ -11,7 +11,7 @@ class SVDFeatureReduction(BaseTransform):
|
|
11
11
|
Decomposition (SVD) (functional name: :obj:`svd_feature_reduction`).
|
12
12
|
|
13
13
|
Args:
|
14
|
-
out_channels (int): The
|
14
|
+
out_channels (int): The dimensionality of node features after
|
15
15
|
reduction.
|
16
16
|
"""
|
17
17
|
def __init__(self, out_channels: int):
|
@@ -37,7 +37,8 @@ class VirtualNode(BaseTransform):
|
|
37
37
|
col = torch.cat([col, full, arange], dim=0)
|
38
38
|
edge_index = torch.stack([row, col], dim=0)
|
39
39
|
|
40
|
-
|
40
|
+
num_edge_types = int(edge_type.max()) if edge_type.numel() > 0 else 0
|
41
|
+
new_type = edge_type.new_full((num_nodes, ), num_edge_types + 1)
|
41
42
|
edge_type = torch.cat([edge_type, new_type, new_type + 1], dim=0)
|
42
43
|
|
43
44
|
old_data = copy.copy(data)
|
torch_geometric/typing.py
CHANGED
@@ -13,6 +13,9 @@ WITH_PT20 = int(torch.__version__.split('.')[0]) >= 2
|
|
13
13
|
WITH_PT21 = WITH_PT20 and int(torch.__version__.split('.')[1]) >= 1
|
14
14
|
WITH_PT22 = WITH_PT20 and int(torch.__version__.split('.')[1]) >= 2
|
15
15
|
WITH_PT23 = WITH_PT20 and int(torch.__version__.split('.')[1]) >= 3
|
16
|
+
WITH_PT24 = WITH_PT20 and int(torch.__version__.split('.')[1]) >= 4
|
17
|
+
WITH_PT25 = WITH_PT20 and int(torch.__version__.split('.')[1]) >= 5
|
18
|
+
WITH_PT26 = WITH_PT20 and int(torch.__version__.split('.')[1]) >= 6
|
16
19
|
WITH_PT111 = WITH_PT20 or int(torch.__version__.split('.')[1]) >= 11
|
17
20
|
WITH_PT112 = WITH_PT20 or int(torch.__version__.split('.')[1]) >= 12
|
18
21
|
WITH_PT113 = WITH_PT20 or int(torch.__version__.split('.')[1]) >= 13
|
@@ -304,6 +307,8 @@ class EdgeTypeStr(str):
|
|
304
307
|
r"""A helper class to construct serializable edge types by merging an edge
|
305
308
|
type tuple into a single string.
|
306
309
|
"""
|
310
|
+
edge_type: tuple[str, str, str]
|
311
|
+
|
307
312
|
def __new__(cls, *args: Any) -> 'EdgeTypeStr':
|
308
313
|
if isinstance(args[0], (list, tuple)):
|
309
314
|
# Unwrap `EdgeType((src, rel, dst))` and `EdgeTypeStr((src, dst))`:
|
@@ -311,27 +316,37 @@ class EdgeTypeStr(str):
|
|
311
316
|
|
312
317
|
if len(args) == 1 and isinstance(args[0], str):
|
313
318
|
arg = args[0] # An edge type string was passed.
|
319
|
+
edge_type = tuple(arg.split(EDGE_TYPE_STR_SPLIT))
|
320
|
+
if len(edge_type) != 3:
|
321
|
+
raise ValueError(f"Cannot convert the edge type '{arg}' to a "
|
322
|
+
f"tuple since it holds invalid characters")
|
314
323
|
|
315
324
|
elif len(args) == 2 and all(isinstance(arg, str) for arg in args):
|
316
325
|
# A `(src, dst)` edge type was passed - add `DEFAULT_REL`:
|
317
|
-
|
326
|
+
edge_type = (args[0], DEFAULT_REL, args[1])
|
327
|
+
arg = EDGE_TYPE_STR_SPLIT.join(edge_type)
|
318
328
|
|
319
329
|
elif len(args) == 3 and all(isinstance(arg, str) for arg in args):
|
320
330
|
# A `(src, rel, dst)` edge type was passed:
|
331
|
+
edge_type = tuple(args)
|
321
332
|
arg = EDGE_TYPE_STR_SPLIT.join(args)
|
322
333
|
|
323
334
|
else:
|
324
335
|
raise ValueError(f"Encountered invalid edge type '{args}'")
|
325
336
|
|
326
|
-
|
337
|
+
out = str.__new__(cls, arg)
|
338
|
+
out.edge_type = edge_type # type: ignore
|
339
|
+
return out
|
327
340
|
|
328
341
|
def to_tuple(self) -> EdgeType:
|
329
342
|
r"""Returns the original edge type."""
|
330
|
-
|
331
|
-
if len(out) != 3:
|
343
|
+
if len(self.edge_type) != 3:
|
332
344
|
raise ValueError(f"Cannot convert the edge type '{self}' to a "
|
333
345
|
f"tuple since it holds invalid characters")
|
334
|
-
return
|
346
|
+
return self.edge_type
|
347
|
+
|
348
|
+
def __reduce__(self) -> tuple[Any, Any]:
|
349
|
+
return (self.__class__, (self.edge_type, ))
|
335
350
|
|
336
351
|
|
337
352
|
# There exist some short-cuts to query edge-types (given that the full triplet
|
@@ -369,3 +384,14 @@ MaybeHeteroEdgeTensor = Union[Tensor, Dict[EdgeType, Tensor]]
|
|
369
384
|
|
370
385
|
InputNodes = Union[OptTensor, NodeType, Tuple[NodeType, OptTensor]]
|
371
386
|
InputEdges = Union[OptTensor, EdgeType, Tuple[EdgeType, OptTensor]]
|
387
|
+
|
388
|
+
# Serialization ###############################################################
|
389
|
+
|
390
|
+
if WITH_PT24:
|
391
|
+
torch.serialization.add_safe_globals([
|
392
|
+
SparseTensor,
|
393
|
+
SparseStorage,
|
394
|
+
TensorFrame,
|
395
|
+
MockTorchCSCTensor,
|
396
|
+
EdgeTypeStr,
|
397
|
+
])
|