kumoai 2.13.0.dev202511211730__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.
Files changed (42) hide show
  1. kumoai/__init__.py +12 -0
  2. kumoai/_version.py +1 -1
  3. kumoai/client/pquery.py +6 -2
  4. kumoai/connector/utils.py +23 -2
  5. kumoai/experimental/rfm/__init__.py +20 -45
  6. kumoai/experimental/rfm/backend/__init__.py +0 -0
  7. kumoai/experimental/rfm/backend/local/__init__.py +42 -0
  8. kumoai/experimental/rfm/{local_graph_store.py → backend/local/graph_store.py} +37 -90
  9. kumoai/experimental/rfm/backend/local/sampler.py +313 -0
  10. kumoai/experimental/rfm/backend/local/table.py +119 -0
  11. kumoai/experimental/rfm/backend/snow/__init__.py +37 -0
  12. kumoai/experimental/rfm/backend/snow/sampler.py +119 -0
  13. kumoai/experimental/rfm/backend/snow/table.py +135 -0
  14. kumoai/experimental/rfm/backend/sqlite/__init__.py +32 -0
  15. kumoai/experimental/rfm/backend/sqlite/sampler.py +112 -0
  16. kumoai/experimental/rfm/backend/sqlite/table.py +115 -0
  17. kumoai/experimental/rfm/base/__init__.py +23 -0
  18. kumoai/experimental/rfm/base/column.py +66 -0
  19. kumoai/experimental/rfm/base/sampler.py +773 -0
  20. kumoai/experimental/rfm/base/source.py +19 -0
  21. kumoai/experimental/rfm/{local_table.py → base/table.py} +152 -141
  22. kumoai/experimental/rfm/{local_graph.py → graph.py} +352 -80
  23. kumoai/experimental/rfm/infer/__init__.py +6 -0
  24. kumoai/experimental/rfm/infer/dtype.py +79 -0
  25. kumoai/experimental/rfm/infer/pkey.py +126 -0
  26. kumoai/experimental/rfm/infer/time_col.py +62 -0
  27. kumoai/experimental/rfm/pquery/pandas_executor.py +1 -1
  28. kumoai/experimental/rfm/rfm.py +224 -167
  29. kumoai/experimental/rfm/sagemaker.py +11 -3
  30. kumoai/pquery/predictive_query.py +10 -6
  31. kumoai/testing/decorators.py +1 -1
  32. kumoai/testing/snow.py +50 -0
  33. kumoai/utils/__init__.py +2 -0
  34. kumoai/utils/sql.py +3 -0
  35. {kumoai-2.13.0.dev202511211730.dist-info → kumoai-2.14.0.dev202512141732.dist-info}/METADATA +9 -8
  36. {kumoai-2.13.0.dev202511211730.dist-info → kumoai-2.14.0.dev202512141732.dist-info}/RECORD +39 -23
  37. kumoai/experimental/rfm/local_graph_sampler.py +0 -182
  38. kumoai/experimental/rfm/local_pquery_driver.py +0 -689
  39. kumoai/experimental/rfm/utils.py +0 -344
  40. {kumoai-2.13.0.dev202511211730.dist-info → kumoai-2.14.0.dev202512141732.dist-info}/WHEEL +0 -0
  41. {kumoai-2.13.0.dev202511211730.dist-info → kumoai-2.14.0.dev202512141732.dist-info}/licenses/LICENSE +0 -0
  42. {kumoai-2.13.0.dev202511211730.dist-info → kumoai-2.14.0.dev202512141732.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.dev202511211730'
1
+ __version__ = '2.14.0.dev202512141732'
kumoai/client/pquery.py CHANGED
@@ -176,8 +176,12 @@ def filter_model_plan(
176
176
  # Undefined
177
177
  pass
178
178
 
179
- new_opt_fields.append((field.name, _type, default))
180
- new_opts.append(getattr(section, field.name))
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
- _SAN_RE = re.compile(r"[^0-9A-Za-z]+")
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
- delimiter.
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 typing import Optional, Dict, Tuple
42
- import os
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
- from .sagemaker import (KumoClient_SageMakerAdapter,
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
- 'LocalGraph',
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 LocalGraph
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: LocalGraph,
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, preprocess)
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.pkey_name_dict, self.pkey_map_dict = self.get_pkey_data(graph)
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
- self.time_column_dict,
48
- self.end_time_column_dict,
49
- self.time_dict,
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"{self.min_time.date()} to {self.max_time.date()}")
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: LocalGraph,
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
- table_name: table._data.copy(deep=False).reset_index(drop=True)
125
- for table_name, table in graph.tables.items()
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 get_stype_dict(self, graph: LocalGraph) -> Dict[str, Dict[str, Stype]]:
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: LocalGraph,
184
- ) -> Tuple[
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 pkey_name_dict, pkey_map_dict
175
+ return pkey_map_dict
218
176
 
219
177
  def get_time_data(
220
178
  self,
221
- graph: LocalGraph,
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
- min_time = pd.Timestamp.max
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
- time_dict[table.name] = time.astype('datetime64[ns]').astype(
243
- int).to_numpy() // 1000**3
244
- time_column_dict[table.name] = table._time_column
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
- min_time = min(min_time, time.min())
250
- max_time = max(max_time, time.max())
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: LocalGraph,
209
+ graph: 'Graph',
263
210
  ) -> Tuple[
264
211
  Dict[Tuple[str, str, str], np.ndarray],
265
212
  Dict[Tuple[str, str, str], np.ndarray],