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