kumoai 2.12.0.dev202510231830__cp311-cp311-win_amd64.whl → 2.14.0.dev202512311733__cp311-cp311-win_amd64.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 +41 -35
- kumoai/_version.py +1 -1
- kumoai/client/client.py +15 -13
- kumoai/client/endpoints.py +1 -0
- kumoai/client/jobs.py +24 -0
- kumoai/client/pquery.py +6 -2
- kumoai/client/rfm.py +35 -7
- kumoai/connector/utils.py +23 -2
- kumoai/experimental/rfm/__init__.py +191 -48
- kumoai/experimental/rfm/authenticate.py +3 -4
- 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} +65 -127
- kumoai/experimental/rfm/backend/local/sampler.py +312 -0
- kumoai/experimental/rfm/backend/local/table.py +113 -0
- kumoai/experimental/rfm/backend/snow/__init__.py +37 -0
- kumoai/experimental/rfm/backend/snow/sampler.py +297 -0
- kumoai/experimental/rfm/backend/snow/table.py +242 -0
- kumoai/experimental/rfm/backend/sqlite/__init__.py +32 -0
- kumoai/experimental/rfm/backend/sqlite/sampler.py +398 -0
- kumoai/experimental/rfm/backend/sqlite/table.py +184 -0
- kumoai/experimental/rfm/base/__init__.py +30 -0
- kumoai/experimental/rfm/base/column.py +152 -0
- kumoai/experimental/rfm/base/expression.py +44 -0
- kumoai/experimental/rfm/base/sampler.py +761 -0
- kumoai/experimental/rfm/base/source.py +19 -0
- kumoai/experimental/rfm/base/sql_sampler.py +143 -0
- kumoai/experimental/rfm/base/table.py +735 -0
- kumoai/experimental/rfm/graph.py +1237 -0
- kumoai/experimental/rfm/infer/__init__.py +8 -0
- kumoai/experimental/rfm/infer/dtype.py +82 -0
- kumoai/experimental/rfm/infer/multicategorical.py +1 -1
- kumoai/experimental/rfm/infer/pkey.py +128 -0
- kumoai/experimental/rfm/infer/stype.py +35 -0
- kumoai/experimental/rfm/infer/time_col.py +61 -0
- kumoai/experimental/rfm/pquery/__init__.py +0 -4
- kumoai/experimental/rfm/pquery/executor.py +27 -27
- kumoai/experimental/rfm/pquery/pandas_executor.py +64 -40
- kumoai/experimental/rfm/relbench.py +76 -0
- kumoai/experimental/rfm/rfm.py +386 -276
- kumoai/experimental/rfm/sagemaker.py +138 -0
- kumoai/kumolib.cp311-win_amd64.pyd +0 -0
- kumoai/pquery/predictive_query.py +10 -6
- kumoai/spcs.py +1 -3
- kumoai/testing/decorators.py +1 -1
- kumoai/testing/snow.py +50 -0
- kumoai/trainer/distilled_trainer.py +175 -0
- kumoai/trainer/trainer.py +9 -10
- kumoai/utils/__init__.py +3 -2
- kumoai/utils/display.py +51 -0
- kumoai/utils/progress_logger.py +188 -16
- kumoai/utils/sql.py +3 -0
- {kumoai-2.12.0.dev202510231830.dist-info → kumoai-2.14.0.dev202512311733.dist-info}/METADATA +13 -2
- {kumoai-2.12.0.dev202510231830.dist-info → kumoai-2.14.0.dev202512311733.dist-info}/RECORD +57 -36
- kumoai/experimental/rfm/local_graph.py +0 -810
- kumoai/experimental/rfm/local_graph_sampler.py +0 -184
- kumoai/experimental/rfm/local_pquery_driver.py +0 -494
- kumoai/experimental/rfm/local_table.py +0 -545
- kumoai/experimental/rfm/pquery/backend.py +0 -136
- kumoai/experimental/rfm/pquery/pandas_backend.py +0 -478
- kumoai/experimental/rfm/utils.py +0 -344
- {kumoai-2.12.0.dev202510231830.dist-info → kumoai-2.14.0.dev202512311733.dist-info}/WHEEL +0 -0
- {kumoai-2.12.0.dev202510231830.dist-info → kumoai-2.14.0.dev202512311733.dist-info}/licenses/LICENSE +0 -0
- {kumoai-2.12.0.dev202510231830.dist-info → kumoai-2.14.0.dev202512311733.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
from pathlib import Path
|
|
2
|
+
from typing import Any, TypeAlias
|
|
3
|
+
|
|
4
|
+
try:
|
|
5
|
+
import adbc_driver_sqlite.dbapi as adbc
|
|
6
|
+
except ImportError:
|
|
7
|
+
raise ImportError("No module named 'adbc_driver_sqlite'. Please install "
|
|
8
|
+
"Kumo SDK with the 'sqlite' extension via "
|
|
9
|
+
"`pip install kumoai[sqlite]`.")
|
|
10
|
+
|
|
11
|
+
Connection: TypeAlias = adbc.AdbcSqliteConnection
|
|
12
|
+
|
|
13
|
+
|
|
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
|
+
"""
|
|
21
|
+
return adbc.connect(uri, **kwargs)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
from .table import SQLiteTable # noqa: E402
|
|
25
|
+
from .sampler import SQLiteSampler # noqa: E402
|
|
26
|
+
|
|
27
|
+
__all__ = [
|
|
28
|
+
'connect',
|
|
29
|
+
'Connection',
|
|
30
|
+
'SQLiteTable',
|
|
31
|
+
'SQLiteSampler',
|
|
32
|
+
]
|
|
@@ -0,0 +1,398 @@
|
|
|
1
|
+
import warnings
|
|
2
|
+
from collections import defaultdict
|
|
3
|
+
from typing import TYPE_CHECKING
|
|
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.sqlite import SQLiteTable
|
|
11
|
+
from kumoai.experimental.rfm.base import SQLSampler, Table
|
|
12
|
+
from kumoai.experimental.rfm.pquery import PQueryPandasExecutor
|
|
13
|
+
from kumoai.utils import ProgressLogger, quote_ident
|
|
14
|
+
|
|
15
|
+
if TYPE_CHECKING:
|
|
16
|
+
from kumoai.experimental.rfm import Graph
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class SQLiteSampler(SQLSampler):
|
|
20
|
+
def __init__(
|
|
21
|
+
self,
|
|
22
|
+
graph: 'Graph',
|
|
23
|
+
verbose: bool | ProgressLogger = True,
|
|
24
|
+
optimize: bool = False,
|
|
25
|
+
) -> None:
|
|
26
|
+
super().__init__(graph=graph, verbose=verbose)
|
|
27
|
+
|
|
28
|
+
for table in graph.tables.values():
|
|
29
|
+
assert isinstance(table, SQLiteTable)
|
|
30
|
+
self._connection = table._connection
|
|
31
|
+
|
|
32
|
+
if optimize:
|
|
33
|
+
with self._connection.cursor() as cursor:
|
|
34
|
+
cursor.execute("PRAGMA temp_store = MEMORY")
|
|
35
|
+
cursor.execute("PRAGMA cache_size = -2000000") # 2 GB
|
|
36
|
+
|
|
37
|
+
# Collect database indices for speeding sampling:
|
|
38
|
+
index_dict: dict[str, set[tuple[str, ...]]] = defaultdict(set)
|
|
39
|
+
for table_name, primary_key in self.primary_key_dict.items():
|
|
40
|
+
source_table = self.source_table_dict[table_name]
|
|
41
|
+
if primary_key not in source_table:
|
|
42
|
+
continue # No physical column.
|
|
43
|
+
if source_table[primary_key].is_unique_key:
|
|
44
|
+
continue
|
|
45
|
+
index_dict[table_name].add((primary_key, ))
|
|
46
|
+
for src_table_name, foreign_key, _ in graph.edges:
|
|
47
|
+
source_table = self.source_table_dict[src_table_name]
|
|
48
|
+
if foreign_key not in source_table:
|
|
49
|
+
continue # No physical column.
|
|
50
|
+
if source_table[foreign_key].is_unique_key:
|
|
51
|
+
continue
|
|
52
|
+
time_column = self.time_column_dict.get(src_table_name)
|
|
53
|
+
if time_column is not None and time_column in source_table:
|
|
54
|
+
index_dict[src_table_name].add((foreign_key, time_column))
|
|
55
|
+
else:
|
|
56
|
+
index_dict[src_table_name].add((foreign_key, ))
|
|
57
|
+
|
|
58
|
+
# Only maintain missing indices:
|
|
59
|
+
with self._connection.cursor() as cursor:
|
|
60
|
+
for table_name in list(index_dict.keys()):
|
|
61
|
+
indices = index_dict[table_name]
|
|
62
|
+
source_name = self.source_name_dict[table_name]
|
|
63
|
+
sql = f"PRAGMA index_list({source_name})"
|
|
64
|
+
cursor.execute(sql)
|
|
65
|
+
for _, index_name, *_ in cursor.fetchall():
|
|
66
|
+
sql = f"PRAGMA index_info({quote_ident(index_name)})"
|
|
67
|
+
cursor.execute(sql)
|
|
68
|
+
# Fetch index information and sort by `seqno`:
|
|
69
|
+
index_info = tuple(info[2] for info in sorted(
|
|
70
|
+
cursor.fetchall(), key=lambda x: x[0]))
|
|
71
|
+
# Remove all indices in case primary index already exists:
|
|
72
|
+
for index in list(indices):
|
|
73
|
+
if index_info[0] == index[0]:
|
|
74
|
+
indices.discard(index)
|
|
75
|
+
if len(indices) == 0:
|
|
76
|
+
del index_dict[table_name]
|
|
77
|
+
|
|
78
|
+
if optimize and len(index_dict) > 0:
|
|
79
|
+
if not isinstance(verbose, ProgressLogger):
|
|
80
|
+
verbose = ProgressLogger.default(
|
|
81
|
+
msg="Optimizing SQLite database",
|
|
82
|
+
verbose=verbose,
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
with verbose as logger, self._connection.cursor() as cursor:
|
|
86
|
+
for table_name, indices in index_dict.items():
|
|
87
|
+
for index in indices:
|
|
88
|
+
name = f"kumo_index_{table_name}_{'_'.join(index)}"
|
|
89
|
+
name = quote_ident(name)
|
|
90
|
+
columns = ', '.join(quote_ident(v) for v in index)
|
|
91
|
+
columns += ' DESC' if len(index) > 1 else ''
|
|
92
|
+
source_name = self.source_name_dict[table_name]
|
|
93
|
+
sql = (f"CREATE INDEX IF NOT EXISTS {name}\n"
|
|
94
|
+
f"ON {source_name}({columns})")
|
|
95
|
+
cursor.execute(sql)
|
|
96
|
+
self._connection.commit()
|
|
97
|
+
if len(index) > 1:
|
|
98
|
+
logger.log(f"Created index on {index} in table "
|
|
99
|
+
f"'{table_name}'")
|
|
100
|
+
else:
|
|
101
|
+
logger.log(f"Created index on '{index[0]}' in "
|
|
102
|
+
f"table '{table_name}'")
|
|
103
|
+
|
|
104
|
+
elif len(index_dict) > 0:
|
|
105
|
+
num = sum(len(indices) for indices in index_dict.values())
|
|
106
|
+
index_repr = '1 index' if num == 1 else f'{num} indices'
|
|
107
|
+
num = len(index_dict)
|
|
108
|
+
table_repr = '1 table' if num == 1 else f'{num} tables'
|
|
109
|
+
warnings.warn(f"Missing {index_repr} in {table_repr} for optimal "
|
|
110
|
+
f"database querying. For improving runtime, we "
|
|
111
|
+
f"strongly suggest to create indices for primary "
|
|
112
|
+
f"and foreign keys, e.g., automatically by "
|
|
113
|
+
f"instantiating KumoRFM via "
|
|
114
|
+
f"`KumoRFM(graph, optimize=True)`.")
|
|
115
|
+
|
|
116
|
+
def _get_min_max_time_dict(
|
|
117
|
+
self,
|
|
118
|
+
table_names: list[str],
|
|
119
|
+
) -> dict[str, tuple[pd.Timestamp, pd.Timestamp]]:
|
|
120
|
+
selects: list[str] = []
|
|
121
|
+
for table_name in table_names:
|
|
122
|
+
column = self.time_column_dict[table_name]
|
|
123
|
+
column_ref = self.table_column_ref_dict[table_name][column]
|
|
124
|
+
select = (f"SELECT\n"
|
|
125
|
+
f" ? as table_name,\n"
|
|
126
|
+
f" MIN({column_ref}) as min_date,\n"
|
|
127
|
+
f" MAX({column_ref}) as max_date\n"
|
|
128
|
+
f"FROM {self.source_name_dict[table_name]}")
|
|
129
|
+
selects.append(select)
|
|
130
|
+
sql = "\nUNION ALL\n".join(selects)
|
|
131
|
+
|
|
132
|
+
out_dict: dict[str, tuple[pd.Timestamp, pd.Timestamp]] = {}
|
|
133
|
+
with self._connection.cursor() as cursor:
|
|
134
|
+
cursor.execute(sql, table_names)
|
|
135
|
+
for table_name, _min, _max in cursor.fetchall():
|
|
136
|
+
out_dict[table_name] = (
|
|
137
|
+
pd.Timestamp.max if _min is None else pd.Timestamp(_min),
|
|
138
|
+
pd.Timestamp.min if _max is None else pd.Timestamp(_max),
|
|
139
|
+
)
|
|
140
|
+
return out_dict
|
|
141
|
+
|
|
142
|
+
def _sample_entity_table(
|
|
143
|
+
self,
|
|
144
|
+
table_name: str,
|
|
145
|
+
columns: set[str],
|
|
146
|
+
num_rows: int,
|
|
147
|
+
random_seed: int | None = None,
|
|
148
|
+
) -> pd.DataFrame:
|
|
149
|
+
# NOTE SQLite does not natively support passing a `random_seed`.
|
|
150
|
+
|
|
151
|
+
source_table = self.source_table_dict[table_name]
|
|
152
|
+
filters: list[str] = []
|
|
153
|
+
|
|
154
|
+
key = self.primary_key_dict[table_name]
|
|
155
|
+
if key not in source_table or source_table[key].is_nullable:
|
|
156
|
+
key_ref = self.table_column_ref_dict[table_name][key]
|
|
157
|
+
filters.append(f" {key_ref} IS NOT NULL")
|
|
158
|
+
|
|
159
|
+
column = self.time_column_dict.get(table_name)
|
|
160
|
+
if column is None:
|
|
161
|
+
pass
|
|
162
|
+
elif column not in source_table or source_table[column].is_nullable:
|
|
163
|
+
column_ref = self.table_column_ref_dict[table_name][column]
|
|
164
|
+
filters.append(f" {column_ref} IS NOT NULL")
|
|
165
|
+
|
|
166
|
+
# TODO Make this query more efficient - it does full table scan.
|
|
167
|
+
projections = [
|
|
168
|
+
self.table_column_proj_dict[table_name][column]
|
|
169
|
+
for column in columns
|
|
170
|
+
]
|
|
171
|
+
sql = (f"SELECT {', '.join(projections)}\n"
|
|
172
|
+
f"FROM {self.source_name_dict[table_name]}")
|
|
173
|
+
if len(filters) > 0:
|
|
174
|
+
sql += f"\nWHERE{' AND'.join(filters)}"
|
|
175
|
+
sql += f"\nORDER BY RANDOM() LIMIT {num_rows}"
|
|
176
|
+
|
|
177
|
+
with self._connection.cursor() as cursor:
|
|
178
|
+
# NOTE This may return duplicate primary keys. This is okay.
|
|
179
|
+
cursor.execute(sql)
|
|
180
|
+
table = cursor.fetch_arrow_table()
|
|
181
|
+
|
|
182
|
+
return Table._sanitize(
|
|
183
|
+
df=table.to_pandas(types_mapper=pd.ArrowDtype),
|
|
184
|
+
dtype_dict=self.table_dtype_dict[table_name],
|
|
185
|
+
stype_dict=self.table_stype_dict[table_name],
|
|
186
|
+
)
|
|
187
|
+
|
|
188
|
+
def _sample_target(
|
|
189
|
+
self,
|
|
190
|
+
query: ValidatedPredictiveQuery,
|
|
191
|
+
entity_df: pd.DataFrame,
|
|
192
|
+
train_index: np.ndarray,
|
|
193
|
+
train_time: pd.Series,
|
|
194
|
+
num_train_examples: int,
|
|
195
|
+
test_index: np.ndarray,
|
|
196
|
+
test_time: pd.Series,
|
|
197
|
+
num_test_examples: int,
|
|
198
|
+
columns_dict: dict[str, set[str]],
|
|
199
|
+
time_offset_dict: dict[
|
|
200
|
+
tuple[str, str, str],
|
|
201
|
+
tuple[pd.DateOffset | None, pd.DateOffset],
|
|
202
|
+
],
|
|
203
|
+
) -> tuple[pd.Series, np.ndarray, pd.Series, np.ndarray]:
|
|
204
|
+
train_y, train_mask = self._sample_target_set(
|
|
205
|
+
query=query,
|
|
206
|
+
entity_df=entity_df,
|
|
207
|
+
index=train_index,
|
|
208
|
+
anchor_time=train_time,
|
|
209
|
+
num_examples=num_train_examples,
|
|
210
|
+
columns_dict=columns_dict,
|
|
211
|
+
time_offset_dict=time_offset_dict,
|
|
212
|
+
)
|
|
213
|
+
|
|
214
|
+
test_y, test_mask = self._sample_target_set(
|
|
215
|
+
query=query,
|
|
216
|
+
entity_df=entity_df,
|
|
217
|
+
index=test_index,
|
|
218
|
+
anchor_time=test_time,
|
|
219
|
+
num_examples=num_test_examples,
|
|
220
|
+
columns_dict=columns_dict,
|
|
221
|
+
time_offset_dict=time_offset_dict,
|
|
222
|
+
)
|
|
223
|
+
|
|
224
|
+
return train_y, train_mask, test_y, test_mask
|
|
225
|
+
|
|
226
|
+
def _by_pkey(
|
|
227
|
+
self,
|
|
228
|
+
table_name: str,
|
|
229
|
+
pkey: pd.Series,
|
|
230
|
+
columns: set[str],
|
|
231
|
+
) -> tuple[pd.DataFrame, np.ndarray]:
|
|
232
|
+
source_table = self.source_table_dict[table_name]
|
|
233
|
+
key = self.primary_key_dict[table_name]
|
|
234
|
+
key_ref = self.table_column_ref_dict[table_name][key]
|
|
235
|
+
projections = [
|
|
236
|
+
self.table_column_proj_dict[table_name][column]
|
|
237
|
+
for column in columns
|
|
238
|
+
]
|
|
239
|
+
|
|
240
|
+
tmp = pa.table([pa.array(pkey)], names=['__kumo_id__'])
|
|
241
|
+
tmp_name = f'tmp_{table_name}_{key}_{id(tmp)}'
|
|
242
|
+
|
|
243
|
+
sql = (f"SELECT "
|
|
244
|
+
f"tmp.rowid - 1 as __kumo_batch__, "
|
|
245
|
+
f"{', '.join(projections)}\n"
|
|
246
|
+
f"FROM {quote_ident(tmp_name)} tmp\n"
|
|
247
|
+
f"JOIN {self.source_name_dict[table_name]} ent\n")
|
|
248
|
+
|
|
249
|
+
if key in source_table and source_table[key].is_unique_key:
|
|
250
|
+
sql += (f" ON {key_ref} = tmp.__kumo_id__")
|
|
251
|
+
else:
|
|
252
|
+
sql += (f" ON ent.rowid = (\n"
|
|
253
|
+
f" SELECT rowid\n"
|
|
254
|
+
f" FROM {self.source_name_dict[table_name]}\n"
|
|
255
|
+
f" WHERE {key_ref} == tmp.__kumo_id__\n"
|
|
256
|
+
f" LIMIT 1\n"
|
|
257
|
+
f")")
|
|
258
|
+
|
|
259
|
+
with self._connection.cursor() as cursor:
|
|
260
|
+
cursor.adbc_ingest(tmp_name, tmp, mode='replace')
|
|
261
|
+
cursor.execute(sql)
|
|
262
|
+
table = cursor.fetch_arrow_table()
|
|
263
|
+
|
|
264
|
+
batch = table['__kumo_batch__'].to_numpy()
|
|
265
|
+
batch_index = table.schema.get_field_index('__kumo_batch__')
|
|
266
|
+
table = table.remove_column(batch_index)
|
|
267
|
+
|
|
268
|
+
return Table._sanitize(
|
|
269
|
+
df=table.to_pandas(),
|
|
270
|
+
dtype_dict=self.table_dtype_dict[table_name],
|
|
271
|
+
stype_dict=self.table_stype_dict[table_name],
|
|
272
|
+
), batch
|
|
273
|
+
|
|
274
|
+
# Helper Methods ##########################################################
|
|
275
|
+
|
|
276
|
+
def _by_time(
|
|
277
|
+
self,
|
|
278
|
+
table_name: str,
|
|
279
|
+
fkey: str,
|
|
280
|
+
pkey: pd.Series,
|
|
281
|
+
anchor_time: pd.Series,
|
|
282
|
+
min_offset: pd.DateOffset | None,
|
|
283
|
+
max_offset: pd.DateOffset,
|
|
284
|
+
columns: set[str],
|
|
285
|
+
) -> tuple[pd.DataFrame, np.ndarray]:
|
|
286
|
+
time_column = self.time_column_dict[table_name]
|
|
287
|
+
|
|
288
|
+
# NOTE SQLite does not have a native datetime format. Currently, we
|
|
289
|
+
# assume timestamps are given as `TEXT` in `ISO-8601 UTC`:
|
|
290
|
+
tmp = pa.table([pa.array(pkey)], names=['__kumo_id__'])
|
|
291
|
+
end_time = anchor_time + max_offset
|
|
292
|
+
end_time = end_time.dt.strftime("%Y-%m-%d %H:%M:%S")
|
|
293
|
+
tmp = tmp.append_column('__kumo_end__', pa.array(end_time))
|
|
294
|
+
if min_offset is not None:
|
|
295
|
+
start_time = anchor_time + min_offset
|
|
296
|
+
start_time = start_time.dt.strftime("%Y-%m-%d %H:%M:%S")
|
|
297
|
+
tmp = tmp.append_column('__kumo_start__', pa.array(start_time))
|
|
298
|
+
tmp_name = f'tmp_{table_name}_{fkey}_{id(tmp)}'
|
|
299
|
+
|
|
300
|
+
key_ref = self.table_column_ref_dict[table_name][fkey]
|
|
301
|
+
time_ref = self.table_column_ref_dict[table_name][time_column]
|
|
302
|
+
projections = [
|
|
303
|
+
self.table_column_proj_dict[table_name][column]
|
|
304
|
+
for column in columns
|
|
305
|
+
]
|
|
306
|
+
sql = (f"SELECT "
|
|
307
|
+
f"tmp.rowid - 1 as __kumo_batch__, "
|
|
308
|
+
f"{', '.join(projections)}\n"
|
|
309
|
+
f"FROM {quote_ident(tmp_name)} tmp\n"
|
|
310
|
+
f"JOIN {self.source_name_dict[table_name]} fact\n"
|
|
311
|
+
f" ON {key_ref} = tmp.__kumo_id__\n"
|
|
312
|
+
f" AND {time_ref} <= tmp.__kumo_end__")
|
|
313
|
+
if min_offset is not None:
|
|
314
|
+
sql += f"\n AND {time_ref} > tmp.__kumo_start__"
|
|
315
|
+
|
|
316
|
+
with self._connection.cursor() as cursor:
|
|
317
|
+
cursor.adbc_ingest(tmp_name, tmp, mode='replace')
|
|
318
|
+
cursor.execute(sql)
|
|
319
|
+
table = cursor.fetch_arrow_table()
|
|
320
|
+
|
|
321
|
+
batch = table['__kumo_batch__'].to_numpy()
|
|
322
|
+
batch_index = table.schema.get_field_index('__kumo_batch__')
|
|
323
|
+
table = table.remove_column(batch_index)
|
|
324
|
+
|
|
325
|
+
return Table._sanitize(
|
|
326
|
+
df=table.to_pandas(types_mapper=pd.ArrowDtype),
|
|
327
|
+
dtype_dict=self.table_dtype_dict[table_name],
|
|
328
|
+
stype_dict=self.table_stype_dict[table_name],
|
|
329
|
+
), batch
|
|
330
|
+
|
|
331
|
+
def _sample_target_set(
|
|
332
|
+
self,
|
|
333
|
+
query: ValidatedPredictiveQuery,
|
|
334
|
+
entity_df: pd.DataFrame,
|
|
335
|
+
index: np.ndarray,
|
|
336
|
+
anchor_time: pd.Series,
|
|
337
|
+
num_examples: int,
|
|
338
|
+
columns_dict: dict[str, set[str]],
|
|
339
|
+
time_offset_dict: dict[
|
|
340
|
+
tuple[str, str, str],
|
|
341
|
+
tuple[pd.DateOffset | None, pd.DateOffset],
|
|
342
|
+
],
|
|
343
|
+
batch_size: int = 10_000,
|
|
344
|
+
) -> tuple[pd.Series, np.ndarray]:
|
|
345
|
+
|
|
346
|
+
count = 0
|
|
347
|
+
ys: list[pd.Series] = []
|
|
348
|
+
mask = np.full(len(index), False, dtype=bool)
|
|
349
|
+
for start in range(0, len(index), batch_size):
|
|
350
|
+
df = entity_df.iloc[index[start:start + batch_size]]
|
|
351
|
+
time = anchor_time.iloc[start:start + batch_size]
|
|
352
|
+
|
|
353
|
+
feat_dict: dict[str, pd.DataFrame] = {query.entity_table: df}
|
|
354
|
+
time_dict: dict[str, pd.Series] = {}
|
|
355
|
+
time_column = self.time_column_dict.get(query.entity_table)
|
|
356
|
+
if time_column in columns_dict[query.entity_table]:
|
|
357
|
+
time_dict[query.entity_table] = df[time_column]
|
|
358
|
+
batch_dict: dict[str, np.ndarray] = {
|
|
359
|
+
query.entity_table: np.arange(len(df)),
|
|
360
|
+
}
|
|
361
|
+
for edge_type, (_min, _max) in time_offset_dict.items():
|
|
362
|
+
table_name, fkey, _ = edge_type
|
|
363
|
+
feat_dict[table_name], batch_dict[table_name] = self._by_time(
|
|
364
|
+
table_name=table_name,
|
|
365
|
+
fkey=fkey,
|
|
366
|
+
pkey=df[self.primary_key_dict[query.entity_table]],
|
|
367
|
+
anchor_time=time,
|
|
368
|
+
min_offset=_min,
|
|
369
|
+
max_offset=_max,
|
|
370
|
+
columns=columns_dict[table_name],
|
|
371
|
+
)
|
|
372
|
+
time_column = self.time_column_dict.get(table_name)
|
|
373
|
+
if time_column in columns_dict[table_name]:
|
|
374
|
+
time_dict[table_name] = feat_dict[table_name][time_column]
|
|
375
|
+
|
|
376
|
+
y, _mask = PQueryPandasExecutor().execute(
|
|
377
|
+
query=query,
|
|
378
|
+
feat_dict=feat_dict,
|
|
379
|
+
time_dict=time_dict,
|
|
380
|
+
batch_dict=batch_dict,
|
|
381
|
+
anchor_time=anchor_time,
|
|
382
|
+
num_forecasts=query.num_forecasts,
|
|
383
|
+
)
|
|
384
|
+
ys.append(y)
|
|
385
|
+
mask[start:start + batch_size] = _mask
|
|
386
|
+
|
|
387
|
+
count += len(y)
|
|
388
|
+
if count >= num_examples:
|
|
389
|
+
break
|
|
390
|
+
|
|
391
|
+
if len(ys) == 0:
|
|
392
|
+
y = pd.Series([], dtype=float)
|
|
393
|
+
elif len(ys) == 1:
|
|
394
|
+
y = ys[0]
|
|
395
|
+
else:
|
|
396
|
+
y = pd.concat(ys, axis=0, ignore_index=True)
|
|
397
|
+
|
|
398
|
+
return y, mask
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import re
|
|
2
|
+
from collections import Counter
|
|
3
|
+
from collections.abc import Sequence
|
|
4
|
+
from typing import cast
|
|
5
|
+
|
|
6
|
+
import pandas as pd
|
|
7
|
+
from kumoapi.model_plan import MissingType
|
|
8
|
+
from kumoapi.typing import Dtype
|
|
9
|
+
|
|
10
|
+
from kumoai.experimental.rfm.backend.sqlite import Connection
|
|
11
|
+
from kumoai.experimental.rfm.base import (
|
|
12
|
+
ColumnSpec,
|
|
13
|
+
ColumnSpecType,
|
|
14
|
+
DataBackend,
|
|
15
|
+
SourceColumn,
|
|
16
|
+
SourceForeignKey,
|
|
17
|
+
Table,
|
|
18
|
+
)
|
|
19
|
+
from kumoai.utils import quote_ident
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class SQLiteTable(Table):
|
|
23
|
+
r"""A table backed by a :class:`sqlite` database.
|
|
24
|
+
|
|
25
|
+
Args:
|
|
26
|
+
connection: The connection to a :class:`sqlite` database.
|
|
27
|
+
name: The name of this table.
|
|
28
|
+
source_name: The source name of this table. If set to ``None``,
|
|
29
|
+
``name`` is being used.
|
|
30
|
+
columns: The selected columns of this table.
|
|
31
|
+
primary_key: The name of the primary key of this table, if it exists.
|
|
32
|
+
time_column: The name of the time column of this table, if it exists.
|
|
33
|
+
end_time_column: The name of the end time column of this table, if it
|
|
34
|
+
exists.
|
|
35
|
+
"""
|
|
36
|
+
def __init__(
|
|
37
|
+
self,
|
|
38
|
+
connection: Connection,
|
|
39
|
+
name: str,
|
|
40
|
+
source_name: str | None = None,
|
|
41
|
+
columns: Sequence[ColumnSpecType] | None = None,
|
|
42
|
+
primary_key: MissingType | str | None = MissingType.VALUE,
|
|
43
|
+
time_column: str | None = None,
|
|
44
|
+
end_time_column: str | None = None,
|
|
45
|
+
) -> None:
|
|
46
|
+
|
|
47
|
+
self._connection = connection
|
|
48
|
+
|
|
49
|
+
super().__init__(
|
|
50
|
+
name=name,
|
|
51
|
+
source_name=source_name,
|
|
52
|
+
columns=columns,
|
|
53
|
+
primary_key=primary_key,
|
|
54
|
+
time_column=time_column,
|
|
55
|
+
end_time_column=end_time_column,
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
@property
|
|
59
|
+
def backend(self) -> DataBackend:
|
|
60
|
+
return cast(DataBackend, DataBackend.SQLITE)
|
|
61
|
+
|
|
62
|
+
def _get_source_columns(self) -> list[SourceColumn]:
|
|
63
|
+
source_columns: list[SourceColumn] = []
|
|
64
|
+
with self._connection.cursor() as cursor:
|
|
65
|
+
sql = f"PRAGMA table_info({self._quoted_source_name})"
|
|
66
|
+
cursor.execute(sql)
|
|
67
|
+
columns = cursor.fetchall()
|
|
68
|
+
|
|
69
|
+
if len(columns) == 0:
|
|
70
|
+
raise ValueError(f"Table '{self.source_name}' does not exist "
|
|
71
|
+
f"in the SQLite database")
|
|
72
|
+
|
|
73
|
+
unique_keys: set[str] = set()
|
|
74
|
+
sql = f"PRAGMA index_list({self._quoted_source_name})"
|
|
75
|
+
cursor.execute(sql)
|
|
76
|
+
for _, index_name, is_unique, *_ in cursor.fetchall():
|
|
77
|
+
if bool(is_unique):
|
|
78
|
+
sql = f"PRAGMA index_info({quote_ident(index_name)})"
|
|
79
|
+
cursor.execute(sql)
|
|
80
|
+
index = cursor.fetchall()
|
|
81
|
+
if len(index) == 1:
|
|
82
|
+
unique_keys.add(index[0][2])
|
|
83
|
+
|
|
84
|
+
# Special SQLite case that creates a rowid alias for
|
|
85
|
+
# `INTEGER PRIMARY KEY` annotated columns:
|
|
86
|
+
rowid_candidates = [
|
|
87
|
+
column for _, column, dtype, _, _, is_pkey in columns
|
|
88
|
+
if bool(is_pkey) and dtype.strip().upper() == 'INTEGER'
|
|
89
|
+
]
|
|
90
|
+
if len(rowid_candidates) == 1:
|
|
91
|
+
unique_keys.add(rowid_candidates[0])
|
|
92
|
+
|
|
93
|
+
for _, column, dtype, notnull, _, is_pkey in columns:
|
|
94
|
+
source_column = SourceColumn(
|
|
95
|
+
name=column,
|
|
96
|
+
dtype=self._to_dtype(dtype),
|
|
97
|
+
is_primary_key=bool(is_pkey),
|
|
98
|
+
is_unique_key=column in unique_keys,
|
|
99
|
+
is_nullable=not bool(is_pkey) and not bool(notnull),
|
|
100
|
+
)
|
|
101
|
+
source_columns.append(source_column)
|
|
102
|
+
|
|
103
|
+
return source_columns
|
|
104
|
+
|
|
105
|
+
def _get_source_foreign_keys(self) -> list[SourceForeignKey]:
|
|
106
|
+
source_foreign_keys: list[SourceForeignKey] = []
|
|
107
|
+
with self._connection.cursor() as cursor:
|
|
108
|
+
sql = f"PRAGMA foreign_key_list({self._quoted_source_name})"
|
|
109
|
+
cursor.execute(sql)
|
|
110
|
+
rows = cursor.fetchall()
|
|
111
|
+
counts = Counter(row[0] for row in rows)
|
|
112
|
+
for idx, _, dst_table, foreign_key, primary_key, *_ in rows:
|
|
113
|
+
if counts[idx] == 1:
|
|
114
|
+
source_foreign_key = SourceForeignKey(
|
|
115
|
+
name=foreign_key,
|
|
116
|
+
dst_table=dst_table,
|
|
117
|
+
primary_key=primary_key,
|
|
118
|
+
)
|
|
119
|
+
source_foreign_keys.append(source_foreign_key)
|
|
120
|
+
return source_foreign_keys
|
|
121
|
+
|
|
122
|
+
def _get_source_sample_df(self) -> pd.DataFrame:
|
|
123
|
+
with self._connection.cursor() as cursor:
|
|
124
|
+
columns = [quote_ident(col) for col in self._source_column_dict]
|
|
125
|
+
sql = (f"SELECT {', '.join(columns)} "
|
|
126
|
+
f"FROM {self._quoted_source_name} "
|
|
127
|
+
f"ORDER BY rowid "
|
|
128
|
+
f"LIMIT {self._NUM_SAMPLE_ROWS}")
|
|
129
|
+
cursor.execute(sql)
|
|
130
|
+
table = cursor.fetch_arrow_table()
|
|
131
|
+
|
|
132
|
+
if len(table) == 0:
|
|
133
|
+
raise RuntimeError(f"Table '{self.source_name}' is empty")
|
|
134
|
+
|
|
135
|
+
return self._sanitize(
|
|
136
|
+
df=table.to_pandas(types_mapper=pd.ArrowDtype),
|
|
137
|
+
dtype_dict={
|
|
138
|
+
column.name: column.dtype
|
|
139
|
+
for column in self._source_column_dict.values()
|
|
140
|
+
},
|
|
141
|
+
stype_dict=None,
|
|
142
|
+
)
|
|
143
|
+
|
|
144
|
+
def _get_num_rows(self) -> int | None:
|
|
145
|
+
return None
|
|
146
|
+
|
|
147
|
+
def _get_expr_sample_df(
|
|
148
|
+
self,
|
|
149
|
+
columns: Sequence[ColumnSpec],
|
|
150
|
+
) -> pd.DataFrame:
|
|
151
|
+
with self._connection.cursor() as cursor:
|
|
152
|
+
projections = [
|
|
153
|
+
f"{column.expr} AS {quote_ident(column.name)}"
|
|
154
|
+
for column in columns
|
|
155
|
+
]
|
|
156
|
+
sql = (f"SELECT {', '.join(projections)} "
|
|
157
|
+
f"FROM {self._quoted_source_name} "
|
|
158
|
+
f"ORDER BY rowid "
|
|
159
|
+
f"LIMIT {self._NUM_SAMPLE_ROWS}")
|
|
160
|
+
cursor.execute(sql)
|
|
161
|
+
table = cursor.fetch_arrow_table()
|
|
162
|
+
|
|
163
|
+
if len(table) == 0:
|
|
164
|
+
raise RuntimeError(f"Table '{self.source_name}' is empty")
|
|
165
|
+
|
|
166
|
+
return self._sanitize(
|
|
167
|
+
df=table.to_pandas(types_mapper=pd.ArrowDtype),
|
|
168
|
+
dtype_dict={column.name: column.dtype
|
|
169
|
+
for column in columns},
|
|
170
|
+
stype_dict=None,
|
|
171
|
+
)
|
|
172
|
+
|
|
173
|
+
@staticmethod
|
|
174
|
+
def _to_dtype(dtype: str | None) -> Dtype | None:
|
|
175
|
+
if dtype is None:
|
|
176
|
+
return None
|
|
177
|
+
dtype = dtype.strip().upper()
|
|
178
|
+
if re.search('INT', dtype):
|
|
179
|
+
return Dtype.int
|
|
180
|
+
if re.search('TEXT|CHAR|CLOB', dtype):
|
|
181
|
+
return Dtype.string
|
|
182
|
+
if re.search('REAL|FLOA|DOUB', dtype):
|
|
183
|
+
return Dtype.float
|
|
184
|
+
return None # NUMERIC affinity.
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
from kumoapi.common import StrEnum
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class DataBackend(StrEnum):
|
|
5
|
+
LOCAL = 'local'
|
|
6
|
+
SQLITE = 'sqlite'
|
|
7
|
+
SNOWFLAKE = 'snowflake'
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
from .source import SourceColumn, SourceForeignKey # noqa: E402
|
|
11
|
+
from .expression import Expression, LocalExpression # noqa: E402
|
|
12
|
+
from .column import ColumnSpec, ColumnSpecType, Column # noqa: E402
|
|
13
|
+
from .table import Table # noqa: E402
|
|
14
|
+
from .sampler import SamplerOutput, Sampler # noqa: E402
|
|
15
|
+
from .sql_sampler import SQLSampler # noqa: E402
|
|
16
|
+
|
|
17
|
+
__all__ = [
|
|
18
|
+
'DataBackend',
|
|
19
|
+
'SourceColumn',
|
|
20
|
+
'SourceForeignKey',
|
|
21
|
+
'Expression',
|
|
22
|
+
'LocalExpression',
|
|
23
|
+
'ColumnSpec',
|
|
24
|
+
'ColumnSpecType',
|
|
25
|
+
'Column',
|
|
26
|
+
'Table',
|
|
27
|
+
'SamplerOutput',
|
|
28
|
+
'Sampler',
|
|
29
|
+
'SQLSampler',
|
|
30
|
+
]
|