diff --git a/.github/workflows/build-check.yml b/.github/workflows/build-check.yml index 5507358..05bc1e9 100644 --- a/.github/workflows/build-check.yml +++ b/.github/workflows/build-check.yml @@ -22,7 +22,7 @@ jobs: id: setup-python uses: actions/setup-python@v5 with: - python-version: "3.10" + python-version: "3.11" - name: Install Poetry run: pipx install poetry diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5d5412d..45baa10 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -30,7 +30,7 @@ jobs: id: setup-python uses: actions/setup-python@v5 with: - python-version: "3.10" + python-version: "3.11" - name: Install Poetry run: pipx install poetry @@ -64,7 +64,7 @@ jobs: id: setup-python uses: actions/setup-python@v5 with: - python-version: "3.10" + python-version: "3.11" - name: Install Poetry run: pipx install poetry @@ -95,7 +95,7 @@ jobs: id: setup-python uses: actions/setup-python@v5 with: - python-version: "3.10" + python-version: "3.11" - name: Install Poetry run: pipx install poetry @@ -127,7 +127,7 @@ jobs: fail-fast: false matrix: os: [ubuntu-latest, windows-latest, macos-latest] - python-version: ["3.10", "3.11", "3.12", "3.13"] + python-version: ["3.11", "3.12", "3.13"] steps: - uses: actions/checkout@v4 @@ -158,16 +158,16 @@ jobs: run: poetry run pytest tests/ -v minimum-deps: - name: Minimum dependencies (Python 3.10) + name: Minimum dependencies (Python 3.11) runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-python@v5 with: - python-version: "3.10" + python-version: "3.11" - name: Install with minimum supported dependency series run: >- - python -m pip install . pytest pytest-cov + python -m pip install . pytest pytest-cov 'jsonschema>=4.26,<5' "numpy==1.24.4" "pandas==2.0.3" "scipy==1.10.1" "scikit-learn==1.6.0" - name: Run tests run: python -m pytest tests/ -q diff --git a/.github/workflows/publish-pypi.yml b/.github/workflows/publish-pypi.yml index ada08e2..0a0b5f9 100644 --- a/.github/workflows/publish-pypi.yml +++ b/.github/workflows/publish-pypi.yml @@ -44,7 +44,7 @@ jobs: id: setup-python uses: actions/setup-python@v5 with: - python-version: "3.10" + python-version: "3.11" - name: Install Poetry run: pipx install poetry diff --git a/.github/workflows/publish-testpypi.yml b/.github/workflows/publish-testpypi.yml index f50e178..cd5b48f 100644 --- a/.github/workflows/publish-testpypi.yml +++ b/.github/workflows/publish-testpypi.yml @@ -39,7 +39,7 @@ jobs: id: setup-python uses: actions/setup-python@v5 with: - python-version: "3.10" + python-version: "3.11" - name: Install Poetry run: pipx install poetry @@ -107,7 +107,7 @@ jobs: - name: Set up Python uses: actions/setup-python@v5 with: - python-version: "3.10" + python-version: "3.11" - name: Install from TestPyPI (with retry) run: | diff --git a/CHANGELOG.md b/CHANGELOG.md index 2768894..4d4af5a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,15 @@ This project adheres to [Semantic Versioning](https://semver.org/) and uses Going forward, this file is updated automatically by `cz bump` on each release. +## Unreleased + +### Removed + +- Python 3.10 support. PreTab 1.1 requires Python 3.11 to 3.13 + (`>=3.11,<3.14`), matching DeepTab 2.1. PreTab 1.0.0 is the final release + for Python 3.10; install `pretab<1.1` if you cannot upgrade Python. See the + [migration guidance](docs/getting_started/installation.md#python-310-migration). + ## v1.0.0 (2026-09-06) First stable release, consolidating the release-candidate cycle (`rc1`-`rc5`) below into one diff --git a/README.md b/README.md index e6c38ce..5e54a46 100644 --- a/README.md +++ b/README.md @@ -26,10 +26,13 @@ embeddings) is also available as a standalone transformer. Because it speaks the API, PreTab drops straight into `Pipeline` and `ColumnTransformer` workflows and accepts any sklearn transformer alongside its own. -Beyond the transformers themselves, every fitted representation is self-describing: it -reports per-output-column lineage, guards supervised methods against leakage, serializes to -a portable versioned spec, and can be extended with your own representations through a -public, discoverable protocol. +Fitted preprocessors report which inputs produced each output column. PreTab warns when +supervised transformers are fitted outside a pipeline or cross-validation context. Supported +fitted state can be exported to a versioned JSON spec for restoration in the same environment. +Load specs only from trusted sources. You can also register your own representations. + +See [What's new in PreTab 1.1](https://pretab.readthedocs.io/en/latest/getting_started/overview.html#whats-new-in-pretab-1-1) +for release highlights and upgrade guidance. ## Why PreTab? @@ -63,16 +66,17 @@ import pandas as pd from pretab import Preprocessor +rng = np.random.default_rng(0) df = pd.DataFrame({ - "age": np.random.randint(18, 65, size=100), - "income": np.random.normal(60_000, 15_000, size=100).astype(int), - "city": np.random.choice(["Berlin", "Munich", "Hamburg"], size=100), - "experience": np.random.randint(0, 40, size=100), + "age": rng.integers(18, 65, size=100), + "income": rng.normal(60_000, 15_000, size=100).astype(int), + "city": rng.choice(["Berlin", "Munich", "Hamburg"], size=100), + "experience": rng.integers(0, 40, size=100), }) -y = np.random.randn(100) +y = rng.standard_normal(100) # Global strategies: PLE for numerics, integer codes for categoricals -preprocessor = Preprocessor(numerical_method="ple", categorical_method="int") +preprocessor = Preprocessor(numerical_method="ple", categorical_method="int", task="regression") X = preprocessor.fit_transform(df, y) # single stacked array, one row per sample @@ -175,11 +179,14 @@ pip install pretab ```bash pip install "pretab[embeddings]" # adds sentence-transformers, for the `pretrained` strategy pip install "pretab[lightgbm]" # adds lightgbm, for placement_strategy="lightgbm" -pip install "pretab[all]" # both of the above +pip install "pretab[polars]" # adds Polars for eager DataFrame input +pip install "pretab[all]" # all three extras ``` > **Note:** The core install has no heavy dependencies. Each extra is opt-in and only -> needed if you use the corresponding strategy. PreTab requires Python 3.10 to 3.13. +> needed if you use the corresponding strategy. PreTab 1.1 requires Python 3.11 to 3.13. +> Python 3.10 users must stay on `pretab<1.1`; see the +> [migration guidance](docs/getting_started/installation.md#python-310-migration). **From source:** @@ -204,29 +211,22 @@ preprocessor = Preprocessor( feature_preprocessing={ "age": "ple", "income": "rbf", - "experience": "quantile", + "experience": {"method": "quantile", "params": {"n_quantiles": len(df)}}, "city": "one-hot", }, task="regression", ) -X_array = preprocessor.fit_transform(df, y) # single stacked ndarray -X_dict = preprocessor.transform(df, return_array=False) # {"num_age": ..., "cat_city": ...} +X_array = preprocessor.fit_transform(df, y) +X_dict = preprocessor.transform(df, return_array=False) -preprocessor.get_feature_info(verbose=True) # inspect resolved strategies +assert X_array.shape == (100, 18) +assert X_dict["cat_city"].shape == (100, 3) +assert len(preprocessor.get_feature_lineage()) == X_array.shape[1] ``` -`get_feature_info(verbose=True)` prints the resolved layout so you can confirm every column -at a glance: - -```text -feature kind pipeline dim cats -------------------------------------------------------------------- -age numerical imputer -> minmax -> ple 7 - -income numerical imputer -> minmax -> rbf 7 - -experience numerical imputer -> minmax -> quantile 1 - -city categorical imputer -> onehot -> to_float 3 3 -``` +The three cities produce three one-hot columns. `get_feature_lineage()` maps each output +column back to its source feature and representation. > **Note:** `transform` returns a single stacked array by default, so a `Preprocessor` drops > straight into a plain `sklearn.pipeline.Pipeline`. Pass `output_structure="blocks"` (or diff --git a/docs/api/preprocessor.rst b/docs/api/preprocessor.rst index f7e5c48..d5f951d 100644 --- a/docs/api/preprocessor.rst +++ b/docs/api/preprocessor.rst @@ -1,9 +1,10 @@ Preprocessor ============ -The high-level entry point. :class:`~pretab.Preprocessor` reads a ``DataFrame``, -detects feature types, resolves a per-column representation from a single -configuration, and produces model-ready output with full lineage. +The high-level entry point. :class:`~pretab.Preprocessor` accepts a pandas +DataFrame, an eager Polars DataFrame, a NumPy array, or a dictionary of columns. +It detects feature types, resolves per-column and grouped representations from a +single configuration, and produces model-ready output with full lineage. .. currentmodule:: pretab @@ -13,9 +14,184 @@ configuration, and produces model-ready output with full lineage. Preprocessor +Task and target validation +-------------------------- + +``task`` is ``"regression"`` by default. Set it to ``"classification"`` for class +labels. ``task_validation`` is keyword-only: ``"off"`` (default) skips the +consistency check, ``"warn"`` emits ``ConfigWarning``, and ``"raise"`` raises +``InvalidParamError`` before fitting the representations. + +The check applies to supported single-output targets when a fitted representation +uses ``y`` for placement. It does not infer the task, change the target, or extend +the supported target shapes. Turning it off does not disable task-string validation +or leakage warnings. See :doc:`../core_concepts/resolution_and_placement` for +examples and the limits of the diagnostic. + +Representation values +--------------------- + +:class:`~pretab.RepresentationConfig` stores a representation request with +read-only, detached parameters and JSON-compatible dictionary conversion. +Constructing the value does not fit an estimator or resolve method aliases. +Pass it as a value in ``Preprocessor(feature_preprocessing={...})``; strings +and mappings with a ``method`` key are accepted there as well. + +.. autosummary:: + :toctree: _autosummary + :nosignatures: + + RepresentationConfig + +Fields and conversion +~~~~~~~~~~~~~~~~~~~~~ + +``method`` + Required method name or alias. Validation against the selected method + happens during configuration resolution or fitting. + +``output_dim`` + Positive requested width, subject to the representation's constraints. + An explicit local width suppresses inherited adaptive sizing unless + local ``adaptive=True`` also opts in. + +``target_aware``, ``placement_strategy`` + Local target-use and placement controls, where the method supports them. + +``adaptive``, ``min_output_dim``, ``max_output_dim`` + Local adaptive sizing and bounds. Bounds must be positive integers or + ``None`` where accepted. Explicit bounds with fixed sizing are invalid. + +``params`` + Family-specific constructor options, such as ``{"gamma": 0.5}`` for + RBF. Common fields belong at the top level, not in this mapping. + One-hot entries accept encoder options such as ``categories``, ``drop``, + ``handle_unknown``, and ``sparse_output``. For example, + ``{"method": "one-hot", "params": {"drop": "first", "sparse_output": False}}`` + drops one category and requests dense encoding. Encoder ``dtype`` values + must be portable, such as ``"float32"``, rather than NumPy scalar classes. + Use the preprocessor's ``dtype`` to control the final output dtype; + encoder settings do not bypass subsequent output conversion. + +``name`` + Optional nonempty metadata label, default ``None``. It does not rename + input columns or fitted output features. + +Omitted common controls retain ``UNSET`` until resolution. An explicit local +value takes precedence over an applicable constructor-wide value; ``None`` +is an explicit value only for fields that accept it, not an inheritance marker. +Imputation, scaling, missing indicators, and output formatting remain run-wide. + +Nested ``params`` values may contain strings, booleans, integers, finite floats, +``None``, sequences, and mappings with string keys. Construction copies them +into read-only storage. Callables, arbitrary objects, sets, nonfinite floats, +and circular references are rejected. + +``to_dict()`` returns detached dict/list containers, omits ``UNSET`` fields, +and retains explicit ``None`` values. It preserves the requested method +spelling; it does not resolve an alias. The result can be passed through +``json.dumps`` / ``json.loads`` and reconstructed with ``from_dict()``. +``from_dict()`` also accepts family parameters beside ``method`` and collects +them under ``params``. Supplying the same option in both places is an error, +even when the values agree. + +.. note:: + + This is a value object, not a scikit-learn estimator. It has no fitted state + or ``set_params`` method. Replace an entry through the containing + preprocessor's ``set_params(feature_preprocessing=...)``, or through + ``pre__feature_preprocessing`` when its pipeline step is named ``pre``. + The replacement is used by the next fit; it does not refit automatically. + Frozen preprocessors reject configuration replacement. + +Feature groups +-------------- + +:class:`~pretab.FeatureGroup` is an immutable request with three fields: +``name``, ordered ``columns``, and ``representation``. The representation accepts +a method string, mapping, or :class:`~pretab.RepresentationConfig`. Pass an ordered +sequence of these values to ``Preprocessor(feature_groups=...)``, or use a mapping +from group names to dictionaries containing ``columns`` and ``representation``. + +.. autosummary:: + :toctree: _autosummary + :nosignatures: + + FeatureGroup + +The supported group methods are ``tensorspline`` and ``tprs``, each with at least +two detected numerical inputs. Sources are exclusive: they cannot overlap another +group or an explicit per-feature override. Local representation settings take +precedence over applicable constructor-wide controls. The value itself neither +fits an estimator nor resolves method aliases. + +Fitted groups appear once as ``group_`` in block output and ``output_dims_``. +Output names and lineage retain group identity and source order. Joint basis width +and raw missing-state columns count together for output budgets. Ungrouped numerical +blocks precede groups in declaration order; categorical blocks follow them. + +See the :doc:`multivariate tutorial <../tutorials/multivariate_features>` for +executable declarations, block widths and trusted-spec replay. Frozen preprocessors +reject group replacement; otherwise ``set_params(feature_groups=...)`` changes +the request without refitting the existing representation. + +Requested and resolved settings +------------------------------- + +``get_params()`` preserves the raw constructor arguments, including caller-owned +override mappings. Raw mapping edits before fit remain observable. Typed values +detach on construction; raw representation settings detach during normalization +and fitting. + +:meth:`~pretab.Preprocessor.get_resolved_config` returns a detached current-request +dict, retaining the existing outer keys and expanding presets. Declared overrides +become canonical method mappings with applicable inherited controls and family +parameters. It does not enumerate undeclared columns, validate actual column +existence or detected kind before fit, or report learned widths or knot state. +Reading it never fits or transforms data. After fit or freeze it still describes +the current request, not the last successful fit. Use ``output_dims_``, +``total_output_dim_``, and :meth:`~pretab.Preprocessor.get_feature_info` for fitted +results. + +Value construction validates field types and portable data. Resolution additionally +validates method names, option applicability, and target/placement combinations; +invalid feature declarations report their configuration path. Actual input checks +belong to fitting. + +See the :doc:`configuration guide <../core_concepts/configuration>` for the +precedence table and three executable examples. Supported legacy string +configuration needs no syntax change, and can be mixed with structured entries. + Configuration, output, and reproducibility ------------------------------------------ +Fitted preprocessors with supported state using string, mapping, or +:class:`~pretab.RepresentationConfig` entries can be saved with +:meth:`~pretab.Preprocessor.to_spec` and restored with +:meth:`~pretab.Preprocessor.from_spec` in the same environment. Restored names, +lineage, widths, output values, and fingerprints retain the fitted state, +including adaptive sizing and separate missing indicators. Representation +summaries describe the representation itself, excluding separate indicators; +output budgets and reported output dimensions include those indicators. + +Specs retain schema version 1. ``params`` describes the current constructor +requests; ``resolved_config``, when present, describes the last successful fit. +The reader restores the encoded ``state`` rather than fitting from either set of +settings. See :ref:`portable-serialization` for the field reference, reading +legacy specs, downgrade limits, and when to use pickle instead. + +Registration does not enable spec persistence. ``to_spec()``, ``fingerprint_``, +and ``reproducibility_report()`` raise ``PretabSerializationError`` on unsupported +estimator state, including nested estimators. File export raises before opening +the destination. Use supported built-in representations for JSON replay, or a +trusted pickle or joblib checkpoint in a matching environment if all components +support it. + +.. warning:: + + Load specs only from trusted sources. Dependency versions recorded in a + spec do not guarantee compatibility with a different environment. + Supporting types returned or consumed by the preprocessor. .. autosummary:: diff --git a/docs/api/representations.rst b/docs/api/representations.rst index 2b7f8b6..42ac46d 100644 --- a/docs/api/representations.rst +++ b/docs/api/representations.rst @@ -35,6 +35,15 @@ Multivariate splines Canonical import: ``pretab.expansion.spline.multivariate``. +Typed spline penalties +---------------------- + +.. autoclass:: pretab.PenaltySpec + :members: matrix, to_summary + +The :doc:`spline guide <../representations/spline_expansions>` lists the supported +accessors and shows how to add a penalty to a downstream loss. + Functional expansions ---------------------- diff --git a/docs/api/search_and_cross_fitting.rst b/docs/api/search_and_cross_fitting.rst index 6b3f299..d094078 100644 --- a/docs/api/search_and_cross_fitting.rst +++ b/docs/api/search_and_cross_fitting.rst @@ -12,6 +12,13 @@ Representation search Cross-validate a downstream estimator over candidate numerical methods and refit the best one. +Classifier searches use ``task="classification"`` for preprocessing unless +``preprocessor_params`` specifies ``task``. The search's keyword-only +``task_validation`` checks the downstream classifier or regressor task and active +candidate placement tasks. A candidate's own policy in +``preprocessor_params["task_validation"]`` is independent. Turning one off does +not turn the other off. + .. autosummary:: :toctree: _autosummary :nosignatures: @@ -24,6 +31,22 @@ Cross-fitting Produce out-of-fold training features from a supervised transformer while transforming new data with an all-data model. +A wrapped :class:`~pretab.Preprocessor` must use ``output_structure="matrix"``. +Cross-fitting accepts dense arrays, sparse matrices, and DataFrames as output, +but not dictionaries of feature blocks. Each fold must match the all-data +model's output width and, for DataFrames, its column names and order. + +The wrapper's keyword-only ``task_validation`` checks its splitter's configured +task. It does not replace the wrapped estimator's policy. If a later pipeline +step needs transformed inputs to determine target use, it checks when those +inputs are available, before training its representations and before any folds. + +Both wrappers accept ``"off"`` (default), ``"warn"`` (``ConfigWarning``), and +``"raise"`` (``InvalidParamError``). Matching checks for the same task, mode, +target and use need not repeat in the folds of one fit. An independent fit checks +again. See :doc:`../core_concepts/resolution_and_placement` for policy selection, +suppression and target-type limits. + .. autosummary:: :toctree: _autosummary :nosignatures: diff --git a/docs/core_concepts/configuration.md b/docs/core_concepts/configuration.md index 5261fdb..a22feb3 100644 --- a/docs/core_concepts/configuration.md +++ b/docs/core_concepts/configuration.md @@ -1,15 +1,15 @@ # Configuration The `Preprocessor` is configured through a small, predictable set of parameters. This page -covers the four ways to express intent: global defaults, per-feature overrides, presets, and +covers global defaults, per-feature overrides, feature groups, presets, and reading back the resolved configuration. The mechanics of width and placement live in [Resolution and placement](resolution_and_placement.md), and target usage in [Target awareness](target_awareness.md). ## Global defaults -The simplest configuration sets one strategy for every numerical column and one for every -categorical column. +The simplest configuration sets one strategy for every ungrouped numerical column and one +for every categorical column. ```python from pretab import Preprocessor @@ -23,6 +23,19 @@ pre = Preprocessor( The defaults are `numerical_method="ple"` and `categorical_method="int"`. The full list of strategy strings is in the [representation comparison](../representations/comparison_table.md). +## Supported inputs + +| Input | Column matching | Extra for input | +| ---------------------------------- | ----------------------------------------------------------- | --------------------------------------------------------------------------- | +| `pandas.DataFrame` | By column label | None | +| `dict` of columns | By dictionary key | None | +| 2D `numpy.ndarray` or list of rows | By position; names such as `feature_0` are generated at fit | None | +| Eager `polars.DataFrame` | By column name | [Polars extra](../getting_started/installation.md); PyArrow is not required | +| `polars.LazyFrame` | Not supported; call `collect()` to get an eager frame | Not applicable | + +Named inputs match by label after fitting on named data. When either training +or inference uses a positional input, keep column order and width consistent. + ## NumPy array input `Preprocessor` also accepts a plain `numpy.ndarray`, not just a `DataFrame`. Columns are @@ -76,23 +89,61 @@ float, as in pandas), and `String` (`Utf8` on older Polars), `Categorical`, `Enu categorical. Polars nulls become missing values, so imputation and `missing_policy` treat them like `NaN` in a pandas frame. The conversion does not need `pyarrow`. +### Check parity with pandas + +Build the equivalent Polars frame from a dictionary of lists rather than using +`pl.from_pandas`, so the example works without PyArrow. The same configuration +produces identical features for this data, even if you reorder named columns at transform time. + +```python +import numpy as np +import pandas as pd +import polars as pl +from pretab import Preprocessor + +X = pd.DataFrame({ + "age": [25.0, None, 47.0, 33.0], + "city": ["Paris", "Rome", "Paris", "Rome"], + "active": [True, False, True, False], +}) +X_polars = pl.DataFrame(X.to_dict(orient="list")) +options = { + "numerical_method": "minmax", + "categorical_method": "one-hot", + "missing_policy": "impute_with_indicator", +} +from_pandas = Preprocessor(**options).fit(X) +from_polars = Preprocessor(**options).fit(X_polars) + +np.testing.assert_array_equal(from_polars.get_feature_names_out(), from_pandas.get_feature_names_out()) +np.testing.assert_array_equal( + from_polars.transform(X_polars.select("active", "city", "age")), + from_pandas.transform(X), +) +``` + +### Pass Polars through a scikit-learn pipeline + ```python import polars as pl from sklearn.impute import SimpleImputer from sklearn.pipeline import Pipeline +from pretab import Preprocessor X = pl.DataFrame({"age": [25.0, None, 47.0, 33.0], "income": [3.1e4, 5.2e4, None, 4.4e4]}) y = [0.0, 1.0, 1.0, 0.0] pipe = Pipeline([("impute", SimpleImputer()), ("pretab", Preprocessor(numerical_method="minmax"))]) pipe.set_output(transform="polars") -pipe.fit_transform(X, y) # a polars.DataFrame with columns num_age, num_income +assert isinstance(pipe.fit_transform(X, y), pl.DataFrame) ``` ## Per-feature overrides Columns rarely want identical treatment. The `feature_preprocessing` dict assigns a strategy to individual columns and takes precedence over the global defaults for those columns. +Each value can be a method string, a mapping with a `method` key, or a +{class}`~pretab.RepresentationConfig`. You can mix these forms in the same dict. ```python pre = Preprocessor( @@ -113,12 +164,22 @@ feature-type detection. ### Columns not listed in `feature_preprocessing` -`feature_preprocessing` only overrides the columns it names. Any numerical column left out -falls back to `numerical_method`, and any categorical column left out falls back to +`feature_preprocessing` only overrides the columns it names. Any ungrouped numerical column +left out falls back to `numerical_method`, and any categorical column left out falls back to `categorical_method`. This is real method resolution, not just a logging detail: the fallback column is fit with the global default's transformer, exactly as if you had listed it yourself. ```python +import pandas as pd + +df = pd.DataFrame({ + "age": np.linspace(25.0, 63.0, 20), + "income": np.linspace(25_000.0, 90_000.0, 20), + "city": ["Oslo", "Lima"] * 10, + "region": ["north", "south"] * 10, +}) +y = 0.4 * df["age"] + 0.0002 * df["income"] + pre = Preprocessor( numerical_method="bspline", # applies to every numerical column not listed below feature_preprocessing={ @@ -126,6 +187,12 @@ pre = Preprocessor( "city": "one-hot", }, ).fit(df, y) + +numerical, categorical, _ = pre.get_feature_info(verbose=False) +assert numerical["age"]["preprocessing"].endswith("bspline") +assert numerical["income"]["preprocessing"].endswith("rbf") +assert categorical["city"]["dimension"] == 2 +assert categorical["region"]["dimension"] == 1 ``` | Column | Kind | Listed in `feature_preprocessing`? | Resolved method | @@ -142,6 +209,201 @@ Don't infer the resolved method per column from the constructor arguments alone. [Fit-time logging](outputs_and_inspection.md#fit-time-logging). ``` +## Feature groups + +Use `feature_groups` when several numerical columns need one joint representation. +It accepts an ordered sequence of {class}`~pretab.FeatureGroup` values or an ordered +mapping from group names to `columns` and `representation`. The supported group +methods are `tensorspline` and `tprs`; they are not per-column `numerical_method` +choices. Group settings use the same {class}`~pretab.RepresentationConfig` values +and representation mappings as per-feature settings. + +A group exclusively owns at least two detected numerical columns. Groups cannot +overlap or claim columns with explicit `feature_preprocessing` entries. Boolean +and categorical columns are not eligible. Use `treat_all_integers_as_numerical=True` +when integer sources should bypass cardinality-based categorical detection. +Group declaration order controls block order; ordered source labels control +the group's input axes. Read joint widths from `output_dims_["group_"]` +after fit, including any raw missing-state columns. + +The [multivariate tutorial](../tutorials/multivariate_features.md#grouped-preprocessing-with-preprocessor) +covers typed and mapping declarations, tensor versus thin-plate sizing, output +budgets, block-based model inputs, and fitted-state replay. + +## Structured per-feature configuration + +The first three examples use the same training data and a scikit-learn regression pipeline. +`income` is deliberately left out of each override map, so it uses the global `"none"` +method and contributes one column. + +```python +import json + +import numpy as np +import pandas as pd +from sklearn.base import clone +from sklearn.linear_model import Ridge +from sklearn.pipeline import Pipeline + +from pretab import Preprocessor, RepresentationConfig + +frame = pd.DataFrame({ + "age": np.linspace(18.0, 70.0, 40), + "income": np.linspace(25000.0, 90000.0, 40), + "city": ["Oslo", "Lima"] * 20, +}) +target = 0.4 * frame["age"] + 0.0002 * frame["income"] +common = { + "numerical_method": "none", + "output_dim": 7, + "target_aware": False, + "placement_strategy": "uniform", + "scaling": "none", + "random_state": 17, +} +``` + +### Method strings + +Strings select the representation and retain the applicable constructor-wide controls. +Here `"RBF"` is an alias for `"rbf"`, and `"OHE"` selects one-hot encoding. + +```python +legacy = Preprocessor( + **common, + feature_preprocessing={"age": "RBF", "city": "OHE"}, +) +legacy_model = Pipeline([("pre", legacy), ("model", Ridge())]).fit(frame, target) + +assert legacy.output_dims_ == {"age": 7, "income": 1, "city": 2} +assert legacy.transform(frame, return_array=True).shape == (40, 10) +assert legacy_model.predict(frame).shape == (40,) +``` + +### Mappings with local settings + +A mapping adds controls for that feature. `age` requests three RBF outputs and a local +`gamma`; it does not change `income` or the two learned city categories. + +```python +mapped = Preprocessor( + **common, + feature_preprocessing={ + "age": {"method": "rbf", "output_dim": 3, "params": {"gamma": 0.5}}, + "city": "one-hot", + }, +) +mapped_model = Pipeline([("pre", mapped), ("model", Ridge())]).fit(frame, target) +report = mapped.get_resolved_config() + +assert report["output_dim"] == 7 +assert report["feature_preprocessing"]["age"]["output_dim"] == 3 +assert report["feature_preprocessing"]["age"]["params"]["gamma"] == 0.5 +assert mapped.output_dims_ == {"age": 3, "income": 1, "city": 2} +assert mapped.transform(frame, return_array=True).shape == (40, 6) +assert mapped_model.predict(frame).shape == (40,) +``` + +Family parameters can also appear beside `method`, for example +`{"method": "rbf", "gamma": 0.5}`. Normalization collects them under `params`. +Do not supply the same parameter in both places. Common controls such as `output_dim` +belong at the top level, not inside `params`. + +### Immutable values and JSON + +`RepresentationConfig` detaches its nested inputs immediately. Its dictionary form can be +stored as JSON, reconstructed, and used with `clone` and `Pipeline`. + +```python +params = {"gamma": 0.5} +value = RepresentationConfig(method="RBF", output_dim=3, params=params) +params["gamma"] = 9.0 +assert value.params["gamma"] == 0.5 + +payload = json.loads(json.dumps(value.to_dict(), allow_nan=False)) +restored = RepresentationConfig.from_dict(payload) +assert restored == value + +typed = Preprocessor( + **common, + feature_preprocessing={"age": restored, "city": {"method": "OHE"}}, +) +fresh = clone(typed) +assert fresh.get_params() == typed.get_params() +typed_model = Pipeline([("pre", fresh), ("model", Ridge())]).fit(frame, target) + +assert fresh.output_dims_ == {"age": 3, "income": 1, "city": 2} +np.testing.assert_array_equal( + fresh.transform(frame, return_array=True), + mapped.transform(frame, return_array=True), +) +assert typed_model.predict(frame).shape == (40,) +``` + +```{important} +Raw mappings passed to `Preprocessor` remain live constructor parameters, as required by +scikit-learn. Edits before fitting affect that fit. Normalization and fitting detach the +representation settings; editing a raw mapping afterward does not refit the learned +transformers. Use `RepresentationConfig` when the request itself should be immutable from +construction onward. Neither form changes an already fitted graph without another fit. +``` + +### Different widths for the same method + +Each column can use the same representation with a different width. With +`output_structure="blocks"`, numerical block keys have a `num_` prefix, while +`output_dims_` and `get_feature_info()` use the source column names. + +```python +import numpy as np +import pandas as pd + +from pretab import Preprocessor + +numeric_frame = pd.DataFrame({ + "age": np.linspace(18.0, 70.0, 80), + "income": np.linspace(25000.0, 90000.0, 80), + "tenure": np.linspace(0.0, 30.0, 80), +}) +widths = Preprocessor( + feature_preprocessing={ + "age": {"method": "rbf", "output_dim": 2}, + "income": {"method": "rbf", "output_dim": 3}, + "tenure": {"method": "rbf", "output_dim": 5}, + }, + target_aware=False, + placement_strategy="uniform", + scaling="none", + output_structure="blocks", +) +blocks = widths.fit_transform(numeric_frame) + +assert widths.output_dims_ == {"age": 2, "income": 3, "tenure": 5} +assert widths.total_output_dim_ == 10 +numerical, categorical, embeddings = widths.get_feature_info(verbose=False) +assert {name: info["dimension"] for name, info in numerical.items()} == widths.output_dims_ +assert categorical == embeddings == {} +names = widths.get_feature_names_out() +assert names.tolist() == [ + f"num_{feature}_rbf{index}" + for feature, width in widths.output_dims_.items() + for index in range(width) +] +assert {name: block.shape for name, block in blocks.items()} == { + "num_age": (80, 2), + "num_income": (80, 3), + "num_tenure": (80, 5), +} +np.testing.assert_array_equal( + np.hstack([blocks["num_age"], blocks["num_income"], blocks["num_tenure"]]), + widths.transform(numeric_frame, return_array=True), +) +``` + +The blocks contain two, three and five columns in source order. Their concatenation +matches the ten-column matrix returned by `return_array=True`. Size each input +block from the fitted dimensions, not the constructor-wide `output_dim`. + ## Presets Presets are transparent, named bundles of parameters for common intents. They set the same @@ -199,17 +461,27 @@ the preset's value for that knob, including `numerical_method` itself, for examp ## Reading the resolved configuration -Because global defaults, per-feature overrides, and presets interact, PreTab lets you read -back exactly what will be used. `get_resolved_config()` returns the fully resolved settings -as a plain dict. +`get_resolved_config()` returns a detached plain dict for the current request. Outer keys +retain the preset-expanded constructor settings. Each declared `feature_preprocessing` +entry becomes a mapping with its canonical method, applicable inherited controls, local +settings, and `params`. Omitted, inapplicable controls are not added. ```python pre = Preprocessor(preset="expanded", feature_preprocessing={"age": "bspline"}) pre.get_resolved_config() ``` -This is the authoritative answer to "what did my configuration actually become", and it is -useful in tests and reproducible experiments. +You can edit the returned dict, including nested containers, without changing the estimator. +The report includes only declared overrides, not a row for every input column. It can be read +before fitting; actual column existence and compatibility with detected feature kinds are +checked at fit time. + +```{note} +The report stays a current-request view after fitting or freezing. It is not a record of the +last fit, learned knots, or realized output widths. Changing a live raw request can change +the report while the fitted transformer continues to produce its original output. Use +`output_dims_`, `total_output_dim_`, and `get_feature_info()` for fitted results. +``` ## How the layers combine @@ -220,14 +492,39 @@ The resolution order is deterministic. Later layers win. 3. Explicit constructor arguments (`numerical_method`, `output_dim`, and so on). 4. Per-column `feature_preprocessing` entries, for the columns they name. +Within a structured entry, inheritance is per field, not an all-or-nothing replacement. + +| Setting | Effective choice | +| :------------------ | :--------------------------------------------------------------------------------------------------------------------------------------------------- | +| Method | The local `method`, otherwise the global method for the detected kind. | +| Common controls | Explicit local values win. Omitted values inherit constructor settings only when the method supports them; other defaults belong to the transformer. | +| Family `params` | Local parameters win over applicable inherited `degree`, `task`, or an explicit `random_state`. Other family defaults are left to the transformer. | +| Fixed local width | An explicit local `output_dim` disables inherited adaptive sizing unless that entry also explicitly sets `adaptive=True`. | +| Adaptive bounds | Omitted bounds inherit only when adaptive sizing is active. Explicit bounds with fixed sizing are rejected; unsupported controls are not forwarded. | +| Run-wide processing | Imputation, scaling, missing indicators, and output formatting remain constructor-wide settings, not representation parameters. | + +Omission is different from an explicit value. For example, a local +`params={"random_state": None}` overrides an inherited seed where the method accepts it. +Passing `None` is valid only for options that accept it; it does not mean "inherit". + ```{warning} -Configuration is validated at `fit` time, not silently coerced. An invalid combination, such -as a method that requires the target used with `target_aware=False`, or a `task` other than -`"regression"` / `"classification"`, raises a typed error. -This is intentional: it surfaces mistakes early rather than producing a quietly wrong -representation. +Value construction validates portable data and field types. `get_resolved_config()` and +`fit` also validate method names, supported options, and target/placement combinations. +Unknown keys and invalid methods raise typed errors with the feature's configuration path. +A local override does not make an invalid constructor-wide task or placement combination +valid. Actual input-column and feature-kind checks still require `fit`. ``` +## Using existing string configurations + +No syntax change is required for supported legacy configuration. Existing method strings, +aliases, global parameters, and per-column string overrides remain supported. Adopt mappings +or typed values only where you need local settings; other entries can stay strings. + +Equivalent fitted outputs do not imply that differently written requests have identical +fingerprints. Keep the requested configuration and dependency versions with your experiment; +see [Reproducibility](reproducibility.md) for fitted artifacts and upgrade precautions. + ## Key parameters at a glance The parameters below are the ones you reach for most. Each links to the page that explains it diff --git a/docs/core_concepts/missing_values.md b/docs/core_concepts/missing_values.md index 5a2ddbb..249f8ab 100644 --- a/docs/core_concepts/missing_values.md +++ b/docs/core_concepts/missing_values.md @@ -61,13 +61,13 @@ that cannot be fitted on a constant column. For finer control, `missing_policy` selects one of five behaviours for the whole preprocessor. -| Policy | Behaviour | -| ------------------------- | --------------------------------------------------------------------------------------------------- | -| `"error"` | Reject any missing value at `fit` and `transform`. | -| `"propagate"` | Pass missing values through to the transformer unchanged. | -| `"impute"` | Fill using the imputation parameters above. | -| `"impute_with_indicator"` | Impute and add a missing indicator column. | -| `"separate_state"` | Impute the basis, and add a dedicated `__missing` column that does not activate the ordinary basis. | +| Policy | Behaviour | +| ------------------------- | -------------------------------------------------------------------------------------- | +| `"error"` | Reject any missing value at `fit` and `transform`. | +| `"propagate"` | Pass missing values through to the transformer unchanged. | +| `"impute"` | Fill using the imputation parameters above. | +| `"impute_with_indicator"` | Impute and add a missing indicator column. | +| `"separate_state"` | Transform the imputed value as usual and add a dedicated `__missing` indicator column. | ```python pre = Preprocessor(missing_policy="separate_state") diff --git a/docs/core_concepts/outputs_and_inspection.md b/docs/core_concepts/outputs_and_inspection.md index 68f1989..acbc352 100644 --- a/docs/core_concepts/outputs_and_inspection.md +++ b/docs/core_concepts/outputs_and_inspection.md @@ -10,11 +10,23 @@ feature names, lineage, and the output budget. `fit_transform` and `transform` return a single stacked `numpy.ndarray` by default. Pass `output_structure="blocks"` (or `return_array=False` for a single call) to receive a dictionary that maps each feature to its transformed block instead, with keys prefixed -`num_` or `cat_`. +`num_` or `cat_`. A [feature group](configuration.md#feature-groups) has one block +with a `group_` prefix. ```python -X_array = pre.fit_transform(df, y) # one stacked ndarray -X_dict = Preprocessor(output_structure="blocks").fit_transform(df, y) # {"num_age": ..., "cat_city": ...} +import numpy as np +import pandas as pd +from pretab import Preprocessor + +df = pd.DataFrame({"age": [25, 40, 63], "city": ["A", "B", "A"]}) +y = [0.1, 0.9, 0.3] + +pre = Preprocessor(numerical_method="minmax", categorical_method="one-hot") +X_array = pre.fit_transform(df) +X_dict = pre.transform(df, return_array=False) + +assert X_array.shape == (3, 3) +assert set(X_dict) == {"num_age", "cat_city"} ``` ```{note} @@ -26,19 +38,20 @@ for feeding blocks to different model heads; pass `return_array` explicitly to o ### Example: one column expands into several -A single input column rarely maps to a single output column. Most numerical methods (splines, -feature maps, PLE) expand one feature into `output_dim` basis columns, so the matrix width -grows well beyond the number of input columns. A B-spline makes this concrete: `output_dim=6` -turns the one `age` column into 6 local basis functions, each capturing a different region of -its range. +Many numerical representations expand one input into several columns. A B-spline with +`output_dim=6` turns the `age` column into six local basis functions, each covering a +different part of its range. ```python -df = pd.DataFrame({"age": [25, 40, 63, 51]}) -y = [0.1, 0.9, 0.3, 0.6] - -pre = Preprocessor(numerical_method="bspline", output_dim=6, - target_aware=False, placement_strategy="quantile").fit(df, y) -out = pre.transform(df) +ages = pd.DataFrame({"age": [25, 40, 63, 51]}) + +pre_spline = Preprocessor( + numerical_method="bspline", output_dim=6, + target_aware=False, placement_strategy="quantile", +).fit(ages) +out = pre_spline.transform(ages) +assert out.shape == (4, 6) +np.testing.assert_allclose(out.sum(axis=1), 1.0) out.shape ``` @@ -46,6 +59,10 @@ out.shape (4, 6) ``` +```python +out.round(3) +``` + ```text array([[1. , 0. , 0. , 0. , 0. , 0. ], [0. , 0.179, 0.593, 0.228, 0. , 0. ], @@ -59,22 +76,18 @@ basis is a partition of unity). `get_feature_names_out()` shows exactly where ea from: ```python -list(pre.get_feature_names_out()) +list(pre_spline.get_feature_names_out()) ``` ```text ['num_age_bs0', 'num_age_bs1', 'num_age_bs2', 'num_age_bs3', 'num_age_bs4', 'num_age_bs5'] ``` -All six still trace back to the single `age` input, which is exactly what `output_structure= -"blocks"` reflects: one dict entry per **input** feature, holding its full expanded block, not -one entry per output column. +All six still trace back to the single `age` input. In block output, `num_age` holds all +six columns together. ```python -pre_blocks = Preprocessor(numerical_method="bspline", output_dim=6, - target_aware=False, placement_strategy="quantile", - output_structure="blocks").fit(df, y) -pre_blocks.transform(df)["num_age"].shape +pre_spline.transform(ages, return_array=False)["num_age"].shape ``` ```text @@ -82,10 +95,8 @@ pre_blocks.transform(df)["num_age"].shape ``` ```{tip} -This is why a wide expansion (a spline or feature map with a large `output_dim`, or several -expanded columns) can produce a much wider matrix than the input `DataFrame` had columns. -Use `get_feature_info(verbose=True)` (below) or `estimate_output_shape(df)` to see the total -width before committing, especially with several expanded columns at once. +After fitting, use `get_feature_info(verbose=True)` to see the width of each block or +`estimate_output_shape(X)` to estimate the shape for a new batch without transforming it. ``` ## Output format and dtype @@ -102,14 +113,16 @@ even for a single row. Default `"dense"`. : The floating-point precision of the output, for example `numpy.float32` to halve memory. ```python -pre = Preprocessor(output_format="auto", dtype="float32") +pre = Preprocessor(numerical_method="minmax", categorical_method="one-hot", + output_format="auto", dtype="float32").fit(df) ``` -After fitting, `output_report_` summarizes what was produced: the chosen format, dimensions, -density, and memory saved. +After a call to `transform`, `output_report_` summarizes that batch's format, dimensions, +density, and memory use. Calling `fit_transform` also populates the report. ```python -pre.fit(df, y) +out = pre.transform(df) +assert out.dtype == np.float32 pre.output_report_ ``` @@ -140,17 +153,7 @@ sparse), and `set_output` (scikit-learn's own DataFrame protocol). This section decision guide: what each one controls, how they interact, and which combination fits a given use case, with the literal output shown for each rather than just a description of it. -The examples below all share the same tiny, fixed input so the printed output is directly -comparable: - -```python -import numpy as np -import pandas as pd -from pretab import Preprocessor - -df = pd.DataFrame({"age": [25, 40, 63], "city": ["A", "B", "A"]}) -y = [0.1, 0.9, 0.3] -``` +The examples below reuse the three-row `df` from [Output shapes](#output-shapes). ### Parameter impact at a glance @@ -239,14 +242,18 @@ independently of `output_structure`: a sparse `"matrix"` is a single stacked `scipy.sparse.csr_matrix`, and a sparse `"blocks"` dict holds a CSR matrix per feature. ```python +from scipy.sparse import isspmatrix_csr + pre = Preprocessor(numerical_method="minmax", categorical_method="one-hot", output_format="sparse").fit(df, y) -pre.transform(df) +out = pre.transform(df) +assert isspmatrix_csr(out) +assert (out.shape, out.nnz) == ((3, 3), 5) +out.shape, out.nnz ``` ```text - +((3, 3), 5) ``` Halving memory on a large dataset @@ -320,50 +327,41 @@ list(pipe.fit(X, [0.0, 1.0, 1.0, 0.0]).get_feature_names_out()) ['num_age', 'num_income'] ``` -Use `get_feature_info(verbose=True)` for a human-readable table of the resolved per-feature -pipeline, output width, and category count. - -```text -feature kind pipeline dim cats ----------------------------------------------------------------- -age numerical imputer -> minmax -> bspline 13 - -income numerical imputer -> minmax -> ple 12 - -city categorical imputer -> onehot -> to_float 4 4 -``` - -`verbose=True` is the default, so `get_feature_info()` both logs that table and returns the -same data as a tuple of dicts, one per feature kind, keyed by input column name: +`get_feature_info()` logs a table with the fitted pipelines, widths, and category counts. +It also returns three dictionaries for numerical, categorical, and embedding blocks. +Pass `verbose=False` to return the same data without logging the table. ```python -pre.get_feature_info() -``` +numerical, categorical, embeddings = pre.get_feature_info() -```text -feature kind pipeline dim cats ----------------------------------------------------------------- -age numerical imputer -> minmax -> bspline 7 - -income numerical imputer -> minmax -> rbf 7 - -city categorical imputer -> onehot -> to_float 3 3 +assert numerical["age"]["dimension"] == 1 +assert categorical["city"]["dimension"] == 2 +assert categorical["city"]["categories"] == 2 +assert embeddings == {} ``` -```python -( - {"age": {"preprocessing": "imputer -> minmax -> bspline", "dimension": 7, "categories": None}, - "income": {"preprocessing": "imputer -> minmax -> rbf", "dimension": 7, "categories": None}}, - {"city": {"preprocessing": "imputer -> onehot -> to_float", "dimension": 3, "categories": 3}}, - {}, -) -``` +After the table, `get_feature_info()` logs the effective settings recorded at fit time +for declared feature overrides and groups, with group sources in their declared order. +This section does not enumerate every pipeline step. Its `output_dim`, when present, is +a configuration setting; the table's `dim` is the actual fitted width. Edits after fit +do not change the recorded settings. Use `get_resolved_config()` for current settings. +Older fits without a settings record report that it is unavailable. ```{tip} -`get_feature_info()` is a handy, no-setup way to check exactly what happened to each feature: -which pipeline it went through, how many output columns it produced, and (for categoricals) -how many categories were seen. Pass `verbose=False` to get just the returned dicts, silently. -For other fitted details (total output width, per-feature output counts, the last -`transform`'s memory report), see the `Preprocessor` **Attributes** in the +For programmatic checks, compare the returned dimensions with `output_dims_` or use +`total_output_dim_` to size a downstream model. See the `Preprocessor` attributes in the [API reference](../api/preprocessor.rst). ``` +```{note} +`dimension` is the actual width of the fitted feature block, including any +missing-indicator columns. Inspection reads the fitted output spans without +evaluating dummy inputs, so it also works for representations restricted to a +particular input domain. `categories` records vocabulary size separately: dropped +or grouped one-hot categories can produce fewer columns than the vocabulary +contains, while additional representation or indicator columns can increase width. +``` + ## Fit-time logging `verbose` controls how much `fit` reports through the shared `"pretab"` logger, useful when @@ -377,12 +375,12 @@ running PreTab inside a larger training script or notebook. | `3` | Also logs internal fitted decisions (bins, knots, centers). | ```python -Preprocessor(numerical_method="ple", verbose=1).fit(df, y) +logged = Preprocessor(numerical_method="ple", task="regression", verbose=1).fit(df, y) +assert logged.total_output_dim_ == 8 ``` -```text -fit complete: 2 numerical (ple) + 1 categorical (int) feature(s) -> 15 output columns in 0.02s -``` +This fit logs one numerical feature (`ple`), one categorical feature (`int`), eight output +columns, and the elapsed time. Each fit applies its own level, so a later `verbose=2` fit in the same process or notebook logs the table even after a `verbose=1` fit. PreTab attaches its own stream handler only when no host @@ -431,8 +429,8 @@ model fit on top of the expansion. ## Output budget -Expansions can multiply columns quickly, especially wide splines or high-cardinality one-hot. -The output budget lets you cap the blast radius and estimate cost before committing. +Wide splines and high-cardinality one-hot encodings can produce many columns. Set a budget +before fitting, then use the fitted width to estimate the size of future batches. | Parameter | Effect | | ------------------------ | ---------------------------------------------- | @@ -442,16 +440,19 @@ The output budget lets you cap the blast radius and estimate cost before committ | `overflow_policy` | What to do on overflow, default `"error"`. | ```python -pre = Preprocessor(max_output_features=500, overflow_policy="error") +budgeted = Preprocessor( + numerical_method="minmax", categorical_method="one-hot", dtype="float32", + max_output_features=500, overflow_policy="error", +).fit(df) -pre.estimate_output_shape(df) # predicted (n_rows, n_cols) without transforming -pre.estimate_memory(df) # predicted dense memory in bytes +assert budgeted.estimate_output_shape(df) == (3, 3) +assert budgeted.estimate_memory(df) == 36 # 3 rows * 3 columns * 4 bytes ``` ```{warning} -With `overflow_policy="error"`, exceeding a budget raises `OutputBudgetError` at `fit`. Use -`estimate_output_shape` and `estimate_memory` first when you work with wide expansions or -large data. +With `overflow_policy="error"`, exceeding a budget at fit time raises `OutputBudgetError`. +`estimate_output_shape` and `estimate_memory` require a fitted preprocessor. They do not +materialize transformed output or predict what an unfitted configuration will learn. ``` ## Where to go next diff --git a/docs/core_concepts/reproducibility.md b/docs/core_concepts/reproducibility.md index 63755dd..4b70ef4 100644 --- a/docs/core_concepts/reproducibility.md +++ b/docs/core_concepts/reproducibility.md @@ -11,53 +11,118 @@ placement, and the randomized feature maps. Set it to an integer whenever you ne output, for example in tests or published experiments. ```python +import numpy as np from pretab import Preprocessor +X = np.linspace(0.0, 1.0, 50).reshape(-1, 1) +y = np.sin(2 * np.pi * X[:, 0]) pre = Preprocessor(numerical_method="rbf", random_state=0) ``` ```{note} -With a fixed `random_state`, repeated fits on the same data produce identical output. Methods -with no stochastic component ignore the seed. The standalone kernel approximations +In the same environment, a fixed `random_state` lets you repeat a fit on the same data. +Methods with no stochastic component ignore the seed. The standalone kernel approximations (`RandomFourierFeaturesTransformer`, `NystroemFeaturesTransformer`) accept `random_state` directly; they are fit outside `Preprocessor` since they operate on the whole feature block. ``` -## Portable serialization +(portable-serialization)= -`to_spec` writes a fitted `Preprocessor` to a versioned, declarative schema, and `from_spec` -reconstructs it. The spec records the schema and library versions, the resolved parameters, -and the per-representation fitted state (parameters, knots, centers, columns, scaling). +## Portable serialization -The spec is strict JSON, so any standard parser (JavaScript, Go, Rust, JSON schema validators) -reads it. Non-finite floats, such as the imputers' `missing_values=np.nan`, are stored as a -tagged value, `{"__float__": "nan"}` (or `"inf"`, `"-inf"`), instead of a bare `NaN` token. -Specs written by PreTab 1.0.0, which contain bare `NaN` tokens, still load. -The reverse is not supported: older readers cannot decode the new float tags. -The tagged encoding also changes fingerprints for fitted state containing non-finite -values, including the default imputers; this change does not alter transformed values. +`to_spec()` exports a fitted `Preprocessor` as a JSON-compatible dictionary and can also +write it to a file. `from_spec()` restores it from either form without refitting. ```python +pre.fit(X, y) spec = pre.to_spec() # returns a dict pre.to_spec("representation.json") # or writes JSON to a path restored = Preprocessor.from_spec("representation.json") +np.testing.assert_array_equal(pre.transform(X), restored.transform(X)) ``` +### What's in a spec + +- `schema_version`, `pretab_version`, and `library_versions` identify the format and the + environment that wrote the spec. +- `params` holds constructor requests at export time. These can change after fit. +- `resolved_config` holds effective settings recorded at the last successful fit, including + normalized declared feature overrides and groups in declared order. It is absent if the + fit has no settings record. +- `feature_names_out` and `feature_lineage` give the output column order and fitted + provenance, including group identity and ordered sources where applicable. +- `output_dims` and `total_output_dim` give actual per-block and total widths, including + separate missing indicators. These are not requested `output_dim` values. +- `representations` describes blocks that expose representation metadata. Group entries + include `group_id`, ordered `columns`, fitted `dimension`, and a half-open `output_slice`. + Supported typed penalties add compact `penalties` metadata, including coefficient + coordinates and a matrix checksum, not the matrix itself. +- `state` is the encoded fitted object state. This is what the reader restores; the + descriptive fields alone cannot recreate the learned transformation. + +Use `get_resolved_config()` to inspect effective settings for the **current** requests. +It is not a substitute for the recorded fit-time `resolved_config`. Don't edit a spec to +change a fit: the reader checks recorded configuration and layout fields against the +stored state where applicable and raises `PretabSerializationError` on mismatches. +Those checks do not authenticate the artifact. + +### Compatibility + +The current writer still uses `schema_version: 1`. It writes strict JSON, encoding +non-finite floats such as the default imputer's `np.nan` as tagged values, for example +`{"__float__": "nan"}`, instead of bare `NaN`. Standard JSON parsers can inspect new specs; +restoring the fitted object requires PreTab. + +The current reader loads supported PreTab 1.0.0 schema-v1 specs, including legacy bare +`NaN` tokens and specs without the added metadata. It does not invent a missing fit-time +settings record. **Downgrades are not supported:** PreTab 1.0.0 cannot decode the new +float tags, even though the schema number is unchanged. Keep the original artifact and +its environment for rollback. The change to tagged encoding can affect fingerprints for +state containing non-finite values without changing transformed values. + ```{important} Load specs only from trusted sources. Reconstruction restricts imports to `pretab`, `scikit-learn`, `numpy`, and `scipy`, reconstructs dataclasses only from an exact, closed allow-list, and bypasses estimator initialization and pickle hooks. These restrictions are -not a sandbox: importing library modules can still execute code. Use the same PreTab and -dependency versions when restoring; recorded versions are informational, and cross-version -compatibility is not guaranteed. +not a sandbox: importing library modules can still execute code. Recorded versions are +informational, not a guarantee of compatibility. Use the original environment for exact +replay, and verify fitted outputs when upgrading. ``` +### Spec or pickle? + +Use a spec when you need an inspectable JSON artifact for supported fitted PreTab state. Supported built-in representations reproduce `transform` bit-for-bit in the same environment. -Third-party representations and pretrained language models are not supported by the JSON -serializer; unsupported state raises `PretabSerializationError` when the spec is built. The -spec is serialized before `to_spec(path)` opens the file, so a failed save leaves an existing -spec at that path untouched. +The spec covers preprocessing, not a downstream model. Registering a third-party +representation enables fitting and transforming, not spec persistence. `to_spec()` raises +`PretabSerializationError` and names the unsupported estimator if its module is outside +the spec's allowed modules, even when it is nested in an otherwise supported pipeline. +The fitted object is unchanged, and `to_spec(path)` raises before opening the destination. +Use supported built-in representations when you need JSON replay; don't rely on specs +to persist third-party representations or pretrained language models. + +Use pickle or joblib when you need to persist a larger Python object, such as a complete +scikit-learn pipeline, and every component supports that mechanism. Use a matching +environment to restore the checkpoint; neither format guarantees cross-version replay. +Unpickling can execute arbitrary code: only load trusted pickle or joblib artifacts. +The same trusted-source requirement applies to specs. + +```{note} +Restoring a PreTab 1.0.0 `Preprocessor` from a spec or trusted pickle repairs +the stale feature count in pass-through and float-cast helpers directly after +sparse one-hot encoders. With unchanged dependencies, these objects retain their +transformed values and names without refitting, and can again export specs and +fingerprints. Feature information reports the fitted layout; previously incorrect +dimension metadata can change. Standalone helper validation is unchanged. +Fingerprints can differ from 1.0.0 because the fitted metadata and JSON encoding +have been corrected. This targeted repair is not a general guarantee of +cross-version compatibility. +``` + +When refitting after an upgrade, check output names and widths before reusing a +trained model. If the feature layout changes, refit the preprocessing and retrain +the model together. ## Fingerprint @@ -66,14 +131,14 @@ resolved config, the schema, the fitted parameters, the output-column order, the library versions, and the output precision. ```python -pre.fit(df, y) -pre.fingerprint_ +fingerprint = pre.fingerprint_ +assert fingerprint == restored.fingerprint_ ``` Inference reports and advisory lifecycle flags are excluded from the fingerprint. -The fingerprint is deterministic within a process and across processes, and it survives a -`to_spec` / `from_spec` round-trip. Two preprocessors with the same fingerprint will produce -the same output; a change to config, data, seed, or version changes the fingerprint. +It identifies the fitted state and configuration, not the raw training data. For example, +changing the target of an unsupervised fit can leave the fingerprint unchanged. A spec +round-trip in the same environment preserves the fingerprint. ```{tip} Log the fingerprint alongside model metrics. If it changes unexpectedly between runs, your @@ -88,6 +153,10 @@ versions, seed, output dtype and format, output widths, and the per-feature fami pre.reproducibility_report() ``` +`fingerprint_` and `reproducibility_report()` require supported spec state. Both raise +`PretabSerializationError` on unsupported estimator state rather than returning a digest +or partial report. + ## Immutable lifecycle A fitted representation moves through a small set of explicit states, which prevents @@ -102,8 +171,16 @@ accidental mutation of something you intend to deploy. ```python pre.freeze() # lock it -pre.is_frozen() # True -pre.set_params(...) # raises FrozenRepresentationError while frozen +assert pre.is_frozen() + +from pretab import FrozenRepresentationError + +try: + pre.set_params(output_dim=9) +except FrozenRepresentationError: + pass +else: + raise AssertionError("Expected a frozen preprocessor to reject parameter changes") ``` Freezing is useful when a representation is validated and about to ship. To make a fresh, @@ -112,9 +189,22 @@ object and leaves the original untouched, and `mark_stale(reason)` records why a should no longer be used. ```{warning} -`fit`, `fit_transform`, and `set_params` on a frozen preprocessor raise `FrozenRepresentationError`. This is deliberate: -a deployed representation should not silently change shape. Use `refit` to produce a new -object instead of mutating the old one. +Attempts to refit a frozen preprocessor, change its parameters, or change its +`set_output` format raise `FrozenRepresentationError`. Use `clone_unfitted()` +for a mutable copy or `refit()` to produce a new fitted object. +``` + +`set_output(transform=None)` leaves the configuration unchanged. Repeating an +explicitly selected format, such as `"pandas"`, is also allowed after freezing. +Selecting a format for the first time is a change, even if it matches the +current global default. + +```{note} +Freezing protects instance settings, not sklearn's global configuration. If no +instance format is set, `sklearn.set_config(transform_output="pandas")` can +still change the returned container without changing the fingerprint. Call +`set_output(transform="default")`, or select another supported format, before +`freeze()` to make the output container independent of global settings. ``` ## Where to go next diff --git a/docs/core_concepts/resolution_and_placement.md b/docs/core_concepts/resolution_and_placement.md index a3d19e9..d1a4323 100644 --- a/docs/core_concepts/resolution_and_placement.md +++ b/docs/core_concepts/resolution_and_placement.md @@ -7,19 +7,19 @@ they combine. ## Resolution: the `output_dim` width -`output_dim` is the main capacity control. It sets the number of non-bias output columns per -input feature: basis functions for the splines, centers for the feature maps, and bins for -PLE. A larger value captures finer structure at the cost of more columns and a higher chance -of overfitting. A smaller value is more compact and regularizes the representation. +`output_dim` controls capacity for methods that support it. With fixed sizing it requests +the number of basis functions or centers per input feature, excluding any optional bias +column. For PLE it sets a maximum number of bins; the fitted width can be smaller. A wider +representation can capture finer structure but uses more columns and can increase overfitting. ```{note} -When you configure through the `Preprocessor`, its single `output_dim` (default `7`) is -forwarded to **every** numerical method. Per-transformer defaults only apply when you build a -transformer directly, for example `RBFExpansionTransformer()`. +`Preprocessor` inherits its global `output_dim` (default `7`) for methods that accept it, +unless a per-feature request supplies a width. Methods without a width parameter, such as +`minmax`, ignore it. A standalone transformer uses its own default when no width is supplied. ``` ```{warning} -Numeric binning (`custombin`) is the one exception: `output_dim` sets the number of *bins*, +For numeric binning (`custombin`), `output_dim` sets the number of *bins*, but with the default `encode="ordinal"` each input feature still emits a single output column holding the bin index. Pass `encode="onehot"` or `encode="soft"` if you want `output_dim` to also control the output width. @@ -46,23 +46,22 @@ steps and watch the total column count. ## Adaptive sizing -Some features are simple and some are complex, and one fixed width rarely suits all of them. -PLE, the feature maps, and the freely-placed knot splines can size each feature from the data -instead. +For supported methods, `adaptive=True` lets fitting adjust the per-feature width. The +`min_output_dim` and `max_output_dim` settings specify the requested bounds. How they are used +depends on the method and placement path: -`adaptive` -: When `True`, the width for each feature is chosen from the data and kept inside -`[min_output_dim, max_output_dim]`. Fixed-width methods such as the plain scalers ignore -this flag. - -`min_output_dim`, `max_output_dim` -: The lower and upper bounds that apply only when `adaptive=True` (defaults `5` and `10`). -They are ignored otherwise. +- **Supervised search.** Two explicit bounds define the search window. An unset bound can + fall back to `output_dim`, which must still be valid for the method even when both bounds + are set. PLE always uses the target and does not take a `target_aware` flag. +- **Target-free placement.** B-, M-, and I-splines start from `output_dim` and adjust the + unsupervised knots toward the bounds. With bounds `[4, 6]`, a target-free B-spline can + keep a requested width of 5 or reduce a requested width of 12 to 6. Other methods, such + as RBF and natural cubic splines, keep their ordinary sizing on the target-free path. ```{note} -When `adaptive=True` and both `min_output_dim` and `max_output_dim` are set, `output_dim` has -no effect at all: the window comes entirely from the two bounds. `output_dim` only matters in -adaptive mode when one of the bounds is left unset, where it fills in for the missing one. +B-, M-, and I-splines can fit fewer columns than `min_output_dim` when there are too few +distinct input values for the requested knots. Use `output_dims_` or `total_output_dim_` +after fitting a `Preprocessor` to size a downstream model. ``` ```python @@ -70,6 +69,8 @@ from pretab import Preprocessor pre = Preprocessor( numerical_method="rbf", + target_aware=True, + placement_strategy="cart", adaptive=True, min_output_dim=4, max_output_dim=12, @@ -116,6 +117,84 @@ switching to `target_aware=False` also means passing `placement_strategy="unifor Target-aware placement is a supervised decision and carries leakage considerations. See [Target awareness](target_awareness.md). +## Choose a task and validate the target + +Set `task="classification"` when `y` contains class labels, such as whether a home sold. +Use `task="regression"` for numeric outcomes such as sale prices. `Preprocessor` defaults +to regression and never infers the task from `y`. + +Use `task_validation` to catch a clear mismatch before fitting the target-aware representation: + +- `"off"` (default) skips the consistency check. Use it to preserve existing behavior or + silence this diagnostic for an intentional configuration. +- `"warn"` emits a `ConfigWarning` and lets fitting proceed. The estimator may still reject + the target, and a Python warnings-as-errors filter can stop the fit at the warning. +- `"raise"` stops the fit with `InvalidParamError`. Use it when a clear mismatch should + fail the pipeline. + +For example, a classifier for sale status should receive class labels, not sale prices: + +```python +import numpy as np +import pandas as pd + +from pretab import Preprocessor +from pretab.exceptions import InvalidParamError + +homes = pd.DataFrame({"listing_views": np.arange(32)}) +sale_status = np.where(homes["listing_views"] >= 16, "sold", "not sold") +sale_price = np.linspace(120_000.25, 450_000.75, len(homes)) + +pre = Preprocessor( + numerical_method="rbf", output_dim=3, task="classification", task_validation="raise" +) +try: + pre.fit(homes, sale_price) +except InvalidParamError as error: + assert "target type 'continuous'" in str(error) +else: + raise AssertionError("Expected the classifier's continuous target to be rejected") + +pre.fit(homes, sale_status) +``` + +The check also catches nonnumeric class labels used for target-aware regression. It does not +apply to representations that ignore `y`. Missing, multilabel, and other multi-output targets +are left to the usual input checks. Silence does not mean a target shape is supported. + +```{note} +Few distinct integer values do not tell you which task to use. Daily order counts of `0`, +`1`, and `2` can be regression outcomes, while the same values can label three classes. +The diagnostic leaves both interpretations open. Numeric-looking strings can also be +ambiguous. It does not rewrite `y` or the configured task. +``` + +`RepresentationSearchCV` defaults its preprocessing task to classification when the +downstream estimator is a classifier and no `task` was passed in `preprocessor_params`. +An explicitly supplied preprocessing task takes precedence. Set `task_validation` on +the search and in `preprocessor_params` independently: + +```python +from sklearn.linear_model import LogisticRegression + +from pretab import RepresentationSearchCV + +search = RepresentationSearchCV( + LogisticRegression(), + methods=["rbf"], + cv=3, + preprocessor_params={"output_dim": 3, "task_validation": "raise"}, + task_validation="raise", +).fit(homes, sale_status) +assert search.best_preprocessor_.task == "classification" +``` + +`CrossFittedTransformer` also accepts `task_validation` for its own task, which determines +the splitter. Turning the check off on a wrapper does not turn off its inner estimator's +policy. It also does not disable task-string validation or leakage warnings. A consistency +check answers whether the target fits the task; it does not prevent leakage. Use a pipeline +or cross-fitting to keep target-aware preprocessing within the training data for each split. + ## Resolution and placement are independent Keeping the two axes separate is what makes the system predictable. You choose a width diff --git a/docs/core_concepts/target_awareness.md b/docs/core_concepts/target_awareness.md index 3ac549e..482b0c4 100644 --- a/docs/core_concepts/target_awareness.md +++ b/docs/core_concepts/target_awareness.md @@ -19,8 +19,8 @@ Every method declares how it uses `y` through three levels. from pretab.transformers import PLETransformer t = PLETransformer() -t.requires_y # True: PLE always needs y -t.is_supervised # True +assert t.requires_y +assert t.is_supervised ``` ```{warning} @@ -44,8 +44,10 @@ After fitting, a transformer reports whether it actually consumed the target thr whether it was supervised. ```python -t = PLETransformer().fit(x, y) -t.uses_target_ # True +X = [[0.0], [1.0], [2.0]] +y = [0.1, 0.4, 1.2] +t = PLETransformer().fit(X, y) # Emits LeakageWarning when run directly. +assert t.uses_target_ ``` ## Leakage safety @@ -54,10 +56,11 @@ Fitting a supervised transformer on your full dataset and then evaluating on par target information and inflates scores. PreTab warns when it detects this pattern. ```{important} -A supervised transformer emits a `LeakageWarning` when it is fit with a target **outside** a -cross-validation or `Pipeline` context. Inside a scikit-learn `Pipeline`, `ColumnTransformer`, -`Preprocessor`, or a cross-fitting wrapper, the warning is suppressed because those contexts -already keep the fit confined to the training fold. +`LeakageWarning` is a reminder, not a check of your data split. A supervised transformer +can warn when fitted directly with `y`. PreTab suppresses the warning inside a scikit-learn +`Pipeline`, `ColumnTransformer`, `Preprocessor`, or cross-fitting wrapper. That suppression +does not mean rows were held out: a pipeline fitted on the full dataset still sees the full +dataset. Split before fitting, or pass the entire pipeline to cross-validation. ``` The safe patterns are: @@ -83,11 +86,20 @@ the same format, or a pandas/Polars DataFrame. Fold outputs are restored to the order. A pandas output keeps the input index when the wrapped transformer preserves it; otherwise it uses a fresh row index. -Cross-fitting currently requires matrix output. A wrapped `Preprocessor` configured with -`output_structure="blocks"` raises an explicit error; use `output_structure="matrix"` instead. +`CrossFittedTransformer.fit_transform` requires matrix output. A wrapped `Preprocessor` +configured with `output_structure="blocks"` raises `IncompatibleParamsError`; use +`output_structure="matrix"` instead. Each fold must return a 2D output with one row per held-out sample, a fixed width, and, for DataFrames, the same column labels in the same order as the all-data fit. +`output_format="dense"` makes block values dense; it does not turn a block dictionary into +a matrix. DeepTab's preprocessing factory requests dense blocks, so a preprocessor built by +that factory cannot be wrapped unchanged to produce cross-fitted training features. + +Calling `fit(X, y).transform(X)` is not an out-of-fold workaround: it uses the estimator fit +on all training rows, even when ordinary block transformation succeeds. Use `fit_transform` +for out-of-fold training features and `transform` for genuinely new rows. + A wrapped `Preprocessor` is not refit from scratch on each fold: every fold reuses its all-data fit and refits only the target-aware representations and subsequent pipeline steps. Column types, target-free blocks and their category vocabularies, imputers, scalers before the @@ -132,10 +144,10 @@ predict. ```{tip} Use `CrossFittedTransformer` when you need the **training features themselves** to be -leakage-free, for example to feed a second-stage model or to report an honest training-set -metric. A supervised transformer inside a plain `Pipeline` already keeps cross-validation -honest for `cross_val_score` / `GridSearchCV`, since each fold refits from scratch; you only -need cross-fitting when you build the training features once and reuse them directly. +computed without each row's own target, for example to feed a second-stage model. To evaluate +that model, still use a separate validation or test set, or put the entire workflow inside +cross-validation. A supervised transformer inside a `Pipeline` passed to `cross_val_score` +or `GridSearchCV` is refit on each training fold before the held-out fold is scored. ``` The fitted spec records `cross_fitted=True` and the number of folds, so the choice is @@ -182,18 +194,19 @@ search = RepresentationSearchCV( random_state=0, ) search.fit(X, y) -search.cv_results_ +assert search.best_method_ == max(search.cv_results_, key=search.cv_results_.get) +{method: round(score, 3) for method, score in search.cv_results_.items()} search.best_method_ ``` ```text -{'minmax': 0.636, 'ple': 0.949, 'bspline': 0.973, 'rbf': 0.841} +{'minmax': 0.636, 'ple': 0.949, 'bspline': 0.976, 'rbf': 0.841} 'bspline' ``` -`bspline` scored highest across the 5 folds for this sine-shaped signal, so `search. -best_preprocessor_` and `search.best_estimator_` are refit on all the data with `bspline` and -ready to call `.predict(X_new)`. +`bspline` had the highest mean validation score for this sine-shaped signal. The selected +preprocessor and estimator are refit on all the training data, so you can call +`search.predict(X_new)` on new rows. When several rows belong to the same unit, such as repeated measurements of one patient, a row-level split validates each candidate on units it has already seen in training. Pass a diff --git a/docs/developer_guide/architecture.md b/docs/developer_guide/architecture.md new file mode 100644 index 0000000..0e67fc5 --- /dev/null +++ b/docs/developer_guide/architecture.md @@ -0,0 +1,156 @@ +# Architecture contract + +PreTab separates representation algorithms, the composition that selects and wires +them, and the public `Preprocessor` that owns the fitting lifecycle. Use these +boundaries when adding a representation or a consumer of fitted state. + +## Dependency directions + +- `pretab.core` owns shared estimator, validation, and representation primitives. + It depends on core peers and shared exceptions, not on registered methods or + the facade. `pretab.placement` uses core and placement peers, not concrete + representations. +- Expansion, encoding, kernel approximation, embedding, and preprocessing modules + use their own implementations and lower-level core, placement, or exception + facilities as needed. They do not import composition, the facade, extension + registration, or the public reexport modules. +- `pretab.compose` selects and assembles concrete implementations. The registry is + the source of method capabilities; config resolves requests and the factory builds + pipelines from the resolved settings. Add a method capability there rather than + duplicating it in the facade or an output consumer. +- `Preprocessor` orchestrates fitting, inference, and lifecycle operations through + composition and core. The extension API registers through the same registry and + uses the core representation contract. + +Two composition modules intentionally refer to the facade: `pretab.compose.search` +constructs candidates and `pretab.compose.serialize` imports `Preprocessor` locally +to restore one. These are upper-layer exceptions, not a dependency for a representation +implementation. The codec's controlled class resolution is separate from static imports. + +Use the documented public imports in application and plugin code. `pretab` exports +the facade, configuration values, and extension functions. `pretab.transformers` +reexports concrete transformers from their implementation families. Inside PreTab, +import from the owner rather than routing implementation dependencies through these +convenience exports. See the [API reference](../api/preprocessor.rst) and +[extensibility API](../api/extension.rst) for the supported entry points. + +## Requests, resolution, and fitted state + +Keep these views distinct: + +- `get_params()` exposes the current constructor requests, preserving spellings and + caller-owned raw mappings. Typed requests such as `RepresentationConfig` detach + their input data at construction. +- `get_resolved_config()` normalizes current requests and applies defaults and + inheritance. It does not fit, inspect the input, or recover learned state. +- The last successful fit records its effective settings separately. Supported specs + expose them as `resolved_config` when available; legacy specs need not have that + record. The fitted estimators and their actual layout are authoritative for inference. + +Changing a request with `set_params()` does not replace the fitted representation. +This example checks the live and recorded methods before the next fit: + +```python +import numpy as np +import pandas as pd + +from pretab import Preprocessor, RepresentationConfig + +frame = pd.DataFrame({"value": np.linspace(0.0, 1.0, 32)}) +pre = Preprocessor( + feature_preprocessing={"value": RepresentationConfig(method="rbf", output_dim=3)}, + target_aware=False, + placement_strategy="uniform", +).fit(frame) +fitted_output = pre.transform(frame, return_array=True) + +pre.set_params(feature_preprocessing={"value": "minmax"}) +assert pre.get_params(deep=False)["feature_preprocessing"] == {"value": "minmax"} +current = pre.get_resolved_config()["feature_preprocessing"] +recorded = pre.to_spec()["resolved_config"]["feature_preprocessing"] +assert current["value"]["method"] == "minmax" +assert recorded["value"]["method"] == "rbf" +np.testing.assert_array_equal(pre.transform(frame, return_array=True), fitted_output) +``` + +## Fitted layout and lineage + +The fitted `ColumnTransformer` owns the ordered blocks and their output spans. +Composition inspection reads the fitted entries and `output_indices_`; output +formatting consumes those spans. Do not infer the number or order of columns from +a request, refit a block for inspection, or use a leaf estimator's basis width as +the width of its whole pipeline. Adaptive sizing, joint bases, and missing-state +columns can all make the actual width differ from the request. + +Use `output_dims_` and `total_output_dim_` when sizing a consumer, and +`get_feature_names_out()` and `get_feature_lineage()` when labeling it. A group +owns its sources and contributes one block. Joint basis columns record all of the +group's sources in declared order; each raw missing-state column records only its +own source but retains the same group ID. The example requests three basis +functions per axis, yielding nine joint columns and two missing-state columns. + +```python +from pretab import FeatureGroup + +group_frame = frame.assign(other=np.sin(4.0 * frame["value"])) +group_frame.loc[0, "value"] = np.nan +group = FeatureGroup( + name="pair", + columns=("other", "value"), + representation=RepresentationConfig(method="tensorspline", output_dim=3, params={"degree": 2}), +) +grouped = Preprocessor( + feature_groups=[group], + target_aware=False, + placement_strategy="uniform", + missing_policy="separate_state", + output_structure="blocks", + output_format="dense", +) +blocks = grouped.fit_transform(group_frame) +lineage = grouped.get_feature_lineage() + +assert list(blocks) == ["group_pair"] +assert blocks["group_pair"].shape[1] == grouped.output_dims_["group_pair"] == 11 +assert len(lineage) == len(grouped.get_feature_names_out()) == grouped.total_output_dim_ == 11 +assert all(item.group_id == "group_pair" for item in lineage) +assert [item.source_features for item in lineage if item.component != "indicator"] == [group.columns] * 9 +assert [item.source_features for item in lineage if item.component == "indicator"] == [("other",), ("value",)] +``` + +## Input-only state and supervised refitting + +When `CrossFittedTransformer` wraps a `Preprocessor`, it uses the fitted block's +actual target use to decide what to refit. A target-consuming representation and +any steps after it are refit on the fold's training rows. Input-only state from +the full input to the wrapper stays fitted: column routing, target-free blocks +and their vocabularies, imputers and scalers before the representation, and +separate missing branches. A group still uses its ordered sources as one block. +This keeps category identities and +indicator columns aligned across folds without letting a representation use the +held-out row's target. The refitted block must retain its fitted width. + +```{note} +Cross-fitting produces a matrix, not a dictionary of blocks. It protects the +held-out targets within the data passed to the wrapper. For evaluation, still +fit the whole pipeline within each outer training split. +``` + +## Optional dependencies and persistence + +Keep optional packages at the feature boundary. Composition checks availability +through `pretab.core.dependencies`, without importing the selected model package. +The LightGBM selector and language embedding transformer import their dependencies +only when needed. Polars is handled at the input and output boundaries. Do not make +a base import or an unrelated method require an extra. Preserve an actionable +`OptionalDependencyError` for the path that needs the missing package. + +Registration makes a representation selectable for fitting and inference. It does +not register a persistence codec or extend the schema-v1 import policy. If a +fitted estimator's module is outside that policy, `to_spec()` rejects it with +`PretabSerializationError` before opening a destination, even if it is nested +inside a supported pipeline. `fingerprint_` and `reproducibility_report()` raise +the same error rather than dropping state. Use supported built-in representations +for JSON replay, or a trusted pickle or joblib checkpoint in a matching environment +if all components support it. See [Reproducibility](../core_concepts/reproducibility.md) +for the artifact and trusted-source limits. diff --git a/docs/developer_guide/contributing.md b/docs/developer_guide/contributing.md index 5054dfd..9c19ca0 100644 --- a/docs/developer_guide/contributing.md +++ b/docs/developer_guide/contributing.md @@ -3,6 +3,9 @@ Thanks for contributing to pretab. This page covers environment setup, the local workflow, and what a pull request needs to pass review. +Read the [architecture contract](architecture.md) before changing how methods are +registered, how fitted state is interpreted, or how modules depend on one another. + ## Code of Conduct All contributors are expected to follow the project @@ -22,8 +25,8 @@ git clone https://github.com/OpenTabular/PreTab cd PreTab ``` -2. Install the prerequisites: `pip install poetry` and `just` (see the - [just install guide](https://just.systems/man/en/packages.html), e.g. `brew install just`). +2. Use Python 3.11, 3.12, or 3.13. Install Poetry (`pip install poetry`) and `just` + (see the [just install guide](https://just.systems/man/en/packages.html), e.g. `brew install just`). 3. Install dependencies and register the pre-commit hooks: @@ -63,29 +66,28 @@ This project uses [pre-commit](https://pre-commit.com/) to enforce code quality automatically. `just install` registers all three hook types so each fires at the right time: -| Stage | Hook | -| ------------ | ----------------------------------------------------------------------- | -| `commit-msg` | Validates the message against Conventional Commits. | -| `pre-commit` | `ruff` format and lint, plus file hygiene (whitespace, EOF, conflicts). | -| `pre-push` | `pyright` type checking (slower, so deferred to push). Also runs in CI. | +| Stage | Hook | +| ------------ | ------------------------------------------------------------------------------- | +| `commit-msg` | Validates the message against Conventional Commits. | +| `pre-commit` | Ruff format and lint, Prettier for Markdown, YAML, and JSON, plus file hygiene. | +| `pre-push` | The same checks, plus Pyright type checking. Pyright also runs in CI. | ```{important} -Run `just check` before opening a PR. It runs every `pre-commit`- and `pre-push`-stage hook -(ruff format, ruff lint, pyright, and file hygiene checks) against every file. It does not -validate the commit message itself, that is the `commit-msg` hook, checked when you actually -run `git commit` or `just commit`. +Run `just check` before opening a PR. It runs the `pre-push` stage against all tracked files, +including the checks shared with `pre-commit`. The `commit-msg` hook checks the message +separately when you run `git commit` or `just commit`. ``` Individual recipes are available when you want to run one step: -| Command | Action | -| ------------- | ----------------------------------------------- | -| `just lint` | Lint and auto-fix with ruff. | -| `just format` | Run the ruff formatter. | -| `just types` | Run the pyright type checker. | -| `just test` | Run the test suite with coverage. | -| `just docs` | Build the HTML documentation. | -| `just check` | Run all hooks across all files (commit + push). | +| Command | Action | +| ------------- | ------------------------------------------------ | +| `just lint` | Lint and auto-fix with ruff. | +| `just format` | Run the ruff formatter. | +| `just types` | Run the pyright type checker. | +| `just test` | Run the test suite with coverage. | +| `just docs` | Build the HTML documentation. | +| `just check` | Run the pre-push hooks across all tracked files. | ## Testing @@ -122,7 +124,7 @@ directory. | `tests/extension/` | The public extensibility surface and conformance. | | `tests/integration/` | End-to-end `Preprocessor` and pipeline behaviour. | | `tests/regression/` | Pinned outputs that guard against silent numerical drift. | -| `tests/doc_snippets/` | Executes the `docs/tutorials/*.md` code fences, so the tutorials cannot silently rot. | +| `tests/doc_snippets/` | Runs Python examples in the tutorials, core concepts pages, and selected other guides. | ```{note} Regression tests pin known-good output. If one fails after a deliberate change to a @@ -187,6 +189,9 @@ poetry run pytest --cov=pretab --cov-report=term-missing tests/ If you extend PreTab, run the conformance suite in your own tests. It verifies your class obeys the representation contract, the same one the built-ins satisfy. +Adapt this template to import your own class. For an example you can run as written, see the +[custom representation tutorial](../tutorials/custom_representation.md). + ```python from pretab import check_representation from my_package import MyRepresentation @@ -203,7 +208,7 @@ your test suite keeps a future refactor from silently breaking compatibility wit ### Before you push Run `just check` and `just test` locally; together they cover most of what CI checks, though -CI additionally runs across the full Python 3.10-3.13 matrix, builds the package, and +CI additionally runs across the full Python 3.11-3.13 matrix, builds the package, and enforces a branch-coverage threshold. ```bash @@ -389,7 +394,7 @@ commits format and rejects non-conforming messages. Version bumps are driven by commitizen, wrapped in `just` recipes. Preview first with the `-preview` (dry-run) variant, then apply. Each apply recipe updates `version` in -`pyproject.toml`, appends to `CHANGELOG.md`, and creates the bump commit and tag. +`pyproject.toml` and updates `CHANGELOG.md` before creating the bump commit and tag. | Goal | Preview | Apply | | ----------------- | ---------------------- | -------------- | diff --git a/docs/developer_guide/release.md b/docs/developer_guide/release.md index 30cbe1a..9691b72 100644 --- a/docs/developer_guide/release.md +++ b/docs/developer_guide/release.md @@ -4,8 +4,8 @@ pretab is published to [PyPI](https://pypi.org/project/pretab/) with a release-c step on [TestPyPI](https://test.pypi.org/project/pretab/) first. The whole flow is driven by [commitizen](https://commitizen-tools.github.io/commitizen/) version bumps and Git tags; publishing itself runs on GitHub Actions using -[PyPI trusted publishing](https://docs.pypi.org/trusted-publishers/) (OIDC), so no API -tokens are stored anywhere. +[PyPI trusted publishing](https://docs.pypi.org/trusted-publishers/) (OIDC), so neither +publish workflow needs a stored PyPI API token. For the SemVer rules and commit conventions that decide the next version, see [Versioning](contributing.md#versioning). @@ -20,20 +20,22 @@ For the SemVer rules and commit conventions that decide the next version, see ## What runs when -`ci.yml` and `docs.yml` trigger on both `main` and `release/**` branches, so a commit -pushed straight to a release branch (step 4 below) gets the same feedback as a commit on -`main`, without waiting for the next RC tag. +Both `ci.yml` and `docs.yml` run on pushes to `main` and `release/**`, without waiting +for a release tag. On pull requests, CI checks the target branch and the docs workflow +checks the changed paths independently. -| Event | `ci.yml` | `docs.yml` | Publish workflow | -| -------------------- | :-----------: | :------------------: | ---------------------- | -| PR into `main` | ✅ | ✅ (docs paths only) | - | -| Push to `main` | ✅ | ✅ | - | -| Push to `release/**` | ✅ | ✅ | - | -| Push tag `vX.Y.ZrcN` | ✅ (via `qa`) | ✅ (via `docs`) | `publish-testpypi.yml` | -| Push tag `vX.Y.Z` | ✅ (via `qa`) | ✅ (via `docs`) | `publish-pypi.yml` | +| Event | `ci.yml` | `docs.yml` | Publish workflow | +| ---------------------- | -------- | ----------------- | ---------------------- | +| PR into `main` | Yes | On matching paths | None | +| PR into another branch | No | On matching paths | None | +| Push to `main` | Yes | Yes | None | +| Push to `release/**` | Yes | Yes | None | +| Push tag `vX.Y.ZrcN` | Via `qa` | Yes | `publish-testpypi.yml` | +| Push tag `vX.Y.Z` | Via `qa` | Yes | `publish-pypi.yml` | -Every publish workflow re-runs the full `ci.yml`/`docs.yml` gate on the exact tagged -commit before anything is uploaded, rather than trusting whatever last passed on `main`. +Matching tags trigger a standalone docs build. Each publish workflow also calls both +`ci.yml` and `docs.yml` and waits for those jobs to pass on the exact tagged commit +before uploading. ## QA gate checks @@ -42,17 +44,17 @@ commit before anything is uploaded, rather than trusting whatever last passed on | Lint (`ruff check`, `ruff format --check`) | `lint` | | Type checking (`pyright`) | `typecheck` | | Package build + `twine check` | `build` | -| Full test matrix (3.10-3.13, 3 OSes) | `tests` | +| Full test matrix (3.11-3.13, 3 OSes) | `tests` | | Minimum supported dependency versions | `minimum-deps` | | Smoke test + quickstart script | `smoke` | | Coverage (fails under 90%) | `coverage` | | Optional extras (`embeddings`, `lightgbm`, `polars`) | `optional-deps` | | Docs build (`sphinx-build -W --keep-going`) | `docs.yml` (separate workflow) | -| Wheel install + import smoke test | publish workflow's own steps | +| Tag/version match and clean-wheel quickstart | publish workflow's own steps | ## Prerequisites -- You are a maintainer with permission to push tags to `main`. +- You are a maintainer with permission to push release tags. - The `pypi-publish` and `testpypi-publish` GitHub Environments are configured with tag-based protection and trusted publishing enabled. - Your working tree is clean and `main` is up to date. @@ -96,13 +98,32 @@ GitHub pre-release. ### 4. Verify the release candidate -Install the candidate from TestPyPI in a clean environment and smoke-test it: +Download the exact candidate wheel from TestPyPI, then install it in a fresh virtual +environment with dependencies from PyPI. The check verifies both the installed version +and that the import came from that environment rather than from the checkout. ```bash -pip install --index-url https://test.pypi.org/simple/ \ - --extra-index-url https://pypi.org/simple/ \ - "pretab==X.Y.ZrcN" -python -c "import pretab; print(pretab.__version__)" +version=X.Y.ZrcN # Replace with your tag version, without the leading v. +verify_dir=$(mktemp -d) +python3 -m venv "$verify_dir/venv" +verify_python="$verify_dir/venv/bin/python" + +"$verify_python" -m pip download --no-deps --only-binary=:all: \ + --index-url https://test.pypi.org/simple/ \ + --dest "$verify_dir" "pretab==$version" && +"$verify_python" -m pip install --index-url https://pypi.org/simple/ \ + "$verify_dir"/pretab-*.whl && +"$verify_python" -I - "$version" <<'PY' +import sys +from pathlib import Path + +import pretab + +path = Path(pretab.__file__).resolve() +assert path.is_relative_to(Path(sys.prefix).resolve()), path +assert pretab.__version__ == sys.argv[1], pretab.__version__ +print(pretab.__version__, path) +PY ``` If the candidate has problems, fix them on the branch and produce the next RC: @@ -141,9 +162,27 @@ exactly what both publishing workflows wait on before uploading. ### 7. Confirm +Confirm that the exact stable version can be installed from PyPI. Use a new virtual +environment, not the one used to verify the candidate. + ```bash -pip install --upgrade pretab -python -c "import pretab; print(pretab.__version__)" +version=X.Y.Z # Replace with your tag version, without the leading v. +verify_dir=$(mktemp -d) +python3 -m venv "$verify_dir/venv" +verify_python="$verify_dir/venv/bin/python" + +"$verify_python" -m pip install --index-url https://pypi.org/simple/ "pretab==$version" && +"$verify_python" -I - "$version" <<'PY' +import sys +from pathlib import Path + +import pretab + +path = Path(pretab.__file__).resolve() +assert path.is_relative_to(Path(sys.prefix).resolve()), path +assert pretab.__version__ == sys.argv[1], pretab.__version__ +print(pretab.__version__, path) +PY ``` Check the release on [PyPI](https://pypi.org/project/pretab/) and the auto-generated @@ -152,5 +191,5 @@ GitHub Release notes. ```{tip} Need a build artifact without publishing? Run the `build-check.yml` workflow manually from the GitHub Actions tab. It builds the wheel and sdist, runs `twine check`, and performs an -import smoke test. +import and quickstart check against the installed wheel. ``` diff --git a/docs/getting_started/installation.md b/docs/getting_started/installation.md index 184e5df..3d3a2b1 100644 --- a/docs/getting_started/installation.md +++ b/docs/getting_started/installation.md @@ -1,23 +1,21 @@ # Installation -pretab supports Python 3.10 to 3.13, with the following minimum core dependency versions: +PreTab 1.1 supports Python 3.11 to 3.13. The table distinguishes the declared minimum +dependency versions from the pinned versions tested in the Python 3.11 CI job. -| Dependency | Minimum | -| -------------- | ------- | -| `numpy` | 1.24 | -| `pandas` | 2.0 | -| `scipy` | 1.10 | -| `scikit-learn` | 1.6 | +| Dependency | Declared minimum | Tested CI pin | +| -------------- | ---------------- | ------------- | +| `numpy` | 1.24 | 1.24.4 | +| `pandas` | 2.0 | 2.0.3 | +| `scipy` | 1.10 | 1.10.1 | +| `scikit-learn` | 1.6 | 1.6.0 | ```{note} -`scikit-learn>=1.6` is required for the `__sklearn_tags__` tag-dispatch API pretab's -transformers use. A dedicated CI job installs exactly these minimum versions and runs the -test suite against them, so this floor is verified, not just declared. +PreTab's transformers require `scikit-learn>=1.6` for the `__sklearn_tags__` API. ``` The core dependencies are NumPy >=1.24,<3, pandas >=2,<3, SciPy >=1.10,<2, -and scikit-learn >=1.6,<2. The scikit-learn minimum matches the validation and -estimator-tag APIs used by PreTab. +and scikit-learn >=1.6,<2. ## From PyPI @@ -25,6 +23,24 @@ estimator-tag APIs used by PreTab. pip install pretab ``` +### Python 3.10 migration + +Starting with PreTab 1.1, the supported Python range is `>=3.11,<3.14`. +Upgrade to Python 3.11, 3.12, or 3.13 before installing PreTab 1.1. The minimum +NumPy, pandas, SciPy, and scikit-learn versions have not changed. + +If you must keep Python 3.10, install the last compatible release: + +```bash +pip install "pretab<1.1" +``` + +```{warning} +PreTab 1.0.0 is the final release supporting Python 3.10. It does not include +the fixes or features in 1.1. Python 3.10 reached end of life in October 2026; +staying on an older PreTab release does not provide Python security updates. +``` + ### Optional extras Language-embedding features depend on @@ -101,7 +117,13 @@ preprocessing, feature lineage, leakage-safe cross-fitting, serialization, and m seconds, and doubles as the reviewer smoke test: ```bash -just quickstart # or: python scripts/quickstart.py +just quickstart +``` + +Without `just`, run the script in the Poetry environment: + +```bash +poetry run python scripts/quickstart.py ``` To work on the documentation, also install the docs group: diff --git a/docs/getting_started/overview.md b/docs/getting_started/overview.md index ef35a8b..c69aff0 100644 --- a/docs/getting_started/overview.md +++ b/docs/getting_started/overview.md @@ -20,22 +20,45 @@ declare intent once, for example "expand `age` with a spline, encode `income` wi piecewise-linear bins, treat `hour` as periodic", and PreTab fits the corresponding basis per column, tracks where every output column came from, and hands back a clean matrix. +The examples on this page use the same small regression dataset. + ```python +import numpy as np +import pandas as pd + from pretab import Preprocessor -pre = Preprocessor(feature_preprocessing={ - "age": "naturalspline", # smooth non-linear effect - "income": "ple", # supervised piecewise-linear encoding - "hour": "fourier", # periodic representation - "city": "one-hot", # categorical -}) +rng = np.random.default_rng(0) +n_rows = 64 +df = pd.DataFrame( + { + "age": rng.uniform(18, 65, size=n_rows), + "income": rng.uniform(25_000, 90_000, size=n_rows), + "hour": rng.integers(0, 24, size=n_rows), + "city": rng.choice(["Oslo", "Rome"], size=n_rows), + } +) +y = np.sin(df["age"] / 10) + np.log(df["income"]) + np.cos(2 * np.pi * df["hour"] / 24) + +pre = Preprocessor( + task="regression", + random_state=0, + feature_preprocessing={ + "age": "naturalspline", + "income": "ple", + "hour": "fourier", + "city": "one-hot", + }, +) X = pre.fit_transform(df, y) +assert X.shape == (len(df), len(pre.get_feature_names_out())) ``` ## Two ways to use it -PreTab exposes the same capabilities through two surfaces. They share the same underlying -code, so the choice is about ergonomics, not capability. +`Preprocessor` and standalone transformers share many of the same representations. Use +`Preprocessor` to configure a whole table, or compose standalone transformers when you need +to control each pipeline step or use a standalone-only method. ::::{grid} 1 1 2 2 :gutter: 3 @@ -47,8 +70,8 @@ strategies from one config. ::: :::{grid-item-card} Standalone transformers -Every strategy is also a plain scikit-learn transformer you can import and compose inside a -`Pipeline` or `ColumnTransformer`. Reach for them when you want a single estimator object. +Import a transformer from `pretab.transformers` and use it on its own or inside a +`Pipeline` or `ColumnTransformer`. ::: :::: @@ -60,15 +83,12 @@ map), or want the framework services that live at this level: feature lineage, output-format control, missing-value policy, output budgets, serialization, and a reproducibility fingerprint. -```python -from pretab import Preprocessor +The fitted `Preprocessor` above can also return the same four features as separate blocks. -pre = Preprocessor(feature_preprocessing={ - "age": "naturalspline", - "income": "ple", - "city": "one-hot", -}) -X = pre.fit_transform(df, y) # one stacked array, or output_structure="blocks" for a dict +```python +blocks = pre.transform(df, return_array=False) +assert set(blocks) == {"num_age", "num_income", "num_hour", "cat_city"} +assert sum(block.shape[1] for block in blocks.values()) == X.shape[1] ``` **Reach for standalone transformers** when you want a single estimator object that composes @@ -76,18 +96,25 @@ cleanly inside one `Pipeline`, rely on scikit-learn model selection (`cross_val_ `GridSearchCV`, `step__param` hyperparameter addressing), or need fine control over one column's transformer and its parameters. +This pipeline uses just `age` and `income`. It fits their representations and Ridge on the +training split, then transforms and predicts on held-out rows. + ```python from sklearn.compose import ColumnTransformer -from sklearn.pipeline import Pipeline from sklearn.linear_model import Ridge +from sklearn.model_selection import train_test_split +from sklearn.pipeline import Pipeline from pretab.transformers import NaturalCubicSplineTransformer, PLETransformer features = ColumnTransformer([ ("age", NaturalCubicSplineTransformer(output_dim=10), ["age"]), - ("income", PLETransformer(output_dim=12), ["income"]), + ("income", PLETransformer(output_dim=12, task="regression", random_state=0), ["income"]), ]) model = Pipeline([("features", features), ("ridge", Ridge())]) +df_train, df_test, y_train, _ = train_test_split(df, y, random_state=0) +model.fit(df_train, y_train) +assert model.predict(df_test).shape == (len(df_test),) ``` ```{note} @@ -104,8 +131,9 @@ surface that keeps the intent of your code clearest. ```{note} The tensor-product spline, thin-plate spline, random Fourier features, and Nyström map model -several columns jointly. They are standalone-only and are not selectable per column through -`Preprocessor(numerical_method=...)`. See +several columns jointly. Use `Preprocessor(feature_groups=...)` for tensor-product or +thin-plate splines, or fit their standalone transformers directly. Random Fourier features +and Nyström remain standalone-only. None is a per-column `numerical_method`. See [Multivariate features](../tutorials/multivariate_features.md). ``` @@ -116,21 +144,27 @@ PreTab is not a competitor to scikit-learn. Every transformer subclasses `BaseEs The real question is what PreTab adds where scope overlaps with scikit-learn's own `SplineTransformer`, `KBinsDiscretizer`, `PolynomialFeatures`, and `TargetEncoder`. -| Capability | scikit-learn | PreTab | -| -------------------------- | ------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Knot / threshold placement | Fixed `n_knots`, placed `"uniform"` or `"quantile"` before fitting | Configured via `output_dim` (how many basis functions you want); PreTab derives the knot count from it and places them with `placement_strategy`, optionally target-aware (a CART or LightGBM model places them where the target changes fastest) | -| How many basis functions | You pick a fixed count | `adaptive=True` searches a width in `[min_output_dim, max_output_dim]` from the data | -| Leakage safety | `TargetEncoder` cross-fits internally; nothing else does, and nothing warns you | Every supervised representation emits a `LeakageWarning` outside a `Pipeline`, and any of them can be wrapped in `CrossFittedTransformer` | -| Feature provenance | `get_feature_names_out()` returns names only | A typed `RepresentationSpec` per transformer plus a `FeatureLineage` record per output column (family, component, target usage) | -| Persistence | `pickle` / `joblib`, which execute arbitrary code on load | `to_spec()` / `from_spec()`: a versioned JSON spec for supported fitted state, plus a stable `fingerprint_`; restore trusted specs in the same environment | -| Choosing per column | Hand-assemble a `ColumnTransformer` yourself | One `Preprocessor(feature_preprocessing={...})`, validated against a capability registry so incompatible combinations (a required-target method without `y`, for example) raise a typed error at fit time | +| Capability | scikit-learn | PreTab | +| ------------------------ | -------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Knot placement | `SplineTransformer` places `"uniform"` or `"quantile"` knots during `fit` | Configured via `output_dim` (how many basis functions you want); PreTab derives the knot count from it and places them with `placement_strategy`, optionally target-aware (a CART or LightGBM model places them where the target changes fastest) | +| How many basis functions | You pick a fixed count | `adaptive=True` searches a width in `[min_output_dim, max_output_dim]` from the data | +| Target-aware fitting | `TargetEncoder.fit_transform` cross-fits; `fit` followed by `transform` does not | `CrossFittedTransformer` makes out-of-fold training features when the output width is consistent across folds. Direct standalone fits that use `y` can emit `LeakageWarning`. | +| Feature provenance | `get_feature_names_out()` returns names only | A typed `RepresentationSpec` per transformer plus a `FeatureLineage` record per output column (family, component, target usage) | +| Persistence | `pickle` / `joblib`, which execute arbitrary code on load | `to_spec()` / `from_spec()`: a versioned JSON spec for supported fitted state, plus a stable `fingerprint_`; restore trusted specs in the same environment | +| Choosing per column | Hand-assemble a `ColumnTransformer` yourself | One `Preprocessor(feature_preprocessing={...})`, validated against a capability registry so incompatible combinations (a required-target method without `y`, for example) raise a typed error at fit time | + +```{warning} +A fit inside `Preprocessor` or a scikit-learn `Pipeline` does not emit the standalone +`LeakageWarning`. That does not make the fit leakage-safe by itself. For evaluation, fit +the whole pipeline on training rows only, or cross-validate the unfitted pipeline. See +[Target awareness](../core_concepts/target_awareness.md). +``` ```{note} Piecewise-linear encoding (`ple`) and the neural-style basis maps (`rbf`, `relu`, `sigmoid`, `tanh`, deterministic `fourier`) have no scikit-learn equivalent. `rff` and `nystroem` are thin -wrappers around scikit-learn's own `RBFSampler` and `Nystroem`; unlike the other methods on -this page, they operate on the whole feature block at once, so they are standalone -transformers rather than a per-column `Preprocessor` choice. +wrappers around scikit-learn's own `RBFSampler` and `Nystroem`. Both operate on whole +feature blocks and are available as standalone transformers only. ``` ## When to reach for PreTab @@ -162,8 +196,9 @@ full breakdown. Knowing the boundaries is as useful as knowing the features. PreTab deliberately does not try to be an everything-library. -- **Not a modelling library.** PreTab produces features. It does not fit predictors, tune - models, or select features for you. It sits _in front of_ an estimator. +- **Not a modelling library.** PreTab supplies representations, not predictors. Use your own + estimator downstream. [`RepresentationSearchCV`](../api/search_and_cross_fitting.rst) + fits that estimator while comparing candidate representations by cross-validation. - **Not a time-series toolkit.** Generic lag and rolling-window utilities were removed on purpose. PreTab keeps the periodic encoding that expresses cyclic structure (hour, day, month) but leaves sequence modelling to dedicated libraries. @@ -175,6 +210,28 @@ try to be an everything-library. The [failure modes](../representations/choosing_a_method.md#when-basis-expansion-does-not-help) section is explicit about where it does not help. +## What's new in PreTab 1.1 + +- **More control per feature.** Set a [width or method options](../core_concepts/configuration.md) + for individual columns, or use a [`FeatureGroup`](../tutorials/multivariate_features.md) + to fit a joint spline across numerical columns. +- **Inspect what was fitted.** Read [actual widths and output lineage](../core_concepts/outputs_and_inspection.md) + and use [`PenaltySpec`](../representations/spline_expansions.md) to align supported + spline penalties with fitted basis coefficients. +- **Use Polars directly.** Pass an [eager `polars.DataFrame`](../core_concepts/configuration.md#polars-dataframe-input) + to `Preprocessor` without PyArrow. +- **Export strict JSON.** [Schema-v1 specs](../core_concepts/reproducibility.md) can + record fit-time settings and output layout. Supported 1.0.0 specs still load in 1.1. + +**Upgrading:** PreTab 1.1 supports Python 3.11 through 3.13. On Python 3.10, +stay on PreTab 1.0.0 or [upgrade Python](installation.md#python-310-migration). + +```{note} +Use fitted attributes and methods in code rather than parsing verbose inspection +text, which may change. Only the thin-plate spline's legacy penalty matrix is +experimental, not its transform. The matrix is not guaranteed positive semidefinite. +``` + ## Where to go next - [Installation](installation.md) sets up PreTab and its optional extras. diff --git a/docs/getting_started/quickstart.md b/docs/getting_started/quickstart.md index 010660a..38515cb 100644 --- a/docs/getting_started/quickstart.md +++ b/docs/getting_started/quickstart.md @@ -46,7 +46,8 @@ pre = Preprocessor(feature_preprocessing=config, task="regression", random_state # Fit and transform into a single stacked array X = pre.fit_transform(df, y) -X.shape +assert X.shape == (200, 26) +print(X.shape) ``` ```text @@ -62,90 +63,98 @@ When no per-feature config is given, the `Preprocessor` falls back to its global Ask for a dict of per-feature blocks instead, for inspection or per-block downstream heads: ```python -X_dict = pre.transform(df, return_array=False) # {"num_age": ..., "cat_city": ...} +blocks = pre.transform(df, return_array=False) +assert sum(block.shape[1] for block in blocks.values()) == X.shape[1] +for name, block in blocks.items(): + print(name, block.shape) ``` ```text -{'num_age': (200, 7), 'num_income': (200, 7), 'num_experience': (200, 7), - 'cat_job': (200, 4), 'cat_city': (200, 1)} +num_age (200, 7) +num_income (200, 7) +num_experience (200, 7) +cat_job (200, 4) +cat_city (200, 1) ``` ## Inspect what was built -Every fitted representation is self-describing. Read the resolved layout, or trace each -output column back to its source. +Call `pre.get_feature_info(verbose=True)` for a table of fitted pipelines and widths. +Use `verbose=False` to read the numerical, categorical, and grouped feature information +in code. The lineage records trace output columns back to their inputs. ```python -pre.get_feature_info(verbose=True) # human-readable table of per-feature pipelines +_, categorical_info, _ = pre.get_feature_info(verbose=False) +print(categorical_info["job"]["preprocessing"]) -lineage = pre.get_feature_lineage() # one record per output column -lineage[0] +lineage = pre.get_feature_lineage() +first = lineage[0] +print(first.output_feature, first.source_features, first.uses_target) +assert [record.output_feature for record in lineage] == list(pre.get_feature_names_out()) ``` ```text -feature kind pipeline dim cats ------------------------------------------------------------------------ -age numerical imputer -> minmax -> ple 7 - -income numerical imputer -> minmax -> rbf 7 - -experience numerical imputer -> minmax -> naturalspline 7 - -job categorical imputer -> onehot -> to_float 4 4 -city categorical imputer -> continuous_ordinal 1 5 +normalize_missing -> imputer -> onehot -> to_float +num_age_ple0 ('age',) True ``` -```text -FeatureLineage(output_feature='num_age_ple0', output_index=0, source_features=('age',), - family='piecewise_linear', component='interval', component_index=0, - uses_target=True, is_interaction=False) -``` - -The lineage covers every output column, and the names line up with `get_feature_names_out`. +The first output column comes from `age` and was fitted using the target. The lineage +covers every output column, in the same order as `get_feature_names_out()`. See [Outputs and inspection](../core_concepts/outputs_and_inspection.md) for the full contract. ## Use a transformer on its own -Every strategy is also importable from `pretab.transformers` and follows the scikit-learn -API, so it drops into a `Pipeline` or `ColumnTransformer`. +Import individual transformers from `pretab.transformers`. They follow the scikit-learn +API and work inside a `Pipeline` or `ColumnTransformer`. ```python import numpy as np from pretab.transformers import PLETransformer -x = np.random.randn(200, 1) -y = np.random.randn(200) +rng = np.random.default_rng(0) +values = rng.normal(size=(200, 1)) +target = values[:, 0] ** 2 -x_ple = PLETransformer(output_dim=15, task="regression").fit_transform(x, y) -x_ple.shape[1] # number of piecewise-linear bins +ple = PLETransformer(output_dim=15, task="regression", random_state=0) +features = ple.fit_transform(values, target) +assert features.shape == (len(values), 15) +print(features.shape[1]) ``` ```text 15 ``` -```{note} -`PLETransformer` is supervised: it reads the target `y` during `fit` to place its bin edges. -Always pass `y` when fitting it, or any pipeline that contains it. See -[Target awareness](../core_concepts/target_awareness.md). +```{warning} +`PLETransformer` uses the target to place its bin edges. The direct fit above emits a +`LeakageWarning`: do not fit on all rows before splitting them to evaluate a model. Put the +transformer and predictor in one pipeline and fit them on the training split only, or +cross-validate the unfitted pipeline. See [Target awareness](../core_concepts/target_awareness.md) +for out-of-fold training features. ``` -Spline families that carry a smoothness penalty expose it through `get_penalty_matrix()`: +Spline families with a smoothness penalty expose it through `get_penalty_matrix()`. +For natural cubic splines, the matrix penalizes the integrated squared curvature. ```python import numpy as np from pretab.transformers import NaturalCubicSplineTransformer -x = np.random.randn(200, 1) +rng = np.random.default_rng(0) +values = rng.normal(size=(200, 1)) spline = NaturalCubicSplineTransformer(output_dim=8) -spline.fit_transform(x) - -penalty = spline.get_penalty_matrix() # integrated-curvature penalty for GAM-style fitting +features = spline.fit_transform(values) +penalty = spline.get_penalty_matrix() +assert features.shape == (len(values), 8) +assert penalty.shape == (features.shape[1], features.shape[1]) +print(features.shape, penalty.shape) ``` ```text -(200, 8) # spline.fit_transform(x).shape -(8, 8) # penalty.shape +(200, 8) (8, 8) ``` The multivariate thin-plate spline models several columns jointly and is sized by @@ -156,15 +165,18 @@ import numpy as np from pretab.transformers import ThinPlateSplineTransformer -x = np.random.randn(200, 2) # two input columns, modelled together -tp = ThinPlateSplineTransformer(n_components=10) -features = tp.fit_transform(x) -penalty = tp.get_penalty_matrix() +rng = np.random.default_rng(0) +values = rng.normal(size=(200, 2)) +thin_plate = ThinPlateSplineTransformer(n_components=10, random_state=0) +features = thin_plate.fit_transform(values) +penalty = thin_plate.get_penalty_matrix() +assert features.shape == (len(values), 10) +assert penalty.shape == (features.shape[1], features.shape[1]) +print(features.shape, penalty.shape) ``` ```text -(200, 10) # features.shape -(10, 10) # penalty.shape +(200, 10) (10, 10) ``` ```{warning} diff --git a/docs/homepage.md b/docs/homepage.md index 4112bd8..fd1e12b 100644 --- a/docs/homepage.md +++ b/docs/homepage.md @@ -35,7 +35,7 @@ compose standalone representations with scikit-learn transformers and estimators :::{grid-item-card} 🧠 Smart defaults Automatic feature-type detection (numerical vs. categorical) with support for -`pandas.DataFrame`, `polars.DataFrame` and `numpy.ndarray` inputs. +`pandas.DataFrame`, eager `polars.DataFrame` and `numpy.ndarray` inputs. ::: :::: @@ -47,50 +47,46 @@ import numpy as np import pandas as pd from pretab import Preprocessor +rng = np.random.default_rng(0) df = pd.DataFrame({ - "age": np.random.randint(18, 65, size=100), - "income": np.random.normal(60_000, 15_000, size=100).astype(int), - "city": np.random.choice(["Berlin", "Munich", "Hamburg"], size=100), + "age": rng.integers(18, 65, size=100), + "income": rng.normal(60_000, 15_000, size=100).astype(int), + "city": rng.choice(["Berlin", "Munich", "Hamburg"], size=100), }) -y = np.random.randn(100) +y = rng.standard_normal(100) # One strategy per feature type: PLE for numerics, integer codes for categoricals -pre = Preprocessor(numerical_method="ple", categorical_method="int") -X = pre.fit_transform(df, y) # single stacked, model-ready array -X.shape -# (100, 15) +pre = Preprocessor(numerical_method="ple", categorical_method="int", task="regression") +X = pre.fit_transform(df, y) +assert X.shape == (100, 15) +assert len(pre.get_feature_lineage()) == X.shape[1] ``` -`Preprocessor` detects the column types, fits a strategy per column, and returns a single -stacked, model-ready array by default, so it drops straight into a plain -`sklearn.pipeline.Pipeline`; pass `output_structure="blocks"` for a dict of per-feature blocks -instead. Inspect the resolved layout at any time with `get_feature_info(verbose=True)`: - -```text -feature kind pipeline dim cats ----------------------------------------------------------------- -age numerical imputer -> minmax -> ple 7 - -income numerical imputer -> minmax -> ple 7 - -city categorical imputer -> continuous_ordinal 1 4 -``` +`Preprocessor` detects column types and returns one array by default. Pass +`output_structure="blocks"` to get a dictionary of feature blocks instead. After fitting, +`get_feature_lineage()` traces each output column back to its input. ### Mix strategies per column -Columns rarely want the same treatment. Pass a `feature_preprocessing` map to give each -column its own strategy, and a single `fit` still returns one coherent feature set: +Use `feature_preprocessing` to choose a different strategy for each column. The output +still has one row per input sample: ```python -pre = Preprocessor(feature_preprocessing={ - "age": "ple", # piecewise-linear encoding - "income": "rbf", # radial-basis expansion - "city": "one-hot", # one-hot categorical -}) +pre = Preprocessor( + feature_preprocessing={ + "age": "ple", + "income": "rbf", + "city": "one-hot", + }, + task="regression", +) X = pre.fit_transform(df, y) - -X.shape -# (100, 17) +assert X.shape == (100, 17) ``` +See [What's new in PreTab 1.1](getting_started/overview.md#whats-new-in-pretab-11) +for per-feature widths, grouped splines, and other 1.1 changes. + ## Get started ::::{grid} 1 1 3 3 diff --git a/docs/index.rst b/docs/index.rst index 43e660c..17f0992 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -68,4 +68,5 @@ :hidden: developer_guide/contributing + developer_guide/architecture developer_guide/release diff --git a/docs/representations/choosing_a_method.md b/docs/representations/choosing_a_method.md index 7524f36..158df00 100644 --- a/docs/representations/choosing_a_method.md +++ b/docs/representations/choosing_a_method.md @@ -15,15 +15,16 @@ The right representation depends on what sits downstream. ## Match the method to the signal -| If the relationship is... | Reach for... | -| --------------------------------- | ---------------------------------------- | -| Smooth and curved | B-spline, natural cubic spline, P-spline | -| Monotone (must not reverse) | I-spline | -| Sharp, threshold-like | PLE, numeric binning, ReLU expansion | -| Local bumps around centers | RBF expansion | -| Periodic (known period) | Periodic encoding, Fourier features | -| A smooth surface over two inputs | Tensor-product or thin-plate spline | -| A general kernel over many inputs | Random Fourier features, Nyström | +| If the relationship is... | Reach for... | +| ---------------------------------- | ----------------------------------------- | +| Smooth and curved | B-spline, natural cubic spline, P-spline | +| Monotone (must not reverse) | I-spline | +| Sharp, threshold-like | PLE, numeric binning, ReLU expansion | +| Local bumps around centers | RBF expansion | +| Periodic (known period) | Periodic encoding with an explicit period | +| Oscillations over the fitted range | Fourier features | +| A smooth surface over two inputs | Tensor-product or thin-plate spline | +| A general kernel over many inputs | Random Fourier features, Nyström | ```{tip} When unsure, start with the `"standard"` preset (min-max scaling, integer categoricals, and @@ -45,8 +46,10 @@ measure the difference instead of guessing. ## Control the width More columns means more flexibility and more overfitting risk. Start narrow and widen only if -validation improves. Turn on `adaptive=True` to let the data choose a width between -`min_output_dim` and `max_output_dim`. See +validation improves. For [methods that support adaptive sizing](comparison_table.md), +`adaptive=True` lets the data choose a width between `min_output_dim` and `max_output_dim`. +Inspect the fitted width before sizing a downstream model. Use a fixed width for cross-fitting +if adaptive sizing changes the width across folds. See [Resolution and placement](../core_concepts/resolution_and_placement.md). ## When basis expansion does not help @@ -87,11 +90,10 @@ PreTab is explicit about degenerate inputs rather than failing silently. tensor-product) raise a typed error rather than fitting a meaningless basis. Numeric binning falls back to a single bin instead of raising, and PLE and the feature maps place all their bins or centers at the same value, a degenerate but still valid basis. -- **Discrete or heavily tied column**: target-aware PLE and feature maps still get the - requested number of distinct bin edges or centers strictly inside the observed range. When - the tree finds fewer splits than requested, the shortfall is filled with spaced quantile - points and then evenly spaced points, so the output width does not depend on the data (or - on the cross-fitting fold). +- **Discrete or heavily tied column**: in fixed-width mode, PLE and target-aware feature maps + fill in missing tree splits with additional points inside the observed range of a nonconstant + feature to keep the requested width. Adaptive mode can choose a narrower width. Unsupervised + quantile binning instead merges duplicate edges, so it can produce fewer bins than requested. - **Out-of-range input at transform**: B/M/I-spline, P-spline, and tensor-product clip values beyond the fitted range by default; natural-cubic and cubic-regression extrapolate smoothly by default. Pass `policy=RepresentationPolicy(out_of_range=...)` directly to any diff --git a/docs/representations/comparison_table.md b/docs/representations/comparison_table.md index 8d81a3c..e8396b6 100644 --- a/docs/representations/comparison_table.md +++ b/docs/representations/comparison_table.md @@ -43,7 +43,10 @@ source of truth, and these tables mirror it. ```{note} The multivariate splines (`tensorspline`, `tprs`) model several inputs jointly and are used -standalone, not selected per column through `Preprocessor`. The alias `thinplate` resolves to +through `Preprocessor(feature_groups=...)` or their standalone transformers, not +per-column `numerical_method`. See the +[grouped preprocessing tutorial](../tutorials/multivariate_features.md). +The alias `thinplate` resolves to `tprs`. `ThinPlateSplineTransformer.get_penalty_matrix()` is experimental: it is not guaranteed positive semi-definite (the retained eigenvalues of the projected landmark kernel can be negative) and emits a `ConfigWarning` on every call. `transform()` is unaffected; only the diff --git a/docs/representations/embeddings.md b/docs/representations/embeddings.md index b4e48d9..80f8598 100644 --- a/docs/representations/embeddings.md +++ b/docs/representations/embeddings.md @@ -17,18 +17,18 @@ t.fit_transform(X).shape # model's own dimensionality once fitted, e.g. via t.embedding_dim_ ``` -Constructor highlights: `model_name="paraphrase-MiniLM-L3-v2"`, or pass a preloaded `model` -(useful for tests or a custom embedding backend without pulling in `sentence-transformers`). -Any object with a `.encode(X)` method works for the `transform` step; `embedding_dim_` is -read from `get_sentence_embedding_dimension()` when the model exposes it (as a real -`SentenceTransformer` does), falling back to a `dim` attribute, or, if neither is present, -probed by calling `.encode()` once on a placeholder input during `fit`. The registry key is -`pretrained`. +Use `model_name` to load a pretrained model, or pass a preloaded `model` to the standalone +transformer. A custom model must accept `encode(texts, convert_to_numpy=True)`, where `texts` +is a list of strings, and return a two-dimensional numeric array with one row per string. +During `fit`, PreTab obtains `embedding_dim_` from `get_sentence_embedding_dimension()` or +the model's `dim` attribute. If neither is available, it calls `encode` with the same keyword +on a placeholder string to determine the width. ```{important} -Language embeddings require the optional `embeddings` extra, which pulls in -`sentence-transformers`. Install it with `pip install "pretab[embeddings]"`. Without it, -requesting `pretrained` raises a clear `OptionalDependencyError`. +Loading a model by name or selecting the `pretrained` registry method requires the optional +`embeddings` extra. Install it with `pip install "pretab[embeddings]"`; otherwise these paths +raise `OptionalDependencyError`. A preloaded `model` passed to the standalone transformer +does not require `sentence-transformers`. ``` ```{note} diff --git a/docs/representations/functional_expansions.md b/docs/representations/functional_expansions.md index 98fa2bc..5a02ee9 100644 --- a/docs/representations/functional_expansions.md +++ b/docs/representations/functional_expansions.md @@ -6,9 +6,10 @@ ramps, sigmoids) or project it onto a deterministic Fourier basis. Together they threshold, and periodic structure with a per-column, `Preprocessor`-selectable transformer. ```{important} -As with splines, `output_dim` (or `n_frequencies` for the Fourier map) is the number of output -columns **per input feature**. A `(n_samples, 3)` input with `output_dim=10` produces -`(n_samples, 30)` output. +For fixed-width RBF, ReLU, sigmoid, and tanh expansions, `output_dim` counts output columns +**per input feature**: three inputs with `output_dim=10` produce 30 columns. Fourier counts +frequencies instead: three inputs with `n_frequencies=10` produce 60 sine and cosine columns, +or 63 columns when `include_original=True`. ``` ## Radial basis functions @@ -42,10 +43,12 @@ Constructor highlights: `output_dim`, `gamma=1.0` (bump width; larger is narrowe ``` ```{warning} -`target_aware=True` places centers using a supervised tree over `(X, y)`. Fitting it directly -on your full training set (outside a `Pipeline` or `pretab.CrossFittedTransformer`) raises a -`LeakageWarning`, because the center placement has already seen the labels you would then train -on. The same applies to ReLU, sigmoid, and tanh below whenever `target_aware=True`. +`target_aware=True` places centers using a supervised tree over `(X, y)`. A standalone fit with +`y` emits `LeakageWarning`. For evaluation, split before fitting or cross-validate the whole +pipeline. A plain pipeline still uses the training rows' targets to place their centers; +wrap the expansion in `pretab.CrossFittedTransformer` for out-of-fold training features. +This also applies to ReLU, sigmoid, and tanh whenever `target_aware=True`. See +[Target awareness](../core_concepts/target_awareness.md). ``` ## ReLU, sigmoid, and tanh expansions @@ -107,8 +110,9 @@ from pretab.transformers import FourierFeatureTransformer X = np.linspace(0, 1, 50).reshape(-1, 1) t = FourierFeatureTransformer(n_frequencies=5, frequency_strategy="harmonic") -t.fit_transform(X).shape -# (50, 10): 2 columns (sin, cos) per frequency +encoded = t.fit_transform(X) +assert encoded.shape == (50, 10) +np.testing.assert_allclose(encoded[0], encoded[-1], atol=1e-12) ``` Constructor highlights: `n_frequencies=5`, `frequency_strategy="harmonic"`, @@ -121,9 +125,10 @@ the base frequency (1x, 2x, 3x, ...); the alternative spacing is useful when the a clean harmonic series. ```{tip} -Use `FourierFeatureTransformer` when you want the model to work across a set of frequencies -without committing to a single known period. If the period is known (hour of day, month of -year), the direct [periodic encoder](numerical_encoding.md#periodic-encoding) is usually simpler. +Use `FourierFeatureTransformer` for a range-based frequency basis. The fitted range sets the +base frequency; it is not an estimate of the signal's period. For example, the harmonic map +repeats every 23 units if fitted on hours 0 through 23. To encode a 24-hour cycle, use +the [periodic encoder](numerical_encoding.md#periodic-encoding) with `period=24`. ``` ## Where to go next diff --git a/docs/representations/kernel_approximation.md b/docs/representations/kernel_approximation.md index bf155aa..10ef2a5 100644 --- a/docs/representations/kernel_approximation.md +++ b/docs/representations/kernel_approximation.md @@ -47,15 +47,16 @@ them, following Williams and Seeger. It supports several kernels through `kernel more accurate than random Fourier features at a given output width because the landmarks adapt to the data rather than being drawn at random. For landmarks $z_1, \dots, z_m$ (the sampled training rows) and kernel function $K$, let $k_m(x) = \big(K(x, z_1), \dots, K(x, z_m)\big)$ be -the vector of kernel evaluations between $x$ and every landmark. The output is +the vector of kernel evaluations between $x$ and every landmark. For a positive-semidefinite +landmark kernel matrix, the map takes the form $$ \phi(x) = K_{mm}^{-1/2}\ k_m(x), $$ -where $K_{mm}$ is the $m \times m$ kernel matrix between the landmarks themselves, and -$K_{mm}^{-1/2}$ is computed once at fit time via its eigendecomposition. The inner product -$\phi(x)^\top \phi(x')$ approximates $K(x, x')$. +where $K_{mm}$ is the $m \times m$ kernel matrix between the landmarks. Scikit-learn computes +the normalization at fit time using SVD, flooring small singular values before taking their +inverse square roots. The inner product $\phi(x)^\top \phi(x')$ approximates $K(x, x')$. ```python import numpy as np @@ -63,20 +64,19 @@ from pretab.transformers import NystroemFeaturesTransformer X = np.random.default_rng(0).uniform(size=(200, 3)) t = NystroemFeaturesTransformer(n_components=100, kernel="rbf") -t.fit_transform(X).shape -# (200, 100) +assert t.fit_transform(X).shape == (200, 100) ``` Constructor highlights: `n_components=100`, `kernel="rbf"`, `gamma=None`, `degree=3`, `coef0=1`, `random_state`. ```{warning} -Nyström samples its landmarks from the training rows, so `n_components` cannot exceed -`n_samples`. If you fit on fewer rows than `n_components` (for example a small -cross-validation fold), scikit-learn silently clamps `n_components` down to `n_samples` and -emits a `UserWarning` rather than raising: the fitted output width is `min(n_components, -n_samples_seen_in_fit)`. Random Fourier features have no such limit, since they draw a random -basis instead of sampling training rows. +Nyström samples its landmarks from the training rows. If a fit has fewer rows than +`n_components` (for example in a small cross-validation fold), scikit-learn emits a +`UserWarning` and uses all the available rows as landmarks. The fitted width is +`min(n_components, n_samples_seen_in_fit)`; the requested `n_components` remains unchanged. +Random Fourier features have no such limit because they draw a random basis instead of +sampling training rows. ``` ```{note} diff --git a/docs/representations/numerical_encoding.md b/docs/representations/numerical_encoding.md index 0799fcd..75ebdcc 100644 --- a/docs/representations/numerical_encoding.md +++ b/docs/representations/numerical_encoding.md @@ -17,37 +17,40 @@ from pretab.transformers import NumericBinningTransformer X = np.random.default_rng(0).uniform(size=(100, 1)) # (100, 1) onehot = NumericBinningTransformer(output_dim=8, encode="onehot", placement_strategy="quantile") -onehot.fit_transform(X).shape -# (100, 8): one column per bin +assert onehot.fit_transform(X).shape == (100, 8) ordinal = NumericBinningTransformer(output_dim=8, encode="ordinal", placement_strategy="quantile") -ordinal.fit_transform(X).shape -# (100, 1): a single integer column, regardless of output_dim +assert ordinal.fit_transform(X).shape == (100, 1) + +tied = np.repeat([0, 1, 2], 3).reshape(-1, 1) +for encoding in ("onehot", "soft"): + binner = NumericBinningTransformer(output_dim=8, encode=encoding, placement_strategy="quantile") + assert binner.fit_transform(tied).shape == (9, 2) + assert binner.n_bins_ == [2] ``` -The `encode` parameter selects the output form, and it changes the output **width**, not just -the values: `"onehot"` produces `output_dim` columns, while `"ordinal"` and `"soft"` behave -differently from each other despite both accepting the same `output_dim`. +`output_dim` requests a bin count per input feature. Quantile placement merges duplicate +edges, so tied data can yield fewer bins than requested. A constant feature falls back to +one bin. Inspect `n_bins_` for the fitted counts. The `encode` parameter determines how those +bins become output columns: `"ordinal"` -: A single integer column giving the bin index (output width is always 1, independent of -`output_dim`). +: One integer column per input feature, giving the bin index regardless of the bin count. `"onehot"` -: One indicator column per bin (output width equals `output_dim`). +: One indicator column per fitted bin. `"soft"` : A soft assignment that spreads each value across neighbouring bins, so the boundaries are not -hard (output width equals `output_dim`, same shape as `"onehot"` but with fractional -membership instead of a single 1). +hard. It emits one column per fitted bin, like `"onehot"`, but with fractional memberships. Edge placement follows `placement_strategy`: `"uniform"` for equal-width bins, `"quantile"` for equal-frequency bins. See [Resolution and placement](../core_concepts/resolution_and_placement.md). ```{tip} -Quantile edges give every bin a similar number of samples, which is usually more stable than -equal-width bins when the feature is skewed. +When the feature has few ties, quantile edges give bins similar sample counts, which can be +more stable than equal-width bins on skewed data. ``` ## Piecewise-linear encoding @@ -64,10 +67,8 @@ from pretab.transformers import PLETransformer X = np.random.default_rng(0).uniform(size=(100, 1)) y = np.random.default_rng(0).integers(0, 2, size=100) t = PLETransformer(output_dim=12, task="classification") -t.fit_transform(X, y).shape -# (100, 12): output_dim is exact here (no adaptive clamping) -t.total_output_dim_ -# 12 +assert t.fit_transform(X, y).shape == (100, 12) +assert t.total_output_dim_ == 12 ``` Constructor highlights: `output_dim`, `placement_strategy="cart"`, `task="regression"`, @@ -80,10 +81,11 @@ and should be fit leakage-safely, ideally with cross-fitting. See ``` ```{warning} -Because PLE always reads `y` to place its bins, fitting it directly on data you will also train -on emits a `LeakageWarning`. Fit it inside a scikit-learn `Pipeline` or wrap it in -`pretab.CrossFittedTransformer` so the bin edges never see the rows they will later transform -for training. +The standalone fit above emits `LeakageWarning` because PLE uses `y` to place its bins. For +evaluation, split before fitting or pass the entire scikit-learn `Pipeline` to +cross-validation. A plain pipeline suppresses the warning but still uses each training +row's target when fitting its bins. For out-of-fold training features, wrap PLE in +`pretab.CrossFittedTransformer` and use `fit_transform(X, y)`. ``` ### Why piecewise-linear rather than one-hot @@ -108,12 +110,18 @@ opposite ends of a number line. ```python import numpy as np +from pretab.exceptions import PretabDataError from pretab.transformers import PeriodicEncodingTransformer X = np.array([[0], [6], [12], [18], [24]]) # hour-of-day style values t = PeriodicEncodingTransformer(period=24, harmonics=2) # e.g. hour of day -t.fit_transform(X).shape -# (5, 4): 2 columns (sin, cos) per harmonic +encoded = t.fit_transform(X) +assert encoded.shape == (5, 4) +np.testing.assert_allclose(encoded[0], encoded[-1], atol=1e-12) +np.testing.assert_allclose(t.transform([[25], [-1]]), t.transform([[1], [23]]), atol=1e-12) + +with np.testing.assert_raises(PretabDataError): + PeriodicEncodingTransformer(period=24).fit([[0], [25]]) ``` Constructor highlights: `period` (required, the cycle length), `harmonics=1`, @@ -124,25 +132,19 @@ one extra column when `include_original=True`. Higher `harmonics` lets the encod finer-grained sub-cycles (for example distinguishing morning from afternoon within a day), at the cost of a wider output. -```{warning} -PreTab has no mechanism to detect the period automatically from the data. `period` is a -required constructor argument with no default, and `fit` only validates that values fall -within `[0, period]`, it never infers the cycle length. You must know and supply the period -yourself (24 for hour of day, 7 for day of week, 12 for month of year, and so on). -``` - ```{important} -Valid input is the **closed interval** `[0, period]`: both endpoints are accepted, and by -construction they map to the identical `(sin, cos)` pair, since `x=0` and `x=period` are the -same point on the cycle. Values outside `[0, period]` raise a `PretabDataError` at fit and -transform, there is no silent wrap-around or clamping. +Supply the period explicitly. `fit` does not infer it and raises `PretabDataError` if a +training value falls outside `[0, period]`. Both endpoints are accepted and their harmonic +columns agree up to floating-point precision. After fitting, `transform` accepts values +outside that interval and the sine and cosine terms wrap around the cycle. If +`include_original=True`, the extra raw column is not wrapped. ``` ```{note} Periodic encoding is a standalone time-series utility. It is not wired into `Preprocessor` because it requires a per-feature `period`, so apply it directly to the relevant cyclical -column. Use [Fourier features](functional_expansions.md#fourier-features) instead when you want -the model to search across a set of frequencies rather than commit to one known period. +column. [Fourier features](functional_expansions.md#fourier-features) instead set their base +frequency from the fitted range; they do not infer a cycle length from the data. ``` ## Binning versus PLE diff --git a/docs/representations/overview.md b/docs/representations/overview.md index 13474b2..9f49282 100644 --- a/docs/representations/overview.md +++ b/docs/representations/overview.md @@ -57,12 +57,12 @@ Pretrained language embeddings for high-cardinality text categories. Every family is described with the same terms, introduced in [Preprocessing and representation](../core_concepts/feature_representation.md). -| Term | Meaning | -| ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `scope` | `univariate` methods transform one column at a time. `multivariate` methods such as tensor-product spline, thin-plate spline, random Fourier features, and Nyström model several columns jointly and are used standalone, not per column through `Preprocessor`. | -| `supervision` | Whether the method uses the target: `forbidden`, `optional`, or `required`. See [Target awareness](../core_concepts/target_awareness.md). | -| `output_dim` | The width of the expansion. See [Resolution and placement](../core_concepts/resolution_and_placement.md). | -| `placement` | Where the knots, centers, or edges are placed, chosen via `target_aware` and `placement_strategy`. | +| Term | Meaning | +| ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `scope` | `univariate` methods transform one column at a time. `multivariate` methods model several columns jointly. Tensor-product and thin-plate splines support `Preprocessor(feature_groups=...)`; random Fourier features and Nyström are standalone-only. | +| `supervision` | Whether the method uses the target: `forbidden`, `optional`, or `required`. See [Target awareness](../core_concepts/target_awareness.md). | +| `output_dim` | The width of the expansion. See [Resolution and placement](../core_concepts/resolution_and_placement.md). | +| `placement` | Where the knots, centers, or edges are placed, chosen via `target_aware` and `placement_strategy`. | ## How to select a method diff --git a/docs/representations/spline_expansions.md b/docs/representations/spline_expansions.md index ced5a12..10028bc 100644 --- a/docs/representations/spline_expansions.md +++ b/docs/representations/spline_expansions.md @@ -1,29 +1,29 @@ # Spline expansions -Splines are piecewise-polynomial bases with local support. They turn a single numerical column -into a set of smooth, overlapping basis functions, so a linear model on top can bend to follow -the data while staying stable. PreTab ships the full family, from the workhorse B-spline to the -multivariate thin-plate spline. +Knot-based splines turn a numerical column into piecewise-polynomial basis functions, so a +linear model can fit a smooth curve. Some bases, such as B-splines, have local support. PreTab +also provides multivariate splines for modeling smooth surfaces over several inputs. ## The idea A spline places a set of **knots** along the range of a feature and builds basis functions -between them. The transformed feature is the vector of basis values, +between them. The transformed feature is the vector of basis values: $$ -x \mapsto \big(B_1(x),\ B_2(x),\ \dots,\ B_K(x)\big), +x \mapsto \big(B_1(x),\ B_2(x),\ \dots,\ B_K(x)\big). $$ -where each $B_k$ is nonzero only near a few knots. Local support is what keeps splines stable: -a point in one region does not disturb the fit in another. Width is set by `output_dim` and -knot positions by `placement_strategy` (see +For a B-spline basis, each $B_k$ is nonzero only near a few knots, so changing one coefficient +affects the fitted curve only in that region. Configure width with `output_dim` and knot +placement with `placement_strategy` (see [Resolution and placement](../core_concepts/resolution_and_placement.md)). ```{important} -Without explicit knots, `output_dim` is the number of output columns for a univariate spline -**per input feature**, not the total. A `(n_samples, 3)` input produces -`(n_samples, 3 * output_dim)` output (plus one extra column per feature if -`include_bias=True`). Feature names are suffixed per input, for example `age_bs0, age_bs1, ...` +In fixed-width mode with automatic knot placement, a standalone univariate spline emits +`output_dim` columns **per input feature**, plus one per feature if `include_bias=True`. +With adaptive sizing, supported families can fit different widths for different features. +Check `n_basis_` for the per-feature widths, including any bias, or `total_output_dim_` for the +total. Feature names are suffixed per input, for example `age_bs0, age_bs1, ...` for a B-spline fitted on a DataFrame column `age` (`x0_bs0, x0_bs1, ...` for array input). For B/M/I splines with explicit `knot_locations`, a feature with `K` retained unique interior knots instead gets `K + degree + 1` non-bias columns; @@ -67,9 +67,8 @@ smoother, wider-support basis functions at the same `output_dim`; `degree=1` rec piecewise-linear segments. `output_dim` -: The exact per-feature output width (unlike the cubic/natural/tensor families below, no -conversion is applied). Ignored when `knot_locations` is provided. More columns track finer -local detail and increase overfitting risk. +: The per-feature width before any bias in fixed-width mode. Explicit `knot_locations` +override this request. More columns track finer local detail and increase overfitting risk. `include_bias` : Defaults to `False`. A B-spline basis over a clamped knot vector already sums to 1 in every @@ -83,13 +82,10 @@ Increase `output_dim` for more wiggle, decrease it to regularize. ``` ```{note} -Every spline in this family exposes `get_penalty_matrix(feature_index=0, diff_order=2)`, a -`D^T D` second-difference penalty matrix of shape `(m, m)`, where `m` is the fitted non-bias -width (plus the bias -row/column left unpenalized when `include_bias=True`). It is not limited to the "penalized" -splines further down this page. Note that `diff_order` is specific to this B/M/I family; the -cubic, natural cubic, P-spline, tensor-product, and thin-plate variants expose -`get_penalty_matrix(feature_index=0)` with their own fixed penalty construction instead. +The B/M/I family exposes `get_penalty_matrix(feature_index=0, diff_order=2)` and +the corresponding typed `get_penalty_spec()`. The returned matrix covers the +fitted output width, including a zero row and column for the leading bias if present. +See [Typed spline penalties](#typed-spline-penalties) for the other families. ``` ## M-spline and I-spline @@ -153,8 +149,8 @@ Requires `output_dim >= 2`. For knots $\xi_1, \dots, \xi_T$ ($\xi_1$, $\xi_T$ th knots), the basis stacks $x$ with one constrained term per interior knot $\xi_k$, $$ -d_k(x) = \frac{(x - \xi_k)_+^3 - (x - \xi_T)_+^3}{\xi_T - \xi_k}, \qquad -N_k(x) = d_k(x) - \frac{\xi_T - \xi_k}{\xi_T - \xi_1} d_1(x) - \frac{\xi_k - \xi_1}{\xi_T - \xi_1} d_T(x). +d_k(x) = (x - \xi_k)_+^3 - (x - \xi_T)_+^3, \qquad +N_k(x) = d_k(x) - \frac{\xi_T - \xi_k}{\xi_T - \xi_1} d_1(x), \quad k = 2, \ldots, T - 1. $$ ```python @@ -164,9 +160,12 @@ from pretab.transformers import NaturalCubicSplineTransformer X = np.linspace(0, 1, 50).reshape(-1, 1) t = NaturalCubicSplineTransformer(output_dim=8) X2 = t.fit_transform(X) -X2.shape # (50, 8): output width equals output_dim exactly -t.n_knots_ # [7]: fitted interior-knot count per feature (output_dim - 1) -t.get_penalty_matrix().shape # (8, 8) +assert X2.shape == (50, 8) +assert t.n_knots_ == [7] +assert t.get_penalty_matrix().shape == (8, 8) + +tail = t.transform([[1.0], [1.25], [1.5]]) +np.testing.assert_allclose(np.diff(tail, n=2, axis=0), 0, atol=1e-12) ``` ```{tip} @@ -186,9 +185,9 @@ $$ \lambda\, \beta^\top D^\top D\, \beta, $$ -where $D$ is the `diff_order`-th order difference operator (the same matrix returned by -`get_penalty_matrix()`) and $\lambda$ is chosen by the downstream penalized model, not by -`PSplineTransformer` itself. +where $D$ is the `diff_order`-th order difference operator. `get_penalty_matrix()` +returns $D^\top D$, padded for the optional unpenalized bias. The downstream model, +not `PSplineTransformer`, chooses $\lambda$ and adds the penalty to its loss. ```python import numpy as np @@ -201,8 +200,8 @@ t.get_penalty_matrix().shape # (8, 8) ``` Constructor highlights: `output_dim`, `degree=3`, `diff_order=2`, `include_bias=False`, -`placement_strategy="uniform"`, `adaptive`. The P-spline is unsupervised; it does not read the -target. +`placement_strategy="uniform"`. The P-spline uses uniformly spaced knots and a fixed width; +it does not read the target. **Parameter impact.** `diff_order` sets the order of the penalty: `diff_order=1` penalizes changes in level between adjacent coefficients (favors flat fits), `diff_order=2` (the default) @@ -216,8 +215,9 @@ penalty do the regularizing. Its penalty matrix plugs directly into penalized li ## Multivariate splines -Two families model several inputs jointly. They are used standalone, not selected per column -through `Preprocessor`. +Two families model several inputs jointly. Use them through +`Preprocessor(feature_groups=...)` for exclusive numerical groups, or fit their +standalone transformers directly. Neither is a per-column `numerical_method`. ### Tensor-product spline @@ -230,8 +230,9 @@ $$ \Phi_{k_1, \dots, k_d}(x_1, \dots, x_d) = \prod_{j=1}^{d} B_{k_j}(x_j). $$ -It exposes an anisotropic penalty per marginal via -`get_penalty_matrix(feature_index=...)`. +`get_penalty_matrix(feature_index=...)` returns a marginal matrix. +`get_penalty_specs()` returns one full joint matrix per source direction, ready +to apply to the coefficients of the tensor basis. ```python import numpy as np @@ -286,12 +287,107 @@ non-negative, so the returned penalty is not guaranteed positive semi-definite, actual smoothing regularization until it is fully fixed. ``` -```{warning} -The tensor-product and thin-plate splines are multivariate. They are standalone transformers -and are not available as a per-column `numerical_method`. Fit them directly on the columns you -want to model jointly. +```{note} +Use `feature_groups` to select the joint sources inside `Preprocessor`. A group +has one fitted width and one output block, including its raw missing states. +The [multivariate tutorial](../tutorials/multivariate_features.md) shows how to +configure groups and inspect the actual width rather than assigning it to each source. +``` + +## Typed spline penalties + +Fit the spline first, then call its typed accessor. Each {py:class}`pretab.PenaltySpec` +pairs a penalty matrix with the ordered `coefficient_names` and zero-based +`coefficient_indices` of the fitted transformer's output. `axis` identifies the +input direction. It does not index the coefficients. The legacy matrix accessors +remain available, and neither accessor changes the fitted basis or trains a model. + +| Spline family | Typed accessor | Matrix convention | +| ---------------------------- | ---------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- | +| B-spline, M-spline, I-spline | `get_penalty_spec(feature_index=0, diff_order=None)` | Coefficient differences. Defaults to order 2; the accessor accepts an explicit order. | +| P-spline | `get_penalty_spec(feature_index=0)` | Coefficient differences of fitted order 1 or 2. Higher orders remain available through the legacy accessor. | +| Natural cubic | `get_penalty_spec(feature_index=0)` | Approximate integrated squared second derivative, using finite differences and trapezoidal integration. | +| Cubic regression | `get_penalty_spec(feature_index=0)` | Integrated squared second derivative, using piecewise Simpson integration, exact in exact arithmetic. | +| Tensor-product | `get_penalty_specs()` | One full joint coefficient-difference matrix per fitted axis, using the fitted order. | +| Thin-plate | None | Experimental legacy matrix only; positive semidefiniteness is not guaranteed. | + +For $m$ selected coefficients, `matrix` is a detached, read-only `float64` +array of shape $(m, m)$. Let $P$ denote that matrix and $\beta$ the coefficient +vector in the recorded order. The unweighted penalty is $\beta^\top P\beta$, +with no implicit factor of $1/2$. Symmetry, positive semidefiniteness and +numerical rank use the recorded tolerance `atol + rtol * spectral_norm`, where +the norm is of the symmetric part of $P$. Eigenvalues above that threshold +count toward `rank`; `nullity` is $m$ minus `rank`. Accepted entries are not +rounded, clipped, or symmetrized. A penalty can be singular without being invalid. + +For coefficient differences, $P = D^\top D$ and the penalty is +$\lVert D\beta\rVert_2^2$. A difference penalty of order $r$ on $q$ non-bias +coefficients has rank $q-r$ and nullity $r$ when $1 \le r < q$; a leading +bias is unpenalized and adds one null direction. Differences operate on the +ordered coefficients, not derivatives in input units. The two curvature +penalties instead integrate over their fitted input domains. The linear term +and any explicit bias have zero curvature. Scaling inputs before fitting can +change these curvature matrices, even if the output width stays the same. + +The tensor matrices share the full joint coefficient order (C order, with the +last declared axis varying fastest). Each direction applies a marginal +difference operator along its axis, holding the others fixed. With marginal +bias enabled, that direction leaves its own bias index unpenalized; other +directions may still penalize such terms. Apply the matrices to the same +joint coefficients and add their quadratic forms with nonnegative weights +$\lambda_j$. Do not substitute marginal matrices or add matrices defined in +different coefficient coordinates without first aligning them. + +### Fit with a quadratic penalty + +This example fits a P-spline basis, then uses its penalty in a least-squares +model. Because the example uses the **sum** of squared residuals, the normal +equations add $\lambda P$ to the design's Gram matrix. A mean-reduced loss uses +a different effective weight, so choose the weight for your loss convention. + +```python +import numpy as np +from pretab.transformers import PSplineTransformer + +source = np.linspace(0.0, 1.0, 80) +features = source.reshape(-1, 1) +target = np.sin(2.0 * np.pi * source) +spline = PSplineTransformer(output_dim=6, diff_order=2, include_bias=False).fit(features) +penalty = spline.get_penalty_spec() +indices = np.asarray(penalty.coefficient_indices) +assert tuple(spline.get_feature_names_out()[indices]) == penalty.coefficient_names +design = spline.transform(features)[:, indices] + +weight = 0.1 +matrix = penalty.matrix +coefficients = np.linalg.solve(design.T @ design + weight * matrix, design.T @ target) +residuals = design @ coefficients - target +roughness = coefficients @ matrix @ coefficients +loss = residuals @ residuals + weight * roughness + +assert np.isfinite(loss) +np.testing.assert_allclose(roughness, np.sum(np.diff(coefficients, n=2) ** 2)) ``` +### Use in DeepTab and other estimators + +Apply the quadratic form to the downstream weights that multiply the spline +basis columns directly, not to the input values or activations. `coefficient_indices` +are local to the fitted transformer's output. In a combined model input, use the +fitted block layout and output lineage to find the corresponding columns. For +a tensor group, keep the full joint basis in one block; do not split the penalty +by source or include raw missing indicators in it. The +[multivariate tutorial](../tutorials/multivariate_features.md) shows how to +inspect that fitted layout. This is consumer guidance, not a DeepTab configuration API. + +For a tensor-based training loop, copy the read-only array to a fixed tensor +on the coefficients' device and dtype. If you have several coefficient vectors +for the same basis (for example, several output units), compute the form for each +vector and reduce the results consistently with your task loss. Recheck the +alignment after refitting or changing the design. `to_summary()` can log the +convention, coordinates, numerical rank and matrix checksum without including +the matrix. It is not a way to restore the matrix or train from the summary alone. + ## Where to go next - [Functional expansions](functional_expansions.md) for non-spline bases. diff --git a/docs/tutorials/adaptive_resolution.md b/docs/tutorials/adaptive_resolution.md index 6f7870a..d055410 100644 --- a/docs/tutorials/adaptive_resolution.md +++ b/docs/tutorials/adaptive_resolution.md @@ -1,31 +1,21 @@ # Adaptive resolution -Picking the width of an expansion by hand is guesswork. Adaptive resolution lets the data -choose it for you, within bounds you set. This tutorial shows how to turn it on and how to read -the width that was selected. +Adaptive resolution lets supported representations adjust their width at fit time. This tutorial +shows how to set a search window and how to read the fitted width. ## The idea -Every adaptive-capable method accepts three parameters that turn a fixed width into a searched -one. +Adaptive-capable methods accept three settings: `adaptive=True` -: Enables data-driven width selection. +: Enables width adaptation on supported placement paths. `min_output_dim` and `max_output_dim` -: The lower and upper bounds of the search. The method picks a width in this range. - -When adaptive is on and both bounds are set, `output_dim` is ignored completely: the fitted -width comes only from `[min_output_dim, max_output_dim]` and the data. If you leave one bound -unset, `output_dim` fills in for it (as the missing lower or upper edge of the search), so it -still matters in that case. See -[Resolution and placement](../core_concepts/resolution_and_placement.md) for the mechanics. - -```{warning} -Setting `output_dim` alongside `adaptive=True` with both `min_output_dim` and `max_output_dim` -is harmless but silently has no effect. It is easy to assume it caps or anchors the search; it -does not. Drop it, or drop one of the two bounds if you meant `output_dim` to anchor the window. -``` +: The requested lower and upper bounds. The final width also depends on the method and data. + +When a supervised search runs, two explicit bounds define its search window. If a bound is +omitted, `output_dim` helps determine the missing edge. The requested `output_dim` must still +be valid for the method, even when both bounds are set. ## A worked example @@ -34,8 +24,10 @@ one chose. ```python import warnings + import numpy as np -import pandas as pd + +from pretab.exceptions import LeakageWarning from pretab.transformers import BSplineTransformer rng = np.random.default_rng(0) @@ -51,7 +43,7 @@ for name, y in [("simple", simple), ("wiggly", wiggly)]: target_aware=True, placement_strategy="cart", task="regression", ) with warnings.catch_warnings(): - warnings.simplefilter("ignore") # one-off fit, not reused to train a model + warnings.simplefilter("ignore", LeakageWarning) t.fit(x.reshape(-1, 1), y) print(f"{name:8s} -> selected width {t.total_output_dim_}") ``` @@ -61,12 +53,9 @@ simple -> selected width 20 wiggly -> selected width 20 ``` -Both widths land inside the `[5, 20]` window without you having to guess a number up front. -Here both reach the upper bound: with 3000 samples the CART selector finds more informative -splits than the window admits, so it keeps the most informative ones. Its split count is governed -more by its own tree depth and minimum-samples settings than by how wiggly the signal looks; with -smaller data or a wider window the two searches can land on different widths. The bound is what -you control directly, the exact count inside it is data-driven. +Both fits reach the upper bound in this example. Adaptive width reflects the splits the CART +selector finds under its tree settings. A more irregular signal does not necessarily get more +columns. ```{note} Fitting a target-aware transformer directly like this, outside a `Pipeline`, normally emits a @@ -75,53 +64,59 @@ output is never used to train a downstream model. See [Target awareness](../core_concepts/target_awareness.md) for when the warning matters. ``` -```{note} -Adaptive resolution only takes effect on the target-aware placement path -(`target_aware=True`, paired with `placement_strategy="cart"` or `"lightgbm"`). With the -default `target_aware=False`, `adaptive=True` is a silent no-op and the transformer keeps its -ordinary fixed `output_dim` width. -``` +## Adaptation without a target -```{tip} -Set `min_output_dim` and `max_output_dim` to a range you consider reasonable, then let the data -place the width inside it. This is more robust than committing to a single `output_dim` across -features of different complexity. +B-, M-, and I-splines can also adapt without a target. They start from `output_dim` and adjust +the unsupervised knots toward the requested bounds. For example, a target-free B-spline with +bounds `[4, 6]` can keep a requested width of 5 or reduce a requested width of 12 to 6. +By contrast, natural cubic splines and maps such as RBF and ReLU keep their ordinary fixed +sizing on the target-free path. PLE always uses the target and does not require a +`target_aware` flag. + +```{note} +B-, M-, and I-splines cap the number of interior knots by the number of distinct input +values. A column with few distinct values can produce fewer columns than `min_output_dim`. +Use the fitted width for any downstream model or size check. ``` ## Adaptive across a whole preprocessor -The same switch works at the `Preprocessor` level, so every eligible column adapts -independently. +`Preprocessor` passes the global settings to eligible features, which are fitted independently. +This example applies the target-free B-spline settings to two columns with enough distinct values. ```python import pandas as pd from pretab import Preprocessor -df = pd.DataFrame({"simple": simple, "wiggly": wiggly}) +df = pd.DataFrame({"value": x, "squared": x**2}) pre = Preprocessor( numerical_method="bspline", + output_dim=12, adaptive=True, - min_output_dim=5, - max_output_dim=15, + min_output_dim=4, + max_output_dim=6, + target_aware=False, + placement_strategy="quantile", ) -pre.fit(df, wiggly) -pre.get_feature_info() +pre.fit(df) +assert pre.output_dims_ == {"value": 6, "squared": 6} +assert pre.total_output_dim_ == 12 ``` -Each numerical column receives a width suited to its own complexity, visible in the resolved -feature info. +`output_dims_` and `total_output_dim_` describe the fitted output, not the requested width +or bounds. For a per-feature breakdown, call `pre.get_feature_info()` after fitting. ```{note} -Adaptive resolution is available for B/M/I splines, the freely-placed cubic and natural cubic -splines, PLE, and the RBF, ReLU, sigmoid, and tanh feature maps. The penalized P-spline and the -tensor-product and thin-plate splines have a fixed structure and ignore the adaptive flag. The -[comparison table](../representations/comparison_table.md) marks which methods adapt. +The [comparison table](../representations/comparison_table.md) marks which methods support +adaptive resolution. An unsupported method such as P-spline ignores the global adaptive +setting. An explicit per-feature `RepresentationConfig("pspline", adaptive=True)` is +rejected when `Preprocessor` validates its configuration. ``` ## Where to go next -- [Resolution and placement](../core_concepts/resolution_and_placement.md) for how width and - placement interact. +- [Placement strategies](../core_concepts/resolution_and_placement.md#placement-where-the-units-go) + for how the locations of knots and centers are chosen. - [Comparing representations](comparing_representations.md) to measure adaptive against fixed. - [Choosing a method](../representations/choosing_a_method.md) for width guidance. diff --git a/docs/tutorials/comparing_representations.md b/docs/tutorials/comparing_representations.md index 4d4d10b..5fbdc11 100644 --- a/docs/tutorials/comparing_representations.md +++ b/docs/tutorials/comparing_representations.md @@ -1,8 +1,7 @@ # Comparing representations -Choosing a representation should be an experiment, not a guess. This tutorial evaluates several -numerical methods on the same task with the same model, so the only thing that varies is the -basis. The pattern generalizes to any dataset you have. +Compare numerical representations on the same task, with the same folds and downstream model. +This tutorial measures both validation scores and fitted widths for each candidate. ## The setup @@ -15,7 +14,7 @@ import pandas as pd from sklearn.pipeline import Pipeline from sklearn.compose import ColumnTransformer from sklearn.linear_model import Ridge -from sklearn.model_selection import cross_val_score +from sklearn.model_selection import cross_validate rng = np.random.default_rng(0) n = 3000 @@ -48,18 +47,18 @@ results = {} for name, transformer in candidates.items(): features = ColumnTransformer([("x", transformer, ["x"])]) model = Pipeline([("features", features), ("ridge", Ridge(alpha=1.0))]) - scores = cross_val_score(model, df, y, cv=5, scoring="r2") - results[name] = (scores.mean(), scores.std()) + results[name] = cross_validate(model, df, y, cv=5, scoring="r2", return_estimator=True) -for name, (mean, std) in results.items(): - print(f"{name:20s} R2 = {mean:.3f} +/- {std:.3f}") +for name, result in results.items(): + scores = result["test_score"] + print(f"{name:20s} R2 = {scores.mean():.3f} +/- {scores.std():.3f}") ``` ```text minmax (baseline) R2 = 0.111 +/- 0.030 bspline R2 = 0.966 +/- 0.002 rbf R2 = 0.965 +/- 0.003 -ple R2 = 0.955 +/- 0.005 +ple R2 = 0.942 +/- 0.004 ``` The scaled baseline fits a straight line and cannot follow the sine. Every expansion captures @@ -72,22 +71,24 @@ That isolates the effect of the basis so the comparison is fair. ## Weigh width against accuracy -More columns can buy accuracy, but they also cost memory and overfitting headroom. Estimate the -output width before you commit, using the `Preprocessor` budget tools. +Wider representations use more memory and can overfit. Count the output features of the same +fitted pipelines that produced the validation scores. Widths can differ across folds, so check +each one rather than assuming the requested `output_dim` was realized. ```python -from pretab import Preprocessor - -for method in ["bspline", "rbf", "ple"]: - pre = Preprocessor(numerical_method=method, output_dim=12).fit(df, y) - shape = pre.estimate_output_shape(df) - print(f"{method:8s} -> {shape[1]} columns") +for name, result in results.items(): + widths = [ + len(fold.named_steps["features"].get_feature_names_out()) + for fold in result["estimator"] + ] + print(f"{name:20s} fitted widths: {widths}") ``` ```{note} -A method that wins by a hair but doubles the column count may not be worth it. Read the width -from `estimate_output_shape` and factor it into the decision. See -[Outputs and inspection](../core_concepts/outputs_and_inspection.md). +Here the baseline has one column and every expansion has 12 in each fold. When comparing +`Preprocessor` candidates, you can read `total_output_dim_` after fitting or call +`estimate_output_shape(X)` on a fitted instance to include the row count for new input. See +[Outputs and inspection](../core_concepts/outputs_and_inspection.md) for output budgets. ``` ## When nothing beats the baseline diff --git a/docs/tutorials/custom_representation.md b/docs/tutorials/custom_representation.md index d7b65b5..9dd2590 100644 --- a/docs/tutorials/custom_representation.md +++ b/docs/tutorials/custom_representation.md @@ -12,11 +12,12 @@ A complete, installable version of this example lives in the repository under ## Subclass `BaseRepresentation` -`BaseRepresentation` gives you the shared scikit-learn contract: NaN-aware validation, estimator -tags, `get_feature_names_out`, and a typed `RepresentationSpec`. You implement `fit`, -`transform`, and one sizing hook, and declare a small amount of metadata. Fitted on a DataFrame, -`self._validate` records the column names as `feature_names_in_` and checks them at `transform`, -and the output names use them (`length_f0` rather than `x0_f0`). +`BaseRepresentation` provides input validation, scikit-learn tags, `get_feature_names_out`, +and a typed `RepresentationSpec`. The shared validator accepts `NaN` by default, but it does +not impute values for you. This example sets `_allow_nan = False` because computing a column's +range requires finite data. When fitted on a DataFrame, `self._validate` records its column names +and checks them at transform time. The output names use the recorded names (`length_f0` rather +than `x0_f0`). ```python import numpy as np @@ -31,6 +32,7 @@ class ChebyshevRepresentation(BaseRepresentation): feature_kind = "numerical" scope = "univariate" supervision = "unsupervised" + _allow_nan = False def __init__(self, degree=5): self.degree = degree @@ -47,7 +49,7 @@ class ChebyshevRepresentation(BaseRepresentation): return np.clip(2.0 * (X - self.data_min_) / span - 1.0, -1.0, 1.0) def transform(self, X): - check_is_fitted(self, "n_features_in_") + check_is_fitted(self, ("data_min_", "data_max_")) z = self._rescale(np.asarray(self._validate(X, reset=False), dtype=float)) theta = np.arccos(z) blocks = [ @@ -122,14 +124,18 @@ import pandas as pd rng = np.random.default_rng(0) df = pd.DataFrame({"x": rng.uniform(-3, 3, size=500)}) -y = np.cos(df["x"] * 2) + rng.normal(0, 0.1, size=500) +df.loc[0, "x"] = np.nan pre = Preprocessor(numerical_method="chebyshev", degree=8) -X2 = pre.fit_transform(df, y) +X2 = pre.fit_transform(df) +assert X2.shape == (len(df), 8) +assert np.isfinite(X2).all() ``` The `allowed_args` list tells `Preprocessor` which of its shared keyword arguments to pass -through to your constructor. +through to your constructor. Its numerical pipeline imputes the missing value before calling +the representation. When using the transformer on its own, pass finite data or put an imputer +before it in a pipeline. ## Ship it as a plugin @@ -160,4 +166,6 @@ the others. - [Representations overview](../representations/overview.md) to see the built-in families your method joins. - [Extensibility API](../api/extension.rst) for the full signatures. +- [Architecture contract](../developer_guide/architecture.md) for dependency boundaries, + fitted state, and why registration does not enable spec persistence. - The `examples/pretab-chebyshev/` package for a complete, tested template. diff --git a/docs/tutorials/multivariate_features.md b/docs/tutorials/multivariate_features.md index 4fba8ad..2a8d3fd 100644 --- a/docs/tutorials/multivariate_features.md +++ b/docs/tutorials/multivariate_features.md @@ -24,12 +24,216 @@ is usually a more natural fit there. `nystroem` : Nyström kernel map. A landmark-based kernel approximation. +```{note} +Use `feature_groups` on `Preprocessor` to apply `tensorspline` or `tprs` to named +numerical columns jointly. Neither is a per-column `numerical_method`. Random +Fourier features and Nyström remain standalone transformers; use a scikit-learn +`ColumnTransformer` to combine them with other representations. +``` + +## Grouped preprocessing with Preprocessor + +A feature group owns its source columns and produces one joint block. Other +columns keep their per-column representations. Here latitude and longitude share +a tensor-product basis, size receives an RBF expansion, and city is one-hot encoded. + +```python +import numpy as np +import pandas as pd + +from pretab import FeatureGroup, Preprocessor, RepresentationConfig + +group_rng = np.random.default_rng(17) +data = pd.DataFrame({ + "longitude": group_rng.uniform(-3, 3, 96), + "latitude": group_rng.uniform(-2, 2, 96), + "size": group_rng.uniform(20, 200, 96), + "city": np.resize(["Lima", "Oslo", "Rome"], 96), +}) +data.loc[0, "latitude"] = np.nan + +location = FeatureGroup( + name="location", + columns=("latitude", "longitude"), + representation=RepresentationConfig( + method="tensorspline", output_dim=3, params={"degree": 2}, + ), +) +pre = Preprocessor( + numerical_method="none", + categorical_method="one-hot", + feature_preprocessing={"size": {"method": "rbf", "output_dim": 3}}, + feature_groups=[location], + target_aware=False, + placement_strategy="uniform", + missing_policy="separate_state", + output_structure="blocks", + output_format="dense", +) +blocks = pre.fit_transform(data) +assert list(blocks) == ["num_size", "group_location", "cat_city"] +``` + +Each group must contain at least two detected numerical columns. A source may +belong to only one group, and cannot also have an explicit `feature_preprocessing` +entry. Categorical and Boolean columns cannot be group sources. Set +`treat_all_integers_as_numerical=True` when low-cardinality integer sources +would otherwise be detected as categorical. +See [Configuration](../core_concepts/configuration.md) for feature detection settings. + +Group order and source order have different meanings. Output blocks appear as +ungrouped numerical columns, groups in declaration order, then categorical columns. +The ordered `columns` tuple determines a group's input axes; it does not need to +match the DataFrame's column order. Named inference columns are matched by label. +Arrays and lists instead use fitted input positions and must have the same width. + +### Read the fitted width + +Tensor-product `output_dim` is the width **per input axis**, not the total group +width. Three basis functions on each of two axes produce $3^2 = 9$ joint basis +columns. With `missing_policy="separate_state"`, two additional raw missing-state +columns follow that basis, in declared source order. The group therefore has +eleven output columns, even when one source has no missing values during fitting. + +```python +assert pre.output_dims_["group_location"] == 11 +assert blocks["group_location"].shape == (len(data), 11) +np.testing.assert_array_equal(blocks["group_location"][0, -2:], [1.0, 0.0]) +assert sum(pre.output_dims_.values()) == pre.total_output_dim_ + +names = pre.get_feature_names_out() +lineage = pre.get_feature_lineage() +assert len(names) == len(lineage) == pre.total_output_dim_ +location_lineage = [item for item in lineage if item.group_id == "group_location"] +assert len(location_lineage) == 11 +assert all( + item.source_features == ("latitude", "longitude") + for item in location_lineage if item.component != "indicator" +) +assert not any(item.uses_target for item in location_lineage) +``` + +Names encode the group and its ordered sources. Joint basis columns trace back to +both inputs; each missing indicator traces back to its own raw source. The two +sources do not receive duplicate copies of the joint width in `output_dims_` or +`get_feature_info()`. + ```{warning} -These four are standalone transformers. They are not available as a per-column -`numerical_method` on `Preprocessor`, because they need the whole input block. Fit them -directly on the columns you want to model jointly. +Tensor-product width grows multiplicatively with the number of sources. Inspect +the fitted width and use output budgets before passing a large joint basis to a +model. `max_features_per_input` applies to the whole group, including raw missing +states, not to an average width per source. ``` +```python +bounded = pre.clone_unfitted().set_params( + max_features_per_input=16, + max_output_features=64, +) +bounded.fit(data) +assert bounded.output_dims_["group_location"] == 11 +``` + +The built-in tensor and thin-plate groups do not use the target. Tensor-product +splines use local `output_dim`; thin-plate splines use `n_components` to size the +joint basis. To replace the tensor basis with a six-column thin-plate basis: + +```python +thin_plate = FeatureGroup( + name="location", + columns=("latitude", "longitude"), + representation=RepresentationConfig( + method="tprs", + params={ + "n_components": 6, + "landmark_strategy": "subsample", + "random_state": 17, + }, + ), +) +thin_pre = pre.clone_unfitted().set_params(feature_groups=[thin_plate]) +thin_blocks = thin_pre.fit_transform(data) +assert thin_blocks["group_location"].shape[1] == 8 +``` + +The thin-plate group has six joint basis columns plus the same two raw indicators. +Fitted widths are authoritative; they also include categorical encodings and +missing-state columns outside the group. + +### Mapping syntax + +An ordered mapping is equivalent to the typed group declaration. Representation +options belong inside `representation`, not beside `columns`. + +```python +mapped = pre.clone_unfitted().set_params(feature_groups={ + "location": { + "columns": ["latitude", "longitude"], + "representation": {"method": "tensorspline", "output_dim": 3, "degree": 2}, + }, +}) +mapped_blocks = mapped.fit_transform(data) +for key in blocks: + np.testing.assert_array_equal(mapped_blocks[key], blocks[key]) +``` + +Typed values detach their settings when constructed. Raw constructor mappings +remain live until normalization or fitting. After fitting, `set_params` changes +the requested configuration, not the existing fitted representation. Refit an +unfrozen instance, or use `clone_unfitted()` to learn a different representation. + +### Block widths for DeepTab + +A block-based model needs one input width per output block, not one joint width +for each raw source. Read those widths from fitted output: + +```python +block_widths = {name: values.shape[1] for name, values in blocks.items()} +assert list(block_widths) == ["num_size", "group_location", "cat_city"] +assert block_widths["group_location"] == 11 +assert "latitude" not in block_widths and "longitude" not in block_widths +assert sum(block_widths.values()) == pre.total_output_dim_ +print(block_widths) +``` + +`group_location` is one model input with eleven coordinates. Do not divide eleven +by the two sources or create two identical joint inputs. This example stops at +PreTab's dense block-output boundary. It does not construct or fit a DeepTab +model, and `block_widths` is not a DeepTab configuration object. + +```{note} +PreTab accepts eager `polars.DataFrame` inputs, but end-to-end DeepTab training +and prediction with Polars are not supported by this integration. Use an input +format documented by your version of DeepTab. + +Dictionary output is not supported for out-of-fold assembly by +`CrossFittedTransformer`. Use matrix output for that training workflow. An +ordinary all-data `fit` followed by a dictionary `transform` is not a substitute +for out-of-fold features when another representation uses the target. +``` + +### Preserve a fitted group + +Specs retain fitted group order, learned parameters, output metadata and frozen +state. The example uses strict JSON and reloads the preprocessor without fitting: + +```python +import json + +pre.freeze() +restored = Preprocessor.from_spec(json.loads(json.dumps(pre.to_spec(), allow_nan=False))) +restored_blocks = restored.transform(data[data.columns[::-1]]) +assert restored.is_frozen() +assert restored.fingerprint_ == pre.fingerprint_ +np.testing.assert_array_equal(restored.get_feature_names_out(), names) +for key in blocks: + np.testing.assert_array_equal(restored_blocks[key], blocks[key]) +``` + +Use specs only from trusted sources; loading can import supported library code. +A spec does not guarantee compatibility across dependency versions. See +[Reproducibility](../core_concepts/reproducibility.md) for the persistence contract. + ## A smooth surface with thin-plate splines Suppose the target is a smooth function of two coordinates. A per-column expansion cannot see @@ -49,7 +253,7 @@ X = rng.uniform(-3, 3, size=(n, 2)) y = np.exp(-(X[:, 0] ** 2 + X[:, 1] ** 2)) * 5 + rng.normal(0, 0.2, n) model = Pipeline([ - ("tps", ThinPlateSplineTransformer(n_components=20)), + ("tps", ThinPlateSplineTransformer(n_components=20, random_state=0)), ("ridge", Ridge(alpha=1.0)), ]) @@ -74,7 +278,7 @@ features approximate an RBF kernel without forming the full kernel matrix. from pretab.transformers import RandomFourierFeaturesTransformer model = Pipeline([ - ("rff", RandomFourierFeaturesTransformer(n_components=200, gamma=0.5)), + ("rff", RandomFourierFeaturesTransformer(n_components=200, gamma=0.5, random_state=0)), ("ridge", Ridge(alpha=1.0)), ]) @@ -82,6 +286,9 @@ scores = cross_val_score(model, X, y, cv=5, scoring="r2") print(f"5-fold R2: {scores.mean():.3f} +/- {scores.std():.3f}") ``` +Both examples seed the transformer as well as the data generator. This makes landmark +selection and random projections repeatable in the same environment. + ```{note} Random Fourier features and Nyström both approximate a kernel machine. Random Fourier features scale to large data with random projections; Nyström samples landmark points and is often more diff --git a/docs/tutorials/nonlinear_regression.md b/docs/tutorials/nonlinear_regression.md index 2c47964..e548d0c 100644 --- a/docs/tutorials/nonlinear_regression.md +++ b/docs/tutorials/nonlinear_regression.md @@ -121,13 +121,13 @@ print(f"MAE: {mean_absolute_error(y_test, pred):.2f}") ```text features: 40 -R2: 0.983 -MAE: 1.78 +R2: 0.977 +MAE: 2.04 ``` The data and the `Ridge` model are unchanged, but the expressive features let it capture the -nonlinear structure. The $R^2$ jumps from `0.124` to `0.983` and the mean absolute error drops -from `11.20` to `1.78`. +nonlinear structure. The $R^2$ rises from `0.124` to `0.977` and the mean absolute error drops +from `11.20` to `2.04`. ```{tip} `Preprocessor.transform` returns a single stacked array by default, so it drops straight into @@ -138,26 +138,23 @@ a plain scikit-learn estimator or `Pipeline`. Pass `output_structure="blocks"` ( ## What actually changed -The `Preprocessor` expands four raw columns into 40 features. Inspect the resolved layout with -`get_feature_info`: +The `Preprocessor` expands four raw columns into 40 features. `get_feature_info()` returns +separate dictionaries for numerical, categorical, and embedding features. Read the fitted +widths directly from those dictionaries: ```python -pre.get_feature_info() +numerical, categorical, _ = pre.get_feature_info(verbose=False) +assert {name: info["dimension"] for name, info in numerical.items()} == { + "age": 12, "income": 12, "tenure": 12, +} +assert categorical["city"]["dimension"] == 4 ``` -```text -feature kind pipeline dim cats ----------------------------------------------------------------- -age numerical imputer -> minmax -> bspline 12 - -income numerical imputer -> minmax -> ple 12 - -tenure numerical imputer -> minmax -> rbf 12 - -city categorical imputer -> onehot -> to_float 4 4 -``` - -Each numeric column is imputed, scaled, then expanded into a basis the linear model can weight -independently: 12 spline coefficients for `age`, 12 PLE bins for `income`, and 12 RBF bumps for -`tenure`, while `city` becomes four one-hot columns. To trace any single output column back to -its source, use [feature lineage](../core_concepts/outputs_and_inspection.md). +Each numeric column is imputed, scaled, then expanded into features the linear model can weight +independently. The categorical pipeline normalizes missing values, imputes them, and produces +four floating-point one-hot columns. Call `get_feature_info(verbose=True)` to log the fitted +pipelines and fit-time settings. To trace an output column back to its source, use +[feature lineage](../core_concepts/outputs_and_inspection.md). ## Where to go next diff --git a/docs/tutorials/sklearn_pipeline.md b/docs/tutorials/sklearn_pipeline.md index 0f5f343..7749e3c 100644 --- a/docs/tutorials/sklearn_pipeline.md +++ b/docs/tutorials/sklearn_pipeline.md @@ -5,7 +5,9 @@ they drop straight into a `ColumnTransformer` and `Pipeline`, and work with `cross_val_score`, `GridSearchCV`, and every other `sklearn` utility. The high-level `Preprocessor` composes the same way (it returns a single stacked array by default), but this page focuses on wiring each column's transformer by hand for fine-grained, per-transformer -control: addressable hyperparameters (`step__param`), one estimator per column. +control: addressable hyperparameters (`step__param`), one estimator per column. The +[mixed-column example](#configure-mixed-columns-with-preprocessor) then uses `Preprocessor` +to configure, inspect and save the fitted preprocessing step. This tutorial builds the regression task from the [nonlinear regression tutorial](nonlinear_regression.md) as a single, self-contained @@ -77,7 +79,7 @@ print(f"5-fold R2: {scores.mean():.3f} +/- {scores.std():.3f}") ``` ```text -5-fold R2: 0.948 +/- 0.005 +5-fold R2: 0.944 +/- 0.004 ``` ## Tune with GridSearchCV @@ -103,11 +105,149 @@ print(f"best CV R2: {grid.best_score_:.3f}") ```text best params: {'features__age__output_dim': 6, 'ridge__alpha': 0.1} -best CV R2: 0.949 +best CV R2: 0.945 ``` Every pretab transformer participates in the search grid just like a native `sklearn` step. +## Configure mixed columns with Preprocessor + +Run this example in the +{download}`companion notebook <../../examples/per-feature-configuration.ipynb>`. + +`Preprocessor` can select column types and build the preprocessing step for you. +This independent example uses three numerical columns, a Boolean column and a +string category. Keep their dtypes in a `DataFrame`: Booleans are categorical, +while these floating-point columns are numerical. + +```python +import json + +import numpy as np +import pandas as pd +from sklearn.linear_model import Ridge +from sklearn.pipeline import Pipeline + +from pretab import Preprocessor, RepresentationConfig + +frame = pd.DataFrame({ + "age": np.linspace(18.0, 70.0, 80), + "income": np.linspace(25000.0, 90000.0, 80), + "tenure": np.linspace(0.0, 30.0, 80), + "active": [True, False] * 40, + "city": ["Oslo", "Lima", "Perth", "Oslo"] * 20, +}) +target = 0.4 * frame["age"] + 2.0 * frame["active"] +``` + +### Request local settings + +Method strings, mappings and immutable `RepresentationConfig` values can coexist. +The three numerical columns use RBF expansions with different widths. The Boolean +uses integer encoding, and the city encoder drops its first learned category. +Override declaration order does not determine output order. + +```python +pre = Preprocessor( + numerical_method="none", + output_dim=7, + target_aware=False, + placement_strategy="uniform", + scaling="none", + output_format="dense", + random_state=17, + feature_preprocessing={ + "city": {"method": "one-hot", "params": {"drop": "first"}}, + "tenure": RepresentationConfig(method="rbf", output_dim=5), + "active": "int", + "income": {"method": "rbf", "output_dim": 3, "params": {"gamma": 0.25}}, + "age": RepresentationConfig(method="RBF", output_dim=2), + }, +) +requested = pre.get_params(deep=False) +assert requested["output_dim"] == 7 +assert requested["feature_preprocessing"]["age"].output_dim == 2 +``` + +### Read the resolved configuration + +`get_resolved_config()` normalizes aliases and applies configuration precedence +without fitting. The constructor-wide width remains seven, but each numerical +override supplies its own width. This report does not contain learned categories +or guarantee the realized output width. + +```python +resolved = pre.get_resolved_config() +assert resolved["output_dim"] == 7 +assert resolved["feature_preprocessing"]["age"]["method"] == "rbf" +assert resolved["feature_preprocessing"]["age"]["output_dim"] == 2 +assert resolved["feature_preprocessing"]["income"]["params"]["gamma"] == 0.25 +assert not hasattr(pre, "output_dims_") +``` + +### Inspect the fitted state and width + +Fit inside the pipeline so training and prediction use the same preprocessing. +The fitted dimensions account for the learned city vocabulary and its dropped +category, not just the requested RBF widths. + +```python +mixed_model = Pipeline([("pre", pre), ("ridge", Ridge(alpha=1.0))]) +mixed_model.fit(frame, target) + +assert pre.numerical_features_ == ["age", "income", "tenure"] +assert pre.categorical_features_ == ["active", "city"] +expected_dims = {"age": 2, "income": 3, "tenure": 5, "active": 1, "city": 2} +assert pre.output_dims_ == expected_dims +assert list(pre.output_dims_) == list(expected_dims) +assert pre.total_output_dim_ == 13 + +numerical, categorical, embeddings = pre.get_feature_info(verbose=False) +assert {name: info["dimension"] for name, info in numerical.items()} == { + "age": 2, "income": 3, "tenure": 5, +} +assert {name: info["dimension"] for name, info in categorical.items()} == { + "active": 1, "city": 2, +} +assert embeddings == {} +matrix = pre.transform(frame, return_array=True) +assert isinstance(matrix, np.ndarray) +assert matrix.shape == (80, 13) +assert pre.get_feature_names_out().shape == (13,) +predictions = mixed_model.predict(frame) +assert isinstance(predictions, np.ndarray) +assert predictions.shape == (80,) +``` + +```{important} +Use fitted attributes and inspection methods to size downstream inputs. Numerical +outputs precede categorical outputs, with source-column order within each kind. +Changing constructor parameters after fitting changes the request, not the +learned transformers. Fit again to apply a new request. +``` + +### Save and restore the fitted preprocessor + +`to_spec()` captures the fitted preprocessing state, including the typed local +settings. Pass the JSON-decoded specification to `from_spec()` to restore it +without fitting again. This saves the preprocessing step, not the Ridge model. + +```python +spec = json.loads(json.dumps(pre.to_spec(), allow_nan=False)) +replayed = Preprocessor.from_spec(spec) + +assert replayed.output_dims_ == expected_dims +assert replayed.total_output_dim_ == 13 +np.testing.assert_array_equal(replayed.get_feature_names_out(), pre.get_feature_names_out()) +np.testing.assert_array_equal(replayed.transform(frame, return_array=True), matrix) +assert replayed.fingerprint_ == pre.fingerprint_ +``` + +For precedence and copy semantics, see +[Structured per-feature configuration](../core_concepts/configuration.md#structured-per-feature-configuration). +For artifact trust and persistence details, see +[Reproducibility](../core_concepts/reproducibility.md). + ## When to use which - **Standalone transformers** (this page) compose inside one `Pipeline` and integrate with diff --git a/docs/tutorials/target_aware_classification.md b/docs/tutorials/target_aware_classification.md index f3d7fc0..9869524 100644 --- a/docs/tutorials/target_aware_classification.md +++ b/docs/tutorials/target_aware_classification.md @@ -142,11 +142,11 @@ print(f"5-fold ROC AUC: {scores.mean():.3f} +/- {scores.std():.3f}") ``` ```{important} -A supervised transformer fit outside a cross-validation or `Pipeline` context emits a -`LeakageWarning`. Inside the `Pipeline` here, the warning is suppressed because each fold fits -the representation on training data only. For the strongest guarantee on training features -themselves, wrap the transformer in `CrossFittedTransformer`. See -[Target awareness](../core_concepts/target_awareness.md). +PreTab suppresses `LeakageWarning` in recognized fitting contexts such as `Pipeline`, even for +a single fit on the full dataset. Here `cross_val_score`, not warning suppression, keeps +validation labels out of the fit. A plain pipeline still trains the classifier on features that +can depend on those same rows' labels. Wrap the preprocessing step in `CrossFittedTransformer` +to generate out-of-fold training features. See [Target awareness](../core_concepts/target_awareness.md). ``` ## Where to go next diff --git a/examples/per-feature-configuration.ipynb b/examples/per-feature-configuration.ipynb new file mode 100644 index 0000000..f01bfb6 --- /dev/null +++ b/examples/per-feature-configuration.ipynb @@ -0,0 +1,213 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "b5803dce", + "metadata": {}, + "source": [ + "# Per-feature configuration and fitted widths\n", + "\n", + "Configure numerical, Boolean and categorical columns, inspect actual fitted widths, and restore the preprocessing state from JSON. The same code appears in the [pipeline tutorial](../docs/tutorials/sklearn_pipeline.md#configure-mixed-columns-with-preprocessor).\n", + "\n", + "## Training data\n", + "\n", + "Keep column dtypes in a DataFrame. The three floating-point columns are numerical; `active` and `city` are categorical. The chosen RBF placement does not use the target." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "77b32509", + "metadata": {}, + "outputs": [], + "source": [ + "import json\n", + "\n", + "import numpy as np\n", + "import pandas as pd\n", + "from sklearn.linear_model import Ridge\n", + "from sklearn.pipeline import Pipeline\n", + "\n", + "from pretab import Preprocessor, RepresentationConfig\n", + "\n", + "frame = pd.DataFrame({\n", + " \"age\": np.linspace(18.0, 70.0, 80),\n", + " \"income\": np.linspace(25000.0, 90000.0, 80),\n", + " \"tenure\": np.linspace(0.0, 30.0, 80),\n", + " \"active\": [True, False] * 40,\n", + " \"city\": [\"Oslo\", \"Lima\", \"Perth\", \"Oslo\"] * 20,\n", + "})\n", + "target = 0.4 * frame[\"age\"] + 2.0 * frame[\"active\"]" + ] + }, + { + "cell_type": "markdown", + "id": "51327e9b", + "metadata": {}, + "source": [ + "## Request local settings\n", + "\n", + "Mix method strings, mappings and immutable `RepresentationConfig` values. RBF widths are local to each numerical column. The Boolean uses integer encoding; the city encoder drops its first learned category. The deliberately reversed override map does not set output order.\n", + "\n", + "`get_params()` reads the constructor request, including the global width of seven." + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "2887c806", + "metadata": {}, + "outputs": [], + "source": [ + "pre = Preprocessor(\n", + " numerical_method=\"none\",\n", + " output_dim=7,\n", + " target_aware=False,\n", + " placement_strategy=\"uniform\",\n", + " scaling=\"none\",\n", + " output_format=\"dense\",\n", + " random_state=17,\n", + " feature_preprocessing={\n", + " \"city\": {\"method\": \"one-hot\", \"params\": {\"drop\": \"first\"}},\n", + " \"tenure\": RepresentationConfig(method=\"rbf\", output_dim=5),\n", + " \"active\": \"int\",\n", + " \"income\": {\"method\": \"rbf\", \"output_dim\": 3, \"params\": {\"gamma\": 0.25}},\n", + " \"age\": RepresentationConfig(method=\"RBF\", output_dim=2),\n", + " },\n", + ")\n", + "requested = pre.get_params(deep=False)\n", + "assert requested[\"output_dim\"] == 7\n", + "assert requested[\"feature_preprocessing\"][\"age\"].output_dim == 2" + ] + }, + { + "cell_type": "markdown", + "id": "9fba5c2e", + "metadata": {}, + "source": [ + "## Read the resolved configuration\n", + "\n", + "`get_resolved_config()` applies precedence and normalizes aliases without fitting. It reports settings, not learned categories or realized output widths. The global width stays seven while the local age width is two." + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "17994994", + "metadata": {}, + "outputs": [], + "source": [ + "resolved = pre.get_resolved_config()\n", + "assert resolved[\"output_dim\"] == 7\n", + "assert resolved[\"feature_preprocessing\"][\"age\"][\"method\"] == \"rbf\"\n", + "assert resolved[\"feature_preprocessing\"][\"age\"][\"output_dim\"] == 2\n", + "assert resolved[\"feature_preprocessing\"][\"income\"][\"params\"][\"gamma\"] == 0.25\n", + "assert not hasattr(pre, \"output_dims_\")" + ] + }, + { + "cell_type": "markdown", + "id": "2efc8799", + "metadata": {}, + "source": [ + "## Inspect fitted state and actual widths\n", + "\n", + "Fit inside the pipeline so training and prediction use the same preprocessing. The fitted widths are:\n", + "\n", + "| Column | Width |\n", + "| --- | ---: |\n", + "| `age` | 2 |\n", + "| `income` | 3 |\n", + "| `tenure` | 5 |\n", + "| `active` | 1 |\n", + "| `city` | 2 |\n", + "\n", + "The city width depends on its three learned categories and `drop=\"first\"`. Numerical outputs precede categorical outputs, in source order within each kind. Use fitted dimensions to size downstream inputs. Changing a request after fitting does not refit the learned transformers." + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "b5cf1598", + "metadata": {}, + "outputs": [], + "source": [ + "mixed_model = Pipeline([(\"pre\", pre), (\"ridge\", Ridge(alpha=1.0))])\n", + "mixed_model.fit(frame, target)\n", + "\n", + "assert pre.numerical_features_ == [\"age\", \"income\", \"tenure\"]\n", + "assert pre.categorical_features_ == [\"active\", \"city\"]\n", + "expected_dims = {\"age\": 2, \"income\": 3, \"tenure\": 5, \"active\": 1, \"city\": 2}\n", + "assert pre.output_dims_ == expected_dims\n", + "assert list(pre.output_dims_) == list(expected_dims)\n", + "assert pre.total_output_dim_ == 13\n", + "\n", + "numerical, categorical, embeddings = pre.get_feature_info(verbose=False)\n", + "assert {name: info[\"dimension\"] for name, info in numerical.items()} == {\n", + " \"age\": 2, \"income\": 3, \"tenure\": 5,\n", + "}\n", + "assert {name: info[\"dimension\"] for name, info in categorical.items()} == {\n", + " \"active\": 1, \"city\": 2,\n", + "}\n", + "assert embeddings == {}\n", + "matrix = pre.transform(frame, return_array=True)\n", + "assert isinstance(matrix, np.ndarray)\n", + "assert matrix.shape == (80, 13)\n", + "assert pre.get_feature_names_out().shape == (13,)\n", + "predictions = mixed_model.predict(frame)\n", + "assert isinstance(predictions, np.ndarray)\n", + "assert predictions.shape == (80,)" + ] + }, + { + "cell_type": "markdown", + "id": "9532ddb0", + "metadata": {}, + "source": [ + "## Save and restore fitted preprocessing\n", + "\n", + "`to_spec()` captures fitted preprocessing state, including typed local settings. Round-trip it through strict JSON, then use `from_spec()` without fitting again. This saves the preprocessing step, not the Ridge model.\n", + "\n", + "For persistence and artifact trust details, see the [reproducibility guide](../docs/core_concepts/reproducibility.md)." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "9e4a8347", + "metadata": {}, + "outputs": [], + "source": [ + "spec = json.loads(json.dumps(pre.to_spec(), allow_nan=False))\n", + "replayed = Preprocessor.from_spec(spec)\n", + "\n", + "assert replayed.output_dims_ == expected_dims\n", + "assert replayed.total_output_dim_ == 13\n", + "np.testing.assert_array_equal(replayed.get_feature_names_out(), pre.get_feature_names_out())\n", + "np.testing.assert_array_equal(replayed.transform(frame, return_array=True), matrix)\n", + "assert replayed.fingerprint_ == pre.fingerprint_" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": ".venv", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.13.2" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/examples/pretab-chebyshev/pyproject.toml b/examples/pretab-chebyshev/pyproject.toml index 7849367..ad9b3f4 100644 --- a/examples/pretab-chebyshev/pyproject.toml +++ b/examples/pretab-chebyshev/pyproject.toml @@ -7,7 +7,7 @@ name = "pretab-chebyshev" version = "0.1.0" description = "Example PreTab extension: a Chebyshev polynomial feature representation." readme = "README.md" -requires-python = ">=3.10" +requires-python = ">=3.11" license = { text = "MIT" } dependencies = [ "pretab", diff --git a/examples/pretab-chebyshev/src/pretab_chebyshev/__init__.py b/examples/pretab-chebyshev/src/pretab_chebyshev/__init__.py index 808ae65..495789d 100644 --- a/examples/pretab-chebyshev/src/pretab_chebyshev/__init__.py +++ b/examples/pretab-chebyshev/src/pretab_chebyshev/__init__.py @@ -24,6 +24,9 @@ class ChebyshevRepresentation(BaseRepresentation): ``T_0`` term is dropped to avoid a redundant bias column). This yields ``degree`` output columns per input feature. + Inputs must be finite. Impute missing values before calling the transformer + directly, or use it in a ``Preprocessor`` numerical pipeline. + Parameters ---------- degree : int, default=5 @@ -34,6 +37,7 @@ class ChebyshevRepresentation(BaseRepresentation): feature_kind = "numerical" scope = "univariate" supervision = "unsupervised" + _allow_nan = False def __init__(self, degree=5): self.degree = degree @@ -50,7 +54,7 @@ def _rescale(self, X): return np.clip(2.0 * (X - self.data_min_) / span - 1.0, -1.0, 1.0) def transform(self, X): - check_is_fitted(self, "n_features_in_") + check_is_fitted(self, ("data_min_", "data_max_")) z = self._rescale(np.asarray(self._validate(X, reset=False), dtype=float)) theta = np.arccos(z) blocks = [ diff --git a/examples/pretab-chebyshev/tests/test_chebyshev.py b/examples/pretab-chebyshev/tests/test_chebyshev.py index 4f52d12..bddb7b9 100644 --- a/examples/pretab-chebyshev/tests/test_chebyshev.py +++ b/examples/pretab-chebyshev/tests/test_chebyshev.py @@ -6,9 +6,28 @@ import numpy as np import pandas as pd +import pytest from pretab_chebyshev import ChebyshevRepresentation +from sklearn.exceptions import NotFittedError from pretab import Preprocessor, check_representation, list_representations, register_representation +from pretab.compose import registry + + +@pytest.fixture(autouse=True) +def _restore_registry(): + saved_registry = registry.TRANSFORMER_REGISTRY.copy() + saved_numerical = registry.NUMERICAL_METHODS.copy() + saved_categorical = registry.CATEGORICAL_METHODS.copy() + try: + yield + finally: + registry.TRANSFORMER_REGISTRY.clear() + registry.TRANSFORMER_REGISTRY.update(saved_registry) + registry.NUMERICAL_METHODS.clear() + registry.NUMERICAL_METHODS.update(saved_numerical) + registry.CATEGORICAL_METHODS.clear() + registry.CATEGORICAL_METHODS.update(saved_categorical) def test_passes_conformance_suite(): @@ -17,11 +36,28 @@ def test_passes_conformance_suite(): assert "deterministic" in passed +def test_rejects_nan_during_fit_and_transform(): + finite = np.array([[0.0], [1.0]]) + missing = np.array([[0.0], [np.nan], [1.0]]) + transformer = ChebyshevRepresentation() + + with pytest.raises(ValueError, match="NaN"): + transformer.fit(missing) + with pytest.raises(NotFittedError): + transformer.transform(finite) + + transformer.fit(finite) + with pytest.raises(ValueError, match="NaN"): + transformer.transform(missing) + assert np.isfinite(transformer.transform(finite)).all() + + def test_register_and_use_through_preprocessor(): register_representation("chebyshev", ChebyshevRepresentation, allowed_args=("degree",), override=True) assert "chebyshev" in list_representations(feature_kind="numerical") X = pd.DataFrame({"a": np.linspace(0, 1, 20), "b": np.linspace(-1, 1, 20)}) + X.loc[0, "a"] = np.nan pre = Preprocessor( numerical_method="chebyshev", categorical_method="none", @@ -31,3 +67,4 @@ def test_register_and_use_through_preprocessor(): ) out = np.asarray(pre.fit_transform(X, return_array=True)) assert out.shape == (20, 8) # degree 4 x 2 features + assert np.isfinite(out).all() diff --git a/poetry.lock b/poetry.lock index aa4f1d2..9816bbf 100644 --- a/poetry.lock +++ b/poetry.lock @@ -58,7 +58,6 @@ files = [ ] [package.dependencies] -exceptiongroup = {version = ">=1.0.2", markers = "python_version < \"3.11\""} idna = ">=2.8" typing_extensions = {version = ">=4.5", markers = "python_version < \"3.13\""} @@ -109,6 +108,18 @@ files = [ astroid = ["astroid (>=2,<5)"] test = ["astroid (>=2,<5)", "pytest (<9.0)", "pytest-cov", "pytest-xdist"] +[[package]] +name = "attrs" +version = "26.1.0" +description = "Classes Without Boilerplate" +optional = false +python-versions = ">=3.9" +groups = ["dev"] +files = [ + {file = "attrs-26.1.0-py3-none-any.whl", hash = "sha256:c647aa4a12dfbad9333ca4e71fe62ddc36f4e63b2d260a37a8b83d2f043ac309"}, + {file = "attrs-26.1.0.tar.gz", hash = "sha256:d03ceb89cb322a8fd706d4fb91940737b6642aa36998fe130a9bc96c985eff32"}, +] + [[package]] name = "babel" version = "2.18.0" @@ -131,7 +142,7 @@ description = "Backport of CPython tarfile module" optional = false python-versions = ">=3.8" groups = ["dev"] -markers = "python_version < \"3.12\" and (platform_machine == \"aarch64\" or platform_machine == \"x86_64\") or python_version < \"3.12\" and platform_machine != \"ppc64le\" and platform_machine != \"s390x\"" +markers = "python_version == \"3.11\" and (platform_machine == \"aarch64\" or platform_machine == \"x86_64\" or platform_machine != \"ppc64le\" and platform_machine != \"s390x\")" files = [ {file = "backports.tarfile-1.2.0-py3-none-any.whl", hash = "sha256:77e284d754527b01fb1e6fa8a1afe577858ebe4e9dad8919e34c862cb399bc34"}, {file = "backports_tarfile-1.2.0.tar.gz", hash = "sha256:d75e02c268746e1b8144c278978b6e98e85de6ad16f8e4b0844a154557eca991"}, @@ -615,9 +626,6 @@ files = [ {file = "coverage-7.15.1.tar.gz", hash = "sha256:165e9949eaf222ef1f018635d0d7f368a23bfe0212af558534c40d8c04686d67"}, ] -[package.dependencies] -tomli = {version = "*", optional = true, markers = "python_full_version <= \"3.11.0a6\" and extra == \"toml\""} - [package.extras] toml = ["tomli ; python_full_version <= \"3.11.0a6\""] @@ -680,7 +688,6 @@ files = [ [package.dependencies] cffi = {version = ">=2.0.0", markers = "platform_python_implementation != \"PyPy\""} -typing-extensions = {version = ">=4.13.2", markers = "python_full_version < \"3.11.0\""} [package.extras] ssh = ["bcrypt (>=3.1.5)"] @@ -897,19 +904,6 @@ files = [ {file = "distlib-0.4.3.tar.gz", hash = "sha256:f152097224a0ae24be5a0f6bae1b9359af82133bce63f98a95f86cae1aede9ed"}, ] -[[package]] -name = "docutils" -version = "0.21.2" -description = "Docutils -- Python Documentation Utilities" -optional = false -python-versions = ">=3.9" -groups = ["dev", "docs"] -markers = "python_version == \"3.10\"" -files = [ - {file = "docutils-0.21.2-py3-none-any.whl", hash = "sha256:dafca5b9e384f0e419294eb4d2ff9fa826435bf15f15b7bd45723e8ad76811b2"}, - {file = "docutils-0.21.2.tar.gz", hash = "sha256:3a6b18732edf182daa3cd12775bbb338cf5691468f91eeeb109deff6ebfa986f"}, -] - [[package]] name = "docutils" version = "0.22.4" @@ -917,31 +911,11 @@ description = "Docutils -- Python Documentation Utilities" optional = false python-versions = ">=3.9" groups = ["dev", "docs"] -markers = "python_version >= \"3.11\"" files = [ {file = "docutils-0.22.4-py3-none-any.whl", hash = "sha256:d0013f540772d1420576855455d050a2180186c91c15779301ac2ccb3eeb68de"}, {file = "docutils-0.22.4.tar.gz", hash = "sha256:4db53b1fde9abecbb74d91230d32ab626d94f6badfc575d6db9194a49df29968"}, ] -[[package]] -name = "exceptiongroup" -version = "1.3.1" -description = "Backport of PEP 654 (exception groups)" -optional = false -python-versions = ">=3.7" -groups = ["main", "dev"] -files = [ - {file = "exceptiongroup-1.3.1-py3-none-any.whl", hash = "sha256:a7a39a3bd276781e98394987d3a5701d0c4edffb633bb7a5144577f82c773598"}, - {file = "exceptiongroup-1.3.1.tar.gz", hash = "sha256:8b412432c6055b0b7d14c310000ae93352ed6754f70fa8f7c34141f91c4e3219"}, -] -markers = {main = "python_version == \"3.10\" and (extra == \"embeddings\" or extra == \"all\")", dev = "python_version == \"3.10\""} - -[package.dependencies] -typing-extensions = {version = ">=4.6.0", markers = "python_version < \"3.13\""} - -[package.extras] -test = ["pytest (>=6)"] - [[package]] name = "executing" version = "2.2.1" @@ -1219,7 +1193,7 @@ description = "Read metadata from Python packages" optional = false python-versions = ">=3.10" groups = ["dev"] -markers = "python_version < \"3.12\" and (platform_machine == \"aarch64\" or platform_machine == \"x86_64\") or python_version < \"3.12\" and platform_machine != \"ppc64le\" and platform_machine != \"s390x\"" +markers = "python_version == \"3.11\" and (platform_machine == \"aarch64\" or platform_machine == \"x86_64\" or platform_machine != \"ppc64le\" and platform_machine != \"s390x\")" files = [ {file = "importlib_metadata-9.0.0-py3-none-any.whl", hash = "sha256:2d21d1cc5a017bd0559e36150c21c830ab1dc304dedd1b7ea85d20f45ef3edd7"}, {file = "importlib_metadata-9.0.0.tar.gz", hash = "sha256:a4f57ab599e6a2e3016d7595cfd72eb4661a5106e787a95bcc90c7105b831efc"}, @@ -1283,46 +1257,6 @@ pyqt5 = ["pyqt5"] pyside6 = ["pyside6"] test = ["flaky", "ipyparallel", "pre-commit", "pytest (>=7.0,<10)", "pytest-asyncio (>=0.23.5)", "pytest-cov", "pytest-timeout"] -[[package]] -name = "ipython" -version = "8.39.0" -description = "IPython: Productive Interactive Computing" -optional = false -python-versions = ">=3.10" -groups = ["dev"] -markers = "python_version == \"3.10\"" -files = [ - {file = "ipython-8.39.0-py3-none-any.whl", hash = "sha256:bb3c51c4fa8148ab1dea07a79584d1c854e234ea44aa1283bcb37bc75054651f"}, - {file = "ipython-8.39.0.tar.gz", hash = "sha256:4110ae96012c379b8b6db898a07e186c40a2a1ef5d57a7fa83166047d9da7624"}, -] - -[package.dependencies] -colorama = {version = "*", markers = "sys_platform == \"win32\""} -decorator = "*" -exceptiongroup = {version = "*", markers = "python_version < \"3.11\""} -jedi = ">=0.16" -matplotlib-inline = "*" -pexpect = {version = ">4.3", markers = "sys_platform != \"win32\" and sys_platform != \"emscripten\""} -prompt_toolkit = ">=3.0.41,<3.1.0" -pygments = ">=2.4.0" -stack_data = "*" -traitlets = ">=5.13.0" -typing_extensions = {version = ">=4.6", markers = "python_version < \"3.12\""} - -[package.extras] -all = ["ipython[black,doc,kernel,matplotlib,nbconvert,nbformat,notebook,parallel,qtconsole]", "ipython[test,test-extra]"] -black = ["black"] -doc = ["docrepr", "exceptiongroup", "intersphinx_registry", "ipykernel", "ipython[test]", "matplotlib", "setuptools (>=18.5)", "sphinx (>=1.3)", "sphinx-rtd-theme", "sphinxcontrib-jquery", "tomli ; python_version < \"3.11\"", "typing_extensions"] -kernel = ["ipykernel"] -matplotlib = ["matplotlib"] -nbconvert = ["nbconvert"] -nbformat = ["nbformat"] -notebook = ["ipywidgets", "notebook"] -parallel = ["ipyparallel"] -qtconsole = ["qtconsole"] -test = ["packaging", "pickleshare", "pytest", "pytest-asyncio (<0.22)", "testpath"] -test-extra = ["curio", "ipython[test]", "jupyter_ai", "matplotlib (!=3.2.0)", "nbformat", "numpy (>=1.23)", "pandas", "trio"] - [[package]] name = "ipython" version = "9.15.0" @@ -1330,7 +1264,6 @@ description = "IPython: Productive Interactive Computing" optional = false python-versions = ">=3.11" groups = ["dev"] -markers = "python_version >= \"3.11\"" files = [ {file = "ipython-9.15.0-py3-none-any.whl", hash = "sha256:515ad9c3cdf0c932a5a9f6245419e8aba706b7bd03c3e1d3a1c83d9351d6aa6e"}, {file = "ipython-9.15.0.tar.gz", hash = "sha256:da2819ce2aa83135257df830660b1176d986c3d2876db24df01974fa955b2756"}, @@ -1365,7 +1298,6 @@ description = "Defines a variety of Pygments lexers for highlighting IPython cod optional = false python-versions = ">=3.8" groups = ["dev"] -markers = "python_version >= \"3.11\"" files = [ {file = "ipython_pygments_lexers-1.1.1-py3-none-any.whl", hash = "sha256:a9462224a505ade19a605f71f8fa63c2048833ce50abc86768a0d81d876dc81c"}, {file = "ipython_pygments_lexers-1.1.1.tar.gz", hash = "sha256:09c0138009e56b6854f9535736f4171d855c8c08a563a0dcd8022f78355c7e81"}, @@ -1509,6 +1441,43 @@ files = [ {file = "joblib-1.5.3.tar.gz", hash = "sha256:8561a3269e6801106863fd0d6d84bb737be9e7631e33aaed3fb9ce5953688da3"}, ] +[[package]] +name = "jsonschema" +version = "4.26.0" +description = "An implementation of JSON Schema validation for Python" +optional = false +python-versions = ">=3.10" +groups = ["dev"] +files = [ + {file = "jsonschema-4.26.0-py3-none-any.whl", hash = "sha256:d489f15263b8d200f8387e64b4c3a75f06629559fb73deb8fdfb525f2dab50ce"}, + {file = "jsonschema-4.26.0.tar.gz", hash = "sha256:0c26707e2efad8aa1bfc5b7ce170f3fccc2e4918ff85989ba9ffa9facb2be326"}, +] + +[package.dependencies] +attrs = ">=22.2.0" +jsonschema-specifications = ">=2023.03.6" +referencing = ">=0.28.4" +rpds-py = ">=0.25.0" + +[package.extras] +format = ["fqdn", "idna", "isoduration", "jsonpointer (>1.13)", "rfc3339-validator", "rfc3987", "uri-template", "webcolors (>=1.11)"] +format-nongpl = ["fqdn", "idna", "isoduration", "jsonpointer (>1.13)", "rfc3339-validator", "rfc3986-validator (>0.1.0)", "rfc3987-syntax (>=1.1.0)", "uri-template", "webcolors (>=24.6.0)"] + +[[package]] +name = "jsonschema-specifications" +version = "2025.9.1" +description = "The JSON Schema meta-schemas and vocabularies, exposed as a Registry" +optional = false +python-versions = ">=3.9" +groups = ["dev"] +files = [ + {file = "jsonschema_specifications-2025.9.1-py3-none-any.whl", hash = "sha256:98802fee3a11ee76ecaca44429fda8a41bff98b00a0f2838151b113f210cc6fe"}, + {file = "jsonschema_specifications-2025.9.1.tar.gz", hash = "sha256:b540987f239e745613c7a9176f3edb72b832a4ac465cf02712288397832b5e8d"}, +] + +[package.dependencies] +referencing = ">=0.31.0" + [[package]] name = "jupyter-client" version = "8.9.1" @@ -1630,32 +1599,6 @@ dask = ["dask[array,dataframe,distributed] (>=2.0.0)", "pandas (>=0.24.0)"] pandas = ["pandas (>=0.24.0)"] scikit-learn = ["scikit-learn (>=0.24.2)"] -[[package]] -name = "markdown-it-py" -version = "3.0.0" -description = "Python port of markdown-it. Markdown parsing, done right!" -optional = false -python-versions = ">=3.8" -groups = ["main", "dev", "docs"] -files = [ - {file = "markdown-it-py-3.0.0.tar.gz", hash = "sha256:e3f60a94fa066dc52ec76661e37c851cb232d92f9886b15cb560aaada2df8feb"}, - {file = "markdown_it_py-3.0.0-py3-none-any.whl", hash = "sha256:355216845c60bd96232cd8d8c40e8f9765cc86f46880e43a8fd22dc1a1a8cab1"}, -] -markers = {main = "python_version == \"3.10\" and (extra == \"embeddings\" or extra == \"all\")", dev = "python_version == \"3.10\"", docs = "python_version == \"3.10\""} - -[package.dependencies] -mdurl = ">=0.1,<1.0" - -[package.extras] -benchmarking = ["psutil", "pytest", "pytest-benchmark"] -code-style = ["pre-commit (>=3.0,<4.0)"] -compare = ["commonmark (>=0.9,<1.0)", "markdown (>=3.4,<4.0)", "mistletoe (>=1.0,<2.0)", "mistune (>=2.0,<3.0)", "panflute (>=2.3,<3.0)"] -linkify = ["linkify-it-py (>=1,<3)"] -plugins = ["mdit-py-plugins"] -profiling = ["gprof2dot"] -rtd = ["jupyter_sphinx", "mdit-py-plugins", "myst-parser", "pyyaml", "sphinx", "sphinx-copybutton", "sphinx-design", "sphinx_book_theme"] -testing = ["coverage", "pytest", "pytest-cov", "pytest-regressions"] - [[package]] name = "markdown-it-py" version = "4.2.0" @@ -1667,7 +1610,7 @@ files = [ {file = "markdown_it_py-4.2.0-py3-none-any.whl", hash = "sha256:9f7ebbcd14fe59494226453aed97c1070d83f8d24b6fc3a3bcf9a38092641c4a"}, {file = "markdown_it_py-4.2.0.tar.gz", hash = "sha256:04a21681d6fbb623de53f6f364d352309d4094dd4194040a10fd51833e418d49"}, ] -markers = {main = "python_version >= \"3.11\" and (extra == \"embeddings\" or extra == \"all\")", dev = "python_version >= \"3.11\"", docs = "python_version >= \"3.11\""} +markers = {main = "extra == \"embeddings\" or extra == \"all\""} [package.dependencies] mdurl = ">=0.1,<1.0" @@ -1940,34 +1883,6 @@ files = [ {file = "msgpack-1.2.1.tar.gz", hash = "sha256:04c721c2c7448767e9e3f2520a475663d8ee0f09c31890f6d2bd70fd636a9647"}, ] -[[package]] -name = "myst-parser" -version = "4.0.1" -description = "An extended [CommonMark](https://spec.commonmark.org/) compliant parser," -optional = false -python-versions = ">=3.10" -groups = ["docs"] -markers = "python_version == \"3.10\"" -files = [ - {file = "myst_parser-4.0.1-py3-none-any.whl", hash = "sha256:9134e88959ec3b5780aedf8a99680ea242869d012e8821db3126d427edc9c95d"}, - {file = "myst_parser-4.0.1.tar.gz", hash = "sha256:5cfea715e4f3574138aecbf7d54132296bfd72bb614d31168f48c477a830a7c4"}, -] - -[package.dependencies] -docutils = ">=0.19,<0.22" -jinja2 = "*" -markdown-it-py = ">=3.0,<4.0" -mdit-py-plugins = ">=0.4.1,<1.0" -pyyaml = "*" -sphinx = ">=7,<9" - -[package.extras] -code-style = ["pre-commit (>=4.0,<5.0)"] -linkify = ["linkify-it-py (>=2.0,<3.0)"] -rtd = ["ipython", "sphinx (>=7)", "sphinx-autodoc2 (>=0.5.0,<0.6.0)", "sphinx-book-theme (>=1.1,<2.0)", "sphinx-copybutton", "sphinx-design", "sphinx-pyscript", "sphinx-tippy (>=0.4.3)", "sphinx-togglebutton", "sphinxext-opengraph (>=0.9.0,<0.10.0)", "sphinxext-rediraffe (>=0.2.7,<0.3.0)"] -testing = ["beautifulsoup4", "coverage[toml]", "defusedxml", "pygments (<2.19)", "pytest (>=8,<9)", "pytest-cov", "pytest-param-files (>=0.6.0,<0.7.0)", "pytest-regressions", "sphinx-pytest"] -testing-docutils = ["pygments", "pytest (>=8,<9)", "pytest-param-files (>=0.6.0,<0.7.0)"] - [[package]] name = "myst-parser" version = "5.1.0" @@ -1975,7 +1890,6 @@ description = "An extended [CommonMark](https://spec.commonmark.org/) compliant optional = false python-versions = ">=3.11" groups = ["docs"] -markers = "python_version >= \"3.11\"" files = [ {file = "myst_parser-5.1.0-py3-none-any.whl", hash = "sha256:9c91c52b3cdb4d94a6506e4fab4e2f296c7623a0da0dcbe6de1565c3dad67a8a"}, {file = "myst_parser-5.1.0.tar.gz", hash = "sha256:ab69322dc6719dcc7f296479dbb70181b66df6ed315064f92dbc85c0e1bf2f02"}, @@ -2003,7 +1917,6 @@ description = "Extremely lightweight compatibility layer between dataframe libra optional = false python-versions = ">=3.10" groups = ["main"] -markers = "python_version >= \"3.11\"" files = [ {file = "narwhals-2.24.0-py3-none-any.whl", hash = "sha256:42fdedf44e5b2ca7505630d45b4ac3058f38d8485cba9fe1652ca23152df7489"}, {file = "narwhals-2.24.0.tar.gz", hash = "sha256:b5c0f684ccd9d7475b564111e319a4964abcf2baf79d3cf6b1003d06ac9b828d"}, @@ -2035,27 +1948,6 @@ files = [ {file = "nest_asyncio2-1.7.2.tar.gz", hash = "sha256:1921d70b92cc4612c374928d081552efb59b83d91b2b789d935c665fa01729a8"}, ] -[[package]] -name = "networkx" -version = "3.4.2" -description = "Python package for creating and manipulating graphs and networks" -optional = true -python-versions = ">=3.10" -groups = ["main"] -markers = "python_version == \"3.10\" and (extra == \"embeddings\" or extra == \"all\")" -files = [ - {file = "networkx-3.4.2-py3-none-any.whl", hash = "sha256:df5d4365b724cf81b8c6a7312509d0c22386097011ad1abe274afd5e9d3bbc5f"}, - {file = "networkx-3.4.2.tar.gz", hash = "sha256:307c3669428c5362aab27c8a1260aa8f47c4e91d3891f48be0141738d8d053e1"}, -] - -[package.extras] -default = ["matplotlib (>=3.7)", "numpy (>=1.24)", "pandas (>=2.0)", "scipy (>=1.10,!=1.11.0,!=1.11.1)"] -developer = ["changelist (==0.5)", "mypy (>=1.1)", "pre-commit (>=3.2)", "rtoml"] -doc = ["intersphinx-registry", "myst-nb (>=1.1)", "numpydoc (>=1.8.0)", "pillow (>=9.4)", "pydata-sphinx-theme (>=0.15)", "sphinx (>=7.3)", "sphinx-gallery (>=0.16)", "texext (>=0.6.7)"] -example = ["cairocffi (>=1.7)", "contextily (>=1.6)", "igraph (>=0.11)", "momepy (>=0.7.2)", "osmnx (>=1.9)", "scikit-learn (>=1.5)", "seaborn (>=0.13)"] -extra = ["lxml (>=4.6)", "pydot (>=3.0.1)", "pygraphviz (>=1.14)", "sympy (>=1.10)"] -test = ["pytest (>=7.2)", "pytest-cov (>=4.0)"] - [[package]] name = "networkx" version = "3.6.1" @@ -2063,7 +1955,7 @@ description = "Python package for creating and manipulating graphs and networks" optional = true python-versions = "!=3.14.1,>=3.11" groups = ["main"] -markers = "python_version >= \"3.11\" and (extra == \"embeddings\" or extra == \"all\")" +markers = "extra == \"embeddings\" or extra == \"all\"" files = [ {file = "networkx-3.6.1-py3-none-any.whl", hash = "sha256:d47fbf302e7d9cbbb9e2555a0d267983d2aa476bac30e90dfbe5669bd57f3762"}, {file = "networkx-3.6.1.tar.gz", hash = "sha256:26b7c357accc0c8cde558ad486283728b65b6a95d85ee1cd66bafab4c8168509"}, @@ -2129,72 +2021,6 @@ files = [ {file = "nodeenv-1.10.0.tar.gz", hash = "sha256:996c191ad80897d076bdfba80a41994c2b47c68e224c542b48feba42ba00f8bb"}, ] -[[package]] -name = "numpy" -version = "2.2.6" -description = "Fundamental package for array computing in Python" -optional = false -python-versions = ">=3.10" -groups = ["main"] -markers = "python_version == \"3.10\"" -files = [ - {file = "numpy-2.2.6-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:b412caa66f72040e6d268491a59f2c43bf03eb6c96dd8f0307829feb7fa2b6fb"}, - {file = "numpy-2.2.6-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:8e41fd67c52b86603a91c1a505ebaef50b3314de0213461c7a6e99c9a3beff90"}, - {file = "numpy-2.2.6-cp310-cp310-macosx_14_0_arm64.whl", hash = "sha256:37e990a01ae6ec7fe7fa1c26c55ecb672dd98b19c3d0e1d1f326fa13cb38d163"}, - {file = "numpy-2.2.6-cp310-cp310-macosx_14_0_x86_64.whl", hash = "sha256:5a6429d4be8ca66d889b7cf70f536a397dc45ba6faeb5f8c5427935d9592e9cf"}, - {file = "numpy-2.2.6-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:efd28d4e9cd7d7a8d39074a4d44c63eda73401580c5c76acda2ce969e0a38e83"}, - {file = "numpy-2.2.6-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fc7b73d02efb0e18c000e9ad8b83480dfcd5dfd11065997ed4c6747470ae8915"}, - {file = "numpy-2.2.6-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:74d4531beb257d2c3f4b261bfb0fc09e0f9ebb8842d82a7b4209415896adc680"}, - {file = "numpy-2.2.6-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:8fc377d995680230e83241d8a96def29f204b5782f371c532579b4f20607a289"}, - {file = "numpy-2.2.6-cp310-cp310-win32.whl", hash = "sha256:b093dd74e50a8cba3e873868d9e93a85b78e0daf2e98c6797566ad8044e8363d"}, - {file = "numpy-2.2.6-cp310-cp310-win_amd64.whl", hash = "sha256:f0fd6321b839904e15c46e0d257fdd101dd7f530fe03fd6359c1ea63738703f3"}, - {file = "numpy-2.2.6-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:f9f1adb22318e121c5c69a09142811a201ef17ab257a1e66ca3025065b7f53ae"}, - {file = "numpy-2.2.6-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:c820a93b0255bc360f53eca31a0e676fd1101f673dda8da93454a12e23fc5f7a"}, - {file = "numpy-2.2.6-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:3d70692235e759f260c3d837193090014aebdf026dfd167834bcba43e30c2a42"}, - {file = "numpy-2.2.6-cp311-cp311-macosx_14_0_x86_64.whl", hash = "sha256:481b49095335f8eed42e39e8041327c05b0f6f4780488f61286ed3c01368d491"}, - {file = "numpy-2.2.6-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b64d8d4d17135e00c8e346e0a738deb17e754230d7e0810ac5012750bbd85a5a"}, - {file = "numpy-2.2.6-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ba10f8411898fc418a521833e014a77d3ca01c15b0c6cdcce6a0d2897e6dbbdf"}, - {file = "numpy-2.2.6-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:bd48227a919f1bafbdda0583705e547892342c26fb127219d60a5c36882609d1"}, - {file = "numpy-2.2.6-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:9551a499bf125c1d4f9e250377c1ee2eddd02e01eac6644c080162c0c51778ab"}, - {file = "numpy-2.2.6-cp311-cp311-win32.whl", hash = "sha256:0678000bb9ac1475cd454c6b8c799206af8107e310843532b04d49649c717a47"}, - {file = "numpy-2.2.6-cp311-cp311-win_amd64.whl", hash = "sha256:e8213002e427c69c45a52bbd94163084025f533a55a59d6f9c5b820774ef3303"}, - {file = "numpy-2.2.6-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:41c5a21f4a04fa86436124d388f6ed60a9343a6f767fced1a8a71c3fbca038ff"}, - {file = "numpy-2.2.6-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:de749064336d37e340f640b05f24e9e3dd678c57318c7289d222a8a2f543e90c"}, - {file = "numpy-2.2.6-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:894b3a42502226a1cac872f840030665f33326fc3dac8e57c607905773cdcde3"}, - {file = "numpy-2.2.6-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:71594f7c51a18e728451bb50cc60a3ce4e6538822731b2933209a1f3614e9282"}, - {file = "numpy-2.2.6-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f2618db89be1b4e05f7a1a847a9c1c0abd63e63a1607d892dd54668dd92faf87"}, - {file = "numpy-2.2.6-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fd83c01228a688733f1ded5201c678f0c53ecc1006ffbc404db9f7a899ac6249"}, - {file = "numpy-2.2.6-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:37c0ca431f82cd5fa716eca9506aefcabc247fb27ba69c5062a6d3ade8cf8f49"}, - {file = "numpy-2.2.6-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:fe27749d33bb772c80dcd84ae7e8df2adc920ae8297400dabec45f0dedb3f6de"}, - {file = "numpy-2.2.6-cp312-cp312-win32.whl", hash = "sha256:4eeaae00d789f66c7a25ac5f34b71a7035bb474e679f410e5e1a94deb24cf2d4"}, - {file = "numpy-2.2.6-cp312-cp312-win_amd64.whl", hash = "sha256:c1f9540be57940698ed329904db803cf7a402f3fc200bfe599334c9bd84a40b2"}, - {file = "numpy-2.2.6-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:0811bb762109d9708cca4d0b13c4f67146e3c3b7cf8d34018c722adb2d957c84"}, - {file = "numpy-2.2.6-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:287cc3162b6f01463ccd86be154f284d0893d2b3ed7292439ea97eafa8170e0b"}, - {file = "numpy-2.2.6-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:f1372f041402e37e5e633e586f62aa53de2eac8d98cbfb822806ce4bbefcb74d"}, - {file = "numpy-2.2.6-cp313-cp313-macosx_14_0_x86_64.whl", hash = "sha256:55a4d33fa519660d69614a9fad433be87e5252f4b03850642f88993f7b2ca566"}, - {file = "numpy-2.2.6-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f92729c95468a2f4f15e9bb94c432a9229d0d50de67304399627a943201baa2f"}, - {file = "numpy-2.2.6-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1bc23a79bfabc5d056d106f9befb8d50c31ced2fbc70eedb8155aec74a45798f"}, - {file = "numpy-2.2.6-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:e3143e4451880bed956e706a3220b4e5cf6172ef05fcc397f6f36a550b1dd868"}, - {file = "numpy-2.2.6-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:b4f13750ce79751586ae2eb824ba7e1e8dba64784086c98cdbbcc6a42112ce0d"}, - {file = "numpy-2.2.6-cp313-cp313-win32.whl", hash = "sha256:5beb72339d9d4fa36522fc63802f469b13cdbe4fdab4a288f0c441b74272ebfd"}, - {file = "numpy-2.2.6-cp313-cp313-win_amd64.whl", hash = "sha256:b0544343a702fa80c95ad5d3d608ea3599dd54d4632df855e4c8d24eb6ecfa1c"}, - {file = "numpy-2.2.6-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:0bca768cd85ae743b2affdc762d617eddf3bcf8724435498a1e80132d04879e6"}, - {file = "numpy-2.2.6-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:fc0c5673685c508a142ca65209b4e79ed6740a4ed6b2267dbba90f34b0b3cfda"}, - {file = "numpy-2.2.6-cp313-cp313t-macosx_14_0_arm64.whl", hash = "sha256:5bd4fc3ac8926b3819797a7c0e2631eb889b4118a9898c84f585a54d475b7e40"}, - {file = "numpy-2.2.6-cp313-cp313t-macosx_14_0_x86_64.whl", hash = "sha256:fee4236c876c4e8369388054d02d0e9bb84821feb1a64dd59e137e6511a551f8"}, - {file = "numpy-2.2.6-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e1dda9c7e08dc141e0247a5b8f49cf05984955246a327d4c48bda16821947b2f"}, - {file = "numpy-2.2.6-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f447e6acb680fd307f40d3da4852208af94afdfab89cf850986c3ca00562f4fa"}, - {file = "numpy-2.2.6-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:389d771b1623ec92636b0786bc4ae56abafad4a4c513d36a55dce14bd9ce8571"}, - {file = "numpy-2.2.6-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:8e9ace4a37db23421249ed236fdcdd457d671e25146786dfc96835cd951aa7c1"}, - {file = "numpy-2.2.6-cp313-cp313t-win32.whl", hash = "sha256:038613e9fb8c72b0a41f025a7e4c3f0b7a1b5d768ece4796b674c8f3fe13efff"}, - {file = "numpy-2.2.6-cp313-cp313t-win_amd64.whl", hash = "sha256:6031dd6dfecc0cf9f668681a37648373bddd6421fff6c66ec1624eed0180ee06"}, - {file = "numpy-2.2.6-pp310-pypy310_pp73-macosx_10_15_x86_64.whl", hash = "sha256:0b605b275d7bd0c640cad4e5d30fa701a8d59302e127e5f79138ad62762c3e3d"}, - {file = "numpy-2.2.6-pp310-pypy310_pp73-macosx_14_0_x86_64.whl", hash = "sha256:7befc596a7dc9da8a337f79802ee8adb30a552a94f792b9c9d18c840055907db"}, - {file = "numpy-2.2.6-pp310-pypy310_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ce47521a4754c8f4593837384bd3424880629f718d87c5d44f8ed763edd63543"}, - {file = "numpy-2.2.6-pp310-pypy310_pp73-win_amd64.whl", hash = "sha256:d042d24c90c41b54fd506da306759e06e568864df8ec17ccc17e9e884634fd00"}, - {file = "numpy-2.2.6.tar.gz", hash = "sha256:e29554e2bef54a90aa5cc07da6ce955accb83f21ab5de01a62c8478897b264fd"}, -] - [[package]] name = "numpy" version = "2.4.6" @@ -2703,7 +2529,6 @@ files = [ [package.dependencies] numpy = [ - {version = ">=1.22.4", markers = "python_version < \"3.11\""}, {version = ">=1.23.2", markers = "python_version == \"3.11\""}, {version = ">=1.26.0", markers = "python_version >= \"3.12\""}, ] @@ -3130,12 +2955,10 @@ files = [ [package.dependencies] colorama = {version = ">=0.4", markers = "sys_platform == \"win32\""} -exceptiongroup = {version = ">=1", markers = "python_version < \"3.11\""} iniconfig = ">=1.0.1" packaging = ">=22" pluggy = ">=1.5,<2" pygments = ">=2.7.2" -tomli = {version = ">=1", markers = "python_version < \"3.11\""} [package.extras] dev = ["argcomplete", "attrs (>=19.2)", "hypothesis (>=3.56)", "mock", "requests", "setuptools", "xmlschema"] @@ -3443,6 +3266,23 @@ Pygments = ">=2.5.1" [package.extras] md = ["comrak (>=0.0.11)"] +[[package]] +name = "referencing" +version = "0.37.0" +description = "JSON Referencing + Python" +optional = false +python-versions = ">=3.10" +groups = ["dev"] +files = [ + {file = "referencing-0.37.0-py3-none-any.whl", hash = "sha256:381329a9f99628c9069361716891d34ad94af76e461dcb0335825aecc7692231"}, + {file = "referencing-0.37.0.tar.gz", hash = "sha256:44aefc3142c5b842538163acb373e24cce6632bd54bdb01b21ad5863489f50d8"}, +] + +[package.dependencies] +attrs = ">=22.2.0" +rpds-py = ">=0.7.0" +typing-extensions = {version = ">=4.4.0", markers = "python_version < \"3.13\""} + [[package]] name = "regex" version = "2026.7.10" @@ -3647,12 +3487,149 @@ description = "Manipulate well-formed Roman numerals" optional = false python-versions = ">=3.10" groups = ["docs"] -markers = "python_version >= \"3.11\"" files = [ {file = "roman_numerals-4.1.0-py3-none-any.whl", hash = "sha256:647ba99caddc2cc1e55a51e4360689115551bf4476d90e8162cf8c345fe233c7"}, {file = "roman_numerals-4.1.0.tar.gz", hash = "sha256:1af8b147eb1405d5839e78aeb93131690495fe9da5c91856cb33ad55a7f1e5b2"}, ] +[[package]] +name = "rpds-py" +version = "2026.9.1" +description = "Python bindings to Rust's persistent data structures (rpds)" +optional = false +python-versions = ">=3.11" +groups = ["dev"] +files = [ + {file = "rpds_py-2026.9.1-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:2711d29b653b3bce48a63d18b9c6b53274669e6d6c4094dddeb4d9a0e45128b2"}, + {file = "rpds_py-2026.9.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:3231c4c0e521dafa5be0c9f114ee2c2ad46650836f2d72caa86801950c3e7044"}, + {file = "rpds_py-2026.9.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e01b3c878c8641913e688edd1b3f08658c6783d29cf6b826bd3c0d1ae7a1ffaa"}, + {file = "rpds_py-2026.9.1-cp311-cp311-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:3e524c7874ac72884d28e16dd5b8d839fd09e0fe76b020d3fbca23212a7b8c52"}, + {file = "rpds_py-2026.9.1-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:761fdae6728ceb99ab182fad2f0cc1e262f610834dc891aea1d1a2a2e634776f"}, + {file = "rpds_py-2026.9.1-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:6b723eb406dec5bc9ec516c73ab9c3239a3284e017f7eb89ee2b3258bd504fb7"}, + {file = "rpds_py-2026.9.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:136a1c3fe4402b7008bc81cb62ee538481795b61a7e83df88dff3b3f02b726ff"}, + {file = "rpds_py-2026.9.1-cp311-cp311-manylinux_2_31_riscv64.whl", hash = "sha256:839dde845559254f34885267c6878f60d61d5205180226d976fe488d45fa128e"}, + {file = "rpds_py-2026.9.1-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:56cd8b3f77d7b6812f533b662186a1f28316931166ddc00fb893b1b0db7e9888"}, + {file = "rpds_py-2026.9.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:074a4d198bc34d9a8ea425114fc3ded6d11ec01f6a314a8db67454a5152d8834"}, + {file = "rpds_py-2026.9.1-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:6beb738155fe8ab8091afdfa5a3226b21c2b1593f1e50ebb90eb25b44dbc0391"}, + {file = "rpds_py-2026.9.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:57492a550a1d88d29d003247e5f78dd8cf04a701fac0e4c8db8745a6d2504e0a"}, + {file = "rpds_py-2026.9.1-cp311-cp311-win32.whl", hash = "sha256:d95a354e02393eada6d7351184671aced9d4cce109dabf927cb7aa99624352a1"}, + {file = "rpds_py-2026.9.1-cp311-cp311-win_amd64.whl", hash = "sha256:ce4d4f52e2a4324396caddbd45a97d8d7be5f42edd25d2355282a9c34f9b2f7f"}, + {file = "rpds_py-2026.9.1-cp311-cp311-win_arm64.whl", hash = "sha256:fdcd198979b4ecffcc1beba366a7fbcf4eb41243691a82fe52ceb0b902f09c12"}, + {file = "rpds_py-2026.9.1-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:50906f5aea24b5a865cbd0a589698288631d9f3a54c3a937c83aefa95a0d14af"}, + {file = "rpds_py-2026.9.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:e21c1429e205828ea886a2293a4a2c8e01f4c25d9893ca330e97a6cf73f52e7b"}, + {file = "rpds_py-2026.9.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2693b2728bbcc48d09a981a356954b0c47c53ff25b545856f28a889ea619f69a"}, + {file = "rpds_py-2026.9.1-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:8601470267d938bcb7f3ab1a336100af51a4fd5b6ed030ef52461bb3ef5e7e07"}, + {file = "rpds_py-2026.9.1-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:3890a6aa36e6baa53d5258a2a25d3ef8b37ad165a6ab27a892d7c3e3a432cd69"}, + {file = "rpds_py-2026.9.1-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:6b5b393eda5ea42cca1c1a6665f2a4882b4fd5d1777e41ce0545a107fb008c9d"}, + {file = "rpds_py-2026.9.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:addeda51556dac7c1a2f14cda62db8b621cd12afba3091d03a96c72932387eab"}, + {file = "rpds_py-2026.9.1-cp312-cp312-manylinux_2_31_riscv64.whl", hash = "sha256:d9edf30457d74eebfd76b045535e36f1cd89062566a128a0db2145ca042d787e"}, + {file = "rpds_py-2026.9.1-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:815d26356930846a40c7bc1366e7b1b0320ab8a063e66c11298a208bed0fd237"}, + {file = "rpds_py-2026.9.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:3b5a6f40f0a1486b4b36c888123afc67acdbd9f33235927acf5ff295429a0ba3"}, + {file = "rpds_py-2026.9.1-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:b5b8b0753718d258fd454283fbd57e14545d3b40583fa672e27cb4f987626bcc"}, + {file = "rpds_py-2026.9.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:46d80bc76b51a6c24f9944368c28d38b8bcbcea1da4f2f8d3ebc31a67e8c6ec6"}, + {file = "rpds_py-2026.9.1-cp312-cp312-win32.whl", hash = "sha256:befc2d6a953e563f8a7bfd87a42c22ebf8a3e980dcb7b6a4d17b70b0e914e8a3"}, + {file = "rpds_py-2026.9.1-cp312-cp312-win_amd64.whl", hash = "sha256:5ce8943f79c2210f7abcc28e86367b03b28d95027fd01c46d2472373ae70c86f"}, + {file = "rpds_py-2026.9.1-cp312-cp312-win_arm64.whl", hash = "sha256:501909f2e4a1e2dee528ef766fe3c469060ebc17e54a8383d404ba07a81a6f02"}, + {file = "rpds_py-2026.9.1-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:a36b70596407634ca82d4b989a3729074a008537a0522e4c8046a67c729103e9"}, + {file = "rpds_py-2026.9.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:eba5d173f7d5708b22a93815017a4611873ed54db9f268077c0dd1ed99cfc858"}, + {file = "rpds_py-2026.9.1-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:457866b85daf5034296666168b84a69e0b2e89dc4f1af102b46f6448a60b9063"}, + {file = "rpds_py-2026.9.1-cp313-cp313-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:a3a52a3ba86436ab3aef510fbe21512abc2ddd1993005dfe50514bd2284ef025"}, + {file = "rpds_py-2026.9.1-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:d7841166b7fa64c9c56404617ae4341448847482d45933b13135d26c130519e5"}, + {file = "rpds_py-2026.9.1-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:926bdd3e3b5998ddf70cc64bc8cf57209571f9044542913afb673799fec77dd0"}, + {file = "rpds_py-2026.9.1-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7868b85224291c6cb6759f9b5adb9745f486d226f62b16a614dd5a2a5ab2b35b"}, + {file = "rpds_py-2026.9.1-cp313-cp313-manylinux_2_31_riscv64.whl", hash = "sha256:3cd182d7291d29b92c521a0069d9c01ba6193628a9a105531d11b40a6d731a33"}, + {file = "rpds_py-2026.9.1-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:e6ea1cda8d8c688278430e4268a42f5e5da3bdd74578dfadc0820c3f1766ce83"}, + {file = "rpds_py-2026.9.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:5943980471829f6de242a20b109de3111ba6b77e3af0ffc587028ac854b05e6c"}, + {file = "rpds_py-2026.9.1-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:76d3af9732d2dab69f28179b40ba2d87e2f1d5824b4a694780aa787d685e8f36"}, + {file = "rpds_py-2026.9.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:78326f4cb4427a56ba4996c0762b63be45f06b85f086526420d2b3a66e40f84d"}, + {file = "rpds_py-2026.9.1-cp313-cp313-win32.whl", hash = "sha256:172e47169583f46ce118cbec68e6795d0da0f4606b488b6434f8276bca0a058c"}, + {file = "rpds_py-2026.9.1-cp313-cp313-win_amd64.whl", hash = "sha256:3e93b2cd69a9830be33e03945cd7cda940a0a8bfcfbff41d6144f0cb0d3d8bd9"}, + {file = "rpds_py-2026.9.1-cp313-cp313-win_arm64.whl", hash = "sha256:d151e148117294133bf8af7eeace085e7e87432db15ab6adf640330298a47f6f"}, + {file = "rpds_py-2026.9.1-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:c9d1aca01f49170fdcf5c92761b1fafe97f554b721ca4570c5949fff778f0d4b"}, + {file = "rpds_py-2026.9.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:3f0e9ac28fc067d4d34b88ae43c48e9489455c97fee9633d851f7eeed5a05d35"}, + {file = "rpds_py-2026.9.1-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:07deecbfce94c78473018bc7d10b337cc651d12df87a1eb2cb3e4024bc9c33d0"}, + {file = "rpds_py-2026.9.1-cp314-cp314-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:821b2755db9194409254012f429c56643416fb96ef9be090be82ec8826b7f477"}, + {file = "rpds_py-2026.9.1-cp314-cp314-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:3c91c210ae7645626c608400e3519b4a642f837cce09ca830db3beb2e9f274d4"}, + {file = "rpds_py-2026.9.1-cp314-cp314-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:54ac2158a6f96cfbabff0b2eedaf94b90c5ec7ca8317fcadc61e1c2b2e0ff6ef"}, + {file = "rpds_py-2026.9.1-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:eac2f5dbafd585dfe31f86a23ebf0d3ba480a9d49ebc87947267b5608d4ea0cd"}, + {file = "rpds_py-2026.9.1-cp314-cp314-manylinux_2_31_riscv64.whl", hash = "sha256:8aa5dda18d39b6143eb24809d158f9252c88f402749b6f1b62a506cc7d96cc35"}, + {file = "rpds_py-2026.9.1-cp314-cp314-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:5c90e7fa02e8f5de0d10c17595c568ada48c5302e749462c0ea1a4c362111a86"}, + {file = "rpds_py-2026.9.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:e6d198bad4e49dd6732fbd636e2fc5c082f45c8cad0b4acb756b00c82c76072e"}, + {file = "rpds_py-2026.9.1-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:96beca19ec79de272e8668585380ff9092c47077c1d7a1e098e00bbd921f4785"}, + {file = "rpds_py-2026.9.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:a5cf77eb04f20b720be95265a3e00eb2a14814074255cc27069c551b2db53118"}, + {file = "rpds_py-2026.9.1-cp314-cp314-win32.whl", hash = "sha256:a03d57b86d2a51d0a66c92177e2be154ad015f357791d306e714569999cdb4cc"}, + {file = "rpds_py-2026.9.1-cp314-cp314-win_amd64.whl", hash = "sha256:837c6b305e26fe0f75b15c92cf3b2ba29e0ae19dc40b1c557b026cb426347d0c"}, + {file = "rpds_py-2026.9.1-cp314-cp314-win_arm64.whl", hash = "sha256:fce4b85234a0cbad67bf8e6e1201ee815d172c9aebad75f25645bc4d834f8e31"}, + {file = "rpds_py-2026.9.1-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:3a72c11530d71abfb66c8d7696a2f86c43e63fca8b948f1a784ac490f4ec688e"}, + {file = "rpds_py-2026.9.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:068c37bba854ec2fe42f7365c640af11dd9895890ccbf2df5070d0c059bd7f96"}, + {file = "rpds_py-2026.9.1-cp314-cp314t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d7fca4eb6df565e2a928f1c7dad92d27db8f9df0f449e76423ed5d7e713ed445"}, + {file = "rpds_py-2026.9.1-cp314-cp314t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:c933c6678c6f116ff8af47a4c6db0868b8ace74af0343016c0ef00f00272ea69"}, + {file = "rpds_py-2026.9.1-cp314-cp314t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:028ad274ea951dac64491b5d1e65712a4aeabfdbdb9fccf797b57bd899b0c495"}, + {file = "rpds_py-2026.9.1-cp314-cp314t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:740d0a99cf9de0b17a3943388e9294a59becf75e7c43421f387bd3c7a9901f7c"}, + {file = "rpds_py-2026.9.1-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0da298fb372dc192610a4b9ecbc68a0cd8b675bbbd1fc519d01b41cfd658333e"}, + {file = "rpds_py-2026.9.1-cp314-cp314t-manylinux_2_31_riscv64.whl", hash = "sha256:eb61be926bb81567c1f48bdc8aa22b9855048dc2efd53871f9f7e6e9a5632346"}, + {file = "rpds_py-2026.9.1-cp314-cp314t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:42e75466f83cd43f6026c81eab74246efb2bdadafb307b85700632d06c68f299"}, + {file = "rpds_py-2026.9.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:617f59cde379b4f648a09797b7f683d04b90a46344cddab85639da5aff0f5531"}, + {file = "rpds_py-2026.9.1-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:3edae8c5ddfdb6985d49ae9d150516e5076888879022f91a26c2de9276ce0bdb"}, + {file = "rpds_py-2026.9.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:0f045bb053c9057720d72c56dffe30dffdc05997b2897a827b9325f0ab6623fa"}, + {file = "rpds_py-2026.9.1-cp314-cp314t-win32.whl", hash = "sha256:bf35d0568abda97233239ce32896d3ad53fccc537832c104e30c94aa5fb93569"}, + {file = "rpds_py-2026.9.1-cp314-cp314t-win_amd64.whl", hash = "sha256:1e8d4d79d828299bf44a55db22a9388ab967b49d17132c88eab0f4360b48da8e"}, + {file = "rpds_py-2026.9.1-cp315-cp315-macosx_10_12_x86_64.whl", hash = "sha256:1d77b649e6f7cdf12ca5c2a98dad0ad37f9ea9b6f960408a92f0cb12bb3d04d9"}, + {file = "rpds_py-2026.9.1-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:00ba2d8c7dd4ee537978ddf4b3fbd712bef2d8751603f7f3146b3f4287768e25"}, + {file = "rpds_py-2026.9.1-cp315-cp315-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ec450527cbf485e13c8d3602a54f428ab0432fdade0ede75efd74b735421c871"}, + {file = "rpds_py-2026.9.1-cp315-cp315-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:306ee1850d8105b5baf977e78d45fcadd12c1a54678d614c9baf217708446e91"}, + {file = "rpds_py-2026.9.1-cp315-cp315-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:ef6b65b03247c54692ad4fd9ee97cb772781927db72e3cb05e70b3db6d1ff14f"}, + {file = "rpds_py-2026.9.1-cp315-cp315-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:a575404ebc9cf2e91edd32eaf570ec1430eb900d4f56724ba7dd4bc1fc9c176d"}, + {file = "rpds_py-2026.9.1-cp315-cp315-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2c16ab111bc27c646ba8aa005d0527754edc538ebb636f0b1bf8e244b48d1945"}, + {file = "rpds_py-2026.9.1-cp315-cp315-manylinux_2_31_riscv64.whl", hash = "sha256:7664419f27db41d4f1c43a78dccda7dd6e8ef2428df3ee01d0c2a07a6b071297"}, + {file = "rpds_py-2026.9.1-cp315-cp315-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:4b26b03d9d2658ee2fa234f8f4f19f38a09773fe5261028025032e26d4d35af0"}, + {file = "rpds_py-2026.9.1-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:be3e47e2d91aa3942ff9bf4077a505226005abfc39b6f7554a91c1b9393986b9"}, + {file = "rpds_py-2026.9.1-cp315-cp315-musllinux_1_2_i686.whl", hash = "sha256:6307a0da524939decb8ca4a3933b8ab62525794411d6984fca6726e732804af6"}, + {file = "rpds_py-2026.9.1-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:159a7aab5c5e8b112c8830f54717ce56da1252ebdbb526f5be2df2309280b9e7"}, + {file = "rpds_py-2026.9.1-cp315-cp315-win32.whl", hash = "sha256:dbc2673f9223d420c91145599b3ba45a8a50c207d1976908e5fb5ddb0c9b9429"}, + {file = "rpds_py-2026.9.1-cp315-cp315-win_amd64.whl", hash = "sha256:75c38c50ab9aca840225d9a9a3810bf11d04bd5c1f186cabbb8aee56db3e9b15"}, + {file = "rpds_py-2026.9.1-cp315-cp315-win_arm64.whl", hash = "sha256:a431156bb41865fc14cd5d79bb9d7bbed83110b0159e34e62ae30951f96c0009"}, + {file = "rpds_py-2026.9.1-cp315-cp315t-macosx_10_12_x86_64.whl", hash = "sha256:ef0d8c843e2827d6c120ab4687e9423fb1d893db1df27b7c1506615bcb9734a0"}, + {file = "rpds_py-2026.9.1-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:45bc6bccf78b20fd834237d18db64965d7ee68ba7f60440a26c7ab71e7b8d51a"}, + {file = "rpds_py-2026.9.1-cp315-cp315t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1d55198263bb51f557550c6ed2e6d1cb6a6fed6eb5c9120b741c5926bef8a45d"}, + {file = "rpds_py-2026.9.1-cp315-cp315t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:a8763f20692da7df39b0afdd1ba3042b004c50a45994f76c2d9a25641f7673db"}, + {file = "rpds_py-2026.9.1-cp315-cp315t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:e43d4a1f673e8a1cbd8533e809e02b4bf9d4f2280269bb640436556312121250"}, + {file = "rpds_py-2026.9.1-cp315-cp315t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:ea394a937f17a54c51239348bdbe2e3518124c8d4a8951ba04a311d3095bd18f"}, + {file = "rpds_py-2026.9.1-cp315-cp315t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:cdeaa99ce822dca76cfb1b993e9120c5ea212f2eb66d48950ad63c349668a018"}, + {file = "rpds_py-2026.9.1-cp315-cp315t-manylinux_2_31_riscv64.whl", hash = "sha256:b4f062343e7ad3fa94f2c66e5ae667dee47ee74dd41a9057c4fbe163236a123d"}, + {file = "rpds_py-2026.9.1-cp315-cp315t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:22ffd29a63d71fb1b81552c21f2c2b734949b7ac751a9be70675a939a900839b"}, + {file = "rpds_py-2026.9.1-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:08dae4a4095150a7c4545a1fb40b98e1ab1744fbc2770d92c977b9dadaa49ab6"}, + {file = "rpds_py-2026.9.1-cp315-cp315t-musllinux_1_2_i686.whl", hash = "sha256:9a0460d43603d1fd9ef59c30278531e15d78581721ddb538fa560aa7817ea4ad"}, + {file = "rpds_py-2026.9.1-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:1c2d1f6da5128eabf34e963d7163a818846075a52568250d006c4c953b40f903"}, + {file = "rpds_py-2026.9.1-cp315-cp315t-win32.whl", hash = "sha256:5c6ee90dee3e85e055ddfd502d611643d9b0fd94c818220bda84ec3dacd9b27b"}, + {file = "rpds_py-2026.9.1-cp315-cp315t-win_amd64.whl", hash = "sha256:fe5ad0664ec772b02c45859041aa17655709cced7a31005817fbbbd988c25567"}, + {file = "rpds_py-2026.9.1-pp311-pypy311_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4c0d2cb595a420b34d5086db0add011e26e2c09d6a024afbac4228bf8f863a30"}, + {file = "rpds_py-2026.9.1-pp311-pypy311_pp73-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:f3d6ed6a98cfd19155996605474982cc470d7601746a6439078f1a5a3fa8b050"}, + {file = "rpds_py-2026.9.1-pp311-pypy311_pp73-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:8171b44a054e5c67fd748ada04187f1250bf35b95f85e52ab64bcf3331a923bb"}, + {file = "rpds_py-2026.9.1-pp311-pypy311_pp73-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:fda1d96e542c37b6c804547dbf489c129fe7c97183a76a5ec275909ba1a063df"}, + {file = "rpds_py-2026.9.1-pp311-pypy311_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:270bdcdaac5d5b6f73c5e22e7e135c7f2a50e789f71d9e241d5be8d90026e19a"}, + {file = "rpds_py-2026.9.1-pp311-pypy311_pp73-manylinux_2_31_riscv64.whl", hash = "sha256:84a6ecc0c940169190d2c23bd969debd48c94dbc855acd60188a68d71d421608"}, + {file = "rpds_py-2026.9.1-pp311-pypy311_pp73-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:ab4b2fda7c2b542f7f9d886cc6a838c5079d2b76f72e6081411faba11adde2c9"}, + {file = "rpds_py-2026.9.1-pp311-pypy311_pp73-musllinux_1_2_aarch64.whl", hash = "sha256:44b32a7c4f0da3d28af31c259e38ddcff096f855e205ed0671d02fcf44f1ea1c"}, + {file = "rpds_py-2026.9.1-pp311-pypy311_pp73-musllinux_1_2_i686.whl", hash = "sha256:a3dbc5ed9514908d5046107d7b1346bde71eea61de6e0e4919c19354f97e769f"}, + {file = "rpds_py-2026.9.1-pp311-pypy311_pp73-musllinux_1_2_x86_64.whl", hash = "sha256:6eae33003518fd4cb4f83a218d5371469dd3001aa3b87128c005b07762f7fe5e"}, + {file = "rpds_py-2026.9.1-pp311-pypy311_pp80-macosx_10_12_x86_64.whl", hash = "sha256:0483515261947e4e8b8e1375bf7463e7eb6ccfb3d86e7b554d90cd5285f20f32"}, + {file = "rpds_py-2026.9.1-pp311-pypy311_pp80-macosx_11_0_arm64.whl", hash = "sha256:4cfaf02209061880210819934de2f4f6aa83dc04dafe6770276acc240a56da31"}, + {file = "rpds_py-2026.9.1-pp312-pypy312_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6cdc537c8633d7fd92a82e2e0d2ab74320a3f63d5e59fb9cf08711e08fe151c4"}, + {file = "rpds_py-2026.9.1-pp312-pypy312_pp73-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:10e208f2425d973938afcd56e28a7c4be32e27b6a60b5d381f49fb9d8acf9759"}, + {file = "rpds_py-2026.9.1-pp312-pypy312_pp73-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:6c0dbbcc19735fe5f8b0a54c07659d154a9e69f47e15d0a6ab7299215daf62cb"}, + {file = "rpds_py-2026.9.1-pp312-pypy312_pp73-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:684fd492fff4fead00587544e059be2bbcb6f93454f21fa2a91b66fc7508be82"}, + {file = "rpds_py-2026.9.1-pp312-pypy312_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d1028417bb44037eb3069c1009bd7b7277212876cda22fbe565b0bca9fab6d2c"}, + {file = "rpds_py-2026.9.1-pp312-pypy312_pp73-manylinux_2_31_riscv64.whl", hash = "sha256:492e5e428cbe126221611f47e068f01660352feec4ad18bc0f5ea9b2ae88fb14"}, + {file = "rpds_py-2026.9.1-pp312-pypy312_pp73-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:88b5268892fde430d5531f95bc560b6efbbd67c929662c586afd729a96e7461c"}, + {file = "rpds_py-2026.9.1-pp312-pypy312_pp73-musllinux_1_2_aarch64.whl", hash = "sha256:01445c8d194aa032a08e944f16567672da1c62dbdbefd8b6d0693032e290cf68"}, + {file = "rpds_py-2026.9.1-pp312-pypy312_pp73-musllinux_1_2_i686.whl", hash = "sha256:eef6a03b0b6d08d0835ccfa8ec8d1bc70525e3801387567137b50c557695e6da"}, + {file = "rpds_py-2026.9.1-pp312-pypy312_pp73-musllinux_1_2_x86_64.whl", hash = "sha256:6b9bf3135b4ad5981df9a73d71a35272d650a2985ae9c2746357b24d59de2448"}, + {file = "rpds_py-2026.9.1-pp312-pypy312_pp80-macosx_10_12_x86_64.whl", hash = "sha256:56c6952a9b15047466d0c2347c446a761d4527f89976156341e68f0ce5cc08b0"}, + {file = "rpds_py-2026.9.1-pp312-pypy312_pp80-macosx_11_0_arm64.whl", hash = "sha256:b242c27c8f836305a4a72df9cdd564386ac57b807bd252a063223331c9316b37"}, + {file = "rpds_py-2026.9.1.tar.gz", hash = "sha256:4793ef7f78268b124b73fa933440f01d258bbae01de9fa53e9080c9ab0425a12"}, +] + [[package]] name = "ruff" version = "0.15.12" @@ -3724,63 +3701,6 @@ testing = ["fsspec (>=2024.6.0)", "h5py (>=3.7.0)", "hypothesis (>=6.70.2)", "py tf-nightly = ["safetensors[numpy]", "tf-nightly"] torch = ["safetensors[numpy]", "torch (>=2.4)"] -[[package]] -name = "scikit-learn" -version = "1.7.2" -description = "A set of python modules for machine learning and data mining" -optional = false -python-versions = ">=3.10" -groups = ["main"] -markers = "python_version == \"3.10\"" -files = [ - {file = "scikit_learn-1.7.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:6b33579c10a3081d076ab403df4a4190da4f4432d443521674637677dc91e61f"}, - {file = "scikit_learn-1.7.2-cp310-cp310-macosx_12_0_arm64.whl", hash = "sha256:36749fb62b3d961b1ce4fedf08fa57a1986cd409eff2d783bca5d4b9b5fce51c"}, - {file = "scikit_learn-1.7.2-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:7a58814265dfc52b3295b1900cfb5701589d30a8bb026c7540f1e9d3499d5ec8"}, - {file = "scikit_learn-1.7.2-cp310-cp310-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4a847fea807e278f821a0406ca01e387f97653e284ecbd9750e3ee7c90347f18"}, - {file = "scikit_learn-1.7.2-cp310-cp310-win_amd64.whl", hash = "sha256:ca250e6836d10e6f402436d6463d6c0e4d8e0234cfb6a9a47835bd392b852ce5"}, - {file = "scikit_learn-1.7.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:c7509693451651cd7361d30ce4e86a1347493554f172b1c72a39300fa2aea79e"}, - {file = "scikit_learn-1.7.2-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:0486c8f827c2e7b64837c731c8feff72c0bd2b998067a8a9cbc10643c31f0fe1"}, - {file = "scikit_learn-1.7.2-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:89877e19a80c7b11a2891a27c21c4894fb18e2c2e077815bcade10d34287b20d"}, - {file = "scikit_learn-1.7.2-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8da8bf89d4d79aaec192d2bda62f9b56ae4e5b4ef93b6a56b5de4977e375c1f1"}, - {file = "scikit_learn-1.7.2-cp311-cp311-win_amd64.whl", hash = "sha256:9b7ed8d58725030568523e937c43e56bc01cadb478fc43c042a9aca1dacb3ba1"}, - {file = "scikit_learn-1.7.2-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:8d91a97fa2b706943822398ab943cde71858a50245e31bc71dba62aab1d60a96"}, - {file = "scikit_learn-1.7.2-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:acbc0f5fd2edd3432a22c69bed78e837c70cf896cd7993d71d51ba6708507476"}, - {file = "scikit_learn-1.7.2-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:e5bf3d930aee75a65478df91ac1225ff89cd28e9ac7bd1196853a9229b6adb0b"}, - {file = "scikit_learn-1.7.2-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b4d6e9deed1a47aca9fe2f267ab8e8fe82ee20b4526b2c0cd9e135cea10feb44"}, - {file = "scikit_learn-1.7.2-cp312-cp312-win_amd64.whl", hash = "sha256:6088aa475f0785e01bcf8529f55280a3d7d298679f50c0bb70a2364a82d0b290"}, - {file = "scikit_learn-1.7.2-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:0b7dacaa05e5d76759fb071558a8b5130f4845166d88654a0f9bdf3eb57851b7"}, - {file = "scikit_learn-1.7.2-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:abebbd61ad9e1deed54cca45caea8ad5f79e1b93173dece40bb8e0c658dbe6fe"}, - {file = "scikit_learn-1.7.2-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:502c18e39849c0ea1a5d681af1dbcf15f6cce601aebb657aabbfe84133c1907f"}, - {file = "scikit_learn-1.7.2-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7a4c328a71785382fe3fe676a9ecf2c86189249beff90bf85e22bdb7efaf9ae0"}, - {file = "scikit_learn-1.7.2-cp313-cp313-win_amd64.whl", hash = "sha256:63a9afd6f7b229aad94618c01c252ce9e6fa97918c5ca19c9a17a087d819440c"}, - {file = "scikit_learn-1.7.2-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:9acb6c5e867447b4e1390930e3944a005e2cb115922e693c08a323421a6966e8"}, - {file = "scikit_learn-1.7.2-cp313-cp313t-macosx_12_0_arm64.whl", hash = "sha256:2a41e2a0ef45063e654152ec9d8bcfc39f7afce35b08902bfe290c2498a67a6a"}, - {file = "scikit_learn-1.7.2-cp313-cp313t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:98335fb98509b73385b3ab2bd0639b1f610541d3988ee675c670371d6a87aa7c"}, - {file = "scikit_learn-1.7.2-cp313-cp313t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:191e5550980d45449126e23ed1d5e9e24b2c68329ee1f691a3987476e115e09c"}, - {file = "scikit_learn-1.7.2-cp313-cp313t-win_amd64.whl", hash = "sha256:57dc4deb1d3762c75d685507fbd0bc17160144b2f2ba4ccea5dc285ab0d0e973"}, - {file = "scikit_learn-1.7.2-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:fa8f63940e29c82d1e67a45d5297bdebbcb585f5a5a50c4914cc2e852ab77f33"}, - {file = "scikit_learn-1.7.2-cp314-cp314-macosx_12_0_arm64.whl", hash = "sha256:f95dc55b7902b91331fa4e5845dd5bde0580c9cd9612b1b2791b7e80c3d32615"}, - {file = "scikit_learn-1.7.2-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:9656e4a53e54578ad10a434dc1f993330568cfee176dff07112b8785fb413106"}, - {file = "scikit_learn-1.7.2-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:96dc05a854add0e50d3f47a1ef21a10a595016da5b007c7d9cd9d0bffd1fcc61"}, - {file = "scikit_learn-1.7.2-cp314-cp314-win_amd64.whl", hash = "sha256:bb24510ed3f9f61476181e4db51ce801e2ba37541def12dc9333b946fc7a9cf8"}, - {file = "scikit_learn-1.7.2.tar.gz", hash = "sha256:20e9e49ecd130598f1ca38a1d85090e1a600147b9c02fa6f15d69cb53d968fda"}, -] - -[package.dependencies] -joblib = ">=1.2.0" -numpy = ">=1.22.0" -scipy = ">=1.8.0" -threadpoolctl = ">=3.1.0" - -[package.extras] -benchmark = ["matplotlib (>=3.5.0)", "memory_profiler (>=0.57.0)", "pandas (>=1.4.0)"] -build = ["cython (>=3.0.10)", "meson-python (>=0.17.1)", "numpy (>=1.22.0)", "scipy (>=1.8.0)"] -docs = ["Pillow (>=8.4.0)", "matplotlib (>=3.5.0)", "memory_profiler (>=0.57.0)", "numpydoc (>=1.2.0)", "pandas (>=1.4.0)", "plotly (>=5.14.0)", "polars (>=0.20.30)", "pooch (>=1.6.0)", "pydata-sphinx-theme (>=0.15.3)", "scikit-image (>=0.19.0)", "seaborn (>=0.9.0)", "sphinx (>=7.3.7)", "sphinx-copybutton (>=0.5.2)", "sphinx-design (>=0.5.0)", "sphinx-design (>=0.6.0)", "sphinx-gallery (>=0.17.1)", "sphinx-prompt (>=1.4.0)", "sphinx-remove-toctrees (>=1.0.0.post1)", "sphinxcontrib-sass (>=0.3.4)", "sphinxext-opengraph (>=0.9.1)", "towncrier (>=24.8.0)"] -examples = ["matplotlib (>=3.5.0)", "pandas (>=1.4.0)", "plotly (>=5.14.0)", "pooch (>=1.6.0)", "scikit-image (>=0.19.0)", "seaborn (>=0.9.0)"] -install = ["joblib (>=1.2.0)", "numpy (>=1.22.0)", "scipy (>=1.8.0)", "threadpoolctl (>=3.1.0)"] -maintenance = ["conda-lock (==3.0.1)"] -tests = ["matplotlib (>=3.5.0)", "mypy (>=1.15)", "numpydoc (>=1.2.0)", "pandas (>=1.4.0)", "polars (>=0.20.30)", "pooch (>=1.6.0)", "pyamg (>=4.2.1)", "pyarrow (>=12.0.0)", "pytest (>=7.1.2)", "pytest-cov (>=2.9.0)", "ruff (>=0.11.7)", "scikit-image (>=0.19.0)"] - [[package]] name = "scikit-learn" version = "1.9.0" @@ -3788,7 +3708,6 @@ description = "A set of python modules for machine learning and data mining" optional = false python-versions = ">=3.11" groups = ["main"] -markers = "python_version >= \"3.11\"" files = [ {file = "scikit_learn-1.9.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:9db6f4d34e68c8899e4cab27fdf8eafe6ed21f2ba52ceb25ea250cd237f8e47b"}, {file = "scikit_learn-1.9.0-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:f401448645a3e7bc115aa3c094097865155b34bff1cba8101857d9104e99074c"}, @@ -3839,71 +3758,6 @@ install = ["joblib (>=1.4.0)", "narwhals (>=2.0.1)", "numpy (>=1.24.1)", "scipy maintenance = ["conda-lock (==3.0.1)"] tests = ["matplotlib (>=3.6.1)", "mypy (>=1.15)", "numpydoc (>=1.2.0)", "pandas (>=1.5.0)", "polars (>=0.20.30)", "pooch (>=1.8.0)", "pyamg (>=5.0.0)", "pyarrow (>=13.0.0)", "pytest (>=7.1.2)", "pytest-cov (>=2.9.0)", "rich (>=14.1.0)", "ruff (>=0.12.2)"] -[[package]] -name = "scipy" -version = "1.15.3" -description = "Fundamental algorithms for scientific computing in Python" -optional = false -python-versions = ">=3.10" -groups = ["main"] -markers = "python_version == \"3.10\"" -files = [ - {file = "scipy-1.15.3-cp310-cp310-macosx_10_13_x86_64.whl", hash = "sha256:a345928c86d535060c9c2b25e71e87c39ab2f22fc96e9636bd74d1dbf9de448c"}, - {file = "scipy-1.15.3-cp310-cp310-macosx_12_0_arm64.whl", hash = "sha256:ad3432cb0f9ed87477a8d97f03b763fd1d57709f1bbde3c9369b1dff5503b253"}, - {file = "scipy-1.15.3-cp310-cp310-macosx_14_0_arm64.whl", hash = "sha256:aef683a9ae6eb00728a542b796f52a5477b78252edede72b8327a886ab63293f"}, - {file = "scipy-1.15.3-cp310-cp310-macosx_14_0_x86_64.whl", hash = "sha256:1c832e1bd78dea67d5c16f786681b28dd695a8cb1fb90af2e27580d3d0967e92"}, - {file = "scipy-1.15.3-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:263961f658ce2165bbd7b99fa5135195c3a12d9bef045345016b8b50c315cb82"}, - {file = "scipy-1.15.3-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9e2abc762b0811e09a0d3258abee2d98e0c703eee49464ce0069590846f31d40"}, - {file = "scipy-1.15.3-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:ed7284b21a7a0c8f1b6e5977ac05396c0d008b89e05498c8b7e8f4a1423bba0e"}, - {file = "scipy-1.15.3-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:5380741e53df2c566f4d234b100a484b420af85deb39ea35a1cc1be84ff53a5c"}, - {file = "scipy-1.15.3-cp310-cp310-win_amd64.whl", hash = "sha256:9d61e97b186a57350f6d6fd72640f9e99d5a4a2b8fbf4b9ee9a841eab327dc13"}, - {file = "scipy-1.15.3-cp311-cp311-macosx_10_13_x86_64.whl", hash = "sha256:993439ce220d25e3696d1b23b233dd010169b62f6456488567e830654ee37a6b"}, - {file = "scipy-1.15.3-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:34716e281f181a02341ddeaad584205bd2fd3c242063bd3423d61ac259ca7eba"}, - {file = "scipy-1.15.3-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:3b0334816afb8b91dab859281b1b9786934392aa3d527cd847e41bb6f45bee65"}, - {file = "scipy-1.15.3-cp311-cp311-macosx_14_0_x86_64.whl", hash = "sha256:6db907c7368e3092e24919b5e31c76998b0ce1684d51a90943cb0ed1b4ffd6c1"}, - {file = "scipy-1.15.3-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:721d6b4ef5dc82ca8968c25b111e307083d7ca9091bc38163fb89243e85e3889"}, - {file = "scipy-1.15.3-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:39cb9c62e471b1bb3750066ecc3a3f3052b37751c7c3dfd0fd7e48900ed52982"}, - {file = "scipy-1.15.3-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:795c46999bae845966368a3c013e0e00947932d68e235702b5c3f6ea799aa8c9"}, - {file = "scipy-1.15.3-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:18aaacb735ab38b38db42cb01f6b92a2d0d4b6aabefeb07f02849e47f8fb3594"}, - {file = "scipy-1.15.3-cp311-cp311-win_amd64.whl", hash = "sha256:ae48a786a28412d744c62fd7816a4118ef97e5be0bee968ce8f0a2fba7acf3bb"}, - {file = "scipy-1.15.3-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:6ac6310fdbfb7aa6612408bd2f07295bcbd3fda00d2d702178434751fe48e019"}, - {file = "scipy-1.15.3-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:185cd3d6d05ca4b44a8f1595af87f9c372bb6acf9c808e99aa3e9aa03bd98cf6"}, - {file = "scipy-1.15.3-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:05dc6abcd105e1a29f95eada46d4a3f251743cfd7d3ae8ddb4088047f24ea477"}, - {file = "scipy-1.15.3-cp312-cp312-macosx_14_0_x86_64.whl", hash = "sha256:06efcba926324df1696931a57a176c80848ccd67ce6ad020c810736bfd58eb1c"}, - {file = "scipy-1.15.3-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c05045d8b9bfd807ee1b9f38761993297b10b245f012b11b13b91ba8945f7e45"}, - {file = "scipy-1.15.3-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:271e3713e645149ea5ea3e97b57fdab61ce61333f97cfae392c28ba786f9bb49"}, - {file = "scipy-1.15.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:6cfd56fc1a8e53f6e89ba3a7a7251f7396412d655bca2aa5611c8ec9a6784a1e"}, - {file = "scipy-1.15.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:0ff17c0bb1cb32952c09217d8d1eed9b53d1463e5f1dd6052c7857f83127d539"}, - {file = "scipy-1.15.3-cp312-cp312-win_amd64.whl", hash = "sha256:52092bc0472cfd17df49ff17e70624345efece4e1a12b23783a1ac59a1b728ed"}, - {file = "scipy-1.15.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:2c620736bcc334782e24d173c0fdbb7590a0a436d2fdf39310a8902505008759"}, - {file = "scipy-1.15.3-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:7e11270a000969409d37ed399585ee530b9ef6aa99d50c019de4cb01e8e54e62"}, - {file = "scipy-1.15.3-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:8c9ed3ba2c8a2ce098163a9bdb26f891746d02136995df25227a20e71c396ebb"}, - {file = "scipy-1.15.3-cp313-cp313-macosx_14_0_x86_64.whl", hash = "sha256:0bdd905264c0c9cfa74a4772cdb2070171790381a5c4d312c973382fc6eaf730"}, - {file = "scipy-1.15.3-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:79167bba085c31f38603e11a267d862957cbb3ce018d8b38f79ac043bc92d825"}, - {file = "scipy-1.15.3-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:c9deabd6d547aee2c9a81dee6cc96c6d7e9a9b1953f74850c179f91fdc729cb7"}, - {file = "scipy-1.15.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:dde4fc32993071ac0c7dd2d82569e544f0bdaff66269cb475e0f369adad13f11"}, - {file = "scipy-1.15.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:f77f853d584e72e874d87357ad70f44b437331507d1c311457bed8ed2b956126"}, - {file = "scipy-1.15.3-cp313-cp313-win_amd64.whl", hash = "sha256:b90ab29d0c37ec9bf55424c064312930ca5f4bde15ee8619ee44e69319aab163"}, - {file = "scipy-1.15.3-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:3ac07623267feb3ae308487c260ac684b32ea35fd81e12845039952f558047b8"}, - {file = "scipy-1.15.3-cp313-cp313t-macosx_12_0_arm64.whl", hash = "sha256:6487aa99c2a3d509a5227d9a5e889ff05830a06b2ce08ec30df6d79db5fcd5c5"}, - {file = "scipy-1.15.3-cp313-cp313t-macosx_14_0_arm64.whl", hash = "sha256:50f9e62461c95d933d5c5ef4a1f2ebf9a2b4e83b0db374cb3f1de104d935922e"}, - {file = "scipy-1.15.3-cp313-cp313t-macosx_14_0_x86_64.whl", hash = "sha256:14ed70039d182f411ffc74789a16df3835e05dc469b898233a245cdfd7f162cb"}, - {file = "scipy-1.15.3-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0a769105537aa07a69468a0eefcd121be52006db61cdd8cac8a0e68980bbb723"}, - {file = "scipy-1.15.3-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9db984639887e3dffb3928d118145ffe40eff2fa40cb241a306ec57c219ebbbb"}, - {file = "scipy-1.15.3-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:40e54d5c7e7ebf1aa596c374c49fa3135f04648a0caabcb66c52884b943f02b4"}, - {file = "scipy-1.15.3-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:5e721fed53187e71d0ccf382b6bf977644c533e506c4d33c3fb24de89f5c3ed5"}, - {file = "scipy-1.15.3-cp313-cp313t-win_amd64.whl", hash = "sha256:76ad1fb5f8752eabf0fa02e4cc0336b4e8f021e2d5f061ed37d6d264db35e3ca"}, - {file = "scipy-1.15.3.tar.gz", hash = "sha256:eae3cf522bc7df64b42cad3925c876e1b0b6c35c1337c93e12c0f366f55b0eaf"}, -] - -[package.dependencies] -numpy = ">=1.23.5,<2.5" - -[package.extras] -dev = ["cython-lint (>=0.12.2)", "doit (>=0.36.0)", "mypy (==1.10.0)", "pycodestyle", "pydevtool", "rich-click", "ruff (>=0.0.292)", "types-psutil", "typing_extensions"] -doc = ["intersphinx_registry", "jupyterlite-pyodide-kernel", "jupyterlite-sphinx (>=0.19.1)", "jupytext", "matplotlib (>=3.5)", "myst-nb", "numpydoc", "pooch", "pydata-sphinx-theme (>=0.15.2)", "sphinx (>=5.0.0,<8.0.0)", "sphinx-copybutton", "sphinx-design (>=0.4.0)"] -test = ["Cython", "array-api-strict (>=2.0,<2.1.1)", "asv", "gmpy2", "hypothesis (>=6.30)", "meson", "mpmath", "ninja ; sys_platform != \"emscripten\"", "pooch", "pytest", "pytest-cov", "pytest-timeout", "pytest-xdist", "scikit-umfpack", "threadpoolctl"] - [[package]] name = "scipy" version = "1.17.1" @@ -4177,43 +4031,6 @@ files = [ {file = "soupsieve-2.8.4.tar.gz", hash = "sha256:e121fd02e975c695e4e9e8774a5ee35d74714b59307868dcc5319ad2d9e3328e"}, ] -[[package]] -name = "sphinx" -version = "8.1.3" -description = "Python documentation generator" -optional = false -python-versions = ">=3.10" -groups = ["docs"] -markers = "python_version == \"3.10\"" -files = [ - {file = "sphinx-8.1.3-py3-none-any.whl", hash = "sha256:09719015511837b76bf6e03e42eb7595ac8c2e41eeb9c29c5b755c6b677992a2"}, - {file = "sphinx-8.1.3.tar.gz", hash = "sha256:43c1911eecb0d3e161ad78611bc905d1ad0e523e4ddc202a58a821773dc4c927"}, -] - -[package.dependencies] -alabaster = ">=0.7.14" -babel = ">=2.13" -colorama = {version = ">=0.4.6", markers = "sys_platform == \"win32\""} -docutils = ">=0.20,<0.22" -imagesize = ">=1.3" -Jinja2 = ">=3.1" -packaging = ">=23.0" -Pygments = ">=2.17" -requests = ">=2.30.0" -snowballstemmer = ">=2.2" -sphinxcontrib-applehelp = ">=1.0.7" -sphinxcontrib-devhelp = ">=1.0.6" -sphinxcontrib-htmlhelp = ">=2.0.6" -sphinxcontrib-jsmath = ">=1.0.1" -sphinxcontrib-qthelp = ">=1.0.6" -sphinxcontrib-serializinghtml = ">=1.1.9" -tomli = {version = ">=2", markers = "python_version < \"3.11\""} - -[package.extras] -docs = ["sphinxcontrib-websupport"] -lint = ["flake8 (>=6.0)", "mypy (==1.11.1)", "pyright (==1.1.384)", "pytest (>=6.0)", "ruff (==0.6.9)", "sphinx-lint (>=0.9)", "tomli (>=2)", "types-Pillow (==10.2.0.20240822)", "types-Pygments (==2.18.0.20240506)", "types-colorama (==0.4.15.20240311)", "types-defusedxml (==0.7.0.20240218)", "types-docutils (==0.21.0.20241005)", "types-requests (==2.32.0.20240914)", "types-urllib3 (==1.26.25.14)"] -test = ["cython (>=3.0)", "defusedxml (>=0.7.1)", "pytest (>=8.0)", "setuptools (>=70.0)", "typing_extensions (>=4.9)"] - [[package]] name = "sphinx" version = "9.0.4" @@ -4297,33 +4114,6 @@ sphinx = ">=1.8" code-style = ["pre-commit (==2.12.1)"] rtd = ["ipython", "myst-nb", "sphinx", "sphinx-book-theme", "sphinx-examples"] -[[package]] -name = "sphinx-design" -version = "0.6.1" -description = "A sphinx extension for designing beautiful, view size responsive web components." -optional = false -python-versions = ">=3.9" -groups = ["docs"] -markers = "python_version == \"3.10\"" -files = [ - {file = "sphinx_design-0.6.1-py3-none-any.whl", hash = "sha256:b11f37db1a802a183d61b159d9a202314d4d2fe29c163437001324fe2f19549c"}, - {file = "sphinx_design-0.6.1.tar.gz", hash = "sha256:b44eea3719386d04d765c1a8257caca2b3e6f8421d7b3a5e742c0fd45f84e632"}, -] - -[package.dependencies] -sphinx = ">=6,<9" - -[package.extras] -code-style = ["pre-commit (>=3,<4)"] -rtd = ["myst-parser (>=2,<4)"] -testing = ["defusedxml", "myst-parser (>=2,<4)", "pytest (>=8.3,<9.0)", "pytest-cov", "pytest-regressions"] -testing-no-myst = ["defusedxml", "pytest (>=8.3,<9.0)", "pytest-cov", "pytest-regressions"] -theme-furo = ["furo (>=2024.7.18,<2024.8.0)"] -theme-im = ["sphinx-immaterial (>=0.12.2,<0.13.0)"] -theme-pydata = ["pydata-sphinx-theme (>=0.15.2,<0.16.0)"] -theme-rtd = ["sphinx-rtd-theme (>=2.0,<3.0)"] -theme-sbt = ["sphinx-book-theme (>=1.1,<2.0)"] - [[package]] name = "sphinx-design" version = "0.7.0" @@ -4331,7 +4121,6 @@ description = "A sphinx extension for designing beautiful, view size responsive optional = false python-versions = ">=3.11" groups = ["docs"] -markers = "python_version >= \"3.11\"" files = [ {file = "sphinx_design-0.7.0-py3-none-any.whl", hash = "sha256:f82bf179951d58f55dca78ab3706aeafa496b741a91b1911d371441127d64282"}, {file = "sphinx_design-0.7.0.tar.gz", hash = "sha256:d2a3f5b19c24b916adb52f97c5f00efab4009ca337812001109084a740ec9b7a"}, @@ -4582,7 +4371,7 @@ version = "2.4.1" description = "A lil' TOML parser" optional = false python-versions = ">=3.8" -groups = ["dev", "docs"] +groups = ["dev"] files = [ {file = "tomli-2.4.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:f8f0fc26ec2cc2b965b7a3b87cd19c5c6b8c5e5f436b984e85f486d652285c30"}, {file = "tomli-2.4.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:4ab97e64ccda8756376892c53a72bd1f964e519c77236368527f758fbc36a53a"}, @@ -4632,7 +4421,6 @@ files = [ {file = "tomli-2.4.1-py3-none-any.whl", hash = "sha256:0d85819802132122da43cb86656f8d1f8c6587d54ae7dcaf30e90533028b49fe"}, {file = "tomli-2.4.1.tar.gz", hash = "sha256:7c7e1a961a0b2f2472c1ac5b69affa0ae1132c39adcb67aba98568702b9cc23f"}, ] -markers = {docs = "python_version == \"3.10\""} [[package]] name = "tomli-w" @@ -4960,7 +4748,6 @@ distlib = ">=0.3.7,<1" filelock = {version = ">=3.24.2,<4", markers = "python_version >= \"3.10\""} platformdirs = ">=3.9.1,<5" python-discovery = ">=1.4.2" -typing-extensions = {version = ">=4.13.2", markers = "python_version < \"3.11\""} [[package]] name = "wcwidth" @@ -4981,7 +4768,7 @@ description = "Backport of pathlib-compatible object wrapper for zip files" optional = false python-versions = ">=3.10" groups = ["dev"] -markers = "python_version < \"3.12\" and (platform_machine == \"aarch64\" or platform_machine == \"x86_64\") or python_version < \"3.12\" and platform_machine != \"ppc64le\" and platform_machine != \"s390x\"" +markers = "python_version == \"3.11\" and (platform_machine == \"aarch64\" or platform_machine == \"x86_64\" or platform_machine != \"ppc64le\" and platform_machine != \"s390x\")" files = [ {file = "zipp-4.1.0-py3-none-any.whl", hash = "sha256:25ad4e16390cd314347dd8f1de67a2ac538ae658ed4ab9db16029c07c188e97f"}, {file = "zipp-4.1.0.tar.gz", hash = "sha256:4cb57381f544315db7688e976e922a2b18cdb513d21cc194eb42232ba2a3e602"}, @@ -5003,5 +4790,5 @@ polars = ["polars"] [metadata] lock-version = "2.1" -python-versions = ">=3.10,<3.14" -content-hash = "72350f56d6631ce5895d0ccc60dc374cd09526ccb2068569acc2c4204489589f" +python-versions = ">=3.11,<3.14" +content-hash = "e0214dbfddf78e19d25b36663c3cd5b05fce6b1caf04619fbc65a47cb1c7f39f" diff --git a/pretab/__init__.py b/pretab/__init__.py index afa6482..61f5681 100644 --- a/pretab/__init__.py +++ b/pretab/__init__.py @@ -1,4 +1,5 @@ from ._version import __version__ +from .compose import FeatureGroup, RepresentationConfig from .compose.search import RepresentationSearchCV from .core.logging import configure_logging, set_verbosity from .core.policy import RepresentationPolicy @@ -12,6 +13,7 @@ PretabWarning, RepresentationConformanceError, ) +from .expansion.spline import PenaltySpec from .extension import ( BaseRepresentation, check_representation, @@ -24,13 +26,16 @@ __all__ = [ "BaseRepresentation", "CrossFittedTransformer", + "FeatureGroup", "FeatureLineage", "FrozenRepresentationError", "LeakageWarning", "OutputBudgetError", + "PenaltySpec", "Preprocessor", "PretabSerializationError", "PretabWarning", + "RepresentationConfig", "RepresentationConformanceError", "RepresentationPolicy", "RepresentationSearchCV", diff --git a/pretab/compose/__init__.py b/pretab/compose/__init__.py index e00ec52..d6b522d 100644 --- a/pretab/compose/__init__.py +++ b/pretab/compose/__init__.py @@ -4,3 +4,7 @@ Includes the ``config``, ``registry``, ``factory``, ``feature_detection``, ``output`` and ``inspection`` modules. """ + +from .config import FeatureGroup, RepresentationConfig + +__all__ = ["FeatureGroup", "RepresentationConfig"] diff --git a/pretab/compose/config.py b/pretab/compose/config.py index 4408cb2..353dc62 100644 --- a/pretab/compose/config.py +++ b/pretab/compose/config.py @@ -8,33 +8,434 @@ the estimator (as scikit-learn requires); this object is the internal, normalized counterpart the composition layer consumes. -Per-column overrides in ``feature_preprocessing`` are kept verbatim because the -namespace they resolve in (numerical vs categorical) depends on the column type, -which is only known after feature detection; :meth:`PreprocessorConfig.method_for` -resolves them in the correct namespace at build time. +Structured per-column overrides detach at normalization. Their method namespace +(numerical vs categorical) depends on feature detection; ``method_for`` keeps +returning a string, while ``representation_for`` resolves applicable settings. """ from __future__ import annotations -from dataclasses import dataclass +from collections.abc import Iterator, Mapping, Sequence +from contextvars import ContextVar +from dataclasses import dataclass, field, fields, replace +from difflib import get_close_matches +from math import isfinite +from re import fullmatch +from typing import Any -from ..core.parameters import validate_placement, validate_task -from ..exceptions import invalid_param_error +from ..core.dependencies import _check_optional_dependency +from ..core.parameters import UNSET, _Unset, validate_placement, validate_task +from ..exceptions import IncompatibleParamsError, InvalidParamError, invalid_param_error from .registry import ( CATEGORICAL_ALIASES, CATEGORICAL_METHODS, NUMERICAL_ALIASES, NUMERICAL_METHODS, + TRANSFORMER_REGISTRY, resolve_method, ) -__all__ = ["PreprocessorConfig"] +__all__ = ["FeatureGroup", "PreprocessorConfig", "RepresentationConfig"] # Valid values for the high-level ``missing_policy`` orchestration knob. ``None`` # keeps the explicit imputation parameters authoritative (historical behaviour). MISSING_POLICIES = frozenset({"error", "propagate", "impute", "impute_with_indicator", "separate_state"}) +_REPRESENTATION_PATH = ContextVar("representation_config_path", default="RepresentationConfig") +_FEATURE_GROUP_PATH = ContextVar("feature_group_path", default="FeatureGroup") + + +def _representation_error(param, value, constraint, *, valid=None): + """Use the standalone value name or the current normalization path.""" + return invalid_param_error(_REPRESENTATION_PATH.get(), param, value, constraint, valid=valid) + + +@dataclass(frozen=True, slots=True, eq=False) +class _FrozenParams(Mapping[str, Any]): + _entries: tuple[tuple[str, Any], ...] + + def __getitem__(self, key: str) -> Any: + for stored_key, value in self._entries: + if stored_key == key: + return value + raise KeyError(key) + + def __iter__(self) -> Iterator[str]: + return (key for key, _ in self._entries) + + def __len__(self) -> int: + return len(self._entries) + + def __repr__(self) -> str: + return repr(dict(self)) + + +def _freeze_config_value(value: Any, path: str, active: set[int]) -> Any: + if value is None or type(value) in (str, bool, int): + return value + if type(value) is float and isfinite(value): + return value + if not isinstance(value, (Mapping, Sequence)) or isinstance(value, (str, bytes, bytearray, memoryview)): + raise _representation_error(path, value, "must contain only finite JSON-compatible values") + identity = id(value) + if identity in active: + raise _representation_error(path, value, "must not contain circular references") + active.add(identity) + try: + if isinstance(value, Mapping): + entries = [] + for key, item in value.items(): + if type(key) is not str: + raise _representation_error(path, key, "mapping keys must be strings") + entries.append((key, _freeze_config_value(item, f"{path}[{key!r}]", active))) + return _FrozenParams(tuple(entries)) + return tuple(_freeze_config_value(item, f"{path}[{index}]", active) for index, item in enumerate(value)) + finally: + active.remove(identity) + + +def _config_value_to_json(value: Any) -> Any: + if isinstance(value, Mapping): + return {key: _config_value_to_json(item) for key, item in value.items()} + if isinstance(value, tuple): + return [_config_value_to_json(item) for item in value] + return value + + +@dataclass(frozen=True) +class RepresentationConfig: + """Immutable, JSON-compatible settings for one representation. + + Parameters + ---------- + method : str + Requested method name. Alias resolution and parameter applicability + require a numerical or categorical context and are checked separately. + output_dim : int, optional + Positive requested width, subject to the selected family's constraints. + target_aware : bool, optional + Whether to use the target for placement. + placement_strategy : str, optional + Requested nonempty placement-strategy name. + adaptive : bool, optional + Whether to use adaptive resolution. + min_output_dim, max_output_dim : int or None, optional + Positive adaptive bounds, or ``None`` where the method permits it. + params : mapping, optional + Family-specific options. Nested mappings and sequences are copied into + read-only storage. Only finite JSON-compatible values are accepted. + name : str or None, default=None + Optional metadata label; it does not rename input or output columns. + + Notes + ----- + Omitted common settings retain ``UNSET`` rather than adopting method defaults. + This value is not an estimator; it has no fitted state or ``set_params``. + """ + + method: str + output_dim: int | _Unset = UNSET + target_aware: bool | _Unset = UNSET + placement_strategy: str | _Unset = UNSET + adaptive: bool | _Unset = UNSET + min_output_dim: int | _Unset | None = UNSET + max_output_dim: int | _Unset | None = UNSET + params: Mapping[str, Any] = field(default_factory=dict) + name: str | None = None + + def __post_init__(self) -> None: + if self.method is UNSET: + raise _representation_error("method", self.method, "is required") + for key in ("method", "placement_strategy", "name"): + value = getattr(self, key) + if (key == "placement_strategy" and value is UNSET) or (key == "name" and value is None): + continue + if type(value) is not str or not value.strip(): + raise _representation_error(key, value, "must be a nonempty string") + for key in ("output_dim", "min_output_dim", "max_output_dim"): + value = getattr(self, key) + if value is UNSET or (key != "output_dim" and value is None): + continue + if type(value) is not int or value < 1: + raise _representation_error(key, value, "must be a positive integer") + for key in ("target_aware", "adaptive"): + value = getattr(self, key) + if value is not UNSET and type(value) is not bool: + raise _representation_error(key, value, "must be a boolean") + if not isinstance(self.params, Mapping): + raise _representation_error("params", self.params, "must be a mapping") + reserved = {item.name for item in fields(self)} + for key in self.params: + if key in reserved: + raise _representation_error( + f"params[{key!r}]", + self.params[key], + "must be supplied as a top-level field", + ) + object.__setattr__(self, "params", _freeze_config_value(self.params, "params", set())) + + def to_dict(self) -> dict[str, Any]: + """Return detached JSON-compatible settings, omitting ``UNSET`` fields.""" + return { + item.name: _config_value_to_json(value) + for item in fields(self) + if (value := getattr(self, item.name)) is not UNSET + } + + @classmethod + def from_dict(cls, data: Mapping[str, Any]) -> RepresentationConfig: + """Build a value from a mapping, collecting family options into ``params``. + + An option supplied both at the top level and in ``params`` is an error, + even if the two values agree. Method-specific validation requires the + feature-kind context and is not performed by this constructor. + """ + if not isinstance(data, Mapping): + raise _representation_error("data", data, "must be a mapping") + requested = dict(data) + if any(type(key) is not str for key in requested): + raise _representation_error("data", data, "mapping keys must be strings") + if "method" not in requested: + raise _representation_error("method", UNSET, "is required") + params = requested.pop("params", {}) + if not isinstance(params, Mapping): + raise _representation_error("params", params, "must be a mapping") + params = dict(params) + common = {item.name for item in fields(cls)} + for key in list(requested): + if key not in common: + if key in params: + raise _representation_error(key, requested[key], "must not also be supplied inside params") + params[key] = requested.pop(key) + return cls(**requested, params=params) + + +def _validate_representation_capabilities( + config: RepresentationConfig, + *, + is_numerical: bool, + source: str | Mapping[str, Any] | RepresentationConfig, + is_group: bool = False, +) -> None: + """Check explicit settings against the live spec without choosing defaults.""" + spec = TRANSFORMER_REGISTRY[config.method] + kind = "numerical" if is_numerical else "categorical" + if kind not in spec.feature_kind: + raise _representation_error("method", config.method, f"does not support {kind} features") + if is_group and not spec.group_compatible: + raise _representation_error("method", config.method, "does not support explicit feature groups") + if not is_group and not spec.preprocessor_compatible: + raise _representation_error("method", config.method, "is not selectable through Preprocessor") + for key, value in config.params.items(): + if key not in spec.allowed_args: + location = key if isinstance(source, Mapping) and key in source else f"params[{key!r}]" + raise _representation_error( + location, value, f"is not applicable to method {config.method!r}", valid=spec.allowed_args + ) + if ( + config.output_dim is not UNSET + and "output_dim" not in spec.allowed_args + and not spec.supports_adaptive_resolution + ): + raise _representation_error("output_dim", config.output_dim, f"is not applicable to method {config.method!r}") + for key in ("adaptive", "min_output_dim", "max_output_dim"): + value = getattr(config, key) + if value is not UNSET and not spec.supports_adaptive_resolution: + raise _representation_error(key, value, f"method {config.method!r} does not support adaptive resolution") + if config.target_aware is True and spec.target_usage == "forbidden": + raise _representation_error("target_aware", True, f"method {config.method!r} cannot use the target") + if config.target_aware is False and spec.target_usage == "required": + raise _representation_error("target_aware", False, f"method {config.method!r} requires the target") + if isinstance(config.placement_strategy, str): + if config.placement_strategy not in spec.placement_strategies: + raise _representation_error( + "placement_strategy", + config.placement_strategy, + f"is not supported by method {config.method!r}", + valid=spec.placement_strategies, + ) + target_aware = config.target_aware + if target_aware is UNSET and spec.target_usage != "optional": + target_aware = spec.target_usage == "required" + if isinstance(target_aware, bool): + try: + validate_placement(target_aware, config.placement_strategy) + except InvalidParamError as error: + raise _representation_error("placement_strategy", config.placement_strategy, str(error)) from error + for key in ("min_output_dim", "max_output_dim"): + value = getattr(config, key) + if config.adaptive is False and value is not UNSET: + raise _representation_error(key, value, "must not be supplied with adaptive=False") + if config.adaptive is True and type(config.min_output_dim) is int and type(config.max_output_dim) is int: + if config.min_output_dim > config.max_output_dim: + raise _representation_error("max_output_dim", config.max_output_dim, "must be >= min_output_dim") + path = _REPRESENTATION_PATH.get() + if spec.optional_dependency: + _check_optional_dependency(spec.optional_dependency, f"{path}.method = {config.method!r}") + if config.placement_strategy == "lightgbm": + _check_optional_dependency("lightgbm", f"{path}.placement_strategy = 'lightgbm'") + + +def _representation_request(value: str | Mapping[str, Any] | RepresentationConfig) -> RepresentationConfig: + if isinstance(value, RepresentationConfig): + return value + if isinstance(value, str): + return RepresentationConfig(method=value) + if isinstance(value, Mapping): + return RepresentationConfig.from_dict(value) + raise _representation_error("value", value, "must be a string, mapping, or RepresentationConfig") + + +@dataclass(frozen=True) +class FeatureGroup: + """Immutable declaration of ordered source columns and their representation. + + Parameters + ---------- + name : str + ASCII identifier beginning with a letter, without double underscores. + columns : sequence + Nonempty ordered source labels. Labels retain their original types; + integer labels identify named columns rather than positions. + representation : str, mapping, or RepresentationConfig + Representation request. Mappings use the same common fields and family + options as :class:`RepresentationConfig`. + + Notes + ----- + Columns become a tuple and representation settings detach into an immutable + value. This declaration has no fitted state and does not resolve an input + schema or perform a transformation. + """ + + name: str + columns: Sequence[Any] + representation: str | Mapping[str, Any] | RepresentationConfig + + def __post_init__(self) -> None: + path = _FEATURE_GROUP_PATH.get() + if type(self.name) is not str or fullmatch(r"[A-Za-z][A-Za-z0-9_]*", self.name) is None or "__" in self.name: + raise invalid_param_error(path, "name", self.name, "must be an ASCII identifier without double underscores") + if not isinstance(self.columns, Sequence) or isinstance(self.columns, (str, bytes, bytearray, memoryview)): + raise invalid_param_error(path, "columns", self.columns, "must be a nonempty ordered sequence of labels") + if not self.columns: + raise invalid_param_error(path, "columns", self.columns, "must be a nonempty ordered sequence of labels") + columns = tuple(self.columns) + for index, label in enumerate(columns): + try: + hash(label) + except TypeError as error: + raise invalid_param_error( + path, f"columns[{index}]", label, "must be a hashable column label" + ) from error + token = _REPRESENTATION_PATH.set(f"{path}.representation") + try: + representation = _representation_request(self.representation) + if representation.name is not None and representation.name != self.name: + raise _representation_error("name", representation.name, "must match the group name") + finally: + _REPRESENTATION_PATH.reset(token) + object.__setattr__(self, "columns", columns) + object.__setattr__(self, "representation", representation) + + +def _normalize_representation_config( + value: str | Mapping[str, Any] | RepresentationConfig, + *, + is_numerical: bool, + path: str = "RepresentationConfig", + is_group: bool = False, +) -> RepresentationConfig: + """Normalize one request in its known feature-kind namespace. + + Raw mappings detach through ``from_dict``. Typed values retain their + requested spelling; normalization replaces rather than mutates an alias. + Omitted fields remain ``UNSET``. Unknown methods/options and invalid value + shapes raise path-qualified errors. Explicit options are checked against + live registry capabilities; omitted effective defaults remain unresolved. + """ + token = _REPRESENTATION_PATH.set(path) + try: + config = _representation_request(value) + canonical = TRANSFORMER_REGISTRY if is_group else (NUMERICAL_METHODS if is_numerical else CATEGORICAL_METHODS) + aliases = NUMERICAL_ALIASES if is_numerical else CATEGORICAL_ALIASES + method = resolve_method(config.method, canonical, aliases) + if method not in canonical: + kind = "numerical" if is_numerical else "categorical" + raise _representation_error( + "method", method, f"unrecognized {kind} preprocessing method", valid=set(canonical) + ) + common = {item.name for item in fields(RepresentationConfig)} + known = common | {key for spec in TRANSFORMER_REGISTRY.values() for key in spec.allowed_args} + applicable = common | set(TRANSFORMER_REGISTRY[method].allowed_args) + for key in config.params: + if key not in known: + location = key if isinstance(value, Mapping) and key in value else f"params[{key!r}]" + matches = get_close_matches(key, sorted(applicable), n=3) + constraint = "unrecognized representation option" + if matches: + constraint += f". Did you mean {', '.join(repr(match) for match in matches)}?" + raise _representation_error(location, config.params[key], constraint, valid=applicable) + normalized = config if method == config.method else replace(config, method=method) + _validate_representation_capabilities(normalized, is_numerical=is_numerical, source=value, is_group=is_group) + return normalized + finally: + _REPRESENTATION_PATH.reset(token) + + +def _normalize_feature_groups(value) -> tuple[FeatureGroup, ...]: + if value is None: + return () + mapping_form = isinstance(value, Mapping) + if mapping_form: + entries = value.items() + elif isinstance(value, Sequence) and not isinstance(value, (str, bytes, bytearray, memoryview)): + entries = enumerate(value) + else: + raise invalid_param_error("Preprocessor", "feature_groups", value, "must be an ordered mapping or sequence") + groups = [] + names = set() + for key, entry in entries: + path = f"feature_groups[{key!r}]" + token = _FEATURE_GROUP_PATH.set(path) + try: + if mapping_form: + if not isinstance(key, str): + raise invalid_param_error(path, "name", key, "must be a string") + if not isinstance(entry, Mapping) or set(entry) != {"columns", "representation"}: + raise invalid_param_error( + "Preprocessor", path, entry, "mapping entries must contain exactly columns and representation" + ) + group = FeatureGroup(name=key, columns=entry["columns"], representation=entry["representation"]) + elif isinstance(entry, FeatureGroup): + group = entry + elif isinstance(entry, Mapping) and set(entry) == {"name", "columns", "representation"}: + group = FeatureGroup( + name=entry["name"], columns=entry["columns"], representation=entry["representation"] + ) + else: + raise invalid_param_error( + "Preprocessor", + path, + entry, + "must be a FeatureGroup or a mapping with name, columns and representation", + ) + if group.name in names: + raise invalid_param_error(path, "name", group.name, "must be unique among feature groups") + representation = _normalize_representation_config( + group.representation, + is_numerical=True, + is_group=True, + path=f"feature_groups[{group.name!r}].representation", + ) + groups.append(replace(group, representation=representation)) + names.add(group.name) + finally: + _FEATURE_GROUP_PATH.reset(token) + return tuple(groups) + + def _normalize_method(method, canonical, aliases) -> str: """Resolve a global method name to canonical form, mapping ``None`` to ``"none"``.""" if method is None: @@ -47,8 +448,9 @@ class PreprocessorConfig: """Frozen, normalized configuration derived from Preprocessor parameters. Built via :meth:`from_params`, which normalizes the global method names and - validates the placement contract and the task. All other knobs are carried - through as-is for the factory and orchestration layers. + validates the placement contract and the task. Structured overrides detach + into immutable requests; their feature-kind resolution is deferred until + ``method_for`` or ``representation_for`` is called. """ numerical_method: str @@ -71,6 +473,7 @@ class PreprocessorConfig: add_missing_indicator: bool missing_policy: str | None verbose: int + feature_groups: tuple[FeatureGroup, ...] = () @classmethod def from_params( @@ -96,6 +499,7 @@ def from_params( add_missing_indicator, missing_policy, verbose, + feature_groups=None, ) -> PreprocessorConfig: """Normalize and validate raw Preprocessor parameters into a config. @@ -117,10 +521,19 @@ def from_params( "must be None or one of 'error', 'propagate', 'impute', 'impute_with_indicator', 'separate_state'", valid=set(MISSING_POLICIES), ) + overrides = dict(feature_preprocessing or {}) + for feature, value in overrides.items(): + if isinstance(value, str): + continue + token = _REPRESENTATION_PATH.set(f"feature_preprocessing[{feature!r}]") + try: + overrides[feature] = _representation_request(value) + finally: + _REPRESENTATION_PATH.reset(token) return cls( numerical_method=_normalize_method(numerical_method, NUMERICAL_METHODS, NUMERICAL_ALIASES), categorical_method=_normalize_method(categorical_method, CATEGORICAL_METHODS, CATEGORICAL_ALIASES), - feature_preprocessing=dict(feature_preprocessing or {}), + feature_preprocessing=overrides, output_dim=output_dim, degree=degree, target_aware=target_aware, @@ -138,6 +551,7 @@ def from_params( add_missing_indicator=add_missing_indicator, missing_policy=missing_policy, verbose=verbose, + feature_groups=_normalize_feature_groups(feature_groups), ) @staticmethod @@ -159,8 +573,111 @@ def method_for(self, feature, *, is_numerical: bool) -> str: """ default = self.numerical_method if is_numerical else self.categorical_method raw = self.feature_preprocessing.get(feature, default) + if isinstance(raw, (Mapping, RepresentationConfig)): + return _normalize_representation_config( + raw, is_numerical=is_numerical, path=f"feature_preprocessing[{feature!r}]" + ).method return self.resolve_numerical(raw) if is_numerical else self.resolve_categorical(raw) + def representation_for(self, feature, *, is_numerical: bool | None = None) -> RepresentationConfig: + """Resolve one feature request over applicable constructor-wide controls. + + Method defaults remain omitted when the existing factory would not + forward a constructor-wide value. Inherited inactive adaptive bounds + are dropped, but contradictory explicit local bounds are rejected. + Without a detected kind, resolve the declared method's namespace only; + compatibility with the actual input still belongs to fitting. + """ + default = self.categorical_method if is_numerical is False else self.numerical_method + raw = self.feature_preprocessing.get(feature, default) + path = f"feature_preprocessing[{feature!r}]" + if is_numerical is None: + token = _REPRESENTATION_PATH.set(path) + try: + method = _representation_request(raw).method + finally: + _REPRESENTATION_PATH.reset(token) + is_numerical = self.resolve_categorical(method) not in CATEGORICAL_METHODS + return self._resolve_representation(raw, is_numerical=is_numerical, path=path) + + def group_representation_for(self, group: FeatureGroup) -> RepresentationConfig: + """Resolve a group's representation over applicable constructor controls.""" + return self._resolve_representation( + group.representation, + is_numerical=True, + is_group=True, + path=f"feature_groups[{group.name!r}].representation", + ) + + def validate_feature_groups(self, columns, numerical_features, *, y=None) -> None: + """Check group ownership and capabilities against the detected input schema.""" + available = set(columns) + numerical = set(numerical_features) + owners = {} + for group in self.feature_groups: + path = f"feature_groups[{group.name!r}]" + representation = self.group_representation_for(group) + spec = TRANSFORMER_REGISTRY[representation.method] + for index, label in enumerate(group.columns): + location = f"columns[{index}]" + if label in owners: + owner, source_index = owners[label] + raise invalid_param_error( + path, + location, + label, + f"already assigned to feature_groups[{owner!r}].columns[{source_index}]", + ) + if label in self.feature_preprocessing: + raise invalid_param_error( + path, location, label, f"must not also be assigned in feature_preprocessing[{label!r}]" + ) + if label not in available: + raise invalid_param_error(path, location, label, "must name a column present in X", valid=columns) + kind = "numerical" if label in numerical else "categorical" + if kind not in spec.feature_kind: + raise invalid_param_error( + path, location, label, f"detected {kind} source is not supported by method {spec.name!r}" + ) + owners[label] = (group.name, index) + arity = len(group.columns) + if arity < spec.min_arity or (spec.max_arity is not None and arity > spec.max_arity): + bounds = ( + f"at least {spec.min_arity}" if spec.max_arity is None else f"{spec.min_arity} to {spec.max_arity}" + ) + raise invalid_param_error( + path, "columns", group.columns, f"method {spec.name!r} requires {bounds} source columns" + ) + if y is None and (spec.requires_target or representation.target_aware is True): + raise IncompatibleParamsError( + f"{path}.representation.method = {spec.name!r} requires y at fit time; got y=None." + ) + + def _resolve_representation(self, raw, *, is_numerical: bool, path: str, is_group: bool = False): + requested = _normalize_representation_config(raw, is_numerical=is_numerical, path=path, is_group=is_group) + spec = TRANSFORMER_REGISTRY[requested.method] + inherited = {} + if "output_dim" in spec.allowed_args or spec.supports_adaptive_resolution: + inherited["output_dim"] = self.output_dim + if spec.target_usage in ("optional", "required"): + inherited["target_aware"] = self.target_aware + if spec.placement_strategies and (spec.target_usage != "forbidden" or not self.target_aware): + inherited["placement_strategy"] = self.placement_strategy + if spec.supports_adaptive_resolution: + adaptive = self.adaptive if requested.adaptive is UNSET else requested.adaptive + if requested.output_dim is not UNSET and requested.adaptive is UNSET: + adaptive = False + inherited["adaptive"] = adaptive + if adaptive: + inherited["min_output_dim"] = self.min_output_dim + inherited["max_output_dim"] = self.max_output_dim + shared = {"degree": self.degree, "task": self.task, **self.seed_kwargs} + params = {key: value for key, value in shared.items() if key in spec.allowed_args} + params.update(requested.params) + settings = {key: value for key, value in inherited.items() if getattr(requested, key) is UNSET} + resolved = replace(requested, **settings, params=params) + return _normalize_representation_config(resolved, is_numerical=is_numerical, path=path, is_group=is_group) + @property def seed_kwargs(self) -> dict: """Return ``{"random_state": ...}`` only when a seed was explicitly set. diff --git a/pretab/compose/factory.py b/pretab/compose/factory.py index c518edc..d96e84f 100644 --- a/pretab/compose/factory.py +++ b/pretab/compose/factory.py @@ -1,8 +1,8 @@ -"""Build the per-column transformer pipelines and combine them. +"""Build single-column and grouped transformer pipelines and combine them. -This module turns a resolved method name plus a :class:`PreprocessorConfig` into -scikit-learn transformer steps, wraps them in a per-column -:class:`~sklearn.pipeline.Pipeline`, and assembles every column into the final +This module turns resolved requests plus a :class:`PreprocessorConfig` into +scikit-learn transformer steps, wraps them in a shared +:class:`~sklearn.pipeline.Pipeline` construction path, and assembles the blocks into a :class:`~sklearn.compose.ColumnTransformer`. The class to instantiate, the constructor arguments it accepts, and which placement keyword arguments apply are all taken from :data:`~pretab.compose.registry.TRANSFORMER_REGISTRY`. @@ -19,12 +19,13 @@ from ..exceptions import ConfigWarning, IncompatibleParamsError, invalid_param_error from ..preprocessing.floats import ToFloatTransformer from ..preprocessing.missing import MissingStateIndicator, _CategoricalMissingNormalizer -from .config import PreprocessorConfig +from .config import PreprocessorConfig, RepresentationConfig, _normalize_representation_config from .registry import ( CATEGORICAL_ALIASES, CATEGORICAL_METHODS, NUMERICAL_ALIASES, NUMERICAL_METHODS, + TRANSFORMER_REGISTRY, TransformerSpec, get_spec, resolve_method, @@ -140,7 +141,28 @@ def get_numerical_transformer_steps( **kwargs, ): """Return the ordered ``(name, transformer)`` steps for a numerical ``method``.""" - method = resolve_method(method, NUMERICAL_METHODS, NUMERICAL_ALIASES) + return _get_numerical_transformer_steps( + method, add_imputer, imputer_strategy, imputer_kwargs, add_missing_indicator, scaling, kwargs + ) + + +def _get_numerical_transformer_steps( + method, + add_imputer, + imputer_strategy, + imputer_kwargs, + add_missing_indicator, + scaling, + kwargs, + *, + is_group=False, +): + methods = ( + {name for name, spec in TRANSFORMER_REGISTRY.items() if spec.group_compatible and spec.is_numerical} + if is_group + else NUMERICAL_METHODS + ) + method = resolve_method(method, methods, NUMERICAL_ALIASES) steps = [] if add_imputer: @@ -164,13 +186,13 @@ def get_numerical_transformer_steps( if scaling in scalers and scaling != method and method != "none": steps.append(scalers[scaling]) - if method not in NUMERICAL_METHODS: + if method not in methods: raise invalid_param_error( "get_numerical_transformer_steps", "method", method, "unrecognized numerical preprocessing method", - valid=set(NUMERICAL_METHODS), + valid=set(methods), ) spec = get_spec(method) @@ -268,12 +290,20 @@ def get_categorical_transformer_steps( return steps -def create_transformer(method: str, *, is_numerical: bool, config: PreprocessorConfig) -> Pipeline | FeatureUnion: +def create_transformer( + method: str, + *, + is_numerical: bool, + config: PreprocessorConfig, + representation: RepresentationConfig | None = None, +) -> Pipeline | FeatureUnion: """Build the per-column :class:`~sklearn.pipeline.Pipeline` for one feature. ``method`` is the resolved method name; ``is_numerical`` selects the numerical - or categorical construction path. All width / placement / seeding knobs are - taken from ``config``. + or categorical construction path. When ``representation`` is supplied, its + resolved settings replace the run-wide representation controls. Otherwise + existing calls use ``config`` unchanged. Imputation, scaling, and indicator + policy always come from ``config``. Raises ------ @@ -282,46 +312,86 @@ def create_transformer(method: str, *, is_numerical: bool, config: PreprocessorC run is configured with ``target_aware=False``; such a combination cannot be satisfied and is rejected instead of silently ignored. """ - known = method in NUMERICAL_METHODS if is_numerical else method in CATEGORICAL_METHODS + return _create_transformer(method, is_numerical=is_numerical, config=config, representation=representation) + + +def _create_transformer( + method: str, + *, + is_numerical: bool, + config: PreprocessorConfig, + representation: RepresentationConfig | None = None, + is_group: bool = False, +) -> Pipeline | FeatureUnion: + if representation is None: + shared_kwargs = { + "task": config.task, + "target_aware": config.target_aware, + "output_dim": config.output_dim, + "adaptive": config.adaptive, + "min_output_dim": config.min_output_dim if config.adaptive else None, + "max_output_dim": config.max_output_dim if config.adaptive else None, + "degree": config.degree, + "placement_strategy": config.placement_strategy, + **config.seed_kwargs, + } + else: + if not isinstance(representation, RepresentationConfig): + raise invalid_param_error( + "create_transformer", "representation", representation, "must be a RepresentationConfig or None" + ) + representation = _normalize_representation_config( + representation, is_numerical=is_numerical, path="create_transformer.representation", is_group=is_group + ) + resolved_method = config.resolve_numerical(method) if is_numerical else config.resolve_categorical(method) + if resolved_method != representation.method: + raise invalid_param_error( + "create_transformer", + "representation.method", + representation.method, + f"must match the selected method {resolved_method!r}", + ) + method = representation.method + settings = representation.to_dict() + shared_kwargs = {key: value for key, value in settings.items() if key not in {"method", "params", "name"}} + shared_kwargs.update(settings["params"]) + + known = ( + method in TRANSFORMER_REGISTRY + if is_group + else (method in NUMERICAL_METHODS if is_numerical else method in CATEGORICAL_METHODS) + ) if known: spec = get_spec(method) - if spec.requires_target and not config.target_aware: + if representation is None and spec.requires_target and not config.target_aware: raise IncompatibleParamsError( f"method {method!r} is always target-aware and requires target_aware=True " f"with placement_strategy in {{'cart', 'lightgbm'}}; got target_aware=False." ) plan = config.imputation_plan(is_numerical=is_numerical) - if is_numerical: + if is_group: + steps = _get_numerical_transformer_steps( + method, + plan["add_imputer"], + plan["strategy"], + None, + False, + config.scaling, + shared_kwargs, + is_group=True, + ) + elif is_numerical: steps = get_numerical_transformer_steps( method=method, - task=config.task, - target_aware=config.target_aware, add_imputer=plan["add_imputer"], imputer_strategy=plan["strategy"], - output_dim=config.output_dim, - adaptive=config.adaptive, - min_output_dim=config.min_output_dim if config.adaptive else None, - max_output_dim=config.max_output_dim if config.adaptive else None, - degree=config.degree, scaling=config.scaling, - placement_strategy=config.placement_strategy, - **config.seed_kwargs, + **shared_kwargs, ) else: constructor_kwargs = {} if known: - shared_kwargs = { - "task": config.task, - "target_aware": config.target_aware, - "output_dim": config.output_dim, - "adaptive": config.adaptive, - "min_output_dim": config.min_output_dim if config.adaptive else None, - "max_output_dim": config.max_output_dim if config.adaptive else None, - "degree": config.degree, - "placement_strategy": config.placement_strategy, - **config.seed_kwargs, - } constructor_kwargs = _filter_kwargs(spec.allowed_args, shared_kwargs) constructor_kwargs.update(_placement_kwargs(spec, shared_kwargs)) steps = get_categorical_transformer_steps( @@ -387,24 +457,57 @@ def build_column_transformer( *, sparse_threshold: float = 0.3, ) -> ColumnTransformer: - """Assemble the per-column pipelines into the final ColumnTransformer. + """Assemble single-column and declared group pipelines into a ColumnTransformer. Numerical steps are prefixed ``num_`` and categorical steps ``cat_`` to match the block names the Preprocessor exposes (see :func:`_step_names` for labels that cannot be embedded in a step name); untransformed columns pass through via - ``remainder="passthrough"``. Each step selects its column by + ``remainder="passthrough"``. Single-column steps select their column by the label's string form: scikit-learn reads an integer selector as a *position*, so the Preprocessor fits and transforms the ColumnTransformer on a frame whose labels are strings (see :func:`~pretab.compose.feature_detection.with_string_labels`). + Groups select ordered lists of those internal labels and own their sources + exclusively. Blocks are ordered as numerical singles, declared groups, then + categorical singles. Group steps use ``group_``; a collision with an + input label or single-column block key is rejected before construction. """ - blocks = [("num", feature) for feature in numerical_features] - blocks += [("cat", feature) for feature in categorical_features] + groups = {group.name: group for group in config.feature_groups} + claimed = {label for group in config.feature_groups for label in group.columns} + blocks = [("num", feature) for feature in numerical_features if feature not in claimed] + blocks += [("group", group.name) for group in config.feature_groups] + blocks += [("cat", feature) for feature in categorical_features if feature not in claimed] + if groups: + raw_labels = {str(label) for label in [*numerical_features, *categorical_features]} + single_names = {f"{kind}_{feature}" for kind, feature in blocks if kind != "group"} + for group in config.feature_groups: + public_name = f"group_{group.name}" + if public_name in raw_labels or public_name in single_names: + raise invalid_param_error( + f"feature_groups[{group.name!r}]", + "name", + group.name, + f"public block key {public_name!r} conflicts with an input label or single-column block", + ) transformers = [] for (kind, feature), name in zip(blocks, _step_names(blocks), strict=True): + if kind == "group": + group = groups[feature] + representation = config.group_representation_for(group) + pipeline = _create_transformer( + representation.method, is_numerical=True, config=config, representation=representation, is_group=True + ) + transformers.append((name, pipeline, [str(label) for label in group.columns])) + continue is_numerical = kind == "num" method = config.method_for(feature, is_numerical=is_numerical) - pipeline = create_transformer(method, is_numerical=is_numerical, config=config) + if isinstance(config.feature_preprocessing.get(feature, method), str): + pipeline = create_transformer(method, is_numerical=is_numerical, config=config) + else: + representation = config.representation_for(feature, is_numerical=is_numerical) + pipeline = create_transformer( + method, is_numerical=is_numerical, config=config, representation=representation + ) transformers.append((name, pipeline, [str(feature)])) return ColumnTransformer( transformers=transformers, diff --git a/pretab/compose/inspection.py b/pretab/compose/inspection.py index f6ca0cf..3866c4c 100644 --- a/pretab/compose/inspection.py +++ b/pretab/compose/inspection.py @@ -8,20 +8,19 @@ """ import copy +from collections.abc import Iterator +from dataclasses import dataclass from typing import Any, cast +from urllib.parse import quote import numpy as np -import pandas as pd from sklearn.base import clone from sklearn.pipeline import FeatureUnion, Pipeline from ..core._typing import TransformerLike -from ..core.logging import get_logger from ..core.representation import FeatureLineage from .registry import TRANSFORMER_REGISTRY -logger = get_logger(__name__) - __all__ = [ "block_name", "block_uses_target", @@ -58,6 +57,34 @@ def block_name(step_name, columns): return step_name if block is None else f"{block[0]}_{block[1]}" +@dataclass(frozen=True) +class _FittedBlock: + """Read-only block metadata retaining the fitted transformer and selector references.""" + + step_name: str + transformer: Any + columns: Any + _column_transformer: Any + + @property + def public_name(self) -> str: + return block_name(self.step_name, self.columns) + + @property + def group_id(self) -> str | None: + return self.step_name if self.step_name.startswith("group_") else None + + @property + def span(self) -> slice: + return self._column_transformer.output_indices_[self.step_name] + + +def _iter_fitted_blocks(column_transformer) -> Iterator[_FittedBlock]: + """Yield every fitted block in order, leaving filtering and span access to callers.""" + for name, transformer, columns in column_transformer.transformers_: + yield _FittedBlock(name, transformer, columns, column_transformer) + + def get_output_slices(column_transformer): """Return ordered ``(name, start, width)`` spans for each output block. @@ -67,16 +94,16 @@ def get_output_slices(column_transformer): """ indices = column_transformer.output_indices_ slices = [] - for name, transformer, columns in column_transformer.transformers_: - if transformer == "drop": + for block in _iter_fitted_blocks(column_transformer): + if block.transformer == "drop" or block.step_name not in indices: continue - span = indices.get(name) + span = block.span if span is None: continue width = span.stop - span.start if width == 0: continue - slices.append((block_name(name, columns), span.start, width)) + slices.append((block.public_name, span.start, width)) return slices @@ -97,7 +124,8 @@ def feature_names_out(column_transformer, input_features=None): rename = {str(label): str(name) for label, name in zip(fitted_labels, input_features, strict=True)} raw_names = [] - for name, transformer, columns in column_transformer.transformers_: + for block in _iter_fitted_blocks(column_transformer): + name, transformer, columns = block.step_name, block.transformer, block.columns if transformer == "drop" or len(columns) == 0: continue labels = [rename[str(column)] for column in columns] @@ -145,13 +173,20 @@ def clean_feature_names(column_transformer, names, *, rename=None): column labels to the input feature names ``names`` were built from (see :func:`feature_names_out`); a step of a renamed column is then reported under the new name, e.g. ``num_feature_0`` as ``num_age``. + Group names retain their public block key and prepend percent-escaped source + labels in declared order to the leaf output name. """ rename = rename or {} - step_to_columns = { - name: [rename.get(str(column), column) for column in columns] - for name, _transformer, columns in column_transformer.transformers_ - if name != "remainder" and len(columns) == 1 - } + step_to_columns = {} + group_ids = set() + for block in _iter_fitted_blocks(column_transformer): + if block.step_name == "remainder": + continue + if block.group_id is not None: + group_ids.add(block.group_id) + elif len(block.columns) != 1: + continue + step_to_columns[block.step_name] = [rename.get(str(column), column) for column in block.columns] cleaned = [] for raw in names: raw = str(raw) @@ -160,6 +195,10 @@ def clean_feature_names(column_transformer, names, *, rename=None): if not sep or columns is None: cleaned.append(raw) continue + if step_name in group_ids: + sources = "+".join(quote(str(column), safe="") for column in columns) + cleaned.append(f"{step_name}__{sources}__{inner_name}") + continue block = _block(step_name, columns) if block is not None: kind_prefix, feature = block @@ -185,19 +224,6 @@ def _separate_state_branches(transformer): return branches["representation"], branches["missing"] -def _probe_input(step, value): - """Return a one-row probe input for measuring a fitted step's output width. - - A step fitted directly on the ColumnTransformer's DataFrame column records - ``feature_names_in_`` and, like scikit-learn, warns on input without feature - names, so its probe is a DataFrame carrying the fitted names. - """ - names = getattr(step, "feature_names_in_", None) - if names is None: - return np.full((1, 1), value) - return pd.DataFrame(np.full((1, len(names)), value), columns=names) - - def representation_leaf(transformer): """Return the last step of a fitted per-column block's representation. @@ -214,6 +240,8 @@ def representation_leaf(transformer): def build_feature_info(column_transformer, *, embeddings, embedding_dimensions): """Collect per-feature metadata (preprocessing, dimension, categories). + Dimensions come from the fitted output spans without evaluating transformers. + Category counts describe fitted vocabularies, not emitted widths. Returns a ``(numerical_info, categorical_info, embedding_info)`` tuple of dicts keyed by feature name. """ @@ -229,114 +257,58 @@ def build_feature_info(column_transformer, *, embeddings, embedding_dimensions): else {} ) - for ( - name, - transformer_pipeline, - columns, - ) in column_transformer.transformers_: + for block in _iter_fitted_blocks(column_transformer): + name, transformer_pipeline, columns = block.step_name, block.transformer, block.columns + if transformer_pipeline == "drop" or len(columns) == 0: + continue + span = block.span + dimension = span.stop - span.start separate_state = _separate_state_branches(transformer_pipeline) if separate_state is not None: representation_pipeline, _missing_indicator = separate_state steps = [step[0] for step in representation_pipeline.steps] preprocessing_type = f"representation({' -> '.join(steps)}) + missing" - span = column_transformer.output_indices_.get(name) - separate_state_dimension = None if span is None else span.stop - span.start else: representation_pipeline = transformer_pipeline - steps = [step[0] for step in representation_pipeline.steps] + steps = ( + [step[0] for step in representation_pipeline.steps] + if isinstance(representation_pipeline, Pipeline) + else [type(representation_pipeline).__name__] + ) preprocessing_type = " -> ".join(steps) - separate_state_dimension = None + group_id = block.group_id + if group_id is not None: + numerical_feature_info[group_id] = { + "preprocessing": preprocessing_type, + "dimension": dimension, + "categories": None, + "group": group_id.removeprefix("group_"), + "source_features": tuple(columns), + } + continue for feature_name in columns: - dimension = None categories = None - - if "discretizer" in steps or any( - step in steps - for step in [ - "standardization", - "minmax", - "quantile", - "polynomial", - "splines", - "box-cox", - ] - ): - last_step = representation_pipeline.steps[-1][1] - if hasattr(last_step, "transform"): - dummy_input = _probe_input(last_step, 1e-05) - try: - transformed_feature = last_step.transform(dummy_input) - dimension = transformed_feature.shape[1] - except (ValueError, TypeError, AttributeError, IndexError) as exc: - logger.debug( - "Could not introspect output width of %r: %s", - feature_name, - exc, - ) - dimension = None - if separate_state_dimension is not None: - dimension = separate_state_dimension - numerical_feature_info[feature_name] = { - "preprocessing": preprocessing_type, - "dimension": dimension, - "categories": None, - } - - elif "continuous_ordinal" in steps: + if "continuous_ordinal" in steps: step = representation_pipeline.named_steps["continuous_ordinal"] position = columns.index(feature_name) # An encoder that received no column (a 0-width block) has no mapping. has_mapping = position < len(step.mapping_) categories = len(step.mapping_[position]) if has_mapping else None - dimension = separate_state_dimension if separate_state_dimension is not None else int(has_mapping) - categorical_feature_info[feature_name] = { - "preprocessing": preprocessing_type, - "dimension": dimension, - "categories": categories, - } - elif "onehot" in steps: step = representation_pipeline.named_steps["onehot"] if hasattr(step, "categories_"): categories = sum(len(cat) for cat in step.categories_) - dimension = categories - if separate_state_dimension is not None: - dimension = separate_state_dimension - categorical_feature_info[feature_name] = { - "preprocessing": preprocessing_type, - "dimension": dimension, - "categories": categories, - } - - else: - last_step = representation_pipeline.steps[-1][1] - if hasattr(last_step, "transform"): - dummy_input = _probe_input(last_step, 0.0) - try: - transformed_feature = last_step.transform(dummy_input) - dimension = transformed_feature.shape[1] - except (ValueError, TypeError, AttributeError, IndexError) as exc: - logger.debug( - "Could not introspect output width of %r: %s", - feature_name, - exc, - ) - dimension = None - if separate_state_dimension is not None: - dimension = separate_state_dimension - if name.startswith("cat_"): - categorical_feature_info[feature_name] = { - "preprocessing": preprocessing_type, - "dimension": dimension, - "categories": None, - } - else: - numerical_feature_info[feature_name] = { - "preprocessing": preprocessing_type, - "dimension": dimension, - "categories": None, - } + feature_info = ( + categorical_feature_info + if name.startswith("cat_") or "continuous_ordinal" in steps or "onehot" in steps + else numerical_feature_info + ) + feature_info[feature_name] = { + "preprocessing": preprocessing_type, + "dimension": dimension, + "categories": categories, + } return numerical_feature_info, categorical_feature_info, embedding_feature_info @@ -365,6 +337,33 @@ def build_transformer_summary(numerical_info, categorical_info, embedding_info): return lines +def _build_effective_settings_summary(fit_config: dict | None) -> list[str]: + """Render settings recorded for declared overrides and groups at fit time.""" + if fit_config is None: + return ["Fit-time effective settings unavailable (not recorded)."] + + def format_settings(settings): + fields = [ + f"{key}={value!r}" + for key, value in settings.items() + if key != "params" and not (key == "name" and value is None) + ] + fields.extend(f"{key}={value!r}" for key, value in settings.get("params", {}).items()) + return ", ".join(fields) + + rows = [ + f"feature {feature!r}: {format_settings(settings)}" + for feature, settings in (fit_config["feature_preprocessing"] or {}).items() + ] + rows.extend( + f"group_{group['name']} (sources={group['columns']!r}): {format_settings(group['representation'])}" + for group in fit_config["feature_groups"] or [] + ) + if not rows: + return ["Fit-time effective settings: no per-feature overrides or groups recorded."] + return ["Fit-time effective settings (declared overrides and groups; fitted dimensions are shown above):", *rows] + + # Mapping from pipeline step name to (family, component) for representation-bearing # scikit-learn steps that do not expose ``get_representation_spec``. _STEP_FAMILY = { @@ -429,8 +428,23 @@ def _resolve_block_representation(pipeline, columns): return _locate_block_representation(pipeline, columns)[1] +def _block_uses_task(transformer) -> bool: + """Check a constructed block for a target consumer configured with a task.""" + separate_state = _separate_state_branches(transformer) + representation = separate_state[0] if separate_state is not None else transformer + for name, step in representation.steps: + spec = TRANSFORMER_REGISTRY.get(name) + if spec is None or not isinstance(step, spec.transformer_cls) or getattr(step, "task", None) is None: + continue + if spec.target_usage == "required" or ( + spec.target_usage == "optional" and getattr(step, "target_aware", False) + ): + return True + return False + + def block_uses_target(transformer) -> bool: - """Whether a fitted per-column block's representation consumed the target ``y``. + """Whether a fitted single-feature or joint block's representation consumed ``y``. For a separate-state / missing-indicator union the representation branch decides; helper steps such as imputers and scalers never use the target. The spec is read without @@ -442,7 +456,7 @@ def block_uses_target(transformer) -> bool: def refit_block_representation(transformer, X, y) -> TransformerLike: - """Return a copy of a fitted per-column block whose representation is refit on ``(X, y)``. + """Copy a fitted block and refit its representation on its ordered inputs and ``y``. Only the representation step and the steps after it are refit. The steps before it (the imputer with its missing indicator, scalers) never use the @@ -494,13 +508,17 @@ def build_feature_lineage(column_transformer): output_indices = column_transformer.output_indices_ feature_names_in = getattr(column_transformer, "feature_names_in_", None) records = [] - for name, transformer, columns in column_transformer.transformers_: - span = output_indices.get(name) + for block in _iter_fitted_blocks(column_transformer): + name, transformer, columns = block.step_name, block.transformer, block.columns + if name not in output_indices: + continue + span = block.span if span is None: continue width = span.stop - span.start if width == 0: continue + group_id = block.group_id if transformer == "passthrough" or name == "remainder": for offset in range(width): index = span.start + offset @@ -543,20 +561,26 @@ def build_feature_lineage(column_transformer): component_index=offset, uses_target=uses_target, is_interaction=is_interaction, + group_id=group_id, ) ) + indicator = missing_indicator.steps[-1][1] if isinstance(missing_indicator, Pipeline) else missing_indicator + missing_sources = getattr(indicator, "features_", range(len(columns))) for offset in range(missing_width): index = span.start + representation_width + offset records.append( FeatureLineage( output_feature=output_names[index], output_index=index, - source_features=source_features, + source_features=(str(columns[missing_sources[offset]]),) + if group_id is not None + else source_features, family="missing_state", component="indicator", component_index=offset, uses_target=False, is_interaction=False, + group_id=group_id, ) ) continue @@ -574,6 +598,7 @@ def build_feature_lineage(column_transformer): component_index=offset, uses_target=uses_target, is_interaction=is_interaction, + group_id=group_id, ) ) records.sort(key=lambda record: record.output_index) diff --git a/pretab/compose/output.py b/pretab/compose/output.py index 1868cf5..6974324 100644 --- a/pretab/compose/output.py +++ b/pretab/compose/output.py @@ -137,6 +137,17 @@ def compute_output_report(array, output_format, *, threshold=_SPARSE_AUTO_THRESH return fmt, report +def _require_polars(): + try: + import polars as pl # type: ignore + except ImportError as exc: + raise OptionalDependencyError( + "set_output(transform='polars') requires the optional 'polars' package. " + "Install it with `pip install polars`." + ) from exc + return pl + + def to_dataframe_output(array, columns, container, *, index=None): """Wrap a dense stacked array in a pandas or polars DataFrame. @@ -167,13 +178,7 @@ def to_dataframe_output(array, columns, container, *, index=None): import pandas as pd return pd.DataFrame(array, index=index, columns=pd.Index(columns)) - try: - import polars as pl # type: ignore - except ImportError as exc: # pragma: no cover - exercised only without polars - raise OptionalDependencyError( - "set_output(transform='polars') requires the optional 'polars' package. " - "Install it with `pip install polars`." - ) from exc + pl = _require_polars() return pl.from_numpy(array, schema=columns) diff --git a/pretab/compose/registry.py b/pretab/compose/registry.py index 22d168b..812fa5c 100644 --- a/pretab/compose/registry.py +++ b/pretab/compose/registry.py @@ -126,6 +126,17 @@ class TransformerSpec: sparse_output : bool Whether the method can emit a sparse matrix (e.g. one-hot). Surfaced through :func:`pretab.list_representations`. + group_compatible : bool + Whether the method declares support for explicit column groups. + Independent of single-column ``preprocessor_compatible`` selection. + min_arity : int + Minimum declared group size, relevant only when ``group_compatible`` + is true. Does not constrain standalone transformer input dimensions. + max_arity : int or None + Maximum declared group size, or ``None`` for no declared upper bound. + Relevant only when ``group_compatible`` is true. + typed_penalty : bool + Whether the method exposes validated penalty metadata aligned to its output. """ name: str @@ -140,6 +151,10 @@ class TransformerSpec: optional_dependency: str | None = None periodic: bool = False sparse_output: bool = False + group_compatible: bool = False + min_arity: int = 1 + max_arity: int | None = 1 + typed_penalty: bool = False @property def is_numerical(self) -> bool: @@ -264,12 +279,14 @@ def _spec(name, cls, allowed_args=(), **kwargs): "max_output_dim", "random_state", ), + typed_penalty=True, **_BOTH_MODE, ), _spec( "naturalspline", NaturalCubicSplineTransformer, ("output_dim", "include_bias", "task", "adaptive", "min_output_dim", "max_output_dim", "random_state"), + typed_penalty=True, **_BOTH_MODE, ), # --- numerical: penalized splines (equally-spaced knots, unsupervised only) --- @@ -278,6 +295,7 @@ def _spec(name, cls, allowed_args=(), **kwargs): PSplineTransformer, ("output_dim", "degree", "diff_order"), placement_strategies=_UNIFORM_ONLY, + typed_penalty=True, ), _spec( "tensorspline", @@ -286,6 +304,10 @@ def _spec(name, cls, allowed_args=(), **kwargs): arity="multivariate", placement_strategies=_UNSUPERVISED_STRATEGIES, preprocessor_compatible=False, + group_compatible=True, + min_arity=2, + max_arity=None, + typed_penalty=True, ), # --- numerical: kernel-based thin-plate spline (knot-free, multivariate) --- _spec( @@ -294,6 +316,9 @@ def _spec(name, cls, allowed_args=(), **kwargs): ("n_components", "landmark_strategy", "rank_strategy", "random_state"), arity="multivariate", preprocessor_compatible=False, + group_compatible=True, + min_arity=2, + max_arity=None, ), # --- numerical: kernel-approximation feature maps (multivariate, standalone) --- _spec( @@ -315,25 +340,43 @@ def _spec(name, cls, allowed_args=(), **kwargs): "bspline", BSplineTransformer, ("degree", "task", "adaptive", "min_output_dim", "max_output_dim", "random_state"), + typed_penalty=True, **_BOTH_MODE, ), _spec( "mspline", MSplineTransformer, ("degree", "task", "adaptive", "min_output_dim", "max_output_dim", "random_state"), + typed_penalty=True, **_BOTH_MODE, ), _spec( "ispline", ISplineTransformer, ("degree", "task", "adaptive", "min_output_dim", "max_output_dim", "random_state"), + typed_penalty=True, **_BOTH_MODE, ), # --- numerical / categorical: passthrough --- _spec("none", NoTransformer, feature_kind=frozenset({NUMERICAL, CATEGORICAL})), # --- categorical-only methods --- _spec("int", ContinuousOrdinalTransformer, feature_kind=frozenset({CATEGORICAL})), - _spec("one-hot", OneHotEncoder, feature_kind=frozenset({CATEGORICAL}), sparse_output=True), + _spec( + "one-hot", + OneHotEncoder, + ( + "categories", + "drop", + "sparse_output", + "dtype", + "handle_unknown", + "min_frequency", + "max_categories", + "feature_name_combiner", + ), + feature_kind=frozenset({CATEGORICAL}), + sparse_output=True, + ), _spec("onehot_from_ordinal", OneHotFromOrdinalTransformer, feature_kind=frozenset({CATEGORICAL})), _spec( "pretrained", diff --git a/pretab/compose/search.py b/pretab/compose/search.py index a3c9020..c1dd4f9 100644 --- a/pretab/compose/search.py +++ b/pretab/compose/search.py @@ -13,7 +13,7 @@ from typing import cast import numpy as np -from sklearn.base import BaseEstimator, clone, is_classifier +from sklearn.base import BaseEstimator, clone, is_classifier, is_regressor from sklearn.metrics import check_scoring from sklearn.model_selection import BaseCrossValidator, check_cv from sklearn.utils import get_tags @@ -21,7 +21,14 @@ from sklearn.utils.validation import _check_method_params, check_is_fitted from ..core._typing import PredictorLike -from ..core.validation import is_polars_frame, polars_to_pandas +from ..core.validation import ( + _check_task_target_once, + _task_target_scope, + _TaskValidationMode, + _validate_task_validation, + is_polars_frame, + polars_to_pandas, +) from ..exceptions import InvalidParamError from ..preprocessor import Preprocessor @@ -101,13 +108,28 @@ class RepresentationSearchCV(BaseEstimator): string column names. """ - def __init__(self, estimator, methods, *, cv=5, scoring=None, preprocessor_params=None, random_state=None): + def __init__( + self, + estimator, + methods, + *, + cv=5, + scoring=None, + preprocessor_params=None, + random_state=None, + task_validation="off", + ): self.estimator = estimator self.methods = methods self.cv = cv self.scoring = scoring self.preprocessor_params = preprocessor_params self.random_state = random_state + self.task_validation = task_validation + + def __setstate__(self, state): + super().__setstate__(state) + self.__dict__.setdefault("task_validation", "off") def _make_preprocessor(self, method): """Build a Preprocessor for ``method`` with the shared parameters. @@ -121,6 +143,23 @@ def _make_preprocessor(self, method): params.setdefault("task", "classification") return Preprocessor(numerical_method=method, **params) + def _preflight_task_targets(self, X, y, methods, *, mode: _TaskValidationMode, classifier, n_samples): + inner_mode = dict(self.preprocessor_params or {}).get("task_validation", "off") + if mode == "off" and isinstance(inner_mode, str) and inner_mode == "off": + return + owner = type(self).__name__ + for method in methods: + self._make_preprocessor(method)._preflight_task_target(X, y, outer_mode=mode, owner=owner) + if mode != "off" and (classifier or is_regressor(self.estimator)): + _check_task_target_once( + y, + task="classification" if classifier else "regression", + mode=mode, + estimator=owner, + role="representation search", + n_samples=n_samples, + ) + def fit(self, X, y=None, *, groups=None, **fit_params): """Search over ``methods`` and refit the best representation on all data. @@ -157,6 +196,7 @@ def fit(self, X, y=None, *, groups=None, **fit_params): raise InvalidParamError("methods must be a non-empty sequence of numerical methods.") if y is None: raise InvalidParamError("RepresentationSearchCV requires y at fit time; got y=None.") + mode = _validate_task_validation(self.task_validation, type(self).__name__) y_arr = np.asarray(y).ravel() if is_polars_frame(X): # Converted once, so every fold's rows carry the dtypes of the whole frame, @@ -166,7 +206,10 @@ def fit(self, X, y=None, *, groups=None, **fit_params): # As in scikit-learn's searches: per-sample fit params are made indexable # so each fold can take its training rows. fit_params = _check_method_params(X, params=fit_params) - cv = cast(BaseCrossValidator, check_cv(self.cv, y_arr, classifier=is_classifier(self.estimator))) + classifier = is_classifier(self.estimator) + cv = cast(BaseCrossValidator, check_cv(self.cv, y_arr, classifier=classifier)) + with _task_target_scope(y) as receipts: + self._preflight_task_targets(X, y, methods, mode=mode, classifier=classifier, n_samples=n_samples) # Reuse the same held-out rows for every candidate, including splitters # whose random state advances on each call to split(). splits = list(cv.split(np.zeros(n_samples), y_arr, groups)) @@ -179,7 +222,9 @@ def fit(self, X, y=None, *, groups=None, **fit_params): for train_idx, test_idx in splits: pre = self._make_preprocessor(method) est = cast(PredictorLike, clone(self.estimator)) - x_train = pre.fit_transform(_row_subset(X, train_idx), y_arr[train_idx], return_array=True) + train_y = y_arr[train_idx] + with _task_target_scope(train_y, receipts.copy()): + x_train = pre.fit_transform(_row_subset(X, train_idx), train_y, return_array=True) fold_params = _check_method_params(X, params=fit_params, indices=train_idx) est.fit(x_train, y_arr[train_idx], **fold_params) scorer = cast("Callable[..., float]", check_scoring(est, scoring=self.scoring)) @@ -195,7 +240,8 @@ def fit(self, X, y=None, *, groups=None, **fit_params): self.best_method_ = best_method self.best_score_ = best_score self.best_preprocessor_ = self._make_preprocessor(best_method) - x_all = self.best_preprocessor_.fit_transform(X, y_arr, return_array=True) + with _task_target_scope(y_arr, receipts.copy()): + x_all = self.best_preprocessor_.fit_transform(X, y_arr, return_array=True) self.best_estimator_ = cast(PredictorLike, clone(self.estimator)).fit(x_all, y_arr, **fit_params) self.n_features_in_ = self.best_preprocessor_.n_features_in_ # scikit-learn convention: feature names are recorded only for input whose diff --git a/pretab/compose/serialize.py b/pretab/compose/serialize.py index 0c7a424..796a068 100644 --- a/pretab/compose/serialize.py +++ b/pretab/compose/serialize.py @@ -23,20 +23,28 @@ import importlib import math from collections import UserList +from itertools import pairwise from typing import Any, cast import numpy as np from sklearn.base import BaseEstimator +from sklearn.pipeline import FeatureUnion, Pipeline +from sklearn.preprocessing import OneHotEncoder from sklearn.utils.validation import check_is_fitted from .._version import __version__ as _PRETAB_VERSION from ..core.parameters import UNSET from ..core.policy import RepresentationPolicy from ..core.representation import FeatureLineage, RepresentationSpec -from ..exceptions import PretabSerializationError +from ..exceptions import PretabConfigError, PretabSerializationError +from ..expansion.spline.p_spline import PSplineTransformer +from ..expansion.spline.penalty import PenaltySpec, _copy_provenance from ..placement.base import PlacementResult -from .inspection import representation_leaf -from .registry import TransformerSpec +from ..preprocessing.floats import NoTransformer, ToFloatTransformer +from .config import FeatureGroup, RepresentationConfig +from .inspection import _iter_fitted_blocks, representation_leaf +from .output import _require_polars +from .registry import TRANSFORMER_REGISTRY, TransformerSpec SCHEMA_VERSION = 1 @@ -55,7 +63,16 @@ # let a spec construct an arbitrary sklearn/numpy/scipy dataclass with # attacker-controlled fields. _ALLOWED_DATACLASSES = frozenset( - {RepresentationPolicy, RepresentationSpec, FeatureLineage, PlacementResult, TransformerSpec} + { + RepresentationPolicy, + RepresentationSpec, + FeatureLineage, + PlacementResult, + TransformerSpec, + RepresentationConfig, + FeatureGroup, + PenaltySpec, + } ) @@ -149,7 +166,33 @@ def _encode(obj): if isinstance(obj, list): return [_encode(v) for v in obj] if isinstance(obj, BaseEstimator): + cls = type(obj) + if not _module_allowed(cls.__module__): + raise PretabSerializationError( + f"Cannot serialize estimator {cls.__module__}.{cls.__qualname__} in a schema-v1 spec. " + "Registration does not enable spec persistence. Use a supported built-in representation for JSON " + "replay, or a trusted pickle or joblib checkpoint in a matching environment if all components support it." + ) return {"__estimator__": {"class": _qualname(obj), "state": _encode_mapping(vars(obj))}} + if type(obj) is RepresentationConfig: + fields = {key: _encode(value) for key, value in obj.to_dict().items()} + return {"__dataclass__": {"class": _qualname(obj), "fields": fields}} + if type(obj) is PenaltySpec: + fields = _encode_mapping( + { + "matrix": obj.matrix, + "kind": obj.kind, + "order": obj.order, + "axis": obj.axis, + "coordinate_system": obj.coordinate_system, + "coefficient_names": obj.coefficient_names, + "coefficient_indices": obj.coefficient_indices, + "atol": obj.atol, + "rtol": obj.rtol, + "provenance": _copy_provenance(obj.provenance), + } + ) + return {"__dataclass__": {"class": _qualname(obj), "fields": fields}} if dataclasses.is_dataclass(obj) and not isinstance(obj, type): fields = {f.name: _encode(getattr(obj, f.name)) for f in dataclasses.fields(obj)} return {"__dataclass__": {"class": _qualname(obj), "fields": fields}} @@ -163,6 +206,55 @@ def _encode_mapping(mapping: dict) -> dict: return {str(k): _encode(v) for k, v in mapping.items()} +def _canonicalize_feature_block(transformer: dict, *, structured: bool) -> None: + """Keep the encoded representation leaf compatible with the legacy fingerprint.""" + pipeline = transformer["__estimator__"]["state"] + if "transformer_list" in pipeline: + branches = dict(item["__tuple__"] for item in pipeline["transformer_list"]) + pipeline = branches["representation"]["__estimator__"]["state"] + method, leaf = pipeline["steps"][-1]["__tuple__"] + state = leaf["__estimator__"]["state"] + if method == "pspline": + fitted = state.get("_penalty_fit_") + if fitted == {"__tuple__": [state.get("diff_order"), state.get("include_bias")]}: + state.pop("_penalty_fit_") + if not structured: + return + spec = TRANSFORMER_REGISTRY.get(method) + if spec is None or not spec.supports_adaptive_resolution: + return + if state.get("adaptive") is False: + for field in ("min_output_dim", "max_output_dim"): + if field in spec.allowed_args and state.get(field) == {"__unset__": True}: + state[field] = None + + +def _canonicalize_feature_fingerprint(state: dict, requests) -> None: + """Normalize single-feature requests and blocks without changing replay state.""" + structured = set() + if isinstance(requests, dict): + for (feature, request), pair in zip(requests.items(), state["feature_preprocessing"]["__dict__"], strict=True): + if isinstance(request, dict): + try: + request = RepresentationConfig.from_dict(request) + except PretabConfigError: + continue + if type(request) is RepresentationConfig: + settings = request.to_dict() + method_only = ( + settings.keys() == {"method", "params", "name"} and not request.params and request.name is None + ) + pair[1] = request.method if method_only else settings + structured.add(str(feature)) + graph = state.get("column_transformer_") + if isinstance(graph, dict): + for field in ("transformers", "transformers_"): + for block in graph["__estimator__"]["state"][field]: + name, transformer, columns = block["__tuple__"] + if name.startswith(("num_", "cat_")) and len(columns) == 1 and isinstance(transformer, dict): + _canonicalize_feature_block(transformer, structured=columns[0] in structured) + + def _json_safe(obj): """Best-effort readable encoding used for the declarative ``params`` block. @@ -286,7 +378,37 @@ def _library_versions() -> dict: } -def _representation_summary(preprocessor) -> list: +def _penalty_summaries(leaf) -> list[dict]: + scope = next( + ( + spec.arity + for spec in TRANSFORMER_REGISTRY.values() + if spec.typed_penalty and spec.transformer_cls is type(leaf) + ), + None, + ) + if scope is None: + return [] + if scope == "multivariate": + penalties = leaf.get_penalty_specs() + else: + if isinstance(leaf, PSplineTransformer) and leaf._has_legacy_only_penalty(): + return [] + penalties = (leaf.get_penalty_spec(feature_index=index) for index in range(leaf.n_features_in_)) + return [penalty.to_summary() for penalty in penalties] + + +def _group_layout(block, columns: list[str]) -> dict: + span = block.span + return { + "columns": columns, + "group_id": block.group_id, + "dimension": span.stop - span.start, + "output_slice": [span.start, span.stop], + } + + +def _representation_summary(preprocessor, *, include_penalties: bool = False) -> list: """Declarative per-representation summary (family/columns/locations). One entry per block whose representation ends in a PreTab transformer, built from its @@ -296,43 +418,60 @@ def _representation_summary(preprocessor) -> list: :func:`~pretab.compose.inspection.representation_leaf`), not the union itself. Blocks whose representation ends in a step without ``get_representation_spec`` (scikit-learn scalers and encoders, embeddings) - have no entry. The steps are fitted, so a spec that fails to build is a bug: + have no entry. Explicit groups also carry their public identity, actual full + block dimension and half-open fitted output slice, including raw indicators. + The steps are fitted, so a spec that fails to build is a bug: its error propagates instead of silently dropping the entry. """ summary: list = [] column_transformer = getattr(preprocessor, "column_transformer_", None) if column_transformer is None: return summary - for name, transformer, columns in column_transformer.transformers_: - if name == "remainder": + for block in _iter_fitted_blocks(column_transformer): + if block.step_name == "remainder": continue - leaf = representation_leaf(transformer) + leaf = representation_leaf(block.transformer) spec_fn = getattr(leaf, "get_representation_spec", None) if spec_fn is None: continue - block_columns = [str(col) for col in columns] + block_columns = [str(col) for col in block.columns] # A leaf with more inputs than its block has columns (one fitted behind # the imputer's built-in missing indicator, add_missing_indicator=True) # names its own inputs. fits_block = getattr(leaf, "n_features_in_", len(block_columns)) == len(block_columns) entry = spec_fn(input_features=block_columns if fits_block else None).to_dict() entry["columns"] = block_columns + if block.group_id is not None: + entry.update(_group_layout(block, block_columns)) + if include_penalties and (penalties := _penalty_summaries(leaf)): + entry["penalties"] = penalties summary.append(entry) return summary -def preprocessor_to_spec(preprocessor) -> dict: +def preprocessor_to_spec(preprocessor, *, include_fitted_metadata: bool = True) -> dict: """Serialize a fitted preprocessor into a portable, versioned spec dictionary.""" check_is_fitted(preprocessor) - return { + state = vars(preprocessor) + if not include_fitted_metadata: + state = {key: value for key, value in state.items() if key != "_fit_config_"} + has_fit_config = "_fit_config_" in state + spec = { "schema_version": SCHEMA_VERSION, "pretab_version": _PRETAB_VERSION, "library_versions": _library_versions(), "params": _json_safe(preprocessor.get_params(deep=False)), "feature_names_out": [str(name) for name in preprocessor.get_feature_names_out()], - "representations": _representation_summary(preprocessor), - "state": _encode_mapping(vars(preprocessor)), + "representations": _representation_summary(preprocessor, include_penalties=has_fit_config), + "state": _encode_mapping(state), } + if include_fitted_metadata: + if has_fit_config: + spec["resolved_config"] = _json_safe(state["_fit_config_"]) + spec["output_dims"] = _json_safe(preprocessor.output_dims_) + spec["total_output_dim"] = preprocessor.total_output_dim_ + spec["feature_lineage"] = _json_safe([item.to_dict() for item in preprocessor.get_feature_lineage()]) + return spec def check_spec_schema(data: dict) -> None: @@ -346,6 +485,69 @@ def check_spec_schema(data: dict) -> None: ) +def _validate_group_layout(representations, column_transformer) -> None: + if not isinstance(representations, list) or not all(isinstance(entry, dict) for entry in representations): + raise PretabSerializationError("Spec 'representations' must be a list of mappings.") + fields = ("columns", "group_id", "dimension", "output_slice") + declared = [{field: entry.get(field) for field in fields} for entry in representations if "group_id" in entry] + fitted = [ + _group_layout(block, [str(column) for column in block.columns]) + for block in _iter_fitted_blocks(column_transformer) + if block.group_id is not None + and getattr(representation_leaf(block.transformer), "get_representation_spec", None) is not None + ] + if declared != fitted: + raise PretabSerializationError("Spec 'representations' group layout does not match stored preprocessor state.") + + +def _validate_spec_metadata(data: dict, preprocessor) -> None: + """Check descriptive fields against their source in restored state, when available.""" + state = vars(preprocessor) + has_fit_config = "_fit_config_" in state + has_fitted_metadata = has_fit_config or "output_dims" in data or "total_output_dim" in data + expected = {} + if "params" in data and has_fitted_metadata: + expected["params"] = _json_safe(preprocessor.get_params(deep=False)) + if "resolved_config" in data and has_fit_config: + expected["resolved_config"] = _json_safe(state["_fit_config_"]) + if "output_dims" in data: + expected["output_dims"] = _json_safe(preprocessor.output_dims_) + if "total_output_dim" in data: + names = data.get("feature_names_out") + if isinstance(names, list): + expected["total_output_dim"] = len(names) + else: + spans = preprocessor.column_transformer_.output_indices_.values() + expected["total_output_dim"] = max((span.stop for span in spans), default=0) + for field, value in expected.items(): + if data[field] != value: + raise PretabSerializationError(f"Spec {field!r} does not match stored preprocessor state.") + if "representations" in data and has_fitted_metadata: + _validate_group_layout(data["representations"], preprocessor.column_transformer_) + + +def _repair_legacy_sparse_feature_counts(preprocessor) -> None: + """Repair the sparse-input helper width stored by PreTab 1.0.0.""" + column_transformer = getattr(preprocessor, "column_transformer_", None) + if column_transformer is None: + return + for _, transformer, _ in column_transformer.transformers_: + if isinstance(transformer, FeatureUnion): + transformer = dict(vars(transformer)["transformer_list"]).get("representation") + if not isinstance(transformer, Pipeline): + continue + for (_, encoder), (_, helper) in pairwise(transformer.steps): + if ( + type(encoder) is OneHotEncoder + and vars(encoder)["sparse_output"] + and hasattr(encoder, "categories_") + and type(helper) in (NoTransformer, ToFloatTransformer) + and getattr(helper, "n_features_in_", None) == 1 + and not hasattr(helper, "feature_names_in_") + ): + helper.n_features_in_ = len(encoder.get_feature_names_out()) + + def preprocessor_from_spec(data: dict): """Reconstruct a fitted preprocessor from a spec produced by :func:`preprocessor_to_spec`.""" check_spec_schema(data) @@ -353,4 +555,11 @@ def preprocessor_from_spec(data: dict): obj = Preprocessor.__new__(Preprocessor) obj.__dict__.update(_decode_mapping(data["state"])) + obj.__dict__.setdefault("feature_groups", None) + obj.__dict__.setdefault("task_validation", "off") + output_config = getattr(obj, "_sklearn_output_config", None) + if isinstance(output_config, dict) and output_config.get("transform") == "polars": + _require_polars() + _repair_legacy_sparse_feature_counts(obj) + _validate_spec_metadata(data, obj) return obj diff --git a/pretab/core/dependencies.py b/pretab/core/dependencies.py index 234ecd3..4c4bd26 100644 --- a/pretab/core/dependencies.py +++ b/pretab/core/dependencies.py @@ -10,6 +10,7 @@ from __future__ import annotations import importlib +import importlib.util from types import ModuleType from ..exceptions import OptionalDependencyError @@ -21,6 +22,15 @@ ] +def _check_optional_dependency(extra: str, purpose: str) -> None: + """Check top-level discovery without importing an optional model package.""" + module_name = "sentence_transformers" if extra == "embeddings" else extra + if importlib.util.find_spec(module_name.partition(".")[0]) is None: + raise OptionalDependencyError( + f"{purpose} requires the optional '{module_name}' dependency. Install it with: pip install pretab[{extra}]" + ) + + def require_module(module_name: str, extra: str, purpose: str) -> ModuleType: """Import ``module_name`` or raise :class:`OptionalDependencyError`. diff --git a/pretab/core/representation.py b/pretab/core/representation.py index bf1bf8e..d023a58 100644 --- a/pretab/core/representation.py +++ b/pretab/core/representation.py @@ -173,6 +173,8 @@ class FeatureLineage: Whether the producing transformer consumed ``y``. is_interaction : bool Whether the column mixes multiple input features. + group_id : str or None, default=None + Public block key of an explicit feature group, or ``None`` for singles. """ output_feature: str @@ -183,6 +185,7 @@ class FeatureLineage: component_index: int uses_target: bool is_interaction: bool + group_id: str | None = None def to_dict(self) -> dict: """Return a JSON-serializable dictionary representation.""" @@ -195,6 +198,7 @@ def to_dict(self) -> dict: "component_index": self.component_index, "uses_target": self.uses_target, "is_interaction": self.is_interaction, + **({"group_id": self.group_id} if self.group_id is not None else {}), } diff --git a/pretab/core/supervised.py b/pretab/core/supervised.py index 2adb49b..9ed0435 100644 --- a/pretab/core/supervised.py +++ b/pretab/core/supervised.py @@ -23,6 +23,7 @@ from scipy import sparse as sp from sklearn.base import BaseEstimator, TransformerMixin, clone from sklearn.model_selection import KFold, StratifiedKFold +from sklearn.pipeline import Pipeline from sklearn.utils.validation import check_is_fitted from ..exceptions import ( @@ -34,7 +35,14 @@ from ._typing import TransformerLike from .parameters import validate_task from .representation import RepresentationSpecMixin -from .validation import is_polars_frame, polars_to_pandas +from .validation import ( + _check_task_target_once, + _task_target_scope, + _TaskValidationMode, + _validate_task_validation, + is_polars_frame, + polars_to_pandas, +) __all__ = ["CrossFittedTransformer", "in_controlled_context", "warn_target_leakage"] @@ -165,7 +173,8 @@ class CrossFittedTransformer(RepresentationSpecMixin, TransformerMixin, BaseEsti A supervised (target-aware) PreTab transformer to cross-fit, or an estimator such as a :class:`~pretab.Preprocessor` or ``Pipeline`` built from them. For a :class:`~pretab.Preprocessor`, only its target-aware - representations and subsequent steps are refit per fold. Column types, + representations and subsequent steps are refit per fold, including joint + representations selected by feature groups. Column types, target-free blocks and their vocabularies, imputers, scalers before the representation and missing-indicator branches come from the all-data fit. Target-free feature values match :meth:`transform`; target-aware values @@ -193,12 +202,19 @@ class CrossFittedTransformer(RepresentationSpecMixin, TransformerMixin, BaseEsti _representation_supervision = "supervised" - def __init__(self, transformer, n_folds=5, task="regression", shuffle=True, random_state=None): + def __init__( + self, transformer, n_folds=5, task="regression", shuffle=True, random_state=None, *, task_validation="off" + ): self.transformer = transformer self.n_folds = n_folds self.task = task self.shuffle = shuffle self.random_state = random_state + self.task_validation = task_validation + + def __setstate__(self, state): + super().__setstate__(state) + self.__dict__.setdefault("task_validation", "off") def _make_splitter(self): """Return the cross-fitting splitter for the configured task.""" @@ -207,26 +223,55 @@ def _make_splitter(self): return StratifiedKFold(n_splits=self.n_folds, shuffle=self.shuffle, random_state=seed) return KFold(n_splits=self.n_folds, shuffle=self.shuffle, random_state=seed) - def _fit_full(self, X, y): - """Validate inputs and fit ``estimator_``; return 2D input and target array.""" + def _validate_fit_params(self, y) -> _TaskValidationMode: if y is None: raise IncompatibleParamsError("CrossFittedTransformer requires y at fit time; got y=None.") if not isinstance(self.n_folds, (int, np.integer)) or self.n_folds < 2: raise InvalidParamError(f"n_folds must be an integer >= 2; got {self.n_folds!r}.") validate_task(self.task, type(self).__name__) + return _validate_task_validation(self.task_validation, type(self).__name__) + + def _preflight_task_target(self, X, y): + mode = self._validate_fit_params(y) + self._check_fit_target(X, y, mode=mode) + + def _check_fit_target(self, X, y, *, mode: _TaskValidationMode): + _check_task_target_once( + y, + task=self.task, + mode=mode, + estimator=type(self).__name__, + role="cross-fitting", + n_samples=len(X), + ) + transformer = self.transformer + while isinstance(transformer, Pipeline): + transformer = next( + (step for _, step in transformer.steps if step is not None and step != "passthrough"), None + ) + preflight = getattr(transformer, "_preflight_task_target", None) + if preflight is not None: + preflight(X, y) + + def _fit_full(self, X, y): + """Validate inputs and fit ``estimator_``; return input, target and diagnostic receipts.""" + mode = self._validate_fit_params(y) X_arr = _as_2d(X) y_arr = np.asarray(y).ravel() if len(X_arr) != len(y_arr): raise PretabDataError(f"X and y must have same length. Got {len(X_arr)} and {len(y_arr)}") - estimator = cast(TransformerLike, clone(self.transformer)) - token = _cross_fit_active.set(True) - try: - estimator.fit(X_arr, y_arr) - finally: - _cross_fit_active.reset(token) + with _task_target_scope(y) as receipts: + self._check_fit_target(X_arr, y, mode=mode) + estimator = cast(TransformerLike, clone(self.transformer)) + token = _cross_fit_active.set(True) + try: + with _task_target_scope(y_arr, receipts): + estimator.fit(X_arr, y_arr) + finally: + _cross_fit_active.reset(token) self.estimator_ = estimator self.n_features_in_ = X_arr.shape[1] - return X_arr, y_arr + return X_arr, y_arr, receipts def fit(self, X, y=None): """Fit the all-data ``estimator_`` used by :meth:`transform`.""" @@ -271,7 +316,7 @@ def fit_transform(self, X, y=None): or if a fold's output has an invalid shape, a different width, or DataFrame columns other than the all-data fit's. """ - X_arr, y_arr = self._fit_full(X, y) + X_arr, y_arr, receipts = self._fit_full(X, y) names = list(self.estimator_.get_feature_names_out()) width = len(names) blocks, test_indices = [], [] @@ -279,7 +324,9 @@ def fit_transform(self, X, y=None): token = _cross_fit_active.set(True) try: for train_idx, test_idx in splitter.split(X_arr, y_arr): - fold = self._fit_fold(_take_rows(X_arr, train_idx), y_arr[train_idx]) + train_y = y_arr[train_idx] + with _task_target_scope(train_y, receipts.copy()): + fold = self._fit_fold(_take_rows(X_arr, train_idx), train_y) fold_out = fold.transform(_take_rows(X_arr, test_idx)) if isinstance(fold_out, dict): raise IncompatibleParamsError( diff --git a/pretab/core/validation.py b/pretab/core/validation.py index 34d1824..68ee5cc 100644 --- a/pretab/core/validation.py +++ b/pretab/core/validation.py @@ -8,13 +8,16 @@ import sys import warnings +from contextlib import contextmanager +from contextvars import ContextVar from typing import Literal, cast import numpy as np import pandas as pd +from sklearn.utils.multiclass import type_of_target from sklearn.utils.validation import _check_feature_names, _check_feature_names_in, check_array -from ..exceptions import DataWarning, IncompatibleParamsError, PretabDataError, invalid_param_error +from ..exceptions import ConfigWarning, DataWarning, IncompatibleParamsError, PretabDataError, invalid_param_error __all__ = ["is_polars_frame", "polars_to_pandas", "resolve_input_features", "single_target", "validate_2d_allow_nan"] @@ -80,6 +83,125 @@ def single_target(y, estimator: str, *, fix: str | None = None) -> np.ndarray: return y.ravel() +_TaskValidationMode = Literal["off", "warn", "raise"] + + +def _validate_task_validation(mode: object, estimator: str) -> _TaskValidationMode: + """Validate the requested consistency policy without normalizing it.""" + if not isinstance(mode, str) or mode not in ("off", "warn", "raise"): + raise invalid_param_error(estimator, "task_validation", mode, "must be 'off', 'warn', or 'raise'") + return cast(_TaskValidationMode, mode) + + +_TaskTargetContract = tuple[str, _TaskValidationMode, str] +_task_target_context: ContextVar[tuple[object, set[_TaskTargetContract]] | None] = ContextVar( + "_task_target_context", default=None +) + + +@contextmanager +def _task_target_scope(y: object, receipts: set[_TaskTargetContract] | None = None): + """Bind completed checks only to this target or an explicitly related fold.""" + active = _task_target_context.get() + if receipts is None and active is not None and active[0] is y: + yield active[1] + return + if receipts is None: + receipts = set() + token = _task_target_context.set((y, receipts)) + try: + yield receipts + finally: + _task_target_context.reset(token) + + +def _check_task_target_once( + y: object, + *, + task: str, + mode: _TaskValidationMode, + estimator: str, + role: str, + n_samples: int, +) -> None: + if mode == "off" or y is None: + return + active = _task_target_context.get() + receipts = active[1] if active is not None and active[0] is y else None + contract = (task, mode, role) + if receipts is not None and contract in receipts: + return + _validate_task_target(y, task=task, mode=mode, estimator=estimator, role=role, n_samples=n_samples) + if receipts is not None: + receipts.add(contract) + + +def _validate_task_target( + y: object, + *, + task: str, + mode: _TaskValidationMode, + estimator: str, + role: str, + n_samples: int | None = None, +) -> None: + """Diagnose clear mismatches for a validated task, mode and target-consuming role. + + Inspect only supported single-output targets. The caller retains ownership + of target validation and passes the original target on to fitting. + """ + if mode == "off" or not isinstance(y, (np.ndarray, pd.Series, pd.DataFrame, pd.Index, list, tuple)): + return + try: + values = np.asarray(y, dtype=object) if isinstance(y, (list, tuple)) else np.asarray(y) + except (TypeError, ValueError, OverflowError): + return + if ( + values.size == 0 + or values.ndim not in (1, 2) + or (n_samples is not None and values.shape[0] != n_samples) + or (values.ndim == 2 and values.shape[-1] != 1) + or values.dtype.kind not in "biufOU" + or pd.isna(values).any() + ): + return + + text_labels = values.dtype.kind == "U" or ( + values.dtype.kind == "O" and all(isinstance(value, str) for value in values.flat) + ) + if values.dtype.kind == "O" and not text_labels: + if not all(isinstance(value, (bool, int, float, np.bool_, np.integer, np.floating)) for value in values.flat): + return + values = np.asarray(values.tolist()) + if values.dtype.kind not in "biuf": + return + integer_limit = -int(np.iinfo(np.int64).min) + if values.dtype.kind == "f" and not (-integer_limit <= float(values.min()) and float(values.max()) < integer_limit): + return + + try: + observed = type_of_target(y) + except (TypeError, ValueError, OverflowError): + return + if task == "classification" and observed == "continuous": + suggested = "regression" + elif task == "regression" and observed in ("binary", "multiclass") and text_labels: + try: + np.asarray(values, dtype=np.float64) + except ValueError: + suggested = "classification" + else: + return + else: + return + + detail = f"{role} uses task={task!r}, but y has target type {observed!r}" + fix = f"use task={suggested!r} or set task_validation='off' if this is intentional" + if mode == "raise": + raise invalid_param_error(estimator, "task", task, f"{detail}; {fix}.") + warnings.warn(f"{estimator}: {detail}; {fix}.", ConfigWarning, stacklevel=2) + + def is_polars_frame(X) -> bool: """Return True if ``X`` is a polars DataFrame, without importing polars. diff --git a/pretab/embedding/language.py b/pretab/embedding/language.py index 71c0479..b27bbc7 100644 --- a/pretab/embedding/language.py +++ b/pretab/embedding/language.py @@ -38,8 +38,9 @@ class LanguageEmbeddingTransformer(TransformerMixin, BaseEstimator): Notes ----- - Requires the optional ``sentence-transformers`` dependency. Install it with - ``pip install sentence-transformers`` or pass a preloaded ``model``. + Install ``pretab[embeddings]`` to use the default model. The first call to + ``fit`` may download the model weights if they are not cached. Pass a + preloaded ``model`` to skip model loading. Examples -------- diff --git a/pretab/encoding/numerical/periodic.py b/pretab/encoding/numerical/periodic.py index 75aaf31..5cf6bd4 100644 --- a/pretab/encoding/numerical/periodic.py +++ b/pretab/encoding/numerical/periodic.py @@ -1,3 +1,5 @@ +from numbers import Real + import numpy as np from sklearn.utils.validation import check_is_fitted @@ -15,8 +17,9 @@ class PeriodicEncodingTransformer(BasePreTabTransformer): Parameters ---------- - period : int - The full cycle length (e.g., 24 for hours, 7 for weekdays). + period : int or float, > 0 + The finite, positive full cycle length (e.g., 24 for hours, 7 for + weekdays). Boolean values are not accepted. harmonics : int, default=1 The number of sine/cosine harmonic pairs to emit. Harmonic ``h`` uses the angle :math:`2\pi h x / p`, so ``harmonics`` pairs contribute @@ -69,7 +72,7 @@ class PeriodicEncodingTransformer(BasePreTabTransformer): _representation_family = "periodic" _representation_component_kind = "frequency" - def __init__(self, period: int, harmonics: int = 1, include_original: bool = False): + def __init__(self, period: int | float, harmonics: int = 1, include_original: bool = False): self.period = period self.harmonics = harmonics self.include_original = include_original @@ -79,6 +82,13 @@ def _representation_periodic(self): return True, float(self.period) def fit(self, X, y=None): + if ( + isinstance(self.period, (bool, np.bool_)) + or not isinstance(self.period, Real) + or not np.isfinite(self.period) + or self.period <= 0 + ): + raise InvalidParamError(f"period must be a finite, positive real number; got {self.period!r}.") X = self._validate(X, reset=True) if not isinstance(self.harmonics, (int, np.integer)) or self.harmonics < 1: raise InvalidParamError(f"harmonics must be a positive integer; got {self.harmonics!r}.") diff --git a/pretab/encoding/numerical/ple.py b/pretab/encoding/numerical/ple.py index c09a07c..d0b6c74 100644 --- a/pretab/encoding/numerical/ple.py +++ b/pretab/encoding/numerical/ple.py @@ -107,10 +107,17 @@ class PLETransformer( Examples -------- + Inspect the encoding on the data used to fit it. Because PLE uses the target + to place breakpoints, this emits :class:`~pretab.LeakageWarning`. Use + :class:`~pretab.CrossFittedTransformer` to produce out-of-fold training + features for a downstream model. + >>> from sklearn.datasets import make_regression + >>> from pretab.transformers import PLETransformer >>> X, y = make_regression(n_samples=100, n_features=5, noise=10, random_state=51) >>> ple = PLETransformer(output_dim=10, task="regression") - >>> X_transformed = ple.fit_transform(X, y) + >>> ple.fit_transform(X, y).shape + (100, 50) """ _param_aliases: ClassVar[dict[str, str]] = {} diff --git a/pretab/expansion/functional/rbf.py b/pretab/expansion/functional/rbf.py index a35e229..bdacdd2 100644 --- a/pretab/expansion/functional/rbf.py +++ b/pretab/expansion/functional/rbf.py @@ -75,9 +75,8 @@ class RBFExpansionTransformer(BaseCenterExpansion): >>> from pretab.transformers import RBFExpansionTransformer >>> X = np.array([[1.0], [2.0], [3.0]]) >>> transformer = RBFExpansionTransformer(output_dim=3, gamma=0.5, target_aware=False, placement_strategy="uniform") - >>> transformer.fit(X) - RBFExpansionTransformer(...) - >>> transformer.transform(X).shape + >>> fitted = transformer.fit(X) + >>> fitted.transform(X).shape (3, 3) """ diff --git a/pretab/expansion/functional/relu.py b/pretab/expansion/functional/relu.py index 624ffda..16cf126 100644 --- a/pretab/expansion/functional/relu.py +++ b/pretab/expansion/functional/relu.py @@ -77,9 +77,8 @@ class ReLUExpansionTransformer(BaseCenterExpansion): >>> from pretab.transformers import ReLUExpansionTransformer >>> X = np.array([[1.0], [2.0], [3.0]]) >>> transformer = ReLUExpansionTransformer(output_dim=3, target_aware=False, placement_strategy="uniform") - >>> transformer.fit(X) - ReLUExpansionTransformer(...) - >>> transformer.transform(X).shape + >>> fitted = transformer.fit(X) + >>> fitted.transform(X).shape (3, 3) """ diff --git a/pretab/expansion/functional/sigmoid.py b/pretab/expansion/functional/sigmoid.py index 31fe989..fb8fed3 100644 --- a/pretab/expansion/functional/sigmoid.py +++ b/pretab/expansion/functional/sigmoid.py @@ -75,9 +75,8 @@ class SigmoidExpansionTransformer(BaseCenterExpansion): >>> from pretab.transformers import SigmoidExpansionTransformer >>> X = np.array([[1.0], [2.0], [3.0]]) >>> transformer = SigmoidExpansionTransformer(output_dim=3, target_aware=False, placement_strategy="uniform") - >>> transformer.fit(X) - SigmoidExpansionTransformer(...) - >>> transformer.transform(X).shape + >>> fitted = transformer.fit(X) + >>> fitted.transform(X).shape (3, 3) """ diff --git a/pretab/expansion/functional/tanh.py b/pretab/expansion/functional/tanh.py index 5b4a195..c308e6f 100644 --- a/pretab/expansion/functional/tanh.py +++ b/pretab/expansion/functional/tanh.py @@ -75,9 +75,8 @@ class TanhExpansionTransformer(BaseCenterExpansion): >>> from pretab.transformers import TanhExpansionTransformer >>> X = np.array([[1.0], [2.0], [3.0]]) >>> transformer = TanhExpansionTransformer(output_dim=3, target_aware=False, placement_strategy="uniform") - >>> transformer.fit(X) - TanhExpansionTransformer(...) - >>> transformer.transform(X).shape + >>> fitted = transformer.fit(X) + >>> fitted.transform(X).shape (3, 3) """ diff --git a/pretab/expansion/spline/__init__.py b/pretab/expansion/spline/__init__.py index 72976f6..984a058 100644 --- a/pretab/expansion/spline/__init__.py +++ b/pretab/expansion/spline/__init__.py @@ -7,6 +7,7 @@ from .multivariate.thin_plate import ThinPlateSplineTransformer from .natural_cubic import NaturalCubicSplineTransformer from .p_spline import PSplineTransformer +from .penalty import PenaltySpec __all__ = [ "BSplineTransformer", @@ -16,6 +17,7 @@ "MSplineTransformer", "NaturalCubicSplineTransformer", "PSplineTransformer", + "PenaltySpec", "TensorProductSplineTransformer", "ThinPlateSplineTransformer", ] diff --git a/pretab/expansion/spline/base.py b/pretab/expansion/spline/base.py index d5540bf..8350025 100644 --- a/pretab/expansion/spline/base.py +++ b/pretab/expansion/spline/base.py @@ -30,13 +30,16 @@ from ...core.parameters import UNSET, validate_placement, validate_task from ...core.policy import RepresentationPolicy, resolve_out_of_range from ...core.supervised import warn_target_leakage +from ...core.validation import resolve_input_features from ...exceptions import ( DataWarning, InvalidParamError, PretabDataError, + PretabNotFittedError, invalid_param_error, ) from ...placement.adapters import SplinePlacementAdapter +from .penalty import PenaltySpec class BaseSplineTransformer(BasePreTabTransformer): @@ -444,3 +447,65 @@ def get_penalty_matrix(self, feature_index: int = 0, diff_order: int = 2): full[1:, 1:] = penalty return full return penalty + + def get_penalty_spec(self, feature_index: int = 0, *, diff_order: int | None = None) -> PenaltySpec: + """Return the base difference penalty in the selected feature's output coordinates. + + ``diff_order=None`` selects the legacy default of two. An explicit order + must be positive and smaller than the selected basis width without bias. + Output indices refer to this transformer's full output, including any + unpenalized bias column. Subclasses with a different matrix convention + must provide their own typed accessor. + + Raises + ------ + PretabNotFittedError + If the transformer has not been fitted. + InvalidParamError + If a feature index or difference order is invalid, or the subclass + overrides the legacy matrix without a typed convention. + """ + estimator = type(self).__name__ + if not hasattr(self, "n_basis_"): + raise PretabNotFittedError(f"{estimator} must be fitted before calling get_penalty_spec().") + legacy_accessor = self.get_penalty_matrix + if getattr(legacy_accessor, "__func__", None) is not BaseSplineTransformer.get_penalty_matrix: + raise invalid_param_error( + estimator, + "get_penalty_spec", + None, + "this penalty convention is not supported; use get_penalty_matrix() for the legacy matrix", + ) + if ( + isinstance(feature_index, (bool, np.bool_)) + or not isinstance(feature_index, (int, np.integer)) + or not 0 <= feature_index < len(self.n_basis_) + ): + raise invalid_param_error( + estimator, "feature_index", feature_index, f"must be in [0, {len(self.n_basis_)})" + ) + index = int(feature_index) + order = 2 if diff_order is None else diff_order + if ( + isinstance(order, (bool, np.bool_)) + or not isinstance(order, (int, np.integer)) + or order < 1 + or (diff_order is not None and order >= self.n_basis_[index]) + ): + raise invalid_param_error( + estimator, "diff_order", diff_order, f"must be an integer in [1, {self.n_basis_[index]})" + ) + sizes = self._output_sizes() + start = sum(sizes[:index]) + stop = start + sizes[index] + axis = str(resolve_input_features(self, None)[index]) + return PenaltySpec( + matrix=legacy_accessor(feature_index=index, diff_order=int(order)), + kind="coefficient_difference", + order=int(order), + axis=(axis,), + coordinate_system="output_coefficients", + coefficient_names=tuple(self.get_feature_names_out()[start:stop]), + coefficient_indices=range(start, stop), + provenance={"transformer": estimator, "include_bias": bool(self.include_bias)}, + ) diff --git a/pretab/expansion/spline/cubic_regression.py b/pretab/expansion/spline/cubic_regression.py index 1ce7fde..add9796 100644 --- a/pretab/expansion/spline/cubic_regression.py +++ b/pretab/expansion/spline/cubic_regression.py @@ -1,4 +1,5 @@ import itertools +from typing import Any import numpy as np from sklearn.base import BaseEstimator, TransformerMixin @@ -10,6 +11,7 @@ from ...exceptions import InvalidParamError from ...placement.adapters import SplinePlacementAdapter from .mixins import SplineBasisMixin +from .penalty import PenaltySpec class CubicRegressionSplineTransformer(SplineBasisMixin, TransformerMixin, BaseEstimator): @@ -276,6 +278,25 @@ def get_penalty_matrix(self, feature_index=0): P += (D * weights[:, None]).T @ D return P + def get_penalty_spec( + self, feature_index: int | np.integer[Any] = 0, *, diff_order: int | None = None + ) -> PenaltySpec: + """Return the integrated squared curvature penalty in fitted output coordinates. + + The integral is over the fitted feature range, in fitted input units. + Its derivative order is two; ``diff_order`` must be omitted or ``None``. + The linear column and optional leading bias are unpenalized; the quadratic, + cubic, and truncated cubic columns contribute to the penalty. + """ + return self._curvature_penalty_spec( + feature_index, + diff_order, + legacy_method=CubicRegressionSplineTransformer.get_penalty_matrix, + kind="integrated_squared_second_derivative", + base_width=3, + integration="piecewise_simpson", + ) + def _second_derivative(self, x, basis_index, knots): """Second derivative of one basis column, evaluated at ``x``.""" poly_offset = 1 if self.include_bias else 0 diff --git a/pretab/expansion/spline/mixins.py b/pretab/expansion/spline/mixins.py index ddb7971..874a404 100644 --- a/pretab/expansion/spline/mixins.py +++ b/pretab/expansion/spline/mixins.py @@ -10,11 +10,16 @@ transformer only has to implement its own basis math. """ +from collections.abc import Callable +from typing import Any + import numpy as np from ...core.base import BasePreTabTransformer from ...core.knots import generate_internal_knots, select_knots, spanning_knots, supplement_interior_knots -from ...exceptions import IncompatibleParamsError, PretabDataError +from ...core.validation import resolve_input_features +from ...exceptions import IncompatibleParamsError, PretabDataError, PretabNotFittedError, invalid_param_error +from .penalty import PenaltySpec class SplineBasisMixin(BasePreTabTransformer): @@ -49,6 +54,62 @@ def _output_sizes(self) -> list[int]: """Number of output columns contributed by each input feature.""" return [int(n) for n in self.n_basis_] + def _curvature_penalty_spec( + self, + feature_index: int | np.integer[Any], + diff_order: int | None, + *, + legacy_method: Callable[..., object], + kind: str, + base_width: int, + integration: str, + ) -> PenaltySpec: + estimator = type(self).__name__ + knot_counts: list[int] | None = getattr(self, "n_knots_", None) + if knot_counts is None or len(self.n_basis_) != self.n_features_in_ or len(knot_counts) != len(self.n_basis_): + raise PretabNotFittedError(f"{estimator} must be fitted before calling get_penalty_spec().") + legacy_accessor = getattr(self, "get_penalty_matrix", None) + if not callable(legacy_accessor) or getattr(legacy_accessor, "__func__", None) is not legacy_method: + raise invalid_param_error( + estimator, "get_penalty_spec", None, "the matrix convention is overridden; use get_penalty_matrix()" + ) + if diff_order is not None: + raise invalid_param_error( + estimator, + "diff_order", + diff_order, + "omit for a fixed second-derivative penalty, not a difference penalty", + ) + sizes = self._output_sizes() + if ( + isinstance(feature_index, (bool, np.bool_)) + or not isinstance(feature_index, (int, np.integer)) + or not 0 <= feature_index < len(sizes) + ): + raise invalid_param_error(estimator, "feature_index", feature_index, f"must be in [0, {len(sizes)})") + include_bias = bool(getattr(self, "include_bias", False)) + if any( + width != knot_count + base_width + include_bias + for width, knot_count in zip(sizes, knot_counts, strict=True) + ): + raise invalid_param_error( + estimator, "include_bias", include_bias, "refit after changing the fitted basis width" + ) + + index = int(feature_index) + start = sum(sizes[:index]) + stop = start + sizes[index] + return PenaltySpec( + matrix=legacy_accessor(index), + kind=kind, + order=2, + axis=(str(resolve_input_features(self, None)[index]),), + coordinate_system="output_coefficients", + coefficient_names=tuple(self.get_feature_names_out()[start:stop]), + coefficient_indices=range(start, stop), + provenance={"transformer": estimator, "include_bias": include_bias, "integration": integration}, + ) + def _finite_column(self, x, y): """Drop NaN samples from one feature (aligning ``y``) before knot placement. diff --git a/pretab/expansion/spline/multivariate/tensor_product.py b/pretab/expansion/spline/multivariate/tensor_product.py index 6e83586..5137dc8 100644 --- a/pretab/expansion/spline/multivariate/tensor_product.py +++ b/pretab/expansion/spline/multivariate/tensor_product.py @@ -6,8 +6,9 @@ from ....core.parameters import UNSET from ....core.policy import RepresentationPolicy, resolve_out_of_range from ....core.validation import resolve_input_features -from ....exceptions import InvalidParamError +from ....exceptions import InvalidParamError, PretabNotFittedError, invalid_param_error from ..mixins import SplineBasisMixin +from ..penalty import PenaltySpec class TensorProductSplineTransformer(SplineBasisMixin, TransformerMixin, BaseEstimator): @@ -186,7 +187,11 @@ def _difference_penalty(self, n_basis): D = np.diff(D, n=1, axis=0) return D.T @ D + _penalty_source_axes_: tuple[str, ...] + def fit(self, X, y=None): + self.__dict__.pop("_penalty_fit_", None) + self.__dict__.pop("_penalty_source_axes_", None) X = self._validate_allow_nan(X, reset=True) output_dim = self._resolve_param("output_dim", default=4) if self.placement_strategy not in ("uniform", "quantile"): @@ -234,6 +239,7 @@ def fit(self, X, y=None): self.penalties_.append(penalty) self.n_knots_.append(max(0, len(knots) - 2 * (self.degree + 1))) + self._penalty_fit_ = (int(self.diff_order), bool(self.include_bias), int(self.degree)) return self def transform(self, X): @@ -326,3 +332,59 @@ def get_penalty_matrix(self, feature_index=0): """ check_is_fitted(self, "penalties_") return self.penalties_[feature_index] + + def get_penalty_specs(self) -> tuple[PenaltySpec, ...]: + """Return one full joint penalty per fitted source direction, in source order. + + Every matrix matches the corresponding entry in :meth:`get_penalty_matrices`. + Names and indices address this transformer's joint output in C order, + with the last input axis varying fastest. Bias, when enabled at fit, + belongs to each marginal basis, not to an extra joint intercept. + + Raises + ------ + PretabNotFittedError + If no fitted marginal penalties are available. + InvalidParamError + If the fitted convention is unavailable, the basis settings require + a refit, or a subclass overrides the joint matrix convention. + """ + estimator = type(self).__name__ + if not hasattr(self, "penalties_"): + raise PretabNotFittedError(f"{estimator} must be fitted before calling get_penalty_specs().") + fitted = getattr(self, "_penalty_fit_", None) + if fitted is None: + raise invalid_param_error(estimator, "get_penalty_specs", None, "refit to record the fitted penalty order") + order, include_bias, degree = fitted + if (bool(self.include_bias), self.degree) != (include_bias, degree): + raise invalid_param_error( + estimator, "get_penalty_specs", None, "refit after changing degree or include_bias" + ) + legacy_accessor = self.get_penalty_matrices + if getattr(legacy_accessor, "__func__", None) is not TensorProductSplineTransformer.get_penalty_matrices: + raise invalid_param_error( + estimator, "get_penalty_specs", None, "the matrix convention is overridden; use get_penalty_matrices()" + ) + + axes = getattr(self, "_penalty_source_axes_", None) + if axes is None: + axes = resolve_input_features(self, None) + names = tuple(self.get_feature_names_out()) + return tuple( + PenaltySpec( + matrix=matrix, + kind="coefficient_difference", + order=order, + axis=(str(axis),), + coordinate_system="output_coefficients", + coefficient_names=names, + coefficient_indices=range(len(names)), + provenance={ + "transformer": estimator, + "include_bias": include_bias, + "marginal_sizes": self.marginal_sizes_, + "flatten_order": "C", + }, + ) + for axis, matrix in zip(axes, legacy_accessor(), strict=True) + ) diff --git a/pretab/expansion/spline/natural_cubic.py b/pretab/expansion/spline/natural_cubic.py index 4462b00..6f63460 100644 --- a/pretab/expansion/spline/natural_cubic.py +++ b/pretab/expansion/spline/natural_cubic.py @@ -1,3 +1,5 @@ +from typing import Any + import numpy as np from scipy.integrate import trapezoid from sklearn.base import BaseEstimator, TransformerMixin @@ -9,6 +11,7 @@ from ...exceptions import InvalidParamError from ...placement.adapters import SplinePlacementAdapter from .mixins import SplineBasisMixin +from .penalty import PenaltySpec class NaturalCubicSplineTransformer(SplineBasisMixin, TransformerMixin, BaseEstimator): @@ -273,3 +276,22 @@ def get_penalty_matrix(self, feature_index=0): P[i, j] = trapezoid(integrand, x_grid) return P + + def get_penalty_spec( + self, feature_index: int | np.integer[Any] = 0, *, diff_order: int | None = None + ) -> PenaltySpec: + """Return the legacy approximate curvature penalty in fitted output coordinates. + + The penalty uses numerical second derivatives and trapezoidal integration + on a 200-point grid over the fitted feature range, in fitted input units. + Its derivative order is two; ``diff_order`` must be omitted or ``None``. + The linear column and optional leading bias are unpenalized. + """ + return self._curvature_penalty_spec( + feature_index, + diff_order, + legacy_method=NaturalCubicSplineTransformer.get_penalty_matrix, + kind="approximate_integrated_squared_second_derivative", + base_width=1, + integration="finite_difference_trapezoid_200", + ) diff --git a/pretab/expansion/spline/p_spline.py b/pretab/expansion/spline/p_spline.py index 6ba7b2c..fe521b0 100644 --- a/pretab/expansion/spline/p_spline.py +++ b/pretab/expansion/spline/p_spline.py @@ -1,3 +1,5 @@ +from typing import Any + import numpy as np from sklearn.base import BaseEstimator, TransformerMixin from sklearn.utils.validation import check_is_fitted @@ -5,8 +7,10 @@ from ...core.knots import bspline_basis, extrapolate_bspline_rows from ...core.parameters import UNSET from ...core.policy import RepresentationPolicy, resolve_out_of_range -from ...exceptions import InvalidParamError +from ...core.validation import resolve_input_features +from ...exceptions import InvalidParamError, PretabNotFittedError, invalid_param_error from .mixins import SplineBasisMixin +from .penalty import PenaltySpec class PSplineTransformer(SplineBasisMixin, TransformerMixin, BaseEstimator): @@ -155,6 +159,7 @@ def __init__( self.policy = policy def fit(self, X, y=None): + self.__dict__.pop("_penalty_fit_", None) X = self._validate_allow_nan(X, reset=True) output_dim = self._resolve_param("output_dim", default=6) if self.placement_strategy != "uniform": @@ -204,6 +209,7 @@ def fit(self, X, y=None): self.n_knots_.append(max(0, len(knots) - 2 * (self.degree + 1))) self.penalty_.append(penalty) + self._penalty_fit_ = (int(self.diff_order), bool(self.include_bias)) return self def transform(self, X): @@ -241,3 +247,68 @@ def get_penalty_matrix(self, feature_index=0): """ check_is_fitted(self, "penalty_") return self.penalty_[feature_index] + + def _has_legacy_only_penalty(self) -> bool: + fitted = getattr(self, "_penalty_fit_", None) + return fitted is not None and fitted[0] not in (1, 2) + + def get_penalty_spec( + self, feature_index: int | np.integer[Any] = 0, *, diff_order: int | np.integer[Any] | None = None + ) -> PenaltySpec: + """Return the fitted difference penalty for the selected feature. + + Typed penalties support fitted orders one and two. Omit ``diff_order`` + to use the fitted order, or specify that same order explicitly. The + coefficient positions refer to the full transformer output, including + the leading unpenalized bias column for each feature if fitted with bias. + + Raises + ------ + PretabNotFittedError + If no fitted penalty matrices are available. + InvalidParamError + If the fitted convention is unavailable or unsupported, or the + feature index or explicit order is invalid. + """ + estimator = type(self).__name__ + if not hasattr(self, "penalty_"): + raise PretabNotFittedError(f"{estimator} must be fitted before calling get_penalty_spec().") + fitted = getattr(self, "_penalty_fit_", None) + if fitted is None: + raise invalid_param_error(estimator, "get_penalty_spec", None, "refit to record the fitted penalty order") + order, include_bias = fitted + if self._has_legacy_only_penalty(): + raise invalid_param_error( + estimator, + "diff_order", + order, + "typed P-spline penalties support fitted orders 1 and 2; " + "use get_penalty_matrix() for the legacy matrix", + ) + if diff_order is not None and ( + isinstance(diff_order, (bool, np.bool_)) + or not isinstance(diff_order, (int, np.integer)) + or diff_order != order + ): + raise invalid_param_error(estimator, "diff_order", diff_order, f"must match the fitted order ({order})") + sizes = self._output_sizes() + if ( + isinstance(feature_index, (bool, np.bool_)) + or not isinstance(feature_index, (int, np.integer)) + or not 0 <= feature_index < len(sizes) + ): + raise invalid_param_error(estimator, "feature_index", feature_index, f"must be in [0, {len(sizes)})") + index = int(feature_index) + start = sum(sizes[:index]) + stop = start + sizes[index] + axis = str(resolve_input_features(self, None)[index]) + return PenaltySpec( + matrix=self.get_penalty_matrix(index), + kind="coefficient_difference", + order=order, + axis=(axis,), + coordinate_system="output_coefficients", + coefficient_names=tuple(self.get_feature_names_out()[start:stop]), + coefficient_indices=range(start, stop), + provenance={"transformer": estimator, "include_bias": include_bias}, + ) diff --git a/pretab/expansion/spline/penalty.py b/pretab/expansion/spline/penalty.py new file mode 100644 index 0000000..c4a6111 --- /dev/null +++ b/pretab/expansion/spline/penalty.py @@ -0,0 +1,243 @@ +"""Validated penalty matrices in explicit coefficient coordinates.""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from dataclasses import dataclass, field +from hashlib import sha256 +from math import isfinite +from numbers import Integral, Real +from struct import pack +from types import MappingProxyType +from typing import Any + +import numpy as np +from numpy.typing import ArrayLike, NDArray + +from ...exceptions import InvalidParamError, invalid_param_error + + +def _invalid(name: str, value: object, constraint: str) -> InvalidParamError: + return invalid_param_error("PenaltySpec", name, value, constraint) + + +def _text(name: str, value: str) -> str: + if not isinstance(value, str) or not value.strip(): + raise _invalid(name, value, "must be a nonempty string") + return value + + +def _items(name: str, values: object) -> tuple[Any, ...]: + if isinstance(values, (str, bytes, bytearray)) or not isinstance(values, (Sequence, np.ndarray)): + raise _invalid(name, values, "must be a nonempty ordered sequence") + if (isinstance(values, np.ndarray) and values.ndim != 1) or len(values) == 0: + raise _invalid(name, values, "must be a nonempty one-dimensional sequence") + return tuple(values) + + +def _integer(name: str, value: int, minimum: int) -> int: + if isinstance(value, (bool, np.bool_)) or not isinstance(value, Integral) or value < minimum: + raise _invalid(name, value, f"must be an integer >= {minimum}") + return int(value) + + +def _tolerance(name: str, value: float) -> float: + if isinstance(value, (bool, np.bool_)) or not isinstance(value, Real) or value < 0: + raise _invalid(name, value, "must be a finite nonnegative real number") + try: + result = float(value) + except OverflowError as exc: + raise _invalid(name, value, "must be a finite nonnegative real number") from exc + if not isfinite(result): + raise _invalid(name, value, "must be a finite nonnegative real number") + return result + + +def _freeze_provenance(value: Any, active: set[int]) -> Any: + if value is None or isinstance(value, (str, bool, int)): + return value + if isinstance(value, float) and isfinite(value): + return float(value) + if isinstance(value, (Mapping, list, tuple)): + identity = id(value) + if identity in active: + raise _invalid("provenance", value, "must not contain circular references") + active.add(identity) + try: + if isinstance(value, Mapping): + if not all(isinstance(key, str) for key in value): + raise _invalid("provenance", value, "mapping keys must be strings") + return MappingProxyType({key: _freeze_provenance(item, active) for key, item in value.items()}) + return tuple(_freeze_provenance(item, active) for item in value) + finally: + active.remove(identity) + raise _invalid("provenance", value, "must contain only finite JSON-compatible values") + + +def _copy_provenance(value: Any) -> Any: + if isinstance(value, Mapping): + return {key: _copy_provenance(item) for key, item in value.items()} + if isinstance(value, tuple): + return [_copy_provenance(item) for item in value] + return value + + +def _validated_matrix(matrix: ArrayLike, atol: float, rtol: float) -> tuple[NDArray[np.float64], int]: + try: + raw = np.asarray(matrix) + except (TypeError, ValueError, OverflowError) as exc: + raise _invalid("matrix", matrix, "must be a nonempty real square matrix") from exc + if raw.ndim != 2 or raw.shape[0] == 0 or raw.shape[0] != raw.shape[1] or raw.dtype.kind not in "iuf": + raise _invalid("matrix", matrix, "must be a nonempty real square matrix") + with np.errstate(over="ignore", invalid="ignore"): + values = np.array(raw, dtype=np.float64, order="C", copy=True) + if not np.isfinite(values).all(): + raise _invalid("matrix", matrix, "must contain only finite float64 values") + + scale = float(np.max(np.abs(values))) or 1.0 + scaled = values / scale + symmetric = (scaled + scaled.T) * 0.5 + try: + eigenvalues = np.linalg.eigvalsh(symmetric) + except np.linalg.LinAlgError as exc: + raise _invalid("matrix", matrix, "could not validate its symmetric eigenvalues") from exc + threshold = atol / scale + rtol * float(np.max(np.abs(eigenvalues))) + if (threshold == 0 and not np.array_equal(values, values.T)) or np.max(np.abs(scaled - scaled.T)) > threshold: + raise _invalid("matrix", matrix, "must be symmetric within the recorded tolerance") + if eigenvalues[0] < -threshold: + raise _invalid("matrix", matrix, "must be positive semidefinite within the recorded tolerance") + return values, int(np.count_nonzero(eigenvalues > threshold)) + + +@dataclass(frozen=True, init=False, eq=False, slots=True) +class PenaltySpec: + """Immutable quadratic penalty and its ordered output coefficient coordinates. + + ``matrix`` is a detached, read-only float64 array. The unscaled penalty is + ``beta.T @ matrix @ beta`` in the order of ``coefficient_names`` and + ``coefficient_indices``. ``axis`` names the source directions. ``order`` is + a positive integer or ``None`` for a convention without a difference order. + + Symmetry, positive semidefiniteness and numerical rank are checked using + ``atol + rtol * spectral_norm`` of the symmetric part. Validation never + repairs the stored matrix. ``rank`` and ``nullity`` are derived, and nested + JSON-compatible ``provenance`` is detached and read-only. + """ + + _matrix_bytes: bytes = field(repr=False) + kind: str + order: int | None + axis: tuple[str, ...] + coordinate_system: str + coefficient_names: tuple[str, ...] + coefficient_indices: tuple[int, ...] + rank: int + nullity: int + atol: float + rtol: float + provenance: Mapping[str, Any] + + def __init__( + self, + matrix: ArrayLike, + kind: str, + order: int | None, + axis: Sequence[str], + coordinate_system: str, + coefficient_names: Sequence[str], + coefficient_indices: Sequence[int], + atol: float = 1e-10, + rtol: float = 1e-10, + provenance: Mapping[str, Any] | None = None, + ) -> None: + kind = _text("kind", kind) + if kind == "coefficient_difference" and order is None: + raise _invalid("order", order, "coefficient_difference requires a positive integer order") + order = None if order is None else _integer("order", order, 1) + axes = tuple(_text("axis", label) for label in _items("axis", axis)) + coordinate_system = _text("coordinate_system", coordinate_system) + names = tuple(_text("coefficient_names", name) for name in _items("coefficient_names", coefficient_names)) + indices = tuple( + _integer("coefficient_indices", index, 0) for index in _items("coefficient_indices", coefficient_indices) + ) + atol, rtol = _tolerance("atol", atol), _tolerance("rtol", rtol) + values, rank = _validated_matrix(matrix, atol, rtol) + width = values.shape[0] + for field_name, coordinates in (("coefficient_names", names), ("coefficient_indices", indices)): + if len(coordinates) != width or len(set(coordinates)) != width: + raise _invalid(field_name, coordinates, "must contain one distinct entry per matrix row") + if len(set(axes)) != len(axes): + raise _invalid("axis", axis, "must contain distinct source labels") + if provenance is not None and not isinstance(provenance, Mapping): + raise _invalid("provenance", provenance, "must be a mapping") + + object.__setattr__(self, "_matrix_bytes", values.tobytes()) + object.__setattr__(self, "kind", kind) + object.__setattr__(self, "order", order) + object.__setattr__(self, "axis", axes) + object.__setattr__(self, "coordinate_system", coordinate_system) + object.__setattr__(self, "coefficient_names", names) + object.__setattr__(self, "coefficient_indices", indices) + object.__setattr__(self, "rank", rank) + object.__setattr__(self, "nullity", width - rank) + object.__setattr__(self, "atol", atol) + object.__setattr__(self, "rtol", rtol) + object.__setattr__(self, "provenance", _freeze_provenance({} if provenance is None else provenance, set())) + + @property + def matrix(self) -> NDArray[np.float64]: + """Read-only matrix with independent array metadata on each access.""" + width = len(self.coefficient_indices) + return np.frombuffer(self._matrix_bytes, dtype=np.float64).reshape(width, width) + + def to_summary(self) -> dict[str, Any]: + """Return detached JSON metadata without the dense matrix. + + ``matrix_sha256`` is the hexadecimal SHA-256 digest of the row and + column counts (two unsigned 64-bit little-endian integers), followed + by C-order little-endian float64 matrix bytes. The checksum treats + negative zero as positive zero and does not round any other values. + It identifies exact matrix content, not tolerance-based equivalence. + The summary cannot reconstruct the matrix. + """ + matrix = np.array(self.matrix, dtype=" bool: + if not isinstance(other, PenaltySpec): + return NotImplemented + return self._metadata() == other._metadata() and np.array_equal(self.matrix, other.matrix) + + def _metadata(self) -> tuple: + return ( + self.kind, + self.order, + self.axis, + self.coordinate_system, + self.coefficient_names, + self.coefficient_indices, + self.atol, + self.rtol, + self.provenance, + ) + + def __reduce__(self): + return type(self), (self.matrix, *self._metadata()[:-1], _copy_provenance(self.provenance)) diff --git a/pretab/extension.py b/pretab/extension.py index 7129eed..cad72cb 100644 --- a/pretab/extension.py +++ b/pretab/extension.py @@ -21,6 +21,7 @@ import inspect import warnings +from collections.abc import Iterable import numpy as np from sklearn.base import clone @@ -35,7 +36,9 @@ ) from .core.base import BasePreTabTransformer from .core.representation import RepresentationSpec -from .exceptions import ConfigWarning, RepresentationConformanceError +from .core.validation import resolve_input_features +from .exceptions import ConfigWarning, PretabNotFittedError, RepresentationConformanceError +from .expansion.spline.penalty import PenaltySpec __all__ = [ "BaseRepresentation", @@ -136,6 +139,7 @@ def register_representation( periodic=False, sparse_output=False, override=False, + typed_penalty=False, ): """Register a representation class under ``name`` so it is selectable by name. @@ -186,6 +190,8 @@ class without one raises ``TypeError``. For a class without a Whether the method can emit a sparse matrix. override : bool, default=False Whether replacing an already-registered ``name`` is allowed. + typed_penalty : bool, default=False + Opt in to the typed penalty contract checked by :func:`check_representation`. Returns ------- @@ -228,6 +234,7 @@ class without one raises ``TypeError``. For a class without a optional_dependency=optional_dependency, periodic=bool(periodic), sparse_output=bool(sparse_output), + typed_penalty=bool(typed_penalty), ) return register_spec(spec, override=override) @@ -251,10 +258,7 @@ def load_entry_point_representations(group=ENTRY_POINT_GROUP, *, override=False) """ from importlib.metadata import entry_points - try: - eps = entry_points(group=group) - except TypeError: # pragma: no cover - Python < 3.10 selection fallback - eps = entry_points().get(group, []) + eps = entry_points(group=group) loaded = [] for ep in eps: @@ -336,6 +340,71 @@ def _densify(array): return np.asarray(array) +def _check_typed_penalty(fitted, unfitted, *, joint, names): + typed_name, legacy_name = ( + ("get_penalty_specs", "get_penalty_matrices") if joint else ("get_penalty_spec", "get_penalty_matrix") + ) + label = f"{type(fitted).__name__}.{typed_name}" + typed_accessor = getattr(fitted, typed_name, None) + legacy_accessor = getattr(fitted, legacy_name, None) + if not callable(typed_accessor) or not callable(legacy_accessor): + raise RepresentationConformanceError(f"{label} and {legacy_name} are required by typed_penalty") + try: + getattr(unfitted, typed_name)() + except PretabNotFittedError: + pass + except Exception as exc: + raise RepresentationConformanceError(f"{label} before fit must raise PretabNotFittedError") from exc + else: + raise RepresentationConformanceError(f"{label} before fit must raise PretabNotFittedError") + + axes = tuple(str(axis) for axis in resolve_input_features(fitted, None)) + try: + if joint: + penalties = typed_accessor() + matrices = legacy_accessor() + if not isinstance(matrices, Iterable): + raise TypeError(f"{legacy_name} must return an iterable of matrices") + legacy = tuple(matrices) + else: + penalties = tuple(typed_accessor(feature_index=index) for index in range(len(axes))) + legacy = tuple(legacy_accessor(feature_index=index) for index in range(len(axes))) + except Exception as exc: + raise RepresentationConformanceError(f"{label} failed on fitted data: {exc}") from exc + if not isinstance(penalties, tuple) or len(penalties) != len(axes) or len(legacy) != len(axes): + raise RepresentationConformanceError(f"{label} must provide one PenaltySpec and legacy matrix per fitted axis") + + output_indices = tuple(range(len(names))) + covered_indices = [] + for axis, penalty, reference in zip(axes, penalties, legacy, strict=True): + if not isinstance(penalty, PenaltySpec): + raise RepresentationConformanceError(f"{label} must return PenaltySpec values") + if penalty.axis != (axis,) or penalty.coordinate_system != "output_coefficients": + raise RepresentationConformanceError(f"{label} must identify fitted axis {axis!r} in output coefficients") + indices = penalty.coefficient_indices + if ( + (joint and indices != output_indices) + or any(index >= len(names) for index in indices) + or penalty.coefficient_names != tuple(names[index] for index in indices) + ): + raise RepresentationConformanceError(f"{label} coefficient names and indices must match fitted output") + matrix = penalty.matrix + if not np.array_equal(matrix, reference): + raise RepresentationConformanceError(f"{label} matrix must match {legacy_name}") + if matrix.flags.writeable or np.shares_memory(matrix, reference): + raise RepresentationConformanceError(f"{label} matrix must be read-only and detached from {legacy_name}") + try: + matrix.setflags(write=True) + except ValueError: + pass + else: + matrix.setflags(write=False) + raise RepresentationConformanceError(f"{label} matrix must not allow writes to be re-enabled") + covered_indices.extend(indices) + if not joint and tuple(covered_indices) != output_indices: + raise RepresentationConformanceError(f"{label} must cover consecutive feature blocks in fitted output order") + + def check_representation(cls, *, X=None, y=None): """Run the representation conformance suite on a class. @@ -346,6 +415,9 @@ def check_representation(cls, *, X=None, y=None): width and is unique; the result is deterministic across ``clone`` + refit; the typed :class:`~pretab.RepresentationSpec` agrees with the declared ``scope`` and output width; and a ``"supervised"`` class refuses to fit without ``y``. + A registered ``typed_penalty`` claim additionally checks penalty access + before fit and validates fitted axes, output coordinates, and legacy matrix + parity. Parameters ---------- @@ -368,8 +440,14 @@ class declares ``supervision="supervised"``. On the first failed check, with a message identifying the violation. """ rng = np.random.RandomState(0) + penalty_scopes = { + spec.arity for spec in TRANSFORMER_REGISTRY.values() if spec.transformer_cls is cls and spec.typed_penalty + } + if len(penalty_scopes) > 1: + raise RepresentationConformanceError(f"{cls.__name__} has conflicting typed_penalty scopes") + penalty_scope = next(iter(penalty_scopes), None) if X is None: - X = rng.uniform(-2.0, 2.0, size=(40, 1)).astype(float) + X = rng.uniform(-2.0, 2.0, size=(40, 2 if penalty_scope == "multivariate" else 1)).astype(float) X = np.asarray(X) n_samples = X.shape[0] @@ -445,7 +523,7 @@ def _fit(est): spec = fitted.get_representation_spec() if not isinstance(spec, RepresentationSpec): raise RepresentationConformanceError(f"{cls.__name__}.get_representation_spec must return a RepresentationSpec") - declared_scope = getattr(cls, "scope", "univariate") + declared_scope = getattr(cls, "scope", penalty_scope or "univariate") if spec.scope != declared_scope: raise RepresentationConformanceError( f"{cls.__name__} spec.scope {spec.scope!r} != declared scope {declared_scope!r}" @@ -456,6 +534,12 @@ def _fit(est): ) passed.append("spec_consistent") + if penalty_scope is not None: + if spec.scope != penalty_scope: + raise RepresentationConformanceError(f"{cls.__name__} spec.scope must match its typed_penalty scope") + _check_typed_penalty(fitted, _make(), joint=penalty_scope == "multivariate", names=names) + passed.append("typed_penalty_consistent") + # 7. a supervised class must refuse to fit without y. if needs_y: est = _make() diff --git a/pretab/preprocessor.py b/pretab/preprocessor.py index aaba9df..ebd50a2 100644 --- a/pretab/preprocessor.py +++ b/pretab/preprocessor.py @@ -5,6 +5,7 @@ import os import time import warnings +from dataclasses import fields from typing import cast import numpy as np @@ -23,7 +24,9 @@ with_string_labels, ) from .compose.inspection import ( - block_name, + _block_uses_task, + _build_effective_settings_summary, + _iter_fitted_blocks, block_uses_target, build_feature_info, build_feature_lineage, @@ -41,11 +44,18 @@ to_dataframe_output, validate_embedding_request, ) -from .compose.serialize import SCHEMA_VERSION, preprocessor_from_spec, preprocessor_to_spec +from .compose.serialize import ( + SCHEMA_VERSION, + _canonicalize_feature_fingerprint, + _repair_legacy_sparse_feature_counts, + preprocessor_from_spec, + preprocessor_to_spec, +) from .core._typing import TransformerLike from .core.logging import configure_logging, get_logger from .core.parameters import UNSET, validate_task from .core.policy import RepresentationPolicy, apply_constant_policy +from .core.validation import _check_task_target_once, _validate_task_validation from .exceptions import ( ConfigWarning, DataWarning, @@ -57,6 +67,7 @@ PretabSerializationError, invalid_param_error, ) +from .expansion.spline.multivariate.tensor_product import TensorProductSplineTransformer logger = get_logger(__name__) @@ -170,10 +181,15 @@ class Preprocessor(TransformerMixin, BaseEstimator): language embeddings). Pass ``None`` (resolved to ``"none"``) to leave categorical columns unchanged. feature_preprocessing : dict, optional - Mapping of individual column names to a method, overriding the global ``numerical_method`` / - ``categorical_method`` for those columns only, e.g. - ``{"age": "cubicspline", "city": "pretrained"}``. Columns absent from the dict fall back to - the global defaults. + Mapping of column names to method strings, mappings with a ``method`` key, or + :class:`~pretab.RepresentationConfig` values. Forms may be mixed, for example + ``{"age": {"method": "rbf", "output_dim": 3, "params": {"gamma": 0.5}}, "city": "one-hot"}``. + Local settings override applicable constructor-wide controls; omitted columns use the + global methods. A local explicit width disables inherited adaptive sizing unless + local ``adaptive=True`` also opts in. Imputation, scaling, and output formatting remain + run-wide. Raw mappings stay live until normalization or fit; typed values detach on + construction. See :meth:`get_resolved_config` for detached effective declarations, + not learned state or realized widths. output_dim : int, default=7 The single width knob shared by every numerical method: the number of non-bias output columns produced per input feature (bins for PLE/binning, centers for the feature maps, @@ -277,9 +293,10 @@ class Preprocessor(TransformerMixin, BaseEstimator): features. ``None`` disables the check. A violation is handled per ``overflow_policy``. max_features_per_input : int or None, default=None - Upper bound on the number of output columns any single input feature may - expand to. ``None`` disables the check. A violation is handled per - ``overflow_policy``. + Upper bound on the actual output width of each single feature or joint + feature group, including raw missing indicators. A group counts as one + unit; its width is not divided among sources. ``None`` disables the check. + A violation is handled per ``overflow_policy``. max_dense_memory : int or None, default=None Upper bound, in bytes, on the estimated dense output footprint (``n_rows * total_output_dim_ * itemsize``) evaluated against the training @@ -340,6 +357,12 @@ class Preprocessor(TransformerMixin, BaseEstimator): and one-hot encodes categoricals, and ``"adaptive"`` sizes each feature's width from the data within ``[7, 15]``. Call :meth:`get_resolved_config` to see the effective parameters. ``None`` (default) uses the individual parameters unchanged. + feature_groups : mapping or sequence, default=None + Ordered named declarations of source columns and representation settings. + Constructor inputs remain unchanged; :meth:`get_resolved_config` returns + detached declarations with canonical methods and applicable settings. + ``None`` or an empty collection keeps single-column processing. Each + nonempty declaration fits one joint block over its ordered sources. Attributes ---------- @@ -490,6 +513,9 @@ def __init__( dtype=None, verbose=0, preset=None, + *, + feature_groups=None, + task_validation="off", ): """ Initialize the Preprocessor with various transformation options for tabular data. @@ -527,6 +553,15 @@ def __init__( self.dtype = dtype self.verbose = verbose self.preset = preset + self.feature_groups = feature_groups + self.task_validation = task_validation + + def __setstate__(self, state): + super().__setstate__(state) + if not hasattr(self, "feature_groups"): + self.feature_groups = None + self.__dict__.setdefault("task_validation", "off") + _repair_legacy_sparse_feature_counts(self) def fit(self, X, y=None, embeddings=None): """ @@ -577,42 +612,23 @@ def fit(self, X, y=None, embeddings=None): start_time = time.perf_counter() resolved = self._resolved_params() - config = PreprocessorConfig.from_params( - numerical_method=resolved["numerical_method"], - categorical_method=resolved["categorical_method"], - feature_preprocessing=resolved["feature_preprocessing"], - output_dim=resolved["output_dim"], - degree=resolved["degree"], - target_aware=resolved["target_aware"], - placement_strategy=resolved["placement_strategy"], - task=resolved["task"], - adaptive=resolved["adaptive"], - min_output_dim=resolved["min_output_dim"], - max_output_dim=resolved["max_output_dim"], - random_state=resolved["random_state"], - scaling=resolved["scaling"], - cat_cutoff=resolved["cat_cutoff"], - treat_all_integers_as_numerical=resolved["treat_all_integers_as_numerical"], - numerical_imputation=resolved["numerical_imputation"], - categorical_imputation=resolved["categorical_imputation"], - add_missing_indicator=resolved["add_missing_indicator"], - missing_policy=resolved["missing_policy"], - verbose=resolved["verbose"], - ) + config = self._fit_config(resolved) + + if config.feature_groups: + group_frame = to_dataframe(X) + group_numerical, _ = detect_column_types( + group_frame, + cat_cutoff=resolved["cat_cutoff"], + treat_all_integers_as_numerical=resolved["treat_all_integers_as_numerical"], + estimator_name=type(self).__name__, + ) + config.validate_feature_groups(group_frame.columns, group_numerical, y=y) + with_string_labels(group_frame) fitted_on_array = not has_column_labels(X) X = to_dataframe(X) - if self.feature_preprocessing: - unknown_features = set(self.feature_preprocessing) - set(X.columns) - if unknown_features: - raise invalid_param_error( - type(self).__name__, - "feature_preprocessing", - sorted(unknown_features), - "every key must name a column present in X", - valid=X.columns, - ) + self._validate_feature_overrides(X) if self.missing_policy == "error": self._reject_missing(X) @@ -653,25 +669,8 @@ def fit(self, X, y=None, embeddings=None): numeric_values[:, np.isnan(numeric_values).all(axis=0)] = 0.0 apply_constant_policy(numeric_values, self.policy_, estimator=self) - valid_formats = ("auto", "dense", "sparse") - if self.output_format not in valid_formats: - raise invalid_param_error( - type(self).__name__, - "output_format", - self.output_format, - "must be one of 'auto', 'dense', 'sparse'", - valid=set(valid_formats), - ) - - valid_structures = ("matrix", "blocks") - if self.output_structure not in valid_structures: - raise invalid_param_error( - type(self).__name__, - "output_structure", - self.output_structure, - "must be one of 'matrix', 'blocks'", - valid=set(valid_structures), - ) + self._validate_fit_output() + fit_summary = self._resolved_config_summary(resolved, config, numerical_features=numerical_features) # Ask ColumnTransformer to assemble the representation in the requested # container whenever its component outputs permit it. In particular, @@ -683,6 +682,7 @@ def fit(self, X, y=None, embeddings=None): categorical_features, sparse_threshold=sparse_threshold, ) + vars(self).pop("_fit_config_", None) # The Preprocessor wraps its own output (set_output / output_format), so the # internal steps always produce plain arrays. Otherwise a global # ``sklearn.set_config(transform_output="pandas")`` reaches them and the @@ -691,6 +691,7 @@ def fit(self, X, y=None, embeddings=None): # ColumnTransformer.fit runs fit_transform internally; keep the training # output to resolve output_format="auto" once, from the training density. X_ct = self._column_transformer_input(X) + self._check_placement_target(self.column_transformer_, y, config.task, resolved["task_validation"], len(X_ct)) try: training_output = self.column_transformer_.fit_transform(X_ct, y) except ValueError as exc: @@ -709,6 +710,13 @@ def fit(self, X, y=None, embeddings=None): self._enforce_output_budget(X.shape[0]) + if config.feature_groups: + for block in _iter_fitted_blocks(self.column_transformer_): + if block.group_id is not None: + leaf = representation_leaf(block.transformer) + if isinstance(leaf, TensorProductSplineTransformer): + leaf._penalty_source_axes_ = tuple(block.columns) + if verbose >= 1: numerical_summary = _method_summary(numerical_features, is_numerical=True, config=config) categorical_summary = _method_summary(categorical_features, is_numerical=False, config=config) @@ -728,6 +736,7 @@ def fit(self, X, y=None, embeddings=None): if verbose >= 3: self._log_internal_decisions() + self._fit_config_ = fit_summary return self def transform(self, X, embeddings=None, return_array=None): @@ -773,7 +782,7 @@ def transform(self, X, embeddings=None, return_array=None): ------ PretabDataError If input matched by position has a different number of columns than - ``n_features_in_``: it could never be routed correctly. + ``n_features_in_``, or named input is missing a fitted group source. """ check_is_fitted(self) @@ -839,6 +848,84 @@ def fit_transform(self, X, y=None, embeddings=None, return_array=None): return self.fit(X, y, embeddings=embeddings).transform(X, embeddings, return_array) + @staticmethod + def _fit_config(resolved): + return PreprocessorConfig.from_params( + **{field.name: resolved[field.name] for field in fields(PreprocessorConfig)} + ) + + def _validate_feature_overrides(self, frame): + if self.feature_preprocessing: + unknown_features = set(self.feature_preprocessing) - set(frame.columns) + if unknown_features: + raise invalid_param_error( + type(self).__name__, + "feature_preprocessing", + sorted(unknown_features), + "every key must name a column present in X", + valid=frame.columns, + ) + + def _validate_fit_output(self): + valid_formats = ("auto", "dense", "sparse") + if self.output_format not in valid_formats: + raise invalid_param_error( + type(self).__name__, + "output_format", + self.output_format, + "must be one of 'auto', 'dense', 'sparse'", + valid=set(valid_formats), + ) + + valid_structures = ("matrix", "blocks") + if self.output_structure not in valid_structures: + raise invalid_param_error( + type(self).__name__, + "output_structure", + self.output_structure, + "must be one of 'matrix', 'blocks'", + valid=set(valid_structures), + ) + + def _check_placement_target(self, transformer, y, task, mode, n_samples, *, estimator=None): + if mode == "off" or y is None: + return + blocks = transformer.get_params(deep=False)["transformers"] + if any(_block_uses_task(block) for _, block, _ in blocks): + _check_task_target_once( + y, + task=task, + mode=mode, + estimator=estimator or type(self).__name__, + role="target-aware placement", + n_samples=n_samples, + ) + + def _preflight_task_target(self, X, y, *, outer_mode="off", owner=None): + """Check active placement contracts on a wrapper's full input before it fits clones.""" + _validate_task_validation(self.task_validation, type(self).__name__) + if y is None or (self.task_validation == "off" and outer_mode == "off"): + return + resolved = self._resolved_params() + config = self._fit_config(resolved) + frame = to_dataframe(X) + self._validate_feature_overrides(frame) + if self.missing_policy == "error": + self._reject_missing(frame) + numerical, categorical = detect_column_types( + frame, + cat_cutoff=config.cat_cutoff, + treat_all_integers_as_numerical=config.treat_all_integers_as_numerical, + estimator_name=type(self).__name__, + ) + if config.feature_groups: + config.validate_feature_groups(frame.columns, numerical, y=y) + with_string_labels(frame) + self._validate_fit_output() + transformer = build_column_transformer(config, numerical, categorical) + self._check_placement_target(transformer, y, config.task, outer_mode, len(frame), estimator=owner) + self._check_placement_target(transformer, y, config.task, resolved["task_validation"], len(frame)) + def _resolved_params(self): """Return the effective parameters after expanding ``preset``. @@ -860,6 +947,7 @@ def _resolved_params(self): """ params = self.get_params(deep=False) preset = params.pop("preset", None) + _validate_task_validation(params["task_validation"], type(self).__name__) resolved = {key: (_PRESET_PARAM_DEFAULTS[key] if value is UNSET else value) for key, value in params.items()} validate_task(resolved["task"], type(self).__name__) if preset is None: @@ -884,10 +972,16 @@ def get_resolved_config(self): When ``preset`` is set, its bundled values fill in every parameter the caller left at its default while explicitly-set parameters win; the - ``preset`` key itself is removed. When ``preset`` is ``None`` this is simply - :meth:`get_params` without the ``preset`` entry. The returned dict is the - configuration ``fit`` builds from, so it makes a preset's effect inspectable - before fitting. + ``preset`` key itself is removed. Declared ``feature_preprocessing`` + entries become ordinary mappings with canonical methods and applicable + inherited settings, using the same resolver as fitting. Explicit + ``feature_groups`` become an ordered list of mappings with original + source labels and resolved representation settings. Other global keys + retain their preset-expanded values. + + The result is detached from caller-owned containers and resolves current + parameters before or after fit. It does not describe the last fitted + graph, infer an input schema, or guarantee realized output widths. Returns ------- @@ -897,9 +991,34 @@ def get_resolved_config(self): Raises ------ InvalidParamError - If ``task`` or ``preset`` is invalid, exactly as ``fit`` would raise. + If ``task``, ``task_validation``, ``preset``, or a declared representation is invalid. """ - return self._resolved_params() + resolved = self._resolved_params() + if resolved["feature_preprocessing"] or resolved["feature_groups"] is not None: + return self._resolved_config_summary(resolved, self._fit_config(resolved)) + return copy.deepcopy(resolved) + + @staticmethod + def _resolved_config_summary(resolved, config: PreprocessorConfig, *, numerical_features=None): + resolved = dict(resolved) + if resolved["feature_preprocessing"]: + numerical = None if numerical_features is None else set(numerical_features) + resolved["feature_preprocessing"] = { + feature: config.representation_for( + feature, is_numerical=None if numerical is None else feature in numerical + ).to_dict() + for feature in config.feature_preprocessing + } + if resolved["feature_groups"] is not None: + resolved["feature_groups"] = [ + { + "name": group.name, + "columns": list(group.columns), + "representation": config.group_representation_for(group).to_dict(), + } + for group in config.feature_groups + ] + return copy.deepcopy(resolved) def get_feature_names_out(self, input_features=None): """ @@ -977,31 +1096,34 @@ def total_output_dim_(self) -> int: @property def output_dims_(self) -> dict: - """Per-feature expanded output-column counts. + """Expanded output-column counts per single feature or group. Fitted attribute (available only after ``fit``). Maps each input feature - (by name) to the number of columns it contributes to the transformed - array, complementing the scalar :attr:`total_output_dim_`. The values sum + (by name), or each ``group_`` block, to its actual transformed width, + complementing the scalar :attr:`total_output_dim_`. Group members do not + receive separate widths. The values sum to :attr:`total_output_dim_`. Useful when features get different ``output_dim`` values (via ``feature_preprocessing``) or expand to a non-uniform width (e.g. one-hot encoded categoricals). """ check_is_fitted(self) column_transformer = self.column_transformer_ - output_indices = column_transformer.output_indices_ input_labels = self._input_labels() dims: dict = {} - for name, _transformer, columns in column_transformer.transformers_: - span = output_indices[name] + for block in _iter_fitted_blocks(column_transformer): + span = block.span width = span.stop - span.start if width == 0: continue - if name == "remainder": + if block.group_id is not None: + dims[block.group_id] = width + elif block.step_name == "remainder": # Passthrough columns: one output column per untransformed feature. for full in column_transformer.get_feature_names_out()[span]: feature = full.split("__", 1)[-1] if "__" in full else full dims[feature] = dims.get(feature, 0) + 1 else: + columns = block.columns dims[input_labels.get(columns[0], columns[0])] = width return dims @@ -1021,7 +1143,8 @@ def _align_input(self, X): ------ PretabDataError If array-like input matched by position has a different number of - columns than seen during ``fit``: it could never be routed correctly. + columns than seen during ``fit``, or named input omits a fitted group + source. Group errors identify the group and original missing labels. """ # Synthetic labels mark an array fit only when no input feature names were recorded. fitted_labels = getattr(self.column_transformer_, "feature_names_in_", None) @@ -1034,6 +1157,18 @@ def _align_input(self, X): is_array = not has_column_labels(X) X = to_dataframe(X, copy=True) if not (is_array or (fitted_on_array and list(X.columns) != positional_labels)): + available = {str(column) for column in X.columns} + for block in _iter_fitted_blocks(self.column_transformer_): + if block.group_id is None: + continue + missing = tuple(column for column in block.columns if str(column) not in available) + if missing: + labels = self._input_labels() + sources = tuple(labels.get(column, column) for column in missing) + raise PretabDataError( + f"Feature group {block.group_id!r} is missing sources {sources!r} " + "required by the fitted representation." + ) return X if X.shape[1] != self.n_features_in_: raise PretabDataError( @@ -1135,6 +1270,9 @@ def _cross_fit_fold(self, X, y): the fold. Column types, target-free blocks and their vocabularies, and preprocessing before the representation (imputers and scalers) are shared with this all-data fit. Missing-indicator branches are shared too. + A feature group is one block: its ordered source columns use the same + fitted prefix, and only its target-consuming joint representation is + refit for the fold. An out-of-fold row is encoded exactly like ``transform`` encodes it, except that no target-aware placement has seen that row's target. Refitting the whole preprocessor per fold would @@ -1149,16 +1287,17 @@ def _cross_fit_fold(self, X, y): X_ct = self._column_transformer_input(self._align_input(X)) column_transformer = copy.copy(self.column_transformer_) column_transformer.transformers_ = [] - for name, transformer, columns in self.column_transformer_.transformers_: + for block in _iter_fitted_blocks(self.column_transformer_): + name, transformer, columns = block.step_name, block.transformer, block.columns fold_transformer = transformer if name != "remainder" and block_uses_target(transformer): fold_transformer = refit_block_representation(transformer, X_ct[list(columns)], y) - span = self.column_transformer_.output_indices_[name] + span = block.span expected_width = span.stop - span.start width = len(fold_transformer.get_feature_names_out(list(columns))) if width != expected_width: raise IncompatibleParamsError( - f"Cross-fitting requires a fixed output width for block {block_name(name, columns)!r}; " + f"Cross-fitting requires a fixed output width for block {block.public_name!r}; " f"expected {expected_width}, got {width}. The block's width depends on the training rows; " "configure the representation to produce the same columns on every fold." ) @@ -1178,40 +1317,56 @@ def _reject_missing(self, X) -> None: ) def _raise_for_empty_features(self, X, y, empty_features, config) -> None: - """Name the empty feature behind a failed ``fit``, if one is to blame. + """Name the empty sources behind a failed ``fit``, if they are to blame. - Called when fitting the ColumnTransformer failed. The block of each feature - without an observed value is refitted on its own, and the first that fails - raises a :class:`~pretab.exceptions.PretabDataError` naming that feature, + Called when fitting the ColumnTransformer failed. Each block containing + a source without an observed value is refitted on its own, and the first + that fails raises a :class:`~pretab.exceptions.PretabDataError` naming its + empty sources and, for a group, the declared group and representation, chained to the block's own error: methods that cannot be fitted on a constant column (e.g. the B/M/I and cubic splines, Box-Cox) otherwise only report "the feature at index 0". A block is only blamed when it fits a - stand-in column of distinct observed values with the same ``y``, so a + stand-in frame with distinct observed values for all empty sources and the same ``y``, so a failure with another cause (e.g. a ``y`` of the wrong length) is not attributed to the empty column. Returns without raising when no empty column is to blame, so the caller re-raises the original error. """ empty = {str(feature): feature for feature in empty_features} + groups = {tuple(str(column) for column in group.columns): group for group in config.feature_groups} for _name, transformer, columns in self.column_transformer_.transformers: - if columns[0] not in empty: + empty_columns = tuple(column for column in columns if column in empty) + if not empty_columns: continue - feature = empty[columns[0]] - is_numerical = feature in self.numerical_features_ try: cast(TransformerLike, clone(transformer)).fit(X[columns], y) except PretabConfigError: continue # a configuration problem, not one of the empty column except ValueError as exc: stand_in = X[columns].copy() - stand_in[columns[0]] = ( - np.linspace(1.0, 2.0, len(X)) - if is_numerical - else np.resize(np.array(["a", "b"], dtype=object), len(X)) - ) + for column in empty_columns: + stand_in[column] = ( + np.linspace(1.0, 2.0, len(X)) + if empty[column] in self.numerical_features_ + else np.resize(np.array(["a", "b"], dtype=object), len(X)) + ) try: cast(TransformerLike, clone(transformer)).fit(stand_in, y) except ValueError: continue # the block fails with observed values too: not the emptiness + group = groups.get(tuple(columns)) + if group is not None: + labels = self._input_labels() + sources = tuple(labels.get(column, column) for column in columns) + missing = tuple(empty[column] for column in empty_columns) + raise PretabDataError( + f"Feature group {'group_' + group.name!r} with sources {sources!r} has no observed " + f"(non-missing) value at fit for sources {missing!r}, and its {group.representation.method!r} " + f"representation cannot be fitted on such data: {exc}\n" + "Fix: fit on data where these sources are observed, or change the group's columns or " + "representation via feature_groups." + ) from exc + feature = empty[empty_columns[0]] + is_numerical = feature in self.numerical_features_ method = config.method_for(feature, is_numerical=is_numerical) raise PretabDataError( f"Column {feature!r} has no observed (non-missing) value at fit, and its {method!r} " @@ -1248,10 +1403,21 @@ def _enforce_output_budget(self, n_rows: int) -> None: violations.append(f"total output columns ({total}) exceed max_output_features ({self.max_output_features})") if self.max_features_per_input is not None: + input_labels = self._input_labels() + group_sources = { + block.group_id: tuple(input_labels.get(column, column) for column in block.columns) + for block in _iter_fitted_blocks(self.column_transformer_) + if block.group_id is not None + } for feature, width in self.output_dims_.items(): if width > self.max_features_per_input: + unit = ( + f"group {feature!r} with sources {group_sources[feature]!r}" + if feature in group_sources + else f"feature {feature!r}" + ) violations.append( - f"feature {feature!r} expands to {width} columns, " + f"{unit} expands to {width} columns, " f"exceeding max_features_per_input ({self.max_features_per_input})" ) @@ -1287,14 +1453,18 @@ def get_feature_info(self, verbose=True): verbose : bool, default=True If True, renders an aligned per-feature table through the ``pretab`` logger (attaching a stream handler when no host handler receives its - records), without lowering a more verbose level set earlier. If False, - the info dicts are returned silently. + records), without lowering a more verbose level set earlier. The + table is followed by the recorded fit-time settings for declared + feature overrides and groups, or an explicit notice for older fits + without that record. If False, the info dicts are returned silently. Returns ------- tuple of dicts numerical_feature_info : dict - Metadata for numerical features. + Metadata for numerical singles and groups. Each group appears + once under ``group_`` with its actual joint dimension, + ``group`` name, and ordered original-label ``source_features``. categorical_feature_info : dict Metadata for categorical features. embedding_feature_info : dict @@ -1310,6 +1480,9 @@ def get_feature_info(self, verbose=True): ) input_labels = self._input_labels() numerical_feature_info = {input_labels.get(key, key): info for key, info in numerical_feature_info.items()} + for info in numerical_feature_info.values(): + if "group" in info: + info["source_features"] = tuple(input_labels.get(column, column) for column in info["source_features"]) categorical_feature_info = {input_labels.get(key, key): info for key, info in categorical_feature_info.items()} if verbose: @@ -1321,14 +1494,16 @@ def get_feature_info(self, verbose=True): embedding_feature_info, ): logger.info(line) + for line in _build_effective_settings_summary(getattr(self, "_fit_config_", None)): + logger.info(line) return numerical_feature_info, categorical_feature_info, embedding_feature_info def _log_internal_decisions(self): """Log fitted internal decisions (bins / knots / centers) at DEBUG.""" - for step_name, transformer, columns in self.column_transformer_.transformers_: - name = block_name(step_name, columns) - last_step = representation_leaf(transformer) + for block in _iter_fitted_blocks(self.column_transformer_): + name = block.public_name + last_step = representation_leaf(block.transformer) for attr in ( "thresholds_", "knots_", @@ -1352,6 +1527,12 @@ def to_spec(self, path=None) -> dict: Only load specs from trusted sources. Third-party representations and pretrained language models are not supported by this serializer. + ``params`` describes the current constructor request. When recorded at + fit, ``resolved_config`` describes the settings used for the fitted + graph. Output dimensions and lineage describe fitted output, including + indicator columns. Supported fitted penalties are summarized without + their matrices; the encoded ``state`` remains the source for replay. + Parameters ---------- path : str, os.PathLike, or None, default=None @@ -1399,6 +1580,15 @@ def from_spec(cls, source) -> "Preprocessor": Preprocessor A fitted preprocessor equivalent to the one that produced the spec; ``transform`` reproduces the original output bit-for-bit. + + Raises + ------ + PretabSerializationError + If recorded widths, configuration, or group layout disagree with + the stored state or feature names. These checks do not authenticate + the spec; only load specs from trusted sources. + OptionalDependencyError + If the spec explicitly requests Polars output and Polars is unavailable. """ if isinstance(source, dict): data = source @@ -1415,7 +1605,7 @@ def from_spec(cls, source) -> "Preprocessor": # --- Fingerprint & reproducibility --- def _canonical_spec(self) -> dict: """Deterministic subset of the spec used for fingerprinting.""" - spec = preprocessor_to_spec(self) + spec = preprocessor_to_spec(self, include_fitted_metadata=False) # Runtime reports and advisory lifecycle flags do not change the fitted # representation. Keep them in serialization, but out of its identity. state = { @@ -1423,6 +1613,11 @@ def _canonical_spec(self) -> dict: for key, value in spec["state"].items() if key not in {"output_report_", "_frozen", "_stale_reason"} } + if not getattr(self, "feature_groups", None): + state.pop("feature_groups", None) + if state.get("task_validation") == "off": + state.pop("task_validation") + _canonicalize_feature_fingerprint(state, self.feature_preprocessing) return { "schema_version": spec["schema_version"], "pretab_version": spec["pretab_version"], @@ -1441,6 +1636,11 @@ def fingerprint_(self) -> str: categories). The digest is deterministic across processes and machines, so the same fitted state and configuration produce the same fingerprint. + A method-only per-feature mapping or :class:`RepresentationConfig` can + match its legacy string when the spelling, override order, and fitted + settings agree. Named fields within a structured override are unordered; + the order of per-feature overrides and of group declarations still matters. + Raises ------ PretabSerializationError @@ -1457,15 +1657,29 @@ def reproducibility_report(self) -> dict: ------- dict Fingerprint, schema / library versions, random seed, output dtype and - format, input/output widths, and the per-feature representation - families -- everything needed to audit or reproduce the fit. + format, input/output widths, and representation families keyed by + source or public group key. Active groups also have a ``feature_groups`` + mapping with canonical string ``source_features``, actual full-block + ``dimension`` (including raw indicators), and half-open ``output_slice``. + Group metadata comes from the fitted graph, not current requests. """ check_is_fitted(self) - spec = preprocessor_to_spec(self) + spec = preprocessor_to_spec(self, include_fitted_metadata=False) representations = { - entry["columns"][0]: entry.get("family") for entry in spec["representations"] if entry.get("columns") + entry.get("group_id", entry["columns"][0]): entry.get("family") + for entry in spec["representations"] + if entry.get("columns") } - return { + groups = { + entry["group_id"]: { + "source_features": entry["columns"], + "dimension": entry["dimension"], + "output_slice": entry["output_slice"], + } + for entry in spec["representations"] + if "group_id" in entry + } + report = { "fingerprint": self.fingerprint_, "schema_version": SCHEMA_VERSION, "pretab_version": spec["pretab_version"], @@ -1477,6 +1691,9 @@ def reproducibility_report(self) -> dict: "n_output_features": len(spec["feature_names_out"]), "representations": representations, } + if groups: + report["feature_groups"] = groups + return report # --- Immutable lifecycle --- @property @@ -1497,11 +1714,20 @@ def is_frozen(self) -> bool: return bool(getattr(self, "_frozen", False)) def freeze(self) -> "Preprocessor": - """Freeze the fitted preprocessor, blocking ``fit`` and ``set_params`` mutation. + """Freeze the fitted preprocessor against mutation. + + Blocks ``fit``, ``set_params``, and changes through ``set_output``. + ``set_output(transform=None)`` and repeating an explicitly configured + output format remain no-ops. Returns ``self`` for chaining. A frozen preprocessor is intended as an immutable deployment artifact; use :meth:`clone_unfitted` or :meth:`refit` to obtain a fresh, mutable estimator. + + Global sklearn output configuration remains external to the frozen state: + it can change the returned container without changing the fingerprint. + Call ``set_output(transform="default")`` (or another supported format) + before freezing to pin the container independently of global settings. """ check_is_fitted(self) self._frozen = True @@ -1543,3 +1769,20 @@ def set_params(self, **params): "Use clone_unfitted() for a mutable copy, or refit() to fit fresh data." ) return super().set_params(**params) + + def set_output(self, *, transform=None): + """Set sklearn output wrapping, refusing changes on a frozen preprocessor. + + ``transform`` accepts ``"default"``, ``"pandas"``, ``"polars"``, or + ``None`` with sklearn's usual semantics. ``None`` leaves the setting + unchanged; repeating an explicit instance setting is also a no-op. + """ + if transform is not None and self.is_frozen(): + configured = getattr(self, "_sklearn_output_config", {}).get("transform") + if transform != configured: + raise FrozenRepresentationError( + f"Cannot set_output(transform={transform!r}) on a frozen {type(self).__name__}. " + "Use clone_unfitted() for a mutable copy, or refit() to fit fresh data." + ) + transform = None + return super().set_output(transform=transform) diff --git a/pyproject.toml b/pyproject.toml index 37192d1..a4a77a9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -9,7 +9,7 @@ authors = [ ] readme = "README.md" license = "MIT" -requires-python = ">=3.10,<3.14" +requires-python = ">=3.11,<3.14" dynamic = ["dependencies"] [project.optional-dependencies] @@ -41,6 +41,7 @@ scipy = ">=1.10,<2.0" [tool.poetry.group.dev.dependencies] pytest = "^9.0" pytest-cov = "^4.1" +jsonschema = "^4.26" ruff = "0.15.12" # keep in sync with .pre-commit-config.yaml ruff rev pre-commit = "^3.6" commitizen = "^3.29.1" @@ -95,7 +96,7 @@ exclude = [ "examples", ] -pythonVersion = "3.10" +pythonVersion = "3.11" typeCheckingMode = "basic" venvPath = "." venv = ".venv" @@ -111,7 +112,7 @@ reportUnsupportedDunderAll = false # Configure code linting [tool.ruff] line-length = 120 -target-version = "py310" +target-version = "py311" exclude = ["*.ipynb"] [tool.ruff.lint] diff --git a/scripts/make_deeptab_contract.py b/scripts/make_deeptab_contract.py new file mode 100644 index 0000000..a0b06e2 --- /dev/null +++ b/scripts/make_deeptab_contract.py @@ -0,0 +1,148 @@ +"""Generate synthetic DeepTab contract fixtures: python -m scripts.make_deeptab_contract.""" + +import argparse +import hashlib +import json +import platform +from dataclasses import dataclass +from importlib.metadata import PackageNotFoundError, version +from pathlib import Path +from typing import Any + +import numpy as np +import pandas as pd +from scipy import sparse + +import pretab + +FIXTURE_DIR = Path(__file__).resolve().parents[1] / "tests/integration/_fixtures/deeptab_contract/v1" +TOLERANCES = {"atol": 1e-9, "rtol": 1e-7} + + +@dataclass(frozen=True) +class ContractCase: + fit_data: pd.DataFrame + probe_data: pd.DataFrame + config: dict[str, Any] + target: np.ndarray | None = None + + +def contract_cases() -> dict[str, ContractCase]: + base = {"numerical_method": "minmax", "categorical_method": "one-hot", "output_structure": "matrix"} + reading = np.arange(32, dtype=np.float64) + target = reading / 100 + (reading >= 8) + 3 * (reading >= 16) + 2 * (reading >= 24) + return { + "dense_numeric_boolean": ContractCase( + pd.DataFrame({"level": [0.0, 2.0, 4.0, 6.0], "flag": [True, False, True, False]}), + pd.DataFrame({"level": [1.0, 5.0], "flag": [False, True]}), + {**base, "output_format": "dense"}, + ), + "sparse_unknown_missing": ContractCase( + pd.DataFrame({"level": [0.0, 2.0, 4.0, 6.0], "city": pd.Series(["a", "b", None, "a"], dtype=object)}), + pd.DataFrame({"level": [1.0, np.nan, 5.0], "city": pd.Series(["new", None, "a"], dtype=object)}), + {**base, "output_format": "sparse", "missing_policy": "separate_state"}, + ), + "dense_blocks_adaptive": ContractCase( + pd.DataFrame({"reading": reading, "city": pd.Series(["a", "b"] * 16, dtype=object)}), + pd.DataFrame({"reading": [2.0, 15.0, 29.0], "city": pd.Series(["a", "b", "a"], dtype=object)}), + { + "output_structure": "blocks", + "output_format": "dense", + "categorical_method": "one-hot", + "feature_preprocessing": {"reading": {"method": "rbf", "output_dim": 12, "adaptive": True}}, + "min_output_dim": 3, + "max_output_dim": 4, + "target_aware": True, + "placement_strategy": "cart", + "random_state": 17, + }, + target, + ), + } + + +def _encode_config(config: dict[str, Any]) -> dict[str, Any]: + encoded = config.copy() + if encoded.get("feature_preprocessing") is not None: + encoded["feature_preprocessing"] = [ + {"feature": feature, "settings": settings} for feature, settings in encoded["feature_preprocessing"].items() + ] + return encoded + + +def _source_digest() -> str: + root = Path(pretab.__file__).resolve().parent + digest = hashlib.sha256() + for source in sorted(root.rglob("*.py")): + digest.update(source.relative_to(root).as_posix().encode("utf-8") + b"\0") + digest.update(source.read_bytes() + b"\0") + return digest.hexdigest() + + +def _optional_version(distribution: str) -> str | None: + try: + return version(distribution) + except PackageNotFoundError: + return None + + +def fixture_environment() -> dict[str, str | None]: + return { + "python": platform.python_version(), + "pretab": pretab.__version__, + "numpy": version("numpy"), + "pandas": version("pandas"), + "scipy": version("scipy"), + "scikit_learn": version("scikit-learn"), + "polars": _optional_version("polars"), + "pyarrow": _optional_version("pyarrow"), + "platform": platform.platform(), + "pretab_source_sha256": _source_digest(), + } + + +def capture_fixture(case_id: str, case: ContractCase, environment: dict[str, str | None]) -> dict[str, Any]: + estimator = pretab.Preprocessor(**case.config).fit(case.fit_data, case.target) + blocks = estimator.transform(case.probe_data, return_array=False) + if not isinstance(blocks, dict): + raise TypeError(f"{case_id}: expected a mapping of transformed blocks") + samples = np.concatenate( + [block.toarray() if sparse.issparse(block) else np.asarray(block) for block in blocks.values()], axis=1 + ) + feature_info = estimator.get_feature_info(verbose=False) + return { + "schema_version": 1, + "case_id": case_id, + "input_schema": { + "container": "pandas", + "columns": [{"name": label, "dtype": str(dtype)} for label, dtype in case.fit_data.dtypes.items()], + }, + "constructor_config": _encode_config(case.config), + "resolved_config": _encode_config(estimator.get_resolved_config()), + "output_feature_names": estimator.get_feature_names_out().tolist(), + "block_widths": [{"name": name, "width": block.shape[1]} for name, block in blocks.items()], + "feature_info_dimensions": { + kind: {name: info["dimension"] for name, info in entries.items()} + for kind, entries in zip(("numerical", "categorical", "embedding"), feature_info, strict=True) + }, + "fingerprint": estimator.fingerprint_, + "transformed_rows": [{"row_index": index, "values": row} for index, row in enumerate(samples.tolist())], + "tolerances": TOLERANCES.copy(), + "library_versions": environment.copy(), + } + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output-dir", type=Path, default=FIXTURE_DIR) + output_dir = parser.parse_args().output_dir + environment = fixture_environment() + output_dir.mkdir(parents=True, exist_ok=True) + for case_id, case in contract_cases().items(): + fixture = capture_fixture(case_id, case, environment) + path = output_dir / f"{case_id}.json" + path.write_text(json.dumps(fixture, allow_nan=False, indent=2, sort_keys=True) + "\n", encoding="utf-8") + + +if __name__ == "__main__": + main() diff --git a/tests/compose/test_block_layout_contract.py b/tests/compose/test_block_layout_contract.py new file mode 100644 index 0000000..dd2ddb9 --- /dev/null +++ b/tests/compose/test_block_layout_contract.py @@ -0,0 +1,601 @@ +"""Agreement between fitted block spans and the public output-layout APIs.""" + +import json +import warnings +from contextlib import nullcontext +from unittest.mock import Mock + +import numpy as np +import pandas as pd +import pytest +from scipy import sparse +from sklearn.base import clone +from sklearn.pipeline import FeatureUnion, Pipeline +from sklearn.utils.validation import check_is_fitted + +from pretab import BaseRepresentation, Preprocessor, RepresentationConfig, register_representation +from pretab.compose import registry +from pretab.compose.inspection import block_name, build_feature_lineage, get_output_slices +from pretab.embedding.language import LanguageEmbeddingTransformer +from pretab.exceptions import ConfigWarning, IncompatibleParamsError, OutputBudgetError + + +class _PositiveOnly(BaseRepresentation): + representation_name = "layout_positive_only" + feature_kind = "numerical" + + def fit(self, X, y=None): + self._validate(X, reset=True) + return self + + def transform(self, X): + check_is_fitted(self, "n_features_in_") + values = self._validate(X, reset=False) + if np.any(values <= 0): + raise ValueError("Positive input required") + return np.log(values) + + def _output_sizes(self): + return [1] * self.n_features_in_ + + +@pytest.fixture +def positive_only_method(): + saved_registry = dict(registry.TRANSFORMER_REGISTRY) + saved_numerical = dict(registry.NUMERICAL_METHODS) + saved_categorical = set(registry.CATEGORICAL_METHODS) + try: + register_representation("layout_positive_only", _PositiveOnly) + yield "layout_positive_only" + finally: + registry.TRANSFORMER_REGISTRY.clear() + registry.TRANSFORMER_REGISTRY.update(saved_registry) + registry.NUMERICAL_METHODS.clear() + registry.NUMERICAL_METHODS.update(saved_numerical) + registry.CATEGORICAL_METHODS.clear() + registry.CATEGORICAL_METHODS.update(saved_categorical) + + +@pytest.fixture +def layout_data(): + values = np.linspace(1.0, 9.0, 80) + frame = pd.DataFrame( + { + "value": values, + "other": values**2, + "city": np.resize(["Rome", "Oslo", "Berlin", "Rome"], len(values)), + } + ) + frame.loc[[3, 11], "value"] = np.nan + frame.loc[[5, 17], "city"] = np.nan + return frame, np.sin(values) + + +def _dense(values): + return values.toarray() if sparse.issparse(values) else np.asarray(values) + + +def _assert_block_layout(preprocessor, frame, *, embeddings=None): + transformed = ( + preprocessor.transform(frame, return_array=True) + if embeddings is None + else preprocessor.column_transformer_.transform(frame) + ) + blocks = preprocessor.transform(frame, embeddings=embeddings, return_array=False) + assert isinstance(blocks, dict) + names = preprocessor.get_feature_names_out() + lineage = build_feature_lineage(preprocessor.column_transformer_) + assert lineage == preprocessor.get_feature_lineage() + numerical, categorical, embedding_info = preprocessor.get_feature_info(verbose=False) + assert embedding_info == { + name: {"preprocessing": None, "dimension": width, "categories": None} + for name, width in preprocessor.embedding_dimensions_.items() + } + metadata = {**numerical, **categorical} + dimensions = preprocessor.output_dims_ + slices = get_output_slices(preprocessor.column_transformer_) + sources = { + block_name(name, columns): str(columns[0]) + for name, transformer, columns in preprocessor.column_transformer_.transformers_ + if transformer != "drop" and len(columns) == 1 + } + + assert list(blocks) == [name for name, _, _ in slices] + list(embedding_info) + assert [record.output_index for record in lineage] == list(range(len(names))) + assert [record.output_feature for record in lineage] == list(names) + offset = 0 + for name, start, width in slices: + source = sources[name] + records = [record for record in lineage if record.source_features == (source,)] + stop = start + width + assert start == offset + assert [record.output_index for record in records] == list(range(start, stop)) + assert [record.output_feature for record in records] == list(names[start:stop]) + assert width == len(records) == len(names[start:stop]) + assert width == dimensions[source] == metadata[source]["dimension"] + assert np.shape(blocks[name]) == (len(frame), width) + np.testing.assert_array_equal(_dense(blocks[name]), _dense(transformed[:, start:stop])) + offset = stop + + assert sum(dimensions.values()) == offset == preprocessor.total_output_dim_ + assert offset == np.shape(transformed)[1] == len(names) == len(lineage) + np.testing.assert_array_equal(np.hstack([_dense(blocks[name]) for name, _, _ in slices]), _dense(transformed)) + + +@pytest.mark.parametrize("output_format", ["dense", "sparse"]) +@pytest.mark.parametrize( + "parameters", + [ + pytest.param({"numerical_method": "bspline", "categorical_method": "one-hot"}, id="spline-onehot"), + pytest.param({"numerical_method": "rbf", "categorical_method": "int"}, id="feature-map-ordinal"), + pytest.param( + {"numerical_method": "ple", "target_aware": True, "placement_strategy": "cart"}, + id="target-aware-ple", + ), + pytest.param( + {"numerical_method": "bspline", "categorical_method": "one-hot", "add_missing_indicator": True}, + id="separate-indicators", + ), + pytest.param( + {"numerical_method": "rbf", "missing_policy": "separate_state"}, + id="separate-state-policy", + ), + pytest.param( + { + "numerical_method": "rbf", + "output_dim": 9, + "adaptive": True, + "min_output_dim": 3, + "max_output_dim": 6, + "target_aware": True, + "placement_strategy": "cart", + }, + id="adaptive-widths", + ), + pytest.param({"numerical_method": "none"}, id="passthrough"), + ], +) +def test_fitted_block_layout_agrees_across_views(layout_data, output_format, parameters): + frame, target = layout_data + options = { + "output_dim": 5, + "adaptive": False, + "target_aware": False, + "placement_strategy": "uniform", + "output_format": output_format, + "random_state": 0, + **parameters, + } + preprocessor = Preprocessor(**options) + Pipeline([("preprocessor", preprocessor)]).fit(frame, target) + + _assert_block_layout(preprocessor, frame) + dimensions = preprocessor.output_dims_ + indicators = options.get("add_missing_indicator", False) or options.get("missing_policy") == "separate_state" + for feature in ("value", "other"): + if options["adaptive"]: + assert 3 <= dimensions[feature] <= 6 + assert dimensions[feature] < options["output_dim"] + else: + expected = 1 if options["numerical_method"] == "none" else options["output_dim"] + has_indicator = indicators and ( + options.get("missing_policy") == "separate_state" or frame[feature].isna().any() + ) + assert dimensions[feature] == expected + int(has_indicator) + category_width = frame["city"].nunique() if options.get("categorical_method") == "one-hot" else 1 + assert dimensions["city"] == category_width + int(indicators) + if indicators: + blocks = preprocessor.transform(frame, return_array=False) + assert isinstance(blocks, dict) + for name, _, _ in get_output_slices(preprocessor.column_transformer_): + assert isinstance(preprocessor.column_transformer_.named_transformers_[name], FeatureUnion) + for name, feature in (("num_value", "value"), ("num_other", "other"), ("cat_city", "city")): + if options.get("missing_policy") == "separate_state" or frame[feature].isna().any(): + np.testing.assert_array_equal(_dense(blocks[name])[:, -1], frame[feature].isna().astype(float)) + + +@pytest.mark.parametrize("method", ["tensorspline", "tprs"]) +@pytest.mark.parametrize("missing", ["none", "observed", "all"]) +@pytest.mark.parametrize("output_format", ["dense", "sparse"]) +@pytest.mark.parametrize("dtype", [np.float32, np.float64]) +def test_grouped_block_layout_agrees_across_views(layout_data, method, missing, output_format, dtype): + frame, target = layout_data + frame = frame.assign(spare=np.linspace(2.0, 7.0, len(frame))) + representation = ( + {"method": method, "output_dim": 3, "degree": 2} + if method == "tensorspline" + else {"method": method, "n_components": 3, "landmark_strategy": "subsample", "random_state": 0} + ) + preprocessor = Preprocessor( + numerical_method="none", + categorical_method="one-hot", + target_aware=False, + placement_strategy="uniform", + add_missing_indicator=missing == "observed", + missing_policy="separate_state" if missing == "all" else None, + output_format=output_format, + output_structure="blocks", + dtype=dtype, + feature_groups={"location": {"columns": ["other", "value"], "representation": representation}}, + ).fit(frame, target) + matrix = preprocessor.transform(frame, return_array=True) + blocks = preprocessor.transform(frame) + assert isinstance(blocks, dict) + assert list(blocks) == ["num_spare", "group_location", "cat_city"] + names = preprocessor.get_feature_names_out() + lineage = preprocessor.get_feature_lineage() + numerical, categorical, embeddings = preprocessor.get_feature_info(verbose=False) + dimensions = preprocessor.output_dims_ + assert list(dimensions) == ["spare", "group_location", "city"] + assert list(numerical) == ["spare", "group_location"] + assert list(categorical) == ["city"] + assert embeddings == {} + assert "location" not in numerical + assert numerical["group_location"]["source_features"] == ("other", "value") + assert [record.output_feature for record in lineage] == list(names) + assert [record.output_index for record in lineage] == list(range(len(names))) + offset = 0 + for (name, start, width), key in zip(get_output_slices(preprocessor.column_transformer_), dimensions, strict=True): + assert start == offset + assert width == dimensions[key] == {**numerical, **categorical}[key]["dimension"] + assert width == len(names[start : start + width]) == np.shape(blocks[name])[1] + np.testing.assert_array_equal(_dense(blocks[name]), _dense(matrix)[:, start : start + width]) + offset += width + assert offset == sum(dimensions.values()) == preprocessor.total_output_dim_ == len(names) == len(lineage) + assert offset == np.shape(matrix)[1] + np.testing.assert_array_equal(np.hstack([_dense(block) for block in blocks.values()]), _dense(matrix)) + span = preprocessor.column_transformer_.output_indices_["group_location"] + records = lineage[span] + basis_width = 9 if method == "tensorspline" else 3 + assert all(record.group_id == "group_location" for record in records) + assert all(record.source_features == ("other", "value") for record in records[:basis_width]) + indicators = records[basis_width:] + expected_sources = {"none": [], "observed": [("value",)], "all": [("other",), ("value",)]}[missing] + assert [record.source_features for record in indicators] == expected_sources + for index, record in enumerate(indicators): + assert record.family == "missing_state" and record.component == "indicator" + assert not record.is_interaction and not record.uses_target + source = record.source_features[0] + np.testing.assert_array_equal(_dense(blocks["group_location"])[:, basis_width + index], frame[source].isna()) + assert dimensions["group_location"] == basis_width + len(expected_sources) + report = preprocessor.reproducibility_report() + assert report["fingerprint"] == preprocessor.fingerprint_ + assert report["n_output_features"] == offset + assert list(report["representations"]) == ["group_location"] + assert report["feature_groups"] == { + "group_location": { + "source_features": ["other", "value"], + "dimension": dimensions["group_location"], + "output_slice": [span.start, span.stop], + } + } + (entry,) = preprocessor.to_spec()["representations"] + assert entry["group_id"] == "group_location" + assert entry["columns"] == ["other", "value"] + assert entry["dimension"] == dimensions["group_location"] + assert entry["output_dim"] == basis_width + assert entry["output_slice"] == [span.start, span.stop] + assert json.loads(json.dumps(report, allow_nan=False)) == report + assert preprocessor.estimate_output_shape(frame) == np.shape(matrix) + assert preprocessor.estimate_memory(frame) == _dense(matrix).nbytes + limits = { + "max_output_features": offset, + "max_features_per_input": dimensions["group_location"], + "max_dense_memory": _dense(matrix).nbytes, + } + bounded = clone(preprocessor) + assert isinstance(bounded, Preprocessor) + bounded.set_params(**limits).fit(frame, target) + assert bounded.output_dims_ == dimensions + np.testing.assert_array_equal(_dense(bounded.transform(frame, return_array=True)), _dense(matrix)) + for budget, limit in limits.items(): + rejected = clone(preprocessor) + assert isinstance(rejected, Preprocessor) + rejected.set_params(**{budget: limit - 1}) + with pytest.raises(OutputBudgetError, match=budget) as failure: + rejected.fit(frame, target) + if budget == "max_features_per_input": + assert str(failure.value).count("group 'group_location'") == 1 + assert "('other', 'value')" in str(failure.value) + + +@pytest.mark.parametrize("method", ["tensorspline", "tprs"]) +@pytest.mark.parametrize("overflow_policy", ["error", "warn", "ignore"]) +def test_group_budget_error_identifies_full_joint_width_and_sources(layout_data, method, overflow_policy): + frame, _ = layout_data + representation = ( + {"method": method, "output_dim": 3, "degree": 2} + if method == "tensorspline" + else {"method": method, "n_components": 3, "landmark_strategy": "subsample", "random_state": 0} + ) + width = 9 if method == "tensorspline" else 3 + preprocessor = Preprocessor( + numerical_method="none", + target_aware=False, + placement_strategy="uniform", + max_features_per_input=width - 1, + overflow_policy=overflow_policy, + feature_groups={"location": {"columns": ["other", "value"], "representation": representation}}, + ) + if overflow_policy == "error": + with pytest.raises(OutputBudgetError) as failure: + preprocessor.fit(frame) + message = str(failure.value) + elif overflow_policy == "warn": + with pytest.warns(ConfigWarning) as caught: + preprocessor.fit(frame) + assert len(caught) == 1 + message = str(caught[0].message) + else: + with warnings.catch_warnings(record=True) as caught: + preprocessor.fit(frame) + assert not caught + assert preprocessor.output_dims_["group_location"] == width + return + assert "group 'group_location'" in message + assert "('other', 'value')" in message + assert f"expands to {width} columns" in message + assert f"max_features_per_input ({width - 1})" in message + assert preprocessor.output_dims_["group_location"] == width + + +def test_group_metadata_preserves_original_integer_labels_and_renamed_display_names(): + frame = pd.DataFrame(np.random.default_rng(42).normal(size=(24, 3)), columns=pd.Index([7, 3, 11])) + preprocessor = Preprocessor( + numerical_method="none", + target_aware=False, + placement_strategy="uniform", + feature_groups={ + "location": { + "columns": [11, 7], + "representation": {"method": "tensorspline", "output_dim": 3, "degree": 2}, + } + }, + ).fit(frame) + assert preprocessor.output_dims_ == {3: 1, "group_location": 9} + numerical, categorical, embeddings = preprocessor.get_feature_info(verbose=False) + assert list(numerical) == [3, "group_location"] + assert numerical["group_location"]["source_features"] == (11, 7) + assert categorical == embeddings == {} + original = preprocessor.get_feature_names_out() + renamed = preprocessor.get_feature_names_out(["west%", "single", "east+"]) + assert all(name.startswith("group_location__east%2B+west%25__") for name in renamed[1:]) + assert len(renamed) == len(original) == preprocessor.total_output_dim_ + np.testing.assert_array_equal(preprocessor.get_feature_names_out(), original) + assert all(record.source_features == ("11", "7") for record in preprocessor.get_feature_lineage()[1:]) + report = preprocessor.reproducibility_report() + assert report["feature_groups"]["group_location"]["source_features"] == ["11", "7"] + bounded = clone(preprocessor) + assert isinstance(bounded, Preprocessor) + bounded.set_params(max_features_per_input=8) + with pytest.raises(OutputBudgetError) as failure: + bounded.fit(frame) + assert "sources (11, 7)" in str(failure.value) + + +@pytest.mark.parametrize("typed", [False, True], ids=["mapping", "value"]) +@pytest.mark.parametrize("output_format", ["dense", "sparse"]) +@pytest.mark.parametrize("missing_policy", [None, "separate_state"]) +@pytest.mark.parametrize("sizing", ["fixed", "adaptive", "clamped"]) +def test_structured_fitted_widths_agree_across_views(layout_data, typed, output_format, missing_policy, sizing): + frame, target = layout_data + requests = { + "value": {"method": "rbf", "output_dim": 12, "adaptive": True} + if sizing == "adaptive" + else {"method": "rbf", "output_dim": 2}, + "other": {"method": "bspline", "output_dim": 3 if sizing == "clamped" else 6, "params": {"degree": 2}}, + "city": {"method": "one-hot", "params": {"drop": "first"}}, + } + preprocessor = Preprocessor( + output_dim=12, + adaptive=True, + min_output_dim=3, + max_output_dim=4, + target_aware=True, + placement_strategy="cart", + random_state=17, + missing_policy=missing_policy, + output_format=output_format, + feature_preprocessing={ + feature: RepresentationConfig.from_dict(settings) if typed else settings + for feature, settings in requests.items() + }, + ) + with pytest.warns(ConfigWarning) if sizing == "clamped" else nullcontext(): + Pipeline([("preprocessor", preprocessor)]).fit(frame, target) + + _assert_block_layout(preprocessor, frame) + indicator = int(missing_policy == "separate_state") + dimensions = preprocessor.output_dims_ + if sizing == "adaptive": + assert 3 <= dimensions["value"] - indicator <= 4 + assert dimensions["value"] - indicator < requests["value"]["output_dim"] + else: + assert dimensions["value"] == 2 + indicator + assert dimensions["other"] == (5 if sizing == "clamped" else 6) + indicator + assert dimensions["city"] == frame["city"].nunique() - 1 + indicator + + names = preprocessor.get_feature_names_out() + transformed = _dense(preprocessor.transform(frame, return_array=True)) + fingerprint = preprocessor.fingerprint_ + report = preprocessor.reproducibility_report() + spec = json.loads(json.dumps(preprocessor.to_spec(), allow_nan=False)) + representations = {entry["columns"][0]: entry for entry in spec["representations"]} + assert set(representations) == {"value", "other"} + for feature, entry in representations.items(): + assert entry["output_dim"] == len(entry["output_features"]) == dimensions[feature] - indicator + assert spec["feature_names_out"] == list(names) + assert report["n_features_in"] == frame.shape[1] + assert report["n_output_features"] == transformed.shape[1] == sum(dimensions.values()) + assert report["fingerprint"] == fingerprint + assert report["representations"] == {feature: entry["family"] for feature, entry in representations.items()} + + restored = Preprocessor.from_spec(spec) + _assert_block_layout(restored, frame) + assert restored.output_dims_ == dimensions + assert restored.get_feature_info(verbose=False) == preprocessor.get_feature_info(verbose=False) + assert restored.get_feature_lineage() == preprocessor.get_feature_lineage() + assert restored.reproducibility_report() == report + assert restored.fingerprint_ == fingerprint + np.testing.assert_array_equal(restored.get_feature_names_out(), names) + np.testing.assert_array_equal(_dense(restored.transform(frame, return_array=True)), transformed) + + assert preprocessor.estimate_output_shape(frame) == transformed.shape + assert preprocessor.estimate_memory(frame) == transformed.nbytes + limits = { + "max_output_features": transformed.shape[1], + "max_features_per_input": max(dimensions.values()), + "max_dense_memory": transformed.nbytes, + } + bounded = clone(preprocessor) + assert isinstance(bounded, Preprocessor) + bounded.set_params(**limits) + with pytest.warns(ConfigWarning) if sizing == "clamped" else nullcontext(): + bounded.fit(frame, target) + _assert_block_layout(bounded, frame) + assert bounded.output_dims_ == dimensions + np.testing.assert_array_equal(_dense(bounded.transform(frame, return_array=True)), transformed) + + expected_details = { + "max_output_features": f"total output columns ({transformed.shape[1]})", + "max_features_per_input": f"feature 'other' expands to {dimensions['other']} columns", + "max_dense_memory": f"needs ~{transformed.nbytes} bytes", + } + for budget, limit in limits.items(): + rejected = clone(preprocessor) + assert isinstance(rejected, Preprocessor) + rejected.set_params(**{budget: limit - 1}) + with pytest.raises(OutputBudgetError, match=budget) as error: + with pytest.warns(ConfigWarning) if sizing == "clamped" else nullcontext(): + rejected.fit(frame, target) + assert expected_details[budget] in str(error.value) + + +@pytest.mark.parametrize("typed", [False, True], ids=["mapping", "value"]) +@pytest.mark.parametrize("output_format", ["dense", "sparse"]) +def test_same_method_widths_2_3_5_match_block_contract(typed, output_format): + frame = pd.DataFrame( + { + "age": np.linspace(18.0, 70.0, 80), + "income": np.linspace(25000.0, 90000.0, 80), + "tenure": np.linspace(0.0, 30.0, 80), + } + ) + requests = { + "age": {"method": "rbf", "output_dim": 2}, + "income": {"method": "rbf", "output_dim": 3}, + "tenure": {"method": "rbf", "output_dim": 5}, + } + preprocessor = Preprocessor( + feature_preprocessing={ + feature: RepresentationConfig.from_dict(settings) if typed else settings + for feature, settings in requests.items() + }, + target_aware=False, + placement_strategy="uniform", + scaling="none", + output_structure="blocks", + output_format=output_format, + ) + Pipeline([("preprocessor", preprocessor)]).fit(frame) + + _assert_block_layout(preprocessor, frame) + assert preprocessor.output_dims_ == {"age": 2, "income": 3, "tenure": 5} + assert preprocessor.total_output_dim_ == 10 + assert get_output_slices(preprocessor.column_transformer_) == [ + ("num_age", 0, 2), + ("num_income", 2, 3), + ("num_tenure", 5, 5), + ] + blocks = preprocessor.transform(frame) + assert isinstance(blocks, dict) + assert {name: np.shape(block) for name, block in blocks.items()} == { + "num_age": (80, 2), + "num_income": (80, 3), + "num_tenure": (80, 5), + } + + +@pytest.mark.parametrize("output_format", ["dense", "sparse"]) +def test_language_embedding_block_layout(layout_data, monkeypatch, output_format): + frame, _ = layout_data + model = Mock() + model.get_sentence_embedding_dimension.return_value = 3 + model.encode.side_effect = lambda values, **kwargs: np.array( + [[len(value), len(set(value)), sum(map(ord, value))] for value in values], dtype=float + ) + monkeypatch.setattr(LanguageEmbeddingTransformer, "_resolve_model", lambda self: model) + preprocessor = Preprocessor( + numerical_method="none", + categorical_method="pretrained", + target_aware=False, + placement_strategy="uniform", + output_format=output_format, + ).fit(frame) + + _assert_block_layout(preprocessor, frame) + + assert preprocessor.output_dims_ == {"value": 1, "other": 1, "city": 3} + embedding_records = [record for record in preprocessor.get_feature_lineage() if record.source_features == ("city",)] + assert len(embedding_records) == 3 + assert all( + record.family == "language_embedding" and record.component == "embedding" for record in embedding_records + ) + model.encode.assert_called() + + +@pytest.mark.parametrize("output_format", ["dense", "sparse"]) +def test_external_embedding_blocks_are_separate_from_column_layout(layout_data, output_format): + frame, _ = layout_data + embeddings = [np.arange(len(frame) * width).reshape(len(frame), width) for width in (2, 4)] + preprocessor = Preprocessor( + numerical_method="none", + target_aware=False, + placement_strategy="uniform", + output_structure="blocks", + output_format=output_format, + ).fit(frame, embeddings=embeddings) + + _assert_block_layout(preprocessor, frame, embeddings=embeddings) + + blocks = preprocessor.transform(frame, embeddings=embeddings) + assert isinstance(blocks, dict) + _, _, metadata = preprocessor.get_feature_info(verbose=False) + for name, values in zip(("embedding_1", "embedding_2"), embeddings, strict=True): + assert metadata[name]["dimension"] == values.shape[1] + np.testing.assert_array_equal(_dense(blocks[name]), values) + assert preprocessor.total_output_dim_ == 3 + assert sum(np.shape(block)[1] for block in blocks.values()) == preprocessor.total_output_dim_ + 6 + with pytest.raises(IncompatibleParamsError, match="dictionary output"): + preprocessor.transform(frame, embeddings=embeddings, return_array=True) + + +@pytest.mark.parametrize("output_format", ["dense", "sparse"]) +def test_positive_only_plugin_layout_does_not_probe_transform(positive_only_method, monkeypatch, output_format): + frame = pd.DataFrame({"value": [1.0, 2.0, 4.0, 8.0], "other": [2.0, 3.0, 5.0, 7.0]}) + preprocessor = Preprocessor( + numerical_method=positive_only_method, + numerical_imputation=None, + target_aware=False, + placement_strategy="uniform", + output_format=output_format, + ) + preprocessor.set_params(scaling=None) + preprocessor.fit(frame) + _assert_block_layout(preprocessor, frame) + expected_names = preprocessor.get_feature_names_out() + expected_lineage = preprocessor.get_feature_lineage() + reject_transform = Mock(side_effect=AssertionError("Layout inspection must not invoke transform")) + for pipeline in preprocessor.column_transformer_.named_transformers_.values(): + monkeypatch.setattr(pipeline.named_steps[positive_only_method], "transform", reject_transform) + + numerical, categorical, embedding_info = preprocessor.get_feature_info(verbose=False) + + assert categorical == embedding_info == {} + assert preprocessor.output_dims_ == {"value": 1, "other": 1} + assert [numerical[feature]["dimension"] for feature in frame] == [1, 1] + assert preprocessor.total_output_dim_ == len(expected_names) == len(expected_lineage) == 2 + assert get_output_slices(preprocessor.column_transformer_) == [("num_value", 0, 1), ("num_other", 1, 1)] + np.testing.assert_array_equal(preprocessor.get_feature_names_out(), expected_names) + assert preprocessor.get_feature_lineage() == expected_lineage + reject_transform.assert_not_called() diff --git a/tests/compose/test_config.py b/tests/compose/test_config.py index 657be4f..d9eb95a 100644 --- a/tests/compose/test_config.py +++ b/tests/compose/test_config.py @@ -1,8 +1,288 @@ """Unit tests for :class:`pretab.compose.config.PreprocessorConfig`.""" +import inspect +import json +from dataclasses import asdict, replace +from typing import Any + +import numpy as np +import pandas as pd import pytest +from sklearn.base import clone +from pretab import Preprocessor, RepresentationConfig +from pretab.compose.config import FeatureGroup +from pretab.compose.registry import TRANSFORMER_REGISTRY +from pretab.core.parameters import UNSET from pretab.exceptions import InvalidParamError +from pretab.preprocessor import PRESETS + + +@pytest.mark.parametrize("task", ["regression", "classification"]) +@pytest.mark.parametrize( + ("preset", "overrides"), + [ + (None, {}), + ("standard", {}), + ("expanded", {"categorical_method": "one-hot", "output_dim": 10}), + ("adaptive", {"adaptive": True, "max_output_dim": 15}), + ], +) +def test_resolved_config_matches_inline_preset_contract(task, preset, overrides): + assert set(PRESETS) == {"standard", "expanded", "adaptive"} + preprocessor = Preprocessor(preset=preset, task=task) + requested = preprocessor.get_params(deep=False) + expected = { + "numerical_method": "bspline" if preset is not None and task == "regression" else "ple", + "categorical_method": "int", + "feature_preprocessing": None, + "output_dim": 7, + "degree": 3, + "target_aware": True, + "placement_strategy": "cart", + "task": task, + "adaptive": False, + "min_output_dim": 7, + "max_output_dim": 10, + "random_state": None, + "scaling": "minmax", + "cat_cutoff": 0.03, + "treat_all_integers_as_numerical": False, + "numerical_imputation": "median", + "categorical_imputation": "most_frequent", + "add_missing_indicator": False, + "missing_policy": None, + "policy": None, + "max_output_features": None, + "max_features_per_input": None, + "max_dense_memory": None, + "overflow_policy": "error", + "output_structure": "matrix", + "output_format": "dense", + "dtype": None, + "verbose": 0, + "feature_groups": None, + "task_validation": "off", + **overrides, + } + + assert preprocessor.get_resolved_config() == expected + assert preprocessor.get_params(deep=False) == requested + assert "preset" not in expected + + +@pytest.mark.parametrize("is_numerical", [False, True]) +@pytest.mark.parametrize("configured_imputation", [False, True]) +@pytest.mark.parametrize( + "missing_policy", [None, "error", "propagate", "impute", "impute_with_indicator", "separate_state"] +) +def test_imputation_plan_routes_policy_and_feature_kind( + make_config, is_numerical, configured_imputation, missing_policy +): + config = make_config( + numerical_imputation="mean" if configured_imputation else None, + categorical_imputation="constant" if configured_imputation else None, + add_missing_indicator=True, + missing_policy=missing_policy, + ) + plans = { + None: (configured_imputation, configured_imputation, not configured_imputation), + "error": (False, False, False), + "propagate": (False, False, False), + "impute": (True, False, False), + "impute_with_indicator": (True, True, False), + "separate_state": (True, False, True), + } + add_imputer, add_indicator, separate_state = plans[missing_policy] + numerical_strategy = "mean" if configured_imputation else "median" + categorical_strategy = "constant" if configured_imputation else "most_frequent" + + assert config.imputation_plan(is_numerical=is_numerical) == { + "add_imputer": add_imputer, + "add_indicator": add_indicator, + "separate_state": separate_state, + "strategy": numerical_strategy if is_numerical else categorical_strategy, + } + + +def test_normalized_config_retains_every_representation_setting(make_config): + parameters = { + "numerical_method": "cubic", + "categorical_method": "ohe", + "feature_preprocessing": {"age": "rbf", "city": "int"}, + "output_dim": 11, + "degree": 2, + "target_aware": True, + "placement_strategy": "cart", + "task": "classification", + "adaptive": True, + "min_output_dim": 3, + "max_output_dim": 8, + "random_state": 17, + "scaling": "standardization", + "cat_cutoff": 6, + "treat_all_integers_as_numerical": True, + "numerical_imputation": "mean", + "categorical_imputation": "constant", + "add_missing_indicator": True, + "missing_policy": "separate_state", + "verbose": 2, + } + + config = make_config(**parameters) + + assert asdict(config) == { + **parameters, + "numerical_method": "cubicspline", + "categorical_method": "one-hot", + "feature_groups": (), + } + assert config.feature_preprocessing is not parameters["feature_preprocessing"] + + +@pytest.mark.parametrize("form", ["mapping", "sequence", "values"]) +def test_group_normalization_preserves_declaration_and_source_order(make_config, form): + declarations = [ + {"name": "second", "columns": [1, "latitude"], "representation": {"method": "thinplate", "n_components": 4}}, + {"name": "first", "columns": ["b", "a"], "representation": "tensor"}, + ] + requested = { + "mapping": { + item["name"]: {key: value for key, value in item.items() if key != "name"} for item in declarations + }, + "sequence": declarations, + "values": [FeatureGroup(**item) for item in declarations], + }[form] + config = make_config(feature_groups=requested) + + assert isinstance(config.feature_groups, tuple) + assert [group.name for group in config.feature_groups] == ["second", "first"] + assert [group.columns for group in config.feature_groups] == [(1, "latitude"), ("b", "a")] + assert [group.representation for group in config.feature_groups] == [ + RepresentationConfig("tprs", params={"n_components": 4}), + RepresentationConfig("tensorspline"), + ] + declarations[0]["columns"].append("changed") + assert config.feature_groups[0].columns == (1, "latitude") + + +@pytest.mark.parametrize("requested", [None, {}, [], ()]) +def test_empty_groups_normalize_to_an_empty_tuple(make_config, requested): + assert make_config(feature_groups=requested).feature_groups == () + + +def test_group_representation_uses_existing_inheritance_and_local_priority(make_config): + config = make_config( + feature_groups={ + "surface": {"columns": ["b", "a"], "representation": {"method": "tensor", "output_dim": 4, "degree": 2}}, + "location": {"columns": ["x", "y"], "representation": {"method": "thinplate", "n_components": 6}}, + }, + output_dim=9, + degree=3, + random_state=17, + ) + + surface, location = [config.group_representation_for(group) for group in config.feature_groups] + assert surface == RepresentationConfig( + "tensorspline", output_dim=4, placement_strategy="uniform", params={"degree": 2} + ) + assert location == RepresentationConfig("tprs", params={"n_components": 6, "random_state": 17}) + + +@pytest.mark.parametrize( + "requested", + [ + "location", + {"x", "y"}, + ["x", "y"], + {"location": {"columns": ["x", "y"]}}, + {"location": {"columns": ["x", "y"], "representation": "tprs", "name": "location"}}, + [{"columns": ["x", "y"], "representation": "tprs"}], + [{"name": "location", "columns": ["x", "y"], "representation": "tprs", "extra": True}], + {"location": {"columns": ["x", "y"], "representation": "rff"}}, + {"location": {"columns": ["x", "y"], "representation": {"method": "tprs", "n_componnts": 4}}}, + {"location": {"columns": ["x", "y"], "representation": {"method": "tprs", "name": "other"}}}, + [FeatureGroup("location", ["x", "y"], "tprs"), FeatureGroup("location", ["a", "b"], "tensor")], + ], +) +def test_invalid_group_declarations_raise_contextual_errors(make_config, requested): + with pytest.raises(InvalidParamError, match="feature_groups"): + make_config(feature_groups=requested) + + +def test_group_parameter_is_keyword_only_and_remains_raw_for_sklearn(): + declarations = { + "location": {"columns": [1, "latitude"], "representation": {"method": "thinplate", "n_components": 4}} + } + processor = Preprocessor(feature_groups=declarations, random_state=17) + parameters = inspect.signature(Preprocessor).parameters + + assert parameters["feature_groups"].kind is inspect.Parameter.KEYWORD_ONLY + assert parameters["feature_groups"].default is None + assert processor.get_params(deep=False)["feature_groups"] is declarations + resolved = processor.get_resolved_config() + assert resolved["feature_groups"] == [ + { + "name": "location", + "columns": [1, "latitude"], + "representation": RepresentationConfig("tprs", params={"n_components": 4, "random_state": 17}).to_dict(), + } + ] + resolved["feature_groups"][0]["columns"].append("changed") + resolved["feature_groups"][0]["representation"]["params"]["n_components"] = 8 + assert processor.get_resolved_config()["feature_groups"][0]["representation"]["params"]["n_components"] == 4 + declarations["location"]["representation"]["n_components"] = 6 + assert processor.get_resolved_config()["feature_groups"][0]["representation"]["params"]["n_components"] == 6 + assert processor.feature_groups is declarations + + +@pytest.mark.parametrize("typed", [False, True]) +def test_group_requests_clone_and_set_params_without_normalizing_constructor_values(typed): + requested = ( + [FeatureGroup("location", ["x", "y"], "thinplate")] + if typed + else {"location": {"columns": ["x", "y"], "representation": "thinplate"}} + ) + processor = Preprocessor(feature_groups=requested) + copied = clone(processor) + assert isinstance(copied, Preprocessor) + assert copied.feature_groups == requested + assert copied.feature_groups is not requested + assert copied.get_resolved_config() == processor.get_resolved_config() + processor.set_params(feature_groups=None) + assert processor.feature_groups is None + assert processor.get_resolved_config()["feature_groups"] is None + + +@pytest.mark.parametrize("requested", [None, {}, [], ()]) +def test_empty_groups_preserve_single_column_values_names_and_fingerprint(sample_frame, requested): + parameters = {"numerical_method": "rbf", "target_aware": False, "placement_strategy": "uniform"} + reference = Preprocessor(**parameters).fit(sample_frame) + processor = Preprocessor(feature_groups=requested, **parameters).fit(sample_frame) + + np.testing.assert_array_equal(processor.transform(sample_frame), reference.transform(sample_frame)) + np.testing.assert_array_equal(processor.get_feature_names_out(), reference.get_feature_names_out()) + assert processor.output_dims_ == reference.output_dims_ + assert processor.fingerprint_ == reference.fingerprint_ + assert processor.feature_groups is requested + expected_config = reference.get_resolved_config() + expected_config["feature_groups"] = None if requested is None else [] + assert processor.get_resolved_config() == expected_config + + +def test_nonempty_groups_cannot_be_silently_ignored_by_single_column_fitting(sample_frame): + processor = Preprocessor( + feature_groups={ + "location": { + "columns": ["age", "second"], + "representation": {"method": "tprs", "n_components": 2, "landmark_strategy": "subsample"}, + } + } + ).fit(sample_frame.assign(second=sample_frame["age"] + 1)) + names = processor.column_transformer_.named_transformers_ + assert "group_location" in names + assert "num_age" not in names and "num_second" not in names + assert processor.output_dims_["group_location"] == 2 def test_none_method_normalizes_to_none(make_config): @@ -54,3 +334,309 @@ def test_method_for_resolves_in_the_requested_namespace(make_config): def test_seed_kwargs_reflects_random_state(make_config): assert make_config(random_state=None).seed_kwargs == {} assert make_config(random_state=42).seed_kwargs == {"random_state": 42} + + +@pytest.mark.parametrize("typed", [False, True]) +def test_structured_overrides_detach_and_keep_string_method_lookup(make_config, typed): + data = {"method": "RBF", "output_dim": 3, "gamma": 0.5} + value = RepresentationConfig.from_dict(data) if typed else data + config = make_config(feature_preprocessing={"age": value}, adaptive=True) + data["output_dim"] = 9 + requested = config.feature_preprocessing["age"] + resolved = config.representation_for("age", is_numerical=True) + + assert requested == RepresentationConfig(method="RBF", output_dim=3, params={"gamma": 0.5}) + assert config.method_for("age", is_numerical=True) == "rbf" + assert resolved.output_dim == 3 + assert resolved.adaptive is False + assert resolved.min_output_dim is UNSET + assert resolved.max_output_dim is UNSET + assert resolved.params == {"gamma": 0.5, "task": "regression"} + assert requested.target_aware is UNSET + + +@pytest.mark.parametrize("local", [{"adaptive": True}, {}]) +def test_representation_resolution_inherits_applicable_defaults(make_config, local): + config = make_config( + feature_preprocessing={"age": {"method": "cubic", **local}}, + output_dim=11, + degree=2, + adaptive=True, + min_output_dim=3, + max_output_dim=15, + random_state=17, + ) + resolved = config.representation_for("age", is_numerical=True) + assert resolved == RepresentationConfig( + method="cubicspline", + output_dim=11, + target_aware=False, + placement_strategy="uniform", + adaptive=True, + min_output_dim=3, + max_output_dim=15, + params={"degree": 2, "task": "regression", "random_state": 17}, + ) + + +def test_representation_resolution_keeps_explicit_adaptive_width_and_bounds(make_config): + config = make_config( + feature_preprocessing={ + "age": {"method": "rbf", "output_dim": 3, "adaptive": True, "min_output_dim": None, "max_output_dim": 12} + } + ) + resolved = config.representation_for("age", is_numerical=True) + assert (resolved.output_dim, resolved.adaptive, resolved.min_output_dim, resolved.max_output_dim) == ( + 3, + True, + None, + 12, + ) + + +@pytest.mark.parametrize("method", ["ohe", "ordinal", "identity"]) +def test_representation_resolution_filters_unrelated_constructor_defaults(make_config, method): + config = make_config( + feature_preprocessing={"city": {"method": method}}, target_aware=True, placement_strategy="cart", adaptive=True + ) + resolved = config.representation_for("city", is_numerical=False) + assert resolved == RepresentationConfig(method=config.method_for("city", is_numerical=False)) + + +def test_representation_resolution_rejects_effective_placement_conflict(make_config): + config = make_config( + target_aware=True, + placement_strategy="cart", + feature_preprocessing={"age": {"method": "rbf", "target_aware": False}}, + ) + with pytest.raises(InvalidParamError, match=r"feature_preprocessing\['age'\].placement_strategy"): + config.representation_for("age", is_numerical=True) + + +def test_representation_resolution_rejects_explicit_bounds_in_fixed_mode(make_config): + config = make_config(feature_preprocessing={"age": {"method": "rbf", "min_output_dim": 2}}) + with pytest.raises(InvalidParamError, match=r"feature_preprocessing\['age'\].min_output_dim"): + config.representation_for("age", is_numerical=True) + + +@pytest.mark.parametrize("form", ["string", "mapping", "value"]) +@pytest.mark.parametrize( + ("method", "is_numerical"), + [("RBF", True), ("cubic", True), ("b-spline", True), ("OHE", False), ("identity", False)], +) +def test_representation_resolution_forms_are_equivalent(make_config, form, method, is_numerical): + requested = {"string": method, "mapping": {"method": method}, "value": RepresentationConfig(method=method)}[form] + config = make_config(feature_preprocessing={"feature": requested}) + expected = make_config(feature_preprocessing={"feature": method}).representation_for( + "feature", is_numerical=is_numerical + ) + assert config.representation_for("feature", is_numerical=is_numerical) == expected + assert config.method_for("feature", is_numerical=is_numerical) == expected.method + + +@pytest.mark.parametrize("form", ["string", "mapping", "value"]) +@pytest.mark.parametrize(("method", "is_numerical"), [("RBF", True), ("OHE", False)]) +def test_representation_forms_agree_through_clone_json_report_and_fit(form, method, is_numerical): + requested = {"string": method, "mapping": {"method": method}, "value": RepresentationConfig(method=method)}[form] + overrides = {"feature": requested} + settings: dict[str, Any] = { + "output_dim": 7, + "target_aware": False, + "placement_strategy": "uniform", + "scaling": "none", + "random_state": 17, + } + values = np.linspace(0, 1, 40) if is_numerical else ["a", "b"] * 20 + frame = pd.DataFrame({"feature": values}) + processor = Preprocessor(feature_preprocessing=overrides, **settings) + fresh = clone(processor) + assert isinstance(fresh, Preprocessor) + assert fresh.get_params() == processor.get_params() + assert processor.get_params()["feature_preprocessing"] is overrides + assert overrides["feature"] is requested + + report = fresh.get_resolved_config() + restored_report = json.loads(json.dumps(report, allow_nan=False)) + assert restored_report == report + resolved = RepresentationConfig.from_dict(restored_report["feature_preprocessing"]["feature"]) + assert resolved.to_dict() == report["feature_preprocessing"]["feature"] + + actual = np.asarray(fresh.fit_transform(frame, return_array=True)) + reference = Preprocessor(feature_preprocessing={"feature": method}, **settings).fit(frame) + expected = np.asarray(reference.transform(frame, return_array=True)) + assert actual.dtype == expected.dtype + assert actual.shape == expected.shape + assert actual.tobytes() == expected.tobytes() + np.testing.assert_array_equal(fresh.get_feature_names_out(), reference.get_feature_names_out()) + assert fresh.output_dims_ == reference.output_dims_ + assert fresh.total_output_dim_ == reference.total_output_dim_ + + +@pytest.mark.parametrize("typed", [False, True], ids=["raw", "typed"]) +def test_fit_boundary_detaches_params_without_changing_requested_identity(typed): + params = {"gamma": 0.5} + settings = {"method": "rbf", "output_dim": 3, "params": params} + requested = RepresentationConfig.from_dict(settings) if typed else settings + overrides = {"age": requested} + processor = Preprocessor( + feature_preprocessing=overrides, target_aware=False, placement_strategy="uniform", scaling="none" + ) + params["gamma"] = 0.75 + expected_gamma = 0.5 if typed else 0.75 + frame = pd.DataFrame({"age": np.linspace(0, 1, 40)}) + processor.fit(frame) + original = np.asarray(processor.transform(frame, return_array=True)) + basis = processor.column_transformer_.named_transformers_["num_age"].named_steps["rbf"] + assert basis.gamma == expected_gamma + + report = processor.get_resolved_config() + report["feature_preprocessing"]["age"]["params"]["gamma"] = 9.0 + params["gamma"] = 1.25 + + assert processor.get_params()["feature_preprocessing"] is overrides + assert overrides["age"] is requested + assert basis.gamma == expected_gamma + assert np.asarray(processor.transform(frame, return_array=True)).tobytes() == original.tobytes() + live = processor.get_resolved_config()["feature_preprocessing"]["age"] + assert live["params"]["gamma"] == (0.5 if typed else 1.25) + + +def test_normalized_feature_requests_snapshot_nested_values_at_the_boundary(make_config, monkeypatch): + spec = TRANSFORMER_REGISTRY["rbf"] + monkeypatch.setitem(TRANSFORMER_REGISTRY, "rbf", replace(spec, allowed_args=(*spec.allowed_args, "options"))) + nested = {"values": [1, {"weight": 0.5}]} + raw = {"age": {"method": "rbf", "params": {"options": nested}}} + preprocessor = Preprocessor(feature_preprocessing=raw) + assert preprocessor.get_params(deep=False)["feature_preprocessing"] is raw + nested["values"].append(2) + config = make_config(feature_preprocessing=raw) + nested["values"].append(3) + raw["age"]["params"]["options"] = {"changed": True} + + requested = config.feature_preprocessing["age"] + assert requested.params["options"]["values"] == (1, {"weight": 0.5}, 2) + resolved = config.representation_for("age", is_numerical=True) + view = resolved.to_dict() + view["params"]["options"]["values"].append(4) + assert config.representation_for("age", is_numerical=True) == resolved + assert requested.params["options"]["values"] == (1, {"weight": 0.5}, 2) + + +@pytest.mark.parametrize( + ("data", "location"), + [ + ({}, "method"), + ({"method": "rbf", "output_dim": True}, "output_dim"), + ({"method": "rbf", "gamma": 0.5, "params": {"gamma": 0.5}}, "gamma"), + ({"method": "rbf", "params": {"output_dim": 3}}, "params"), + (None, "value"), + ], +) +def test_structured_override_shape_errors_keep_the_feature_path(make_config, data, location): + with pytest.raises(InvalidParamError) as failure: + make_config(feature_preprocessing={"age": data}) + assert "feature_preprocessing['age']" in str(failure.value) + assert location in str(failure.value) + with pytest.raises(InvalidParamError) as standalone: + RepresentationConfig(method="") + assert str(standalone.value).startswith("RepresentationConfig.method") + + +def test_structured_override_namespace_validation_waits_for_feature_detection(make_config): + config = make_config(feature_preprocessing={"city": {"method": "ohe"}}) + assert config.method_for("city", is_numerical=False) == "one-hot" + with pytest.raises(InvalidParamError, match=r"feature_preprocessing\['city'\].method"): + config.method_for("city", is_numerical=True) + + +@pytest.mark.parametrize("method", ["not_a_method", "ordinal"]) +def test_legacy_method_lookup_still_defers_invalid_names(make_config, method): + config = make_config(feature_preprocessing={"age": method}) + assert config.method_for("age", is_numerical=True) == method + + +def test_representation_resolution_uses_the_global_method_without_an_override(make_config): + config = make_config(numerical_method="cubic", degree=2) + resolved = config.representation_for("age", is_numerical=True) + assert resolved.method == "cubicspline" + assert resolved.output_dim == 7 + assert resolved.params == {"degree": 2, "task": "regression"} + assert resolved.adaptive is False + assert resolved.min_output_dim is UNSET + assert resolved.max_output_dim is UNSET + + +@pytest.mark.parametrize("random_state", [None, 0, 17]) +def test_representation_resolution_preserves_seed_forwarding(make_config, random_state): + config = make_config(numerical_method="rbf", random_state=random_state) + resolved = config.representation_for("age", is_numerical=True) + assert ("random_state" in resolved.params) == (random_state is not None) + if random_state is not None: + assert resolved.params["random_state"] == random_state + + +def test_explicit_family_options_override_constructor_controls_independently(make_config): + config = make_config( + degree=3, + task="regression", + random_state=17, + feature_preprocessing={"age": {"method": "cubic", "degree": 2, "task": "classification", "random_state": None}}, + ) + resolved = config.representation_for("age", is_numerical=True) + assert resolved.params == {"degree": 2, "task": "classification", "random_state": None} + assert config.task == "regression" + assert config.random_state == 17 + + +@pytest.mark.parametrize("local", [{"output_dim": 3}, {"adaptive": False}, {"output_dim": 3, "adaptive": False}]) +def test_fixed_local_requests_ignore_inherited_bounds(make_config, local): + config = make_config( + adaptive=True, + min_output_dim=8, + max_output_dim=5, + feature_preprocessing={"age": {"method": "rbf", **local}}, + ) + resolved = config.representation_for("age", is_numerical=True) + assert resolved.adaptive is False + assert resolved.min_output_dim is UNSET + assert resolved.max_output_dim is UNSET + + +@pytest.mark.parametrize("adaptive", [False, True]) +def test_local_bounds_alone_do_not_opt_into_adaptive_resolution(make_config, adaptive): + config = make_config(adaptive=adaptive, feature_preprocessing={"age": {"method": "rbf", "max_output_dim": 12}}) + if adaptive: + assert config.representation_for("age", is_numerical=True).max_output_dim == 12 + else: + with pytest.raises(InvalidParamError, match=r"feature_preprocessing\['age'\].max_output_dim"): + config.representation_for("age", is_numerical=True) + + +def test_active_inherited_bound_relationships_are_validated(make_config): + config = make_config( + adaptive=True, min_output_dim=8, max_output_dim=5, feature_preprocessing={"age": {"method": "rbf"}} + ) + with pytest.raises(InvalidParamError, match=r"feature_preprocessing\['age'\].max_output_dim"): + config.representation_for("age", is_numerical=True) + + +def test_explicit_unsupervised_pair_overrides_supervised_constructor_settings(make_config): + config = make_config( + target_aware=True, + placement_strategy="cart", + feature_preprocessing={"age": {"method": "rbf", "target_aware": False, "placement_strategy": "quantile"}}, + ) + resolved = config.representation_for("age", is_numerical=True) + assert resolved.target_aware is False + assert resolved.placement_strategy == "quantile" + + +def test_fixed_placement_family_keeps_existing_factory_default_filtering(make_config): + config = make_config( + target_aware=True, placement_strategy="cart", feature_preprocessing={"age": {"method": "pspline"}} + ) + resolved = config.representation_for("age", is_numerical=True) + assert resolved.output_dim == 7 + assert resolved.params == {"degree": 3} + assert resolved.placement_strategy is UNSET + assert resolved.target_aware is UNSET diff --git a/tests/compose/test_factory.py b/tests/compose/test_factory.py index f271615..66ffdfc 100644 --- a/tests/compose/test_factory.py +++ b/tests/compose/test_factory.py @@ -1,18 +1,31 @@ """Unit tests for :mod:`pretab.compose.factory`.""" +from dataclasses import fields, replace +from unittest.mock import Mock, call, patch + import numpy as np import pandas as pd import pytest +from scipy.sparse import issparse +from sklearn.base import clone from sklearn.compose import ColumnTransformer -from sklearn.pipeline import Pipeline +from sklearn.impute import SimpleImputer +from sklearn.pipeline import FeatureUnion, Pipeline +from sklearn.preprocessing import MinMaxScaler, StandardScaler +from pretab import Preprocessor +from pretab.compose.config import PreprocessorConfig, RepresentationConfig from pretab.compose.factory import ( + _clamp_spline_basis, _placement_kwargs, build_column_transformer, + create_transformer, get_categorical_transformer_steps, get_numerical_transformer_steps, ) -from pretab.compose.registry import TransformerSpec, get_spec +from pretab.compose.feature_detection import with_string_labels +from pretab.compose.registry import TRANSFORMER_REGISTRY, TransformerSpec, get_spec +from pretab.core.parameters import UNSET from pretab.exceptions import ConfigWarning, InvalidParamError @@ -188,3 +201,736 @@ def test_build_column_transformer_fits_and_transforms(make_config, sample_frame) out = ct.fit_transform(sample_frame, np.array([0.0, 1.0, 0.0, 1.0, 0.0, 1.0])) assert isinstance(out, np.ndarray) assert out.shape[0] == len(sample_frame) + + +@pytest.mark.parametrize("method", ["tensorspline", "tprs"]) +def test_grouped_factory_selects_sources_once_in_declared_order(make_config, method): + config = make_config(feature_groups={"location": {"columns": ["y", "x"], "representation": method}}) + transformer = build_column_transformer(config, ["x", "untouched", "y"], ["city"]) + + assert [(name, columns) for name, _, columns in transformer.transformers] == [ + ("num_untouched", ["untouched"]), + ("group_location", ["y", "x"]), + ("cat_city", ["city"]), + ] + + +@pytest.mark.parametrize("reverse", [False, True]) +def test_grouped_factory_preserves_declaration_order_between_singles(make_config, reverse): + groups = [ + {"name": "first", "columns": ["y", "x"], "representation": "tensor"}, + {"name": "second", "columns": ["w", "z"], "representation": "thinplate"}, + ] + if reverse: + groups.reverse() + config = make_config(feature_groups=groups) + transformer = build_column_transformer(config, ["w", "x", "untouched", "y", "z"], ["city"]) + assert [(name, columns) for name, _, columns in transformer.transformers] == [ + ("num_untouched", ["untouched"]), + *[(f"group_{group['name']}", group["columns"]) for group in groups], + ("cat_city", ["city"]), + ] + assert [group.name for group in config.feature_groups] == [group["name"] for group in groups] + + +@pytest.mark.parametrize("method", ["tensorspline", "tprs"]) +@pytest.mark.parametrize("scaling", [None, "standardization", "minmax"]) +@pytest.mark.parametrize("missing_policy", ["impute", "impute_with_indicator", "separate_state"]) +def test_grouped_factory_matches_joint_reference_without_indicator_inputs(make_config, method, scaling, missing_policy): + frame = pd.DataFrame(np.random.default_rng(42).normal(size=(24, 2)), columns=pd.Index(["x", "y"])) + frame.loc[[1, 7], "x"] = np.nan + before = frame.copy(deep=True) + options = ( + {"output_dim": 3, "degree": 2, "diff_order": 1, "placement_strategy": "quantile"} + if method == "tensorspline" + else {"n_components": 4, "landmark_strategy": "subsample", "rank_strategy": "nystroem", "random_state": 0} + ) + config = make_config( + numerical_method="ple", + output_dim=13, + degree=5, + adaptive=True, + target_aware=True, + placement_strategy="cart", + scaling=scaling, + missing_policy=missing_policy, + random_state=17, + feature_groups={"location": {"columns": ["y", "x"], "representation": {"method": method, **options}}}, + ) + transformer = build_column_transformer(config, ["x", "y"], [], sparse_threshold=0.0) + result = transformer.fit_transform(frame) + assert isinstance(result, np.ndarray) + block = transformer.named_transformers_["group_location"] + pipeline = dict(block.transformer_list)["representation"] if isinstance(block, FeatureUnion) else block + assert isinstance(pipeline, Pipeline) + leaf = pipeline.named_steps[method] + assert leaf.n_features_in_ == 2 + assert pipeline.named_steps["imputer"].statistics_.shape == (2,) + assert pipeline.named_steps["imputer"].add_indicator is False + for key, value in options.items(): + assert getattr(leaf, key) == value + + reference_steps: list[tuple[str, object]] = [ + ("imputer", SimpleImputer(strategy="median", keep_empty_features=True)) + ] + if scaling is not None: + scaler = StandardScaler() if scaling == "standardization" else MinMaxScaler(feature_range=(-1, 1)) + reference_steps.append(("scaler", scaler)) + reference_steps.append((method, get_spec(method).transformer_cls(**options))) + reference = Pipeline(reference_steps) + expected = reference.fit_transform(frame[["y", "x"]]) + width = expected.shape[1] + assert width == (9 if method == "tensorspline" else 4) + np.testing.assert_allclose(result[:, :width], expected, rtol=1e-12, atol=1e-12) + + missing_columns = ["x"] if missing_policy == "impute_with_indicator" else ["y", "x"] + indicator_width = 0 if missing_policy == "impute" else len(missing_columns) + assert result.shape == (len(frame), width + indicator_width) + assert isinstance(block, Pipeline if missing_policy == "impute" else FeatureUnion) + if indicator_width: + np.testing.assert_array_equal(result[:, width:], frame[missing_columns].isna().to_numpy(dtype=float)) + + heldout = frame.iloc[:4].copy() + heldout.loc[0, "y"] = np.nan + transformed = transformer.transform(heldout[["y", "x"]]) + assert isinstance(transformed, np.ndarray) + np.testing.assert_allclose(transformed[:, :width], reference.transform(heldout[["y", "x"]]), rtol=1e-12, atol=1e-12) + if indicator_width: + np.testing.assert_array_equal(transformed[:, width:], heldout[missing_columns].isna().to_numpy(dtype=float)) + assert transformed.shape[1] == result.shape[1] + pd.testing.assert_frame_equal(frame, before) + + +def test_grouped_factory_maps_integer_labels_without_positional_selection(make_config): + frame = pd.DataFrame(np.random.default_rng(0).normal(size=(16, 3)), columns=pd.Index([7, 3, 9])) + config = make_config( + feature_groups={ + "location": { + "columns": [3, 7], + "representation": {"method": "tprs", "n_components": 2, "landmark_strategy": "subsample"}, + } + }, + random_state=0, + ) + transformer = build_column_transformer(config, [7, 3, 9], []) + assert [(name, columns) for name, _, columns in transformer.transformers] == [ + ("num_9", ["9"]), + ("group_location", ["3", "7"]), + ] + normalized = with_string_labels(frame) + result = transformer.fit_transform(normalized) + np.testing.assert_array_equal(result, transformer.transform(normalized[["9", "3", "7"]])) + assert config.feature_groups[0].columns == (3, 7) + assert list(frame.columns) == [7, 3, 9] + + +def test_grouped_factory_keeps_private_step_names_safe_and_unique(make_config): + frame = pd.DataFrame(np.random.default_rng(1).normal(size=(16, 4)), columns=pd.Index(["_unsafe", "col0", "x", "y"])) + frame["__city"] = ["a", "b"] * 8 + config = make_config( + feature_groups={ + "num_col0": { + "columns": ["x", "y"], + "representation": {"method": "tprs", "n_components": 2, "landmark_strategy": "subsample"}, + } + }, + random_state=0, + ) + transformer = build_column_transformer(config, ["_unsafe", "col0", "x", "y"], ["__city"]) + names = [name for name, _, _ in transformer.transformers] + assert names == ["num_col0_1", "num_col0", "group_num_col0", "cat_col3"] + assert len(set(names)) == len(names) + assert all("__" not in name for name in names) + cloned = clone(transformer) + assert isinstance(cloned, ColumnTransformer) + np.testing.assert_array_equal(transformer.fit_transform(frame), cloned.fit_transform(frame)) + + +@pytest.mark.parametrize("claimed_collision", [False, True]) +def test_group_public_key_collision_precedes_all_construction(make_config, monkeypatch, claimed_collision): + columns = ["group_location", "y"] if claimed_collision else ["x", "y"] + config = make_config(feature_groups={"location": {"columns": columns, "representation": "tprs"}}) + + def unexpected(*args, **kwargs): + pytest.fail("A group public-key collision must be rejected before constructing any block") + + monkeypatch.setattr("pretab.compose.factory._create_transformer", unexpected) + with pytest.raises(InvalidParamError, match=r"feature_groups\['location'\].name.*location") as failure: + build_column_transformer(config, ["untouched", "x", "y", "group_location"], []) + assert "public block key 'group_location'" in str(failure.value) + + +@pytest.mark.parametrize("method", ["tensor", "thinplate"]) +def test_grouped_factory_capability_is_rechecked_before_construction(make_config, monkeypatch, method): + config = make_config(feature_groups={"location": {"columns": ["x", "y"], "representation": method}}) + canonical = config.group_representation_for(config.feature_groups[0]).method + spec = get_spec(canonical) + monkeypatch.setitem(TRANSFORMER_REGISTRY, canonical, replace(spec, group_compatible=False)) + with pytest.raises(InvalidParamError, match="does not support explicit feature groups"): + build_column_transformer(config, ["x", "y"], []) + + +@pytest.mark.parametrize("method", ["tensorspline", "tprs", "rff", "nystroem"]) +def test_grouped_factory_does_not_unlock_single_column_step_selection(method): + with pytest.raises(InvalidParamError, match="unrecognized numerical preprocessing method"): + get_numerical_transformer_steps(method, is_group=True) + + +@pytest.mark.parametrize("method", ["tensorspline", "tprs"]) +def test_grouped_representation_cannot_enter_public_single_column_builder(make_config, method): + with pytest.raises(InvalidParamError, match=r"create_transformer\.representation\.method") as failure: + create_transformer( + method, is_numerical=True, config=make_config(), representation=RepresentationConfig(method=method) + ) + assert "unrecognized numerical preprocessing method" in str(failure.value) + + +@pytest.mark.parametrize("typed", [False, True], ids=["mapping", "value"]) +def test_preprocessor_fits_structured_representation(typed): + settings = {"method": "rbf", "output_dim": 3, "params": {"gamma": 0.5}} + representation = RepresentationConfig.from_dict(settings) if typed else settings + frame = pd.DataFrame({"age": np.linspace(0, 1, 30)}) + processor = Preprocessor( + numerical_method="none", + feature_preprocessing={"age": representation}, + output_dim=9, + target_aware=False, + placement_strategy="quantile", + scaling="none", + ).fit(frame) + + basis = processor.column_transformer_.named_transformers_["num_age"].named_steps["rbf"] + assert basis.output_dim == 3 + assert basis.gamma == 0.5 + transformed = processor.transform(frame, return_array=True) + assert isinstance(transformed, np.ndarray) + assert transformed.shape == (30, 3) + + +@pytest.mark.parametrize("typed", [False, True], ids=["mapping", "value"]) +@pytest.mark.parametrize( + ("method", "canonical", "output_dim", "params"), + [("RBF", "rbf", 3, {"gamma": 0.5}), ("b-spline", "bspline", 6, {"degree": 2})], +) +def test_preprocessor_routes_local_options_through_both_step_builders(typed, method, canonical, output_dim, params): + settings = { + "age": {"method": method, "output_dim": output_dim, "params": params, "name": "age-basis"}, + "city": {"method": "OHE", "params": {"drop": "first", "sparse_output": False}}, + } + overrides = { + feature: RepresentationConfig.from_dict(value) if typed else value for feature, value in settings.items() + } + frame = pd.DataFrame({"age": np.linspace(0, 1, 40), "city": ["a", "b"] * 20}) + processor = Preprocessor( + feature_preprocessing=overrides, + output_dim=11, + degree=3, + random_state=17, + target_aware=False, + placement_strategy="quantile", + scaling="standardization", + ) + + with ( + patch("pretab.compose.factory.create_transformer", wraps=create_transformer) as create, + patch( + "pretab.compose.factory.get_numerical_transformer_steps", wraps=get_numerical_transformer_steps + ) as numerical, + patch( + "pretab.compose.factory.get_categorical_transformer_steps", wraps=get_categorical_transformer_steps + ) as categorical, + ): + processor.fit(frame) + + assert [entry.args[0] for entry in create.call_args_list] == [canonical, "one-hot"] + assert all(isinstance(entry.kwargs["representation"], RepresentationConfig) for entry in create.call_args_list) + numerical.assert_called_once() + options = numerical.call_args.kwargs + assert options["method"] == canonical + assert options["output_dim"] == output_dim + assert options["target_aware"] is False + assert options["placement_strategy"] == "quantile" + assert options["scaling"] == "standardization" + assert "name" not in options + if canonical == "rbf": + assert "degree" not in options + for key, value in params.items(): + assert options[key] == value + categorical.assert_called_once_with( + "one-hot", add_imputer=True, imputer_strategy="most_frequent", drop="first", sparse_output=False + ) + + numeric = processor.column_transformer_.named_transformers_["num_age"] + assert _names(numeric.steps) == ["imputer", "scaler", canonical] + basis = numeric.named_steps[canonical] + assert basis.output_dim == output_dim + assert basis.target_aware is False + assert basis.placement_strategy == "quantile" + for key, value in params.items(): + assert getattr(basis, key) == value + encoder = processor.column_transformer_.named_transformers_["cat_city"].named_steps["onehot"] + assert encoder.drop == "first" + assert encoder.sparse_output is False + transformed = processor.transform(frame, return_array=True) + assert isinstance(transformed, np.ndarray) + assert transformed.shape == (40, output_dim + 1) + + +@pytest.mark.parametrize("typed", [False, True], ids=["mapping", "value"]) +@pytest.mark.parametrize("method", ["bspline", "mspline", "ispline"]) +def test_preprocessor_clamps_each_local_spline_width(typed, method): + settings = { + "age": {"method": method, "output_dim": 3, "placement_strategy": "quantile", "degree": 2}, + "income": {"method": method, "output_dim": 51, "placement_strategy": "uniform", "degree": 3}, + } + overrides = { + feature: RepresentationConfig.from_dict(value) if typed else value for feature, value in settings.items() + } + frame = pd.DataFrame({"age": np.linspace(0, 1, 80) ** 3, "income": np.linspace(2, 8, 80) ** 2}) + with ( + patch("pretab.compose.factory._clamp_spline_basis", wraps=_clamp_spline_basis) as clamp, + pytest.warns(ConfigWarning) as emitted, + ): + processor = Preprocessor( + feature_preprocessing=overrides, + output_dim=11, + target_aware=False, + placement_strategy="uniform", + scaling="none", + ).fit(frame) + + assert clamp.call_args_list == [call(3), call(51)] + assert len(emitted) == 2 + for feature, expected in (("age", 5), ("income", 50)): + basis = processor.column_transformer_.named_transformers_[f"num_{feature}"].named_steps[method] + assert basis.output_dim == expected + assert basis.degree == settings[feature]["degree"] + assert basis.placement_strategy == settings[feature]["placement_strategy"] + transformed = processor.transform(frame, return_array=True) + assert isinstance(transformed, np.ndarray) + assert transformed.shape == (80, 55) + + +@pytest.mark.parametrize("typed", [False, True], ids=["mapping", "value"]) +@pytest.mark.parametrize("handle_unknown", ["error", "ignore"]) +def test_preprocessor_forwards_portable_one_hot_constructor_options(typed, handle_unknown): + params = { + "categories": [["a", "b", "c"]], + "drop": ["a"], + "sparse_output": False, + "dtype": "float32", + "handle_unknown": handle_unknown, + "min_frequency": None, + "max_categories": None, + "feature_name_combiner": "concat", + } + settings = {"method": "one-hot", "params": params} + requested = RepresentationConfig.from_dict(settings) if typed else settings + frame = pd.DataFrame({"city": ["a", "b", "c"] * 10}) + processor = Preprocessor(feature_preprocessing={"city": requested}).fit(frame) + block = processor.column_transformer_.named_transformers_["cat_city"] + encoder = block.named_steps["onehot"] + assert {key: encoder.get_params()[key] for key in params} == params + np.testing.assert_array_equal(processor.transform(frame, return_array=True)[:3], [[0, 0], [1, 0], [0, 1]]) + if handle_unknown == "error": + with pytest.raises(ValueError, match="unknown categories"): + processor.transform(pd.DataFrame({"city": ["unseen"]}), return_array=True) + + +@pytest.mark.parametrize("typed", [False, True], ids=["mapping", "value"]) +def test_preprocessor_applies_each_local_placement_capability(typed): + settings = { + "supervised": {"method": "ple", "output_dim": 3, "target_aware": True, "placement_strategy": "cart"}, + "unsupervised": {"method": "rbf", "output_dim": 4, "target_aware": False, "placement_strategy": "quantile"}, + "penalized": {"method": "pspline", "output_dim": 6, "target_aware": False, "placement_strategy": "uniform"}, + } + overrides = { + feature: RepresentationConfig.from_dict(value) if typed else value for feature, value in settings.items() + } + values = np.linspace(0, 1, 80) + frame = pd.DataFrame({feature: values ** (index + 1) for index, feature in enumerate(settings)}) + with patch("pretab.compose.factory._placement_kwargs", wraps=_placement_kwargs) as placement: + processor = Preprocessor(feature_preprocessing=overrides, scaling="none").fit(frame, np.sin(6 * values)) + + assert [entry.args[0].name for entry in placement.call_args_list] == ["ple", "rbf", "pspline"] + for feature, requested in settings.items(): + basis = processor.column_transformer_.named_transformers_[f"num_{feature}"].named_steps[requested["method"]] + assert basis.output_dim == requested["output_dim"] + assert basis.placement_strategy == requested["placement_strategy"] + if requested["method"] == "rbf": + assert basis.target_aware is False + transformed = processor.transform(frame, return_array=True) + assert isinstance(transformed, np.ndarray) + assert transformed.shape == (80, 13) + + +@pytest.mark.parametrize("adaptive", [False, True]) +@pytest.mark.parametrize("random_state", [None, 17]) +@pytest.mark.parametrize( + "missing_policy", [None, "error", "propagate", "impute", "impute_with_indicator", "separate_state"] +) +def test_create_transformer_forwards_normalized_numerical_options(make_config, adaptive, random_state, missing_policy): + config = make_config( + numerical_method="rbf", + output_dim=11, + degree=2, + target_aware=True, + placement_strategy="cart", + task="classification", + adaptive=adaptive, + min_output_dim=3, + max_output_dim=8, + random_state=random_state, + scaling="standardization", + numerical_imputation=None, + add_missing_indicator=True, + missing_policy=missing_policy, + ) + plan = config.imputation_plan(is_numerical=True) + + with patch( + "pretab.compose.factory.get_numerical_transformer_steps", wraps=get_numerical_transformer_steps + ) as numerical_steps: + block = create_transformer(config.numerical_method, is_numerical=True, config=config) + + numerical_steps.assert_called_once_with( + method="rbf", + task="classification", + target_aware=True, + add_imputer=plan["add_imputer"], + imputer_strategy="median", + output_dim=11, + adaptive=adaptive, + min_output_dim=3 if adaptive else None, + max_output_dim=8 if adaptive else None, + degree=2, + scaling="standardization", + placement_strategy="cart", + **({} if random_state is None else {"random_state": random_state}), + ) + if plan["separate_state"] or plan["add_indicator"]: + assert isinstance(block, FeatureUnion) + representation = dict(block.transformer_list)["representation"] + else: + representation = block + assert isinstance(representation, Pipeline) + assert ("imputer" in representation.named_steps) is plan["add_imputer"] + if plan["add_imputer"]: + assert representation.named_steps["imputer"].strategy == "median" + + +@pytest.mark.parametrize("preset", [None, "standard", "expanded", "adaptive"]) +@pytest.mark.parametrize("missing_policy", [None, "impute_with_indicator", "separate_state"]) +def test_preprocessor_routes_one_normalized_config_through_the_factory(sample_frame, preset, missing_policy): + feature_overrides = {"age": "rbf", "city": "int"} + preprocessor = Preprocessor( + preset=preset, + numerical_method="cubic", + categorical_method="ohe", + feature_preprocessing=feature_overrides, + degree=2, + target_aware=False, + placement_strategy="uniform", + task="classification", + adaptive=False, + min_output_dim=3, + max_output_dim=8, + random_state=17, + scaling="standardization", + cat_cutoff=0.1, + treat_all_integers_as_numerical=True, + numerical_imputation="mean", + categorical_imputation="constant", + add_missing_indicator=True, + missing_policy=missing_policy, + max_output_features=64, + max_features_per_input=16, + max_dense_memory=1_000_000, + output_structure="blocks", + output_format="sparse", + dtype="float32", + ) + requested = preprocessor.get_params(deep=False) + resolved = preprocessor.get_resolved_config() + config_fields = {field.name for field in fields(PreprocessorConfig)} + facade_fields = { + "policy", + "max_output_features", + "max_features_per_input", + "max_dense_memory", + "overflow_policy", + "output_structure", + "output_format", + "dtype", + "task_validation", + } + assert set(resolved) == config_fields | facade_fields + assert config_fields.isdisjoint(facade_fields) + fit_parameters = {name: resolved[name] for name in config_fields} + fit_parameters["feature_preprocessing"] = feature_overrides + + normalized_configs: list[PreprocessorConfig] = [] + from_params = PreprocessorConfig.from_params + + def normalize_config(**parameters): + config = from_params(**parameters) + normalized_configs.append(config) + return config + + with ( + patch.object(PreprocessorConfig, "from_params", side_effect=normalize_config) as normalize, + patch.object( + PreprocessorConfig, "method_for", autospec=True, side_effect=PreprocessorConfig.method_for + ) as method_for, + patch.object( + PreprocessorConfig, "imputation_plan", autospec=True, side_effect=PreprocessorConfig.imputation_plan + ) as imputation_plan, + patch("pretab.compose.factory.create_transformer", wraps=create_transformer) as create, + ): + route = Mock() + for name, spy in ( + ("normalize", normalize), + ("method", method_for), + ("imputation", imputation_plan), + ("create", create), + ): + route.attach_mock(spy, name) + + preprocessor.fit(sample_frame, np.array([0, 1, 0, 1, 0, 1])) + + normalize.assert_called_once_with(**fit_parameters) + (config,) = normalized_configs + assert all(item.kwargs["config"] is config for item in create.call_args_list) + assert all(item.args[0] is config for item in method_for.call_args_list + imputation_plan.call_args_list) + assert config.numerical_method == "cubicspline" + assert config.categorical_method == "one-hot" + assert config.feature_preprocessing == feature_overrides + assert config.feature_preprocessing is not feature_overrides + assert method_for.call_args_list == [ + call(config, "age", is_numerical=True), + call(config, "city", is_numerical=False), + ] + assert create.call_args_list == [ + call("rbf", is_numerical=True, config=config), + call("int", is_numerical=False, config=config), + ] + assert imputation_plan.call_args_list == [call(config, is_numerical=True), call(config, is_numerical=False)] + assert [item[0] for item in route.mock_calls] == [ + "normalize", + "method", + "create", + "imputation", + "method", + "create", + "imputation", + ] + + for name, strategy in (("num_age", "mean"), ("cat_city", "constant")): + block = preprocessor.column_transformer_.named_transformers_[name] + assert isinstance(block, FeatureUnion) + representation = dict(block.transformer_list)["representation"] + assert representation.named_steps["imputer"].strategy == strategy + numerical = dict(preprocessor.column_transformer_.named_transformers_["num_age"].transformer_list)["representation"] + assert numerical.named_steps["rbf"].output_dim == resolved["output_dim"] + assert numerical.named_steps["rbf"].random_state == 17 + assert preprocessor.get_params(deep=False) == requested + assert preprocessor.get_resolved_config() == resolved + assert feature_overrides == {"age": "rbf", "city": "int"} + + +@pytest.mark.parametrize("output_dim", [2, 3, 5]) +def test_resolved_representation_controls_width_and_family_options(make_config, output_dim): + config = make_config( + output_dim=11, + adaptive=True, + feature_preprocessing={"age": {"method": "rbf", "output_dim": output_dim, "gamma": 0.5}}, + ) + resolved = config.representation_for("age", is_numerical=True) + block = create_transformer("rbf", is_numerical=True, config=config, representation=resolved) + assert isinstance(block, Pipeline) + transformer = block.named_steps["rbf"] + assert transformer.output_dim == output_dim + assert transformer.gamma == 0.5 + assert transformer.adaptive is False + assert block.fit_transform(np.linspace(0, 1, 16).reshape(-1, 1)).shape == (16, output_dim) + assert config.output_dim == 11 + assert config.adaptive is True + + +def test_resolved_representation_target_usage_overrides_run_wide_setting(make_config): + config = make_config( + feature_preprocessing={"age": {"method": "ple", "target_aware": True, "placement_strategy": "cart"}} + ) + resolved = config.representation_for("age", is_numerical=True) + block = create_transformer("ple", is_numerical=True, config=config, representation=resolved) + assert isinstance(block, Pipeline) + assert block.named_steps["ple"].placement_strategy == "cart" + assert config.target_aware is False + + +def test_resolved_representation_method_must_match_selected_method(make_config): + with pytest.raises(InvalidParamError, match=r"create_transformer.representation.method.*rbf"): + create_transformer( + "standardization", + is_numerical=True, + config=make_config(), + representation=RepresentationConfig(method="rbf"), + ) + + +@pytest.mark.parametrize("method", ["bspline", "mspline", "ispline"]) +@pytest.mark.parametrize(("output_dim", "expected"), [(3, 5), (51, 50)]) +def test_resolved_representation_reuses_bmi_clamping(make_config, method, output_dim, expected): + config = make_config(feature_preprocessing={"age": {"method": method, "output_dim": output_dim}}) + resolved = config.representation_for("age", is_numerical=True) + with pytest.warns(ConfigWarning, match=f"output_dim={output_dim}.*using {expected}"): + block = create_transformer(method, is_numerical=True, config=config, representation=resolved) + assert isinstance(block, Pipeline) + assert block.named_steps[method].output_dim == expected + assert resolved.output_dim == output_dim + + +@pytest.mark.parametrize(("method", "is_numerical"), [("cubic", True), ("b-spline", True), ("ohe", False)]) +def test_resolved_representation_accepts_matching_method_aliases(make_config, method, is_numerical): + config = make_config(feature_preprocessing={"feature": {"method": method}}) + resolved = config.representation_for("feature", is_numerical=is_numerical) + block = create_transformer(method, is_numerical=is_numerical, config=config, representation=resolved) + assert isinstance(block, Pipeline) + assert get_spec(resolved.method).transformer_cls in {type(step) for step in block.named_steps.values()} + + +@pytest.mark.parametrize( + ("random_state", "options", "expected"), + [(None, {}, UNSET), (17, {}, 17), (17, {"random_state": None}, None), (17, {"random_state": 0}, 0)], +) +def test_resolved_representation_preserves_omitted_and_explicit_seeds(make_config, random_state, options, expected): + config = make_config(random_state=random_state, feature_preprocessing={"age": {"method": "rbf", **options}}) + resolved = config.representation_for("age", is_numerical=True) + with patch( + "pretab.compose.factory.get_numerical_transformer_steps", wraps=get_numerical_transformer_steps + ) as steps: + block = create_transformer("rbf", is_numerical=True, config=config, representation=resolved) + assert isinstance(block, Pipeline) + if expected is UNSET: + assert "random_state" not in steps.call_args.kwargs + assert block.named_steps["rbf"].random_state == get_spec("rbf").transformer_cls().random_state + else: + assert steps.call_args.kwargs["random_state"] == expected + assert block.named_steps["rbf"].random_state == expected + + +def test_resolved_representation_keeps_explicit_adaptive_bounds(make_config): + config = make_config( + feature_preprocessing={ + "age": { + "method": "rbf", + "output_dim": 9, + "adaptive": True, + "min_output_dim": 3, + "max_output_dim": 12, + } + } + ) + resolved = config.representation_for("age", is_numerical=True) + block = create_transformer("rbf", is_numerical=True, config=config, representation=resolved) + assert isinstance(block, Pipeline) + transformer = block.named_steps["rbf"] + assert (transformer.output_dim, transformer.adaptive, transformer.min_output_dim, transformer.max_output_dim) == ( + 9, + True, + 3, + 12, + ) + + +def test_resolved_representation_overrides_supervised_run_without_leaking_defaults(make_config): + config = make_config( + target_aware=True, + placement_strategy="cart", + feature_preprocessing={ + "age": { + "method": "rbf", + "target_aware": False, + "placement_strategy": "quantile", + "output_dim": 3, + } + }, + ) + resolved = config.representation_for("age", is_numerical=True) + block = create_transformer("rbf", is_numerical=True, config=config, representation=resolved) + assert isinstance(block, Pipeline) + transformer = block.named_steps["rbf"] + assert transformer.target_aware is False + assert transformer.placement_strategy == "quantile" + assert block.fit_transform(np.linspace(0, 1, 16).reshape(-1, 1)).shape == (16, 3) + + +@pytest.mark.parametrize("is_numerical", [False, True]) +@pytest.mark.parametrize("missing_policy", [None, "impute", "impute_with_indicator", "separate_state"]) +def test_resolved_representation_preserves_missing_value_and_indicator_assembly( + make_config, is_numerical, missing_policy +): + method = "rbf" if is_numerical else "one-hot" + options = {"output_dim": 3} if is_numerical else {} + config = make_config( + missing_policy=missing_policy, feature_preprocessing={"feature": {"method": method, **options}} + ) + resolved = config.representation_for("feature", is_numerical=is_numerical) + block = create_transformer(method, is_numerical=is_numerical, config=config, representation=resolved) + data = ( + np.array([[0.0], [1.0], [np.nan], [2.0]]) + if is_numerical + else np.array([["a"], ["b"], [np.nan], ["a"]], dtype=object) + ) + result = block.fit_transform(data) + indicator = missing_policy in {"impute_with_indicator", "separate_state"} + assert result.shape == (4, (3 if is_numerical else 2) + int(indicator)) + assert isinstance(block, FeatureUnion if indicator else Pipeline) + representation = dict(block.transformer_list)["representation"] if isinstance(block, FeatureUnion) else block + assert isinstance(representation, Pipeline) + assert representation.named_steps["imputer"].strategy == ("median" if is_numerical else "most_frequent") + if indicator: + values = result.toarray() if issparse(result) else result + np.testing.assert_array_equal(values[:, -1], [0, 0, 1, 0]) + + +def test_resolved_representation_keeps_run_wide_scaling(make_config): + config = make_config(scaling="standardization", feature_preprocessing={"age": {"method": "rbf", "output_dim": 3}}) + block = create_transformer( + "rbf", is_numerical=True, config=config, representation=config.representation_for("age", is_numerical=True) + ) + assert isinstance(block, Pipeline) + assert _names(block.steps) == ["imputer", "scaler", "rbf"] + + +@pytest.mark.parametrize(("method", "is_numerical"), [("rbf", True), ("one-hot", False)]) +def test_explicit_none_representation_keeps_exact_legacy_calls(make_config, method, is_numerical): + config = make_config() + target = ( + "pretab.compose.factory.get_numerical_transformer_steps" + if is_numerical + else "pretab.compose.factory.get_categorical_transformer_steps" + ) + builder = get_numerical_transformer_steps if is_numerical else get_categorical_transformer_steps + with patch(target, wraps=builder) as steps: + create_transformer(method, is_numerical=is_numerical, config=config) + omitted = steps.call_args + create_transformer(method, is_numerical=is_numerical, config=config, representation=None) + assert steps.call_args == omitted + + +@pytest.mark.parametrize("value", [{"method": "rbf"}, "rbf", False]) +def test_factory_resolved_input_requires_a_typed_value(make_config, value): + with pytest.raises(InvalidParamError, match="must be a RepresentationConfig or None"): + create_transformer("rbf", is_numerical=True, config=make_config(), representation=value) + + +@pytest.mark.parametrize(("selected", "requested", "is_numerical"), [("int", "rbf", False), ("rff", "rff", True)]) +def test_factory_resolved_input_does_not_broaden_method_selection(make_config, selected, requested, is_numerical): + with pytest.raises(InvalidParamError): + create_transformer( + selected, + is_numerical=is_numerical, + config=make_config(), + representation=RepresentationConfig(method=requested), + ) diff --git a/tests/compose/test_feature_groups_config.py b/tests/compose/test_feature_groups_config.py new file mode 100644 index 0000000..b62bf88 --- /dev/null +++ b/tests/compose/test_feature_groups_config.py @@ -0,0 +1,303 @@ +"""Pre-fit ownership and input-capability contracts for explicit groups.""" + +from copy import deepcopy +from dataclasses import replace +from re import escape + +import numpy as np +import pandas as pd +import pytest + +from pretab import FeatureGroup, Preprocessor, RepresentationConfig +from pretab.compose.config import PreprocessorConfig +from pretab.compose.registry import TRANSFORMER_REGISTRY +from pretab.exceptions import IncompatibleParamsError, InvalidParamError, OptionalDependencyError, PretabDataError + + +@pytest.fixture +def stop_after_group_preflight(monkeypatch): + def reached(*args, **kwargs): + raise RuntimeError("group preflight complete") + + monkeypatch.setattr("pretab.preprocessor.build_column_transformer", reached) + + +@pytest.fixture +def group_frame(): + return pd.DataFrame( + { + "x": [0.0, 1.0, 2.0], + "y": [2.0, 3.0, 4.0], + "z": [4.0, 5.0, 6.0], + "flag": [True, False, True], + } + ) + + +@pytest.mark.parametrize("method", ["tensorspline", "tprs"]) +@pytest.mark.parametrize( + ("columns", "other_groups", "overrides", "expected"), + [ + (["x", "x"], {}, None, "feature_groups['location'].columns[1]"), + ( + ["x", "y"], + {"other": {"columns": ["y", "z"], "representation": "tprs"}}, + None, + "feature_groups['other'].columns[0]", + ), + (["x", "y"], {}, {"x": "tprs"}, "feature_preprocessing['x']"), + (["x", "absent"], {}, None, "feature_groups['location'].columns[1]"), + (["x"], {}, None, "feature_groups['location'].columns"), + (["x", "flag"], {}, None, "feature_groups['location'].columns[1]"), + ], + ids=["duplicate", "overlap", "override", "missing", "min-arity", "boolean"], +) +def test_group_conflicts_precede_factory(group_frame, monkeypatch, method, columns, other_groups, overrides, expected): + def reject_construction(*args, **kwargs): + raise AssertionError("Group validation must precede factory construction") + + monkeypatch.setattr("pretab.preprocessor.build_column_transformer", reject_construction) + groups = {"location": {"columns": columns, "representation": method}, **other_groups} + original = deepcopy(groups) + processor = Preprocessor(feature_groups=groups, feature_preprocessing=overrides) + with pytest.raises(InvalidParamError, match=escape(expected)) as failure: + processor.fit(group_frame) + assert "location" in str(failure.value) + assert groups == original + assert not hasattr(processor, "column_transformer_") + assert not hasattr(processor, "numerical_features_") + + +@pytest.mark.parametrize("method", ["tensor", "thinplate"]) +@pytest.mark.parametrize("mapping_form", [False, True]) +def test_valid_groups_keep_declared_order_and_unclaimed_sources(make_config, group_frame, method, mapping_form): + declaration = FeatureGroup("location", ["z", "x"], method) + groups = {"location": {"columns": ["z", "x"], "representation": method}} if mapping_form else [declaration] + config = make_config(feature_groups=groups) + original = config.feature_groups + before = group_frame.copy(deep=True) + assert config.validate_feature_groups(group_frame.columns, ["x", "y", "z"]) is None + assert config.feature_groups is original + assert original[0].columns == ("z", "x") + assert original[0].representation.method == {"tensor": "tensorspline", "thinplate": "tprs"}[method] + assert isinstance(declaration.representation, RepresentationConfig) + assert declaration.representation.method == method + pd.testing.assert_frame_equal(group_frame, before) + + +@pytest.mark.parametrize( + ("bounds", "columns", "constraint"), + [ + ({"min_arity": 3}, ["x", "y"], "at least 3"), + ({"max_arity": 2}, ["x", "y", "z"], "2 to 2"), + ], +) +def test_group_arity_uses_live_registry_bounds(group_frame, monkeypatch, bounds, columns, constraint): + spec = TRANSFORMER_REGISTRY["tprs"] + monkeypatch.setitem(TRANSFORMER_REGISTRY, "tprs", replace(spec, **bounds)) + processor = Preprocessor(feature_groups={"location": {"columns": columns, "representation": "tprs"}}) + with pytest.raises(InvalidParamError, match=escape("feature_groups['location'].columns")) as failure: + processor.fit(group_frame) + assert constraint in str(failure.value) + + +@pytest.mark.parametrize( + "values", + [ + pd.Series([True, False, True]), + pd.Series([True, None, False], dtype="boolean"), + pd.Series(["a", "b", "a"], dtype="string"), + pd.Series([1.0, 2.0, 1.0], dtype="category"), + pd.Series([1, 1, 2]), + pd.Series([1, None, 2], dtype="Int64"), + ], + ids=["boolean", "nullable-boolean", "string", "category", "low-cardinality-integer", "nullable-integer"], +) +def test_categorical_sources_are_not_coerced_to_numerical(group_frame, values): + processor = Preprocessor( + cat_cutoff=3, + feature_groups={"location": {"columns": ["x", "source"], "representation": "tprs"}}, + ) + with pytest.raises(InvalidParamError, match=escape("feature_groups['location'].columns[1]")) as failure: + processor.fit(group_frame.assign(source=values)) + assert "detected categorical" in str(failure.value) + assert "'source'" in str(failure.value) + + +@pytest.mark.parametrize("dtype", ["int64", "Int64"]) +def test_explicit_integer_routing_remains_available_to_groups(group_frame, dtype, stop_after_group_preflight): + processor = Preprocessor( + cat_cutoff=3, + treat_all_integers_as_numerical=True, + feature_groups={"location": {"columns": ["x", "code"], "representation": "tprs"}}, + ) + with pytest.raises(RuntimeError, match="group preflight complete"): + processor.fit(group_frame.assign(code=pd.Series([1, 1, 2], dtype=dtype))) + + +@pytest.mark.parametrize( + ("named", "columns", "missing_index"), + [ + (True, [7, 3], None), + (True, ["7", "3"], 0), + (True, [0, 1], 0), + (False, ["feature_1", "feature_0"], None), + (False, [1, 0], 0), + (False, ["feature_0", "absent"], 1), + ], +) +def test_group_sources_follow_existing_label_route(named, columns, missing_index, stop_after_group_preflight): + values = np.array([[0.0, 2.0], [1.0, 3.0], [2.0, 4.0]]) + data = pd.DataFrame(values, columns=pd.Index([7, 3])) if named else values + before = data.copy() + processor = Preprocessor(feature_groups={"location": {"columns": columns, "representation": "tprs"}}) + expected = ( + "group preflight complete" + if missing_index is None + else escape(f"feature_groups['location'].columns[{missing_index}]") + ) + error = RuntimeError if missing_index is None else InvalidParamError + with pytest.raises(error, match=expected): + processor.fit(data) + if named: + pd.testing.assert_frame_equal(data, before) + else: + np.testing.assert_array_equal(data, before) + + +def test_groups_do_not_bypass_existing_string_label_collision_validation(): + data = pd.DataFrame([[0.0, 1.0], [2.0, 3.0]], columns=pd.Index([1, "1"], dtype=object)) + processor = Preprocessor(feature_groups={"location": {"columns": [1, "1"], "representation": "tprs"}}) + with pytest.raises(PretabDataError, match="converted to strings"): + processor.fit(data) + assert list(data.columns) == [1, "1"] + + +@pytest.mark.parametrize("groups", [None, {}, [], ()]) +def test_empty_groups_do_not_enter_group_preflight(group_frame, monkeypatch, groups): + def unexpected(*args, **kwargs): + pytest.fail("The no-groups route must not call group preflight") + + monkeypatch.setattr(PreprocessorConfig, "validate_feature_groups", unexpected) + processor = Preprocessor(numerical_method="standardization", categorical_method="int", feature_groups=groups).fit( + group_frame + ) + assert processor.feature_groups is groups + + +@pytest.mark.parametrize("usage", ["required", "optional"]) +@pytest.mark.parametrize("has_target", [False, True]) +def test_group_target_requirements_keep_typed_errors( + group_frame, monkeypatch, usage, has_target, stop_after_group_preflight +): + def unexpected(*args, **kwargs): + pytest.fail("Group target validation must not construct a transformer") + + spec = TRANSFORMER_REGISTRY["tprs"] + monkeypatch.setitem( + TRANSFORMER_REGISTRY, + "tprs", + replace(spec, target_usage=usage, placement_strategies=frozenset({"cart"}), transformer_cls=unexpected), + ) + processor = Preprocessor( + feature_groups={ + "location": { + "columns": ["x", "y"], + "representation": {"method": "tprs", "target_aware": True, "placement_strategy": "cart"}, + } + } + ) + target = np.array([0.0, 1.0, 2.0]) if has_target else None + if has_target: + with pytest.raises(RuntimeError, match="group preflight complete"): + processor.fit(group_frame, target) + else: + with pytest.raises(IncompatibleParamsError, match=escape("feature_groups['location'].representation.method")): + processor.fit(group_frame) + assert not hasattr(processor, "column_transformer_") + + +@pytest.mark.parametrize("local_off", [False, True]) +def test_group_target_check_uses_resolved_settings(group_frame, monkeypatch, local_off, stop_after_group_preflight): + spec = TRANSFORMER_REGISTRY["tprs"] + monkeypatch.setitem( + TRANSFORMER_REGISTRY, + "tprs", + replace(spec, target_usage="optional", placement_strategies=frozenset({"uniform", "cart"})), + ) + representation = {"method": "tprs", "target_aware": False, "placement_strategy": "uniform"} if local_off else "tprs" + processor = Preprocessor( + target_aware=True, + placement_strategy="cart", + feature_groups={"location": {"columns": ["x", "y"], "representation": representation}}, + ) + error = RuntimeError if local_off else IncompatibleParamsError + expected = "group preflight complete" if local_off else "requires y at fit time" + with pytest.raises(error, match=expected): + processor.fit(group_frame) + + +@pytest.mark.parametrize("available", [False, True]) +def test_group_dependency_check_is_contextual_without_import_or_construction( + group_frame, monkeypatch, available, stop_after_group_preflight +): + discovered = [] + + def discover(module_name): + discovered.append(module_name) + return object() if available else None + + def unexpected(*args, **kwargs): + pytest.fail("Group validation must not import optional packages or construct a transformer") + + spec = TRANSFORMER_REGISTRY["tprs"] + monkeypatch.setitem( + TRANSFORMER_REGISTRY, "tprs", replace(spec, optional_dependency="embeddings", transformer_cls=unexpected) + ) + monkeypatch.setattr("pretab.core.dependencies.importlib.util.find_spec", discover) + monkeypatch.setattr("pretab.core.dependencies.importlib.import_module", unexpected) + processor = Preprocessor(feature_groups={"location": {"columns": ["x", "y"], "representation": "tprs"}}) + if available: + with pytest.raises(RuntimeError, match="group preflight complete"): + processor.fit(group_frame) + else: + with pytest.raises(OptionalDependencyError) as failure: + processor.fit(group_frame) + assert "feature_groups['location'].representation.method" in str(failure.value) + assert "pip install pretab[embeddings]" in str(failure.value) + assert discovered + assert set(discovered) == {"sentence_transformers"} + + +def test_group_placement_dependency_keeps_context_and_install_hint(group_frame, monkeypatch): + spec = TRANSFORMER_REGISTRY["tprs"] + monkeypatch.setitem( + TRANSFORMER_REGISTRY, + "tprs", + replace(spec, target_usage="optional", placement_strategies=frozenset({"lightgbm"})), + ) + monkeypatch.setattr("pretab.core.dependencies.importlib.util.find_spec", lambda module_name: None) + processor = Preprocessor( + feature_groups={ + "location": { + "columns": ["x", "y"], + "representation": {"method": "tprs", "target_aware": True, "placement_strategy": "lightgbm"}, + } + } + ) + with pytest.raises(OptionalDependencyError) as failure: + processor.fit(group_frame, np.array([0.0, 1.0, 2.0])) + assert "feature_groups['location'].representation.placement_strategy" in str(failure.value) + assert "pip install pretab[lightgbm]" in str(failure.value) + + +def test_builtin_group_preflight_does_not_discover_unselected_extras( + group_frame, monkeypatch, stop_after_group_preflight +): + def unexpected(*args, **kwargs): + pytest.fail("No optional dependency is selected") + + monkeypatch.setattr("pretab.core.dependencies.importlib.util.find_spec", unexpected) + processor = Preprocessor(feature_groups={"location": {"columns": ["x", "y"], "representation": "tprs"}}) + with pytest.raises(RuntimeError, match="group preflight complete"): + processor.fit(group_frame) diff --git a/tests/compose/test_inspection.py b/tests/compose/test_inspection.py index a76ee31..cb0ff5f 100644 --- a/tests/compose/test_inspection.py +++ b/tests/compose/test_inspection.py @@ -1,20 +1,30 @@ """Unit tests for :mod:`pretab.compose.inspection`.""" import warnings +from types import SimpleNamespace +from typing import Any, cast +from unittest.mock import Mock import numpy as np import pandas as pd import pytest from sklearn.compose import ColumnTransformer from sklearn.pipeline import Pipeline +from sklearn.preprocessing import FunctionTransformer, MaxAbsScaler, PolynomialFeatures from pretab.compose.factory import build_column_transformer, get_categorical_transformer_steps from pretab.compose.inspection import ( + _iter_fitted_blocks, + _locate_block_representation, + block_uses_target, build_feature_info, + build_feature_lineage, build_transformer_summary, clean_feature_names, + feature_names_out, get_output_slices, ) +from pretab.core.representation import RepresentationSpec @pytest.fixture @@ -24,6 +34,176 @@ def fitted_ct(make_config, sample_frame): return ct, sample_frame +@pytest.fixture(params=["tensorspline", "tprs"]) +def grouped_ct(request, make_config): + values = np.random.default_rng(42).normal(size=(24, 3)) + frame = pd.DataFrame(values, columns=pd.Index(["age", "x% west", "y+east"])) + frame["city"] = ["a", "b"] * 12 + options = ( + {"output_dim": 3, "degree": 2} + if request.param == "tensorspline" + else {"n_components": 3, "landmark_strategy": "subsample", "random_state": 0} + ) + config = make_config( + feature_groups={ + "location": {"columns": ["y+east", "x% west"], "representation": {"method": request.param, **options}} + } + ) + transformer = build_column_transformer(config, ["age", "x% west", "y+east"], ["city"]) + transformer.fit(frame) + return transformer, frame + + +def test_group_feature_info_counts_joint_width_once(grouped_ct): + transformer, _ = grouped_ct + info = build_feature_info(transformer, embeddings=False, embedding_dimensions={}) + assert len(info) == 3 + numerical, categorical, embeddings = info + assert list(numerical) == ["age", "group_location"] + assert list(categorical) == ["city"] + assert embeddings == {} + group = numerical["group_location"] + span = transformer.output_indices_["group_location"] + assert group["dimension"] == span.stop - span.start + assert group["group"] == "location" + assert group["source_features"] == ("y+east", "x% west") + assert group["categories"] is None + assert set(numerical["age"]) == {"preprocessing", "dimension", "categories"} + + +def test_group_names_encode_ordered_sources_and_preserve_leaf_names(grouped_ct): + transformer, _ = grouped_ct + raw = transformer.get_feature_names_out() + names = feature_names_out(transformer) + span = transformer.output_indices_["group_location"] + expected = [f"group_location__y%2Beast+x%25%20west__{name.partition('__')[2]}" for name in raw[span]] + assert names[span] == expected + assert len(set(names)) == len(names) + assert names[0] == "num_age" + + +def test_explicit_group_display_names_preserve_identity_without_mutating_fit(grouped_ct): + transformer, _ = grouped_ct + original = feature_names_out(transformer) + fitted = transformer.feature_names_in_.copy() + renamed = feature_names_out(transformer, ["years", "west%", "east+", "town"]) + span = transformer.output_indices_["group_location"] + assert all(name.startswith("group_location__east%2B+west%25__") for name in renamed[span]) + assert renamed[0] == "num_years" + assert len(renamed) == len(original) + assert feature_names_out(transformer) == original + np.testing.assert_array_equal(transformer.feature_names_in_, fitted) + with pytest.raises(ValueError): + feature_names_out(transformer, ["too", "short"]) + + +def test_group_lineage_covers_actual_span_with_one_identity(grouped_ct): + transformer, _ = grouped_ct + names = feature_names_out(transformer) + lineage = build_feature_lineage(transformer) + span = transformer.output_indices_["group_location"] + assert [record.output_feature for record in lineage] == names + assert [record.output_index for record in lineage] == list(range(len(names))) + for record in lineage[span]: + assert record.group_id == "group_location" + assert record.source_features == ("y+east", "x% west") + assert record.to_dict()["group_id"] == "group_location" + assert [record.component_index for record in lineage[span]] == list(range(span.stop - span.start)) + for record in [*lineage[: span.start], *lineage[span.stop :]]: + assert record.group_id is None + assert "group_id" not in record.to_dict() + + +@pytest.fixture +def declared_representation(): + spec = RepresentationSpec( + family="declared_joint_basis", + component_kind="basis", + scope="multivariate", + supervision="optional", + uses_target=True, + is_interaction=True, + input_features=("age", "income"), + output_features=("age_income",), + output_dim=1, + degree=None, + include_bias=False, + periodic=False, + period=None, + local_support=False, + location_kind=None, + locations=None, + ) + representation = Mock(spec=["get_representation_spec", "n_features_in_"]) + representation.n_features_in_ = 2 + representation.get_representation_spec.return_value = spec + return representation + + +@pytest.mark.parametrize("step_name", ["representation", "scaler", "onehot"]) +@pytest.mark.parametrize("trailing_helper", [False, True]) +def test_locate_representation_spec_precedes_legacy_steps(declared_representation, step_name, trailing_helper): + steps = [("imputer", FunctionTransformer()), (step_name, declared_representation)] + if trailing_helper: + steps.append(("minmax", MaxAbsScaler())) + pipeline = Pipeline(steps) + + assert _locate_block_representation(pipeline, ["age", "income"]) == ( + 1, + ("declared_joint_basis", "basis", True, True), + ) + assert block_uses_target(pipeline) is True + + +@pytest.mark.parametrize( + ("columns", "fitted_width", "expected_names"), + [ + (["age", "income"], 2, ["age", "income"]), + (("age", "income"), 2, ["age", "income"]), + (["age"], 2, None), + (None, 2, None), + ], +) +def test_locate_representation_only_forwards_matching_input_names( + declared_representation, columns, fitted_width, expected_names +): + declared_representation.n_features_in_ = fitted_width + + assert _locate_block_representation(declared_representation, columns) == ( + 0, + ("declared_joint_basis", "basis", True, True), + ) + declared_representation.get_representation_spec.assert_called_once_with(input_features=expected_names) + + +def test_locate_representation_uses_the_rightmost_declared_spec(declared_representation): + earlier = Mock(spec=["get_representation_spec"]) + earlier.get_representation_spec.side_effect = AssertionError("An earlier declaration must not be inspected") + pipeline = Pipeline([("earlier", earlier), ("representation", declared_representation), ("scaler", MaxAbsScaler())]) + + assert _locate_block_representation(pipeline, ["age", "income"]) == ( + 1, + ("declared_joint_basis", "basis", True, True), + ) + earlier.get_representation_spec.assert_not_called() + + +@pytest.mark.parametrize( + ("step_names", "expected"), + [ + (["scaler"], (0, ("standardization", "raw", False, False))), + (["onehot", "scaler"], (1, ("standardization", "raw", False, False))), + (["scaler", "onehot"], (1, ("onehot", "category", False, False))), + (["imputer", "to_float"], (None, ("passthrough", "raw", False, False))), + ], +) +def test_locate_representation_legacy_fallback_is_the_rightmost_known_step(step_names, expected): + pipeline = Pipeline([(name, FunctionTransformer()) for name in step_names]) + + assert _locate_block_representation(pipeline, ["age"]) == expected + assert block_uses_target(pipeline) is False + + def test_get_output_slices_are_ordered_and_named(fitted_ct): ct, _ = fitted_ct slices = get_output_slices(ct) @@ -34,6 +214,59 @@ def test_get_output_slices_are_ordered_and_named(fitted_ct): assert all(width >= 1 for _, _, width in slices) +def test_fitted_block_view_retains_entries_and_fitted_references(): + transformer = Mock(spec=["fit", "transform", "get_feature_names_out", "get_representation_spec"]) + columns = ["age__years"] + ct = SimpleNamespace( + transformers_=[ + ("num_0", transformer, columns), + ("cat_city", "drop", ["city"]), + ("empty", "passthrough", []), + ("unmapped", "passthrough", ["other"]), + ("remainder", "passthrough", [1]), + ], + output_indices_={ + "num_0": slice(0, 2), + "cat_city": slice(0, 0), + "empty": slice(2, 2), + "remainder": slice(2, 3), + }, + ) + original_blocks = ct.transformers_.copy() + original_indices = ct.output_indices_.copy() + + blocks = list(_iter_fitted_blocks(ct)) + + assert [block.step_name for block in blocks] == [entry[0] for entry in original_blocks] + for block, (_, fitted, selector) in zip(blocks, original_blocks, strict=True): + assert block.transformer is fitted + assert block.columns is selector + assert blocks[0].public_name == "num_age__years" + assert blocks[0].span is ct.output_indices_["num_0"] + with pytest.raises(AttributeError): + cast(Any, blocks[0]).step_name = "replacement" + with pytest.raises(KeyError, match="unmapped"): + _ = blocks[3].span + assert get_output_slices(ct) == [("num_age__years", 0, 2), ("remainder", 2, 1)] + assert ct.transformers_ == original_blocks + assert ct.output_indices_ == original_indices + assert transformer.mock_calls == [] + + +def test_fitted_block_view_does_not_eagerly_read_names_or_spans(): + columns = slice(0, 2) + transformer = object() + ct = SimpleNamespace(transformers_=[("joint", transformer, columns)]) + + block = next(_iter_fitted_blocks(ct)) + + assert block.step_name == "joint" + assert block.transformer is transformer + assert block.columns is columns + with pytest.raises(AttributeError, match="output_indices_"): + _ = block.span + + def test_build_feature_info_splits_numerical_and_categorical(fitted_ct): ct, _ = fitted_ct numerical, categorical, embeddings = build_feature_info(ct, embeddings=False, embedding_dimensions={}) @@ -60,13 +293,28 @@ def test_build_feature_info_does_not_infer_kind_from_cat_in_feature_name(make_co assert feature not in categorical +def test_build_feature_info_uses_fitted_width_without_transform(monkeypatch): + frame = pd.DataFrame({"age": [1.0, 2.0, 4.0]}) + pipeline = Pipeline([("positive_only", FunctionTransformer(np.log, feature_names_out="one-to-one"))]) + ct = ColumnTransformer([("num_age", pipeline, ["age"])]).fit(frame) + expected = ct.transform(frame) + expected_names = ct.get_feature_names_out() + + def reject_transform(*_args, **_kwargs): + raise AssertionError("Feature inspection must not invoke transform") + + fitted_transformer = ct.named_transformers_["num_age"].named_steps["positive_only"] + monkeypatch.setattr(fitted_transformer, "transform", reject_transform) + + numerical, _, _ = build_feature_info(ct, embeddings=False, embedding_dimensions={}) + + assert numerical["age"]["dimension"] == np.shape(expected)[1] == len(expected_names) == 1 + assert numerical["age"]["dimension"] == get_output_slices(ct)[0][2] + + @pytest.mark.parametrize(("method", "dimension"), [("rbf", 3), ("standardization", 1)]) -def test_build_feature_info_probes_a_step_fitted_on_the_frame_without_warning( - make_config, sample_frame, method, dimension -): - """Without an imputer the representation is fitted on the DataFrame column and - records ``feature_names_in_``; probing it with a bare array warned that X does - not have valid feature names.""" +def test_build_feature_info_reads_width_after_frame_fit_without_warning(make_config, sample_frame, method, dimension): + """Fitting on named columns must not trigger feature-name warnings during inspection.""" config = make_config(numerical_method=method, numerical_imputation=None, output_dim=3) ct = build_column_transformer(config, ["age"], ["city"]).fit(sample_frame) @@ -91,6 +339,82 @@ def test_build_feature_info_reports_a_zero_width_block(): assert categorical["city"]["dimension"] == 0 +@pytest.mark.parametrize("sparse_output", [False, True]) +def test_build_feature_info_reports_zero_width_after_dropping_only_category(sparse_output): + frame = pd.DataFrame({"city": ["Rome", "Rome", "Rome"], "age": [1.0, 2.0, 3.0]}) + steps = get_categorical_transformer_steps("one-hot", sparse_output=sparse_output, drop="first") + ct = ColumnTransformer([("cat_city", Pipeline(steps), ["city"]), ("num_age", "passthrough", ["age"])]).fit(frame) + + _, categorical, _ = build_feature_info(ct, embeddings=False, embedding_dimensions={}) + + span = ct.output_indices_["cat_city"] + assert categorical["city"]["dimension"] == np.shape(ct.transform(frame)[:, span])[1] == 0 + assert categorical["city"]["categories"] == 1 + assert np.shape(ct.transform(frame))[1] == len(ct.get_feature_names_out()) == 1 + assert get_output_slices(ct) == [("num_age", 0, 1)] + + +@pytest.mark.parametrize("sparse_output", [False, True]) +@pytest.mark.parametrize("suffix", ["to_float", "scaler", "polynomial"]) +@pytest.mark.parametrize( + "encoder_options", + [{}, {"drop": "first"}, {"min_frequency": 2}, {"max_categories": 2}, {"drop": "first", "min_frequency": 2}], +) +def test_build_feature_info_separates_vocabulary_from_emitted_width( + monkeypatch, sparse_output, suffix, encoder_options +): + frame = pd.DataFrame({"city": ["Rome", "Rome", "Berlin", "Oslo", "Paris"]}) + steps = get_categorical_transformer_steps( + "one-hot", add_imputer=False, sparse_output=sparse_output, **encoder_options + ) + if suffix == "scaler": + steps.append(("scaler", MaxAbsScaler())) + elif suffix == "polynomial": + steps.append(("polynomial", PolynomialFeatures(degree=2, include_bias=False))) + ct = ColumnTransformer([("cat_city", Pipeline(steps), ["city"])]).fit(frame) + expected = ct.transform(frame) + expected_names = ct.get_feature_names_out() + reject_transform = Mock(side_effect=AssertionError("Feature inspection must not invoke transform")) + for _, step in ct.named_transformers_["cat_city"].steps: + monkeypatch.setattr(step, "transform", reject_transform) + + numerical, categorical, _ = build_feature_info(ct, embeddings=False, embedding_dimensions={}) + + assert numerical == {} + assert categorical["city"]["categories"] == 4 + assert categorical["city"]["dimension"] == np.shape(expected)[1] == len(expected_names) + assert categorical["city"]["dimension"] == get_output_slices(ct)[0][2] + reject_transform.assert_not_called() + + +@pytest.mark.parametrize("missing_options", [{"add_missing_indicator": True}, {"missing_policy": "separate_state"}]) +def test_build_feature_info_uses_combined_indicator_span(make_config, missing_options): + frame = pd.DataFrame({"age": [1.0, np.nan, 3.0, 4.0], "city": ["Rome", np.nan, "Oslo", "Rome"]}) + config = make_config(numerical_method="rbf", output_dim=3, categorical_method="one-hot", **missing_options) + ct = build_column_transformer(config, ["age"], ["city"]).fit(frame) + + numerical, categorical, _ = build_feature_info(ct, embeddings=False, embedding_dimensions={}) + spans = {name: width for name, _, width in get_output_slices(ct)} + + assert numerical["age"]["dimension"] == spans["num_age"] == 4 + assert categorical["city"]["dimension"] == spans["cat_city"] == 3 + assert categorical["city"]["categories"] == 2 + assert sum(spans.values()) == np.shape(ct.transform(frame))[1] == len(ct.get_feature_names_out()) + + +@pytest.mark.parametrize("passthrough", ["direct", "pipeline"]) +def test_build_feature_info_handles_passthrough_and_dropped_blocks(passthrough): + frame = pd.DataFrame({"age": [1.0, 2.0, 3.0], "ignored": [4.0, 5.0, 6.0]}) + transformer = "passthrough" if passthrough == "direct" else Pipeline([("passthrough", "passthrough")]) + ct = ColumnTransformer([("num_age", transformer, ["age"]), ("num_ignored", "drop", ["ignored"])]).fit(frame) + + numerical, categorical, _ = build_feature_info(ct, embeddings=False, embedding_dimensions={}) + + assert list(numerical) == ["age"] + assert categorical == {} + assert numerical["age"]["dimension"] == np.shape(ct.transform(frame))[1] == len(ct.get_feature_names_out()) == 1 + + def test_build_transformer_summary_has_header_and_rows(): numerical = {"age": {"preprocessing": "imputer -> standardization", "dimension": 1, "categories": None}} categorical = {"city": {"preprocessing": "imputer -> continuous_ordinal", "dimension": 1, "categories": 3}} diff --git a/tests/compose/test_registry_contract.py b/tests/compose/test_registry_contract.py index 8611fc5..bf298ef 100644 --- a/tests/compose/test_registry_contract.py +++ b/tests/compose/test_registry_contract.py @@ -64,6 +64,59 @@ def test_arity_valid(name, spec): assert spec.arity in _VALID_ARITY +@pytest.mark.parametrize("name, spec", _SPEC_ITEMS, ids=_SPEC_IDS) +def test_group_capabilities_are_explicit_and_independent_of_single_column_selection(name, spec): + expected = (True, 2, None) if name in {"tensorspline", "tprs"} else (False, 1, 1) + assert (spec.group_compatible, spec.min_arity, spec.max_arity) == expected + if spec.group_compatible: + assert spec.feature_kind == frozenset({"numerical"}) + assert spec.is_multivariate + assert spec.preprocessor_compatible is False + assert name not in NUMERICAL_METHODS + + +def test_legacy_positional_spec_uses_group_defaults(): + spec = TransformerSpec( + "legacy", + TRANSFORMER_REGISTRY["rbf"].transformer_cls, + ("gamma",), + frozenset({"numerical"}), + "multivariate", + "optional", + frozenset({"uniform", "cart"}), + True, + False, + None, + True, + True, + ) + + assert spec.name == "legacy" + assert spec.allowed_args == ("gamma",) + assert spec.is_multivariate + assert spec.target_aware_capable + assert spec.supports_adaptive_resolution + assert spec.preprocessor_compatible is False + assert spec.optional_dependency is None + assert spec.periodic and spec.sparse_output + assert (spec.group_compatible, spec.min_arity, spec.max_arity) == (False, 1, 1) + + +@pytest.mark.parametrize("name", ["tensorspline", "tprs", "rff", "nystroem"]) +@pytest.mark.parametrize("n_features", [1, 3]) +def test_group_arity_metadata_does_not_constrain_standalone_inputs(name, n_features): + data = np.random.default_rng(0).uniform(size=(40, n_features)) + options = {"output_dim": 4} if name == "tensorspline" else {"n_components": 4, "random_state": 0} + transformer = TRANSFORMER_REGISTRY[name].transformer_cls(**options) + + transformed = transformer.fit_transform(data) + + expected_width = 4**n_features if name == "tensorspline" else 4 + assert transformed.shape == (40, expected_width) + assert transformer.n_features_in_ == n_features + assert np.isfinite(transformed).all() + + @pytest.mark.parametrize("name, spec", _SPEC_ITEMS, ids=_SPEC_IDS) def test_target_usage_valid(name, spec): assert spec.target_usage in _VALID_TARGET_USAGE diff --git a/tests/compose/test_representation_config.py b/tests/compose/test_representation_config.py new file mode 100644 index 0000000..f94578c --- /dev/null +++ b/tests/compose/test_representation_config.py @@ -0,0 +1,570 @@ +"""Value semantics for immutable, portable representation settings.""" + +import copy +import json +import pickle +from collections import UserDict +from dataclasses import FrozenInstanceError, is_dataclass, replace +from types import MappingProxyType +from typing import Any, cast + +import pytest +from sklearn.base import clone + +from pretab import Preprocessor +from pretab.compose.config import FeatureGroup, RepresentationConfig, _normalize_representation_config +from pretab.compose.factory import get_categorical_transformer_steps, get_numerical_transformer_steps +from pretab.compose.registry import TRANSFORMER_REGISTRY +from pretab.core.parameters import UNSET +from pretab.exceptions import InvalidParamError, OptionalDependencyError + + +@pytest.mark.parametrize("form", ["string", "mapping", "value"]) +def test_feature_group_value_accepts_existing_representation_forms(form): + requested = {"string": "tprs", "mapping": {"method": "tprs"}, "value": RepresentationConfig("tprs")}[form] + group = FeatureGroup("location", [1, "latitude"], requested) + + assert group.columns == (1, "latitude") + assert group.representation == RepresentationConfig("tprs") + with pytest.raises(FrozenInstanceError): + cast(Any, group).name = "replacement" + + +def test_feature_group_value_detaches_columns_and_nested_settings(): + columns = ["longitude", "latitude"] + settings = {"method": "tprs", "params": {"options": {"levels": [1, 2]}}} + group = FeatureGroup("location", columns, settings) + columns.reverse() + settings["params"]["options"]["levels"].append(3) + + assert group.columns == ("longitude", "latitude") + assert isinstance(group.representation, RepresentationConfig) + assert group.representation.params["options"]["levels"] == (1, 2) + with pytest.raises(TypeError): + group.representation.params["options"]["levels"][0] = 9 + + +@pytest.mark.parametrize("name", ["", " ", "_location", "1location", "a-b", "a b", "a__b", "caf\u00e9", None, True, 1]) +def test_feature_group_value_rejects_invalid_identifiers(name): + with pytest.raises(InvalidParamError, match=r"FeatureGroup\.name"): + FeatureGroup(name, ["x", "y"], "tprs") + + +@pytest.mark.parametrize( + "columns", [[], (), "xy", b"xy", {"x", "y"}, {"x": 1}, slice(0, 2), lambda: ["x"], None, [["x"]]] +) +def test_feature_group_value_rejects_unordered_or_invalid_columns(columns): + with pytest.raises(InvalidParamError, match=r"FeatureGroup\.columns"): + FeatureGroup("location", columns, "tprs") + + +@pytest.mark.parametrize( + "restore", + [ + copy.copy, + copy.deepcopy, + lambda value: pickle.loads(pickle.dumps(value)), # noqa: S301 + lambda value: clone(value, safe=False), + ], +) +def test_feature_group_value_preserves_immutable_settings_through_copy_and_pickle(restore): + group = FeatureGroup("location", [1, "y"], {"method": "tprs", "params": {"options": {"levels": [1, 2]}}}) + restored = restore(group) + + assert restored == group and restored is not group + assert restored.columns == (1, "y") + with pytest.raises(TypeError): + restored.representation.params["options"]["levels"][0] = 9 + + +@pytest.fixture +def nested_registry_option(monkeypatch): + for method in ("rbf", "cubicspline"): + spec = TRANSFORMER_REGISTRY[method] + monkeypatch.setitem(TRANSFORMER_REGISTRY, method, replace(spec, allowed_args=(*spec.allowed_args, "options"))) + + +def test_omitted_fields_remain_unset(): + config = RepresentationConfig(method="rbf") + + assert is_dataclass(config) + for key in ("output_dim", "target_aware", "placement_strategy", "adaptive", "min_output_dim", "max_output_dim"): + assert getattr(config, key) is UNSET + assert config.to_dict() == {"method": "rbf", "params": {}, "name": None} + assert "RepresentationConfig(method='rbf'" in repr(config) + with pytest.raises(FrozenInstanceError): + cast(Any, config).method = "ple" + with pytest.raises(TypeError): + hash(config) + + +def test_nested_values_are_detached_and_read_only(): + original = {"options": {"locations": [1.0, 2.0]}, "labels": ["a", "b"]} + config = RepresentationConfig(method="rbf", params=original) + original["options"]["locations"][0] = 9.0 + original["labels"].append("c") + original["extra"] = True + + assert config.params["options"]["locations"] == (1.0, 2.0) + assert config.params["labels"] == ("a", "b") + assert "extra" not in config.params + with pytest.raises(TypeError): + cast(Any, config.params)["extra"] = True + with pytest.raises(TypeError): + config.params["options"]["extra"] = True + with pytest.raises(TypeError): + config.params["options"]["locations"][0] = 9.0 + + +def test_json_round_trip_and_returned_containers_are_detached(): + config = RepresentationConfig( + method="rbf", + output_dim=3, + adaptive=True, + max_output_dim=None, + params={"options": {"values": [None, False, 2, 0.5, "x"]}}, + name="age", + ) + data = config.to_dict() + assert RepresentationConfig.from_dict(json.loads(json.dumps(data, allow_nan=False))) == config + data["params"]["options"]["values"].append("changed") + assert len(config.to_dict()["params"]["options"]["values"]) == 5 + assert config.to_dict()["max_output_dim"] is None + + +def test_mapping_shorthand_and_order_have_value_equality(): + shorthand = {"method": "RBF", "output_dim": 3, "gamma": 0.5, "params": {"scale": [1, 2]}} + config = RepresentationConfig.from_dict(shorthand) + + assert config == RepresentationConfig(method="RBF", output_dim=3, params={"gamma": 0.5, "scale": (1, 2)}) + assert config != RepresentationConfig(method="rbf", output_dim=3, params={"gamma": 0.5, "scale": [1, 2]}) + assert config.method == "RBF" + assert shorthand == {"method": "RBF", "output_dim": 3, "gamma": 0.5, "params": {"scale": [1, 2]}} + with pytest.raises(KeyError): + config.params["missing"] + + +@pytest.mark.parametrize( + "restore", + [ + copy.copy, + copy.deepcopy, + lambda value: pickle.loads(pickle.dumps(value)), # noqa: S301 + lambda value: clone(value, safe=False), + ], +) +def test_copy_pickle_and_clone_preserve_immutable_values(restore): + config = RepresentationConfig(method="rbf", params={"locations": [{"value": 0.5}]}) + restored = restore(config) + + assert restored == config and restored is not config + assert restored.output_dim is UNSET + with pytest.raises(TypeError): + restored.params["locations"][0]["value"] = 1.0 + + +def test_value_can_be_cloned_as_an_estimator_parameter(): + config = RepresentationConfig(method="rbf", output_dim=3, params={"gamma": 0.5}) + requested = {"age": config} + original = Preprocessor(feature_preprocessing=requested) + copied = cast(Preprocessor, clone(original)) + + assert original.get_params(deep=False)["feature_preprocessing"] is requested + assert copied.feature_preprocessing is not None + assert copied.feature_preprocessing == requested + assert copied.feature_preprocessing is not requested + assert copied.feature_preprocessing["age"] is not config + + +@pytest.mark.parametrize( + "key", + [ + "method", + "output_dim", + "target_aware", + "placement_strategy", + "adaptive", + "min_output_dim", + "max_output_dim", + "params", + "name", + ], +) +def test_common_fields_cannot_be_hidden_in_params(key): + with pytest.raises(InvalidParamError, match="top-level field"): + RepresentationConfig(method="rbf", params={key: 1}) + + +def test_duplicate_family_options_are_rejected(): + with pytest.raises(InvalidParamError, match="also be supplied inside params"): + RepresentationConfig.from_dict({"method": "rbf", "gamma": 0.5, "params": {"gamma": 0.5}}) + + +@pytest.mark.parametrize("key", ["method", "placement_strategy", "name"]) +@pytest.mark.parametrize("value", ["", " ", 3, False, []]) +def test_invalid_text_fields_raise_typed_errors(key, value): + with pytest.raises(InvalidParamError, match=key): + RepresentationConfig(**{"method": "rbf", key: value}) + + +@pytest.mark.parametrize("key", ["output_dim", "min_output_dim", "max_output_dim"]) +@pytest.mark.parametrize("value", [0, -1, True, 2.5, "3"]) +def test_invalid_counts_raise_typed_errors(key, value): + with pytest.raises(InvalidParamError, match=key): + RepresentationConfig(**{"method": "rbf", key: value}) + + +@pytest.mark.parametrize("key", ["target_aware", "adaptive"]) +@pytest.mark.parametrize("value", [0, 1, None, "true"]) +def test_invalid_boolean_fields_raise_typed_errors(key, value): + with pytest.raises(InvalidParamError, match=key): + RepresentationConfig(**{"method": "rbf", key: value}) + + +@pytest.mark.parametrize( + "value", [float("nan"), float("inf"), float("-inf"), b"raw", {1, 2}, object(), lambda: 1, UNSET] +) +def test_opaque_or_nonfinite_nested_values_are_rejected(value): + with pytest.raises(InvalidParamError, match=r"params\['nested'\]\[0\]"): + RepresentationConfig(method="rbf", params={"nested": [value]}) + + +def test_cyclic_containers_are_rejected_without_recursion_error(): + values = [] + values.append(values) + with pytest.raises(InvalidParamError, match="circular references"): + RepresentationConfig(method="rbf", params={"nested": values}) + + +@pytest.mark.parametrize("data", [None, [], {}, {1: "rbf"}, {"method": "rbf", "params": []}]) +def test_invalid_mapping_shape_raises_typed_error(data): + with pytest.raises(InvalidParamError): + RepresentationConfig.from_dict(data) + + +def test_mapping_keys_and_required_values_are_validated(): + for data in [{1: "invalid"}, {"nested": {1: "invalid"}}]: + with pytest.raises(InvalidParamError, match="keys must be strings"): + cast(Any, RepresentationConfig)(method="rbf", params=data) + with pytest.raises(InvalidParamError, match="method"): + cast(Any, RepresentationConfig)(method=UNSET) + with pytest.raises(InvalidParamError, match="output_dim"): + cast(Any, RepresentationConfig)(method="rbf", output_dim=None) + with pytest.raises(InvalidParamError, match="name"): + cast(Any, RepresentationConfig)(method="rbf", name=UNSET) + with pytest.raises(InvalidParamError, match="params"): + cast(Any, RepresentationConfig)(method="rbf", params=None) + + +@pytest.mark.parametrize("form", ["string", "mapping", "value"]) +@pytest.mark.parametrize( + ("method", "is_numerical", "canonical"), + [ + ("rbf", True, "rbf"), + (" R_B F ", True, "rbf"), + ("cubic", True, "cubicspline"), + ("std", True, "standardization"), + ("binning", True, "custombin"), + (" O_H E ", False, "one-hot"), + ("ordinal", False, "int"), + ("one_hot", False, "one-hot"), + ("identity", True, "none"), + ("identity", False, "none"), + ], +) +def test_normalization_forms_are_equivalent_in_their_namespace(form, method, is_numerical, canonical): + requested = {"string": method, "mapping": {"method": method}, "value": RepresentationConfig(method=method)}[form] + normalized = _normalize_representation_config(requested, is_numerical=is_numerical) + + assert normalized == RepresentationConfig(method=canonical) + assert normalized.output_dim is UNSET + assert normalized.to_dict() == {"method": canonical, "params": {}, "name": None} + + +@pytest.mark.parametrize("form", ["mapping", "value"]) +@pytest.mark.parametrize( + ("method", "is_numerical", "canonical"), [("RBF", True, "rbf"), ("Cubic", True, "cubicspline")] +) +def test_normalization_preserves_explicit_and_omitted_settings( + form, method, is_numerical, canonical, nested_registry_option +): + data = { + "method": method, + "output_dim": 3, + "target_aware": False, + "placement_strategy": "uniform", + "min_output_dim": None, + "name": "feature", + "params": {"options": {"values": [None, False, 2, 0.5, "x"]}}, + } + requested = data if form == "mapping" else RepresentationConfig.from_dict(data) + normalized = _normalize_representation_config(requested, is_numerical=is_numerical) + + assert normalized.to_dict() == {**data, "method": canonical} + assert normalized.adaptive is UNSET + assert normalized.max_output_dim is UNSET + assert normalized.min_output_dim is None + assert data["method"] == method + if isinstance(requested, RepresentationConfig): + assert requested.method == method + assert _normalize_representation_config(normalized, is_numerical=is_numerical) == normalized + + +@pytest.mark.parametrize("mapping_type", [dict, UserDict, MappingProxyType]) +def test_normalization_detaches_mapping_at_the_boundary(mapping_type, nested_registry_option): + data = {"method": "RBF", "gamma": 0.5, "params": {"options": {"values": [1, 2]}}} + requested = mapping_type(data) + preprocessor = Preprocessor(feature_preprocessing={"age": requested}) + data["params"]["options"]["values"][0] = 3 + normalized = _normalize_representation_config(requested, is_numerical=True) + data["params"]["options"]["values"].append(4) + + assert normalized == RepresentationConfig(method="rbf", params={"gamma": 0.5, "options": {"values": [3, 2]}}) + assert preprocessor.get_params(deep=False)["feature_preprocessing"]["age"] is requested + assert requested["method"] == "RBF" + assert "gamma" in requested and "gamma" not in requested["params"] + assert _normalize_representation_config(requested, is_numerical=True).params["options"]["values"] == (3, 2, 4) + with pytest.raises(TypeError): + cast(Any, normalized.params)["changed"] = True + + +@pytest.mark.parametrize("is_numerical", [False, True]) +@pytest.mark.parametrize("value", [None, UNSET, [], 1, True, object(), lambda: "rbf"]) +def test_normalization_rejects_unsupported_input_types(value, is_numerical): + with pytest.raises(InvalidParamError, match="must be a string, mapping, or RepresentationConfig"): + _normalize_representation_config(value, is_numerical=is_numerical) + + +@pytest.mark.parametrize( + "data", + [ + {}, + {"method": None}, + {"method": "rbf", "output_dim": True}, + {"method": "rbf", "params": {"method": "ple"}}, + {"method": "rbf", "gamma": 0.5, "params": {"gamma": 0.5}}, + {"method": "rbf", "params": {"gamma": float("nan")}}, + ], +) +def test_normalization_reuses_value_shape_validation(data): + with pytest.raises(InvalidParamError): + _normalize_representation_config(data, is_numerical=True) + + +@pytest.mark.parametrize("form", ["shorthand", "params", "value"]) +@pytest.mark.parametrize( + ("key", "suggestion"), + [("output_dimm", "output_dim"), ("target_awre", "target_aware"), ("gama", "gamma"), ("not_a_real_option", None)], +) +def test_path_errors_for_unknown_keys_include_close_matches(form, key, suggestion): + data: dict[str, Any] = {"method": "RBF"} + if form == "shorthand": + data[key] = 3 + else: + data["params"] = {key: 3} + requested = RepresentationConfig.from_dict(data) if form == "value" else data + path = "feature_preprocessing['age']" + with pytest.raises(InvalidParamError) as failure: + _normalize_representation_config(requested, is_numerical=True, path=path) + + location = key if form == "shorthand" else f"params[{key!r}]" + message = str(failure.value) + assert f"{path}.{location} = 3 is invalid" in message + if suggestion is None: + assert "Did you mean" not in message + else: + assert "Did you mean" in message + assert repr(suggestion) in message.split("\nValid values:")[0] + assert data["method"] == "RBF" + + +@pytest.mark.parametrize("form", ["string", "mapping", "value"]) +@pytest.mark.parametrize( + ("method", "is_numerical"), + [("ordinal", True), ("binning", False), ("not_a_method", True), ("not_a_method", False), ("rbf", False)], +) +def test_path_errors_for_methods_reuse_canonical_factory_choices(form, method, is_numerical): + requested = {"string": method, "mapping": {"method": method}, "value": RepresentationConfig(method=method)}[form] + path = "feature_preprocessing['feature']" + with pytest.raises(InvalidParamError) as failure: + _normalize_representation_config(requested, is_numerical=is_numerical, path=path) + factory = get_numerical_transformer_steps if is_numerical else get_categorical_transformer_steps + with pytest.raises(InvalidParamError) as existing: + factory(method, add_imputer=False) + + assert f"{path}.method" in str(failure.value) + assert str(failure.value).split("\nConstraint:")[1] == str(existing.value).split("\nConstraint:")[1] + + +@pytest.mark.parametrize( + ("data", "location"), + [ + ({}, "method"), + ({"method": None}, "method"), + ({"method": "rbf", "output_dim": 0}, "output_dim"), + ({"method": "rbf", "output_dim": True}, "output_dim"), + ({"method": "rbf", "target_aware": 1}, "target_aware"), + ({"method": "rbf", "placement_strategy": ""}, "placement_strategy"), + ({"method": "rbf", "adaptive": None}, "adaptive"), + ({"method": "rbf", "min_output_dim": -1}, "min_output_dim"), + ({"method": "rbf", "params": []}, "params"), + ({"method": "rbf", "params": {"method": "ple"}}, "params['method']"), + ({"method": "rbf", "params": {"gamma": [float("inf")]}}, "params['gamma'][0]"), + ({"method": "rbf", "gamma": 0.5, "params": {"gamma": 0.5}}, "gamma"), + ], +) +def test_path_errors_reuse_common_and_nested_value_checks(data, location): + path = "feature_preprocessing['a.b[0]']" + with pytest.raises(InvalidParamError) as failure: + _normalize_representation_config(data, is_numerical=True, path=path) + assert f"{path}.{location}" in str(failure.value) + + +@pytest.mark.parametrize("succeeds", [False, True]) +def test_path_errors_do_not_leak_into_standalone_value_validation(succeeds): + if succeeds: + _normalize_representation_config("rbf", is_numerical=True, path="feature_preprocessing['age']") + else: + with pytest.raises(InvalidParamError): + _normalize_representation_config({"method": "rbf", "output_dim": 0}, is_numerical=True, path="other") + with pytest.raises(InvalidParamError) as failure: + RepresentationConfig(method="") + assert str(failure.value).startswith("RepresentationConfig.method") + + +def test_path_errors_follow_the_live_registry_and_check_applicability(monkeypatch): + data = {"method": "rbf", "plugin_strength": 0.5} + with pytest.raises(InvalidParamError, match="plugin_strength"): + _normalize_representation_config(data, is_numerical=True) + spec = TRANSFORMER_REGISTRY["rbf"] + monkeypatch.setitem( + TRANSFORMER_REGISTRY, "rbf", replace(spec, allowed_args=(*spec.allowed_args, "plugin_strength")) + ) + assert _normalize_representation_config(data, is_numerical=True).params["plugin_strength"] == 0.5 + with pytest.raises(InvalidParamError, match="degree"): + _normalize_representation_config({"method": "ohe", "degree": 3}, is_numerical=False) + + +@pytest.mark.parametrize( + ("data", "is_numerical", "location"), + [ + ({"method": "ohe", "degree": 3}, False, "degree"), + ({"method": "rbf", "params": {"degree": 3}}, True, "params['degree']"), + ({"method": "polynomial", "gamma": 1.0}, True, "gamma"), + ({"method": "ohe", "output_dim": 3}, False, "output_dim"), + ({"method": "minmax", "adaptive": False}, True, "adaptive"), + ({"method": "custombin", "adaptive": True}, True, "adaptive"), + ({"method": "ohe", "min_output_dim": None}, False, "min_output_dim"), + ({"method": "ple", "target_aware": False}, True, "target_aware"), + ({"method": "pspline", "target_aware": True}, True, "target_aware"), + ({"method": "pspline", "placement_strategy": "quantile"}, True, "placement_strategy"), + ({"method": "ohe", "placement_strategy": "uniform"}, False, "placement_strategy"), + ({"method": "rbf", "placement_strategy": "even"}, True, "placement_strategy"), + ({"method": "rbf", "target_aware": False, "placement_strategy": "cart"}, True, "placement_strategy"), + ({"method": "rbf", "target_aware": True, "placement_strategy": "uniform"}, True, "placement_strategy"), + ({"method": "rbf", "adaptive": False, "max_output_dim": None}, True, "max_output_dim"), + ({"method": "rbf", "adaptive": True, "min_output_dim": 5, "max_output_dim": 3}, True, "max_output_dim"), + ], +) +def test_capability_errors_name_the_explicit_option_and_source(data, is_numerical, location): + path = "feature_preprocessing['age']" + with pytest.raises(InvalidParamError) as failure: + _normalize_representation_config(data, is_numerical=is_numerical, path=path) + assert f"{path}.{location}" in str(failure.value) + + +@pytest.mark.parametrize( + "data", + [ + {"method": "rbf", "output_dim": 3, "gamma": 0.5}, + {"method": "bspline", "output_dim": 3}, + {"method": "mspline", "output_dim": 5}, + {"method": "ispline", "output_dim": 5}, + {"method": "pspline", "output_dim": 5, "target_aware": False, "placement_strategy": "uniform"}, + {"method": "ple", "target_aware": True, "placement_strategy": "cart", "adaptive": True}, + {"method": "rbf", "placement_strategy": "quantile"}, + {"method": "rbf", "target_aware": False}, + {"method": "rbf", "adaptive": True, "min_output_dim": None, "max_output_dim": None}, + ], +) +def test_capability_validation_preserves_explicit_requests_without_filling_defaults(data): + normalized = _normalize_representation_config(data, is_numerical=True) + assert normalized == RepresentationConfig.from_dict(data) + + +@pytest.mark.parametrize( + ("field", "value"), + [ + ("feature_kind", frozenset({"categorical"})), + ("preprocessor_compatible", False), + ("supports_adaptive_resolution", False), + ], +) +def test_capability_validation_uses_live_metadata_even_when_derived_views_are_unchanged(monkeypatch, field, value): + spec = TRANSFORMER_REGISTRY["rbf"] + monkeypatch.setitem(TRANSFORMER_REGISTRY, "rbf", replace(spec, **{field: value})) + with pytest.raises(InvalidParamError): + _normalize_representation_config({"method": "rbf", "adaptive": True}, is_numerical=True) + + +@pytest.mark.parametrize("method", ["tensor", "thinplate", "rff", "nystroem"]) +def test_capability_validation_does_not_make_standalone_methods_selectable(method): + with pytest.raises(InvalidParamError, match="method"): + _normalize_representation_config(method, is_numerical=True) + + +@pytest.mark.parametrize("available", [False, True]) +@pytest.mark.parametrize(("method", "is_numerical"), [("pretrained", False), ("rbf", True)]) +def test_optional_dependency_metadata_is_checked_without_import_or_construction( + monkeypatch, method, is_numerical, available +): + discovered = [] + + def discover(module_name): + discovered.append(module_name) + return object() if available else None + + def unexpected(*args, **kwargs): + pytest.fail("normalization must not import optional packages or construct a transformer") + + spec = TRANSFORMER_REGISTRY[method] + monkeypatch.setitem( + TRANSFORMER_REGISTRY, method, replace(spec, optional_dependency="embeddings", transformer_cls=unexpected) + ) + monkeypatch.setattr("pretab.core.dependencies.importlib.util.find_spec", discover) + monkeypatch.setattr("pretab.core.dependencies.importlib.import_module", unexpected) + path = "feature_preprocessing['city']" + if available: + assert _normalize_representation_config(method, is_numerical=is_numerical, path=path).method == method + else: + with pytest.raises(OptionalDependencyError) as failure: + _normalize_representation_config(method, is_numerical=is_numerical, path=path) + assert f"{path}.method" in str(failure.value) + assert "pip install pretab[embeddings]" in str(failure.value) + assert discovered == ["sentence_transformers"] + + +@pytest.mark.parametrize("available", [False, True]) +def test_explicit_lightgbm_placement_uses_import_free_dependency_check(monkeypatch, available): + discovered = [] + + def discover(module_name): + discovered.append(module_name) + return object() if available else None + + monkeypatch.setattr("pretab.core.dependencies.importlib.util.find_spec", discover) + data = {"method": "rbf", "target_aware": True, "placement_strategy": "lightgbm"} + if available: + assert _normalize_representation_config(data, is_numerical=True).placement_strategy == "lightgbm" + else: + with pytest.raises(OptionalDependencyError, match=r"RepresentationConfig.placement_strategy.*lightgbm"): + _normalize_representation_config(data, is_numerical=True) + assert discovered == ["lightgbm"] + + +def test_capability_validation_does_not_check_unselected_optional_dependencies(monkeypatch): + def unexpected(*args, **kwargs): + pytest.fail("no optional dependency is selected") + + monkeypatch.setattr("pretab.core.dependencies.importlib.util.find_spec", unexpected) + assert _normalize_representation_config("rbf", is_numerical=True).target_aware is UNSET diff --git a/tests/compose/test_search.py b/tests/compose/test_search.py index 630666f..821e946 100644 --- a/tests/compose/test_search.py +++ b/tests/compose/test_search.py @@ -6,6 +6,9 @@ (``bspline``) must beat a linear ``standardization`` baseline. """ +import os +import warnings + import numpy as np import pandas as pd import pytest @@ -20,11 +23,12 @@ StratifiedKFold, check_cv, cross_val_score, + cross_validate, ) from sklearn.svm import SVC from pretab import RepresentationSearchCV -from pretab.exceptions import InvalidParamError +from pretab.exceptions import ConfigWarning, InvalidParamError # Unsupervised, deterministic placement so scores are reproducible fold to fold. _UNSUPERVISED = {"target_aware": False, "placement_strategy": "uniform", "output_dim": 10} @@ -129,11 +133,128 @@ def test_predict_before_fit_raises(nonlinear_data): def test_get_params_and_clone_preserve_config(): from sklearn.base import clone - search = RepresentationSearchCV(LinearRegression(), methods=["bspline", "standardization"], cv=3) + search = RepresentationSearchCV( + LinearRegression(), methods=["bspline", "standardization"], cv=3, task_validation="warn" + ) assert search.get_params()["methods"] == ["bspline", "standardization"] cloned = clone(search) assert isinstance(cloned, RepresentationSearchCV) assert cloned.get_params()["cv"] == 3 + assert cloned.get_params()["task_validation"] == "warn" + cloned.set_params(task_validation="raise") + assert cloned.get_params()["task_validation"] == "raise" + + +def test_invalid_search_task_validation_rejected(nonlinear_data): + X, y = nonlinear_data + search = RepresentationSearchCV(LinearRegression(), methods=["bspline"], task_validation="WARN") + assert search.get_params()["task_validation"] == "WARN" + with pytest.raises(InvalidParamError, match=r"RepresentationSearchCV\.task_validation"): + search.fit(X, y) + + +def test_search_preserves_inner_mode_validation(nonlinear_data): + X, y = nonlinear_data + search = RepresentationSearchCV( + LinearRegression(), methods=["minmax"], preprocessor_params={"task_validation": np.array(["off", "warn"])} + ) + + with pytest.raises(InvalidParamError, match=r"Preprocessor\.task_validation"): + search.fit(X, y) + + +@pytest.mark.parametrize( + ("mode", "exception", "owner"), + [("raise", InvalidParamError, r"Preprocessor\.task"), ("warn", ConfigWarning, "Preprocessor:")], +) +def test_search_checks_later_candidate_before_cloning(nonlinear_data, monkeypatch, mode, exception, owner): + X, y = nonlinear_data + search = RepresentationSearchCV( + LinearRegression(), + methods=["minmax", "rbf"], + preprocessor_params={"task": "classification", "task_validation": mode}, + ) + + def reject_clone(*args, **kwargs): + pytest.fail("cloned before checking the later candidate") + + monkeypatch.setattr("pretab.compose.search.clone", reject_clone) + with warnings.catch_warnings(): + warnings.simplefilter("error", ConfigWarning) + with pytest.raises(exception, match=rf"(?s){owner}.*target-aware placement.*continuous"): + search.fit(X, pd.Series(y)) + + +def test_search_checks_outer_classification_before_splitting(nonlinear_data): + X, y = nonlinear_data + search = RepresentationSearchCV(LogisticRegression(), methods=["minmax"], task_validation="raise") + + with pytest.raises(InvalidParamError, match=r"(?s)RepresentationSearchCV\.task.*representation search.*continuous"): + search.fit(X, y) + + +@pytest.mark.parametrize("inner_mode", ["warn", "raise"]) +def test_search_keeps_distinct_contracts_after_failed_fit(inner_mode): + values = np.linspace(-2, 2, 18) + X = pd.DataFrame({"value": values}) + target = pd.Series(values**2 + 0.123) + search = RepresentationSearchCV( + LogisticRegression(), + methods=["rbf"], + cv=2, + preprocessor_params={"task_validation": inner_mode, "output_dim": 3}, + task_validation="warn", + ) + exception = InvalidParamError if inner_mode == "raise" else ValueError + match = r"(?s)Preprocessor\.task.*target-aware placement.*continuous" if inner_mode == "raise" else "continuous" + + for _ in range(2): + with pytest.warns(ConfigWarning) as diagnostics, pytest.raises(exception, match=match): + search.fit(X, target) + messages = [str(item.message) for item in diagnostics] + expected_roles = ["target-aware placement"] + if inner_mode == "warn": + expected_roles.append("representation search") + assert len(messages) == len(expected_roles) + for message, role in zip(messages, expected_roles, strict=True): + assert message.startswith(f"RepresentationSearchCV: {role}") + + +class _DiagnosticRecordingSearch(RepresentationSearchCV): + def fit(self, X, y=None, *, groups=None, **fit_params): + self.fit_pid_ = os.getpid() + with warnings.catch_warnings(record=True) as recorded: + warnings.simplefilter("always", ConfigWarning) + super().fit(X, y, groups=groups, **fit_params) + self.task_diagnostics_ = [str(item.message) for item in recorded if item.category is ConfigWarning] + return self + + +@pytest.mark.parametrize("n_jobs", [1, 2], ids=["serial", "worker-process"]) +@pytest.mark.parametrize(("outer_mode", "owner"), [("off", "Preprocessor"), ("warn", "_DiagnosticRecordingSearch")]) +def test_search_owns_placement_diagnostic_once_per_cv_fit(n_jobs, outer_mode, owner): + values = np.linspace(-2, 2, 18) + X = pd.DataFrame({"value": values}) + target = pd.Series(values**2 + 0.123) + search = _DiagnosticRecordingSearch( + LinearRegression(), + methods=["rbf", "relu"], + cv=2, + preprocessor_params={"task": "classification", "task_validation": "warn", "output_dim": 3}, + task_validation=outer_mode, + ) + + result = cross_validate(search, X, target, cv=3, n_jobs=n_jobs, return_estimator=True) + + assert np.isfinite(result["test_score"]).all() + assert len(result["estimator"]) == 3 + for fitted in result["estimator"]: + assert (fitted.fit_pid_ == os.getpid()) == (n_jobs == 1) + assert set(fitted.cv_results_) == {"rbf", "relu"} + assert fitted.best_preprocessor_.task_validation == "warn" + assert len(fitted.task_diagnostics_) == 1 + assert fitted.task_diagnostics_[0].startswith(f"{owner}: target-aware placement") + assert "target type 'continuous'" in fitted.task_diagnostics_[0] class _RowRecorder(RegressorMixin, BaseEstimator): @@ -324,21 +445,78 @@ def test_search_records_the_input_features(nonlinear_data): assert not hasattr(search, "feature_names_in_") -def test_classifier_search_places_against_class_labels(class_data): +@pytest.mark.parametrize("frame_type", ["pandas", "polars"]) +@pytest.mark.parametrize("estimator_kind", ["regressor", "classifier"]) +@pytest.mark.parametrize("new_width", [1, 2]) +def test_refit_replaces_named_input_metadata(nonlinear_data, class_data, frame_type, estimator_kind, new_width): + frame, target = class_data if estimator_kind == "classifier" else nonlinear_data + estimator = LogisticRegression() if estimator_kind == "classifier" else LinearRegression() + renamed = frame.rename(columns={"x": "renamed"}) + if new_width == 2: + renamed = renamed.assign(squared=frame["x"].to_numpy() ** 2) + expected_columns = list(renamed.columns) + if frame_type == "polars": + polars = pytest.importorskip("polars") + frame = polars.DataFrame({column: frame[column].to_numpy() for column in frame.columns}) + renamed = polars.DataFrame({column: renamed[column].to_numpy() for column in renamed.columns}) + + methods = ["minmax", "standardization"] + search = _search(estimator, methods, cv=3).fit(frame, target) + previous_preprocessor = search.best_preprocessor_ + previous_estimator = search.best_estimator_ + np.testing.assert_array_equal(search.feature_names_in_, ["x"]) + + search.fit(renamed, target) + fresh = _search(estimator, methods, cv=3).fit(renamed, target) + + assert search.n_features_in_ == new_width + np.testing.assert_array_equal(search.feature_names_in_, expected_columns) + np.testing.assert_array_equal(search.best_preprocessor_.feature_names_in_, expected_columns) + assert search.best_preprocessor_ is not previous_preprocessor + assert search.best_estimator_ is not previous_estimator + assert search.best_method_ == fresh.best_method_ + assert search.cv_results_ == fresh.cv_results_ + np.testing.assert_array_equal( + search.best_preprocessor_.get_feature_names_out(), fresh.best_preprocessor_.get_feature_names_out() + ) + if estimator_kind == "classifier": + np.testing.assert_array_equal(search.classes_, fresh.classes_) + np.testing.assert_array_equal(search.predict(renamed), fresh.predict(renamed)) + np.testing.assert_allclose(search.predict_proba(renamed), fresh.predict_proba(renamed)) + else: + np.testing.assert_allclose(search.predict(renamed), fresh.predict(renamed)) + + +@pytest.mark.parametrize("mode", ["off", "warn", "raise"]) +def test_classifier_search_places_against_class_labels(class_data, mode): """A classifier made the search keep task="regression": string labels crashed the target-aware placement and integer labels were treated as a regression target.""" X, y = class_data - search = RepresentationSearchCV(LogisticRegression(), methods=["minmax", "ple"], cv=3, random_state=0).fit(X, y) + search = RepresentationSearchCV( + LogisticRegression(), + methods=["minmax", "ple"], + cv=3, + random_state=0, + preprocessor_params={"task_validation": mode}, + task_validation=mode, + ).fit(X, y) assert search.best_preprocessor_.task == "classification" assert set(search.predict(X)) <= {"pos", "neg"} -def test_classifier_search_keeps_an_explicit_task(class_data): +@pytest.mark.parametrize("use_string_labels", [False, True]) +def test_classifier_search_keeps_an_explicit_task(class_data, use_string_labels): X, y = class_data search = RepresentationSearchCV( - LogisticRegression(), methods=["minmax"], cv=3, preprocessor_params={"task": "regression"} - ).fit(X, (y == "pos").astype(int)) + LogisticRegression(), + methods=["minmax"], + cv=3, + preprocessor_params={"task": "regression", "task_validation": "warn"}, + task_validation="raise", + ).fit(X, y if use_string_labels else (y == "pos").astype(int)) assert search.best_preprocessor_.task == "regression" + assert search.best_preprocessor_.task_validation == "warn" + assert search.task_validation == "raise" def test_regressor_search_keeps_the_regression_task(nonlinear_data): diff --git a/tests/core/test_cross_fitted.py b/tests/core/test_cross_fitted.py index 2d750ab..e73741e 100644 --- a/tests/core/test_cross_fitted.py +++ b/tests/core/test_cross_fitted.py @@ -6,16 +6,20 @@ """ import warnings +from dataclasses import replace from typing import cast import numpy as np import pytest -from sklearn.base import BaseEstimator, TransformerMixin -from sklearn.model_selection import KFold +from sklearn.base import BaseEstimator, TransformerMixin, clone +from sklearn.compose import ColumnTransformer +from sklearn.model_selection import KFold, StratifiedKFold +from sklearn.pipeline import make_pipeline +from sklearn.preprocessing import StandardScaler -from pretab import CrossFittedTransformer, LeakageWarning +from pretab import CrossFittedTransformer, LeakageWarning, Preprocessor from pretab.core._typing import TransformerLike -from pretab.exceptions import IncompatibleParamsError, InvalidParamError +from pretab.exceptions import ConfigWarning, IncompatibleParamsError, InvalidParamError from pretab.transformers import PLETransformer @@ -109,6 +113,97 @@ def test_invalid_task_rejected(data): CrossFittedTransformer(PLETransformer(), task="classificaton").fit_transform(X, y) +@pytest.mark.parametrize("operation", ["fit", "fit_transform"]) +def test_invalid_task_validation_rejected(data, operation): + X, y = data + transformer = CrossFittedTransformer(PLETransformer(), task_validation="WARN") + assert transformer.get_params()["task_validation"] == "WARN" + with pytest.raises(InvalidParamError, match=r"CrossFittedTransformer\.task_validation"): + getattr(transformer, operation)(X, y) + + +def test_cross_fit_task_validation_survives_clone_and_fit(data): + X, y = data + transformer = CrossFittedTransformer(PLETransformer(), 3, "regression", False, 0) + assert transformer.get_params(deep=False)["task_validation"] == "off" + transformer.set_params(task_validation="raise") + copied = clone(transformer) + assert isinstance(copied, CrossFittedTransformer) + copied.fit(X, y) + assert copied.get_params(deep=False) == transformer.get_params(deep=False) | {"transformer": copied.transformer} + + +def test_nested_cross_fit_task_diagnostic_emits_once_per_operation(data): + X, _ = data + target = np.where(X[:, 0] < 0, "low", "high") + inner = CrossFittedTransformer(PLETransformer(task="classification"), n_folds=3, task_validation="warn") + outer = CrossFittedTransformer(inner, n_folds=3, task_validation="warn") + + for _ in range(2): + with warnings.catch_warnings(record=True) as recorded: + warnings.simplefilter("always", ConfigWarning) + outer.fit_transform(X, target) + diagnostics = [item for item in recorded if item.category is ConfigWarning] + assert len(diagnostics) == 1 + assert "cross-fitting uses task='regression'" in str(diagnostics[0].message) + + +def test_cross_fit_preflights_inner_policy_before_cloning(data, monkeypatch): + X, target = data + inner = Preprocessor(numerical_method="rbf", task="classification", task_validation="raise") + outer = CrossFittedTransformer(inner) + + def reject_clone(*args, **kwargs): + pytest.fail("cloned before checking the inner task policy") + + monkeypatch.setattr("pretab.core.supervised.clone", reject_clone) + with pytest.raises(InvalidParamError, match=r"(?s)Preprocessor\.task.*target-aware placement.*continuous"): + outer.fit(X, target) + + +def test_pipeline_placement_diagnostic_is_reused_by_cross_fit_folds(monkeypatch): + X = np.linspace(-2, 2, 12).reshape(-1, 1) + target = X[:, 0] ** 2 + 0.123 + pipeline = make_pipeline( + StandardScaler(), + Preprocessor(numerical_method="rbf", task="classification", task_validation="warn", output_dim=3), + ) + cross_fit = CrossFittedTransformer(pipeline, n_folds=3, shuffle=False) + make_splitter = cross_fit._make_splitter + + with warnings.catch_warnings(record=True) as recorded: + warnings.simplefilter("always", ConfigWarning) + + def check_before_split(): + diagnostics = [item for item in recorded if item.category is ConfigWarning] + assert len(diagnostics) == 1 + assert "target-aware placement uses task='classification'" in str(diagnostics[0].message) + return make_splitter() + + monkeypatch.setattr(cross_fit, "_make_splitter", check_before_split) + result = cross_fit.fit_transform(X, target) + + assert result.shape == (len(target), 3) + assert sum(item.category is ConfigWarning for item in recorded) == 1 + + +def test_pipeline_placement_strict_policy_rejects_before_representation_fit_or_folds(data, monkeypatch): + X, target = data + pipeline = make_pipeline( + StandardScaler(), + Preprocessor(numerical_method="rbf", task="classification", task_validation="raise"), + ) + cross_fit = CrossFittedTransformer(pipeline, n_folds=3) + + def reject_fit_or_split(*args, **kwargs): + pytest.fail("started representation fitting or fold splitting before validating the target") + + monkeypatch.setattr(ColumnTransformer, "fit_transform", reject_fit_or_split) + monkeypatch.setattr(cross_fit, "_make_splitter", reject_fit_or_split) + with pytest.raises(InvalidParamError, match=r"(?s)Preprocessor\.task.*target-aware placement.*continuous"): + cross_fit.fit_transform(X, target) + + # --- fit_transform returns the kind of output transform returns (issue #90) --------- @@ -554,14 +649,16 @@ def test_wrapped_preprocessor_out_of_fold_codes_match_transform(array_with_rare_ np.testing.assert_array_equal(np.unique(out[:, unsupervised[1]]), [1.0, 2.0, 3.0, 4.0]) -def _refit_representation_per_fold(pipeline, column, y): +def _refit_representation_per_fold(pipeline, column, y, splitter=None): """Expected out-of-fold rows of a fitted block pipeline whose last step is its target-aware representation: the helper steps before it keep their all-data fit.""" from sklearn.base import clone helpers, representation = pipeline[:-1], pipeline[-1] blocks = {} - for train_idx, test_idx in KFold(n_splits=5, shuffle=True, random_state=0).split(column): + if splitter is None: + splitter = KFold(n_splits=5, shuffle=True, random_state=0) + for train_idx, test_idx in splitter.split(column, y): fold = cast(TransformerLike, clone(representation)) fold.fit(helpers.transform(column.iloc[train_idx]), y[train_idx]) blocks[tuple(test_idx)] = fold.transform(helpers.transform(column.iloc[test_idx])) @@ -577,6 +674,353 @@ def _fitted_block(cross_fitted, name): return cast(Preprocessor, cross_fitted.estimator_).column_transformer_.named_transformers_[name] +class _JointTargetProjection(TransformerMixin, BaseEstimator): + def __init__(self, target_aware=True): + self.target_aware = target_aware + + def fit(self, X, y=None): + values = np.asarray(X, dtype=float) + target = np.asarray(y) + self.n_features_in_ = values.shape[1] + self.fit_values_ = values.copy() + self.fit_target_ = target.copy() + self.weights_ = values.T @ target / len(values) if self.target_aware else np.arange(1, values.shape[1] + 1) + self.target_mean_ = target.mean() if self.target_aware else 0.0 + return self + + def transform(self, X): + values = np.asarray(X, dtype=float) + return np.column_stack((values @ self.weights_, np.full(len(values), self.target_mean_))) + + def get_feature_names_out(self, input_features=None): + return np.array(["joint_projection", "target_mean"], dtype=object) + + +@pytest.fixture +def grouped_cross_fit_data(): + import pandas as pd + + rng = np.random.default_rng(42) + frame = pd.DataFrame( + { + "north": rng.normal(size=100), + "east": rng.normal(size=100), + "spare": rng.normal(size=100), + "city": ["rare", *(["usual"] * 99)], + } + ) + frame.loc[7, "north"] = np.nan + return frame, rng.normal(size=len(frame)) + + +@pytest.mark.parametrize( + ("target_usage", "target_aware"), [("optional", False), ("optional", True), ("required", True)] +) +@pytest.mark.parametrize("missing", ["none", "observed", "all"]) +@pytest.mark.parametrize("output_format", ["dense", "sparse"]) +@pytest.mark.parametrize("dtype", [np.float32, np.float64]) +@pytest.mark.parametrize("task", ["regression", "classification"]) +def test_grouped_target_aware_cross_fitting_preserves_frozen_prefix_and_missing_state( + grouped_cross_fit_data, monkeypatch, target_usage, target_aware, missing, output_format, dtype, task +): + import pandas as pd + from scipy import sparse as sp + + from pretab import Preprocessor + from pretab.compose.registry import TRANSFORMER_REGISTRY + + monkeypatch.setitem( + TRANSFORMER_REGISTRY, + "tprs", + replace( + TRANSFORMER_REGISTRY["tprs"], + transformer_cls=_JointTargetProjection, + target_usage=target_usage, + allowed_args=(), + placement_strategies=frozenset(), + ), + ) + fold_models = [] + original_fold = Preprocessor._cross_fit_fold + + def record_fold(self, X, y): + fold = original_fold(self, X, y) + fold_models.append(fold) + return fold + + monkeypatch.setattr(Preprocessor, "_cross_fit_fold", record_fold) + frame, target = grouped_cross_fit_data + original_frame = frame.copy(deep=True) + if task == "classification": + target = (target > 0).astype(int) + wrapped = CrossFittedTransformer( + Preprocessor( + numerical_method="minmax", + categorical_method="one-hot", + add_missing_indicator=missing == "observed", + missing_policy="separate_state" if missing == "all" else None, + output_format=output_format, + dtype=dtype, + task=task, + feature_groups={ + "location": { + "columns": ["east", "north"], + "representation": {"method": "tprs", "target_aware": target_aware}, + } + }, + ), + n_folds=5, + random_state=0, + task=task, + ) + out = wrapped.fit_transform(frame, target) + full = wrapped.transform(frame) + assert sp.issparse(out) is (output_format == "sparse") + assert out.dtype == full.dtype == dtype + if output_format == "sparse": + assert out.format == full.format == "csr" + out = out.toarray() if sp.issparse(out) else out + full = full.toarray() if sp.issparse(full) else full + fitted = cast(Preprocessor, wrapped.estimator_) + span = fitted.column_transformer_.output_indices_["group_location"] + block = _fitted_block(wrapped, "group_location") + representation = block if missing == "none" else dict(block.transformer_list)["representation"] + splitter_cls = StratifiedKFold if task == "classification" else KFold + splitter = splitter_cls(n_splits=5, shuffle=True, random_state=0) + expected = _refit_representation_per_fold(representation, frame[["east", "north"]], target, splitter).astype(dtype) + np.testing.assert_array_equal(out[:, span.start : span.start + 2], expected) + np.testing.assert_array_equal(out[:, : span.start], full[:, : span.start]) + np.testing.assert_array_equal(out[:, span.stop :], full[:, span.stop :]) + sources = {"none": [], "observed": ["north"], "all": ["east", "north"]}[missing] + assert span.stop - span.start == 2 + len(sources) + np.testing.assert_array_equal(out[:, span.start + 2 : span.stop], frame[sources].isna().astype(float)) + assert out.shape == full.shape == (len(frame), len(wrapped.get_feature_names_out())) + if target_aware: + assert not np.allclose(out[:, span.start : span.start + 2], full[:, span.start : span.start + 2]) + else: + np.testing.assert_array_equal(out, full) + assert len(fold_models) == 5 + for fold, (train_idx, _) in zip(fold_models, splitter.split(frame, target), strict=True): + fold_block = fold.column_transformer_.named_transformers_["group_location"] + fold_representation = fold_block if missing == "none" else dict(fold_block.transformer_list)["representation"] + assert (fold_block is block) is not target_aware + if target_aware: + assert fold_representation[-1] is not representation[-1] + for (_, helper), (_, fold_helper) in zip( + representation.steps[:-1], fold_representation.steps[:-1], strict=True + ): + assert fold_helper is helper + np.testing.assert_array_equal( + fold_representation[-1].fit_values_, + representation[:-1].transform(frame.iloc[train_idx][["east", "north"]]), + ) + np.testing.assert_array_equal(fold_representation[-1].fit_target_, target[train_idx]) + if missing != "none": + assert dict(fold_block.transformer_list)["missing"] is dict(block.transformer_list)["missing"] + for name in ("num_spare", "cat_city"): + assert ( + fold.column_transformer_.named_transformers_[name] + is fitted.column_transformer_.named_transformers_[name] + ) + assert fold.output_dims_ == fitted.output_dims_ + np.testing.assert_array_equal(fold.get_feature_names_out(), fitted.get_feature_names_out()) + records = fitted.get_feature_lineage()[span] + assert all(record.uses_target is target_aware for record in records[:2]) + assert all(not record.uses_target for record in records[2:]) + pd.testing.assert_frame_equal(frame, original_frame) + + +@pytest.mark.parametrize("method", ["tensorspline", "tprs"]) +@pytest.mark.parametrize("missing", ["none", "observed", "all"]) +def test_builtin_groups_keep_all_data_state_while_supervised_single_is_refit(grouped_cross_fit_data, method, missing): + from pretab import Preprocessor + + frame, target = grouped_cross_fit_data + representation = ( + {"method": method, "output_dim": 3, "degree": 2} + if method == "tensorspline" + else {"method": method, "n_components": 3, "landmark_strategy": "subsample", "random_state": 0} + ) + wrapped = CrossFittedTransformer( + Preprocessor( + numerical_method="ple", + output_dim=4, + categorical_method="one-hot", + add_missing_indicator=missing == "observed", + missing_policy="separate_state" if missing == "all" else None, + feature_groups={"location": {"columns": ["east", "north"], "representation": representation}}, + ), + n_folds=5, + random_state=0, + ) + out = wrapped.fit_transform(frame, target) + fitted = cast(Preprocessor, wrapped.estimator_) + full = wrapped.transform(frame) + span = fitted.column_transformer_.output_indices_["group_location"] + np.testing.assert_array_equal(out[:, span], full[:, span]) + assert not np.allclose(out[:, :4], full[:, :4]) + fingerprint = fitted.fingerprint_ + for train_idx, _ in KFold(n_splits=5, shuffle=True, random_state=0).split(frame): + fold = fitted._cross_fit_fold(frame.iloc[train_idx], target[train_idx]) + assert fold.column_transformer_.named_transformers_["group_location"] is _fitted_block( + wrapped, "group_location" + ) + assert fold.column_transformer_.named_transformers_["num_spare"] is not _fitted_block(wrapped, "num_spare") + assert fitted.fingerprint_ == fingerprint + + +def test_grouped_cross_fitting_retains_dictionary_error_and_matrix_remedy(grouped_cross_fit_data): + from pretab import Preprocessor + + frame, target = grouped_cross_fit_data + wrapped = CrossFittedTransformer( + Preprocessor( + numerical_method="minmax", + output_structure="blocks", + output_format="dense", + feature_groups={ + "location": { + "columns": ["east", "north"], + "representation": {"method": "tensorspline", "output_dim": 3, "degree": 2}, + } + }, + ), + n_folds=5, + random_state=0, + ) + with pytest.raises(IncompatibleParamsError, match=r"dict of blocks.*output_structure='matrix'"): + wrapped.fit_transform(frame, target) + assert isinstance(wrapped.transform(frame), dict) + + +@pytest.mark.parametrize("missing", ["none", "observed", "all"]) +def test_grouped_refit_preserves_prefix_and_refits_representation_suffix(grouped_cross_fit_data, monkeypatch, missing): + from copy import copy + + from sklearn.base import clone + from sklearn.pipeline import Pipeline + from sklearn.preprocessing import StandardScaler + + from pretab import Preprocessor + from pretab.compose.inspection import _separate_state_branches, refit_block_representation + from pretab.compose.registry import TRANSFORMER_REGISTRY + + monkeypatch.setitem( + TRANSFORMER_REGISTRY, + "tprs", + replace( + TRANSFORMER_REGISTRY["tprs"], + transformer_cls=_JointTargetProjection, + target_usage="optional", + allowed_args=(), + placement_strategies=frozenset(), + ), + ) + frame, target = grouped_cross_fit_data + sources = ["east", "north"] + fitted = Preprocessor( + numerical_method="minmax", + add_missing_indicator=missing == "observed", + missing_policy="separate_state" if missing == "all" else None, + feature_groups={"location": {"columns": sources, "representation": "tprs"}}, + ).fit(frame, target) + original_block = fitted.column_transformer_.named_transformers_["group_location"] + representation = original_block if missing == "none" else dict(original_block.transformer_list)["representation"] + pipeline = copy(representation) + pipeline.steps = [ + *representation.steps, + ("suffix", StandardScaler().fit(representation.transform(frame[sources]))), + ] + block = pipeline + if missing != "none": + block = copy(original_block) + block.transformer_list = [ + (name, pipeline if name == "representation" else branch) for name, branch in original_block.transformer_list + ] + original_values = block.transform(frame[sources]).copy() + train, held_out = frame.iloc[20:][sources], frame.iloc[:20][sources] + refitted = refit_block_representation(block, train, target[20:]) + branches = _separate_state_branches(refitted) + if missing == "none": + assert branches is None + refitted_pipeline = refitted + else: + assert branches is not None + refitted_pipeline, indicator = branches + assert indicator is dict(block.transformer_list)["missing"] + assert isinstance(refitted_pipeline, Pipeline) + expected = clone(pipeline[-2:]) + assert isinstance(expected, Pipeline) + expected.fit(pipeline[:-2].transform(train), target[20:]) + np.testing.assert_allclose( + refitted_pipeline.transform(held_out), expected.transform(pipeline[:-2].transform(held_out)) + ) + for (_, helper), (_, fold_helper) in zip(pipeline.steps[:-2], refitted_pipeline.steps[:-2], strict=True): + assert fold_helper is helper + assert refitted_pipeline[-2] is not pipeline[-2] + assert refitted_pipeline[-1] is not pipeline[-1] + np.testing.assert_array_equal(block.transform(frame[sources]), original_values) + np.testing.assert_array_equal(representation[-1].fit_target_, target) + + +class _ChangingJointWidth(_JointTargetProjection): + def fit(self, X, y=None): + super().fit(X, y) + self.width_ = 2 if len(X) == 100 else (3 if np.asarray(X).mean() > 0 else 1) + return self + + def transform(self, X): + values = np.asarray(X, dtype=float) + return np.repeat((values @ self.weights_ + self.target_mean_)[:, None], self.width_, axis=1) + + def get_feature_names_out(self, input_features=None): + return np.array([f"joint_{index}" for index in range(self.width_)], dtype=object) + + +@pytest.mark.parametrize("first_group", ["positive", "negative"]) +def test_grouped_cross_fitting_rejects_opposite_width_changes_with_constant_total(monkeypatch, first_group): + import pandas as pd + + from pretab import Preprocessor + from pretab.compose.inspection import refit_block_representation + from pretab.compose.registry import TRANSFORMER_REGISTRY + + monkeypatch.setitem( + TRANSFORMER_REGISTRY, + "tprs", + replace( + TRANSFORMER_REGISTRY["tprs"], + transformer_cls=_ChangingJointWidth, + target_usage="required", + allowed_args=(), + placement_strategies=frozenset(), + ), + ) + values = np.linspace(1.0, 10.0, 100) + frame = pd.DataFrame( + {"positive": values, "positive_other": values + 1, "negative": -values, "negative_other": -values - 1} + ) + target = np.random.default_rng(42).normal(size=len(frame)) + other_group = "negative" if first_group == "positive" else "positive" + groups = { + name: {"columns": [name, f"{name}_other"], "representation": "tprs"} for name in (first_group, other_group) + } + preprocessor = Preprocessor(scaling="none", feature_groups=groups).fit(frame, target) + assert preprocessor.output_dims_ == {f"group_{first_group}": 2, f"group_{other_group}": 2} + fold_widths = [] + for name in groups: + columns = [name, f"{name}_other"] + block = preprocessor.column_transformer_.named_transformers_[f"group_{name}"] + refitted = refit_block_representation(block, frame.iloc[20:][columns], target[20:]) + fold_widths.append(len(refitted.get_feature_names_out(columns))) + assert sorted(fold_widths) == [1, 3] + assert sum(fold_widths) == preprocessor.total_output_dim_ == 4 + with pytest.raises(IncompatibleParamsError, match="fixed output width") as failure: + CrossFittedTransformer(preprocessor, n_folds=5, shuffle=False).fit_transform(frame, target) + assert f"block 'group_{first_group}'" in str(failure.value) + assert f"expected 2, got {fold_widths[0]}" in str(failure.value) + + def test_wrapped_preprocessor_target_aware_blocks_stay_out_of_fold(array_with_rare_category): """Only the target-aware representation is refit, on each fold's training rows; the helper steps before it (imputer, scaler) keep their all-data fit.""" @@ -807,6 +1251,223 @@ def test_wrapped_preprocessor_keeps_the_separate_state_missing_branch(array_with np.testing.assert_array_equal(out[:, columns], np.column_stack((expected, np.isnan(X[:, 0]).astype(float)))) +@pytest.mark.parametrize("typed", [False, True], ids=["mapping", "value"]) +@pytest.mark.parametrize("missing_policy", [None, "impute_with_indicator", "separate_state"]) +def test_structured_cross_fitting_refits_only_target_representation( + array_with_one_missing_value, monkeypatch, typed, missing_policy +): + import pandas as pd + from sklearn.base import clone + from sklearn.pipeline import FeatureUnion, Pipeline + + from pretab import Preprocessor, RepresentationConfig + + values, target = array_with_one_missing_value + frame = pd.DataFrame(values, columns=pd.Index(["supervised", "fixed"]), index=np.arange(len(values)) * 3 + 5) + frame["city"] = np.resize(["a", "b", "c"], len(frame)) + frame.loc[frame.index[7], "city"] = "rare" + requests = { + "supervised": { + "method": "rbf", + "output_dim": 3, + "target_aware": True, + "placement_strategy": "cart", + "params": {"gamma": 0.25}, + }, + "fixed": { + "method": "rbf", + "output_dim": 5, + "target_aware": False, + "placement_strategy": "uniform", + "params": {"gamma": 0.75}, + }, + "city": {"method": "one-hot", "params": {"drop": "first", "sparse_output": False}}, + } + wrapped = Preprocessor( + feature_preprocessing={ + feature: RepresentationConfig.from_dict(settings) if typed else settings + for feature, settings in requests.items() + }, + missing_policy=missing_policy, + random_state=0, + ) + reference = clone(wrapped) + assert isinstance(reference, Preprocessor) + reference.fit(frame, target) + folds = [] + original = Preprocessor._cross_fit_fold + + def record_fold(fitted, train_frame, train_target): + fold = original(fitted, train_frame, train_target) + folds.append(fold) + return fold + + monkeypatch.setattr(Preprocessor, "_cross_fit_fold", record_fold) + cross_fitted = CrossFittedTransformer(wrapped, n_folds=5, random_state=0) + out = cross_fitted.fit_transform(frame, target) + fitted = cross_fitted.estimator_ + assert isinstance(fitted, Preprocessor) + full = np.asarray(cross_fitted.transform(frame)) + np.testing.assert_array_equal(full, reference.transform(frame)) + assert len(folds) == 5 + indicator = int(missing_policy is not None) + separate = int(missing_policy == "separate_state") + assert fitted.output_dims_ == {"supervised": 3 + indicator, "fixed": 5 + separate, "city": 3 + separate} + assert out.shape == full.shape == (len(frame), 11 + indicator + 2 * separate) + all_blocks = fitted.column_transformer_.named_transformers_ + full_block = all_blocks["num_supervised"] + if indicator: + assert isinstance(full_block, FeatureUnion) + representation = dict(full_block.transformer_list)["representation"] + else: + representation = full_block + assert isinstance(representation, Pipeline) + for fold in folds: + fold_blocks = fold.column_transformer_.named_transformers_ + fold_block = fold_blocks["num_supervised"] + if indicator: + assert isinstance(fold_block, FeatureUnion) + assert dict(fold_block.transformer_list)["missing"] is dict(full_block.transformer_list)["missing"] + fold_representation = dict(fold_block.transformer_list)["representation"] + else: + fold_representation = fold_block + assert isinstance(fold_representation, Pipeline) + assert fold_representation.named_steps["imputer"] is representation.named_steps["imputer"] + assert fold_representation.named_steps["minmax"] is representation.named_steps["minmax"] + assert fold_representation.named_steps["rbf"] is not representation.named_steps["rbf"] + assert fold_representation.named_steps["rbf"].output_dim == 3 + assert fold_representation.named_steps["rbf"].gamma == 0.25 + assert fold_blocks["num_fixed"] is all_blocks["num_fixed"] + assert fold_blocks["cat_city"] is all_blocks["cat_city"] + assert fold.output_dims_ == fitted.output_dims_ + np.testing.assert_array_equal(fold.get_feature_names_out(), fitted.get_feature_names_out()) + supervised = [ + record.output_index + for record in fitted.get_feature_lineage() + if record.source_features == ("supervised",) and record.uses_target + ] + assert len(supervised) == 3 + expected = _refit_representation_per_fold(representation, frame[["supervised"]], target) + np.testing.assert_array_equal(out[:, supervised], expected) + assert not np.allclose(out[:, supervised], full[:, supervised]) + unchanged = [index for index in range(out.shape[1]) if index not in supervised] + np.testing.assert_array_equal(out[:, unchanged], full[:, unchanged]) + + +@pytest.mark.parametrize("typed", [False, True], ids=["mapping", "value"]) +@pytest.mark.parametrize("container", ["dense", "sparse", "auto", "pandas", "polars"]) +def test_structured_cross_fitting_preserves_output_container(array_with_rare_category, typed, container): + import pandas as pd + from scipy import sparse + + from pretab import Preprocessor, RepresentationConfig + + polars = pytest.importorskip("polars") if container == "polars" else None + values, target = array_with_rare_category + frame = pd.DataFrame( + values, + columns=pd.Index(["signal", "count", "city"]), + index=pd.Index(np.arange(len(values))[::-1] * 3, name="row"), + ) + requests = { + "signal": {"method": "rbf", "output_dim": 3, "params": {"gamma": 0.25}}, + "city": {"method": "one-hot", "params": {"drop": "first"}}, + } + parameters = { + "feature_preprocessing": { + feature: RepresentationConfig.from_dict(settings) if typed else settings + for feature, settings in requests.items() + }, + "random_state": 0, + "dtype": np.float32, + } + wrapped = Preprocessor(output_format=container if container in {"sparse", "auto"} else "dense", **parameters) + if container in {"pandas", "polars"}: + wrapped.set_output(transform=container) + cross_fitted, out = _cross_fit(wrapped, frame, target) + full = cross_fitted.transform(frame) + assert type(out) is type(full) + if container == "sparse": + assert sparse.isspmatrix_csr(out) + if sparse.issparse(out): + assert sparse.issparse(full) + assert out.format == full.format == "csr" + out_values = out.toarray() + elif isinstance(out, pd.DataFrame): + assert isinstance(full, pd.DataFrame) + pd.testing.assert_index_equal(out.index, frame.index) + pd.testing.assert_index_equal(out.columns, full.columns) + assert out.columns.tolist() == cross_fitted.get_feature_names_out().tolist() + assert out.dtypes.equals(full.dtypes) + out_values = out.to_numpy() + elif container == "polars": + assert polars is not None + assert isinstance(out, polars.DataFrame) + assert out.columns == full.columns == cross_fitted.get_feature_names_out().tolist() + assert out.schema == full.schema + out_values = out.to_numpy() + else: + assert isinstance(out, np.ndarray) + out_values = out + _, dense = _cross_fit(Preprocessor(**parameters), frame, target) + assert out_values.shape == (len(frame), 7) + assert out_values.dtype == np.float32 + np.testing.assert_array_equal(out_values, dense) + + +@pytest.mark.parametrize("typed", [False, True], ids=["mapping", "value"]) +def test_structured_cross_fitting_checks_each_block_width(array_with_one_missing_value, monkeypatch, typed): + from pretab import Preprocessor, RepresentationConfig + from pretab.expansion.functional.rbf import RBFExpansionTransformer + + values, target = array_with_one_missing_value + requests = { + "feature_0": {"method": "rbf", "output_dim": 3, "params": {"gamma": 0.25}}, + "feature_1": { + "method": "rbf", + "output_dim": 5, + "target_aware": False, + "placement_strategy": "uniform", + }, + } + original = RBFExpansionTransformer.fit + + def change_fold_width(estimator, fold_values, fold_target=None): + if len(fold_values) < len(values) and estimator.gamma == 0.25: + estimator.set_params(output_dim=2) + return original(estimator, fold_values, fold_target) + + monkeypatch.setattr(RBFExpansionTransformer, "fit", change_fold_width) + wrapped = Preprocessor( + feature_preprocessing={ + feature: RepresentationConfig.from_dict(settings) if typed else settings + for feature, settings in requests.items() + }, + random_state=0, + ) + with pytest.raises( + IncompatibleParamsError, + match="fixed output width for block 'num_feature_0'; expected 3, got 2", + ) as error: + _cross_fit(wrapped, values, target) + assert "same columns on every fold" in str(error.value) + + +@pytest.mark.parametrize("typed", [False, True], ids=["mapping", "value"]) +def test_structured_cross_fitting_still_rejects_dictionary_output(integer_array, typed): + from pretab import Preprocessor, RepresentationConfig + + values, target = integer_array + settings = {"method": "rbf", "output_dim": 3} + wrapped = Preprocessor( + feature_preprocessing={"feature_0": RepresentationConfig.from_dict(settings) if typed else settings}, + output_structure="blocks", + random_state=0, + ) + with pytest.raises(IncompatibleParamsError, match="dict of blocks"): + _cross_fit(wrapped, values, target) + + # --- DataFrame input is passed through (issue #58) -------------------------------- diff --git a/tests/core/test_validation.py b/tests/core/test_validation.py new file mode 100644 index 0000000..bed4650 --- /dev/null +++ b/tests/core/test_validation.py @@ -0,0 +1,99 @@ +"""Contracts for shared target inspection, independent of estimator wiring.""" + +import warnings + +import numpy as np +import pandas as pd +import pytest + +from pretab.core import validation +from pretab.exceptions import ConfigWarning, InvalidParamError + + +@pytest.mark.parametrize("mode", ["off", "warn", "raise"]) +def test_task_validation_accepts_exact_modes(mode): + validation._validate_task_validation(mode, "Example") + + +@pytest.mark.parametrize("mode", ["WARN", " off", "", None, True, False, 1, ["warn"], np.array(["warn"])]) +def test_task_validation_rejects_invalid_modes(mode): + with pytest.raises(InvalidParamError, match=r"(?s)Example\.task_validation.*'off', 'warn', or 'raise'"): + validation._validate_task_validation(mode, "Example") + + +@pytest.mark.parametrize( + ("values", "inconsistent_task", "observed"), + [ + pytest.param([0.1, 1.25, 3.5], "classification", "continuous", id="continuous"), + pytest.param([[0.1], [1.25], [3.5]], "classification", "continuous", id="column-vector"), + pytest.param(["private-a", "private-b", "private-a"], "regression", "binary", id="binary-text"), + pytest.param(["private-a", "private-b", "private-c"], "regression", "multiclass", id="multiclass-text"), + pytest.param([0, 1, 0], None, None, id="binary-integer"), + pytest.param([0, 1, 2], None, None, id="multiclass-integer"), + pytest.param([True, False, True], None, None, id="boolean"), + pytest.param([0.0, 1.0, 0.0], None, None, id="binary-integral-float"), + pytest.param([0.0, 1.0, 2.0], None, None, id="multiclass-integral-float"), + pytest.param(["0.5", "1e3", "-2"], None, None, id="numeric-text"), + pytest.param([[0, 1], [1, 0], [1, 1]], None, None, id="multilabel"), + pytest.param([[0.1, 1.1], [1.2, 2.3], [4.5, 0.3]], None, None, id="continuous-multioutput"), + pytest.param([0.1, np.nan, 3.5], None, None, id="missing"), + pytest.param(np.array([0, "private-a", 2], dtype=object), None, None, id="mixed-object"), + ], +) +@pytest.mark.parametrize("container", ["numpy", "pandas"]) +@pytest.mark.parametrize("task", ["classification", "regression"]) +@pytest.mark.parametrize("mode", ["off", "warn", "raise"]) +def test_task_target_policy_matrix(values, inconsistent_task, observed, container, task, mode): + array = np.asarray(values) + target = (pd.Series(array) if array.ndim == 1 else pd.DataFrame(array)) if container == "pandas" else array + original = np.asarray(target).copy() + + def inspect_target(): + validation._validate_task_target(target, task=task, mode=mode, estimator="Example", role="placement") + + if mode == "off" or task != inconsistent_task: + with warnings.catch_warnings(): + warnings.simplefilter("error") + inspect_target() + else: + suggested = "regression" if task == "classification" else "classification" + match = rf"(?s)Example.*placement.*task='{task}'.*'{observed}'.*task='{suggested}'" + if mode == "warn": + with pytest.warns(ConfigWarning, match=match) as recorded: + inspect_target() + assert len(recorded) == 1 + message = str(recorded[0].message) + else: + with pytest.raises(InvalidParamError, match=match) as caught: + inspect_target() + message = str(caught.value) + assert "task_validation='off'" in message + assert "private-" not in message + + np.testing.assert_array_equal(np.asarray(target), original) + + +@pytest.mark.parametrize("target", [[0, 1, 2], [True, False], [0.0, 1.0, 2.0], ["0.5", "1e3", "-2"]]) +def test_task_target_leaves_ambiguous_regression_quiet(target): + validation._validate_task_target(target, task="regression", mode="raise", estimator="Example", role="placement") + + +@pytest.mark.parametrize( + ("target", "mode"), + [ + (np.array([0.1, 1.25, 3.5]), "off"), + (None, "raise"), + (np.array([0.5, np.nan]), "raise"), + (np.array([0.5, np.inf]), "raise"), + (np.array([0.5, 1e30]), "raise"), + ([int(np.iinfo(np.int64).max), 0.5], "raise"), + (pd.Series([0.5, pd.NA], dtype="Float64"), "raise"), + (pd.DataFrame({"a": [1, 0], "b": [0, 1]}), "raise"), + ], +) +def test_task_target_skips_indeterminate_inputs_before_sklearn(target, mode, monkeypatch): + def unexpected_inspection(target): + pytest.fail("target should not be sent to sklearn") + + monkeypatch.setattr(validation, "type_of_target", unexpected_inspection) + validation._validate_task_target(target, task="classification", mode=mode, estimator="Example", role="placement") diff --git a/tests/doc_snippets/test_tutorial_snippets.py b/tests/doc_snippets/test_tutorial_snippets.py index b847722..2a13280 100644 --- a/tests/doc_snippets/test_tutorial_snippets.py +++ b/tests/doc_snippets/test_tutorial_snippets.py @@ -1,13 +1,14 @@ -"""Executes the python code fences in the tutorial pages so API drift breaks CI -instead of the docs quietly going stale. +"""Executes the Python code fences in tutorials and selected documentation pages. -Notebook execution (``myst-nb`` / ``nbmake``) is intentionally out of scope for -1.0; this is the lighter-weight alternative: each tutorial's ```python blocks run -in one shared namespace, in source order, exactly as written on the page. Blocks -that only show expected console output (```text fences) are not touched. +Each page's ```python blocks run in one shared namespace, in source order, +exactly as written on the page. Blocks that only show expected console output +(```text fences) are not touched. The companion notebook is kept in sync with its +executed tutorial section without notebook-rendering dependencies in CI. """ +import json import re +from importlib.util import find_spec from pathlib import Path import pytest @@ -16,30 +17,44 @@ ROOT = Path(__file__).parents[2] TUTORIALS_DIR = ROOT / "docs" / "tutorials" +CORE_CONCEPTS_DIR = ROOT / "docs" / "core_concepts" +REPRESENTATIONS_DIR = ROOT / "docs" / "representations" _FENCE = re.compile(r"^```python\n(.*?)^```\s*$", re.DOTALL | re.MULTILINE) -def _code_blocks(path: Path) -> list[tuple[int, str]]: +def _code_blocks(path: Path, section: str | None = None) -> list[tuple[int, str]]: """Return (1-based start line, source) for every python fence in ``path``. - The source is padded with leading blank lines so a traceback raised while - executing it reports the real line number in the markdown file. + Optionally select one second-level section. The source is padded with leading + blank lines so a traceback reports the real line number in the markdown file. """ text = path.read_text(encoding="utf-8") + start = text.index(f"## {section}\n") if section is not None else 0 + stop = text.find("\n## ", start + 1) if section is not None else -1 + stop = len(text) if stop == -1 else stop blocks = [] for match in _FENCE.finditer(text): + if not start <= match.start() < stop: + continue start_line = text.count("\n", 0, match.start()) + 2 padded = "\n" * (start_line - 1) + match.group(1) blocks.append((start_line, padded)) return blocks -_TUTORIALS = [ +_PAGES = [ *sorted(TUTORIALS_DIR.glob("*.md")), + *sorted(CORE_CONCEPTS_DIR.glob("*.md")), + REPRESENTATIONS_DIR / "functional_expansions.md", + REPRESENTATIONS_DIR / "kernel_approximation.md", + REPRESENTATIONS_DIR / "numerical_encoding.md", + REPRESENTATIONS_DIR / "spline_expansions.md", ROOT / "README.md", ROOT / "docs" / "homepage.md", + ROOT / "docs" / "getting_started" / "overview.md", ROOT / "docs" / "getting_started" / "quickstart.md", + ROOT / "docs" / "developer_guide" / "architecture.md", ] @@ -59,12 +74,42 @@ def isolate_document_state(tmp_path, monkeypatch): registry.CATEGORICAL_METHODS.update(categorical) -@pytest.mark.parametrize("tutorial", _TUTORIALS, ids=[p.stem for p in _TUTORIALS]) +@pytest.mark.parametrize( + ("tutorial", "section"), + [pytest.param(page, None, id=page.stem) for page in _PAGES] + + [ + pytest.param( + TUTORIALS_DIR / "multivariate_features.md", + "Grouped preprocessing with Preprocessor", + id="feature-groups", + ), + ], +) @pytest.mark.filterwarnings("ignore::pretab.exceptions.LeakageWarning") -def test_tutorial_code_runs(tutorial): +def test_tutorial_code_runs(tutorial, section): namespace: dict = {"__name__": "__main__"} - for start_line, source in _code_blocks(tutorial): + blocks = _code_blocks(tutorial, section) + if tutorial == CORE_CONCEPTS_DIR / "configuration.md" and find_spec("polars") is None: + polars_lines = {line for line, _ in _code_blocks(tutorial, "Polars DataFrame input")} + blocks = [(line, source) for line, source in blocks if line not in polars_lines] + assert blocks, f"No Python examples found in {tutorial.name}: {section}" + for start_line, source in blocks: try: exec(compile(source, str(tutorial), "exec"), namespace) # noqa: S102 except Exception as exc: raise AssertionError(f"{tutorial.name}:{start_line} raised {exc!r}") from exc + + +def test_per_feature_notebook_matches_tutorial(): + notebook_path = ROOT / "examples" / "per-feature-configuration.ipynb" + notebook = json.loads(notebook_path.read_text(encoding="utf-8")) + notebook_sources = ["".join(cell["source"]).strip() for cell in notebook["cells"] if cell["cell_type"] == "code"] + tutorial_sources = [ + source.strip() + for _, source in _code_blocks( + TUTORIALS_DIR / "sklearn_pipeline.md", "Configure mixed columns with Preprocessor" + ) + ] + assert notebook["nbformat"] == 4 + assert len(notebook_sources) == 5 + assert notebook_sources == tutorial_sources diff --git a/tests/encoding/numerical/test_periodic.py b/tests/encoding/numerical/test_periodic.py index e0a7270..c626e70 100644 --- a/tests/encoding/numerical/test_periodic.py +++ b/tests/encoding/numerical/test_periodic.py @@ -33,6 +33,34 @@ def test_cyclic_rejects_out_of_range_input(): transformer.fit(np.array([[-1]])) +@pytest.mark.parametrize( + "period", + [0, -1, "24", None, np.nan, np.inf, -np.inf, True, False, np.bool_(True), 24 + 0j, [24], np.array([24])], +) +def test_cyclic_rejects_invalid_period_before_fitting(period): + transformer = PeriodicEncodingTransformer(period=period) + with pytest.raises(InvalidParamError, match=r"period.*finite.*positive") as error: + transformer.fit(np.array([[0.0]])) + + assert repr(period) in str(error.value) + assert not hasattr(transformer, "n_features_in_") + + +@pytest.mark.parametrize("period", [24, 24.0, 7.5, np.int64(7), np.float32(7.5), np.float64(24)]) +def test_cyclic_accepts_positive_finite_period(period): + values = np.array([[0.0], [period / 4], [period / 2], [period]]) + transformer = PeriodicEncodingTransformer(period=period) + transformed = transformer.fit_transform(values) + angles = 2 * np.pi * values[:, 0] / period + + assert transformer.period is period + assert transformed.shape == (4, 2) + assert np.isfinite(transformed).all() + np.testing.assert_allclose(transformed[:, 0], np.sin(angles), atol=1e-12) + np.testing.assert_allclose(transformed[:, 1], np.cos(angles), atol=1e-12) + assert transformer.get_representation_spec().period == float(period) + + def test_cyclic_requires_period(): with pytest.raises(TypeError): PeriodicEncodingTransformer() # type: ignore[call-arg] diff --git a/tests/expansion/spline/test_penalty_matrix_invariants.py b/tests/expansion/spline/test_penalty_matrix_invariants.py index 38c9236..84890f7 100644 --- a/tests/expansion/spline/test_penalty_matrix_invariants.py +++ b/tests/expansion/spline/test_penalty_matrix_invariants.py @@ -79,9 +79,35 @@ def test_tensor_product_penalty_is_symmetric_psd(X_multi): assert_valid_penalty(P) +@pytest.mark.parametrize("include_bias", [False, True]) +@pytest.mark.parametrize("first_weight", [0.0, 3.0]) +def test_weighted_typed_tensor_penalties_match_small_joint_reference(X_multi, include_bias, first_weight): + transformer = TensorProductSplineTransformer(output_dim=3, degree=2, diff_order=2, include_bias=include_bias).fit( + X_multi + ) + first, second = transformer.get_penalty_specs() + combined = first_weight * first.matrix + 2.0 * second.matrix + + difference = np.array([1.0, -2.0, 1.0]) + if include_bias: + difference = np.pad(difference, (1, 0)) + marginal = np.outer(difference, difference) + width = difference.size + identity = np.eye(width) + expected = first_weight * np.kron(marginal, identity) + 2.0 * np.kron(identity, marginal) + np.testing.assert_array_equal(combined, expected) + assert_valid_penalty(combined) + + marginal_nullity = width - 1 + first_nullity = marginal_nullity if first_weight > 0 else width + assert np.linalg.matrix_rank(combined) == width**2 - first_nullity * marginal_nullity + + def test_thinplate_penalty_is_symmetric_but_not_guaranteed_psd(): X = np.linspace(0, 1, 40).reshape(-1, 1) transformer = ThinPlateSplineTransformer(n_components=6, random_state=0).fit(X) + assert not hasattr(transformer, "get_penalty_spec") + assert not hasattr(transformer, "get_penalty_specs") with pytest.warns(ConfigWarning, match="experimental"): P = transformer.get_penalty_matrix() # PSD is explicitly not guaranteed here (see the class docstring); only symmetry is. diff --git a/tests/expansion/spline/test_penalty_spec.py b/tests/expansion/spline/test_penalty_spec.py new file mode 100644 index 0000000..ae34d10 --- /dev/null +++ b/tests/expansion/spline/test_penalty_spec.py @@ -0,0 +1,578 @@ +"""Value and validation contracts for coefficient-coordinate penalties.""" + +import json +import pickle +from copy import copy, deepcopy +from dataclasses import FrozenInstanceError +from hashlib import sha256 +from struct import pack + +import numpy as np +import pandas as pd +import pytest + +from pretab import PenaltySpec +from pretab.exceptions import InvalidParamError, PretabNotFittedError +from pretab.expansion.spline import PenaltySpec as SplinePenaltySpec +from pretab.transformers import ( + BSplineTransformer, + CubicRegressionSplineTransformer, + ISplineTransformer, + MSplineTransformer, + NaturalCubicSplineTransformer, + PSplineTransformer, + TensorProductSplineTransformer, +) + + +def _spec(matrix, **overrides): + settings = { + "kind": "coefficient_difference", + "order": 1, + "axis": ["age"], + "coordinate_system": "output_coefficients", + "coefficient_names": ["age_0", "age_1"], + "coefficient_indices": [2, 3], + } + return PenaltySpec(matrix, **(settings | overrides)) + + +def test_penalty_summary_has_complete_strict_json_metadata_and_canonical_digest(): + spec = _spec([[2.0, 0.0], [0.0, 0.0]], provenance={"options": [{"bias": False}], "note": None}) + canonical = bytes.fromhex( + "0200000000000000 0200000000000000 0000000000000040 0000000000000000 0000000000000000 0000000000000000" + ) + summary = spec.to_summary() + assert ( + summary + == json.loads(json.dumps(summary, allow_nan=False)) + == { + "shape": [2, 2], + "dtype": "float64", + "kind": "coefficient_difference", + "order": 1, + "axis": ["age"], + "coordinate_system": "output_coefficients", + "coefficient_names": ["age_0", "age_1"], + "coefficient_indices": [2, 3], + "rank": 1, + "nullity": 1, + "atol": 1e-10, + "rtol": 1e-10, + "provenance": {"options": [{"bias": False}], "note": None}, + "matrix_sha256": sha256(canonical).hexdigest(), + } + ) + + +@pytest.mark.parametrize("dtype", ["f8"]) +@pytest.mark.parametrize("layout", ["C", "F", "strided"]) +def test_penalty_summary_checksum_is_independent_of_input_byte_order_and_layout(dtype, layout): + values = [[2.0, -0.5], [np.nextafter(-0.5, 0), 1.0]] + if layout == "strided": + matrix = np.zeros((4, 4), dtype=dtype)[::2, ::2] + matrix[:] = values + else: + matrix = np.array(values, dtype=dtype, order=layout) + canonical = pack(" 0, frame["b"] > 0]) + else: + targets = np.column_stack([np.sin(frame["a"]), np.cos(frame["b"])]) + options = { + "numerical_method": method, + "target_aware": False, + "placement_strategy": "uniform", + "task": task, + } reference = Preprocessor(**options).fit(frame).transform(frame) - np.testing.assert_array_equal(Preprocessor(**options).fit(frame, Y).transform(frame), reference) + strict = Preprocessor(**options).set_params(task_validation="raise") + np.testing.assert_array_equal(strict.fit(frame, targets).transform(frame), reference) @pytest.mark.parametrize("method", ["bspline", "mspline", "ispline"]) @@ -444,18 +842,20 @@ def test_multi_output_pipeline_imputes_before_unsupervised_spline(method): @pytest.mark.parametrize("method", ["bspline", "naturalspline", "rbf", "ple"]) -def test_target_aware_numerical_method_rejects_a_multi_output_target(method): +@pytest.mark.parametrize("mode", ["off", "raise"]) +def test_target_aware_numerical_method_rejects_a_multi_output_target(method, mode): """Target-aware placement fits one model on one target. A 2-D target was flattened into twice as many values and failed with an unrelated IndexError / broadcasting error; it now raises a clear error pointing to target_aware=False.""" rng = np.random.default_rng(0) frame = pd.DataFrame({"a": rng.normal(size=200), "b": rng.normal(size=200)}) Y = np.column_stack([np.sin(frame["a"]), np.cos(frame["b"])]) + processor = Preprocessor(numerical_method=method, task_validation=mode) with pytest.raises(IncompatibleParamsError, match=r"single target, but y has shape \(200, 2\)"): - Preprocessor(numerical_method=method).fit(frame, Y) + processor.fit(frame, Y) # A column vector is a single target. - Preprocessor(numerical_method=method).fit(frame, Y[:, :1]) + processor.fit(frame, Y[:, :1]) @pytest.mark.parametrize( diff --git a/tests/integration/test_presets.py b/tests/integration/test_presets.py index 646d3d8..3cf6648 100644 --- a/tests/integration/test_presets.py +++ b/tests/integration/test_presets.py @@ -1,11 +1,14 @@ """Tests for the ``Preprocessor`` preset aliases and ``get_resolved_config`` (P10.5).""" +from dataclasses import replace + import numpy as np import pandas as pd import pytest from sklearn.base import clone -from pretab import Preprocessor +from pretab import Preprocessor, RepresentationConfig +from pretab.compose.registry import TRANSFORMER_REGISTRY from pretab.exceptions import InvalidParamError @@ -29,6 +32,178 @@ def test_no_preset_resolved_config_drops_preset_key(): assert cfg["categorical_method"] == "int" +@pytest.mark.parametrize("form", ["string", "mapping", "value"]) +def test_resolved_config_reports_effective_feature_settings(form): + requested = {"string": "RBF", "mapping": {"method": "RBF"}, "value": RepresentationConfig(method="RBF")}[form] + overrides = {"age": requested} + processor = Preprocessor( + preset="expanded", + feature_preprocessing=overrides, + target_aware=False, + placement_strategy="quantile", + random_state=17, + ) + + report = processor.get_resolved_config() + feature = report["feature_preprocessing"]["age"] + assert feature["method"] == "rbf" + assert feature["output_dim"] == 10 + assert feature["target_aware"] is False + assert feature["placement_strategy"] == "quantile" + assert feature["adaptive"] is False + assert feature["params"] == {"task": "regression", "random_state": 17} + assert processor.get_params()["feature_preprocessing"] is overrides + assert overrides["age"] is requested + + +@pytest.mark.parametrize("form", ["string", "mapping", "value"]) +@pytest.mark.parametrize(("method", "canonical"), [("OHE", "one-hot"), ("identity", "none")]) +def test_resolved_config_reports_categorical_declarations_without_numerical_controls(form, method, canonical): + requested = {"string": method, "mapping": {"method": method}, "value": RepresentationConfig(method=method)}[form] + processor = Preprocessor(preset="adaptive", feature_preprocessing={"city": requested}, degree=2) + + report = processor.get_resolved_config() + + assert set(report) == set(processor.get_params()) - {"preset"} + assert report["feature_preprocessing"] == {"city": {"method": canonical, "params": {}, "name": None}} + assert report["adaptive"] is True + assert report["degree"] == 2 + + +@pytest.mark.parametrize("adaptive", [False, True]) +def test_resolved_config_preserves_local_precedence_and_meaningful_none(adaptive): + settings = {"method": "RBF", "output_dim": 3, "params": {"gamma": 0.5, "random_state": None}, "name": "local"} + if adaptive: + settings.update(adaptive=True, min_output_dim=None, max_output_dim=6) + report = Preprocessor( + preset="adaptive", + feature_preprocessing={"age": settings}, + target_aware=False, + placement_strategy="quantile", + random_state=17, + ).get_resolved_config() + feature = report["feature_preprocessing"]["age"] + + assert feature["method"] == "rbf" + assert feature["output_dim"] == 3 + assert feature["adaptive"] is adaptive + assert feature["name"] == "local" + assert feature["params"] == {"gamma": 0.5, "task": "regression", "random_state": None} + if adaptive: + assert feature["min_output_dim"] is None + assert feature["max_output_dim"] == 6 + else: + assert "min_output_dim" not in feature + assert "max_output_dim" not in feature + assert report["adaptive"] is True + assert report["random_state"] == 17 + + +@pytest.mark.parametrize("overrides", [None, {}]) +def test_resolved_config_without_declarations_keeps_shape_and_detaches_globals(overrides): + policy = {"constant": "allow"} + processor = Preprocessor(feature_preprocessing=overrides, policy=policy) + report = processor.get_resolved_config() + + assert set(report) == set(processor.get_params()) - {"preset"} + assert report["feature_preprocessing"] == overrides + assert report["policy"] == policy + assert report["policy"] is not policy + report["policy"]["constant"] = "raise" + assert policy == {"constant": "allow"} + assert processor.get_resolved_config()["policy"] == policy + + +def test_resolved_config_detaches_nested_params_and_observes_later_raw_edits(monkeypatch): + spec = TRANSFORMER_REGISTRY["rbf"] + monkeypatch.setitem(TRANSFORMER_REGISTRY, "rbf", replace(spec, allowed_args=(*spec.allowed_args, "options"))) + nested = {"weights": [1, {"weight": 0.5}]} + overrides = {"age": {"method": "rbf", "params": {"options": nested}}} + processor = Preprocessor(feature_preprocessing=overrides, target_aware=False, placement_strategy="quantile") + nested["weights"].append(2) + first = processor.get_resolved_config() + returned = first["feature_preprocessing"]["age"]["params"]["options"] + assert returned == {"weights": [1, {"weight": 0.5}, 2]} + nested["weights"].append(3) + returned["weights"][1]["weight"] = 9.0 + returned["weights"].append(4) + first["feature_preprocessing"]["age"]["method"] = "none" + + assert nested == {"weights": [1, {"weight": 0.5}, 2, 3]} + second = processor.get_resolved_config() + assert second["feature_preprocessing"]["age"]["method"] == "rbf" + assert second["feature_preprocessing"]["age"]["params"]["options"] == nested + assert processor.get_params()["feature_preprocessing"] is overrides + + +@pytest.mark.parametrize("frozen", [False, True]) +def test_resolved_config_stays_live_without_refitting_or_reading_fitted_outputs(data, monkeypatch, frozen): + frame, target = data + overrides = {"a": {"method": "rbf", "output_dim": 3}} + processor = Preprocessor( + numerical_method="none", + feature_preprocessing=overrides, + target_aware=False, + placement_strategy="quantile", + scaling="none", + ).fit(frame, target) + if frozen: + processor.freeze() + original = processor.transform(frame, return_array=True) + original_names = processor.get_feature_names_out() + first = processor.get_resolved_config() + overrides["a"]["output_dim"] = 5 + fingerprint = processor.fingerprint_ + + def reject_execution(*args, **kwargs): + raise AssertionError("Configuration reporting must not execute a fitted graph") + + with monkeypatch.context() as patcher: + patcher.setattr(type(processor), "fit", reject_execution) + patcher.setattr(type(processor), "transform", reject_execution) + report = processor.get_resolved_config() + + assert first["feature_preprocessing"]["a"]["output_dim"] == 3 + assert report["feature_preprocessing"]["a"]["output_dim"] == 5 + assert set(report["feature_preprocessing"]) == {"a"} + assert processor.column_transformer_.named_transformers_["num_a"].named_steps["rbf"].output_dim == 3 + assert processor.fingerprint_ == fingerprint + np.testing.assert_array_equal(processor.transform(frame, return_array=True), original) + np.testing.assert_array_equal(processor.get_feature_names_out(), original_names) + overrides["a"]["unexpected"] = True + with pytest.raises(InvalidParamError, match=r"feature_preprocessing\['a'\]\.params\['unexpected'\]"): + processor.get_resolved_config() + np.testing.assert_array_equal(processor.transform(frame, return_array=True), original) + + +@pytest.mark.parametrize( + ("settings", "location"), + [ + ({"method": "unknown"}, "method"), + ({"method": "rff"}, "method"), + ({"method": "rbf", "outpuut_dim": 3}, "outpuut_dim"), + ({"method": "one-hot", "degree": 2}, "degree"), + ({"method": "rbf", "target_aware": True, "placement_strategy": "uniform"}, "placement_strategy"), + ], +) +def test_resolved_config_representation_errors_keep_feature_paths(settings, location): + processor = Preprocessor(feature_preprocessing={"declared": settings}) + with pytest.raises(InvalidParamError) as failure: + processor.get_resolved_config() + assert "feature_preprocessing['declared']" in str(failure.value) + assert location in str(failure.value) + + +@pytest.mark.parametrize("feature", ["a", "not_in_input"]) +def test_resolved_config_does_not_infer_input_schema_or_feature_kind(data, feature): + frame, target = data + processor = Preprocessor(feature_preprocessing={feature: {"method": "OHE"}}) + report = processor.get_resolved_config() + assert report["feature_preprocessing"] == {feature: {"method": "one-hot", "params": {}, "name": None}} + with pytest.raises(InvalidParamError, match="feature_preprocessing"): + processor.fit(frame, target) + + def test_standard_preset_matches_baseline(): # Preprocessor()'s default task is "regression", so the preset resolves # numerical_method to "bspline" (see test_preset_numerical_method_follows_task). diff --git a/tests/integration/test_public_api.py b/tests/integration/test_public_api.py index 095f723..b82d49e 100644 --- a/tests/integration/test_public_api.py +++ b/tests/integration/test_public_api.py @@ -2,13 +2,173 @@ Guards the names third parties import and confirms the legacy ``pretab.pipeline`` package (folded into ``pretab.compose`` during the 1.0.0 restructure) is gone. + +Update current API metadata explicitly, then review the JSON diff before committing:: + + PRETAB_UPDATE_API_SNAPSHOT=1 pytest tests/integration/test_public_api.py -k test_public_api_snapshot """ +import difflib import importlib +import inspect +import json +import os +from dataclasses import asdict, replace +from pathlib import Path import pytest import pretab +from pretab import compose as pretab_compose +from pretab import exceptions as pretab_exceptions +from pretab.compose import registry + +API_SNAPSHOT_PATH = Path(__file__).parents[1] / "regression" / "_snapshots" / "public_api.json" + + +def _snapshot_value(value): + if isinstance(value, type): + return f"{value.__module__}.{value.__qualname__}" + if isinstance(value, frozenset): + return sorted(value) + raise TypeError(f"Unsupported API snapshot value: {type(value).__name__}") + + +def _public_api_contract(): + transformers = importlib.import_module("pretab.transformers") + callables = { + f"pretab.{name}": member + for name in pretab.__all__ + if callable(member := getattr(pretab, name)) + and not (isinstance(member, type) and issubclass(member, BaseException)) + } + callables.update({f"pretab.transformers.{name}": getattr(transformers, name) for name in transformers.__all__}) + exception_classes = { + name: member + for name in pretab_exceptions.__all__ + if isinstance(member := getattr(pretab_exceptions, name), type) and issubclass(member, BaseException) + } + capabilities = [name for name, member in vars(registry.TransformerSpec).items() if isinstance(member, property)] + contract = { + "exports": { + "pretab": sorted(pretab.__all__), + "pretab.compose": sorted(pretab_compose.__all__), + "pretab.transformers": sorted(transformers.__all__), + "pretab.exceptions": sorted(pretab_exceptions.__all__), + "pretab.compose.registry": sorted(registry.__all__), + }, + "signatures": {name: str(inspect.signature(member)) for name, member in callables.items()}, + "registry": { + name: {**asdict(spec), "derived_capabilities": {key: getattr(spec, key) for key in capabilities}} + for name, spec in registry.TRANSFORMER_REGISTRY.items() + }, + "aliases": {"numerical": registry.NUMERICAL_ALIASES, "categorical": registry.CATEGORICAL_ALIASES}, + "selectable_methods": { + "numerical": sorted(registry.NUMERICAL_METHODS), + "categorical": sorted(registry.CATEGORICAL_METHODS), + }, + "exceptions": { + name: { + "class": member, + "bases": member.__bases__, + "kind": "warning" if issubclass(member, Warning) else "error", + } + for name, member in exception_classes.items() + }, + } + return json.loads(json.dumps(contract, default=_snapshot_value, allow_nan=False)) + + +def _assert_api_snapshot(actual, path, *, update=False): + rendered = json.dumps(actual, indent=2, sort_keys=True, allow_nan=False) + "\n" + if update: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(rendered, encoding="utf-8") + return + assert path.is_file(), ( + f"Missing API snapshot: {path}. Create it explicitly with PRETAB_UPDATE_API_SNAPSHOT=1 " + "pytest tests/integration/test_public_api.py -k test_public_api_snapshot, then review the diff." + ) + expected = json.loads(path.read_text(encoding="utf-8")) + if expected != actual: + difference = "".join( + difflib.unified_diff( + (json.dumps(expected, indent=2, sort_keys=True, allow_nan=False) + "\n").splitlines(keepends=True), + rendered.splitlines(keepends=True), + fromfile="reviewed public API", + tofile="current public API", + ) + ) + pytest.fail( + f"Public API changed. Review compatibility before updating the snapshot.\n{difference}", pytrace=False + ) + + +def test_public_api_snapshot(): + _assert_api_snapshot( + _public_api_contract(), API_SNAPSHOT_PATH, update=os.environ.get("PRETAB_UPDATE_API_SNAPSHOT") == "1" + ) + + +def test_api_snapshot_update_is_explicit(tmp_path): + path = tmp_path / "snapshots" / "api.json" + with pytest.raises(AssertionError, match="PRETAB_UPDATE_API_SNAPSHOT=1"): + _assert_api_snapshot({"default": 7}, path) + assert not path.exists() + + _assert_api_snapshot({"default": 7}, path, update=True) + _assert_api_snapshot({"default": 7}, path) + with pytest.raises(pytest.fail.Exception, match="Public API changed"): + _assert_api_snapshot({"default": 8}, path) + assert json.loads(path.read_text(encoding="utf-8")) == {"default": 7} + + _assert_api_snapshot({"default": 8}, path, update=True) + assert json.loads(path.read_text(encoding="utf-8")) == {"default": 8} + + +@pytest.mark.parametrize("surface", ["signature", "default", "registry", "alias", "exception", "export"]) +def test_api_snapshot_rejects_surface_drift_without_rewriting(tmp_path, monkeypatch, surface): + path = tmp_path / "api.json" + _assert_api_snapshot(_public_api_contract(), path, update=True) + reviewed = path.read_bytes() + + if surface in {"signature", "default"}: + signature = inspect.signature(pretab.Preprocessor) + parameters = list(signature.parameters.values()) + if surface == "signature": + parameters.append(inspect.Parameter("contract_probe", inspect.Parameter.KEYWORD_ONLY, default=None)) + else: + parameters = [ + parameter.replace(default=99) if parameter.name == "output_dim" else parameter + for parameter in parameters + ] + monkeypatch.setattr( + pretab.Preprocessor, "__signature__", signature.replace(parameters=parameters), raising=False + ) + elif surface == "registry": + original = registry.TRANSFORMER_REGISTRY["rbf"] + monkeypatch.setitem( + registry.TRANSFORMER_REGISTRY, + "rbf", + replace(original, supports_adaptive_resolution=not original.supports_adaptive_resolution), + ) + elif surface == "alias": + monkeypatch.setitem(registry.NUMERICAL_ALIASES, "std", "minmax") + elif surface == "exception": + changed = type("PretabDataError", (pretab_exceptions.PretabError,), {"__module__": pretab_exceptions.__name__}) + monkeypatch.setattr(pretab_exceptions, "PretabDataError", changed) + else: + monkeypatch.setattr(pretab, "__all__", [*pretab.__all__, "contract_probe"]) + monkeypatch.setattr(pretab, "contract_probe", pretab.Preprocessor, raising=False) + + with pytest.raises(pytest.fail.Exception) as failure: + _assert_api_snapshot(_public_api_contract(), path) + message = str(failure.value) + assert "--- reviewed public API" in message + assert "+++ current public API" in message + assert "@@" in message + assert path.read_bytes() == reviewed + # The stable public transformer facade. Every name here must stay importable from # ``pretab.transformers`` no matter how the internal modules are relocated during the @@ -59,6 +219,23 @@ def test_preprocessor_is_constructible(): assert pretab.Preprocessor() is not None +def test_representation_config_public_exports_are_identical(): + from pretab.compose.config import RepresentationConfig + + assert pretab.RepresentationConfig is RepresentationConfig + assert pretab_compose.RepresentationConfig is RepresentationConfig + assert "RepresentationConfig" in pretab.__all__ + assert pretab_compose.__all__ == ["FeatureGroup", "RepresentationConfig"] + + +def test_feature_group_public_exports_are_identical(): + from pretab.compose.config import FeatureGroup + + assert pretab.FeatureGroup is FeatureGroup + assert pretab_compose.FeatureGroup is FeatureGroup + assert "FeatureGroup" in pretab.__all__ + + def test_transformers_public_surface_is_resolvable(): transformers = importlib.import_module("pretab.transformers") assert transformers.__all__ diff --git a/tests/integration/test_serialization.py b/tests/integration/test_serialization.py index b0a4f17..a4d1c0d 100644 --- a/tests/integration/test_serialization.py +++ b/tests/integration/test_serialization.py @@ -1,21 +1,37 @@ -"""Tests for portable serialization: ``to_spec`` / ``from_spec`` (P9.1). +"""Tests for fitted-state serialization through specs and pickle. Covers the versioned JSON envelope, bit-for-bit transform reproduction across -representation families, file round-trips, categorical / missing-value handling, +representation families, fitted metadata, file round-trips, categorical / missing-value handling, policy preservation, and the security allow-list that keeps loading a spec safe (unlike ``pickle``). """ import json import math +import pickle +import sys from typing import cast import numpy as np import pandas as pd import pytest - -from pretab import Preprocessor, PretabSerializationError, RepresentationPolicy -from pretab.compose.serialize import SCHEMA_VERSION +from sklearn import config_context +from sklearn.base import clone +from sklearn.exceptions import NotFittedError + +from pretab import ( + FeatureGroup, + PenaltySpec, + Preprocessor, + PretabSerializationError, + RepresentationConfig, + RepresentationPolicy, +) +from pretab.compose.registry import TransformerSpec +from pretab.compose.serialize import SCHEMA_VERSION, _decode, _encode, _encode_mapping +from pretab.core.parameters import UNSET +from pretab.exceptions import InvalidParamError, OptionalDependencyError +from pretab.preprocessing.floats import NoTransformer, ToFloatTransformer @pytest.fixture @@ -36,6 +52,57 @@ def target(): return rng.random(60) +@pytest.mark.parametrize("restore_format", ["pickle", "spec"]) +def test_legacy_state_restores_constructor_defaults(frame, restore_format, tmp_path): + processor = Preprocessor(numerical_method="rbf", target_aware=False, placement_strategy="uniform").fit(frame) + expected = processor.transform(frame) + fingerprint = processor.fingerprint_ + if restore_format == "pickle": + del processor.feature_groups + del processor.task_validation + del processor._fit_config_ + restored = pickle.loads(pickle.dumps(processor)) # noqa: S301 + else: + spec = processor.to_spec() + del spec["state"]["feature_groups"] + del spec["params"]["feature_groups"] + del spec["state"]["task_validation"] + del spec["params"]["task_validation"] + del spec["state"]["_fit_config_"] + for key in ("resolved_config", "output_dims", "total_output_dim", "feature_lineage"): + del spec[key] + spec["schema_version"] = 1 + path = tmp_path / "legacy-v1.json" + path.write_text(json.dumps(spec, allow_nan=False), encoding="utf-8") + restored = Preprocessor.from_spec(path) + + assert restored.get_params(deep=False)["feature_groups"] is None + assert restored.get_params(deep=False)["task_validation"] == "off" + assert restored.get_resolved_config()["feature_groups"] is None + assert restored.get_resolved_config()["task_validation"] == "off" + assert restored.fingerprint_ == fingerprint + rewritten = restored.to_spec() + assert rewritten["schema_version"] == 1 + assert "resolved_config" not in rewritten + assert "_fit_config_" not in rewritten["state"] + np.testing.assert_array_equal(restored.transform(frame), expected) + copied = clone(restored) + assert isinstance(copied, Preprocessor) + assert copied.feature_groups is None + assert copied.task_validation == "off" + + +def test_spec_preserves_nondefault_task_validation(frame): + processor = Preprocessor(numerical_method="minmax", task_validation="raise").fit(frame) + expected = processor.transform(frame) + spec = processor.to_spec() + assert spec["params"]["task_validation"] == "raise" + restored = Preprocessor.from_spec(spec) + assert restored.get_resolved_config()["task_validation"] == "raise" + assert restored.fingerprint_ == processor.fingerprint_ + np.testing.assert_array_equal(restored.transform(frame), expected) + + # Representation configs that round-trip; each is (params, id). _CONFIGS = [ {"numerical_method": "rbf", "target_aware": False, "placement_strategy": "quantile"}, @@ -43,6 +110,8 @@ def target(): {"numerical_method": "tanh", "target_aware": False, "placement_strategy": "quantile"}, {"numerical_method": "relu", "target_aware": False, "placement_strategy": "quantile"}, {"numerical_method": "bspline", "target_aware": False, "placement_strategy": "quantile"}, + {"numerical_method": "mspline", "target_aware": False, "placement_strategy": "quantile"}, + {"numerical_method": "ispline", "target_aware": False, "placement_strategy": "quantile"}, {"numerical_method": "cubicspline", "target_aware": False, "placement_strategy": "quantile"}, {"numerical_method": "naturalspline", "target_aware": False, "placement_strategy": "quantile"}, {"numerical_method": "pspline", "target_aware": False, "placement_strategy": "uniform"}, @@ -59,15 +128,114 @@ def _ids(configs): @pytest.mark.parametrize("params", _CONFIGS, ids=_ids(_CONFIGS)) @pytest.mark.parametrize("categorical_method", ["int", "one-hot"]) -def test_round_trip_reproduces_transform_bit_for_bit(frame, target, params, categorical_method): +@pytest.mark.parametrize("restore_format", ["pickle", "spec"]) +def test_round_trip_reproduces_transform_bit_for_bit(frame, target, params, categorical_method, restore_format): p = Preprocessor(output_dim=6, categorical_method=categorical_method, **params).fit(frame, target) + fingerprint = p.fingerprint_ + names = p.get_feature_names_out() + dimensions = p.output_dims_ + feature_info = p.get_feature_info(verbose=False) reference = np.asarray(p.transform(frame, return_array=True), dtype=float) - restored = Preprocessor.from_spec(p.to_spec()) + if restore_format == "pickle": + restored = pickle.loads(pickle.dumps(p)) # noqa: S301 - only locally generated test data + else: + restored = Preprocessor.from_spec(json.loads(json.dumps(p.to_spec(), allow_nan=False))) reproduced = np.asarray(restored.transform(frame, return_array=True), dtype=float) assert np.array_equal(reference, reproduced, equal_nan=True) - assert list(p.get_feature_names_out()) == list(restored.get_feature_names_out()) + np.testing.assert_array_equal(restored.get_feature_names_out(), names) + assert reference.shape == reproduced.shape == (len(frame), len(names)) + assert sum(dimensions.values()) == reference.shape[1] + assert restored.output_dims_ == dimensions + assert restored.get_feature_info(verbose=False) == feature_info + assert p.fingerprint_ == restored.fingerprint_ == fingerprint + + +@pytest.mark.parametrize("restore_format", ["pickle", "spec"]) +@pytest.mark.parametrize("helper_type", [NoTransformer, ToFloatTransformer]) +@pytest.mark.parametrize("add_missing_indicator", [False, True]) +@pytest.mark.parametrize("frozen", [False, True]) +def test_restore_legacy_sparse_one_hot_feature_count(restore_format, helper_type, add_missing_indicator, frozen): + frame = pd.DataFrame({"city": ["Rome", None, "Berlin", "Rome"]}) + fitted = Preprocessor( + numerical_method="none", categorical_method="one-hot", add_missing_indicator=add_missing_indicator + ).fit(frame) + fitted.set_output(transform="default") + if frozen: + fitted.freeze() + expected = fitted.transform(frame) + expected_names = fitted.get_feature_names_out() + expected_info = fitted.get_feature_info(verbose=False) + spec = fitted.to_spec() + pipeline = fitted.column_transformer_.named_transformers_["cat_city"] + if add_missing_indicator: + pipeline = dict(pipeline.transformer_list)["representation"] + helper = helper_type() + helper.__dict__.update(vars(pipeline.named_steps["to_float"])) + helper.n_features_in_ = 1 + pipeline.steps[-1] = ("to_float", helper) + + if restore_format == "pickle": + restored = pickle.loads(pickle.dumps(fitted)) # noqa: S301 - only locally generated test data + else: + spec["state"] = _encode_mapping(vars(fitted)) + restored = Preprocessor.from_spec(spec) + + np.testing.assert_array_equal(restored.transform(frame), expected) + np.testing.assert_array_equal(restored.get_feature_names_out(), expected_names) + assert restored.get_feature_info(verbose=False) == expected_info + assert restored.is_frozen() == frozen + assert vars(restored)["_sklearn_output_config"] == vars(fitted)["_sklearn_output_config"] + restored_pipeline = restored.column_transformer_.named_transformers_["cat_city"] + if add_missing_indicator: + restored_pipeline = dict(restored_pipeline.transformer_list)["representation"] + restored_helper = restored_pipeline.named_steps["to_float"] + assert type(restored_helper) is helper_type + assert restored_helper.n_features_in_ == 2 + rewritten = Preprocessor.from_spec(restored.to_spec()) + assert rewritten.fingerprint_ == restored.fingerprint_ + np.testing.assert_array_equal(rewritten.transform(frame), expected) + + +@pytest.mark.parametrize("restore_format", ["pickle", "spec"]) +@pytest.mark.parametrize("helper_type", [NoTransformer, ToFloatTransformer]) +@pytest.mark.parametrize("state_case", ["healthy", "unexpected_width", "dense_input", "named_input"]) +def test_restore_preserves_nonlegacy_helper_metadata(restore_format, helper_type, state_case): + frame = pd.DataFrame({"city": ["Rome", "Berlin", "Rome"]}) + fitted = Preprocessor(numerical_method="none", categorical_method="one-hot").fit(frame) + spec = fitted.to_spec() + pipeline = fitted.column_transformer_.named_transformers_["cat_city"] + helper = helper_type() + helper.__dict__.update(vars(pipeline.named_steps["to_float"])) + expected_count = {"healthy": 2, "unexpected_width": 3, "dense_input": 1, "named_input": 1}[state_case] + helper.n_features_in_ = expected_count + if state_case == "dense_input": + pipeline.named_steps["onehot"].sparse_output = False + if state_case == "named_input": + helper.feature_names_in_ = np.array(["fitted_name"], dtype=object) + pipeline.steps[-1] = ("to_float", helper) + + if restore_format == "pickle": + restored = pickle.loads(pickle.dumps(fitted)) # noqa: S301 - only locally generated test data + else: + spec["state"] = _encode_mapping(vars(fitted)) + restored = Preprocessor.from_spec(spec) + + restored_helper = restored.column_transformer_.named_transformers_["cat_city"].named_steps["to_float"] + assert restored_helper.n_features_in_ == expected_count + if state_case == "named_input": + np.testing.assert_array_equal(restored_helper.feature_names_in_, ["fitted_name"]) + if state_case != "healthy": + with pytest.raises(ValueError): + restored.get_feature_names_out() + + +def test_pickle_unfitted_preprocessor_preserves_params(): + original = Preprocessor(numerical_method="none", categorical_method="one-hot") + restored = pickle.loads(pickle.dumps(original)) # noqa: S301 - only locally generated test data + assert restored.get_params() == original.get_params() + assert not hasattr(restored, "column_transformer_") def test_spec_is_json_serializable_and_versioned(frame, target): @@ -107,6 +275,192 @@ def test_representation_summary_present(frame, target): assert "rbf" in families +def test_spec_content_describes_the_fit_after_requests_change(frame): + X = frame.assign(extra=np.linspace(-2, 2, len(frame))) + override = {"method": "RBF", "output_dim": 3, "gamma": 0.5} + processor = Preprocessor( + numerical_method="minmax", + target_aware=False, + placement_strategy="quantile", + feature_preprocessing={"extra": override}, + feature_groups=[FeatureGroup("joint", ("b", "a"), RepresentationConfig("tensorspline", output_dim=4))], + ).fit(X) + override["gamma"] = 1.5 + processor.set_params(numerical_method="none", feature_groups=None) + + spec = json.loads(json.dumps(processor.to_spec(), allow_nan=False)) + + assert spec["params"]["numerical_method"] == "none" + assert spec["params"]["feature_preprocessing"]["extra"]["gamma"] == 1.5 + assert spec["params"]["feature_groups"] is None + resolved = spec["resolved_config"] + assert resolved["numerical_method"] == "minmax" + extra = resolved["feature_preprocessing"]["extra"] + assert (extra["method"], extra["output_dim"], extra["params"]["gamma"]) == ("rbf", 3, 0.5) + group = resolved["feature_groups"][0] + assert (group["name"], group["columns"], group["representation"]["method"]) == ("joint", ["b", "a"], "tensorspline") + assert spec["output_dims"] == processor.output_dims_ + assert spec["total_output_dim"] == processor.total_output_dim_ + assert spec["feature_lineage"] == [item.to_dict() for item in processor.get_feature_lineage()] + assert [item["source_features"] for item in spec["feature_lineage"] if item.get("group_id")] == [["b", "a"]] * spec[ + "output_dims" + ]["group_joint"] + + restored = Preprocessor.from_spec(spec) + assert restored.to_spec()["resolved_config"] == resolved + np.testing.assert_array_equal(restored.transform(X), processor.transform(X)) + + processor.fit(X) + refit_spec = processor.to_spec() + assert refit_spec["resolved_config"]["feature_groups"] is None + assert refit_spec["resolved_config"]["feature_preprocessing"]["extra"]["params"]["gamma"] == 1.5 + assert "group_joint" not in refit_spec["output_dims"] + + +@pytest.mark.parametrize("restore", ["none", "current", "legacy"]) +def test_verbose_feature_info_uses_recorded_fit_settings(frame, caplog, restore): + fitting_frame = frame.assign(extra=np.linspace(-2, 2, len(frame))) + override = {"method": "RBF", "output_dim": 3, "gamma": 0.5} + processor = Preprocessor( + numerical_method="minmax", + target_aware=False, + placement_strategy="uniform", + feature_preprocessing={"extra": override}, + feature_groups=[FeatureGroup("joint", ("b", "a"), RepresentationConfig("tensorspline", output_dim=4))], + ).fit(fitting_frame) + override["gamma"] = 1.5 + processor.set_params(feature_groups=None) + if restore != "none": + spec = processor.to_spec() + if restore == "legacy": + del spec["state"]["_fit_config_"] + del spec["resolved_config"] + processor = Preprocessor.from_spec(json.loads(json.dumps(spec, allow_nan=False))) + + before = processor.to_spec() + fingerprint = processor.fingerprint_ + with caplog.at_level("INFO", logger="pretab"): + quiet = processor.get_feature_info(verbose=False) + assert not caplog.messages + assert processor.get_feature_info() == quiet + + assert quiet[0]["group_joint"]["dimension"] == 16 + assert "gamma=1.5" not in caplog.text + if restore == "legacy": + assert "Fit-time effective settings unavailable (not recorded)." in caplog.messages + else: + single = next(message for message in caplog.messages if message.startswith("feature 'extra':")) + assert "method='rbf'" in single and "output_dim=3" in single and "gamma=0.5" in single + assert "placement_strategy='uniform'" in single and "target_aware=False" in single + group = next(message for message in caplog.messages if message.startswith("group_joint (sources=['b', 'a']):")) + assert "method='tensorspline'" in group and "output_dim=4" in group + assert processor.fingerprint_ == fingerprint + assert processor.to_spec() == before + + +@pytest.mark.parametrize("via_file", [False, True], ids=["dict", "file"]) +@pytest.mark.parametrize( + ("path", "value"), + [ + pytest.param(("output_dims", "group_joint"), 1, id="block-width"), + pytest.param(("total_output_dim",), 1, id="total-width"), + pytest.param(("params", "feature_preprocessing", "extra", "output_dim"), 4, id="requested-width"), + pytest.param(("params", "feature_groups", "joint", "columns"), ["a", "b"], id="requested-group-order"), + pytest.param(("resolved_config", "feature_preprocessing", "extra", "output_dim"), 4, id="fitted-width"), + pytest.param(("resolved_config", "feature_groups", 0, "columns"), ["a", "b"], id="fitted-group-order"), + pytest.param(("representations", 1, "dimension"), 1, id="group-summary-width"), + pytest.param(("representations", 1, "columns"), ["a", "b"], id="group-summary-order"), + pytest.param(("representations", 1, "output_slice"), [0, 1], id="group-summary-slice"), + ], +) +def test_from_spec_rejects_inconsistent_metadata(frame, tmp_path, via_file, path, value): + fitting_frame = frame.assign(extra=np.linspace(-2, 2, len(frame))) + processor = Preprocessor( + numerical_method="minmax", + target_aware=False, + placement_strategy="uniform", + feature_preprocessing={"extra": {"method": "rbf", "output_dim": 3}}, + feature_groups={ + "joint": {"columns": ["b", "a"], "representation": {"method": "tensorspline", "output_dim": 4}} + }, + ).fit(fitting_frame) + spec = processor.to_spec() + assert spec["representations"][1]["group_id"] == "group_joint" + destination = spec + for key in path[:-1]: + destination = destination[key] + assert destination[path[-1]] != value + destination[path[-1]] = value + + source = spec + if via_file: + source = tmp_path / "inconsistent.json" + source.write_text(json.dumps(spec, allow_nan=False), encoding="utf-8") + with pytest.raises(PretabSerializationError, match=path[0]): + Preprocessor.from_spec(source) + + +def test_to_spec_unfitted_does_not_create_file(tmp_path): + path = tmp_path / "unfitted.json" + with pytest.raises(NotFittedError): + Preprocessor().to_spec(path) + assert not path.exists() + + +@pytest.mark.parametrize("group_method", ["tensorspline", "tprs"]) +def test_spec_content_includes_only_supported_penalty_summaries(frame, group_method): + X = frame.assign(extra=np.linspace(-2, 2, len(frame))) + X.loc[::7, "b"] = np.nan + width_option = "output_dim" if group_method == "tensorspline" else "n_components" + processor = Preprocessor( + numerical_method="pspline", + output_dim=7, + target_aware=False, + placement_strategy="uniform", + feature_groups={"joint": {"columns": ["b", "a"], "representation": {"method": group_method, width_option: 4}}}, + missing_policy="separate_state", + ).fit(X) + + spec = json.loads(json.dumps(processor.to_spec(), allow_nan=False)) + group = next(entry for entry in spec["representations"] if entry.get("group_id") == "group_joint") + single = next(entry for entry in spec["representations"] if entry["columns"] == ["extra"]) + (penalty,) = single["penalties"] + assert penalty["shape"] == [single["output_dim"]] * 2 + assert penalty["order"] == 2 + assert len(penalty["matrix_sha256"]) == 64 + assert "matrix" not in penalty + if group_method == "tensorspline": + assert [penalty["axis"] for penalty in group["penalties"]] == [["b"], ["a"]] + assert group["dimension"] == group["output_dim"] + 2 + for penalty in group["penalties"]: + assert penalty["shape"] == [group["output_dim"]] * 2 + assert "matrix" not in penalty + else: + assert "penalties" not in group + assert Preprocessor.from_spec(spec).to_spec()["representations"] == spec["representations"] + + del spec["state"]["_fit_config_"] + legacy_spec = Preprocessor.from_spec(spec).to_spec() + assert "resolved_config" not in legacy_spec + assert all("penalties" not in entry for entry in legacy_spec["representations"]) + + +def test_spec_content_keeps_legacy_only_pspline_orders_replayable(frame): + processor = Preprocessor( + numerical_method="minmax", + target_aware=False, + placement_strategy="uniform", + feature_preprocessing={"a": {"method": "pspline", "output_dim": 7, "diff_order": 3}}, + ).fit(frame) + + spec = json.loads(json.dumps(processor.to_spec(), allow_nan=False)) + entry = next(entry for entry in spec["representations"] if entry["columns"] == ["a"]) + + assert "penalties" not in entry + restored = Preprocessor.from_spec(spec) + np.testing.assert_array_equal(restored.transform(frame), processor.transform(frame)) + + @pytest.mark.parametrize("leaf_input", ["imputed", "frame"]) def test_representation_summary_names_each_block_after_its_column(frame, target, leaf_input): """Without an imputer or scaler each representation is fitted on its DataFrame @@ -158,6 +512,51 @@ def test_round_trip_preserves_dtype_and_output_format(frame, target): assert restored.output_format == "dense" +@pytest.mark.parametrize("transform", [None, "default", "pandas"], ids=["unset", "default", "pandas"]) +def test_portable_spec_restores_without_polars(frame, monkeypatch, transform): + fitted = Preprocessor(numerical_method="minmax").fit(frame).set_output(transform=transform) + expected = fitted.transform(frame) + spec = fitted.to_spec() + with monkeypatch.context() as missing: + missing.setitem(sys.modules, "polars", None) + with config_context(transform_output="polars"): + restored = Preprocessor.from_spec(spec) + + actual = restored.transform(frame) + assert type(actual) is type(expected) + np.testing.assert_array_equal(actual, expected) + np.testing.assert_array_equal(restored.get_feature_names_out(), fitted.get_feature_names_out()) + + +@pytest.mark.parametrize("as_file", [False, True], ids=["dict", "file"]) +def test_spec_with_polars_output_requires_polars_at_restore(frame, monkeypatch, tmp_path, as_file): + fitted = Preprocessor(numerical_method="minmax").fit(frame).set_output(transform="polars") + path = tmp_path / "preprocessor.json" + spec = fitted.to_spec(path if as_file else None) + monkeypatch.setitem(sys.modules, "polars", None) + + with pytest.raises(OptionalDependencyError, match=r"set_output.*requires.*polars.*pip install polars"): + Preprocessor.from_spec(path if as_file else spec) + + +@pytest.mark.parametrize("transform", ["default", "polars"]) +def test_spec_round_trip_after_fit_on_polars(frame, monkeypatch, transform): + polars = pytest.importorskip("polars") + polars_frame = polars.DataFrame(frame.to_dict(orient="list")) + fitted = Preprocessor(numerical_method="minmax").fit(polars_frame).set_output(transform=transform) + expected = fitted.transform(frame) + spec = fitted.to_spec() + with monkeypatch.context() as missing: + if transform == "default": + missing.setitem(sys.modules, "polars", None) + restored = Preprocessor.from_spec(spec) + + actual = restored.transform(frame) + assert isinstance(actual, polars.DataFrame if transform == "polars" else np.ndarray) + np.testing.assert_array_equal(actual, expected) + np.testing.assert_array_equal(restored.get_feature_names_out(), fitted.get_feature_names_out()) + + def test_round_trip_preserves_policy(frame, target): p = Preprocessor( numerical_method="bspline", @@ -170,22 +569,64 @@ def test_round_trip_preserves_policy(frame, target): assert restored.policy_.constant == "error" -def test_round_trip_with_missing_values(target): +@pytest.mark.parametrize( + "params", + [ + pytest.param(config, id=config["numerical_method"]) + for config in _CONFIGS + if config["numerical_method"] in {"bspline", "ple", "rbf"} + ], +) +@pytest.mark.parametrize("categorical_method", ["int", "one-hot"]) +@pytest.mark.parametrize("missing_policy", ["impute", "impute_with_indicator", "separate_state"]) +@pytest.mark.parametrize("restore_format", ["pickle", "spec"]) +def test_round_trip_with_missing_values(params, categorical_method, missing_policy, restore_format): frame = pd.DataFrame({"a": [1.0, np.nan, 3.0, 4.0, np.nan, 6.0] * 5, "c": ["x", "y", None, "x", "y", "z"] * 5}) y = np.arange(len(frame), dtype=float) p = Preprocessor( - numerical_method="rbf", - categorical_method="one-hot", - target_aware=False, - placement_strategy="quantile", - numerical_imputation="median", + output_dim=6, + categorical_method=categorical_method, + missing_policy=missing_policy, + random_state=0, + **params, ).fit(frame, y) - restored = Preprocessor.from_spec(p.to_spec()) - assert np.array_equal( - np.asarray(p.transform(frame, return_array=True), dtype=float), - np.asarray(restored.transform(frame, return_array=True), dtype=float), - equal_nan=True, - ) + fingerprint = p.fingerprint_ + names = list(p.get_feature_names_out()) + dimensions = p.output_dims_ + feature_info = p.get_feature_info(verbose=False) + reference = np.asarray(p.transform(frame, return_array=True), dtype=float) + if restore_format == "pickle": + restored = pickle.loads(pickle.dumps(p)) # noqa: S301 - only locally generated test data + else: + restored = Preprocessor.from_spec(json.loads(json.dumps(p.to_spec(), allow_nan=False))) + + np.testing.assert_array_equal(restored.transform(frame, return_array=True), reference) + assert reference.shape == (len(frame), len(names)) + assert np.isfinite(reference).all() + assert sum(dimensions.values()) == reference.shape[1] + assert list(restored.get_feature_names_out()) == names + assert restored.output_dims_ == dimensions + assert restored.get_feature_info(verbose=False) == feature_info + assert feature_info[0]["a"]["dimension"] == dimensions["a"] + assert feature_info[1]["c"]["dimension"] == dimensions["c"] + assert feature_info[2] == {} + + for candidate in (p, restored): + for column, prefix in (("a", "num"), ("c", "cat")): + if missing_policy != "impute": + suffix = ( + f"missingindicator_{column}" + if missing_policy == "impute_with_indicator" + else f"missing__{column}__missing" + ) + indicator_name = f"{prefix}_{column}__{suffix}" + output = np.asarray(candidate.transform(frame, return_array=True), dtype=float) + np.testing.assert_array_equal( + output[:, names.index(indicator_name)], frame[column].isna().astype(float) + ) + with pytest.raises(ValueError, match="columns are missing"): + candidate.transform(frame.drop(columns=[column])) + assert candidate.fingerprint_ == fingerprint def test_round_trip_reproduces_unseen_category_encoding(frame, target): @@ -304,7 +745,8 @@ def test_from_spec_refuses_estimator_not_a_base_estimator(): Preprocessor.from_spec(spec) -def test_from_spec_refuses_dataclass_not_in_allowlist(): +@pytest.mark.parametrize("class_name", ["PreprocessorConfig", "_FrozenParams"]) +def test_from_spec_refuses_dataclass_not_in_allowlist(class_name): """An allowed-module, genuinely-a-dataclass class must still be refused unless it is one of the specifically approved dataclasses. @@ -316,15 +758,150 @@ def test_from_spec_refuses_dataclass_not_in_allowlist(): spec = { "schema_version": SCHEMA_VERSION, "state": { - "__dict__": [ - ["evil", {"__dataclass__": {"class": "pretab.compose.config:PreprocessorConfig", "fields": {}}}] - ] + "__dict__": [["evil", {"__dataclass__": {"class": f"pretab.compose.config:{class_name}", "fields": {}}}]] }, } with pytest.raises(PretabSerializationError, match="disallowed dataclass"): Preprocessor.from_spec(spec) +@pytest.mark.parametrize( + "settings", + [ + {"method": "RBF"}, + {"method": "rbf", "output_dim": 3, "adaptive": False, "name": "local"}, + { + "method": "rbf", + "adaptive": True, + "min_output_dim": None, + "max_output_dim": 7, + "params": {"random_state": None, "nested": {"levels": [True, 2, 0.5, None]}}, + }, + ], +) +def test_representation_config_codec_preserves_portable_values(settings): + value = RepresentationConfig.from_dict(settings) + text = json.dumps(_encode(value), allow_nan=False) + assert "_FrozenParams" not in text + restored = _decode(json.loads(text)) + assert type(restored) is RepresentationConfig + assert restored == value + assert restored.to_dict() == value.to_dict() + for field in ("output_dim", "target_aware", "placement_strategy", "adaptive", "min_output_dim", "max_output_dim"): + if field not in settings: + assert getattr(restored, field) is UNSET + detached = restored.to_dict() + detached["params"]["changed"] = True + assert restored == value + + +@pytest.mark.parametrize( + ("fields", "constraint"), + [ + ({"output_dim": 0}, "must be a positive integer"), + ({"adaptive": "yes"}, "must be a boolean"), + ({"params": {"gamma": math.inf}}, "finite JSON-compatible values"), + ], +) +def test_representation_config_decoder_runs_value_validation(fields, constraint): + payload = { + "__dataclass__": { + "class": "pretab.compose.config:RepresentationConfig", + "fields": _encode_mapping({"method": "rbf", **fields}), + } + } + with pytest.raises(InvalidParamError, match=constraint): + _decode(payload) + + +def test_feature_group_codec_preserves_order_and_nested_config(): + value = FeatureGroup("joint", (10, "first"), RepresentationConfig("tensorspline", output_dim=3)) + + restored = _decode(json.loads(json.dumps(_encode(value), allow_nan=False))) + + assert type(restored) is FeatureGroup + assert restored == value + assert restored.columns == (10, "first") + + +def test_penalty_spec_codec_preserves_exact_immutable_values(): + value = PenaltySpec( + matrix=[[-0.0, 0.0, 0.0], [0.0, 1.0, -1.0], [0.0, -1.0, 1.0]], + kind="coefficient_difference", + order=1, + axis=("age",), + coordinate_system="basis_coefficients", + coefficient_names=("bias", "basis_0", "basis_1"), + coefficient_indices=(3, 4, 5), + atol=1e-12, + rtol=1e-9, + provenance={"source": {"details": [{"label": "age", "verified": True}, None]}}, + ) + + payload = json.loads(json.dumps(_encode(value), allow_nan=False)) + fields = payload["__dataclass__"]["fields"] + assert "__ndarray__" in fields["matrix"] + assert {"_matrix_bytes", "rank", "nullity"}.isdisjoint(fields) + restored = _decode(payload) + + assert type(restored) is PenaltySpec + assert restored == value + assert restored.matrix.dtype == np.float64 + assert restored.matrix.tobytes() == value.matrix.tobytes() + assert (restored.rank, restored.nullity) == (1, 2) + with pytest.raises(ValueError, match="WRITEABLE"): + restored.matrix.setflags(write=True) + with pytest.raises(TypeError): + restored.provenance["source"]["details"][0]["label"] = "changed" + + +def test_penalty_spec_decoder_runs_matrix_validation(): + payload = { + "__dataclass__": { + "class": "pretab.expansion.spline.penalty:PenaltySpec", + "fields": _encode_mapping( + { + "matrix": np.array([[-1.0]]), + "kind": "curvature", + "order": None, + "axis": ("age",), + "coordinate_system": "basis_coefficients", + "coefficient_names": ("basis_0",), + "coefficient_indices": (0,), + } + ), + } + } + + with pytest.raises(InvalidParamError, match="positive semidefinite"): + _decode(payload) + + +@pytest.mark.parametrize( + ("group_fields", "expected"), + [ + ({}, (False, 1, 1)), + ({"group_compatible": False, "min_arity": 1, "max_arity": 1}, (False, 1, 1)), + ({"group_compatible": True, "min_arity": 2, "max_arity": None}, (True, 2, None)), + ], + ids=["legacy", "standalone", "group"], +) +def test_registry_spec_decoder_uses_additive_group_metadata(group_fields, expected): + payload = { + "__dataclass__": { + "class": "pretab.compose.registry:TransformerSpec", + "fields": {"name": "custom", "transformer_cls": _encode(NoTransformer), **group_fields}, + } + } + + restored = _decode(json.loads(json.dumps(payload, allow_nan=False))) + + assert isinstance(restored, TransformerSpec) + assert restored.name == "custom" + assert restored.transformer_cls is NoTransformer + assert (restored.group_compatible, restored.min_arity, restored.max_arity) == expected + + def test_from_spec_rejects_bad_source_type(): with pytest.raises(PretabSerializationError): Preprocessor.from_spec(12345) @@ -496,7 +1073,9 @@ def test_failed_save_leaves_an_existing_spec_untouched(tmp_path, monkeypatch, un # already-opened file used to leave a truncated, invalid spec behind. spec = pre.to_spec() monkeypatch.setattr( - preprocessor_module, "preprocessor_to_spec", lambda _: {**spec, "state": {"unsupported_": unsupported}} + preprocessor_module, + "preprocessor_to_spec", + lambda _processor, **_options: {**spec, "state": {"unsupported_": unsupported}}, ) with pytest.raises(PretabSerializationError, match="cannot be written as JSON"): pre.to_spec(path) @@ -512,6 +1091,46 @@ def test_types_a_spec_cannot_load_are_rejected_at_save_time(): _encode(list) +class _ExternalEstimator(NoTransformer): + pass + + +def test_nested_external_estimator_is_rejected_by_spec_callers(frame, tmp_path): + processor = Preprocessor(numerical_method="minmax").fit(frame) + expected = processor.transform(frame) + path = tmp_path / "spec.json" + spec = processor.to_spec(path) + saved = path.read_bytes() + fingerprint = processor.fingerprint_ + assert processor.reproducibility_report()["fingerprint"] == fingerprint + restored = Preprocessor.from_spec(path) + assert restored.to_spec() == spec + assert restored.fingerprint_ == fingerprint + np.testing.assert_array_equal(restored.transform(frame), expected) + + fitted_pipeline = processor.column_transformer_.named_transformers_["num_a"] + nested = {"estimators": [_ExternalEstimator()]} + fitted_pipeline.extension_state_ = nested + missing_path = tmp_path / "not-created.json" + message = r"_ExternalEstimator.*Registration does not enable spec persistence.*built-in" + + with pytest.raises(PretabSerializationError, match=message): + processor.to_spec() + with pytest.raises(PretabSerializationError, match=message): + processor.to_spec(path) + with pytest.raises(PretabSerializationError, match=message): + processor.to_spec(missing_path) + with pytest.raises(PretabSerializationError, match=message): + _ = processor.fingerprint_ + with pytest.raises(PretabSerializationError, match=message): + processor.reproducibility_report() + + assert path.read_bytes() == saved + assert not missing_path.exists() + assert fitted_pipeline.extension_state_ is nested + np.testing.assert_array_equal(processor.transform(frame), expected) + + def test_object_arrays_written_before_element_encoding_still_load(): from pretab.compose.serialize import _decode diff --git a/tests/regression/_snapshots/public_api.json b/tests/regression/_snapshots/public_api.json new file mode 100644 index 0000000..b0050c6 --- /dev/null +++ b/tests/regression/_snapshots/public_api.json @@ -0,0 +1,1192 @@ +{ + "aliases": { + "categorical": { + "dummy": "one-hot", + "embedding": "pretrained", + "embeddings": "pretrained", + "identity": "none", + "integer": "int", + "label": "int", + "labelencoder": "int", + "language": "pretrained", + "llm": "pretrained", + "ohe": "one-hot", + "onehotencoder": "one-hot", + "ordinal": "int", + "ordinalencoder": "int", + "passthrough": "none", + "raw": "none" + }, + "numerical": { + "bin": "custombin", + "binning": "custombin", + "cubic": "cubicspline", + "fourierfeatures": "fourier", + "identity": "none", + "minmaxscaler": "minmax", + "natural": "naturalspline", + "naturalcubic": "naturalspline", + "nystrom": "nystroem", + "passthrough": "none", + "piecewiselinear": "ple", + "poly": "polynomial", + "quantiletransformer": "quantile", + "randomfourier": "rff", + "randomfourierfeatures": "rff", + "raw": "none", + "rbfsampler": "rff", + "robustscaler": "robust", + "standard": "standardization", + "standardize": "standardization", + "standardscaler": "standardization", + "std": "standardization", + "tensor": "tensorspline", + "tensorproduct": "tensorspline", + "tensorproductspline": "tensorspline", + "thinplate": "tprs", + "thinplatespline": "tprs", + "zscore": "standardization" + } + }, + "exceptions": { + "ConfigWarning": { + "bases": ["pretab.exceptions.PretabWarning"], + "class": "pretab.exceptions.ConfigWarning", + "kind": "warning" + }, + "DataWarning": { + "bases": ["pretab.exceptions.PretabWarning"], + "class": "pretab.exceptions.DataWarning", + "kind": "warning" + }, + "EmptyDataError": { + "bases": ["pretab.exceptions.PretabDataError"], + "class": "pretab.exceptions.EmptyDataError", + "kind": "error" + }, + "FrozenRepresentationError": { + "bases": ["pretab.exceptions.PretabError"], + "class": "pretab.exceptions.FrozenRepresentationError", + "kind": "error" + }, + "IncompatibleParamsError": { + "bases": ["pretab.exceptions.PretabConfigError"], + "class": "pretab.exceptions.IncompatibleParamsError", + "kind": "error" + }, + "InsufficientSamplesError": { + "bases": ["pretab.exceptions.PretabDataError"], + "class": "pretab.exceptions.InsufficientSamplesError", + "kind": "error" + }, + "InvalidParamError": { + "bases": ["pretab.exceptions.PretabConfigError"], + "class": "pretab.exceptions.InvalidParamError", + "kind": "error" + }, + "LeakageWarning": { + "bases": ["pretab.exceptions.PretabWarning"], + "class": "pretab.exceptions.LeakageWarning", + "kind": "warning" + }, + "OptionalDependencyError": { + "bases": ["pretab.exceptions.PretabError", "builtins.ImportError"], + "class": "pretab.exceptions.OptionalDependencyError", + "kind": "error" + }, + "OutputBudgetError": { + "bases": ["pretab.exceptions.PretabError", "builtins.ValueError"], + "class": "pretab.exceptions.OutputBudgetError", + "kind": "error" + }, + "PretabConfigError": { + "bases": ["pretab.exceptions.PretabError", "builtins.ValueError"], + "class": "pretab.exceptions.PretabConfigError", + "kind": "error" + }, + "PretabDataError": { + "bases": ["pretab.exceptions.PretabError", "builtins.ValueError"], + "class": "pretab.exceptions.PretabDataError", + "kind": "error" + }, + "PretabError": { + "bases": ["builtins.Exception"], + "class": "pretab.exceptions.PretabError", + "kind": "error" + }, + "PretabNotFittedError": { + "bases": [ + "pretab.exceptions.PretabError", + "sklearn.exceptions.NotFittedError" + ], + "class": "pretab.exceptions.PretabNotFittedError", + "kind": "error" + }, + "PretabSerializationError": { + "bases": ["pretab.exceptions.PretabError", "builtins.ValueError"], + "class": "pretab.exceptions.PretabSerializationError", + "kind": "error" + }, + "PretabWarning": { + "bases": ["builtins.UserWarning"], + "class": "pretab.exceptions.PretabWarning", + "kind": "warning" + }, + "RepresentationConformanceError": { + "bases": ["pretab.exceptions.PretabError", "builtins.AssertionError"], + "class": "pretab.exceptions.RepresentationConformanceError", + "kind": "error" + } + }, + "exports": { + "pretab": [ + "BaseRepresentation", + "CrossFittedTransformer", + "FeatureGroup", + "FeatureLineage", + "FrozenRepresentationError", + "LeakageWarning", + "OutputBudgetError", + "PenaltySpec", + "Preprocessor", + "PretabSerializationError", + "PretabWarning", + "RepresentationConfig", + "RepresentationConformanceError", + "RepresentationPolicy", + "RepresentationSearchCV", + "RepresentationSpec", + "__version__", + "check_representation", + "configure_logging", + "list_representations", + "load_entry_point_representations", + "register_representation", + "set_verbosity" + ], + "pretab.compose": ["FeatureGroup", "RepresentationConfig"], + "pretab.compose.registry": [ + "CATEGORICAL_ALIASES", + "CATEGORICAL_METHODS", + "NUMERICAL_ALIASES", + "NUMERICAL_METHODS", + "TRANSFORMER_REGISTRY", + "TransformerSpec", + "categorical_method_names", + "get_spec", + "numerical_method_names", + "placement_strategies_for", + "register_spec", + "resolve_method", + "supports_adaptive_resolution", + "supports_target_aware" + ], + "pretab.exceptions": [ + "ConfigWarning", + "DataWarning", + "EmptyDataError", + "FrozenRepresentationError", + "IncompatibleParamsError", + "InsufficientSamplesError", + "InvalidParamError", + "LeakageWarning", + "OptionalDependencyError", + "OutputBudgetError", + "PretabConfigError", + "PretabDataError", + "PretabError", + "PretabNotFittedError", + "PretabSerializationError", + "PretabWarning", + "RepresentationConformanceError", + "insufficient_samples_error", + "invalid_param_error" + ], + "pretab.transformers": [ + "BSplineTransformer", + "ContinuousOrdinalTransformer", + "CubicRegressionSplineTransformer", + "FourierFeatureTransformer", + "ISplineTransformer", + "LanguageEmbeddingTransformer", + "MSplineTransformer", + "MissingStateIndicator", + "NaturalCubicSplineTransformer", + "NoTransformer", + "NumericBinningTransformer", + "NystroemFeaturesTransformer", + "OneHotFromOrdinalTransformer", + "PLETransformer", + "PSplineTransformer", + "PeriodicEncodingTransformer", + "RBFExpansionTransformer", + "RandomFourierFeaturesTransformer", + "ReLUExpansionTransformer", + "SigmoidExpansionTransformer", + "TanhExpansionTransformer", + "TensorProductSplineTransformer", + "ThinPlateSplineTransformer", + "ToFloatTransformer" + ] + }, + "registry": { + "box-cox": { + "allowed_args": [], + "arity": "univariate", + "derived_capabilities": { + "is_categorical": false, + "is_multivariate": false, + "is_numerical": true, + "is_supervised": false, + "requires_target": false, + "requires_y": false, + "target_aware_capable": false + }, + "feature_kind": ["numerical"], + "group_compatible": false, + "max_arity": 1, + "min_arity": 1, + "name": "box-cox", + "optional_dependency": null, + "periodic": false, + "placement_strategies": [], + "preprocessor_compatible": true, + "sparse_output": false, + "supports_adaptive_resolution": false, + "target_usage": "forbidden", + "transformer_cls": "sklearn.preprocessing._data.PowerTransformer", + "typed_penalty": false + }, + "bspline": { + "allowed_args": [ + "degree", + "task", + "adaptive", + "min_output_dim", + "max_output_dim", + "random_state" + ], + "arity": "univariate", + "derived_capabilities": { + "is_categorical": false, + "is_multivariate": false, + "is_numerical": true, + "is_supervised": true, + "requires_target": false, + "requires_y": false, + "target_aware_capable": true + }, + "feature_kind": ["numerical"], + "group_compatible": false, + "max_arity": 1, + "min_arity": 1, + "name": "bspline", + "optional_dependency": null, + "periodic": false, + "placement_strategies": ["cart", "lightgbm", "quantile", "uniform"], + "preprocessor_compatible": true, + "sparse_output": false, + "supports_adaptive_resolution": true, + "target_usage": "optional", + "transformer_cls": "pretab.expansion.spline.b_spline.BSplineTransformer", + "typed_penalty": true + }, + "cubicspline": { + "allowed_args": [ + "output_dim", + "degree", + "include_bias", + "task", + "adaptive", + "min_output_dim", + "max_output_dim", + "random_state" + ], + "arity": "univariate", + "derived_capabilities": { + "is_categorical": false, + "is_multivariate": false, + "is_numerical": true, + "is_supervised": true, + "requires_target": false, + "requires_y": false, + "target_aware_capable": true + }, + "feature_kind": ["numerical"], + "group_compatible": false, + "max_arity": 1, + "min_arity": 1, + "name": "cubicspline", + "optional_dependency": null, + "periodic": false, + "placement_strategies": ["cart", "lightgbm", "quantile", "uniform"], + "preprocessor_compatible": true, + "sparse_output": false, + "supports_adaptive_resolution": true, + "target_usage": "optional", + "transformer_cls": "pretab.expansion.spline.cubic_regression.CubicRegressionSplineTransformer", + "typed_penalty": true + }, + "custombin": { + "allowed_args": ["output_dim", "encode"], + "arity": "univariate", + "derived_capabilities": { + "is_categorical": false, + "is_multivariate": false, + "is_numerical": true, + "is_supervised": false, + "requires_target": false, + "requires_y": false, + "target_aware_capable": false + }, + "feature_kind": ["numerical"], + "group_compatible": false, + "max_arity": 1, + "min_arity": 1, + "name": "custombin", + "optional_dependency": null, + "periodic": false, + "placement_strategies": ["quantile", "uniform"], + "preprocessor_compatible": true, + "sparse_output": false, + "supports_adaptive_resolution": false, + "target_usage": "forbidden", + "transformer_cls": "pretab.encoding.numerical.binning.NumericBinningTransformer", + "typed_penalty": false + }, + "fourier": { + "allowed_args": [ + "n_frequencies", + "frequency_strategy", + "include_original", + "random_state" + ], + "arity": "univariate", + "derived_capabilities": { + "is_categorical": false, + "is_multivariate": false, + "is_numerical": true, + "is_supervised": false, + "requires_target": false, + "requires_y": false, + "target_aware_capable": false + }, + "feature_kind": ["numerical"], + "group_compatible": false, + "max_arity": 1, + "min_arity": 1, + "name": "fourier", + "optional_dependency": null, + "periodic": true, + "placement_strategies": [], + "preprocessor_compatible": true, + "sparse_output": false, + "supports_adaptive_resolution": false, + "target_usage": "forbidden", + "transformer_cls": "pretab.expansion.functional.fourier.FourierFeatureTransformer", + "typed_penalty": false + }, + "int": { + "allowed_args": [], + "arity": "univariate", + "derived_capabilities": { + "is_categorical": true, + "is_multivariate": false, + "is_numerical": false, + "is_supervised": false, + "requires_target": false, + "requires_y": false, + "target_aware_capable": false + }, + "feature_kind": ["categorical"], + "group_compatible": false, + "max_arity": 1, + "min_arity": 1, + "name": "int", + "optional_dependency": null, + "periodic": false, + "placement_strategies": [], + "preprocessor_compatible": true, + "sparse_output": false, + "supports_adaptive_resolution": false, + "target_usage": "forbidden", + "transformer_cls": "pretab.encoding.categorical.ordinal.ContinuousOrdinalTransformer", + "typed_penalty": false + }, + "ispline": { + "allowed_args": [ + "degree", + "task", + "adaptive", + "min_output_dim", + "max_output_dim", + "random_state" + ], + "arity": "univariate", + "derived_capabilities": { + "is_categorical": false, + "is_multivariate": false, + "is_numerical": true, + "is_supervised": true, + "requires_target": false, + "requires_y": false, + "target_aware_capable": true + }, + "feature_kind": ["numerical"], + "group_compatible": false, + "max_arity": 1, + "min_arity": 1, + "name": "ispline", + "optional_dependency": null, + "periodic": false, + "placement_strategies": ["cart", "lightgbm", "quantile", "uniform"], + "preprocessor_compatible": true, + "sparse_output": false, + "supports_adaptive_resolution": true, + "target_usage": "optional", + "transformer_cls": "pretab.expansion.spline.i_spline.ISplineTransformer", + "typed_penalty": true + }, + "minmax": { + "allowed_args": [], + "arity": "univariate", + "derived_capabilities": { + "is_categorical": false, + "is_multivariate": false, + "is_numerical": true, + "is_supervised": false, + "requires_target": false, + "requires_y": false, + "target_aware_capable": false + }, + "feature_kind": ["numerical"], + "group_compatible": false, + "max_arity": 1, + "min_arity": 1, + "name": "minmax", + "optional_dependency": null, + "periodic": false, + "placement_strategies": [], + "preprocessor_compatible": true, + "sparse_output": false, + "supports_adaptive_resolution": false, + "target_usage": "forbidden", + "transformer_cls": "sklearn.preprocessing._data.MinMaxScaler", + "typed_penalty": false + }, + "mspline": { + "allowed_args": [ + "degree", + "task", + "adaptive", + "min_output_dim", + "max_output_dim", + "random_state" + ], + "arity": "univariate", + "derived_capabilities": { + "is_categorical": false, + "is_multivariate": false, + "is_numerical": true, + "is_supervised": true, + "requires_target": false, + "requires_y": false, + "target_aware_capable": true + }, + "feature_kind": ["numerical"], + "group_compatible": false, + "max_arity": 1, + "min_arity": 1, + "name": "mspline", + "optional_dependency": null, + "periodic": false, + "placement_strategies": ["cart", "lightgbm", "quantile", "uniform"], + "preprocessor_compatible": true, + "sparse_output": false, + "supports_adaptive_resolution": true, + "target_usage": "optional", + "transformer_cls": "pretab.expansion.spline.m_spline.MSplineTransformer", + "typed_penalty": true + }, + "naturalspline": { + "allowed_args": [ + "output_dim", + "include_bias", + "task", + "adaptive", + "min_output_dim", + "max_output_dim", + "random_state" + ], + "arity": "univariate", + "derived_capabilities": { + "is_categorical": false, + "is_multivariate": false, + "is_numerical": true, + "is_supervised": true, + "requires_target": false, + "requires_y": false, + "target_aware_capable": true + }, + "feature_kind": ["numerical"], + "group_compatible": false, + "max_arity": 1, + "min_arity": 1, + "name": "naturalspline", + "optional_dependency": null, + "periodic": false, + "placement_strategies": ["cart", "lightgbm", "quantile", "uniform"], + "preprocessor_compatible": true, + "sparse_output": false, + "supports_adaptive_resolution": true, + "target_usage": "optional", + "transformer_cls": "pretab.expansion.spline.natural_cubic.NaturalCubicSplineTransformer", + "typed_penalty": true + }, + "none": { + "allowed_args": [], + "arity": "univariate", + "derived_capabilities": { + "is_categorical": true, + "is_multivariate": false, + "is_numerical": true, + "is_supervised": false, + "requires_target": false, + "requires_y": false, + "target_aware_capable": false + }, + "feature_kind": ["categorical", "numerical"], + "group_compatible": false, + "max_arity": 1, + "min_arity": 1, + "name": "none", + "optional_dependency": null, + "periodic": false, + "placement_strategies": [], + "preprocessor_compatible": true, + "sparse_output": false, + "supports_adaptive_resolution": false, + "target_usage": "forbidden", + "transformer_cls": "pretab.preprocessing.floats.NoTransformer", + "typed_penalty": false + }, + "nystroem": { + "allowed_args": [ + "n_components", + "kernel", + "gamma", + "degree", + "coef0", + "random_state" + ], + "arity": "multivariate", + "derived_capabilities": { + "is_categorical": false, + "is_multivariate": true, + "is_numerical": true, + "is_supervised": false, + "requires_target": false, + "requires_y": false, + "target_aware_capable": false + }, + "feature_kind": ["numerical"], + "group_compatible": false, + "max_arity": 1, + "min_arity": 1, + "name": "nystroem", + "optional_dependency": null, + "periodic": false, + "placement_strategies": [], + "preprocessor_compatible": false, + "sparse_output": false, + "supports_adaptive_resolution": false, + "target_usage": "forbidden", + "transformer_cls": "pretab.kernel_approximation.nystroem.NystroemFeaturesTransformer", + "typed_penalty": false + }, + "one-hot": { + "allowed_args": [ + "categories", + "drop", + "sparse_output", + "dtype", + "handle_unknown", + "min_frequency", + "max_categories", + "feature_name_combiner" + ], + "arity": "univariate", + "derived_capabilities": { + "is_categorical": true, + "is_multivariate": false, + "is_numerical": false, + "is_supervised": false, + "requires_target": false, + "requires_y": false, + "target_aware_capable": false + }, + "feature_kind": ["categorical"], + "group_compatible": false, + "max_arity": 1, + "min_arity": 1, + "name": "one-hot", + "optional_dependency": null, + "periodic": false, + "placement_strategies": [], + "preprocessor_compatible": true, + "sparse_output": true, + "supports_adaptive_resolution": false, + "target_usage": "forbidden", + "transformer_cls": "sklearn.preprocessing._encoders.OneHotEncoder", + "typed_penalty": false + }, + "onehot_from_ordinal": { + "allowed_args": [], + "arity": "univariate", + "derived_capabilities": { + "is_categorical": true, + "is_multivariate": false, + "is_numerical": false, + "is_supervised": false, + "requires_target": false, + "requires_y": false, + "target_aware_capable": false + }, + "feature_kind": ["categorical"], + "group_compatible": false, + "max_arity": 1, + "min_arity": 1, + "name": "onehot_from_ordinal", + "optional_dependency": null, + "periodic": false, + "placement_strategies": [], + "preprocessor_compatible": true, + "sparse_output": false, + "supports_adaptive_resolution": false, + "target_usage": "forbidden", + "transformer_cls": "pretab.encoding.categorical.one_hot.OneHotFromOrdinalTransformer", + "typed_penalty": false + }, + "ple": { + "allowed_args": [ + "output_dim", + "task", + "adaptive", + "min_output_dim", + "max_output_dim", + "random_state" + ], + "arity": "univariate", + "derived_capabilities": { + "is_categorical": false, + "is_multivariate": false, + "is_numerical": true, + "is_supervised": true, + "requires_target": true, + "requires_y": true, + "target_aware_capable": true + }, + "feature_kind": ["numerical"], + "group_compatible": false, + "max_arity": 1, + "min_arity": 1, + "name": "ple", + "optional_dependency": null, + "periodic": false, + "placement_strategies": ["cart", "lightgbm"], + "preprocessor_compatible": true, + "sparse_output": false, + "supports_adaptive_resolution": true, + "target_usage": "required", + "transformer_cls": "pretab.encoding.numerical.ple.PLETransformer", + "typed_penalty": false + }, + "polynomial": { + "allowed_args": ["degree", "interaction_only", "include_bias"], + "arity": "univariate", + "derived_capabilities": { + "is_categorical": false, + "is_multivariate": false, + "is_numerical": true, + "is_supervised": false, + "requires_target": false, + "requires_y": false, + "target_aware_capable": false + }, + "feature_kind": ["numerical"], + "group_compatible": false, + "max_arity": 1, + "min_arity": 1, + "name": "polynomial", + "optional_dependency": null, + "periodic": false, + "placement_strategies": [], + "preprocessor_compatible": true, + "sparse_output": false, + "supports_adaptive_resolution": false, + "target_usage": "forbidden", + "transformer_cls": "sklearn.preprocessing._polynomial.PolynomialFeatures", + "typed_penalty": false + }, + "pretrained": { + "allowed_args": [], + "arity": "univariate", + "derived_capabilities": { + "is_categorical": true, + "is_multivariate": false, + "is_numerical": false, + "is_supervised": false, + "requires_target": false, + "requires_y": false, + "target_aware_capable": false + }, + "feature_kind": ["categorical"], + "group_compatible": false, + "max_arity": 1, + "min_arity": 1, + "name": "pretrained", + "optional_dependency": "embeddings", + "periodic": false, + "placement_strategies": [], + "preprocessor_compatible": true, + "sparse_output": false, + "supports_adaptive_resolution": false, + "target_usage": "forbidden", + "transformer_cls": "pretab.embedding.language.LanguageEmbeddingTransformer", + "typed_penalty": false + }, + "pspline": { + "allowed_args": ["output_dim", "degree", "diff_order"], + "arity": "univariate", + "derived_capabilities": { + "is_categorical": false, + "is_multivariate": false, + "is_numerical": true, + "is_supervised": false, + "requires_target": false, + "requires_y": false, + "target_aware_capable": false + }, + "feature_kind": ["numerical"], + "group_compatible": false, + "max_arity": 1, + "min_arity": 1, + "name": "pspline", + "optional_dependency": null, + "periodic": false, + "placement_strategies": ["uniform"], + "preprocessor_compatible": true, + "sparse_output": false, + "supports_adaptive_resolution": false, + "target_usage": "forbidden", + "transformer_cls": "pretab.expansion.spline.p_spline.PSplineTransformer", + "typed_penalty": true + }, + "quantile": { + "allowed_args": ["n_quantiles", "output_distribution", "random_state"], + "arity": "univariate", + "derived_capabilities": { + "is_categorical": false, + "is_multivariate": false, + "is_numerical": true, + "is_supervised": false, + "requires_target": false, + "requires_y": false, + "target_aware_capable": false + }, + "feature_kind": ["numerical"], + "group_compatible": false, + "max_arity": 1, + "min_arity": 1, + "name": "quantile", + "optional_dependency": null, + "periodic": false, + "placement_strategies": [], + "preprocessor_compatible": true, + "sparse_output": false, + "supports_adaptive_resolution": false, + "target_usage": "forbidden", + "transformer_cls": "sklearn.preprocessing._data.QuantileTransformer", + "typed_penalty": false + }, + "rbf": { + "allowed_args": [ + "output_dim", + "gamma", + "task", + "adaptive", + "min_output_dim", + "max_output_dim", + "random_state" + ], + "arity": "univariate", + "derived_capabilities": { + "is_categorical": false, + "is_multivariate": false, + "is_numerical": true, + "is_supervised": true, + "requires_target": false, + "requires_y": false, + "target_aware_capable": true + }, + "feature_kind": ["numerical"], + "group_compatible": false, + "max_arity": 1, + "min_arity": 1, + "name": "rbf", + "optional_dependency": null, + "periodic": false, + "placement_strategies": ["cart", "lightgbm", "quantile", "uniform"], + "preprocessor_compatible": true, + "sparse_output": false, + "supports_adaptive_resolution": true, + "target_usage": "optional", + "transformer_cls": "pretab.expansion.functional.rbf.RBFExpansionTransformer", + "typed_penalty": false + }, + "relu": { + "allowed_args": [ + "output_dim", + "task", + "adaptive", + "min_output_dim", + "max_output_dim", + "random_state" + ], + "arity": "univariate", + "derived_capabilities": { + "is_categorical": false, + "is_multivariate": false, + "is_numerical": true, + "is_supervised": true, + "requires_target": false, + "requires_y": false, + "target_aware_capable": true + }, + "feature_kind": ["numerical"], + "group_compatible": false, + "max_arity": 1, + "min_arity": 1, + "name": "relu", + "optional_dependency": null, + "periodic": false, + "placement_strategies": ["cart", "lightgbm", "quantile", "uniform"], + "preprocessor_compatible": true, + "sparse_output": false, + "supports_adaptive_resolution": true, + "target_usage": "optional", + "transformer_cls": "pretab.expansion.functional.relu.ReLUExpansionTransformer", + "typed_penalty": false + }, + "rff": { + "allowed_args": ["n_components", "gamma", "random_state"], + "arity": "multivariate", + "derived_capabilities": { + "is_categorical": false, + "is_multivariate": true, + "is_numerical": true, + "is_supervised": false, + "requires_target": false, + "requires_y": false, + "target_aware_capable": false + }, + "feature_kind": ["numerical"], + "group_compatible": false, + "max_arity": 1, + "min_arity": 1, + "name": "rff", + "optional_dependency": null, + "periodic": false, + "placement_strategies": [], + "preprocessor_compatible": false, + "sparse_output": false, + "supports_adaptive_resolution": false, + "target_usage": "forbidden", + "transformer_cls": "pretab.kernel_approximation.random_fourier.RandomFourierFeaturesTransformer", + "typed_penalty": false + }, + "robust": { + "allowed_args": [], + "arity": "univariate", + "derived_capabilities": { + "is_categorical": false, + "is_multivariate": false, + "is_numerical": true, + "is_supervised": false, + "requires_target": false, + "requires_y": false, + "target_aware_capable": false + }, + "feature_kind": ["numerical"], + "group_compatible": false, + "max_arity": 1, + "min_arity": 1, + "name": "robust", + "optional_dependency": null, + "periodic": false, + "placement_strategies": [], + "preprocessor_compatible": true, + "sparse_output": false, + "supports_adaptive_resolution": false, + "target_usage": "forbidden", + "transformer_cls": "sklearn.preprocessing._data.RobustScaler", + "typed_penalty": false + }, + "sigmoid": { + "allowed_args": [ + "output_dim", + "task", + "adaptive", + "min_output_dim", + "max_output_dim", + "random_state" + ], + "arity": "univariate", + "derived_capabilities": { + "is_categorical": false, + "is_multivariate": false, + "is_numerical": true, + "is_supervised": true, + "requires_target": false, + "requires_y": false, + "target_aware_capable": true + }, + "feature_kind": ["numerical"], + "group_compatible": false, + "max_arity": 1, + "min_arity": 1, + "name": "sigmoid", + "optional_dependency": null, + "periodic": false, + "placement_strategies": ["cart", "lightgbm", "quantile", "uniform"], + "preprocessor_compatible": true, + "sparse_output": false, + "supports_adaptive_resolution": true, + "target_usage": "optional", + "transformer_cls": "pretab.expansion.functional.sigmoid.SigmoidExpansionTransformer", + "typed_penalty": false + }, + "standardization": { + "allowed_args": [], + "arity": "univariate", + "derived_capabilities": { + "is_categorical": false, + "is_multivariate": false, + "is_numerical": true, + "is_supervised": false, + "requires_target": false, + "requires_y": false, + "target_aware_capable": false + }, + "feature_kind": ["numerical"], + "group_compatible": false, + "max_arity": 1, + "min_arity": 1, + "name": "standardization", + "optional_dependency": null, + "periodic": false, + "placement_strategies": [], + "preprocessor_compatible": true, + "sparse_output": false, + "supports_adaptive_resolution": false, + "target_usage": "forbidden", + "transformer_cls": "sklearn.preprocessing._data.StandardScaler", + "typed_penalty": false + }, + "tanh": { + "allowed_args": [ + "output_dim", + "scale", + "task", + "adaptive", + "min_output_dim", + "max_output_dim", + "random_state" + ], + "arity": "univariate", + "derived_capabilities": { + "is_categorical": false, + "is_multivariate": false, + "is_numerical": true, + "is_supervised": true, + "requires_target": false, + "requires_y": false, + "target_aware_capable": true + }, + "feature_kind": ["numerical"], + "group_compatible": false, + "max_arity": 1, + "min_arity": 1, + "name": "tanh", + "optional_dependency": null, + "periodic": false, + "placement_strategies": ["cart", "lightgbm", "quantile", "uniform"], + "preprocessor_compatible": true, + "sparse_output": false, + "supports_adaptive_resolution": true, + "target_usage": "optional", + "transformer_cls": "pretab.expansion.functional.tanh.TanhExpansionTransformer", + "typed_penalty": false + }, + "tensorspline": { + "allowed_args": ["output_dim", "degree", "diff_order"], + "arity": "multivariate", + "derived_capabilities": { + "is_categorical": false, + "is_multivariate": true, + "is_numerical": true, + "is_supervised": false, + "requires_target": false, + "requires_y": false, + "target_aware_capable": false + }, + "feature_kind": ["numerical"], + "group_compatible": true, + "max_arity": null, + "min_arity": 2, + "name": "tensorspline", + "optional_dependency": null, + "periodic": false, + "placement_strategies": ["quantile", "uniform"], + "preprocessor_compatible": false, + "sparse_output": false, + "supports_adaptive_resolution": false, + "target_usage": "forbidden", + "transformer_cls": "pretab.expansion.spline.multivariate.tensor_product.TensorProductSplineTransformer", + "typed_penalty": true + }, + "tprs": { + "allowed_args": [ + "n_components", + "landmark_strategy", + "rank_strategy", + "random_state" + ], + "arity": "multivariate", + "derived_capabilities": { + "is_categorical": false, + "is_multivariate": true, + "is_numerical": true, + "is_supervised": false, + "requires_target": false, + "requires_y": false, + "target_aware_capable": false + }, + "feature_kind": ["numerical"], + "group_compatible": true, + "max_arity": null, + "min_arity": 2, + "name": "tprs", + "optional_dependency": null, + "periodic": false, + "placement_strategies": [], + "preprocessor_compatible": false, + "sparse_output": false, + "supports_adaptive_resolution": false, + "target_usage": "forbidden", + "transformer_cls": "pretab.expansion.spline.multivariate.thin_plate.ThinPlateSplineTransformer", + "typed_penalty": false + }, + "yeo-johnson": { + "allowed_args": [], + "arity": "univariate", + "derived_capabilities": { + "is_categorical": false, + "is_multivariate": false, + "is_numerical": true, + "is_supervised": false, + "requires_target": false, + "requires_y": false, + "target_aware_capable": false + }, + "feature_kind": ["numerical"], + "group_compatible": false, + "max_arity": 1, + "min_arity": 1, + "name": "yeo-johnson", + "optional_dependency": null, + "periodic": false, + "placement_strategies": [], + "preprocessor_compatible": true, + "sparse_output": false, + "supports_adaptive_resolution": false, + "target_usage": "forbidden", + "transformer_cls": "sklearn.preprocessing._data.PowerTransformer", + "typed_penalty": false + } + }, + "selectable_methods": { + "categorical": [ + "int", + "none", + "one-hot", + "onehot_from_ordinal", + "pretrained" + ], + "numerical": [ + "box-cox", + "bspline", + "cubicspline", + "custombin", + "fourier", + "ispline", + "minmax", + "mspline", + "naturalspline", + "none", + "ple", + "polynomial", + "pspline", + "quantile", + "rbf", + "relu", + "robust", + "sigmoid", + "standardization", + "tanh", + "yeo-johnson" + ] + }, + "signatures": { + "pretab.BaseRepresentation": "()", + "pretab.CrossFittedTransformer": "(transformer, n_folds=5, task='regression', shuffle=True, random_state=None, *, task_validation='off')", + "pretab.FeatureGroup": "(name: 'str', columns: 'Sequence[Any]', representation: 'str | Mapping[str, Any] | RepresentationConfig') -> None", + "pretab.FeatureLineage": "(output_feature: str, output_index: int, source_features: tuple[str, ...], family: str, component: str, component_index: int, uses_target: bool, is_interaction: bool, group_id: str | None = None) -> None", + "pretab.PenaltySpec": "(matrix: 'ArrayLike', kind: 'str', order: 'int | None', axis: 'Sequence[str]', coordinate_system: 'str', coefficient_names: 'Sequence[str]', coefficient_indices: 'Sequence[int]', atol: 'float' = 1e-10, rtol: 'float' = 1e-10, provenance: 'Mapping[str, Any] | None' = None) -> 'None'", + "pretab.Preprocessor": "(numerical_method=UNSET, categorical_method=UNSET, feature_preprocessing=None, output_dim=UNSET, degree=3, target_aware=True, placement_strategy='cart', task='regression', adaptive=UNSET, min_output_dim=UNSET, max_output_dim=UNSET, random_state=None, scaling='minmax', cat_cutoff=0.03, treat_all_integers_as_numerical=False, numerical_imputation: str | None = 'median', categorical_imputation: str | None = 'most_frequent', add_missing_indicator=False, missing_policy=None, policy=None, max_output_features=None, max_features_per_input=None, max_dense_memory=None, overflow_policy='error', output_structure='matrix', output_format='dense', dtype=None, verbose=0, preset=None, *, feature_groups=None, task_validation='off')", + "pretab.RepresentationConfig": "(method: 'str', output_dim: 'int | _Unset' = UNSET, target_aware: 'bool | _Unset' = UNSET, placement_strategy: 'str | _Unset' = UNSET, adaptive: 'bool | _Unset' = UNSET, min_output_dim: 'int | _Unset | None' = UNSET, max_output_dim: 'int | _Unset | None' = UNSET, params: 'Mapping[str, Any]' = , name: 'str | None' = None) -> None", + "pretab.RepresentationPolicy": "(constant: 'str' = 'allow', out_of_range: 'str' = 'extrapolate') -> None", + "pretab.RepresentationSearchCV": "(estimator, methods, *, cv=5, scoring=None, preprocessor_params=None, random_state=None, task_validation='off')", + "pretab.RepresentationSpec": "(family: str, component_kind: str, scope: str, supervision: str, uses_target: bool, is_interaction: bool, input_features: tuple[str, ...], output_features: tuple[str, ...], output_dim: int, degree: int | None, include_bias: bool, periodic: bool, period: float | None, local_support: bool, location_kind: str | None, locations: tuple[tuple[float, ...], ...] | None, dtype: str = 'float64', cross_fitted: bool = False, n_folds: int | None = None) -> None", + "pretab.check_representation": "(cls, *, X=None, y=None)", + "pretab.configure_logging": "(level: int = 1, handler: 'logging.Handler | None' = None) -> None", + "pretab.list_representations": "(*, feature_kind=None, scope=None, supervised=None, periodic=None, sparse_output=None, adaptive=None, include_optional=True)", + "pretab.load_entry_point_representations": "(group='pretab.representations', *, override=False)", + "pretab.register_representation": "(name, cls, *, feature_kind=None, scope=None, supervision=None, allowed_args=(), placement_strategies=(), supports_adaptive_resolution=False, preprocessor_compatible=True, optional_dependency=None, periodic=False, sparse_output=False, override=False, typed_penalty=False)", + "pretab.set_verbosity": "(level: int = 1) -> None", + "pretab.transformers.BSplineTransformer": "(output_dim=UNSET, degree: int = 3, include_bias: bool = False, knot_locations: numpy.ndarray | None = None, target_aware: bool = False, placement_strategy: str = 'quantile', task: Optional[Literal['regression', 'classification']] = None, adaptive: bool = False, min_output_dim=UNSET, max_output_dim=UNSET, random_state: int | None = None, policy: pretab.core.policy.RepresentationPolicy | dict | None = None)", + "pretab.transformers.ContinuousOrdinalTransformer": "()", + "pretab.transformers.CubicRegressionSplineTransformer": "(output_dim=UNSET, degree=3, include_bias=False, target_aware: bool = False, placement_strategy: str = 'uniform', task=None, adaptive: bool = False, min_output_dim=UNSET, max_output_dim=UNSET, random_state: int | None = None, policy: pretab.core.policy.RepresentationPolicy | dict | None = None)", + "pretab.transformers.FourierFeatureTransformer": "(n_frequencies: int = 5, frequency_strategy: str = 'harmonic', include_original: bool = False, random_state: int | None = None)", + "pretab.transformers.ISplineTransformer": "(output_dim=UNSET, degree: int = 3, include_bias: bool = False, knot_locations: numpy.ndarray | None = None, target_aware: bool = False, placement_strategy: str = 'quantile', task: Optional[Literal['regression', 'classification']] = None, adaptive: bool = False, min_output_dim=UNSET, max_output_dim=UNSET, random_state: int | None = None, policy: pretab.core.policy.RepresentationPolicy | dict | None = None)", + "pretab.transformers.LanguageEmbeddingTransformer": "(model_name='paraphrase-MiniLM-L3-v2', model=None)", + "pretab.transformers.MSplineTransformer": "(output_dim=UNSET, degree: int = 3, include_bias: bool = False, knot_locations: numpy.ndarray | None = None, target_aware: bool = False, placement_strategy: str = 'quantile', task: Optional[Literal['regression', 'classification']] = None, adaptive: bool = False, min_output_dim=UNSET, max_output_dim=UNSET, random_state: int | None = None, policy: pretab.core.policy.RepresentationPolicy | dict | None = None)", + "pretab.transformers.MissingStateIndicator": "()", + "pretab.transformers.NaturalCubicSplineTransformer": "(output_dim=UNSET, degree=3, include_bias=False, target_aware: bool = False, placement_strategy: str = 'uniform', task=None, adaptive: bool = False, min_output_dim=UNSET, max_output_dim=UNSET, random_state: int | None = None, policy: pretab.core.policy.RepresentationPolicy | dict | None = None)", + "pretab.transformers.NoTransformer": "()", + "pretab.transformers.NumericBinningTransformer": "(output_dim=UNSET, encode='ordinal', placement_strategy='uniform')", + "pretab.transformers.NystroemFeaturesTransformer": "(n_components: int = 100, kernel: str = 'rbf', gamma: float | None = None, degree: float = 3, coef0: float = 1, random_state: int | None = None)", + "pretab.transformers.OneHotFromOrdinalTransformer": "()", + "pretab.transformers.PLETransformer": "(output_dim=UNSET, placement_strategy: str = 'cart', task: Literal['regression', 'classification'] = 'regression', adaptive: bool = False, min_output_dim=UNSET, max_output_dim=UNSET, random_state: int | None = 51)", + "pretab.transformers.PSplineTransformer": "(output_dim=UNSET, degree=3, diff_order=2, include_bias=False, placement_strategy: str = 'uniform', adaptive: bool = False, min_output_dim=UNSET, max_output_dim=UNSET, policy: pretab.core.policy.RepresentationPolicy | dict | None = None)", + "pretab.transformers.PeriodicEncodingTransformer": "(period: int | float, harmonics: int = 1, include_original: bool = False)", + "pretab.transformers.RBFExpansionTransformer": "(output_dim=UNSET, gamma: float = 1.0, target_aware: bool = False, placement_strategy=UNSET, task: str = 'regression', adaptive: bool = False, min_output_dim=UNSET, max_output_dim=UNSET, random_state: int | None = None)", + "pretab.transformers.RandomFourierFeaturesTransformer": "(n_components: int = 100, gamma: float = 1.0, random_state: int | None = None)", + "pretab.transformers.ReLUExpansionTransformer": "(output_dim=UNSET, target_aware: bool = False, placement_strategy=UNSET, task: str = 'regression', adaptive: bool = False, min_output_dim=UNSET, max_output_dim=UNSET, random_state: int | None = None)", + "pretab.transformers.SigmoidExpansionTransformer": "(output_dim=UNSET, scale: float = 1.0, target_aware: bool = False, placement_strategy=UNSET, task: str = 'regression', adaptive: bool = False, min_output_dim=UNSET, max_output_dim=UNSET, random_state: int | None = None)", + "pretab.transformers.TanhExpansionTransformer": "(output_dim=UNSET, scale: float = 1.0, target_aware: bool = False, placement_strategy=UNSET, task: str = 'regression', adaptive: bool = False, min_output_dim=UNSET, max_output_dim=UNSET, random_state: int | None = None)", + "pretab.transformers.TensorProductSplineTransformer": "(output_dim=UNSET, degree=3, diff_order=2, include_bias=False, placement_strategy: str = 'uniform', adaptive: bool = False, min_output_dim=UNSET, max_output_dim=UNSET, policy: pretab.core.policy.RepresentationPolicy | dict | None = None)", + "pretab.transformers.ThinPlateSplineTransformer": "(n_components=10, landmark_strategy='kmeans', rank_strategy='eigen', include_bias=False, random_state=None)", + "pretab.transformers.ToFloatTransformer": "()" + } +}