scikit-link 0.1.0__py3-none-any.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 (90) hide show
  1. scikit_link-0.1.0.dist-info/METADATA +272 -0
  2. scikit_link-0.1.0.dist-info/RECORD +90 -0
  3. scikit_link-0.1.0.dist-info/WHEEL +4 -0
  4. scikit_link-0.1.0.dist-info/licenses/LICENSE +21 -0
  5. sklink/__init__.py +19 -0
  6. sklink/_base.py +535 -0
  7. sklink/_compat.py +63 -0
  8. sklink/_config.py +190 -0
  9. sklink/_metadata.py +14 -0
  10. sklink/_numba.py +69 -0
  11. sklink/_show_versions.py +46 -0
  12. sklink/cluster/__init__.py +11 -0
  13. sklink/cluster/_common.py +87 -0
  14. sklink/cluster/_embedding.py +202 -0
  15. sklink/cluster/_kmeans.py +405 -0
  16. sklink/cluster/_tree.py +485 -0
  17. sklink/compose/__init__.py +10 -0
  18. sklink/compose/_tables.py +1141 -0
  19. sklink/database/__init__.py +23 -0
  20. sklink/database/_binding.py +214 -0
  21. sklink/database/_columns.py +747 -0
  22. sklink/database/_database.py +1022 -0
  23. sklink/database/_keys.py +104 -0
  24. sklink/database/_schema.py +368 -0
  25. sklink/datasets/__init__.py +17 -0
  26. sklink/datasets/_shop.py +148 -0
  27. sklink/datasets/_synthetic.py +1323 -0
  28. sklink/datasets/data/customers.parquet +0 -0
  29. sklink/datasets/data/order_items.parquet +0 -0
  30. sklink/datasets/data/orders.parquet +0 -0
  31. sklink/datasets/data/products.parquet +0 -0
  32. sklink/datasets/data/target.parquet +0 -0
  33. sklink/engine/__init__.py +62 -0
  34. sklink/engine/_cache.py +60 -0
  35. sklink/engine/_leafsum.py +65 -0
  36. sklink/engine/_numpy.py +795 -0
  37. sklink/engine/_protocol.py +210 -0
  38. sklink/ensemble/__init__.py +19 -0
  39. sklink/ensemble/_forest.py +1343 -0
  40. sklink/ensemble/_gb.py +1805 -0
  41. sklink/ensemble/_iforest.py +329 -0
  42. sklink/exceptions.py +123 -0
  43. sklink/expressions/__init__.py +48 -0
  44. sklink/expressions/_ast.py +562 -0
  45. sklink/expressions/_enumerate.py +236 -0
  46. sklink/expressions/_naming.py +508 -0
  47. sklink/expressions/_validate.py +130 -0
  48. sklink/feature_extraction/__init__.py +5 -0
  49. sklink/feature_extraction/_featurizer.py +613 -0
  50. sklink/inspection/__init__.py +34 -0
  51. sklink/inspection/_common.py +247 -0
  52. sklink/inspection/_explain.py +361 -0
  53. sklink/inspection/_export.py +519 -0
  54. sklink/inspection/_importances.py +560 -0
  55. sklink/model_selection/__init__.py +10 -0
  56. sklink/model_selection/_split.py +437 -0
  57. sklink/plotting/__init__.py +51 -0
  58. sklink/plotting/_common.py +125 -0
  59. sklink/plotting/_cutoff.py +931 -0
  60. sklink/plotting/_display.py +337 -0
  61. sklink/plotting/_environment.py +28 -0
  62. sklink/plotting/_explanation.py +593 -0
  63. sklink/plotting/_forest.py +1074 -0
  64. sklink/plotting/_importance.py +448 -0
  65. sklink/plotting/_live.py +789 -0
  66. sklink/plotting/_schema.py +964 -0
  67. sklink/plotting/_search.py +546 -0
  68. sklink/plotting/_static/plotting.js +85 -0
  69. sklink/plotting/_svg.py +195 -0
  70. sklink/plotting/_theme.py +89 -0
  71. sklink/plotting/_tree.py +991 -0
  72. sklink/primitives/__init__.py +22 -0
  73. sklink/primitives/_kernels.py +461 -0
  74. sklink/primitives/_registry.py +201 -0
  75. sklink/py.typed +0 -0
  76. sklink/tree/__init__.py +14 -0
  77. sklink/tree/_binning.py +114 -0
  78. sklink/tree/_builder.py +2861 -0
  79. sklink/tree/_classes.py +1369 -0
  80. sklink/tree/_criteria.py +167 -0
  81. sklink/tree/_data.py +957 -0
  82. sklink/tree/_leafsum.py +210 -0
  83. sklink/tree/_numba_kernels.py +603 -0
  84. sklink/tree/_splitter.py +857 -0
  85. sklink/utils/__init__.py +9 -0
  86. sklink/utils/_dates.py +188 -0
  87. sklink/utils/_output.py +35 -0
  88. sklink/utils/_testing.py +628 -0
  89. sklink/utils/estimator_checks.py +1034 -0
  90. sklink/utils/validation.py +432 -0
sklink/_base.py ADDED
@@ -0,0 +1,535 @@
1
+ """Machinery shared by every relational estimator.
2
+
3
+ The mixin turns ``X`` into a resolved population, evaluates expressions through
4
+ the engine and encodes categorical values with vocabularies learned in ``fit``.
5
+ Estimators keep their own ``__init__`` with explicit parameters, as scikit-learn
6
+ requires; this module only holds behavior.
7
+ """
8
+
9
+ import fnmatch
10
+ from collections.abc import Sequence
11
+ from typing import Any
12
+
13
+ import numpy as np
14
+ import numpy.typing as npt
15
+
16
+ from sklink._config import get_config
17
+ from sklink._metadata import __version__
18
+ from sklink.database import Database, Schema, TableSchema
19
+ from sklink.database._columns import RawColumn
20
+ from sklink.engine import (
21
+ Population,
22
+ ResolvedPopulation,
23
+ Session,
24
+ Visibility,
25
+ get_backend,
26
+ )
27
+ from sklink.exceptions import (
28
+ InconsistentVersionWarning,
29
+ LeakageWarning,
30
+ SchemaError,
31
+ SklinkWarning,
32
+ UnknownEntityError,
33
+ VisibilityError,
34
+ _warn,
35
+ )
36
+ from sklink.expressions import (
37
+ Aggregate,
38
+ Condition,
39
+ Expression,
40
+ Path,
41
+ SampleFeature,
42
+ Window,
43
+ enumerate_expressions,
44
+ enumerate_lookups,
45
+ enumerate_paths,
46
+ output_type,
47
+ )
48
+ from sklink.primitives import get_primitive
49
+ from sklink.utils._dates import to_nanoseconds
50
+ from sklink.utils.validation import ValidatedX, check_database, check_relational_X
51
+
52
+ __all__ = ["RelationalMixin", "VersionedStateMixin", "encode_labels", "lookup_keywords"]
53
+
54
+
55
+ def lookup_keywords(lookup: Path) -> dict[str, Any]:
56
+ """Keyword arguments that pass ``lookup`` to a :class:`Session` method.
57
+
58
+ Empty without hops, so that a backend written before lookups existed,
59
+ whose methods take no ``lookup``, keeps working when none is used.
60
+ """
61
+ return {"lookup": lookup} if lookup.hops else {}
62
+
63
+
64
+ def encode_labels(
65
+ values: np.ndarray, missing: np.ndarray, vocabulary: np.ndarray
66
+ ) -> npt.NDArray[np.float64]:
67
+ """Codes of ``values`` in a sorted ``vocabulary``; ``NaN`` if missing or unknown."""
68
+ out = np.full(len(values), np.nan)
69
+ if vocabulary.size == 0:
70
+ return out
71
+ present = ~missing
72
+ lookup = {label: i for i, label in enumerate(vocabulary.tolist())}
73
+ out[present] = [lookup.get(v, np.nan) for v in values[present].tolist()]
74
+ return out
75
+
76
+
77
+ def _labels(raw: RawColumn) -> np.ndarray:
78
+ """Labels of a sample feature column treated as categorical."""
79
+ present = raw.values[~raw.missing]
80
+ if raw.hint == "object" and any(not isinstance(v, str) for v in present):
81
+ # Mixed objects are compared by their string form, as documented.
82
+ return np.asarray([str(v) for v in raw.values], dtype=object)
83
+ return raw.values
84
+
85
+
86
+ def _is_position(key: Any) -> bool:
87
+ """Whether ``key`` gives any of its columns by integer position.
88
+
89
+ ``key`` has already been validated: ``None``, a name, a position or a
90
+ sequence of them (a list, a tuple or an array).
91
+ """
92
+ scalar = key is None or isinstance(key, str | int | np.integer)
93
+ parts = [key] if scalar else list(key)
94
+ return any(
95
+ isinstance(p, int | np.integer) and not isinstance(p, bool) for p in parts
96
+ )
97
+
98
+
99
+ def _sample_kind(raw: RawColumn) -> str:
100
+ if raw.hint in {"numeric", "boolean"}:
101
+ return "numeric"
102
+ if raw.hint == "datetime":
103
+ return "datetime"
104
+ if raw.hint == "object":
105
+ present = raw.values[~raw.missing]
106
+ if all(
107
+ isinstance(v, int | float | bool | np.number | np.bool_) for v in present
108
+ ):
109
+ return "numeric"
110
+ return "categorical"
111
+
112
+
113
+ class VersionedStateMixin:
114
+ """Keep the version of scikit-link in the pickled state of an estimator.
115
+
116
+ scikit-learn stamps its version only on its own estimators, so a model of
117
+ this package saved by one version would load silently in another. Goes
118
+ left of ``BaseEstimator``. A state without the version loads silently.
119
+ """
120
+
121
+ def __getstate__(self) -> dict[str, Any]:
122
+ state: dict[str, Any] = super().__getstate__() # type: ignore[assignment]
123
+ return {**state, "_sklink_version": __version__}
124
+
125
+ def __setstate__(self, state: dict[str, Any]) -> None:
126
+ saved = state.pop("_sklink_version", None)
127
+ if saved is not None and saved != __version__:
128
+ _warn(
129
+ InconsistentVersionWarning(
130
+ estimator_name=type(self).__name__,
131
+ current_version=__version__,
132
+ original_version=saved,
133
+ ),
134
+ InconsistentVersionWarning,
135
+ )
136
+ super().__setstate__(state) # type: ignore[misc]
137
+
138
+
139
+ class RelationalMixin(VersionedStateMixin):
140
+ """Helpers for estimators whose ``X`` is a population table.
141
+
142
+ Subclasses define the parameters ``database``, ``entity``, ``key``,
143
+ ``time``, ``allow_reverse_paths`` and ``handle_unknown_entity``.
144
+ """
145
+
146
+ database: Database | None
147
+ schema_: Schema | None
148
+ entity: str | None
149
+ key: Any
150
+ time: Any
151
+ allow_reverse_paths: bool
152
+ handle_unknown_entity: str
153
+
154
+ # ------------------------------------------------------------ validation
155
+ def _check_params_relational(self) -> Database | None:
156
+ if self.handle_unknown_entity not in {"error", "empty"}:
157
+ raise ValueError(
158
+ "handle_unknown_entity must be 'error' or 'empty', got "
159
+ f"{self.handle_unknown_entity!r}."
160
+ )
161
+ if self.database is None:
162
+ return None
163
+ if self.entity is None:
164
+ raise ValueError("entity is required when a database is given.")
165
+ return check_database(self.database, entity=self.entity)
166
+
167
+ def _validate_X(self, X: Any, *, reset: bool) -> tuple[ValidatedX, Database | None]:
168
+ database = self._check_params_relational()
169
+ validated = check_relational_X(
170
+ self,
171
+ X,
172
+ reset=reset,
173
+ database=database,
174
+ # In flat mode these must be None; check_relational_X says so.
175
+ entity=self.entity,
176
+ key=self.key,
177
+ time=self.time,
178
+ )
179
+ if not reset and database is not None and self.schema_ is not None:
180
+ missing = self.schema_.missing_from(database.schema)
181
+ if missing:
182
+ raise SchemaError(
183
+ "The database lacks what the model uses: "
184
+ + "; ".join(missing)
185
+ + "."
186
+ )
187
+ return validated, database
188
+
189
+ def _visibility(self) -> Visibility:
190
+ return Visibility(
191
+ time=self.time is not None,
192
+ allow_reverse_paths=bool(self.allow_reverse_paths),
193
+ )
194
+
195
+ def _warn_visibility(self, database: Database) -> None:
196
+ if self.allow_reverse_paths and self.time is None:
197
+ _warn(
198
+ "allow_reverse_paths=True lets a sample read rows of other entities "
199
+ "through shared tables; without a cutoff (time=...) this can leak "
200
+ "labels between training and test samples.",
201
+ LeakageWarning,
202
+ )
203
+ if self.time is not None:
204
+ assert self.entity is not None
205
+ schema = database.schema
206
+ untimed: set[str] = set()
207
+ for path in enumerate_paths(
208
+ schema,
209
+ entity=self.entity,
210
+ max_relationship_depth=getattr(self, "max_relationship_depth", 1),
211
+ allow_reverse_paths=bool(self.allow_reverse_paths),
212
+ ):
213
+ # Rows reached down a one-to-many hop are filtered by the cutoff
214
+ # when their table has a time column or when the rows they hang
215
+ # from were filtered (the items of an order not yet placed are
216
+ # invisible). Rows reached up a many-to-one hop are filtered
217
+ # only by their own time column.
218
+ filtered = False
219
+ for hop in path.hops:
220
+ timed = schema.table(hop.target).time_column is not None
221
+ if hop.direction == "to_many":
222
+ filtered = filtered or timed
223
+ if not filtered:
224
+ untimed.add(hop.target)
225
+ else:
226
+ filtered = timed
227
+ if untimed:
228
+ _warn(
229
+ f"Temporal mode: tables {sorted(untimed)} have no time column and "
230
+ "are not reached through one, so all their rows are visible at "
231
+ "every cutoff.",
232
+ SklinkWarning,
233
+ )
234
+
235
+ # ------------------------------------------------------------ population
236
+ def _open(self, database: Database) -> Session:
237
+ threads = get_config()["engine_threads"] or 1
238
+ return get_backend().open(database, n_threads=threads)
239
+
240
+ def _resolve(self, session: Session, validated: ValidatedX) -> ResolvedPopulation:
241
+ assert validated.keys is not None
242
+ assert validated.key_missing is not None
243
+ assert self.entity is not None
244
+ population = Population(validated.keys, validated.key_missing, validated.cutoff)
245
+ visibility = self._visibility()
246
+ if visibility.time and validated.cutoff is None:
247
+ raise VisibilityError(
248
+ "This model was fitted in temporal mode; X needs the time column."
249
+ )
250
+ resolved = session.resolve_population(self.entity, population, visibility)
251
+ n_unknown = int(np.count_nonzero(resolved.unknown[resolved.sample_to_group]))
252
+ if n_unknown and self.handle_unknown_entity == "error":
253
+ hint = ""
254
+ if _is_position(self.key):
255
+ # A position points at another column when a meta-estimator
256
+ # passes a subset or a reordering of the columns of X; the
257
+ # keys then look unknown.
258
+ hint = (
259
+ " The key is given by position, and a meta-estimator that "
260
+ "selects columns of X, such as BaggingClassifier with "
261
+ "max_features below 1.0 or bootstrap_features=True, can move "
262
+ "the key column or leave it out."
263
+ )
264
+ raise UnknownEntityError(
265
+ f"{n_unknown} rows of X have keys that do not exist in table "
266
+ f"{self.entity!r}. Pass handle_unknown_entity='empty' to treat them as "
267
+ f"entities without related rows.{hint}"
268
+ )
269
+ return resolved
270
+
271
+ # ------------------------------------------------------- sample features
272
+ def _fit_sample_features(self, validated: ValidatedX) -> None:
273
+ kinds: list[str] = []
274
+ categories: dict[str, np.ndarray] = {}
275
+ for name, raw in zip(validated.feature_names, validated.features, strict=True):
276
+ kind = _sample_kind(raw)
277
+ kinds.append(kind)
278
+ if kind == "categorical":
279
+ labels = _labels(raw)
280
+ categories[name] = np.unique(labels[~raw.missing])
281
+ self._sample_kinds = kinds
282
+ self._sample_categories = categories
283
+
284
+ def _sample_matrix(self, validated: ValidatedX) -> tuple[np.ndarray, list[bool]]:
285
+ """Sample features as ``float64`` (categoricals as codes)."""
286
+ n = validated.n_samples
287
+ out = np.empty((n, len(validated.features)))
288
+ is_categorical = []
289
+ if len(validated.features) != len(self._sample_kinds):
290
+ raise ValueError(
291
+ f"X has {len(validated.features)} feature columns, but the "
292
+ f"estimator was fitted with {len(self._sample_kinds)}."
293
+ )
294
+ for j, (name, raw, kind) in enumerate(
295
+ zip(
296
+ validated.feature_names,
297
+ validated.features,
298
+ self._sample_kinds,
299
+ strict=True,
300
+ )
301
+ ):
302
+ if kind == "categorical":
303
+ vocab = self._sample_categories.get(name, np.empty(0, dtype=object))
304
+ out[:, j] = encode_labels(_labels(raw), raw.missing, vocab)
305
+ is_categorical.append(True)
306
+ continue
307
+ if raw.hint == "datetime":
308
+ column = (
309
+ to_nanoseconds(raw.values).view(np.int64).astype(np.float64) / 1e9
310
+ )
311
+ else:
312
+ try:
313
+ column = np.asarray(raw.values, dtype=np.float64)
314
+ except (TypeError, ValueError):
315
+ raise ValueError(
316
+ f"Column {name!r} of X was numeric during fit and is not now."
317
+ ) from None
318
+ column = np.where(raw.missing, np.nan, column)
319
+ out[:, j] = column
320
+ is_categorical.append(False)
321
+ return out, is_categorical
322
+
323
+ # ----------------------------------------------------------- expressions
324
+ def _build_catalog(
325
+ self,
326
+ session: Session,
327
+ database: Database,
328
+ resolved: ResolvedPopulation,
329
+ *,
330
+ max_relationship_depth: int,
331
+ primitives: str | Sequence[str],
332
+ max_categories: int,
333
+ category_primitives: Sequence[str],
334
+ conditional: bool = False,
335
+ windows: Sequence[Any] | None = None,
336
+ max_lookup_depth: int = 0,
337
+ ) -> list[Expression]:
338
+ """Unconditioned expressions plus one-category conditions from vocabularies.
339
+
340
+ Category conditions are on the categorical columns of the last table of
341
+ each path and, up to ``max_lookup_depth`` many-to-one hops away, of the
342
+ tables its rows look up (see :func:`~sklink.expressions.enumerate_lookups`).
343
+ With ``conditional``, the numeric columns of the last table are also
344
+ aggregated with ``mean`` and ``sum`` (those of them that a list of
345
+ ``primitives`` names) over the rows of each category of the columns
346
+ whose reachable rows have at most ``max_categories`` categories (a
347
+ complete vocabulary), which bounds the catalog on tables with many
348
+ high-cardinality columns.
349
+ """
350
+ assert self.entity is not None
351
+ schema = database.schema
352
+ visibility = self._visibility()
353
+ temporal = visibility.time
354
+ conditional_primitives = [
355
+ name
356
+ for name in ("mean", "sum")
357
+ if isinstance(primitives, str) or name in primitives
358
+ ]
359
+ conditional = conditional and bool(conditional_primitives)
360
+ base = enumerate_expressions(
361
+ schema,
362
+ entity=self.entity,
363
+ max_relationship_depth=max_relationship_depth,
364
+ primitives=primitives,
365
+ allow_reverse_paths=visibility.allow_reverse_paths,
366
+ temporal=temporal,
367
+ max_lookup_depth=max_lookup_depth,
368
+ )
369
+ extra: list[Expression] = []
370
+ if max_categories > 0:
371
+ for path in enumerate_paths(
372
+ schema,
373
+ entity=self.entity,
374
+ max_relationship_depth=max_relationship_depth,
375
+ allow_reverse_paths=visibility.allow_reverse_paths,
376
+ ):
377
+ if path.is_to_one:
378
+ continue
379
+ table = schema.table(path.last_table(self.entity))
380
+ numeric = [
381
+ c.name
382
+ for c in table.feature_columns()
383
+ if c.semantic_type == "numeric"
384
+ ]
385
+ lookups = [
386
+ Path(),
387
+ *enumerate_lookups(
388
+ schema,
389
+ path,
390
+ entity=self.entity,
391
+ max_relationship_depth=max_relationship_depth,
392
+ max_lookup_depth=max_lookup_depth,
393
+ allow_reverse_paths=visibility.allow_reverse_paths,
394
+ ),
395
+ ]
396
+ categorical = [
397
+ (lookup, column)
398
+ for lookup in lookups
399
+ for column in schema.table(
400
+ lookup.last_table(table.name)
401
+ ).feature_columns()
402
+ if column.semantic_type == "categorical"
403
+ ]
404
+ for lookup, column in categorical:
405
+ # One label more tells whether the vocabulary is complete.
406
+ labels = session.column_stats(
407
+ path,
408
+ column.name,
409
+ resolved,
410
+ visibility,
411
+ kind="top_k",
412
+ k=max_categories + 1 if conditional else max_categories,
413
+ **lookup_keywords(lookup),
414
+ ).tolist()
415
+ complete = len(labels) <= max_categories
416
+ for label in labels[:max_categories]:
417
+ condition = (Condition(column.name, "==", label, lookup),)
418
+ for name in category_primitives:
419
+ extra.append(Aggregate(name, path, None, condition))
420
+ if conditional and complete:
421
+ for other in numeric:
422
+ extra.extend(
423
+ Aggregate(name, path, other, condition)
424
+ for name in conditional_primitives
425
+ )
426
+ catalog = base + extra
427
+ if windows:
428
+ if not temporal:
429
+ raise ValueError(
430
+ "windows need temporal mode: set time=... on the estimator."
431
+ )
432
+ windowed: list[Expression] = []
433
+ for duration in windows:
434
+ window = Window(duration)
435
+ for expression in catalog:
436
+ if not isinstance(expression, Aggregate):
437
+ continue
438
+ table = schema.table(expression.path.last_table(self.entity))
439
+ if (
440
+ table.time_column is None
441
+ or get_primitive(expression.primitive).requires_time
442
+ ):
443
+ continue
444
+ windowed.append(
445
+ Aggregate(
446
+ expression.primitive,
447
+ expression.path,
448
+ expression.column,
449
+ expression.where,
450
+ window,
451
+ expression.params,
452
+ )
453
+ )
454
+ catalog += windowed
455
+ # FE-05: attributes and aggregates by path depth, then canonical name;
456
+ # conditions and windows must not end up after deeper expressions.
457
+ return sorted(catalog, key=lambda e: (e.path.depth, e.name))
458
+
459
+ @staticmethod
460
+ def _filter_catalog(
461
+ catalog: list[Expression],
462
+ entity: str,
463
+ include: Sequence[str] | None,
464
+ exclude: Sequence[str] | None,
465
+ ) -> list[Expression]:
466
+ def matches(expression: Expression, patterns: Sequence[str]) -> bool:
467
+ names = {expression.name}
468
+ names |= (
469
+ set(expression.tables(entity))
470
+ if not isinstance(expression, SampleFeature)
471
+ else set()
472
+ )
473
+ names |= set(expression.relationships())
474
+ return any(fnmatch.fnmatchcase(n, p) for p in patterns for n in names)
475
+
476
+ if include is not None:
477
+ catalog = [
478
+ e
479
+ for e in catalog
480
+ if isinstance(e, SampleFeature) or matches(e, include)
481
+ ]
482
+ if exclude is not None:
483
+ catalog = [e for e in catalog if not matches(e, exclude)]
484
+ return catalog
485
+
486
+ def _schema_used(
487
+ self, database: Database, expressions: Sequence[Expression]
488
+ ) -> Schema:
489
+ """Part of the schema the fitted model reads: tables, columns, links."""
490
+ assert self.entity is not None
491
+ full = database.schema
492
+ columns: dict[str, set[str]] = {
493
+ self.entity: set(full.table(self.entity).primary_key or ())
494
+ }
495
+ relationships: set[str] = set()
496
+ for expression in expressions:
497
+ if isinstance(expression, SampleFeature):
498
+ continue
499
+ for read in expression.tables(self.entity):
500
+ columns.setdefault(read, set())
501
+ for read, column in expression.columns(self.entity):
502
+ columns[read].add(column)
503
+ relationships |= expression.relationships()
504
+ for name in sorted(relationships): # set order varies between runs
505
+ rel = full.relationship(name)
506
+ columns.setdefault(rel.child_table, set()).update(rel.child_columns)
507
+ columns.setdefault(rel.parent_table, set()).update(rel.parent_columns)
508
+ tables = []
509
+ for table_name, used in columns.items():
510
+ table = full.table(table_name)
511
+ time_column = table.time_column if self.time is not None else None
512
+ if time_column is not None:
513
+ used.add(time_column)
514
+ tables.append(
515
+ TableSchema(
516
+ name=table_name,
517
+ columns=tuple(c for c in table.columns if c.name in used),
518
+ primary_key=table.primary_key,
519
+ time_column=time_column,
520
+ excluded=frozenset(),
521
+ )
522
+ )
523
+ return Schema(tables, [full.relationship(r) for r in sorted(relationships)])
524
+
525
+ def _output_types(
526
+ self, database: Database | None, expressions: Sequence[Expression]
527
+ ) -> list[str]:
528
+ schema = database.schema if database is not None else None
529
+ out = []
530
+ for expression in expressions:
531
+ if isinstance(expression, SampleFeature):
532
+ out.append("numeric")
533
+ else:
534
+ out.append(output_type(expression, schema, self.entity))
535
+ return out
sklink/_compat.py ADDED
@@ -0,0 +1,63 @@
1
+ """The single place for code that depends on the version of a dependency.
2
+
3
+ Only public scikit-learn API is used here, as everywhere else. Each version branch
4
+ states the minimum version at which it can be removed.
5
+ """
6
+
7
+ import os
8
+ from collections.abc import Callable
9
+ from typing import Any, cast
10
+
11
+ __all__ = [
12
+ "CALLBACK_FRAME_PREFIXES",
13
+ "HAS_CALLBACKS",
14
+ "CallbackSupportMixin",
15
+ "with_callbacks",
16
+ ]
17
+
18
+ # Callbacks (``sklearn.callback``) are experimental and new in scikit-learn 1.9.
19
+ # On 1.8 the estimators have no ``set_callbacks``: scikit-learn tells whether an
20
+ # estimator supports callbacks by that method, so a method that could only raise
21
+ # would misreport it. The fit code calls the same protocol on every version; on
22
+ # 1.8 it does nothing. Remove the fallback when the minimum is 1.9.
23
+ try:
24
+ import sklearn.callback
25
+ from sklearn.callback import CallbackSupportMixin
26
+ from sklearn.callback import with_callbacks as sklearn_with_callbacks
27
+
28
+ HAS_CALLBACKS = True
29
+ # ``with_callbacks`` adds frames of scikit-learn between the user's call to
30
+ # ``fit`` and sklink; warnings skip them to point at the user's code.
31
+ CALLBACK_FRAME_PREFIXES: tuple[str, ...] = (
32
+ os.path.dirname(os.path.abspath(sklearn.callback.__file__)) + os.sep,
33
+ )
34
+
35
+ def with_callbacks[F: Callable[..., Any]](method: F) -> F:
36
+ """Tear the callbacks of ``fit`` down when it ends, even on error."""
37
+ return cast(F, sklearn_with_callbacks(method))
38
+
39
+ except ImportError: # scikit-learn 1.8
40
+ HAS_CALLBACKS = False
41
+ CALLBACK_FRAME_PREFIXES = ()
42
+
43
+ class _NullContext:
44
+ """Stands for a callback context when scikit-learn has no callbacks."""
45
+
46
+ def subcontext(self, *args: Any, **kwargs: Any) -> "_NullContext":
47
+ return self
48
+
49
+ def call_on_fit_task_begin(self, **kwargs: Any) -> "_NullContext":
50
+ return self
51
+
52
+ def call_on_fit_task_end(self, **kwargs: Any) -> bool:
53
+ return False
54
+
55
+ class CallbackSupportMixin: # type: ignore[no-redef]
56
+ """Callback protocol of the estimators, without callbacks."""
57
+
58
+ def _init_callback_context(self, *args: Any, **kwargs: Any) -> Any:
59
+ return _NullContext()
60
+
61
+ def with_callbacks[F: Callable[..., Any]](method: F) -> F:
62
+ """Return ``method`` unchanged: there are no callbacks to tear down."""
63
+ return method