kumoai 2.12.1__py3-none-any.whl → 2.14.0.dev202512141732__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.
- kumoai/__init__.py +18 -9
- kumoai/_version.py +1 -1
- kumoai/client/client.py +9 -13
- kumoai/client/pquery.py +6 -2
- kumoai/connector/utils.py +23 -2
- kumoai/experimental/rfm/__init__.py +162 -46
- kumoai/experimental/rfm/backend/__init__.py +0 -0
- kumoai/experimental/rfm/backend/local/__init__.py +42 -0
- kumoai/experimental/rfm/{local_graph_store.py → backend/local/graph_store.py} +37 -90
- kumoai/experimental/rfm/backend/local/sampler.py +313 -0
- kumoai/experimental/rfm/backend/local/table.py +119 -0
- kumoai/experimental/rfm/backend/snow/__init__.py +37 -0
- kumoai/experimental/rfm/backend/snow/sampler.py +119 -0
- kumoai/experimental/rfm/backend/snow/table.py +135 -0
- kumoai/experimental/rfm/backend/sqlite/__init__.py +32 -0
- kumoai/experimental/rfm/backend/sqlite/sampler.py +112 -0
- kumoai/experimental/rfm/backend/sqlite/table.py +115 -0
- kumoai/experimental/rfm/base/__init__.py +23 -0
- kumoai/experimental/rfm/base/column.py +66 -0
- kumoai/experimental/rfm/base/sampler.py +773 -0
- kumoai/experimental/rfm/base/source.py +19 -0
- kumoai/experimental/rfm/{local_table.py → base/table.py} +152 -141
- kumoai/experimental/rfm/{local_graph.py → graph.py} +352 -80
- kumoai/experimental/rfm/infer/__init__.py +6 -0
- kumoai/experimental/rfm/infer/dtype.py +79 -0
- kumoai/experimental/rfm/infer/pkey.py +126 -0
- kumoai/experimental/rfm/infer/time_col.py +62 -0
- kumoai/experimental/rfm/pquery/pandas_executor.py +1 -1
- kumoai/experimental/rfm/rfm.py +233 -174
- kumoai/experimental/rfm/sagemaker.py +138 -0
- kumoai/spcs.py +1 -3
- kumoai/testing/decorators.py +1 -1
- kumoai/testing/snow.py +50 -0
- kumoai/utils/__init__.py +2 -0
- kumoai/utils/sql.py +3 -0
- {kumoai-2.12.1.dist-info → kumoai-2.14.0.dev202512141732.dist-info}/METADATA +12 -2
- {kumoai-2.12.1.dist-info → kumoai-2.14.0.dev202512141732.dist-info}/RECORD +40 -23
- kumoai/experimental/rfm/local_graph_sampler.py +0 -184
- kumoai/experimental/rfm/local_pquery_driver.py +0 -689
- kumoai/experimental/rfm/utils.py +0 -344
- {kumoai-2.12.1.dist-info → kumoai-2.14.0.dev202512141732.dist-info}/WHEEL +0 -0
- {kumoai-2.12.1.dist-info → kumoai-2.14.0.dev202512141732.dist-info}/licenses/LICENSE +0 -0
- {kumoai-2.12.1.dist-info → kumoai-2.14.0.dev202512141732.dist-info}/top_level.txt +0 -0
kumoai/__init__.py
CHANGED
|
@@ -184,15 +184,12 @@ def init(
|
|
|
184
184
|
snowflake_credentials
|
|
185
185
|
) if not api_key and snowflake_credentials else None
|
|
186
186
|
client = KumoClient(url=url, api_key=api_key, spcs_token=spcs_token)
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
else:
|
|
194
|
-
raise ValueError("Client authentication failed. Please check if you "
|
|
195
|
-
"have a valid API key.")
|
|
187
|
+
client.authenticate()
|
|
188
|
+
global_state._url = client._url
|
|
189
|
+
global_state._api_key = client._api_key
|
|
190
|
+
global_state._snowflake_credentials = snowflake_credentials
|
|
191
|
+
global_state._spcs_token = client._spcs_token
|
|
192
|
+
global_state._snowpark_session = snowpark_session
|
|
196
193
|
|
|
197
194
|
if not api_key and snowflake_credentials:
|
|
198
195
|
# Refresh token every 10 minutes (expires in 1 hour):
|
|
@@ -283,7 +280,19 @@ __all__ = [
|
|
|
283
280
|
]
|
|
284
281
|
|
|
285
282
|
|
|
283
|
+
def in_snowflake_notebook() -> bool:
|
|
284
|
+
try:
|
|
285
|
+
from snowflake.snowpark.context import get_active_session
|
|
286
|
+
import streamlit # noqa: F401
|
|
287
|
+
get_active_session()
|
|
288
|
+
return True
|
|
289
|
+
except Exception:
|
|
290
|
+
return False
|
|
291
|
+
|
|
292
|
+
|
|
286
293
|
def in_notebook() -> bool:
|
|
294
|
+
if in_snowflake_notebook():
|
|
295
|
+
return True
|
|
287
296
|
try:
|
|
288
297
|
from IPython import get_ipython
|
|
289
298
|
shell = get_ipython()
|
kumoai/_version.py
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
__version__ = '2.
|
|
1
|
+
__version__ = '2.14.0.dev202512141732'
|
kumoai/client/client.py
CHANGED
|
@@ -20,7 +20,6 @@ if TYPE_CHECKING:
|
|
|
20
20
|
)
|
|
21
21
|
from kumoai.client.online import OnlineServingEndpointAPI
|
|
22
22
|
from kumoai.client.pquery import PQueryAPI
|
|
23
|
-
from kumoai.client.rfm import RFMAPI
|
|
24
23
|
from kumoai.client.source_table import SourceTableAPI
|
|
25
24
|
from kumoai.client.table import TableAPI
|
|
26
25
|
|
|
@@ -73,12 +72,15 @@ class KumoClient:
|
|
|
73
72
|
self._session.headers.update(
|
|
74
73
|
{'Authorization': f'Snowflake Token={self._spcs_token}'})
|
|
75
74
|
|
|
76
|
-
def authenticate(self) ->
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
75
|
+
def authenticate(self) -> None:
|
|
76
|
+
"""Raises an exception if authentication fails."""
|
|
77
|
+
try:
|
|
78
|
+
self._session.get(self._url + '/v1/connectors',
|
|
79
|
+
verify=self._verify_ssl).raise_for_status()
|
|
80
|
+
except Exception:
|
|
81
|
+
raise ValueError(
|
|
82
|
+
"Client authentication failed. Please check if you "
|
|
83
|
+
"have a valid API key/credentials.")
|
|
82
84
|
|
|
83
85
|
def set_spcs_token(self, spcs_token: str) -> None:
|
|
84
86
|
r"""Sets the SPCS token for the client and updates the session
|
|
@@ -163,12 +165,6 @@ class KumoClient:
|
|
|
163
165
|
from kumoai.client.online import OnlineServingEndpointAPI
|
|
164
166
|
return OnlineServingEndpointAPI(self)
|
|
165
167
|
|
|
166
|
-
@property
|
|
167
|
-
def rfm_api(self) -> 'RFMAPI':
|
|
168
|
-
r"""Returns the typed RFM API."""
|
|
169
|
-
from kumoai.client.rfm import RFMAPI
|
|
170
|
-
return RFMAPI(self)
|
|
171
|
-
|
|
172
168
|
def _request(self, endpoint: Endpoint, **kwargs: Any) -> requests.Response:
|
|
173
169
|
r"""Send a HTTP request to the specified endpoint."""
|
|
174
170
|
endpoint_str = endpoint.get_path()
|
kumoai/client/pquery.py
CHANGED
|
@@ -176,8 +176,12 @@ def filter_model_plan(
|
|
|
176
176
|
# Undefined
|
|
177
177
|
pass
|
|
178
178
|
|
|
179
|
-
|
|
180
|
-
|
|
179
|
+
# Forward compatibility - Remove any newly introduced arguments not
|
|
180
|
+
# returned yet by the backend:
|
|
181
|
+
value = getattr(section, field.name)
|
|
182
|
+
if value != MissingType.VALUE:
|
|
183
|
+
new_opt_fields.append((field.name, _type, default))
|
|
184
|
+
new_opts.append(value)
|
|
181
185
|
|
|
182
186
|
Section = dataclass(
|
|
183
187
|
config=dict(validate_assignment=True),
|
kumoai/connector/utils.py
CHANGED
|
@@ -381,8 +381,29 @@ def _handle_duplicate_names(names: List[str]) -> List[str]:
|
|
|
381
381
|
|
|
382
382
|
|
|
383
383
|
def _sanitize_columns(names: List[str]) -> Tuple[List[str], bool]:
|
|
384
|
-
|
|
384
|
+
"""Normalize column names in a CSV or Parquet file.
|
|
385
|
+
|
|
386
|
+
Rules:
|
|
387
|
+
- Replace any non-alphanumeric character with "_"
|
|
388
|
+
- Strip leading/trailing underscores
|
|
389
|
+
- Ensure uniqueness by appending suffixes: _1, _2, ...
|
|
390
|
+
- Auto-name empty columns as auto_named_<n>
|
|
391
|
+
|
|
392
|
+
Returns:
|
|
393
|
+
(new_column_names, changed)
|
|
394
|
+
"""
|
|
395
|
+
_SAN_RE = re.compile(r"[^0-9A-Za-z,\t]")
|
|
396
|
+
# 1) Replace non-alphanumeric sequences with underscore
|
|
385
397
|
new = [_SAN_RE.sub("_", n).strip("_") for n in names]
|
|
398
|
+
|
|
399
|
+
# 2) Auto-name any empty column names to match UI behavior
|
|
400
|
+
unnamed_counter = 0
|
|
401
|
+
for i, n in enumerate(new):
|
|
402
|
+
if not n:
|
|
403
|
+
new[i] = f"auto_named_{unnamed_counter}"
|
|
404
|
+
unnamed_counter += 1
|
|
405
|
+
|
|
406
|
+
# 3) Ensure uniqueness (append suffixes where needed)
|
|
386
407
|
new = _handle_duplicate_names(new)
|
|
387
408
|
return new, new != names
|
|
388
409
|
|
|
@@ -1168,7 +1189,7 @@ def _detect_and_validate_csv(head_bytes: bytes) -> str:
|
|
|
1168
1189
|
- Re-serializes those rows and validates with pandas (small nrows) to catch
|
|
1169
1190
|
malformed inputs.
|
|
1170
1191
|
- Raises ValueError on empty input or if parsing fails with the chosen
|
|
1171
|
-
|
|
1192
|
+
delimiter.
|
|
1172
1193
|
"""
|
|
1173
1194
|
if not head_bytes:
|
|
1174
1195
|
raise ValueError("Could not auto-detect a delimiter: file is empty.")
|
|
@@ -1,43 +1,123 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
except Exception as e:
|
|
4
|
-
import platform
|
|
5
|
-
|
|
6
|
-
_msg = f"""RFM is not supported in your environment.
|
|
7
|
-
|
|
8
|
-
💻 Your Environment:
|
|
9
|
-
Python version: {platform.python_version()}
|
|
10
|
-
Operating system: {platform.system()}
|
|
11
|
-
CPU architecture: {platform.machine()}
|
|
12
|
-
glibc version: {platform.libc_ver()[1]}
|
|
13
|
-
|
|
14
|
-
✅ Supported Environments:
|
|
15
|
-
* Python versions: 3.10, 3.11, 3.12, 3.13
|
|
16
|
-
* Operating systems and CPU architectures:
|
|
17
|
-
* Linux (x86_64)
|
|
18
|
-
* macOS (arm64)
|
|
19
|
-
* Windows (x86_64)
|
|
20
|
-
* glibc versions: >=2.28
|
|
21
|
-
|
|
22
|
-
❌ Unsupported Environments:
|
|
23
|
-
* Python versions: 3.8, 3.9, 3.14
|
|
24
|
-
* Operating systems and CPU architectures:
|
|
25
|
-
* Linux (arm64)
|
|
26
|
-
* macOS (x86_64)
|
|
27
|
-
* Windows (arm64)
|
|
28
|
-
* glibc versions: <2.28
|
|
29
|
-
|
|
30
|
-
Please create a feature request at 'https://github.com/kumo-ai/kumo-rfm'."""
|
|
31
|
-
|
|
32
|
-
raise RuntimeError(_msg) from e
|
|
33
|
-
|
|
34
|
-
from typing import Optional, Dict
|
|
1
|
+
import ipaddress
|
|
2
|
+
import logging
|
|
35
3
|
import os
|
|
4
|
+
import re
|
|
5
|
+
import socket
|
|
6
|
+
import threading
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from enum import Enum
|
|
9
|
+
from typing import Dict, Optional, Tuple
|
|
10
|
+
from urllib.parse import urlparse
|
|
11
|
+
|
|
36
12
|
import kumoai
|
|
37
|
-
from .
|
|
38
|
-
|
|
39
|
-
from .rfm import ExplainConfig, Explanation, KumoRFM
|
|
13
|
+
from kumoai.client.client import KumoClient
|
|
14
|
+
|
|
40
15
|
from .authenticate import authenticate
|
|
16
|
+
from .sagemaker import (
|
|
17
|
+
KumoClient_SageMakerAdapter,
|
|
18
|
+
KumoClient_SageMakerProxy_Local,
|
|
19
|
+
)
|
|
20
|
+
from .base import Table
|
|
21
|
+
from .backend.local import LocalTable
|
|
22
|
+
from .graph import Graph
|
|
23
|
+
from .rfm import ExplainConfig, Explanation, KumoRFM
|
|
24
|
+
|
|
25
|
+
logger = logging.getLogger('kumoai_rfm')
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _is_local_address(host: str | None) -> bool:
|
|
29
|
+
"""Return True if the hostname/IP refers to the local machine."""
|
|
30
|
+
if not host:
|
|
31
|
+
return False
|
|
32
|
+
try:
|
|
33
|
+
infos = socket.getaddrinfo(host, None)
|
|
34
|
+
for _, _, _, _, sockaddr in infos:
|
|
35
|
+
ip = sockaddr[0]
|
|
36
|
+
ip_obj = ipaddress.ip_address(ip)
|
|
37
|
+
if ip_obj.is_loopback or ip_obj.is_unspecified:
|
|
38
|
+
return True
|
|
39
|
+
return False
|
|
40
|
+
except Exception:
|
|
41
|
+
return False
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class InferenceBackend(str, Enum):
|
|
45
|
+
REST = "REST"
|
|
46
|
+
LOCAL_SAGEMAKER = "LOCAL_SAGEMAKER"
|
|
47
|
+
AWS_SAGEMAKER = "AWS_SAGEMAKER"
|
|
48
|
+
UNKNOWN = "UNKNOWN"
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _detect_backend(
|
|
52
|
+
url: str) -> Tuple[InferenceBackend, Optional[str], Optional[str]]:
|
|
53
|
+
parsed = urlparse(url)
|
|
54
|
+
|
|
55
|
+
# Remote SageMaker
|
|
56
|
+
if ("runtime.sagemaker" in parsed.netloc
|
|
57
|
+
and parsed.path.endswith("/invocations")):
|
|
58
|
+
# Example: https://runtime.sagemaker.us-west-2.amazonaws.com/
|
|
59
|
+
# endpoints/Name/invocations
|
|
60
|
+
match = re.search(r"runtime\.sagemaker\.([a-z0-9-]+)\.amazonaws\.com",
|
|
61
|
+
parsed.netloc)
|
|
62
|
+
region = match.group(1) if match else None
|
|
63
|
+
m = re.search(r"/endpoints/([^/]+)/invocations", parsed.path)
|
|
64
|
+
endpoint_name = m.group(1) if m else None
|
|
65
|
+
return InferenceBackend.AWS_SAGEMAKER, region, endpoint_name
|
|
66
|
+
|
|
67
|
+
# Local SageMaker
|
|
68
|
+
if parsed.port == 8080 and parsed.path.endswith(
|
|
69
|
+
"/invocations") and _is_local_address(parsed.hostname):
|
|
70
|
+
return InferenceBackend.LOCAL_SAGEMAKER, None, None
|
|
71
|
+
|
|
72
|
+
# Default: regular REST
|
|
73
|
+
return InferenceBackend.REST, None, None
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@dataclass
|
|
77
|
+
class RfmGlobalState:
|
|
78
|
+
_url: str = '__url_not_provided__'
|
|
79
|
+
_backend: InferenceBackend = InferenceBackend.UNKNOWN
|
|
80
|
+
_region: Optional[str] = None
|
|
81
|
+
_endpoint_name: Optional[str] = None
|
|
82
|
+
_thread_local = threading.local()
|
|
83
|
+
|
|
84
|
+
# Thread-safe init-once.
|
|
85
|
+
_initialized: bool = False
|
|
86
|
+
_lock: threading.Lock = threading.Lock()
|
|
87
|
+
|
|
88
|
+
@property
|
|
89
|
+
def client(self) -> KumoClient:
|
|
90
|
+
if self._backend == InferenceBackend.REST:
|
|
91
|
+
return kumoai.global_state.client
|
|
92
|
+
|
|
93
|
+
if hasattr(self._thread_local, '_sagemaker'):
|
|
94
|
+
# Set the spcs token in the client to ensure it has the latest.
|
|
95
|
+
return self._thread_local._sagemaker
|
|
96
|
+
|
|
97
|
+
sagemaker_client: KumoClient
|
|
98
|
+
if self._backend == InferenceBackend.LOCAL_SAGEMAKER:
|
|
99
|
+
sagemaker_client = KumoClient_SageMakerProxy_Local(self._url)
|
|
100
|
+
else:
|
|
101
|
+
assert self._backend == InferenceBackend.AWS_SAGEMAKER
|
|
102
|
+
assert self._region
|
|
103
|
+
assert self._endpoint_name
|
|
104
|
+
sagemaker_client = KumoClient_SageMakerAdapter(
|
|
105
|
+
self._region, self._endpoint_name)
|
|
106
|
+
|
|
107
|
+
self._thread_local._sagemaker = sagemaker_client
|
|
108
|
+
return sagemaker_client
|
|
109
|
+
|
|
110
|
+
def reset(self) -> None: # For testing only.
|
|
111
|
+
with self._lock:
|
|
112
|
+
self._initialized = False
|
|
113
|
+
self._url = '__url_not_provided__'
|
|
114
|
+
self._backend = InferenceBackend.UNKNOWN
|
|
115
|
+
self._region = None
|
|
116
|
+
self._endpoint_name = None
|
|
117
|
+
self._thread_local = threading.local()
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
global_state = RfmGlobalState()
|
|
41
121
|
|
|
42
122
|
|
|
43
123
|
def init(
|
|
@@ -47,21 +127,57 @@ def init(
|
|
|
47
127
|
snowflake_application: Optional[str] = None,
|
|
48
128
|
log_level: str = "INFO",
|
|
49
129
|
) -> None:
|
|
50
|
-
|
|
51
|
-
|
|
130
|
+
with global_state._lock:
|
|
131
|
+
if global_state._initialized:
|
|
132
|
+
if url != global_state._url:
|
|
133
|
+
raise ValueError(
|
|
134
|
+
"Kumo RFM has already been initialized with a different "
|
|
135
|
+
"URL. Re-initialization with a different URL is not "
|
|
136
|
+
"supported.")
|
|
137
|
+
return
|
|
52
138
|
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
snowflake_application=snowflake_application,
|
|
56
|
-
log_level=log_level)
|
|
139
|
+
if url is None:
|
|
140
|
+
url = os.getenv("RFM_API_URL", "https://kumorfm.ai/api")
|
|
57
141
|
|
|
142
|
+
backend, region, endpoint_name = _detect_backend(url)
|
|
143
|
+
if backend == InferenceBackend.REST:
|
|
144
|
+
# Initialize kumoai.global_state
|
|
145
|
+
if (kumoai.global_state.initialized
|
|
146
|
+
and kumoai.global_state._url != url):
|
|
147
|
+
raise ValueError(
|
|
148
|
+
"Kumo AI SDK has already been initialized with different "
|
|
149
|
+
"API URL. Please restart Python interpreter and "
|
|
150
|
+
"initialize via kumoai.rfm.init()")
|
|
151
|
+
kumoai.init(url=url, api_key=api_key,
|
|
152
|
+
snowflake_credentials=snowflake_credentials,
|
|
153
|
+
snowflake_application=snowflake_application,
|
|
154
|
+
log_level=log_level)
|
|
155
|
+
elif backend == InferenceBackend.AWS_SAGEMAKER:
|
|
156
|
+
assert region
|
|
157
|
+
assert endpoint_name
|
|
158
|
+
KumoClient_SageMakerAdapter(region, endpoint_name).authenticate()
|
|
159
|
+
else:
|
|
160
|
+
assert backend == InferenceBackend.LOCAL_SAGEMAKER
|
|
161
|
+
KumoClient_SageMakerProxy_Local(url).authenticate()
|
|
162
|
+
|
|
163
|
+
global_state._url = url
|
|
164
|
+
global_state._backend = backend
|
|
165
|
+
global_state._region = region
|
|
166
|
+
global_state._endpoint_name = endpoint_name
|
|
167
|
+
global_state._initialized = True
|
|
168
|
+
logger.info("Kumo RFM initialized with backend: %s, url: %s", backend,
|
|
169
|
+
url)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
LocalGraph = Graph # NOTE Backward compatibility - do not use anymore.
|
|
58
173
|
|
|
59
174
|
__all__ = [
|
|
175
|
+
'authenticate',
|
|
176
|
+
'init',
|
|
177
|
+
'Table',
|
|
60
178
|
'LocalTable',
|
|
61
|
-
'
|
|
179
|
+
'Graph',
|
|
62
180
|
'KumoRFM',
|
|
63
181
|
'ExplainConfig',
|
|
64
182
|
'Explanation',
|
|
65
|
-
'authenticate',
|
|
66
|
-
'init',
|
|
67
183
|
]
|
|
File without changes
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
try:
|
|
2
|
+
import kumoai.kumolib # noqa: F401
|
|
3
|
+
except Exception as e:
|
|
4
|
+
import platform
|
|
5
|
+
|
|
6
|
+
_msg = f"""RFM is not supported in your environment.
|
|
7
|
+
|
|
8
|
+
💻 Your Environment:
|
|
9
|
+
Python version: {platform.python_version()}
|
|
10
|
+
Operating system: {platform.system()}
|
|
11
|
+
CPU architecture: {platform.machine()}
|
|
12
|
+
glibc version: {platform.libc_ver()[1]}
|
|
13
|
+
|
|
14
|
+
✅ Supported Environments:
|
|
15
|
+
* Python versions: 3.10, 3.11, 3.12, 3.13
|
|
16
|
+
* Operating systems and CPU architectures:
|
|
17
|
+
* Linux (x86_64)
|
|
18
|
+
* macOS (arm64)
|
|
19
|
+
* Windows (x86_64)
|
|
20
|
+
* glibc versions: >=2.28
|
|
21
|
+
|
|
22
|
+
❌ Unsupported Environments:
|
|
23
|
+
* Python versions: 3.8, 3.9, 3.14
|
|
24
|
+
* Operating systems and CPU architectures:
|
|
25
|
+
* Linux (arm64)
|
|
26
|
+
* macOS (x86_64)
|
|
27
|
+
* Windows (arm64)
|
|
28
|
+
* glibc versions: <2.28
|
|
29
|
+
|
|
30
|
+
Please create a feature request at 'https://github.com/kumo-ai/kumo-rfm'."""
|
|
31
|
+
|
|
32
|
+
raise RuntimeError(_msg) from e
|
|
33
|
+
|
|
34
|
+
from .table import LocalTable
|
|
35
|
+
from .graph_store import LocalGraphStore
|
|
36
|
+
from .sampler import LocalSampler
|
|
37
|
+
|
|
38
|
+
__all__ = [
|
|
39
|
+
'LocalTable',
|
|
40
|
+
'LocalGraphStore',
|
|
41
|
+
'LocalSampler',
|
|
42
|
+
]
|
|
@@ -1,13 +1,12 @@
|
|
|
1
1
|
import warnings
|
|
2
|
-
from typing import Dict, List, Optional, Tuple, Union
|
|
2
|
+
from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union
|
|
3
3
|
|
|
4
4
|
import numpy as np
|
|
5
5
|
import pandas as pd
|
|
6
6
|
from kumoapi.rfm.context import Subgraph
|
|
7
7
|
from kumoapi.typing import Stype
|
|
8
8
|
|
|
9
|
-
from kumoai.experimental.rfm import
|
|
10
|
-
from kumoai.experimental.rfm.utils import normalize_text
|
|
9
|
+
from kumoai.experimental.rfm.backend.local import LocalTable
|
|
11
10
|
from kumoai.utils import InteractiveProgressLogger, ProgressLogger
|
|
12
11
|
|
|
13
12
|
try:
|
|
@@ -16,12 +15,14 @@ try:
|
|
|
16
15
|
except ImportError:
|
|
17
16
|
WITH_TORCH = False
|
|
18
17
|
|
|
18
|
+
if TYPE_CHECKING:
|
|
19
|
+
from kumoai.experimental.rfm import Graph
|
|
20
|
+
|
|
19
21
|
|
|
20
22
|
class LocalGraphStore:
|
|
21
23
|
def __init__(
|
|
22
24
|
self,
|
|
23
|
-
graph:
|
|
24
|
-
preprocess: bool = False,
|
|
25
|
+
graph: 'Graph',
|
|
25
26
|
verbose: Union[bool, ProgressLogger] = True,
|
|
26
27
|
) -> None:
|
|
27
28
|
|
|
@@ -32,27 +33,22 @@ class LocalGraphStore:
|
|
|
32
33
|
)
|
|
33
34
|
|
|
34
35
|
with verbose as logger:
|
|
35
|
-
self.df_dict, self.mask_dict = self.sanitize(graph
|
|
36
|
-
self.stype_dict = self.get_stype_dict(graph)
|
|
36
|
+
self.df_dict, self.mask_dict = self.sanitize(graph)
|
|
37
37
|
logger.log("Sanitized input data")
|
|
38
38
|
|
|
39
|
-
self.
|
|
39
|
+
self.pkey_map_dict = self.get_pkey_map_dict(graph)
|
|
40
40
|
num_pkeys = sum(t.has_primary_key() for t in graph.tables.values())
|
|
41
41
|
if num_pkeys > 1:
|
|
42
42
|
logger.log(f"Collected primary keys from {num_pkeys} tables")
|
|
43
43
|
else:
|
|
44
44
|
logger.log(f"Collected primary key from {num_pkeys} table")
|
|
45
45
|
|
|
46
|
-
(
|
|
47
|
-
|
|
48
|
-
self.
|
|
49
|
-
self.
|
|
50
|
-
self.min_time,
|
|
51
|
-
self.max_time,
|
|
52
|
-
) = self.get_time_data(graph)
|
|
53
|
-
if self.max_time != pd.Timestamp.min:
|
|
46
|
+
self.time_dict, self.min_max_time_dict = self.get_time_data(graph)
|
|
47
|
+
if len(self.min_max_time_dict) > 0:
|
|
48
|
+
min_time = min(t for t, _ in self.min_max_time_dict.values())
|
|
49
|
+
max_time = max(t for _, t in self.min_max_time_dict.values())
|
|
54
50
|
logger.log(f"Identified temporal graph from "
|
|
55
|
-
f"{
|
|
51
|
+
f"{min_time.date()} to {max_time.date()}")
|
|
56
52
|
else:
|
|
57
53
|
logger.log("Identified static graph without timestamps")
|
|
58
54
|
|
|
@@ -62,14 +58,6 @@ class LocalGraphStore:
|
|
|
62
58
|
logger.log(f"Created graph with {num_nodes:,} nodes and "
|
|
63
59
|
f"{num_edges:,} edges")
|
|
64
60
|
|
|
65
|
-
@property
|
|
66
|
-
def node_types(self) -> List[str]:
|
|
67
|
-
return list(self.df_dict.keys())
|
|
68
|
-
|
|
69
|
-
@property
|
|
70
|
-
def edge_types(self) -> List[Tuple[str, str, str]]:
|
|
71
|
-
return list(self.row_dict.keys())
|
|
72
|
-
|
|
73
61
|
def get_node_id(self, table_name: str, pkey: pd.Series) -> np.ndarray:
|
|
74
62
|
r"""Returns the node ID given primary keys.
|
|
75
63
|
|
|
@@ -105,8 +93,7 @@ class LocalGraphStore:
|
|
|
105
93
|
|
|
106
94
|
def sanitize(
|
|
107
95
|
self,
|
|
108
|
-
graph:
|
|
109
|
-
preprocess: bool = False,
|
|
96
|
+
graph: 'Graph',
|
|
110
97
|
) -> Tuple[Dict[str, pd.DataFrame], Dict[str, np.ndarray]]:
|
|
111
98
|
r"""Sanitizes raw data according to table schema definition:
|
|
112
99
|
|
|
@@ -115,17 +102,12 @@ class LocalGraphStore:
|
|
|
115
102
|
* drops timezone information from timestamps
|
|
116
103
|
* drops duplicate primary keys
|
|
117
104
|
* removes rows with missing primary keys or time values
|
|
118
|
-
|
|
119
|
-
If ``preprocess`` is set to ``True``, it will additionally pre-process
|
|
120
|
-
data for faster model processing. In particular, it:
|
|
121
|
-
* tokenizes any text column that is not a foreign key
|
|
122
105
|
"""
|
|
123
|
-
df_dict: Dict[str, pd.DataFrame] = {
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
foreign_keys = {(edge.src_table, edge.fkey) for edge in graph.edges}
|
|
106
|
+
df_dict: Dict[str, pd.DataFrame] = {}
|
|
107
|
+
for table_name, table in graph.tables.items():
|
|
108
|
+
assert isinstance(table, LocalTable)
|
|
109
|
+
df = table._data
|
|
110
|
+
df_dict[table_name] = df.copy(deep=False).reset_index(drop=True)
|
|
129
111
|
|
|
130
112
|
mask_dict: Dict[str, np.ndarray] = {}
|
|
131
113
|
for table in graph.tables.values():
|
|
@@ -144,12 +126,6 @@ class LocalGraphStore:
|
|
|
144
126
|
ser = ser.dt.tz_localize(None)
|
|
145
127
|
df_dict[table.name][col.name] = ser
|
|
146
128
|
|
|
147
|
-
# Normalize text in advance (but exclude foreign keys):
|
|
148
|
-
if (preprocess and col.stype == Stype.text
|
|
149
|
-
and (table.name, col.name) not in foreign_keys):
|
|
150
|
-
ser = df_dict[table.name][col.name]
|
|
151
|
-
df_dict[table.name][col.name] = normalize_text(ser)
|
|
152
|
-
|
|
153
129
|
mask: Optional[np.ndarray] = None
|
|
154
130
|
if table._time_column is not None:
|
|
155
131
|
ser = df_dict[table.name][table._time_column]
|
|
@@ -165,34 +141,16 @@ class LocalGraphStore:
|
|
|
165
141
|
|
|
166
142
|
return df_dict, mask_dict
|
|
167
143
|
|
|
168
|
-
def
|
|
169
|
-
stype_dict: Dict[str, Dict[str, Stype]] = {}
|
|
170
|
-
foreign_keys = {(edge.src_table, edge.fkey) for edge in graph.edges}
|
|
171
|
-
for table in graph.tables.values():
|
|
172
|
-
stype_dict[table.name] = {}
|
|
173
|
-
for column in table.columns:
|
|
174
|
-
if column == table.primary_key:
|
|
175
|
-
continue
|
|
176
|
-
if (table.name, column.name) in foreign_keys:
|
|
177
|
-
continue
|
|
178
|
-
stype_dict[table.name][column.name] = column.stype
|
|
179
|
-
return stype_dict
|
|
180
|
-
|
|
181
|
-
def get_pkey_data(
|
|
144
|
+
def get_pkey_map_dict(
|
|
182
145
|
self,
|
|
183
|
-
graph:
|
|
184
|
-
) ->
|
|
185
|
-
Dict[str, str],
|
|
186
|
-
Dict[str, pd.DataFrame],
|
|
187
|
-
]:
|
|
188
|
-
pkey_name_dict: Dict[str, str] = {}
|
|
146
|
+
graph: 'Graph',
|
|
147
|
+
) -> Dict[str, pd.DataFrame]:
|
|
189
148
|
pkey_map_dict: Dict[str, pd.DataFrame] = {}
|
|
190
149
|
|
|
191
150
|
for table in graph.tables.values():
|
|
192
151
|
if table._primary_key is None:
|
|
193
152
|
continue
|
|
194
153
|
|
|
195
|
-
pkey_name_dict[table.name] = table._primary_key
|
|
196
154
|
pkey = self.df_dict[table.name][table._primary_key]
|
|
197
155
|
pkey_map = pd.DataFrame(
|
|
198
156
|
dict(arange=range(len(pkey))),
|
|
@@ -214,52 +172,41 @@ class LocalGraphStore:
|
|
|
214
172
|
|
|
215
173
|
pkey_map_dict[table.name] = pkey_map
|
|
216
174
|
|
|
217
|
-
return
|
|
175
|
+
return pkey_map_dict
|
|
218
176
|
|
|
219
177
|
def get_time_data(
|
|
220
178
|
self,
|
|
221
|
-
graph:
|
|
179
|
+
graph: 'Graph',
|
|
222
180
|
) -> Tuple[
|
|
223
|
-
Dict[str, str],
|
|
224
|
-
Dict[str, str],
|
|
225
181
|
Dict[str, np.ndarray],
|
|
226
|
-
pd.Timestamp,
|
|
227
|
-
pd.Timestamp,
|
|
182
|
+
Dict[str, Tuple[pd.Timestamp, pd.Timestamp]],
|
|
228
183
|
]:
|
|
229
|
-
time_column_dict: Dict[str, str] = {}
|
|
230
|
-
end_time_column_dict: Dict[str, str] = {}
|
|
231
184
|
time_dict: Dict[str, np.ndarray] = {}
|
|
232
|
-
|
|
233
|
-
max_time = pd.Timestamp.min
|
|
185
|
+
min_max_time_dict: Dict[str, tuple[pd.Timestamp, pd.Timestamp]] = {}
|
|
234
186
|
for table in graph.tables.values():
|
|
235
|
-
if table._end_time_column is not None:
|
|
236
|
-
end_time_column_dict[table.name] = table._end_time_column
|
|
237
|
-
|
|
238
187
|
if table._time_column is None:
|
|
239
188
|
continue
|
|
240
189
|
|
|
241
190
|
time = self.df_dict[table.name][table._time_column]
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
191
|
+
if time.dtype != 'datetime64[ns]':
|
|
192
|
+
time = time.astype('datetime64[ns]')
|
|
193
|
+
time_dict[table.name] = time.astype(int).to_numpy() // 1000**3
|
|
245
194
|
|
|
246
195
|
if table.name in self.mask_dict.keys():
|
|
247
196
|
time = time[self.mask_dict[table.name]]
|
|
248
197
|
if len(time) > 0:
|
|
249
|
-
|
|
250
|
-
|
|
198
|
+
min_max_time_dict[table.name] = (time.min(), time.max())
|
|
199
|
+
else:
|
|
200
|
+
min_max_time_dict[table.name] = (
|
|
201
|
+
pd.Timestamp.max,
|
|
202
|
+
pd.Timestamp.min,
|
|
203
|
+
)
|
|
251
204
|
|
|
252
|
-
return
|
|
253
|
-
time_column_dict,
|
|
254
|
-
end_time_column_dict,
|
|
255
|
-
time_dict,
|
|
256
|
-
min_time,
|
|
257
|
-
max_time,
|
|
258
|
-
)
|
|
205
|
+
return time_dict, min_max_time_dict
|
|
259
206
|
|
|
260
207
|
def get_csc(
|
|
261
208
|
self,
|
|
262
|
-
graph:
|
|
209
|
+
graph: 'Graph',
|
|
263
210
|
) -> Tuple[
|
|
264
211
|
Dict[Tuple[str, str, str], np.ndarray],
|
|
265
212
|
Dict[Tuple[str, str, str], np.ndarray],
|