kumoai 2.13.0.dev202512011731__cp312-cp312-macosx_11_0_arm64.whl → 2.14.0.dev202512181731__cp312-cp312-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.
Files changed (45) hide show
  1. kumoai/__init__.py +12 -0
  2. kumoai/_version.py +1 -1
  3. kumoai/client/pquery.py +6 -2
  4. kumoai/experimental/rfm/__init__.py +33 -8
  5. kumoai/experimental/rfm/authenticate.py +3 -4
  6. kumoai/experimental/rfm/backend/local/__init__.py +4 -0
  7. kumoai/experimental/rfm/{local_graph_store.py → backend/local/graph_store.py} +53 -107
  8. kumoai/experimental/rfm/backend/local/sampler.py +315 -0
  9. kumoai/experimental/rfm/backend/local/table.py +41 -80
  10. kumoai/experimental/rfm/backend/snow/__init__.py +37 -0
  11. kumoai/experimental/rfm/backend/snow/sampler.py +252 -0
  12. kumoai/experimental/rfm/backend/snow/table.py +147 -0
  13. kumoai/experimental/rfm/backend/sqlite/__init__.py +11 -2
  14. kumoai/experimental/rfm/backend/sqlite/sampler.py +349 -0
  15. kumoai/experimental/rfm/backend/sqlite/table.py +108 -88
  16. kumoai/experimental/rfm/base/__init__.py +26 -2
  17. kumoai/experimental/rfm/base/column.py +6 -12
  18. kumoai/experimental/rfm/base/column_expression.py +16 -0
  19. kumoai/experimental/rfm/base/sampler.py +773 -0
  20. kumoai/experimental/rfm/base/source.py +19 -0
  21. kumoai/experimental/rfm/base/sql_sampler.py +84 -0
  22. kumoai/experimental/rfm/base/sql_table.py +113 -0
  23. kumoai/experimental/rfm/base/table.py +174 -76
  24. kumoai/experimental/rfm/graph.py +444 -84
  25. kumoai/experimental/rfm/infer/__init__.py +6 -0
  26. kumoai/experimental/rfm/infer/dtype.py +77 -0
  27. kumoai/experimental/rfm/infer/pkey.py +128 -0
  28. kumoai/experimental/rfm/infer/time_col.py +61 -0
  29. kumoai/experimental/rfm/pquery/executor.py +27 -27
  30. kumoai/experimental/rfm/pquery/pandas_executor.py +30 -32
  31. kumoai/experimental/rfm/rfm.py +299 -240
  32. kumoai/experimental/rfm/sagemaker.py +4 -4
  33. kumoai/pquery/predictive_query.py +10 -6
  34. kumoai/testing/snow.py +50 -0
  35. kumoai/utils/__init__.py +3 -2
  36. kumoai/utils/progress_logger.py +178 -12
  37. kumoai/utils/sql.py +3 -0
  38. {kumoai-2.13.0.dev202512011731.dist-info → kumoai-2.14.0.dev202512181731.dist-info}/METADATA +6 -2
  39. {kumoai-2.13.0.dev202512011731.dist-info → kumoai-2.14.0.dev202512181731.dist-info}/RECORD +42 -30
  40. kumoai/experimental/rfm/local_graph_sampler.py +0 -182
  41. kumoai/experimental/rfm/local_pquery_driver.py +0 -689
  42. kumoai/experimental/rfm/utils.py +0 -344
  43. {kumoai-2.13.0.dev202512011731.dist-info → kumoai-2.14.0.dev202512181731.dist-info}/WHEEL +0 -0
  44. {kumoai-2.13.0.dev202512011731.dist-info → kumoai-2.14.0.dev202512181731.dist-info}/licenses/LICENSE +0 -0
  45. {kumoai-2.13.0.dev202512011731.dist-info → kumoai-2.14.0.dev202512181731.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,252 @@
1
+ import json
2
+ from collections.abc import Iterator
3
+ from contextlib import contextmanager
4
+
5
+ import numpy as np
6
+ import pandas as pd
7
+ import pyarrow as pa
8
+ from kumoapi.pquery import ValidatedPredictiveQuery
9
+
10
+ from kumoai.experimental.rfm.backend.snow import Connection
11
+ from kumoai.experimental.rfm.base import SQLSampler
12
+ from kumoai.experimental.rfm.pquery import PQueryPandasExecutor
13
+ from kumoai.utils import quote_ident
14
+
15
+
16
+ @contextmanager
17
+ def paramstyle(connection: Connection, style: str = 'qmark') -> Iterator[None]:
18
+ _style = connection._paramstyle
19
+ connection._paramstyle = style
20
+ yield
21
+ connection._paramstyle = _style
22
+
23
+
24
+ class SnowSampler(SQLSampler):
25
+ def _get_min_max_time_dict(
26
+ self,
27
+ table_names: list[str],
28
+ ) -> dict[str, tuple[pd.Timestamp, pd.Timestamp]]:
29
+ selects: list[str] = []
30
+ for table_name in table_names:
31
+ time_column = self.time_column_dict[table_name]
32
+ select = (f"SELECT\n"
33
+ f" ? as table_name,\n"
34
+ f" MIN({quote_ident(time_column)}) as min_date,\n"
35
+ f" MAX({quote_ident(time_column)}) as max_date\n"
36
+ f"FROM {self.fqn_dict[table_name]}")
37
+ selects.append(select)
38
+ sql = "\nUNION ALL\n".join(selects)
39
+
40
+ out_dict: dict[str, tuple[pd.Timestamp, pd.Timestamp]] = {}
41
+ with paramstyle(self._connection), self._connection.cursor() as cursor:
42
+ cursor.execute(sql, table_names)
43
+ rows = cursor.fetchall()
44
+ for table_name, _min, _max in rows:
45
+ out_dict[table_name] = (
46
+ pd.Timestamp.max if _min is None else pd.Timestamp(_min),
47
+ pd.Timestamp.min if _max is None else pd.Timestamp(_max),
48
+ )
49
+
50
+ return out_dict
51
+
52
+ def _sample_entity_table(
53
+ self,
54
+ table_name: str,
55
+ columns: set[str],
56
+ num_rows: int,
57
+ random_seed: int | None = None,
58
+ ) -> pd.DataFrame:
59
+ # NOTE Snowflake does support `SEED` only as part of `SYSTEM` sampling.
60
+ num_rows = min(num_rows, 1_000_000) # Snowflake's upper limit.
61
+
62
+ filters: list[str] = []
63
+ primary_key = self.primary_key_dict[table_name]
64
+ if self.source_table_dict[table_name][primary_key].is_nullable:
65
+ filters.append(f" {quote_ident(primary_key)} IS NOT NULL")
66
+ time_column = self.time_column_dict.get(table_name)
67
+ if (time_column is not None and
68
+ self.source_table_dict[table_name][time_column].is_nullable):
69
+ filters.append(f" {quote_ident(time_column)} IS NOT NULL")
70
+
71
+ sql = (f"SELECT {', '.join(quote_ident(col) for col in columns)}\n"
72
+ f"FROM {self.fqn_dict[table_name]}\n"
73
+ f"SAMPLE ROW ({num_rows} ROWS)")
74
+ if len(filters) > 0:
75
+ sql += f"\nWHERE{' AND'.join(filters)}"
76
+
77
+ with self._connection.cursor() as cursor:
78
+ # NOTE This may return duplicate primary keys. This is okay.
79
+ cursor.execute(sql)
80
+ table = cursor.fetch_arrow_all()
81
+
82
+ return self._sanitize(table_name, table)
83
+
84
+ def _sample_target(
85
+ self,
86
+ query: ValidatedPredictiveQuery,
87
+ entity_df: pd.DataFrame,
88
+ train_index: np.ndarray,
89
+ train_time: pd.Series,
90
+ num_train_examples: int,
91
+ test_index: np.ndarray,
92
+ test_time: pd.Series,
93
+ num_test_examples: int,
94
+ columns_dict: dict[str, set[str]],
95
+ time_offset_dict: dict[
96
+ tuple[str, str, str],
97
+ tuple[pd.DateOffset | None, pd.DateOffset],
98
+ ],
99
+ ) -> tuple[pd.Series, np.ndarray, pd.Series, np.ndarray]:
100
+
101
+ # NOTE For Snowflake, we execute everything at once to pay minimal
102
+ # query initialization costs.
103
+ index = np.concatenate([train_index, test_index])
104
+ time = pd.concat([train_time, test_time], axis=0, ignore_index=True)
105
+
106
+ entity_df = entity_df.iloc[index].reset_index(drop=True)
107
+
108
+ feat_dict: dict[str, pd.DataFrame] = {query.entity_table: entity_df}
109
+ time_dict: dict[str, pd.Series] = {}
110
+ time_column = self.time_column_dict.get(query.entity_table)
111
+ if time_column in columns_dict[query.entity_table]:
112
+ time_dict[query.entity_table] = entity_df[time_column]
113
+ batch_dict: dict[str, np.ndarray] = {
114
+ query.entity_table: np.arange(len(entity_df)),
115
+ }
116
+ for edge_type, (min_offset, max_offset) in time_offset_dict.items():
117
+ table_name, fkey, _ = edge_type
118
+ feat_dict[table_name], batch_dict[table_name] = self._by_time(
119
+ table_name=table_name,
120
+ fkey=fkey,
121
+ pkey=entity_df[self.primary_key_dict[query.entity_table]],
122
+ anchor_time=time,
123
+ min_offset=min_offset,
124
+ max_offset=max_offset,
125
+ columns=columns_dict[table_name],
126
+ )
127
+ time_column = self.time_column_dict.get(table_name)
128
+ if time_column in columns_dict[table_name]:
129
+ time_dict[table_name] = feat_dict[table_name][time_column]
130
+
131
+ y, mask = PQueryPandasExecutor().execute(
132
+ query=query,
133
+ feat_dict=feat_dict,
134
+ time_dict=time_dict,
135
+ batch_dict=batch_dict,
136
+ anchor_time=time,
137
+ num_forecasts=query.num_forecasts,
138
+ )
139
+
140
+ train_mask = mask[:len(train_index)]
141
+ test_mask = mask[len(train_index):]
142
+
143
+ boundary = int(train_mask.sum())
144
+ train_y = y.iloc[:boundary]
145
+ test_y = y.iloc[boundary:].reset_index(drop=True)
146
+
147
+ return train_y, train_mask, test_y, test_mask
148
+
149
+ def _by_pkey(
150
+ self,
151
+ table_name: str,
152
+ pkey: pd.Series,
153
+ columns: set[str],
154
+ ) -> tuple[pd.DataFrame, np.ndarray]:
155
+
156
+ pkey_name = self.primary_key_dict[table_name]
157
+ source_table = self.source_table_dict[table_name]
158
+
159
+ payload = json.dumps(list(pkey))
160
+
161
+ sql = ("WITH TMP as (\n"
162
+ " SELECT\n"
163
+ " f.index as BATCH,\n")
164
+ if source_table[pkey_name].dtype.is_int():
165
+ sql += " f.value::NUMBER as ID\n"
166
+ elif source_table[pkey_name].dtype.is_float():
167
+ sql += " f.value::FLOAT as ID\n"
168
+ else:
169
+ sql += " f.value::VARCHAR as ID\n"
170
+ sql += (f" FROM TABLE(FLATTEN(INPUT => PARSE_JSON(?))) f\n"
171
+ f")\n"
172
+ f"SELECT TMP.BATCH as __BATCH__, "
173
+ f"{', '.join('ENT.' + quote_ident(col) for col in columns)}\n"
174
+ f"FROM TMP\n"
175
+ f"JOIN {self.fqn_dict[table_name]} ENT\n"
176
+ f" ON ENT.{quote_ident(pkey_name)} = TMP.ID")
177
+
178
+ with paramstyle(self._connection), self._connection.cursor() as cursor:
179
+ cursor.execute(sql, (payload, ))
180
+ table = cursor.fetch_arrow_all()
181
+
182
+ # Remove any duplicated primary keys in post-processing:
183
+ tmp = table.append_column('__TMP__', pa.array(range(len(table))))
184
+ gb = tmp.group_by('__BATCH__').aggregate([('__TMP__', 'min')])
185
+ table = table.take(gb['__TMP___min'])
186
+
187
+ batch = table['__BATCH__'].cast(pa.int64()).to_numpy()
188
+ table = table.remove_column(table.schema.get_field_index('__BATCH__'))
189
+
190
+ return table.to_pandas(), batch # TODO Use `self._sanitize`.
191
+
192
+ # Helper Methods ##########################################################
193
+
194
+ def _by_time(
195
+ self,
196
+ table_name: str,
197
+ fkey: str,
198
+ pkey: pd.Series,
199
+ anchor_time: pd.Series,
200
+ min_offset: pd.DateOffset | None,
201
+ max_offset: pd.DateOffset,
202
+ columns: set[str],
203
+ ) -> tuple[pd.DataFrame, np.ndarray]:
204
+
205
+ end_time = anchor_time + max_offset
206
+ end_time = end_time.dt.strftime("%Y-%m-%d %H:%M:%S")
207
+ if min_offset is not None:
208
+ start_time = anchor_time + min_offset
209
+ start_time = start_time.dt.strftime("%Y-%m-%d %H:%M:%S")
210
+ payload = json.dumps(list(zip(pkey, end_time, start_time)))
211
+ else:
212
+ payload = json.dumps(list(zip(pkey, end_time)))
213
+
214
+ # Based on benchmarking, JSON payload is the fastest way to query by
215
+ # custom indices (compared to large `IN` clauses or temporary tables):
216
+ source_table = self.source_table_dict[table_name]
217
+ time_column = self.time_column_dict[table_name]
218
+ sql = ("WITH TMP as (\n"
219
+ " SELECT\n"
220
+ " f.index as BATCH,\n")
221
+ if source_table[fkey].dtype.is_int():
222
+ sql += " f.value[0]::NUMBER as ID,\n"
223
+ elif source_table[fkey].dtype.is_float():
224
+ sql += " f.value[0]::FLOAT as ID,\n"
225
+ else:
226
+ sql += " f.value[0]::VARCHAR as ID,\n"
227
+ sql += " f.value[1]::TIMESTAMP_NTZ as END_TIME"
228
+ if min_offset is not None:
229
+ sql += ",\n f.value[2]::TIMESTAMP_NTZ as START_TIME"
230
+ sql += (f"\n"
231
+ f" FROM TABLE(FLATTEN(INPUT => PARSE_JSON(?))) f\n"
232
+ f")\n"
233
+ f"SELECT TMP.BATCH as __BATCH__, "
234
+ f"{', '.join('FACT.' + quote_ident(col) for col in columns)}\n"
235
+ f"FROM TMP\n"
236
+ f"JOIN {self.fqn_dict[table_name]} FACT\n"
237
+ f" ON FACT.{quote_ident(fkey)} = TMP.ID\n"
238
+ f" AND FACT.{quote_ident(time_column)} <= TMP.END_TIME")
239
+ if min_offset is not None:
240
+ sql += f"\n AND FACT.{quote_ident(time_column)} > TMP.START_TIME"
241
+
242
+ with paramstyle(self._connection), self._connection.cursor() as cursor:
243
+ cursor.execute(sql, (payload, ))
244
+ table = cursor.fetch_arrow_all()
245
+
246
+ batch = table['__BATCH__'].cast(pa.int64()).to_numpy()
247
+ table = table.remove_column(table.schema.get_field_index('__BATCH__'))
248
+
249
+ return self._sanitize(table_name, table), batch
250
+
251
+ def _sanitize(self, table_name: str, table: pa.table) -> pd.DataFrame:
252
+ return table.to_pandas(types_mapper=pd.ArrowDtype)
@@ -0,0 +1,147 @@
1
+ import re
2
+ from collections.abc import Sequence
3
+ from typing import cast
4
+
5
+ import pandas as pd
6
+ from kumoapi.model_plan import MissingType
7
+ from kumoapi.typing import Dtype
8
+
9
+ from kumoai.experimental.rfm.backend.snow import Connection
10
+ from kumoai.experimental.rfm.base import (
11
+ ColumnExpressionType,
12
+ DataBackend,
13
+ SourceColumn,
14
+ SourceForeignKey,
15
+ SQLTable,
16
+ )
17
+ from kumoai.utils import quote_ident
18
+
19
+
20
+ class SnowTable(SQLTable):
21
+ r"""A table backed by a :class:`sqlite` database.
22
+
23
+ Args:
24
+ connection: The connection to a :class:`snowflake` database.
25
+ name: The logical name of this table.
26
+ source_name: The physical name of this table in the database. If set to
27
+ ``None``, ``name`` is being used.
28
+ database: The database.
29
+ schema: The schema.
30
+ columns: The selected physical columns of this table.
31
+ column_expressions: The logical columns of this table.
32
+ primary_key: The name of the primary key of this table, if it exists.
33
+ time_column: The name of the time column of this table, if it exists.
34
+ end_time_column: The name of the end time column of this table, if it
35
+ exists.
36
+ """
37
+ def __init__(
38
+ self,
39
+ connection: Connection,
40
+ name: str,
41
+ source_name: str | None = None,
42
+ database: str | None = None,
43
+ schema: str | None = None,
44
+ columns: Sequence[str] | None = None,
45
+ column_expressions: Sequence[ColumnExpressionType] | None = None,
46
+ primary_key: MissingType | str | None = MissingType.VALUE,
47
+ time_column: str | None = None,
48
+ end_time_column: str | None = None,
49
+ ) -> None:
50
+
51
+ if database is not None and schema is None:
52
+ raise ValueError(f"Unspecified 'schema' for table "
53
+ f"'{source_name or name}' in database "
54
+ f"'{database}'")
55
+
56
+ self._connection = connection
57
+ self._database = database
58
+ self._schema = schema
59
+
60
+ super().__init__(
61
+ name=name,
62
+ source_name=source_name,
63
+ columns=columns,
64
+ column_expressions=column_expressions,
65
+ primary_key=primary_key,
66
+ time_column=time_column,
67
+ end_time_column=end_time_column,
68
+ )
69
+
70
+ @property
71
+ def backend(self) -> DataBackend:
72
+ return cast(DataBackend, DataBackend.SNOWFLAKE)
73
+
74
+ @property
75
+ def fqn(self) -> str:
76
+ r"""The fully-qualified quoted table name."""
77
+ names: list[str] = []
78
+ if self._database is not None:
79
+ names.append(quote_ident(self._database))
80
+ if self._schema is not None:
81
+ names.append(quote_ident(self._schema))
82
+ return '.'.join(names + [quote_ident(self._source_name)])
83
+
84
+ def _get_source_columns(self) -> list[SourceColumn]:
85
+ source_columns: list[SourceColumn] = []
86
+ with self._connection.cursor() as cursor:
87
+ try:
88
+ sql = f"DESCRIBE TABLE {self.fqn}"
89
+ cursor.execute(sql)
90
+ except Exception as e:
91
+ names: list[str] = []
92
+ if self._database is not None:
93
+ names.append(self._database)
94
+ if self._schema is not None:
95
+ names.append(self._schema)
96
+ source_name = '.'.join(names + [self._source_name])
97
+ raise ValueError(f"Table '{source_name}' does not exist in "
98
+ f"the remote data backend") from e
99
+
100
+ for row in cursor.fetchall():
101
+ column, type, _, null, _, is_pkey, is_unique, *_ = row
102
+
103
+ type = type.strip().upper()
104
+ if type.startswith('NUMBER'):
105
+ dtype = Dtype.int
106
+ elif type.startswith('VARCHAR'):
107
+ dtype = Dtype.string
108
+ elif type == 'FLOAT':
109
+ dtype = Dtype.float
110
+ elif type == 'BOOLEAN':
111
+ dtype = Dtype.bool
112
+ elif re.search('DATE|TIMESTAMP', type):
113
+ dtype = Dtype.date
114
+ else:
115
+ continue
116
+
117
+ source_column = SourceColumn(
118
+ name=column,
119
+ dtype=dtype,
120
+ is_primary_key=is_pkey.strip().upper() == 'Y',
121
+ is_unique_key=is_unique.strip().upper() == 'Y',
122
+ is_nullable=null.strip().upper() == 'Y',
123
+ )
124
+ source_columns.append(source_column)
125
+
126
+ return source_columns
127
+
128
+ def _get_source_foreign_keys(self) -> list[SourceForeignKey]:
129
+ source_fkeys: list[SourceForeignKey] = []
130
+ with self._connection.cursor() as cursor:
131
+ sql = f"SHOW IMPORTED KEYS IN TABLE {self.fqn}"
132
+ cursor.execute(sql)
133
+ for row in cursor.fetchall():
134
+ _, _, _, dst_table, pkey, _, _, _, fkey, *_ = row
135
+ source_fkeys.append(SourceForeignKey(fkey, dst_table, pkey))
136
+ return source_fkeys
137
+
138
+ def _get_sample_df(self) -> pd.DataFrame:
139
+ with self._connection.cursor() as cursor:
140
+ columns = [quote_ident(col) for col in self._source_column_dict]
141
+ sql = f"SELECT {', '.join(columns)} FROM {self.fqn} LIMIT 1000"
142
+ cursor.execute(sql)
143
+ table = cursor.fetch_arrow_all()
144
+ return table.to_pandas(types_mapper=pd.ArrowDtype)
145
+
146
+ def _get_num_rows(self) -> int | None:
147
+ return None
@@ -1,5 +1,5 @@
1
1
  from pathlib import Path
2
- from typing import Any, TypeAlias, Union
2
+ from typing import Any, TypeAlias
3
3
 
4
4
  try:
5
5
  import adbc_driver_sqlite.dbapi as adbc
@@ -11,13 +11,22 @@ except ImportError:
11
11
  Connection: TypeAlias = adbc.AdbcSqliteConnection
12
12
 
13
13
 
14
- def connect(uri: Union[str, Path, None] = None, **kwargs: Any) -> Connection:
14
+ def connect(uri: str | Path | None = None, **kwargs: Any) -> Connection:
15
+ r"""Opens a connection to a :class:`sqlite` database.
16
+
17
+ uri: The path to the database file to be opened.
18
+ kwargs: Additional connection arguments, following the
19
+ :class:`adbc_driver_sqlite` protocol.
20
+ """
15
21
  return adbc.connect(uri, **kwargs)
16
22
 
17
23
 
18
24
  from .table import SQLiteTable # noqa: E402
25
+ from .sampler import SQLiteSampler # noqa: E402
19
26
 
20
27
  __all__ = [
28
+ 'connect',
21
29
  'Connection',
22
30
  'SQLiteTable',
31
+ 'SQLiteSampler',
23
32
  ]