kumoai 2.13.0.dev202511261731__cp313-cp313-macosx_11_0_arm64.whl → 2.13.0.dev202512061731__cp313-cp313-macosx_11_0_arm64.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 +12 -0
- kumoai/_version.py +1 -1
- kumoai/connector/utils.py +23 -2
- kumoai/experimental/rfm/__init__.py +20 -45
- 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} +20 -30
- kumoai/experimental/rfm/backend/local/sampler.py +131 -0
- kumoai/experimental/rfm/backend/local/table.py +109 -0
- kumoai/experimental/rfm/backend/snow/__init__.py +35 -0
- kumoai/experimental/rfm/backend/snow/table.py +117 -0
- kumoai/experimental/rfm/backend/sqlite/__init__.py +30 -0
- kumoai/experimental/rfm/backend/sqlite/table.py +101 -0
- kumoai/experimental/rfm/base/__init__.py +14 -0
- kumoai/experimental/rfm/base/column.py +66 -0
- kumoai/experimental/rfm/base/sampler.py +287 -0
- kumoai/experimental/rfm/base/source.py +18 -0
- kumoai/experimental/rfm/{local_table.py → base/table.py} +139 -139
- kumoai/experimental/rfm/{local_graph.py → graph.py} +334 -79
- 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/local_graph_sampler.py +43 -2
- kumoai/experimental/rfm/local_pquery_driver.py +1 -1
- kumoai/experimental/rfm/rfm.py +7 -17
- kumoai/experimental/rfm/sagemaker.py +11 -3
- kumoai/testing/decorators.py +1 -1
- {kumoai-2.13.0.dev202511261731.dist-info → kumoai-2.13.0.dev202512061731.dist-info}/METADATA +9 -8
- {kumoai-2.13.0.dev202511261731.dist-info → kumoai-2.13.0.dev202512061731.dist-info}/RECORD +33 -19
- kumoai/experimental/rfm/utils.py +0 -344
- {kumoai-2.13.0.dev202511261731.dist-info → kumoai-2.13.0.dev202512061731.dist-info}/WHEEL +0 -0
- {kumoai-2.13.0.dev202511261731.dist-info → kumoai-2.13.0.dev202512061731.dist-info}/licenses/LICENSE +0 -0
- {kumoai-2.13.0.dev202511261731.dist-info → kumoai-2.13.0.dev202512061731.dist-info}/top_level.txt +0 -0
kumoai/__init__.py
CHANGED
|
@@ -280,7 +280,19 @@ __all__ = [
|
|
|
280
280
|
]
|
|
281
281
|
|
|
282
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
|
+
|
|
283
293
|
def in_notebook() -> bool:
|
|
294
|
+
if in_snowflake_notebook():
|
|
295
|
+
return True
|
|
284
296
|
try:
|
|
285
297
|
from IPython import get_ipython
|
|
286
298
|
shell = get_ipython()
|
kumoai/_version.py
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
__version__ = '2.13.0.
|
|
1
|
+
__version__ = '2.13.0.dev202512061731'
|
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,54 +1,26 @@
|
|
|
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 dataclasses import dataclass
|
|
35
|
-
from enum import Enum
|
|
36
1
|
import ipaddress
|
|
37
2
|
import logging
|
|
3
|
+
import os
|
|
38
4
|
import re
|
|
39
5
|
import socket
|
|
40
6
|
import threading
|
|
41
|
-
from
|
|
42
|
-
import
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from enum import Enum
|
|
9
|
+
from typing import Dict, Optional, Tuple
|
|
43
10
|
from urllib.parse import urlparse
|
|
11
|
+
|
|
44
12
|
import kumoai
|
|
45
13
|
from kumoai.client.client import KumoClient
|
|
46
|
-
|
|
47
|
-
KumoClient_SageMakerProxy_Local)
|
|
48
|
-
from .local_table import LocalTable
|
|
49
|
-
from .local_graph import LocalGraph
|
|
50
|
-
from .rfm import ExplainConfig, Explanation, KumoRFM
|
|
14
|
+
|
|
51
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
|
|
52
24
|
|
|
53
25
|
logger = logging.getLogger('kumoai_rfm')
|
|
54
26
|
|
|
@@ -197,12 +169,15 @@ def init(
|
|
|
197
169
|
url)
|
|
198
170
|
|
|
199
171
|
|
|
172
|
+
LocalGraph = Graph # NOTE Backward compatibility - do not use anymore.
|
|
173
|
+
|
|
200
174
|
__all__ = [
|
|
175
|
+
'authenticate',
|
|
176
|
+
'init',
|
|
177
|
+
'Table',
|
|
201
178
|
'LocalTable',
|
|
202
|
-
'
|
|
179
|
+
'Graph',
|
|
203
180
|
'KumoRFM',
|
|
204
181
|
'ExplainConfig',
|
|
205
182
|
'Explanation',
|
|
206
|
-
'authenticate',
|
|
207
|
-
'init',
|
|
208
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,7 +33,7 @@ class LocalGraphStore:
|
|
|
32
33
|
)
|
|
33
34
|
|
|
34
35
|
with verbose as logger:
|
|
35
|
-
self.df_dict, self.mask_dict = self.sanitize(graph
|
|
36
|
+
self.df_dict, self.mask_dict = self.sanitize(graph)
|
|
36
37
|
self.stype_dict = self.get_stype_dict(graph)
|
|
37
38
|
logger.log("Sanitized input data")
|
|
38
39
|
|
|
@@ -105,8 +106,7 @@ class LocalGraphStore:
|
|
|
105
106
|
|
|
106
107
|
def sanitize(
|
|
107
108
|
self,
|
|
108
|
-
graph:
|
|
109
|
-
preprocess: bool = False,
|
|
109
|
+
graph: 'Graph',
|
|
110
110
|
) -> Tuple[Dict[str, pd.DataFrame], Dict[str, np.ndarray]]:
|
|
111
111
|
r"""Sanitizes raw data according to table schema definition:
|
|
112
112
|
|
|
@@ -115,17 +115,12 @@ class LocalGraphStore:
|
|
|
115
115
|
* drops timezone information from timestamps
|
|
116
116
|
* drops duplicate primary keys
|
|
117
117
|
* 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
118
|
"""
|
|
123
|
-
df_dict: Dict[str, pd.DataFrame] = {
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
foreign_keys = {(edge.src_table, edge.fkey) for edge in graph.edges}
|
|
119
|
+
df_dict: Dict[str, pd.DataFrame] = {}
|
|
120
|
+
for table_name, table in graph.tables.items():
|
|
121
|
+
assert isinstance(table, LocalTable)
|
|
122
|
+
df = table._data
|
|
123
|
+
df_dict[table_name] = df.copy(deep=False).reset_index(drop=True)
|
|
129
124
|
|
|
130
125
|
mask_dict: Dict[str, np.ndarray] = {}
|
|
131
126
|
for table in graph.tables.values():
|
|
@@ -144,12 +139,6 @@ class LocalGraphStore:
|
|
|
144
139
|
ser = ser.dt.tz_localize(None)
|
|
145
140
|
df_dict[table.name][col.name] = ser
|
|
146
141
|
|
|
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
142
|
mask: Optional[np.ndarray] = None
|
|
154
143
|
if table._time_column is not None:
|
|
155
144
|
ser = df_dict[table.name][table._time_column]
|
|
@@ -165,7 +154,7 @@ class LocalGraphStore:
|
|
|
165
154
|
|
|
166
155
|
return df_dict, mask_dict
|
|
167
156
|
|
|
168
|
-
def get_stype_dict(self, graph:
|
|
157
|
+
def get_stype_dict(self, graph: 'Graph') -> Dict[str, Dict[str, Stype]]:
|
|
169
158
|
stype_dict: Dict[str, Dict[str, Stype]] = {}
|
|
170
159
|
foreign_keys = {(edge.src_table, edge.fkey) for edge in graph.edges}
|
|
171
160
|
for table in graph.tables.values():
|
|
@@ -180,7 +169,7 @@ class LocalGraphStore:
|
|
|
180
169
|
|
|
181
170
|
def get_pkey_data(
|
|
182
171
|
self,
|
|
183
|
-
graph:
|
|
172
|
+
graph: 'Graph',
|
|
184
173
|
) -> Tuple[
|
|
185
174
|
Dict[str, str],
|
|
186
175
|
Dict[str, pd.DataFrame],
|
|
@@ -218,7 +207,7 @@ class LocalGraphStore:
|
|
|
218
207
|
|
|
219
208
|
def get_time_data(
|
|
220
209
|
self,
|
|
221
|
-
graph:
|
|
210
|
+
graph: 'Graph',
|
|
222
211
|
) -> Tuple[
|
|
223
212
|
Dict[str, str],
|
|
224
213
|
Dict[str, str],
|
|
@@ -239,8 +228,9 @@ class LocalGraphStore:
|
|
|
239
228
|
continue
|
|
240
229
|
|
|
241
230
|
time = self.df_dict[table.name][table._time_column]
|
|
242
|
-
|
|
243
|
-
|
|
231
|
+
if time.dtype != 'datetime64[ns]':
|
|
232
|
+
time = time.astype('datetime64[ns]')
|
|
233
|
+
time_dict[table.name] = time.astype(int).to_numpy() // 1000**3
|
|
244
234
|
time_column_dict[table.name] = table._time_column
|
|
245
235
|
|
|
246
236
|
if table.name in self.mask_dict.keys():
|
|
@@ -259,7 +249,7 @@ class LocalGraphStore:
|
|
|
259
249
|
|
|
260
250
|
def get_csc(
|
|
261
251
|
self,
|
|
262
|
-
graph:
|
|
252
|
+
graph: 'Graph',
|
|
263
253
|
) -> Tuple[
|
|
264
254
|
Dict[Tuple[str, str, str], np.ndarray],
|
|
265
255
|
Dict[Tuple[str, str, str], np.ndarray],
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
from typing import TYPE_CHECKING
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
import pandas as pd
|
|
5
|
+
|
|
6
|
+
from kumoai.experimental.rfm.backend.local import LocalGraphStore
|
|
7
|
+
from kumoai.experimental.rfm.base import EdgeSpec, Sampler, SamplerOutput
|
|
8
|
+
from kumoai.utils import ProgressLogger
|
|
9
|
+
|
|
10
|
+
if TYPE_CHECKING:
|
|
11
|
+
from kumoai.experimental.rfm import Graph
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class LocalSampler(Sampler):
|
|
15
|
+
def __init__(
|
|
16
|
+
self,
|
|
17
|
+
graph: 'Graph',
|
|
18
|
+
verbose: bool | ProgressLogger = True,
|
|
19
|
+
) -> None:
|
|
20
|
+
super().__init__(graph=graph)
|
|
21
|
+
|
|
22
|
+
import kumoai.kumolib as kumolib
|
|
23
|
+
|
|
24
|
+
self._graph_store = LocalGraphStore(graph, verbose)
|
|
25
|
+
self._graph_sampler = kumolib.NeighborSampler(
|
|
26
|
+
list(self.table_stype_dict.keys()),
|
|
27
|
+
self.edge_types,
|
|
28
|
+
{
|
|
29
|
+
'__'.join(edge_type): colptr
|
|
30
|
+
for edge_type, colptr in self._graph_store.colptr_dict.items()
|
|
31
|
+
},
|
|
32
|
+
{
|
|
33
|
+
'__'.join(edge_type): row
|
|
34
|
+
for edge_type, row in self._graph_store.row_dict.items()
|
|
35
|
+
},
|
|
36
|
+
self._graph_store.time_dict,
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
def sample(
|
|
40
|
+
self,
|
|
41
|
+
entity_table_name: str,
|
|
42
|
+
entity_pkey: pd.Series,
|
|
43
|
+
anchor_time: pd.Series,
|
|
44
|
+
column_spec_dict: dict[str, list[str]],
|
|
45
|
+
edge_spec_dict: dict[tuple[str, str, str], list[EdgeSpec]],
|
|
46
|
+
drop_duplicates: bool = False,
|
|
47
|
+
return_edges: bool = False,
|
|
48
|
+
) -> SamplerOutput:
|
|
49
|
+
|
|
50
|
+
if anchor_time.dtype != 'datetime64[ns]':
|
|
51
|
+
anchor_time = anchor_time.astype('datetime64[ns]')
|
|
52
|
+
|
|
53
|
+
num_hops = max([len(specs) for specs in edge_spec_dict.values()] + [0])
|
|
54
|
+
num_neighbors_dict: dict[str, list[int]] = {}
|
|
55
|
+
|
|
56
|
+
for edge_type, specs in edge_spec_dict.items():
|
|
57
|
+
edge_type_str = '__'.join(edge_type)
|
|
58
|
+
num_neighbors_dict[edge_type_str] = [0] * num_hops
|
|
59
|
+
for hop, spec in enumerate(specs):
|
|
60
|
+
# TODO Add support for time-based sampling.
|
|
61
|
+
assert spec.num_neighbors is not None
|
|
62
|
+
num_neighbors_dict[edge_type_str][hop] = spec.num_neighbors
|
|
63
|
+
|
|
64
|
+
(
|
|
65
|
+
row_dict,
|
|
66
|
+
col_dict,
|
|
67
|
+
node_dict,
|
|
68
|
+
batch_dict,
|
|
69
|
+
num_sampled_nodes_dict,
|
|
70
|
+
num_sampled_edges_dict,
|
|
71
|
+
) = self._graph_sampler.sample(
|
|
72
|
+
num_neighbors_dict,
|
|
73
|
+
{},
|
|
74
|
+
entity_table_name,
|
|
75
|
+
self._graph_store.get_node_id(entity_table_name, entity_pkey),
|
|
76
|
+
anchor_time.astype(int).to_numpy() // 1000**3, # to seconds
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
df_dict: dict[str, pd.DataFrame] = {}
|
|
80
|
+
inverse_dict: dict[str, np.ndarray] = {}
|
|
81
|
+
for table_name, node in node_dict.items():
|
|
82
|
+
df = self._graph_store.df_dict[table_name]
|
|
83
|
+
columns = column_spec_dict[table_name]
|
|
84
|
+
if self.end_time_column_dict.get(table_name, None) in columns:
|
|
85
|
+
df = df.iloc[node]
|
|
86
|
+
elif len(columns) > 0 and drop_duplicates:
|
|
87
|
+
# Only store unique rows in `df` above a certain threshold:
|
|
88
|
+
unique_node, inverse = np.unique(node, return_inverse=True)
|
|
89
|
+
if len(node) > 1.05 * len(unique_node):
|
|
90
|
+
df = df.iloc[unique_node]
|
|
91
|
+
inverse_dict[table_name] = inverse
|
|
92
|
+
else:
|
|
93
|
+
df = df.iloc[node]
|
|
94
|
+
else:
|
|
95
|
+
df = df.iloc[node]
|
|
96
|
+
df = df.reset_index(drop=True)
|
|
97
|
+
df = df[columns]
|
|
98
|
+
df_dict[table_name] = df
|
|
99
|
+
|
|
100
|
+
num_sampled_nodes_dict = {
|
|
101
|
+
table_name: num_sampled_nodes.tolist()
|
|
102
|
+
for table_name, num_sampled_nodes in
|
|
103
|
+
num_sampled_nodes_dict.items()
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
if return_edges:
|
|
107
|
+
row_dict = {
|
|
108
|
+
edge_type: row_dict['__'.join(edge_type)]
|
|
109
|
+
for edge_type in edge_spec_dict.keys()
|
|
110
|
+
}
|
|
111
|
+
col_dict = {
|
|
112
|
+
edge_type: col_dict['__'.join(edge_type)]
|
|
113
|
+
for edge_type in edge_spec_dict.keys()
|
|
114
|
+
}
|
|
115
|
+
num_sampled_edges_dict = {
|
|
116
|
+
edge_type:
|
|
117
|
+
num_sampled_edges_dict['__'.join(edge_type)].tolist()
|
|
118
|
+
for edge_type in edge_spec_dict.keys()
|
|
119
|
+
}
|
|
120
|
+
else:
|
|
121
|
+
row_dict = col_dict = num_sampled_edges_dict = None
|
|
122
|
+
|
|
123
|
+
return SamplerOutput(
|
|
124
|
+
df_dict=df_dict,
|
|
125
|
+
inverse_dict=inverse_dict,
|
|
126
|
+
batch_dict=batch_dict,
|
|
127
|
+
num_sampled_nodes_dict=num_sampled_nodes_dict,
|
|
128
|
+
row_dict=row_dict,
|
|
129
|
+
col_dict=col_dict,
|
|
130
|
+
num_sampled_edges_dict=num_sampled_edges_dict,
|
|
131
|
+
)
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import warnings
|
|
2
|
+
from typing import List, Optional
|
|
3
|
+
|
|
4
|
+
import pandas as pd
|
|
5
|
+
|
|
6
|
+
from kumoai.experimental.rfm.base import SourceColumn, SourceForeignKey, Table
|
|
7
|
+
from kumoai.experimental.rfm.infer import infer_dtype
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class LocalTable(Table):
|
|
11
|
+
r"""A table backed by a :class:`pandas.DataFrame`.
|
|
12
|
+
|
|
13
|
+
A :class:`LocalTable` fully specifies the relevant metadata, *i.e.*
|
|
14
|
+
selected columns, column semantic types, primary keys and time columns.
|
|
15
|
+
:class:`LocalTable` is used to create a :class:`Graph`.
|
|
16
|
+
|
|
17
|
+
.. code-block:: python
|
|
18
|
+
|
|
19
|
+
import pandas as pd
|
|
20
|
+
import kumoai.experimental.rfm as rfm
|
|
21
|
+
|
|
22
|
+
# Load data from a CSV file:
|
|
23
|
+
df = pd.read_csv("data.csv")
|
|
24
|
+
|
|
25
|
+
# Create a table from a `pandas.DataFrame` and infer its metadata ...
|
|
26
|
+
table = rfm.LocalTable(df, name="my_table").infer_metadata()
|
|
27
|
+
|
|
28
|
+
# ... or create a table explicitly:
|
|
29
|
+
table = rfm.LocalTable(
|
|
30
|
+
df=df,
|
|
31
|
+
name="my_table",
|
|
32
|
+
primary_key="id",
|
|
33
|
+
time_column="time",
|
|
34
|
+
end_time_column=None,
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
# Verify metadata:
|
|
38
|
+
table.print_metadata()
|
|
39
|
+
|
|
40
|
+
# Change the semantic type of a column:
|
|
41
|
+
table[column].stype = "text"
|
|
42
|
+
|
|
43
|
+
Args:
|
|
44
|
+
df: The data frame to create this table from.
|
|
45
|
+
name: The name of this table.
|
|
46
|
+
primary_key: The name of the primary key of this table, if it exists.
|
|
47
|
+
time_column: The name of the time column of this table, if it exists.
|
|
48
|
+
end_time_column: The name of the end time column of this table, if it
|
|
49
|
+
exists.
|
|
50
|
+
"""
|
|
51
|
+
def __init__(
|
|
52
|
+
self,
|
|
53
|
+
df: pd.DataFrame,
|
|
54
|
+
name: str,
|
|
55
|
+
primary_key: Optional[str] = None,
|
|
56
|
+
time_column: Optional[str] = None,
|
|
57
|
+
end_time_column: Optional[str] = None,
|
|
58
|
+
) -> None:
|
|
59
|
+
|
|
60
|
+
if df.empty:
|
|
61
|
+
raise ValueError("Data frame is empty")
|
|
62
|
+
if isinstance(df.columns, pd.MultiIndex):
|
|
63
|
+
raise ValueError("Data frame must not have a multi-index")
|
|
64
|
+
if not df.columns.is_unique:
|
|
65
|
+
raise ValueError("Data frame must have unique column names")
|
|
66
|
+
if any(col == '' for col in df.columns):
|
|
67
|
+
raise ValueError("Data frame must have non-empty column names")
|
|
68
|
+
|
|
69
|
+
self._data = df.copy(deep=False)
|
|
70
|
+
|
|
71
|
+
super().__init__(
|
|
72
|
+
name=name,
|
|
73
|
+
columns=list(df.columns),
|
|
74
|
+
primary_key=primary_key,
|
|
75
|
+
time_column=time_column,
|
|
76
|
+
end_time_column=end_time_column,
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
def _get_source_columns(self) -> List[SourceColumn]:
|
|
80
|
+
source_columns: List[SourceColumn] = []
|
|
81
|
+
for column in self._data.columns:
|
|
82
|
+
ser = self._data[column]
|
|
83
|
+
try:
|
|
84
|
+
dtype = infer_dtype(ser)
|
|
85
|
+
except Exception:
|
|
86
|
+
warnings.warn(f"Data type inference for column '{column}' in "
|
|
87
|
+
f"table '{self.name}' failed. Consider changing "
|
|
88
|
+
f"the data type of the column to use it within "
|
|
89
|
+
f"this table.")
|
|
90
|
+
continue
|
|
91
|
+
|
|
92
|
+
source_column = SourceColumn(
|
|
93
|
+
name=column,
|
|
94
|
+
dtype=dtype,
|
|
95
|
+
is_primary_key=False,
|
|
96
|
+
is_unique_key=False,
|
|
97
|
+
)
|
|
98
|
+
source_columns.append(source_column)
|
|
99
|
+
|
|
100
|
+
return source_columns
|
|
101
|
+
|
|
102
|
+
def _get_source_foreign_keys(self) -> List[SourceForeignKey]:
|
|
103
|
+
return []
|
|
104
|
+
|
|
105
|
+
def _get_sample_df(self) -> pd.DataFrame:
|
|
106
|
+
return self._data
|
|
107
|
+
|
|
108
|
+
def _get_num_rows(self) -> Optional[int]:
|
|
109
|
+
return len(self._data)
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
from typing import Any, TypeAlias
|
|
2
|
+
|
|
3
|
+
try:
|
|
4
|
+
import snowflake.connector
|
|
5
|
+
except ImportError:
|
|
6
|
+
raise ImportError("No module named 'snowflake'. Please install Kumo SDK "
|
|
7
|
+
"with the 'snowflake' extension via "
|
|
8
|
+
"`pip install kumoai[snowflake]`.")
|
|
9
|
+
|
|
10
|
+
Connection: TypeAlias = snowflake.connector.SnowflakeConnection
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def connect(**kwargs: Any) -> Connection:
|
|
14
|
+
r"""Opens a connection to a :class:`snowflake` database.
|
|
15
|
+
|
|
16
|
+
If available, will return a connection to the active session.
|
|
17
|
+
|
|
18
|
+
kwargs: Connection arguments, following the :class:`snowflake` protocol.
|
|
19
|
+
"""
|
|
20
|
+
try:
|
|
21
|
+
from snowflake.snowpark.context import get_active_session
|
|
22
|
+
return get_active_session().connection
|
|
23
|
+
except Exception:
|
|
24
|
+
pass
|
|
25
|
+
|
|
26
|
+
return snowflake.connector.connect(**kwargs)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
from .table import SnowTable # noqa: E402
|
|
30
|
+
|
|
31
|
+
__all__ = [
|
|
32
|
+
'connect',
|
|
33
|
+
'Connection',
|
|
34
|
+
'SnowTable',
|
|
35
|
+
]
|