kumoai 2.13.0.dev202512040649__cp313-cp313-win_amd64.whl → 2.14.0.dev202601081732__cp313-cp313-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.
Files changed (54) hide show
  1. kumoai/__init__.py +35 -26
  2. kumoai/_version.py +1 -1
  3. kumoai/client/client.py +6 -0
  4. kumoai/client/jobs.py +26 -0
  5. kumoai/client/pquery.py +6 -2
  6. kumoai/connector/utils.py +21 -7
  7. kumoai/experimental/rfm/__init__.py +51 -24
  8. kumoai/experimental/rfm/authenticate.py +3 -4
  9. kumoai/experimental/rfm/backend/local/__init__.py +4 -0
  10. kumoai/experimental/rfm/{local_graph_store.py → backend/local/graph_store.py} +62 -110
  11. kumoai/experimental/rfm/backend/local/sampler.py +312 -0
  12. kumoai/experimental/rfm/backend/local/table.py +35 -31
  13. kumoai/experimental/rfm/backend/snow/__init__.py +2 -0
  14. kumoai/experimental/rfm/backend/snow/sampler.py +366 -0
  15. kumoai/experimental/rfm/backend/snow/table.py +177 -50
  16. kumoai/experimental/rfm/backend/sqlite/__init__.py +4 -2
  17. kumoai/experimental/rfm/backend/sqlite/sampler.py +454 -0
  18. kumoai/experimental/rfm/backend/sqlite/table.py +131 -48
  19. kumoai/experimental/rfm/base/__init__.py +23 -3
  20. kumoai/experimental/rfm/base/column.py +96 -10
  21. kumoai/experimental/rfm/base/expression.py +44 -0
  22. kumoai/experimental/rfm/base/sampler.py +782 -0
  23. kumoai/experimental/rfm/base/source.py +2 -1
  24. kumoai/experimental/rfm/base/sql_sampler.py +247 -0
  25. kumoai/experimental/rfm/base/table.py +404 -203
  26. kumoai/experimental/rfm/graph.py +374 -172
  27. kumoai/experimental/rfm/infer/__init__.py +6 -4
  28. kumoai/experimental/rfm/infer/dtype.py +7 -4
  29. kumoai/experimental/rfm/infer/multicategorical.py +1 -1
  30. kumoai/experimental/rfm/infer/pkey.py +4 -2
  31. kumoai/experimental/rfm/infer/stype.py +35 -0
  32. kumoai/experimental/rfm/infer/time_col.py +1 -2
  33. kumoai/experimental/rfm/pquery/executor.py +27 -27
  34. kumoai/experimental/rfm/pquery/pandas_executor.py +30 -32
  35. kumoai/experimental/rfm/relbench.py +76 -0
  36. kumoai/experimental/rfm/rfm.py +762 -467
  37. kumoai/experimental/rfm/sagemaker.py +4 -4
  38. kumoai/experimental/rfm/task_table.py +292 -0
  39. kumoai/kumolib.cp313-win_amd64.pyd +0 -0
  40. kumoai/pquery/predictive_query.py +10 -6
  41. kumoai/pquery/training_table.py +16 -2
  42. kumoai/testing/snow.py +50 -0
  43. kumoai/trainer/distilled_trainer.py +175 -0
  44. kumoai/utils/__init__.py +3 -2
  45. kumoai/utils/display.py +87 -0
  46. kumoai/utils/progress_logger.py +190 -12
  47. kumoai/utils/sql.py +3 -0
  48. {kumoai-2.13.0.dev202512040649.dist-info → kumoai-2.14.0.dev202601081732.dist-info}/METADATA +3 -2
  49. {kumoai-2.13.0.dev202512040649.dist-info → kumoai-2.14.0.dev202601081732.dist-info}/RECORD +52 -41
  50. kumoai/experimental/rfm/local_graph_sampler.py +0 -223
  51. kumoai/experimental/rfm/local_pquery_driver.py +0 -689
  52. {kumoai-2.13.0.dev202512040649.dist-info → kumoai-2.14.0.dev202601081732.dist-info}/WHEEL +0 -0
  53. {kumoai-2.13.0.dev202512040649.dist-info → kumoai-2.14.0.dev202601081732.dist-info}/licenses/LICENSE +0 -0
  54. {kumoai-2.13.0.dev202512040649.dist-info → kumoai-2.14.0.dev202601081732.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,782 @@
1
+ import copy
2
+ import re
3
+ import warnings
4
+ from abc import ABC, abstractmethod
5
+ from collections import defaultdict
6
+ from dataclasses import dataclass
7
+ from typing import TYPE_CHECKING, Any, Literal, NamedTuple
8
+
9
+ import numpy as np
10
+ import pandas as pd
11
+ from kumoapi.pquery import QueryType, ValidatedPredictiveQuery
12
+ from kumoapi.pquery.AST import Aggregation, ASTNode
13
+ from kumoapi.rfm.context import EdgeLayout, Link, Subgraph, Table
14
+ from kumoapi.typing import Stype
15
+
16
+ from kumoai.utils import ProgressLogger
17
+
18
+ if TYPE_CHECKING:
19
+ from kumoai.experimental.rfm import Graph
20
+
21
+ _coverage_warned = False
22
+
23
+
24
+ @dataclass
25
+ class SamplerOutput:
26
+ anchor_time: np.ndarray
27
+ df_dict: dict[str, pd.DataFrame]
28
+ inverse_dict: dict[str, np.ndarray]
29
+ batch_dict: dict[str, np.ndarray]
30
+ num_sampled_nodes_dict: dict[str, list[int]]
31
+ row_dict: dict[tuple[str, str, str], np.ndarray]
32
+ col_dict: dict[tuple[str, str, str], np.ndarray]
33
+ num_sampled_edges_dict: dict[tuple[str, str, str], list[int]]
34
+
35
+
36
+ class TargetOutput(NamedTuple):
37
+ entity_pkey: pd.Series
38
+ anchor_time: pd.Series
39
+ target: pd.Series
40
+
41
+
42
+ class Sampler(ABC):
43
+ r"""A base class to sample relational data (*i.e.*, subgraphs and
44
+ ground-truth targets) from a custom backend.
45
+
46
+ Args:
47
+ graph: The graph.
48
+ verbose: Whether to print verbose output.
49
+ """
50
+ def __init__(
51
+ self,
52
+ graph: 'Graph',
53
+ verbose: bool | ProgressLogger = True,
54
+ ) -> None:
55
+
56
+ self._edge_types: list[tuple[str, str, str]] = []
57
+ for edge in graph.edges:
58
+ edge_type = (edge.src_table, edge.fkey, edge.dst_table)
59
+ self._edge_types.append(edge_type)
60
+ self._edge_types.append(Subgraph.rev_edge_type(edge_type))
61
+
62
+ # Source Table -> [(Foreign Key, Destination Table)]
63
+ self._foreign_key_dict: dict[str, list[tuple[str, str]]] = {}
64
+ # Destination Table -> [(Source Table, Foreign Key)]
65
+ self._rev_foreign_key_dict: dict[str, list[tuple[str, str]]] = {}
66
+ for table in graph.tables.values():
67
+ self._foreign_key_dict[table.name] = []
68
+ self._rev_foreign_key_dict[table.name] = []
69
+ for src_table, fkey, dst_table in graph.edges:
70
+ self._foreign_key_dict[src_table].append((fkey, dst_table))
71
+ self._rev_foreign_key_dict[dst_table].append((src_table, fkey))
72
+
73
+ self._primary_key_dict: dict[str, str] = {
74
+ table.name: table._primary_key
75
+ for table in graph.tables.values()
76
+ if table._primary_key is not None
77
+ }
78
+
79
+ self._time_column_dict: dict[str, str] = {
80
+ table.name: table._time_column
81
+ for table in graph.tables.values()
82
+ if table._time_column is not None
83
+ }
84
+
85
+ self._end_time_column_dict: dict[str, str] = {
86
+ table.name: table._end_time_column
87
+ for table in graph.tables.values()
88
+ if table._end_time_column is not None
89
+ }
90
+
91
+ foreign_keys = {(edge.src_table, edge.fkey) for edge in graph.edges}
92
+ self._table_stype_dict: dict[str, dict[str, Stype]] = {}
93
+ for table in graph.tables.values():
94
+ self._table_stype_dict[table.name] = {}
95
+ for column in table.columns:
96
+ if column == table.primary_key:
97
+ continue
98
+ if (table.name, column.name) in foreign_keys:
99
+ continue
100
+ self._table_stype_dict[table.name][column.name] = column.stype
101
+
102
+ self._min_time_dict: dict[str, pd.Timestamp] = {}
103
+ self._max_time_dict: dict[str, pd.Timestamp] = {}
104
+
105
+ # Properties ##############################################################
106
+
107
+ @property
108
+ def edge_types(self) -> list[tuple[str, str, str]]:
109
+ r"""All available edge types in the graph."""
110
+ return self._edge_types
111
+
112
+ @property
113
+ def foreign_key_dict(self) -> dict[str, list[tuple[str, str]]]:
114
+ r"""The foreign keys for all tables in the graph."""
115
+ return self._foreign_key_dict
116
+
117
+ @property
118
+ def rev_foreign_key_dict(self) -> dict[str, list[tuple[str, str]]]:
119
+ r"""The foreign key back references for all tables in the graph."""
120
+ return self._rev_foreign_key_dict
121
+
122
+ @property
123
+ def primary_key_dict(self) -> dict[str, str]:
124
+ r"""All available primary keys in the graph."""
125
+ return self._primary_key_dict
126
+
127
+ @property
128
+ def time_column_dict(self) -> dict[str, str]:
129
+ r"""All available time columns in the graph."""
130
+ return self._time_column_dict
131
+
132
+ @property
133
+ def end_time_column_dict(self) -> dict[str, str]:
134
+ r"""All available end time columns in the graph."""
135
+ return self._end_time_column_dict
136
+
137
+ @property
138
+ def table_stype_dict(self) -> dict[str, dict[str, Stype]]:
139
+ r"""The registered semantic types for all feature columns in all tables
140
+ in the graph.
141
+ """
142
+ return self._table_stype_dict
143
+
144
+ def get_min_time(
145
+ self,
146
+ table_names: list[str] | None = None,
147
+ ) -> pd.Timestamp:
148
+ r"""Returns the minimal timestamp in the union of a set of tables.
149
+
150
+ Args:
151
+ table_names: The set of tables.
152
+ """
153
+ if table_names is None or len(table_names) == 0:
154
+ table_names = list(self.time_column_dict.keys())
155
+ unknown = list(set(table_names) - set(self._min_time_dict.keys()))
156
+ if len(unknown) > 0:
157
+ min_max_time_dict = self._get_min_max_time_dict(unknown)
158
+ for table_name, (min_time, max_time) in min_max_time_dict.items():
159
+ self._min_time_dict[table_name] = min_time
160
+ self._max_time_dict[table_name] = max_time
161
+ return min([self._min_time_dict[table]
162
+ for table in table_names] + [pd.Timestamp.max])
163
+
164
+ def get_max_time(
165
+ self,
166
+ table_names: list[str] | None = None,
167
+ ) -> pd.Timestamp:
168
+ r"""Returns the maximum timestamp in the union of a set of tables.
169
+
170
+ Args:
171
+ table_names: The set of tables.
172
+ """
173
+ if table_names is None or len(table_names) == 0:
174
+ table_names = list(self.time_column_dict.keys())
175
+ unknown = list(set(table_names) - set(self._max_time_dict.keys()))
176
+ if len(unknown) > 0:
177
+ min_max_time_dict = self._get_min_max_time_dict(unknown)
178
+ for table_name, (min_time, max_time) in min_max_time_dict.items():
179
+ self._min_time_dict[table_name] = min_time
180
+ self._max_time_dict[table_name] = max_time
181
+ return max([self._max_time_dict[table]
182
+ for table in table_names] + [pd.Timestamp.min])
183
+
184
+ # Subgraph Sampling #######################################################
185
+
186
+ def sample_subgraph(
187
+ self,
188
+ entity_table_names: tuple[str, ...],
189
+ entity_pkey: pd.Series,
190
+ anchor_time: pd.Series | Literal['entity'],
191
+ num_neighbors: list[int],
192
+ exclude_cols_dict: dict[str, list[str]] | None = None,
193
+ ) -> Subgraph:
194
+ r"""Samples distinct subgraphs for each entity primary key.
195
+
196
+ Args:
197
+ entity_table_names: The entity table names.
198
+ entity_pkey: The primary keys to use as seed nodes.
199
+ anchor_time: The anchor time of the subgraphs.
200
+ num_neighbors: The number of neighbors to sample for each hop.
201
+ exclude_cols_dict: The columns to exclude from the subgraph.
202
+ """
203
+ # Exclude all columns that leak target information:
204
+ table_stype_dict: dict[str, dict[str, Stype]] = self.table_stype_dict
205
+ if exclude_cols_dict is not None:
206
+ table_stype_dict = copy.deepcopy(table_stype_dict)
207
+ for table_name, exclude_cols in exclude_cols_dict.items():
208
+ for column_name in exclude_cols:
209
+ del table_stype_dict[table_name][column_name]
210
+
211
+ # Collect all columns being used as features:
212
+ columns_dict: dict[str, set[str]] = {
213
+ table_name: set(stype_dict.keys())
214
+ for table_name, stype_dict in table_stype_dict.items()
215
+ }
216
+ # Make sure to store primary key information for entity tables:
217
+ for table_name in entity_table_names:
218
+ columns_dict[table_name].add(self.primary_key_dict[table_name])
219
+
220
+ if (isinstance(anchor_time, pd.Series)
221
+ and anchor_time.dtype != 'datetime64[ns]'):
222
+ anchor_time = anchor_time.astype('datetime64[ns]')
223
+
224
+ out = self._sample_subgraph(
225
+ entity_table_name=entity_table_names[0],
226
+ entity_pkey=entity_pkey,
227
+ anchor_time=anchor_time,
228
+ columns_dict=columns_dict,
229
+ num_neighbors=num_neighbors,
230
+ )
231
+
232
+ # Parse `SubgraphOutput` into `Subgraph` structure:
233
+ subgraph = Subgraph(
234
+ anchor_time=out.anchor_time,
235
+ table_dict={},
236
+ link_dict={},
237
+ )
238
+
239
+ for table_name, batch in out.batch_dict.items():
240
+ if len(batch) == 0:
241
+ continue
242
+
243
+ primary_key: str | None = None
244
+ if table_name in entity_table_names:
245
+ primary_key = self.primary_key_dict[table_name]
246
+
247
+ df = out.df_dict[table_name].reset_index(drop=True)
248
+ if end_time_column := self.end_time_column_dict.get(table_name):
249
+ # Set end time to NaT for all values greater than anchor time:
250
+ assert table_name not in out.inverse_dict
251
+ ser = df[end_time_column]
252
+ mask = ser.astype(int).to_numpy() > out.anchor_time[batch]
253
+ df.loc[mask, end_time_column] = pd.NaT
254
+
255
+ stype_dict = table_stype_dict[table_name]
256
+ for column_name, stype in stype_dict.items():
257
+ if stype == Stype.text:
258
+ df[column_name] = _normalize_text(df[column_name])
259
+
260
+ subgraph.table_dict[table_name] = Table(
261
+ df=df,
262
+ row=out.inverse_dict.get(table_name),
263
+ batch=batch,
264
+ num_sampled_nodes=out.num_sampled_nodes_dict[table_name],
265
+ stype_dict=stype_dict,
266
+ primary_key=primary_key,
267
+ )
268
+
269
+ for edge_type in out.row_dict.keys():
270
+ row: np.ndarray | None = out.row_dict[edge_type]
271
+ col: np.ndarray | None = out.col_dict[edge_type]
272
+
273
+ if row is None or col is None or len(row) == 0:
274
+ continue
275
+
276
+ # Do not store reverse edge type if it is an exact replica:
277
+ rev_edge_type = Subgraph.rev_edge_type(edge_type)
278
+ if (rev_edge_type in subgraph.link_dict
279
+ and np.array_equal(row, out.col_dict[rev_edge_type])
280
+ and np.array_equal(col, out.row_dict[rev_edge_type])):
281
+ subgraph.link_dict[edge_type] = Link(
282
+ layout=EdgeLayout.REV,
283
+ row=None,
284
+ col=None,
285
+ num_sampled_edges=out.num_sampled_edges_dict[edge_type],
286
+ )
287
+ continue
288
+
289
+ # Do not store non-informative edges:
290
+ layout = EdgeLayout.COO
291
+ if np.array_equal(row, np.arange(len(row))):
292
+ row = None
293
+ if np.array_equal(col, np.arange(len(col))):
294
+ col = None
295
+
296
+ # Store in compressed representation if more efficient:
297
+ num_cols = subgraph.table_dict[edge_type[2]].num_rows
298
+ if col is not None and len(col) > num_cols + 1:
299
+ layout = EdgeLayout.CSC
300
+ colcount = np.bincount(col, minlength=num_cols)
301
+ col = np.empty(num_cols + 1, dtype=col.dtype)
302
+ col[0] = 0
303
+ np.cumsum(colcount, out=col[1:])
304
+
305
+ subgraph.link_dict[edge_type] = Link(
306
+ layout=layout,
307
+ row=row,
308
+ col=col,
309
+ num_sampled_edges=out.num_sampled_edges_dict[edge_type],
310
+ )
311
+
312
+ return subgraph
313
+
314
+ # Predictive Query ########################################################
315
+
316
+ def _get_query_columns_dict(
317
+ self,
318
+ query: ValidatedPredictiveQuery,
319
+ ) -> dict[str, set[str]]:
320
+ columns_dict: dict[str, set[str]] = defaultdict(set)
321
+ for fqn in query.all_query_columns + [query.entity_column]:
322
+ table_name, column_name = fqn.split('.')
323
+ if column_name == '*':
324
+ continue
325
+ columns_dict[table_name].add(column_name)
326
+ if column_name := self.time_column_dict.get(query.entity_table):
327
+ columns_dict[table_name].add(column_name)
328
+ if column_name := self.end_time_column_dict.get(query.entity_table):
329
+ columns_dict[table_name].add(column_name)
330
+ return columns_dict
331
+
332
+ def _get_query_time_offset_dict(
333
+ self,
334
+ query: ValidatedPredictiveQuery,
335
+ ) -> dict[
336
+ tuple[str, str, str],
337
+ tuple[pd.DateOffset | None, pd.DateOffset],
338
+ ]:
339
+ time_offset_dict: dict[
340
+ tuple[str, str, str],
341
+ tuple[pd.DateOffset | None, pd.DateOffset],
342
+ ] = {}
343
+
344
+ def _add_time_offset(node: ASTNode, num_forecasts: int = 1) -> None:
345
+ if isinstance(node, Aggregation):
346
+ table_name = node._get_target_column_name().split('.')[0]
347
+
348
+ edge_types = [
349
+ edge_type for edge_type in self.edge_types
350
+ if edge_type[0] == table_name
351
+ and edge_type[2] == query.entity_table
352
+ ]
353
+ if len(edge_types) != 1:
354
+ raise ValueError(f"Could not find a unique foreign key "
355
+ f"from table '{table_name}' to "
356
+ f"'{query.entity_table}'")
357
+ if edge_types[0] not in time_offset_dict:
358
+ start = node.aggr_time_range.start_date_offset
359
+ end = node.aggr_time_range.end_date_offset * num_forecasts
360
+ else:
361
+ start, end = time_offset_dict[edge_types[0]]
362
+ start = min_date_offset(
363
+ start,
364
+ node.aggr_time_range.start_date_offset,
365
+ )
366
+ end = max_date_offset(
367
+ end,
368
+ node.aggr_time_range.end_date_offset * num_forecasts,
369
+ )
370
+ time_offset_dict[edge_types[0]] = (start, end)
371
+
372
+ for child in node.children:
373
+ _add_time_offset(child, num_forecasts)
374
+
375
+ _add_time_offset(query.target_ast, query.num_forecasts)
376
+ _add_time_offset(query.entity_ast)
377
+ if query.whatif_ast is not None:
378
+ _add_time_offset(query.whatif_ast)
379
+
380
+ return time_offset_dict
381
+
382
+ def sample_target(
383
+ self,
384
+ query: ValidatedPredictiveQuery,
385
+ num_train_examples: int,
386
+ train_anchor_time: pd.Timestamp | Literal['entity'],
387
+ num_train_trials: int,
388
+ num_test_examples: int,
389
+ test_anchor_time: pd.Timestamp | Literal['entity'],
390
+ num_test_trials: int,
391
+ random_seed: int | None = None,
392
+ ) -> tuple[TargetOutput, TargetOutput]:
393
+ r"""Samples ground-truth targets given a predictive query, split into
394
+ training and test set.
395
+
396
+ Args:
397
+ query: The predictive query.
398
+ num_train_examples: How many training examples to produce.
399
+ train_anchor_time: The anchor timestamp for the training set.
400
+ If set to ``"entity"``, will use the timestamp of the entity.
401
+ num_train_trials: The number of training examples to try before
402
+ aborting.
403
+ num_test_examples: How many test examples to produce.
404
+ test_anchor_time: The anchor timestamp for the test set.
405
+ If set to ``"entity"``, will use the timestamp of the entity.
406
+ num_test_trials: The number of test examples to try before
407
+ aborting.
408
+ random_seed: A manual seed for generating pseudo-random numbers.
409
+ """
410
+ rng = np.random.default_rng(random_seed)
411
+
412
+ if num_train_examples == 0 or num_train_trials == 0:
413
+ num_train_examples = num_train_trials = 0
414
+ if num_test_examples == 0 or num_test_trials == 0:
415
+ num_test_examples = num_test_trials = 0
416
+
417
+ # 1. Collect information on what to query #############################
418
+ columns_dict = self._get_query_columns_dict(query)
419
+ time_offset_dict = self._get_query_time_offset_dict(query)
420
+ for table_name, _, _ in time_offset_dict.keys():
421
+ columns_dict[table_name].add(self.time_column_dict[table_name])
422
+
423
+ # 2. Sample random rows from entity table #############################
424
+ shared_train_test = query.query_type == QueryType.STATIC
425
+ shared_train_test &= train_anchor_time == test_anchor_time
426
+ if shared_train_test:
427
+ num_entity_rows = num_train_trials + num_test_trials
428
+ else:
429
+ num_entity_rows = max(num_train_trials, num_test_trials)
430
+ assert num_entity_rows > 0
431
+
432
+ entity_df = self._sample_entity_table(
433
+ table_name=query.entity_table,
434
+ columns=columns_dict[query.entity_table],
435
+ num_rows=num_entity_rows,
436
+ random_seed=random_seed,
437
+ )
438
+
439
+ if len(entity_df) == 0:
440
+ raise ValueError("Failed to find any rows in the entity table "
441
+ "'{query.entity_table}'.")
442
+
443
+ entity_pkey = entity_df[self.primary_key_dict[query.entity_table]]
444
+ entity_time: pd.Series | None = None
445
+ if column_name := self.time_column_dict.get(query.entity_table):
446
+ entity_time = entity_df[column_name]
447
+ entity_end_time: pd.Series | None = None
448
+ if column_name := self.end_time_column_dict.get(query.entity_table):
449
+ entity_end_time = entity_df[column_name]
450
+
451
+ def get_valid_entity_index(
452
+ time: pd.Timestamp | Literal['entity'],
453
+ max_size: int | None = None,
454
+ ) -> np.ndarray:
455
+
456
+ if time == 'entity':
457
+ index: np.ndarray = np.arange(len(entity_pkey))
458
+ elif entity_time is None and entity_end_time is None:
459
+ index = np.arange(len(entity_pkey))
460
+ else:
461
+ mask: np.ndarray | None = None
462
+ if entity_time is not None:
463
+ mask = (entity_time <= time).to_numpy()
464
+ if entity_end_time is not None:
465
+ _mask = (entity_end_time > time).to_numpy()
466
+ _mask |= entity_end_time.isna().to_numpy()
467
+ mask = _mask if mask is None else mask & _mask
468
+ assert mask is not None
469
+ index = mask.nonzero()[0]
470
+
471
+ rng.shuffle(index)
472
+
473
+ if max_size is not None:
474
+ index = index[:max_size]
475
+
476
+ return index
477
+
478
+ # 3. Build training and test candidates ###############################
479
+ train_index = test_index = np.array([], dtype=np.int64)
480
+ train_time = test_time = pd.Series([], dtype='datetime64[ns]')
481
+
482
+ if shared_train_test:
483
+ train_index = get_valid_entity_index(train_anchor_time)
484
+ if train_anchor_time == 'entity': # Sort by timestamp:
485
+ assert entity_time is not None
486
+ train_time = entity_time.iloc[train_index]
487
+ train_time = train_time.reset_index(drop=True)
488
+ train_time = train_time.sort_values(ascending=False)
489
+ perm = train_time.index.to_numpy()
490
+ train_index = train_index[perm]
491
+ train_time = train_time.reset_index(drop=True)
492
+ else:
493
+ train_time = to_ser(train_anchor_time, size=len(train_index))
494
+ else:
495
+ if num_test_examples > 0:
496
+ test_index = get_valid_entity_index( #
497
+ test_anchor_time, max_size=num_test_trials)
498
+ assert test_anchor_time != 'entity'
499
+ test_time = to_ser(test_anchor_time, len(test_index))
500
+
501
+ if query.query_type == QueryType.STATIC and num_train_examples > 0:
502
+ train_index = get_valid_entity_index( #
503
+ train_anchor_time, max_size=num_train_trials)
504
+ assert train_anchor_time != 'entity'
505
+ train_time = to_ser(train_anchor_time, len(train_index))
506
+ elif query.query_type == QueryType.TEMPORAL and num_train_examples:
507
+ aggr_table_names = [
508
+ aggr._get_target_column_name().split('.')[0]
509
+ for aggr in query.get_all_target_aggregations()
510
+ ]
511
+ offset = query.target_timeframe.timeframe * query.num_forecasts
512
+
513
+ train_indices: list[np.ndarray] = []
514
+ train_times: list[pd.Series] = []
515
+ while True:
516
+ train_index = get_valid_entity_index( #
517
+ train_anchor_time, max_size=num_train_trials)
518
+ assert train_anchor_time != 'entity'
519
+ train_time = to_ser(train_anchor_time, len(train_index))
520
+ train_indices.append(train_index)
521
+ train_times.append(train_time)
522
+ if sum(len(x) for x in train_indices) >= num_train_trials:
523
+ break
524
+ train_anchor_time -= offset
525
+ if train_anchor_time < self.get_min_time(aggr_table_names):
526
+ break
527
+ train_index = np.concatenate(train_indices, axis=0)
528
+ train_index = train_index[:num_train_trials]
529
+ train_time = pd.concat(train_times, axis=0, ignore_index=True)
530
+ train_time = train_time.iloc[:num_train_trials]
531
+
532
+ # 4. Sample training and test labels ##################################
533
+ train_y, train_mask, test_y, test_mask = self._sample_target(
534
+ query=query,
535
+ entity_df=entity_df,
536
+ train_index=train_index,
537
+ train_time=train_time,
538
+ num_train_examples=(num_train_examples + num_test_examples
539
+ if shared_train_test else num_train_examples),
540
+ test_index=test_index,
541
+ test_time=test_time,
542
+ num_test_examples=0 if shared_train_test else num_test_examples,
543
+ columns_dict=columns_dict,
544
+ time_offset_dict=time_offset_dict,
545
+ )
546
+
547
+ # 5. Post-processing ##################################################
548
+ if shared_train_test:
549
+ num_examples = num_train_examples + num_test_examples
550
+ train_index = train_index[train_mask][:num_examples]
551
+ train_time = train_time.iloc[train_mask].iloc[:num_examples]
552
+ train_y = train_y.iloc[:num_examples]
553
+
554
+ _num_test = num_test_examples
555
+ _num_train = min(num_train_examples, 1000)
556
+ if (num_test_examples > 0 and num_train_examples > 0
557
+ and len(train_y) < num_examples
558
+ and len(train_y) < _num_test + _num_train):
559
+ # Not enough labels to satisfy requested split without losing
560
+ # large number of training examples:
561
+ _num_test = len(train_y) - _num_train
562
+ if _num_test < _num_train: # Fallback to 50/50 split:
563
+ _num_test = len(train_y) // 2
564
+
565
+ test_index = train_index[:_num_test]
566
+ test_pkey = entity_pkey.iloc[test_index]
567
+ test_time = train_time.iloc[:_num_test]
568
+ test_y = train_y.iloc[:_num_test]
569
+
570
+ train_index = train_index[_num_test:]
571
+ train_pkey = entity_pkey.iloc[train_index]
572
+ train_time = train_time.iloc[_num_test:]
573
+ train_y = train_y.iloc[_num_test:]
574
+ else:
575
+ train_index = train_index[train_mask][:num_train_examples]
576
+ train_pkey = entity_pkey.iloc[train_index]
577
+ train_time = train_time.iloc[train_mask].iloc[:num_train_examples]
578
+ train_y = train_y.iloc[:num_train_examples]
579
+
580
+ test_index = test_index[test_mask][:num_test_examples]
581
+ test_pkey = entity_pkey.iloc[test_index]
582
+ test_time = test_time.iloc[test_mask].iloc[:num_test_examples]
583
+ test_y = test_y.iloc[:num_test_examples]
584
+
585
+ train_pkey = train_pkey.reset_index(drop=True)
586
+ train_time = train_time.reset_index(drop=True)
587
+ train_y = train_y.reset_index(drop=True)
588
+ test_pkey = test_pkey.reset_index(drop=True)
589
+ test_time = test_time.reset_index(drop=True)
590
+ test_y = test_y.reset_index(drop=True)
591
+
592
+ if num_train_examples > 0 and len(train_y) == 0:
593
+ raise RuntimeError("Failed to collect any context examples. Is "
594
+ "your predictive query too restrictive?")
595
+
596
+ if num_test_examples > 0 and len(test_y) == 0:
597
+ raise RuntimeError("Failed to collect any test examples for "
598
+ "evaluation. Is your predictive query too "
599
+ "restrictive?")
600
+
601
+ global _coverage_warned
602
+ if (not num_train_examples > 0 #
603
+ and not _coverage_warned #
604
+ and len(entity_df) >= num_entity_rows
605
+ and len(train_y) < num_train_examples // 2):
606
+ _coverage_warned = True
607
+ warnings.warn(f"Failed to collect {num_train_examples:,} context "
608
+ f"examples within {num_train_trials:,} candidates. "
609
+ f"To improve coverage, consider increasing the "
610
+ f"number of PQ iterations using the "
611
+ f"'max_pq_iterations' option. This warning will not "
612
+ f"be shown again in this run.")
613
+
614
+ if (not num_test_examples > 0 #
615
+ and not _coverage_warned #
616
+ and len(entity_df) >= num_entity_rows
617
+ and len(test_y) < num_test_examples // 2):
618
+ _coverage_warned = True
619
+ warnings.warn(f"Failed to collect {num_test_examples:,} test "
620
+ f"examples within {num_test_trials:,} candidates. "
621
+ f"To improve coverage, consider increasing the "
622
+ f"number of PQ iterations using the "
623
+ f"'max_pq_iterations' option. This warning will not "
624
+ f"be shown again in this run.")
625
+
626
+ return (
627
+ TargetOutput(train_pkey, train_time, train_y),
628
+ TargetOutput(test_pkey, test_time, test_y),
629
+ )
630
+
631
+ # Abstract Methods ########################################################
632
+
633
+ @abstractmethod
634
+ def _get_min_max_time_dict(
635
+ self,
636
+ table_names: list[str],
637
+ ) -> dict[str, tuple[pd.Timestamp, pd.Timestamp]]:
638
+ r"""Returns the minimum and maximum timestamps for a set of tables.
639
+
640
+ Args:
641
+ table_names: The tables.
642
+ """
643
+
644
+ @abstractmethod
645
+ def _sample_subgraph(
646
+ self,
647
+ entity_table_name: str,
648
+ entity_pkey: pd.Series,
649
+ anchor_time: pd.Series | Literal['entity'],
650
+ columns_dict: dict[str, set[str]],
651
+ num_neighbors: list[int],
652
+ ) -> SamplerOutput:
653
+ r"""Samples distinct subgraphs for each entity primary key.
654
+
655
+ Args:
656
+ entity_table_name: The entity table name.
657
+ entity_pkey: The primary keys to use as seed nodes.
658
+ anchor_time: The anchor time of the subgraphs.
659
+ columns_dict: The columns to return for each table.
660
+ num_neighbors: The number of neighbors to sample for each hop.
661
+ """
662
+
663
+ @abstractmethod
664
+ def _sample_entity_table(
665
+ self,
666
+ table_name: str,
667
+ columns: set[str],
668
+ num_rows: int,
669
+ random_seed: int | None = None,
670
+ ) -> pd.DataFrame:
671
+ r"""Returns a random sample of rows from the entity table.
672
+
673
+ Args:
674
+ table_name: The table.
675
+ columns: The columns to return.
676
+ num_rows: Maximum number of rows to return. Can be smaller in case
677
+ the entity table contains less rows.
678
+ random_seed: A manual seed for generating pseudo-random numbers.
679
+ """
680
+
681
+ @abstractmethod
682
+ def _sample_target(
683
+ self,
684
+ query: ValidatedPredictiveQuery,
685
+ entity_df: pd.DataFrame,
686
+ train_index: np.ndarray,
687
+ train_time: pd.Series,
688
+ num_train_examples: int,
689
+ test_index: np.ndarray,
690
+ test_time: pd.Series,
691
+ num_test_examples: int,
692
+ columns_dict: dict[str, set[str]],
693
+ time_offset_dict: dict[
694
+ tuple[str, str, str],
695
+ tuple[pd.DateOffset | None, pd.DateOffset],
696
+ ],
697
+ ) -> tuple[pd.Series, np.ndarray, pd.Series, np.ndarray]:
698
+ r"""Samples ground-truth targets given a predictive query from a set of
699
+ training and test candidates.
700
+
701
+ Args:
702
+ query: The predictive query.
703
+ entity_df: The entity data frame, containing the union of all train
704
+ and test candidates.
705
+ train_index: The indices of training candidates.
706
+ train_time: The anchor time of training candidates.
707
+ num_train_examples: How many training examples to produce.
708
+ test_index: The indices of test candidates.
709
+ test_time: The anchor time of test candidates.
710
+ num_test_examples: How many test examples to produce.
711
+ columns_dict: The columns that are being used to compute
712
+ ground-truth targets.
713
+ time_offset_dict: The date offsets to query for each edge type,
714
+ relative to the anchor time.
715
+ """
716
+
717
+
718
+ # Helper Functions ############################################################
719
+
720
+ PUNCTUATION = re.compile(r"[\'\"\.,\(\)\!\?\;\:]")
721
+ MULTISPACE = re.compile(r"\s+")
722
+
723
+
724
+ def _normalize_text(
725
+ ser: pd.Series,
726
+ max_words: int | None = 50,
727
+ ) -> pd.Series:
728
+ r"""Normalizes text into a list of lower-case words.
729
+
730
+ Args:
731
+ ser: The :class:`pandas.Series` to normalize.
732
+ max_words: The maximum number of words to return.
733
+ This will auto-shrink any large text column to avoid blowing up
734
+ context size.
735
+ """
736
+ if len(ser) == 0 or pd.api.types.is_list_like(ser.iloc[0]):
737
+ return ser
738
+
739
+ def normalize_fn(line: str) -> list[str]:
740
+ line = PUNCTUATION.sub(" ", line)
741
+ line = re.sub(r"<br\s*/?>", " ", line) # Handle <br /> or <br>
742
+ line = MULTISPACE.sub(" ", line)
743
+ words = line.split()
744
+ if max_words is not None:
745
+ words = words[:max_words]
746
+ return words
747
+
748
+ ser = ser.fillna('').astype(str)
749
+
750
+ if max_words is not None:
751
+ # We estimate the number of words as 5 characters + 1 space in an
752
+ # English text on average. We need this pre-filter here, as word
753
+ # splitting on a giant text can be very expensive:
754
+ ser = ser.str[:6 * max_words]
755
+
756
+ ser = ser.str.lower()
757
+ ser = ser.map(normalize_fn)
758
+
759
+ return ser
760
+
761
+
762
+ def min_date_offset(*args: pd.DateOffset | None) -> pd.DateOffset | None:
763
+ if any(arg is None for arg in args):
764
+ return None
765
+
766
+ anchor = pd.Timestamp('2000-01-01')
767
+ timestamps = [anchor + arg for arg in args]
768
+ assert len(timestamps) > 0
769
+ argmin = min(range(len(timestamps)), key=lambda i: timestamps[i])
770
+ return args[argmin]
771
+
772
+
773
+ def max_date_offset(*args: pd.DateOffset) -> pd.DateOffset:
774
+ anchor = pd.Timestamp('2000-01-01')
775
+ timestamps = [anchor + arg for arg in args]
776
+ assert len(timestamps) > 0
777
+ argmax = max(range(len(timestamps)), key=lambda i: timestamps[i])
778
+ return args[argmax]
779
+
780
+
781
+ def to_ser(value: Any, size: int) -> pd.Series:
782
+ return pd.Series([value]).repeat(size).reset_index(drop=True)