graphdatascience 2.0a6__py3-none-any.whl → 2.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. graphdatascience/arrow_client/arrow_info.py +19 -6
  2. graphdatascience/arrow_client/authenticated_flight_client.py +60 -10
  3. graphdatascience/error/not_available_outside_aura.py +5 -0
  4. graphdatascience/graph_data_science.py +101 -9
  5. graphdatascience/procedure_surface/api/catalog/catalog_endpoints.py +11 -1
  6. graphdatascience/procedure_surface/api/catalog/relationships_endpoints.py +20 -2
  7. graphdatascience/procedure_surface/api/centrality/closeness_endpoints.py +9 -0
  8. graphdatascience/procedure_surface/api/job_handle.py +1 -1
  9. graphdatascience/procedure_surface/api/node_embedding/__init__.py +55 -1
  10. graphdatascience/procedure_surface/api/node_embedding/config.py +36 -12
  11. graphdatascience/procedure_surface/api/node_embedding/{train_endpoints.py → embedding_endpoints.py} +31 -37
  12. graphdatascience/procedure_surface/api/node_embedding/fastpath_endpoints.py +2 -0
  13. graphdatascience/procedure_surface/api/node_embedding/graphsage_endpoints.py +48 -0
  14. graphdatascience/procedure_surface/api/node_embedding/graphsage_results.py +51 -0
  15. graphdatascience/procedure_surface/api/node_embedding/graphsage_supervised_endpoints.py +242 -0
  16. graphdatascience/procedure_surface/api/node_embedding/graphsage_supervised_model.py +193 -0
  17. graphdatascience/procedure_surface/api/node_embedding/{predict_endpoints.py → graphsage_unsupervised_endpoints.py} +138 -124
  18. graphdatascience/procedure_surface/api/node_embedding/graphsage_unsupervised_model.py +185 -0
  19. graphdatascience/procedure_surface/api/pipeline/link_prediction_pipeline_endpoints.py +20 -0
  20. graphdatascience/procedure_surface/api/pipeline/node_classification_pipeline_endpoints.py +20 -0
  21. graphdatascience/procedure_surface/api/pipeline/node_regression_pipeline.py +1 -1
  22. graphdatascience/procedure_surface/api/pipeline/node_regression_pipeline_endpoints.py +20 -1
  23. graphdatascience/procedure_surface/api/topological_link_prediction_endpoints.py +32 -16
  24. graphdatascience/procedure_surface/api/write_job_handle.py +1 -1
  25. graphdatascience/procedure_surface/api/write_protocol.py +34 -0
  26. graphdatascience/procedure_surface/arrow/catalog/catalog_arrow_endpoints.py +9 -8
  27. graphdatascience/procedure_surface/arrow/catalog/relationship_arrow_endpoints.py +8 -2
  28. graphdatascience/procedure_surface/arrow/centrality/closeness_arrow_endpoints.py +11 -0
  29. graphdatascience/procedure_surface/arrow/node_embedding/{train_arrow_endpoints.py → embedding_arrow_endpoints.py} +28 -72
  30. graphdatascience/procedure_surface/arrow/node_embedding/fastpath_arrow_endpoints.py +4 -0
  31. graphdatascience/procedure_surface/arrow/node_embedding/graphsage_supervised_arrow_endpoints.py +205 -0
  32. graphdatascience/procedure_surface/arrow/node_embedding/graphsage_train_arrow_endpoints.py +4 -1
  33. graphdatascience/procedure_surface/arrow/node_embedding/graphsage_unsupervised_arrow_endpoints.py +182 -0
  34. graphdatascience/procedure_surface/arrow/pipeline/link_prediction_pipeline_arrow_endpoints.py +11 -0
  35. graphdatascience/procedure_surface/arrow/pipeline/node_classification_pipeline_arrow_endpoints.py +11 -0
  36. graphdatascience/procedure_surface/arrow/pipeline/node_regression_pipeline_arrow_endpoints.py +10 -0
  37. graphdatascience/procedure_surface/arrow/stream_result_mapper.py +11 -0
  38. graphdatascience/procedure_surface/cypher/catalog/catalog_cypher_endpoints.py +10 -12
  39. graphdatascience/procedure_surface/cypher/catalog/relationship_cypher_endpoints.py +5 -5
  40. graphdatascience/procedure_surface/cypher/centrality/closeness_cypher_endpoints.py +8 -0
  41. graphdatascience/procedure_surface/cypher/pipeline/link_prediction_pipeline_cypher_endpoints.py +13 -0
  42. graphdatascience/procedure_surface/cypher/pipeline/node_classification_pipeline_cypher_endpoints.py +13 -0
  43. graphdatascience/procedure_surface/cypher/pipeline/node_regression_pipeline_cypher_endpoints.py +12 -1
  44. graphdatascience/procedure_surface/cypher/topological_link_prediction_cypher_endpoints.py +8 -6
  45. graphdatascience/query_runner/db_environment_resolver.py +2 -2
  46. graphdatascience/query_runner/neo4j_query_runner.py +12 -0
  47. graphdatascience/query_runner/query_mode.py +24 -3
  48. graphdatascience/query_runner/query_runner.py +11 -0
  49. graphdatascience/session/aura_api.py +16 -0
  50. graphdatascience/session/aura_api_responses.py +13 -0
  51. graphdatascience/session/aura_graph_data_science.py +109 -15
  52. graphdatascience/session/endpoint_mappings.py +0 -6
  53. graphdatascience/session/gds_sessions.py +2 -5
  54. graphdatascience/session/remote_ops/project_protocols.py +1 -1
  55. graphdatascience/session/remote_ops/write_protocols.py +3 -31
  56. graphdatascience/version.py +1 -1
  57. {graphdatascience-2.0a6.dist-info → graphdatascience-2.1.dist-info}/METADATA +56 -19
  58. {graphdatascience-2.0a6.dist-info → graphdatascience-2.1.dist-info}/RECORD +61 -59
  59. graphdatascience/procedure_surface/api/node_embedding/embeddings_endpoints.py +0 -29
  60. graphdatascience/procedure_surface/api/node_embedding/encode_endpoints.py +0 -226
  61. graphdatascience/procedure_surface/arrow/node_embedding/embeddings_arrow_endpoints.py +0 -32
  62. graphdatascience/procedure_surface/arrow/node_embedding/encode_arrow_endpoints.py +0 -175
  63. graphdatascience/procedure_surface/arrow/node_embedding/predict_arrow_endpoints.py +0 -174
  64. graphdatascience/procedure_surface/arrow/topological_link_prediction_arrow_endpoints.py +0 -65
  65. {graphdatascience-2.0a6.dist-info → graphdatascience-2.1.dist-info}/WHEEL +0 -0
  66. {graphdatascience-2.0a6.dist-info → graphdatascience-2.1.dist-info}/licenses/LICENSE +0 -0
  67. {graphdatascience-2.0a6.dist-info → graphdatascience-2.1.dist-info}/top_level.txt +0 -0
@@ -2,6 +2,8 @@ from __future__ import annotations
2
2
 
3
3
  from dataclasses import dataclass
4
4
 
5
+ from neo4j.exceptions import Neo4jError
6
+
5
7
  from graphdatascience.query_runner.query_runner import QueryRunner
6
8
  from graphdatascience.query_runner.query_type import QueryType
7
9
 
@@ -15,12 +17,17 @@ class ArrowInfo:
15
17
 
16
18
  @staticmethod
17
19
  def create(query_runner: QueryRunner) -> ArrowInfo:
18
- procResult = query_runner.call_procedure(
19
- endpoint="gds.debug.arrow",
20
- query_type=QueryType.SYSTEM,
21
- custom_error=False,
22
- yields=["listenAddress", "enabled", "running", "versions"],
23
- ).iloc[0]
20
+ try:
21
+ procResult = query_runner.call_procedure(
22
+ endpoint="gds.debug.arrow",
23
+ query_type=QueryType.SYSTEM,
24
+ custom_error=False,
25
+ yields=["listenAddress", "enabled", "running", "versions"],
26
+ ).iloc[0]
27
+ except Neo4jError as e:
28
+ if ArrowInfo._procedure_not_registered(e):
29
+ return ArrowInfo(listenAddress="", enabled=False, running=False, versions=[])
30
+ raise
24
31
 
25
32
  return ArrowInfo(
26
33
  listenAddress=procResult["listenAddress"],
@@ -28,3 +35,9 @@ class ArrowInfo:
28
35
  running=procResult["running"],
29
36
  versions=procResult.get("versions", []),
30
37
  )
38
+
39
+ @staticmethod
40
+ def _procedure_not_registered(e: Neo4jError) -> bool:
41
+ return e.code == "Neo.ClientError.Procedure.ProcedureNotFound" or (
42
+ "no procedure with the name `gds.debug.arrow`" in e.message
43
+ )
@@ -2,7 +2,9 @@ from __future__ import annotations
2
2
 
3
3
  import json
4
4
  import logging
5
+ import math
5
6
  import platform
7
+ import socket
6
8
  from dataclasses import dataclass
7
9
  from types import TracebackType
8
10
  from typing import Any, Callable, Iterator, Type, TypeVar
@@ -39,6 +41,25 @@ FLIGHT_TRANSIENT_EXCEPTIONS = (
39
41
  FlightInternalError,
40
42
  )
41
43
 
44
+ DEFAULT_MAX_ATTEMPTS = 5
45
+ DEFAULT_CALL_TIMEOUT = 30.0
46
+ # Sum of the backoff waits between DEFAULT_MAX_ATTEMPTS attempts under the default
47
+ # wait config `ExponentialWaitConfig(multiplier=1, min=1, max=10)`: 1 + 2 + 4 + 8.
48
+ DEFAULT_BACKOFF_TOTAL = 15
49
+
50
+
51
+ def _default_retry_config(call_timeout: float | None) -> RetryConfigV2:
52
+ # The delay budget must fit all attempts even when every single one runs into the
53
+ # per-call deadline, plus the backoff waits in between. Otherwise one
54
+ # `Deadline Exceeded` exhausts the budget and no retry ever happens.
55
+ budget_timeout = call_timeout if call_timeout is not None else DEFAULT_CALL_TIMEOUT
56
+ after_delay = math.ceil(DEFAULT_MAX_ATTEMPTS * budget_timeout + DEFAULT_BACKOFF_TOTAL)
57
+ return RetryConfigV2(
58
+ retryable_exceptions=list(FLIGHT_TRANSIENT_EXCEPTIONS),
59
+ stop_config=StopConfig(after_delay=after_delay, after_attempt=DEFAULT_MAX_ATTEMPTS),
60
+ wait_config=ExponentialWaitConfig(multiplier=1, min=1, max=10),
61
+ )
62
+
42
63
 
43
64
  class AuthenticatedArrowClient:
44
65
  """Arrow Flight client used to communicate with the GDS Arrow server."""
@@ -72,6 +93,8 @@ class AuthenticatedArrowClient:
72
93
  The user agent string to use for the connection. (default is `neo4j-graphdatascience-v[VERSION] pyarrow-v[PYARROW_VERSION]`)
73
94
  retry_config
74
95
  The retry configuration to use for the Arrow requests send by the client.
96
+ (default: up to 5 attempts with a total delay budget derived from the
97
+ per-call ``call_timeout`` so that timed-out calls are actually retried)
75
98
  advertised_listen_address
76
99
  The advertised listen address of the GDS Arrow server. This will be used by remote projection and writeback operations.
77
100
  health_check
@@ -85,15 +108,11 @@ class AuthenticatedArrowClient:
85
108
  else:
86
109
  host, port = connection_info
87
110
 
88
- if retry_config is None:
89
- retry_config = RetryConfigV2(
90
- retryable_exceptions=list(FLIGHT_TRANSIENT_EXCEPTIONS),
91
- stop_config=StopConfig(after_delay=10, after_attempt=5),
92
- wait_config=ExponentialWaitConfig(multiplier=1, min=1, max=10),
93
- )
94
-
95
111
  options_copy = dict(arrow_client_options) if arrow_client_options else {}
96
- call_timeout = options_copy.pop("call_timeout", 30.0)
112
+ call_timeout = options_copy.pop("call_timeout", DEFAULT_CALL_TIMEOUT)
113
+
114
+ if retry_config is None:
115
+ retry_config = _default_retry_config(call_timeout)
97
116
 
98
117
  self._host = host
99
118
  self._port = int(port)
@@ -219,11 +238,42 @@ class AuthenticatedArrowClient:
219
238
  """
220
239
  try:
221
240
  return operation()
222
- except FLIGHT_TRANSIENT_EXCEPTIONS:
241
+ except FLIGHT_TRANSIENT_EXCEPTIONS as e:
223
242
  if self._health_check:
224
243
  self._health_check.raise_if_unhealthy()
244
+ self._raise_if_grpc_dns_resolver_failed(e)
225
245
  raise
226
246
 
247
+ def _raise_if_grpc_dns_resolver_failed(self, error: Exception) -> None:
248
+ """
249
+ gRPC uses the c-ares DNS resolver that talks directly to the configured nameserver.
250
+ Behind local DNS proxies such as Cloudflare WARP or some VPN clients those queries go unanswered
251
+ while the OS resolver works fine. If gRPC failed to resolve the host but the OS resolver can,
252
+ point the user at the `GRPC_DNS_RESOLVER=native` workaround.
253
+ """
254
+ if not isinstance(error, FlightUnavailableError):
255
+ return
256
+ message = str(error)
257
+ if "address lookup failed" not in message and "errors resolving" not in message:
258
+ return
259
+ if not self._os_resolver_can_resolve_host():
260
+ return
261
+
262
+ raise ConnectionError(
263
+ f"gRPC could not resolve the Arrow server host `{self._host}`, but the operating system resolver can. "
264
+ "This usually happens when a local DNS proxy (e.g. Cloudflare WARP or a VPN client) does not answer "
265
+ "the queries of gRPC's built-in resolver. "
266
+ "Set the environment variable `GRPC_DNS_RESOLVER=native` before importing `graphdatascience` "
267
+ "(for example via `os.environ['GRPC_DNS_RESOLVER'] = 'native'`) to make gRPC use the operating system resolver."
268
+ ) from error
269
+
270
+ def _os_resolver_can_resolve_host(self) -> bool:
271
+ try:
272
+ socket.getaddrinfo(self._host, self._port)
273
+ return True
274
+ except OSError:
275
+ return False
276
+
227
277
  def __enter__(self) -> AuthenticatedArrowClient:
228
278
  return self
229
279
 
@@ -280,7 +330,7 @@ class AuthenticatedArrowClient:
280
330
  def __setstate__(self, state: dict[str, Any]) -> None:
281
331
  self.__dict__.update(state)
282
332
  self.__dict__.setdefault("_health_check", None)
283
- self.__dict__.setdefault("_call_timeout", 30.0)
333
+ self.__dict__.setdefault("_call_timeout", DEFAULT_CALL_TIMEOUT)
284
334
  self.__dict__.setdefault("_call_options", self._build_call_options())
285
335
  self._flight_client = self._instantiate_flight_client()
286
336
 
@@ -0,0 +1,5 @@
1
+ class NotAvailableOutsideAura(Exception):
2
+ def __init__(self, subject: str) -> None:
3
+ super().__init__(
4
+ f"{subject} is not available outside Aura. The underlying Cypher functions are only provided by AuraDBs."
5
+ )
@@ -2,7 +2,7 @@ from __future__ import annotations
2
2
 
3
3
  import warnings
4
4
  from types import TracebackType
5
- from typing import Any, Type
5
+ from typing import Any, Literal, Type
6
6
 
7
7
  import neo4j
8
8
  from neo4j import Driver
@@ -183,6 +183,7 @@ from graphdatascience.query_runner.query_mode import QueryMode
183
183
  from graphdatascience.versions import ServerVersion
184
184
 
185
185
  from .arrow_client.arrow_authentication import UsernamePasswordAuthentication
186
+ from .arrow_client.arrow_client_options_util import disable_server_verification
186
187
  from .arrow_client.arrow_endpoint_version import ArrowEndpointVersion
187
188
  from .arrow_client.arrow_info import ArrowInfo
188
189
  from .arrow_client.authenticated_flight_client import AuthenticatedArrowClient
@@ -272,8 +273,15 @@ class GraphDataScience:
272
273
 
273
274
  self._arrow_client: GdsArrowClient | None = None
274
275
 
275
- arrow_info = ArrowInfo.create(self._query_runner)
276
- if arrow and arrow_info.enabled:
276
+ if isinstance(arrow, str):
277
+ listen_address: str | None = arrow
278
+ elif arrow:
279
+ arrow_info = ArrowInfo.create(self._query_runner)
280
+ listen_address = arrow_info.listenAddress if arrow_info.enabled else None
281
+ else:
282
+ listen_address = None
283
+
284
+ if listen_address is not None:
277
285
  arrow_auth = None
278
286
  if auth is not None:
279
287
  username, password = auth
@@ -287,14 +295,14 @@ class GraphDataScience:
287
295
  "Falling back to use Cypher for GDS. To use Arrow, you must explicitly provide the `auth` parameter."
288
296
  )
289
297
  else:
290
- listen_address = arrow if isinstance(arrow, str) else arrow_info.listenAddress
291
-
292
298
  self._arrow_client = GdsArrowClient(
293
299
  AuthenticatedArrowClient(
294
300
  listen_address,
295
301
  auth=arrow_auth,
296
302
  encrypted=self._query_runner.encrypted(),
297
- arrow_client_options=arrow_client_options,
303
+ arrow_client_options=GraphDataScience._derive_arrow_client_options(
304
+ endpoint, arrow_client_options
305
+ ),
298
306
  )
299
307
  )
300
308
 
@@ -425,6 +433,13 @@ class GraphDataScience:
425
433
  """
426
434
  return BetweennessCypherEndpoints(self._query_runner)
427
435
 
436
+ @property
437
+ def betweenness(self) -> BetweennessEndpoints:
438
+ """
439
+ Return endpoints for the betweenness centrality algorithm.
440
+ """
441
+ return self.betweenness_centrality
442
+
428
443
  @property
429
444
  def bridges(self) -> BridgesEndpoints:
430
445
  """
@@ -460,6 +475,13 @@ class GraphDataScience:
460
475
  """
461
476
  return ClosenessCypherEndpoints(self._query_runner)
462
477
 
478
+ @property
479
+ def closeness(self) -> ClosenessEndpoints:
480
+ """
481
+ Return endpoints for the closeness centrality algorithm.
482
+ """
483
+ return self.closeness_centrality
484
+
463
485
  @property
464
486
  def dag(self) -> DagCypherEndpoints:
465
487
  """
@@ -474,6 +496,13 @@ class GraphDataScience:
474
496
  """
475
497
  return DegreeCypherEndpoints(self._query_runner)
476
498
 
499
+ @property
500
+ def degree(self) -> DegreeEndpoints:
501
+ """
502
+ Return endpoints for the degree centrality algorithm.
503
+ """
504
+ return self.degree_centrality
505
+
477
506
  @property
478
507
  def eigenvector_centrality(self) -> EigenvectorEndpoints:
479
508
  """
@@ -481,6 +510,13 @@ class GraphDataScience:
481
510
  """
482
511
  return EigenvectorCypherEndpoints(self._query_runner)
483
512
 
513
+ @property
514
+ def eigenvector(self) -> EigenvectorEndpoints:
515
+ """
516
+ Return endpoints for the eigenvector centrality algorithm.
517
+ """
518
+ return self.eigenvector_centrality
519
+
484
520
  @property
485
521
  def fast_rp(self) -> FastRPEndpoints:
486
522
  """
@@ -513,6 +549,13 @@ class GraphDataScience:
513
549
  """
514
550
  return ClosenessHarmonicCypherEndpoints(self._query_runner)
515
551
 
552
+ @property
553
+ def harmonic(self) -> ClosenessHarmonicEndpoints:
554
+ """
555
+ Return endpoints for the harmonic centrality algorithm.
556
+ """
557
+ return self.harmonic_centrality
558
+
516
559
  @property
517
560
  def hash_gnn(self) -> HashGNNEndpoints:
518
561
  """
@@ -548,6 +591,13 @@ class GraphDataScience:
548
591
  """
549
592
  return KCoreCypherEndpoints(self._query_runner)
550
593
 
594
+ @property
595
+ def kcore(self) -> KCoreEndpoints:
596
+ """
597
+ Return endpoints for the K-core decomposition algorithm.
598
+ """
599
+ return self.k_core_decomposition
600
+
551
601
  @property
552
602
  def kmeans(self) -> KMeansEndpoints:
553
603
  """
@@ -808,7 +858,8 @@ class GraphDataScience:
808
858
  query: str,
809
859
  params: dict[str, Any] | None = None,
810
860
  database: str | None = None,
811
- mode: QueryMode = QueryMode.WRITE,
861
+ mode: QueryMode | Literal["READ", "WRITE"] = QueryMode.WRITE,
862
+ auto_commit: bool = False,
812
863
  ) -> DataFrame:
813
864
  """
814
865
  Run a Cypher query
@@ -821,8 +872,10 @@ class GraphDataScience:
821
872
  parameters to the query
822
873
  database: str
823
874
  the database on which to run the query
824
- mode: QueryMode
825
- the query mode to use (READ or WRITE). Set based on the operation performed in the query.
875
+ mode
876
+ the query mode to use. Set based on the operation performed in the query.
877
+ auto_commit: bool
878
+ run the query in an auto-commit transaction. This is required for queries using `CALL { ... } IN TRANSACTIONS`.
826
879
 
827
880
  Returns
828
881
  -------
@@ -831,6 +884,11 @@ class GraphDataScience:
831
884
  """
832
885
  query_type = QueryType.USER_DIRECTED
833
886
 
887
+ mode = QueryMode.of(mode)
888
+
889
+ if auto_commit:
890
+ return self._query_runner.run_cypher(query, query_type, params, database, mode, custom_error=False)
891
+
834
892
  return self._query_runner.run_retryable_cypher(
835
893
  query, query_type, params, database, custom_error=False, mode=mode
836
894
  )
@@ -846,6 +904,23 @@ class GraphDataScience:
846
904
  """
847
905
  return self._query_runner.driver_config()
848
906
 
907
+ def db_driver(self) -> neo4j.Driver:
908
+ """
909
+ Get the Neo4j driver used by this client to communicate with the Neo4j DBMS.
910
+
911
+ This is mainly useful when the `run_cypher()` API is too simple for a use case,
912
+ as the driver allows full control over sessions and transactions.
913
+
914
+ The driver is closed by `close()` if the client created it itself, after which it is
915
+ unusable; a driver supplied at construction is never closed by this client.
916
+
917
+ Returns
918
+ -------
919
+ neo4j.Driver
920
+ The Neo4j driver used by this client.
921
+ """
922
+ return self._query_runner.db_driver()
923
+
849
924
  @staticmethod
850
925
  def _derive_aura_ds(endpoint: str, auth: neo4j.Auth | None, database: str | None) -> bool:
851
926
  # Whether a database is hosted in Aura can only be determined by connecting to it,
@@ -858,6 +933,23 @@ class GraphDataScience:
858
933
  finally:
859
934
  detection_runner.close()
860
935
 
936
+ @staticmethod
937
+ def _derive_arrow_client_options(
938
+ endpoint: str | Driver | QueryRunner, arrow_client_options: dict[str, Any] | None
939
+ ) -> dict[str, Any] | None:
940
+ if not isinstance(endpoint, str):
941
+ return arrow_client_options
942
+
943
+ scheme = endpoint.split("://")[0].lower()
944
+ if not scheme.endswith("+ssc"):
945
+ return arrow_client_options
946
+
947
+ options = dict(arrow_client_options) if arrow_client_options else {}
948
+ if "disable_server_verification" in options:
949
+ return options
950
+
951
+ return disable_server_verification(options)
952
+
861
953
  @staticmethod
862
954
  def _validate_endpoint(endpoint: str | Driver | QueryRunner) -> None:
863
955
  if isinstance(endpoint, str):
@@ -2,7 +2,7 @@ from __future__ import annotations
2
2
 
3
3
  from abc import ABC, abstractmethod
4
4
  from types import TracebackType
5
- from typing import Any, NamedTuple, Type
5
+ from typing import Any, List, NamedTuple, Type
6
6
 
7
7
  from pandas import DataFrame
8
8
  from pydantic import field_validator
@@ -289,6 +289,16 @@ class CatalogEndpoints(ABC):
289
289
  return RelationshipPropertiesEndpoints(self.relationships)
290
290
 
291
291
 
292
+ def normalize_graph_names(G: Graph | str | List[Graph | str]) -> List[str]:
293
+ match G:
294
+ case Graph() as graph:
295
+ return [graph.name()]
296
+ case str(name):
297
+ return [name]
298
+ case list(seq):
299
+ return [name for e in seq for name in normalize_graph_names(e)]
300
+
301
+
292
302
  class GraphFilterResult(BaseResult):
293
303
  graph_name: str
294
304
  from_graph_name: str
@@ -170,7 +170,7 @@ class RelationshipsEndpoints(ABC):
170
170
  relationship_type: str,
171
171
  mutate_relationship_type: str,
172
172
  *,
173
- aggregation: Aggregation | dict[str, Aggregation] | None = None,
173
+ aggregation: Aggregation | str | dict[str, Aggregation | str] | None = None,
174
174
  concurrency: int | None = None,
175
175
  sudo: bool = False,
176
176
  log_progress: bool = True,
@@ -189,7 +189,7 @@ class RelationshipsEndpoints(ABC):
189
189
  The input relationship type
190
190
  mutate_relationship_type: str,
191
191
  Name of the relationship type to store the results in.
192
- aggregation: Aggregation | dict[str, Aggregation] | None = None,
192
+ aggregation
193
193
  Specifies how to aggregate parallel relationships in the graph.
194
194
  If a single aggregation is provided, it will be used for properties of the specified relationships.
195
195
  A dictionary can be provided to specify property specific aggregations.
@@ -313,9 +313,27 @@ class CollapsePathResult(BaseResult):
313
313
 
314
314
 
315
315
  class Aggregation(str, Enum):
316
+ """
317
+ Specifies how to aggregate parallel relationships in a graph.
318
+ """
319
+
316
320
  NONE = "NONE"
317
321
  SINGLE = "SINGLE"
318
322
  SUM = "SUM"
319
323
  MIN = "MIN"
320
324
  MAX = "MAX"
321
325
  COUNT = "COUNT"
326
+
327
+ @classmethod
328
+ def of(cls, aggregation: Aggregation | str) -> Aggregation:
329
+ """
330
+ Normalize an `Aggregation` or a plain string into an `Aggregation`.
331
+ """
332
+ if isinstance(aggregation, Aggregation):
333
+ return aggregation
334
+
335
+ valid = [a.value for a in cls]
336
+ if aggregation not in valid:
337
+ raise ValueError(f"Invalid aggregation: '{aggregation}'. Valid values are: {valid}.")
338
+
339
+ return cls(aggregation)
@@ -7,11 +7,20 @@ from pandas import DataFrame
7
7
 
8
8
  from graphdatascience.graph.graph_api import Graph
9
9
  from graphdatascience.procedure_surface.api.base_result import BaseResult
10
+ from graphdatascience.procedure_surface.api.centrality.closeness_harmonic_endpoints import ClosenessHarmonicEndpoints
10
11
  from graphdatascience.procedure_surface.api.default_values import ALL_LABELS, ALL_TYPES
11
12
  from graphdatascience.procedure_surface.api.estimation_result import EstimationResult
12
13
 
13
14
 
14
15
  class ClosenessEndpoints(ABC):
16
+ @property
17
+ @abstractmethod
18
+ def harmonic(self) -> ClosenessHarmonicEndpoints:
19
+ """
20
+ Return endpoints for the harmonic centrality algorithm, a variant of closeness centrality.
21
+ """
22
+ pass
23
+
15
24
  @abstractmethod
16
25
  def mutate(
17
26
  self,
@@ -11,10 +11,10 @@ from graphdatascience.arrow_client.v2.job_client import JobClient
11
11
  from graphdatascience.graph import Graph
12
12
  from graphdatascience.procedure_surface.api.job_not_finished_error import JobNotFinishedError
13
13
  from graphdatascience.procedure_surface.api.write_job_handle import WriteJobHandle
14
+ from graphdatascience.procedure_surface.api.write_protocol import WriteProtocol
14
15
  from graphdatascience.procedure_surface.arrow.mutation_runner import MutationRunner
15
16
  from graphdatascience.procedure_surface.arrow.stream_result_mapper import apply_stream_mapper
16
17
  from graphdatascience.query_runner.termination_flag import TerminationFlag
17
- from graphdatascience.session.remote_ops.write_protocols import WriteProtocol
18
18
 
19
19
 
20
20
  class JobHandle:
@@ -1,3 +1,15 @@
1
+ from graphdatascience.procedure_surface.api.node_embedding.config import (
2
+ FastRPConfig,
3
+ GBClassifierConfig,
4
+ GraphSAGEConfig,
5
+ IdentityConfig,
6
+ MLPClassifierConfig,
7
+ )
8
+ from graphdatascience.procedure_surface.api.node_embedding.embedding_endpoints import (
9
+ EmbeddingCreateResult,
10
+ EmbeddingEndpoints,
11
+ EmbeddingTrainResult,
12
+ )
1
13
  from graphdatascience.procedure_surface.api.node_embedding.fastpath_endpoints import (
2
14
  FastPathEndpoints,
3
15
  FastPathMutateResult,
@@ -9,16 +21,39 @@ from graphdatascience.procedure_surface.api.node_embedding.fastrp_endpoints impo
9
21
  FastRPStatsResult,
10
22
  FastRPWriteResult,
11
23
  )
12
- from graphdatascience.procedure_surface.api.node_embedding.graphsage_endpoints import GraphSageEndpoints
24
+ from graphdatascience.procedure_surface.api.node_embedding.graphsage_endpoints import (
25
+ GraphSageEndpoints,
26
+ SessionGraphSageEndpoints,
27
+ )
13
28
  from graphdatascience.procedure_surface.api.node_embedding.graphsage_predict_endpoints import (
14
29
  GraphSageMutateResult,
15
30
  GraphSagePredictEndpoints,
16
31
  GraphSageWriteResult,
17
32
  )
33
+ from graphdatascience.procedure_surface.api.node_embedding.graphsage_results import (
34
+ GraphSageSupervisedMutateResult,
35
+ GraphSageSupervisedTrainResult,
36
+ GraphSageSupervisedWriteResult,
37
+ GraphSageUnsupervisedMutateResult,
38
+ GraphSageUnsupervisedTrainResult,
39
+ GraphSageUnsupervisedWriteResult,
40
+ )
41
+ from graphdatascience.procedure_surface.api.node_embedding.graphsage_supervised_endpoints import (
42
+ GraphSageSupervisedEndpoints,
43
+ )
44
+ from graphdatascience.procedure_surface.api.node_embedding.graphsage_supervised_model import (
45
+ GraphSageSupervisedModel,
46
+ )
18
47
  from graphdatascience.procedure_surface.api.node_embedding.graphsage_train_endpoints import (
19
48
  GraphSageTrainEndpoints,
20
49
  GraphSageTrainResult,
21
50
  )
51
+ from graphdatascience.procedure_surface.api.node_embedding.graphsage_unsupervised_endpoints import (
52
+ GraphSageUnsupervisedEndpoints,
53
+ )
54
+ from graphdatascience.procedure_surface.api.node_embedding.graphsage_unsupervised_model import (
55
+ GraphSageUnsupervisedModel,
56
+ )
22
57
  from graphdatascience.procedure_surface.api.node_embedding.hashgnn_endpoints import (
23
58
  HashGNNEndpoints,
24
59
  HashGNNMutateResult,
@@ -31,6 +66,10 @@ from graphdatascience.procedure_surface.api.node_embedding.node2vec_endpoints im
31
66
  )
32
67
 
33
68
  __all__ = [
69
+ "EmbeddingEndpoints",
70
+ "EmbeddingCreateResult",
71
+ "EmbeddingTrainResult",
72
+ "FastRPConfig",
34
73
  "FastRPEndpoints",
35
74
  "FastRPMutateResult",
36
75
  "FastRPStatsResult",
@@ -38,16 +77,31 @@ __all__ = [
38
77
  "FastPathEndpoints",
39
78
  "FastPathMutateResult",
40
79
  "FastPathWriteResult",
80
+ "GBClassifierConfig",
81
+ "GraphSAGEConfig",
41
82
  "GraphSageEndpoints",
42
83
  "GraphSageMutateResult",
43
84
  "GraphSagePredictEndpoints",
85
+ "GraphSageSupervisedEndpoints",
86
+ "GraphSageSupervisedModel",
87
+ "GraphSageSupervisedMutateResult",
88
+ "GraphSageSupervisedTrainResult",
89
+ "GraphSageSupervisedWriteResult",
44
90
  "GraphSageTrainEndpoints",
45
91
  "GraphSageTrainResult",
92
+ "GraphSageUnsupervisedEndpoints",
93
+ "GraphSageUnsupervisedModel",
94
+ "GraphSageUnsupervisedMutateResult",
95
+ "GraphSageUnsupervisedTrainResult",
96
+ "GraphSageUnsupervisedWriteResult",
46
97
  "GraphSageWriteResult",
47
98
  "HashGNNEndpoints",
48
99
  "HashGNNMutateResult",
49
100
  "HashGNNWriteResult",
101
+ "IdentityConfig",
102
+ "MLPClassifierConfig",
50
103
  "Node2VecEndpoints",
51
104
  "Node2VecMutateResult",
52
105
  "Node2VecWriteResult",
106
+ "SessionGraphSageEndpoints",
53
107
  ]
@@ -9,12 +9,20 @@ Dropout = Annotated[float, Field(ge=0.0, lt=1.0)]
9
9
 
10
10
 
11
11
  class GraphSAGEConfig(BaseModel):
12
+ """Configuration for the GraphSAGE graph encoder."""
13
+
12
14
  graph_encoder_type: Literal["graphsage"] = "graphsage"
13
- target_type: NodeType
14
- hidden_dims: Annotated[list[PositiveInt], Len(max_length=3)] | None = None
15
- num_neighbors: Annotated[list[PositiveInt], Len(min_length=1, max_length=4)] | None = None
16
- out_dim: PositiveInt | None = None
17
- dropout: Dropout | None = None
15
+ target_type: NodeType = Field(description="Node type (label) of the nodes the encoder is trained on.")
16
+ hidden_dims: Annotated[list[PositiveInt], Len(max_length=3)] | None = Field(
17
+ default=None,
18
+ description="Sizes of the hidden layers. The depth of the GNN is inferred as `len(hidden_dims) + 1`.",
19
+ )
20
+ num_neighbors: Annotated[list[PositiveInt], Len(min_length=1, max_length=4)] | None = Field(
21
+ default=None,
22
+ description="Number of neighbors sampled per layer. Must align with the depth implied by `hidden_dims`.",
23
+ )
24
+ out_dim: PositiveInt | None = Field(default=None, description="Output dimensionality of the embeddings.")
25
+ dropout: Dropout | None = Field(default=None, description="Dropout probability applied during training.")
18
26
 
19
27
  @model_validator(mode="after")
20
28
  def depth_validator(self) -> "GraphSAGEConfig":
@@ -28,16 +36,26 @@ class GraphSAGEConfig(BaseModel):
28
36
 
29
37
 
30
38
  class FastRPConfig(BaseModel):
39
+ """Configuration for the FastRP graph encoder."""
40
+
31
41
  graph_encoder_type: Literal["fast_rp"] = "fast_rp"
32
- out_dim: PositiveInt | None = None
33
- coefficients: list[float] | None = None
34
- normalization_strength: float | None = None
42
+ out_dim: PositiveInt | None = Field(default=None, description="Output dimensionality of the embeddings.")
43
+ coefficients: list[float] | None = Field(
44
+ default=None,
45
+ description="Weights for each iteration. Controls the influence of each iteration on the final embedding.",
46
+ )
47
+ normalization_strength: float | None = Field(
48
+ default=None,
49
+ description="The normalization strength parameter controls how much the embedding is normalized.",
50
+ )
35
51
 
36
52
 
37
53
  class IdentityConfig(BaseModel):
54
+ """Configuration for the Identity encoder, which passes node properties through unchanged."""
55
+
38
56
  graph_encoder_type: Literal["identity"] = "identity"
39
- target_type: NodeType
40
- out_dim: PositiveInt
57
+ target_type: NodeType = Field(description="Node type (label) of the nodes to encode.")
58
+ out_dim: PositiveInt = Field(description="Output dimensionality of the embeddings.")
41
59
 
42
60
 
43
61
  NoTrainGraphEncoderConfig = FastRPConfig | IdentityConfig # can be run without training
@@ -45,13 +63,19 @@ GraphEncoderConfig = FastRPConfig | GraphSAGEConfig | IdentityConfig
45
63
 
46
64
 
47
65
  class GBClassifierConfig(BaseModel):
66
+ """Configuration for the gradient boosted tree classifier decoder."""
67
+
48
68
  decoder_type: Literal["gb_classifier"] = "gb_classifier"
49
69
 
50
70
 
51
71
  class MLPClassifierConfig(BaseModel):
72
+ """Configuration for the multi-layer perceptron classifier decoder."""
73
+
52
74
  decoder_type: Literal["mlp_classifier"] = "mlp_classifier"
53
- hidden_dims: list[PositiveInt] | None = None
54
- dropout: Dropout | None = None
75
+ hidden_dims: list[PositiveInt] | None = Field(
76
+ default=None, description="Sizes of the hidden layers of the network."
77
+ )
78
+ dropout: Dropout | None = Field(default=None, description="Dropout probability applied during training.")
55
79
 
56
80
 
57
81
  DecoderConfig = GBClassifierConfig | MLPClassifierConfig