kumoai 2.13.0.dev202512081731__cp313-cp313-macosx_11_0_arm64.whl → 2.14.0.dev202512211732__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/_version.py +1 -1
- kumoai/client/pquery.py +6 -2
- kumoai/experimental/rfm/__init__.py +33 -8
- kumoai/experimental/rfm/authenticate.py +3 -4
- kumoai/experimental/rfm/backend/local/graph_store.py +40 -83
- kumoai/experimental/rfm/backend/local/sampler.py +213 -14
- kumoai/experimental/rfm/backend/local/table.py +21 -16
- kumoai/experimental/rfm/backend/snow/__init__.py +2 -0
- kumoai/experimental/rfm/backend/snow/sampler.py +252 -0
- kumoai/experimental/rfm/backend/snow/table.py +101 -49
- kumoai/experimental/rfm/backend/sqlite/__init__.py +4 -2
- kumoai/experimental/rfm/backend/sqlite/sampler.py +349 -0
- kumoai/experimental/rfm/backend/sqlite/table.py +84 -31
- kumoai/experimental/rfm/base/__init__.py +25 -6
- kumoai/experimental/rfm/base/column.py +14 -12
- kumoai/experimental/rfm/base/column_expression.py +50 -0
- kumoai/experimental/rfm/base/sampler.py +438 -38
- kumoai/experimental/rfm/base/source.py +1 -0
- kumoai/experimental/rfm/base/sql_sampler.py +84 -0
- kumoai/experimental/rfm/base/sql_table.py +229 -0
- kumoai/experimental/rfm/base/table.py +165 -135
- kumoai/experimental/rfm/graph.py +266 -102
- kumoai/experimental/rfm/infer/__init__.py +6 -4
- kumoai/experimental/rfm/infer/dtype.py +3 -3
- kumoai/experimental/rfm/infer/pkey.py +4 -2
- kumoai/experimental/rfm/infer/stype.py +35 -0
- kumoai/experimental/rfm/infer/time_col.py +1 -2
- kumoai/experimental/rfm/pquery/executor.py +27 -27
- kumoai/experimental/rfm/pquery/pandas_executor.py +30 -32
- kumoai/experimental/rfm/rfm.py +299 -230
- kumoai/experimental/rfm/sagemaker.py +4 -4
- kumoai/pquery/predictive_query.py +10 -6
- kumoai/testing/snow.py +50 -0
- kumoai/utils/__init__.py +3 -2
- kumoai/utils/progress_logger.py +178 -12
- kumoai/utils/sql.py +3 -0
- {kumoai-2.13.0.dev202512081731.dist-info → kumoai-2.14.0.dev202512211732.dist-info}/METADATA +3 -2
- {kumoai-2.13.0.dev202512081731.dist-info → kumoai-2.14.0.dev202512211732.dist-info}/RECORD +41 -35
- kumoai/experimental/rfm/local_graph_sampler.py +0 -223
- kumoai/experimental/rfm/local_pquery_driver.py +0 -689
- {kumoai-2.13.0.dev202512081731.dist-info → kumoai-2.14.0.dev202512211732.dist-info}/WHEEL +0 -0
- {kumoai-2.13.0.dev202512081731.dist-info → kumoai-2.14.0.dev202512211732.dist-info}/licenses/LICENSE +0 -0
- {kumoai-2.13.0.dev202512081731.dist-info → kumoai-2.14.0.dev202512211732.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
from abc import abstractmethod
|
|
2
|
+
from typing import TYPE_CHECKING, Literal
|
|
3
|
+
|
|
4
|
+
import numpy as np
|
|
5
|
+
import pandas as pd
|
|
6
|
+
|
|
7
|
+
from kumoai.experimental.rfm.base import Sampler, SamplerOutput, SQLTable
|
|
8
|
+
from kumoai.utils import ProgressLogger
|
|
9
|
+
|
|
10
|
+
if TYPE_CHECKING:
|
|
11
|
+
from kumoai.experimental.rfm import Graph
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class SQLSampler(Sampler):
|
|
15
|
+
def __init__(
|
|
16
|
+
self,
|
|
17
|
+
graph: 'Graph',
|
|
18
|
+
verbose: bool | ProgressLogger = True,
|
|
19
|
+
) -> None:
|
|
20
|
+
super().__init__(graph=graph, verbose=verbose)
|
|
21
|
+
|
|
22
|
+
self._fqn_dict: dict[str, str] = {}
|
|
23
|
+
for table in graph.tables.values():
|
|
24
|
+
assert isinstance(table, SQLTable)
|
|
25
|
+
self._connection = table._connection
|
|
26
|
+
self._fqn_dict[table.name] = table.fqn
|
|
27
|
+
|
|
28
|
+
@property
|
|
29
|
+
def fqn_dict(self) -> dict[str, str]:
|
|
30
|
+
r"""The fully-qualified quoted source name for all table names in the
|
|
31
|
+
graph.
|
|
32
|
+
"""
|
|
33
|
+
return self._fqn_dict
|
|
34
|
+
|
|
35
|
+
def _sample_subgraph(
|
|
36
|
+
self,
|
|
37
|
+
entity_table_name: str,
|
|
38
|
+
entity_pkey: pd.Series,
|
|
39
|
+
anchor_time: pd.Series | Literal['entity'],
|
|
40
|
+
columns_dict: dict[str, set[str]],
|
|
41
|
+
num_neighbors: list[int],
|
|
42
|
+
) -> SamplerOutput:
|
|
43
|
+
|
|
44
|
+
df, batch = self._by_pkey(
|
|
45
|
+
table_name=entity_table_name,
|
|
46
|
+
pkey=entity_pkey,
|
|
47
|
+
columns=columns_dict[entity_table_name],
|
|
48
|
+
)
|
|
49
|
+
if len(batch) != len(entity_pkey):
|
|
50
|
+
mask = np.ones(len(entity_pkey), dtype=bool)
|
|
51
|
+
mask[batch] = False
|
|
52
|
+
raise KeyError(f"The primary keys "
|
|
53
|
+
f"{entity_pkey.iloc[mask].tolist()} do not exist "
|
|
54
|
+
f"in the '{entity_table_name}' table")
|
|
55
|
+
|
|
56
|
+
perm = batch.argsort()
|
|
57
|
+
batch = batch[perm]
|
|
58
|
+
df = df.iloc[perm].reset_index(drop=True)
|
|
59
|
+
|
|
60
|
+
if not isinstance(anchor_time, pd.Series):
|
|
61
|
+
time_column = self.time_column_dict[entity_table_name]
|
|
62
|
+
anchor_time = df[time_column]
|
|
63
|
+
|
|
64
|
+
return SamplerOutput(
|
|
65
|
+
anchor_time=anchor_time.astype(int).to_numpy(),
|
|
66
|
+
df_dict={entity_table_name: df},
|
|
67
|
+
inverse_dict={},
|
|
68
|
+
batch_dict={entity_table_name: batch},
|
|
69
|
+
num_sampled_nodes_dict={entity_table_name: [len(batch)]},
|
|
70
|
+
row_dict={},
|
|
71
|
+
col_dict={},
|
|
72
|
+
num_sampled_edges_dict={},
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
# Abstract Methods ########################################################
|
|
76
|
+
|
|
77
|
+
@abstractmethod
|
|
78
|
+
def _by_pkey(
|
|
79
|
+
self,
|
|
80
|
+
table_name: str,
|
|
81
|
+
pkey: pd.Series,
|
|
82
|
+
columns: set[str],
|
|
83
|
+
) -> tuple[pd.DataFrame, np.ndarray]:
|
|
84
|
+
pass
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
import warnings
|
|
2
|
+
from abc import abstractmethod
|
|
3
|
+
from collections import defaultdict
|
|
4
|
+
from collections.abc import Sequence
|
|
5
|
+
from functools import cached_property
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import pandas as pd
|
|
9
|
+
from kumoapi.model_plan import MissingType
|
|
10
|
+
|
|
11
|
+
from kumoai.experimental.rfm.base import (
|
|
12
|
+
ColumnExpression,
|
|
13
|
+
ColumnExpressionSpec,
|
|
14
|
+
ColumnExpressionType,
|
|
15
|
+
SourceForeignKey,
|
|
16
|
+
Table,
|
|
17
|
+
)
|
|
18
|
+
from kumoai.experimental.rfm.infer import infer_dtype, infer_stype
|
|
19
|
+
from kumoai.utils import quote_ident
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class SQLTable(Table):
|
|
23
|
+
r"""A :class:`SQLTable` specifies a :class:`Table` backed by a SQL
|
|
24
|
+
database.
|
|
25
|
+
|
|
26
|
+
Args:
|
|
27
|
+
name: The logical name of this table.
|
|
28
|
+
source_name: The physical name of this table in the database. If set to
|
|
29
|
+
``None``, ``name`` is being used.
|
|
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
|
+
name: str,
|
|
40
|
+
source_name: str | None = None,
|
|
41
|
+
columns: Sequence[str] | None = None,
|
|
42
|
+
column_expressions: Sequence[ColumnExpressionType] | None = None,
|
|
43
|
+
primary_key: MissingType | str | None = MissingType.VALUE,
|
|
44
|
+
time_column: str | None = None,
|
|
45
|
+
end_time_column: str | None = None,
|
|
46
|
+
) -> None:
|
|
47
|
+
|
|
48
|
+
self._connection: Any
|
|
49
|
+
self._source_name = source_name or name
|
|
50
|
+
self._expression_sample_df = pd.DataFrame()
|
|
51
|
+
|
|
52
|
+
super().__init__(
|
|
53
|
+
name=name,
|
|
54
|
+
columns=[],
|
|
55
|
+
primary_key=None,
|
|
56
|
+
time_column=None,
|
|
57
|
+
end_time_column=None,
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
# Add column expressions with highest priority:
|
|
61
|
+
self.add_column_expressions(column_expressions or [])
|
|
62
|
+
|
|
63
|
+
if columns is None:
|
|
64
|
+
for column_name in self._source_column_dict.keys():
|
|
65
|
+
if column_name not in self:
|
|
66
|
+
self.add_column(column_name)
|
|
67
|
+
else:
|
|
68
|
+
for column_name in columns:
|
|
69
|
+
self.add_column(column_name)
|
|
70
|
+
|
|
71
|
+
if isinstance(primary_key, MissingType):
|
|
72
|
+
# Inference from source column metadata:
|
|
73
|
+
if '_source_column_dict' in self.__dict__:
|
|
74
|
+
primary_key = self._source_primary_key
|
|
75
|
+
if (primary_key is not None and primary_key in self
|
|
76
|
+
and self[primary_key].is_physical):
|
|
77
|
+
self.primary_key = primary_key
|
|
78
|
+
elif primary_key is not None:
|
|
79
|
+
if primary_key not in self:
|
|
80
|
+
self.add_column(primary_key)
|
|
81
|
+
self.primary_key = primary_key
|
|
82
|
+
|
|
83
|
+
if time_column is not None:
|
|
84
|
+
if time_column not in self:
|
|
85
|
+
self.add_column(time_column)
|
|
86
|
+
self.time_column = time_column
|
|
87
|
+
|
|
88
|
+
if end_time_column is not None:
|
|
89
|
+
if end_time_column not in self:
|
|
90
|
+
self.add_column(end_time_column)
|
|
91
|
+
self.end_time_column = end_time_column
|
|
92
|
+
|
|
93
|
+
@property
|
|
94
|
+
def fqn(self) -> str:
|
|
95
|
+
r"""The fully-qualified quoted source table name."""
|
|
96
|
+
return quote_ident(self._source_name)
|
|
97
|
+
|
|
98
|
+
@cached_property
|
|
99
|
+
def _source_foreign_key_dict(self) -> dict[str, SourceForeignKey]:
|
|
100
|
+
fkeys = self._get_source_foreign_keys()
|
|
101
|
+
# NOTE Drop all keys that link to multiple keys in the same table since
|
|
102
|
+
# we don't support composite keys yet:
|
|
103
|
+
table_pkeys: dict[str, set[str]] = defaultdict(set)
|
|
104
|
+
for fkey in fkeys:
|
|
105
|
+
table_pkeys[fkey.dst_table].add(fkey.primary_key)
|
|
106
|
+
return {
|
|
107
|
+
fkey.name: fkey
|
|
108
|
+
for fkey in fkeys if len(table_pkeys[fkey.dst_table]) == 1
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
def _sample_current_df(self, columns: Sequence[str]) -> pd.DataFrame:
|
|
112
|
+
expr_columns: list[str] = []
|
|
113
|
+
source_columns: list[str] = []
|
|
114
|
+
for column_name in columns:
|
|
115
|
+
column = self[column_name]
|
|
116
|
+
if isinstance(column, ColumnExpression):
|
|
117
|
+
expr_columns.append(column_name)
|
|
118
|
+
else:
|
|
119
|
+
source_columns.append(column_name)
|
|
120
|
+
|
|
121
|
+
dfs: list[pd.DataFrame] = []
|
|
122
|
+
if len(expr_columns) > 0:
|
|
123
|
+
dfs.append(self._expression_sample_df[expr_columns])
|
|
124
|
+
if len(source_columns) > 0:
|
|
125
|
+
dfs.append(self._source_sample_df[source_columns])
|
|
126
|
+
|
|
127
|
+
if len(dfs) == 0:
|
|
128
|
+
return pd.DataFrame(index=range(1000))
|
|
129
|
+
if len(dfs) == 1:
|
|
130
|
+
return dfs[0]
|
|
131
|
+
return pd.concat(dfs, axis=1, ignore_index=True)
|
|
132
|
+
|
|
133
|
+
# Column ##################################################################
|
|
134
|
+
|
|
135
|
+
def add_column_expressions(
|
|
136
|
+
self,
|
|
137
|
+
columns: Sequence[ColumnExpressionType],
|
|
138
|
+
) -> None:
|
|
139
|
+
r"""Adds a set of column expressions to this table.
|
|
140
|
+
|
|
141
|
+
Args:
|
|
142
|
+
columns: The set of column expressions.
|
|
143
|
+
|
|
144
|
+
Raises:
|
|
145
|
+
KeyError: If a column with the same name already exists in the
|
|
146
|
+
table.
|
|
147
|
+
"""
|
|
148
|
+
if len(columns) == 0:
|
|
149
|
+
return
|
|
150
|
+
|
|
151
|
+
column_expression_specs = [
|
|
152
|
+
spec for column in columns
|
|
153
|
+
if (spec := ColumnExpressionSpec._cast(column))
|
|
154
|
+
]
|
|
155
|
+
df = self._get_expression_sample_df(column_expression_specs)
|
|
156
|
+
|
|
157
|
+
for spec in column_expression_specs:
|
|
158
|
+
if spec.name in self:
|
|
159
|
+
raise KeyError(f"Column '{spec.name}' already exists in table "
|
|
160
|
+
f"'{self.name}'")
|
|
161
|
+
|
|
162
|
+
dtype = spec.dtype
|
|
163
|
+
if dtype is None:
|
|
164
|
+
ser = df[spec.name]
|
|
165
|
+
try:
|
|
166
|
+
dtype = infer_dtype(ser)
|
|
167
|
+
except Exception:
|
|
168
|
+
warnings.warn(f"Encountered unsupported data type "
|
|
169
|
+
f"'{ser.dtype}' for column expression "
|
|
170
|
+
f"'{spec.name}' in table '{self.name}'."
|
|
171
|
+
f"Please manually specify the data type for "
|
|
172
|
+
f"this column expression to use it within "
|
|
173
|
+
f"this table, or remove it to suppress "
|
|
174
|
+
f"this warning.")
|
|
175
|
+
continue
|
|
176
|
+
|
|
177
|
+
ser = df[spec.name]
|
|
178
|
+
try:
|
|
179
|
+
stype = infer_stype(ser, spec.name, dtype)
|
|
180
|
+
except Exception as e:
|
|
181
|
+
raise RuntimeError(f"Could not obtain semantic type for "
|
|
182
|
+
f"column expression '{spec.name}' with "
|
|
183
|
+
f"data type '{dtype}' in table "
|
|
184
|
+
f"'{self.name}'. Change the data type of "
|
|
185
|
+
f"the column expression or remove it from "
|
|
186
|
+
f"this table.") from e
|
|
187
|
+
|
|
188
|
+
self._columns[spec.name] = ColumnExpression(
|
|
189
|
+
name=spec.name,
|
|
190
|
+
expr=spec.expr,
|
|
191
|
+
stype=stype,
|
|
192
|
+
dtype=dtype,
|
|
193
|
+
)
|
|
194
|
+
with warnings.catch_warnings():
|
|
195
|
+
warnings.simplefilter('ignore', pd.errors.PerformanceWarning)
|
|
196
|
+
self._expression_sample_df[spec.name] = ser
|
|
197
|
+
|
|
198
|
+
def add_column_expression(
|
|
199
|
+
self,
|
|
200
|
+
column: ColumnExpressionType,
|
|
201
|
+
) -> ColumnExpression:
|
|
202
|
+
r"""Adds a column expression to this table.
|
|
203
|
+
|
|
204
|
+
Args:
|
|
205
|
+
column: The column expression.
|
|
206
|
+
|
|
207
|
+
Raises:
|
|
208
|
+
KeyError: If a column with the same name already exists in the
|
|
209
|
+
table.
|
|
210
|
+
"""
|
|
211
|
+
spec = ColumnExpressionSpec._cast(column)
|
|
212
|
+
assert spec is not None
|
|
213
|
+
self.add_column_expressions([spec])
|
|
214
|
+
column_expression = self.column(spec.name)
|
|
215
|
+
assert isinstance(column_expression, ColumnExpression)
|
|
216
|
+
return column_expression
|
|
217
|
+
|
|
218
|
+
# Abstract Methods ########################################################
|
|
219
|
+
|
|
220
|
+
@abstractmethod
|
|
221
|
+
def _get_source_foreign_keys(self) -> list[SourceForeignKey]:
|
|
222
|
+
pass
|
|
223
|
+
|
|
224
|
+
@abstractmethod
|
|
225
|
+
def _get_expression_sample_df(
|
|
226
|
+
self,
|
|
227
|
+
specs: Sequence[ColumnExpressionSpec],
|
|
228
|
+
) -> pd.DataFrame:
|
|
229
|
+
pass
|