Skip to content

Post-hoc sensitivity

sensitivity_from_table() fits a surrogate over completed experiments and estimates Morris or Sobol sensitivity cheaply through that model. Inspect its cross-validated accuracy before interpreting importance: this measures the surrogate's estimated response, not a new set of simulator evaluations. Use sobol_indices() when you need first-order and total-order indices together; ST - S1 reveals effects attributable to interactions.

See the complete conditional sensitivity and discrete contrasts workflow for explicit fixed-stratum selection, refusal of varying omitted inputs and explicit configuration/dataset grouped validation and its one-partition boundary.

trade_study.TableSensitivity(importance, surrogate_cv_r2, screened_factors=(), fixed_factors=dict(), conditioning=dict(), omitted_config_keys=(), metadata_keys=(), source_rows=(), sampling_factors=(), surrogate_cv_rmse=dict(), surrogate_row_cv_r2=dict(), surrogate_row_cv_rmse=dict(), cv_group_by=None, cv_group_source='rows', cv_group_labels=None, validation_scheme='unreported', validation_groups=list(), cv_folds_requested=5, support_ranges=dict()) dataclass

Post-hoc sensitivity indices computed via a table-fit surrogate.

Attributes:

Name Type Description
importance dict[str, NDArray[floating[Any]]]

Mapping from observable name to an array of factor importances (mu_star for Morris, S1 for Sobol), one value per varying continuous factor, in screened_factors order.

surrogate_cv_r2 dict[str, float]

Per-observable cross-validated R^2 of the surrogate the indices were computed from. A low value means the sensitivity indices reflect a poorly learned response surface, not necessarily the true system -- treat such observables' indices as unreliable. Grouped results stay unavailable/NaN when fewer than two groups survive.

screened_factors tuple[str, ...]

Ordered varying continuous input names.

fixed_factors dict[str, Any]

Observed constants bound during prediction, including continuous factors made constant by conditioning.

conditioning dict[str, Any]

Explicit requested discrete/categorical stratum.

omitted_config_keys tuple[str, ...]

Non-factor config fields excluded from the surface.

metadata_keys tuple[str, ...]

Explicitly declared non-factor bookkeeping fields.

source_rows tuple[int, ...]

Selected original row indices, aligned with validation_groups.

sampling_factors tuple[Factor, ...]

Factor definitions carrying screened bounds/log scales. Sampling is independent uniform in each declared linear/log coordinate.

surrogate_cv_rmse dict[str, float]

Actual held-out RMSE, in observable units.

surrogate_row_cv_r2 dict[str, float]

Shuffled row R² retained alongside grouped metrics.

surrogate_row_cv_rmse dict[str, float]

Shuffled row RMSE.

cv_group_by tuple[str, ...] | None

Factor grouping names, or None for rows/external groups.

cv_group_source str

"rows", "configuration" or caller-declared "external".

cv_group_labels tuple[Hashable, ...] | None

Validated external labels aligned with selected rows.

validation_scheme str

Shuffled rows, held-out designs or named factor groups. External groups are one explicit partition, not automatic crossed CV.

validation_groups list[int]

Group ids aligned with source_rows, empty for row CV.

cv_folds_requested int

Requested maximum; effective folds depend on finite rows/groups for each observable and can be fewer or unavailable.

support_ranges dict[str, dict[str, tuple[float, float]]]

Observed marginal continuous ranges per fitted observable. This does not establish support for joint sampled configurations.

trade_study.sensitivity_from_table(results, factors, *, method='sobol', surrogate_method='rf', n_trajectories=100, seed=42, n_estimators=200, warn_below_r2=0.0, condition_on=None, metadata_keys=(), cv_group_by=None, cv_groups=None, cv_folds=5)

Compute post-hoc Sobol/Morris sensitivity from a collected table.

Only varying continuous factors are screened. Discrete/categorical factors must be observed constants, optionally after explicit conditioning. All constants are bound in surrogate predictions. Varying unmodeled config keys are refused unless explicitly declared bookkeeping through metadata_keys. This is conditional surface sensitivity under independent uniform sampling in declared linear/log coordinates, not sensitivity to discrete factors.

Parameters:

Name Type Description Default
results ResultsTable

A :class:~trade_study.protocols.ResultsTable from a previous run_grid/Study/etc. call.

required
factors list[Factor]

All model factor definitions. At least one continuous factor must vary in the selected rows; observed constants are held fixed.

required
method str

"sobol" or "morris", forwarded to screen().

'sobol'
surrogate_method str

"rf" or "gp", forwarded to :func:trade_study.fit_surrogate.

'rf'
n_trajectories int

Forwarded to screen() (Morris trajectory count, or Sobol base sample size).

100
seed int

Random seed for both the surrogate fit and screen().

42
n_estimators int

Forwarded to :func:trade_study.fit_surrogate (rf only).

200
warn_below_r2 float | None

Forwarded to :func:trade_study.fit_surrogate; warns if any observable's cross-validated R^2 is too low to trust its sensitivity indices. Pass None to disable.

0.0
condition_on Mapping[str, Any] | None

Discrete/categorical values selecting an observed stratum. Remaining varying noncontinuous factors are refused.

None
metadata_keys Sequence[str]

Explicit non-factor config bookkeeping fields; excluded from prediction and reported in omitted_config_keys.

()
cv_group_by str | Sequence[str] | None

Forwarded configuration-factor grouping, including "design".

None
cv_groups Sequence[object] | NDArray[Any] | None

Explicit dataset/replicate group labels aligned with every original results row, including rows excluded by conditioning. Mutually exclusive with cv_group_by. Values are validated before selection, then filtered by source_rows. No grouping is inferred.

None
cv_folds int

Requested CV maximum, forwarded to fit_surrogate. Must be >=2.

5

Returns:

Name Type Description
A TableSensitivity

class:TableSensitivity with importance indices and the

TableSensitivity

surrogate validation, input scope, selected rows and marginal support.

Raises:

Type Description
ValueError

Invalid scope/layout/conditioning, unmodeled variation or no varying continuous factor; also propagated from fit_surrogate.

Source code in src/trade_study/sensitivity.py
def sensitivity_from_table(  # ruff: ignore[too-many-arguments]
    results: ResultsTable,
    factors: list[Factor],
    *,
    method: str = "sobol",
    surrogate_method: str = "rf",
    n_trajectories: int = 100,
    seed: int = 42,
    n_estimators: int = 200,
    warn_below_r2: float | None = 0.0,
    condition_on: Mapping[str, Any] | None = None,
    metadata_keys: Sequence[str] = (),
    cv_group_by: str | Sequence[str] | None = None,
    cv_groups: Sequence[object] | NDArray[Any] | None = None,
    cv_folds: int = 5,
) -> TableSensitivity:
    """Compute post-hoc Sobol/Morris sensitivity from a collected table.

    Only varying continuous factors are screened. Discrete/categorical factors
    must be observed constants, optionally after explicit conditioning. All
    constants are bound in surrogate predictions. Varying unmodeled config keys
    are refused unless explicitly declared bookkeeping through metadata_keys.
    This is conditional surface sensitivity under independent uniform sampling
    in declared linear/log coordinates, not sensitivity to discrete factors.

    Args:
        results: A :class:`~trade_study.protocols.ResultsTable` from a
            previous ``run_grid``/``Study``/etc. call.
        factors: All model factor definitions. At least one continuous factor
            must vary in the selected rows; observed constants are held fixed.
        method: ``"sobol"`` or ``"morris"``, forwarded to ``screen()``.
        surrogate_method: ``"rf"`` or ``"gp"``, forwarded to
            :func:`trade_study.fit_surrogate`.
        n_trajectories: Forwarded to ``screen()`` (Morris trajectory
            count, or Sobol base sample size).
        seed: Random seed for both the surrogate fit and ``screen()``.
        n_estimators: Forwarded to :func:`trade_study.fit_surrogate`
            (``rf`` only).
        warn_below_r2: Forwarded to :func:`trade_study.fit_surrogate`;
            warns if any observable's cross-validated R^2 is too low to
            trust its sensitivity indices. Pass ``None`` to disable.
        condition_on: Discrete/categorical values selecting an observed stratum.
            Remaining varying noncontinuous factors are refused.
        metadata_keys: Explicit non-factor config bookkeeping fields; excluded
            from prediction and reported in omitted_config_keys.
        cv_group_by: Forwarded configuration-factor grouping, including "design".
        cv_groups: Explicit dataset/replicate group labels aligned with every
            original results row, including rows excluded by conditioning.
            Mutually exclusive with cv_group_by. Values are validated before
            selection, then filtered by source_rows. No grouping is inferred.
        cv_folds: Requested CV maximum, forwarded to fit_surrogate. Must be >=2.

    Returns:
        A :class:`TableSensitivity` with importance indices and the
        surrogate validation, input scope, selected rows and marginal support.

    Raises:
        ValueError: Invalid scope/layout/conditioning, unmodeled variation or
            no varying continuous factor; also propagated from fit_surrogate.
    """
    if isinstance(cv_folds, bool) or not isinstance(cv_folds, int) or cv_folds < 2:
        msg = "cv_folds must be an integer >=2"
        raise ValueError(msg)
    if not any(f.factor_type == FactorType.CONTINUOUS for f in factors):
        msg = (
            "Screening requires at least one continuous factor; "
            "use direct factorial or paired contrasts for discrete effects"
        )
        raise ValueError(msg)
    if cv_groups is not None and cv_group_by is not None:
        msg = "cv_groups and cv_group_by are mutually exclusive"
        raise ValueError(msg)
    external = (
        None
        if cv_groups is None
        else _external_group_labels(cv_groups, len(results.configs))
    )
    conditions = dict(condition_on or {})
    scope = _condition_table(results, factors, conditions, metadata_keys)
    surrogate = fit_surrogate(
        scope.table,
        factors,
        method=surrogate_method,
        seed=seed,
        n_estimators=n_estimators,
        warn_below_r2=warn_below_r2,
        cv_group_by=cv_group_by,
        cv_folds=cv_folds,
        cv_groups=None if external is None else tuple(external[i] for i in scope.rows),
    )

    for name, ranges in surrogate.support_ranges.items():
        outside = [
            factor.name
            for factor in scope.continuous
            if factor.bounds is not None
            and (
                factor.bounds[0] < ranges[factor.name][0]
                or factor.bounds[1] > ranges[factor.name][1]
            )
        ]
        if outside:
            warnings.warn(
                f"Sensitivity sampling for {name!r} extends outside observed "
                f"marginal support for {outside}; "
                "inspect TableSensitivity.support_ranges",
                UserWarning,
                stacklevel=2,
            )

    def run_fn(cfg: dict[str, Any]) -> dict[str, float]:
        return surrogate.predict({**cfg, **scope.fixed}, warn_support=False)

    importance = screen(
        run_fn,
        scope.continuous,
        method=method,
        n_trajectories=n_trajectories,
        seed=seed,
    )
    return TableSensitivity(
        importance=importance,
        surrogate_cv_r2=surrogate.cv_r2,
        screened_factors=tuple(factor.name for factor in scope.continuous),
        fixed_factors=dict(scope.fixed),
        conditioning=conditions,
        omitted_config_keys=scope.omitted,
        metadata_keys=tuple(metadata_keys),
        source_rows=scope.rows,
        sampling_factors=tuple(scope.continuous),
        surrogate_cv_rmse=surrogate.cv_rmse,
        surrogate_row_cv_r2=surrogate.row_cv_r2,
        surrogate_row_cv_rmse=surrogate.row_cv_rmse,
        cv_group_by=surrogate.cv_group_by,
        cv_group_source=surrogate.cv_group_source,
        cv_group_labels=surrogate.cv_group_labels,
        validation_scheme="shuffled-rows"
        if surrogate.cv_group_source == "rows"
        else "held-out-external-groups"
        if surrogate.cv_group_source == "external"
        else "held-out-designs"
        if cv_group_by == "design"
        else "held-out-factor-groups",
        validation_groups=surrogate.validation_groups,
        cv_folds_requested=cv_folds,
        support_ranges=surrogate.support_ranges,
    )