> ## Documentation Index
> Fetch the complete documentation index at: https://fpde-80-mintlify-f19c7fde.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# API reference

> Reference for FPDE engine, prototype helpers, explanation functions, metrics, plotting helpers, and result objects exported from fpde.

Import the public package as `fpde`.

```python theme={null}
from fpde import FPDEEngine, class_mean_prototypes, diff_fpde
```

This page documents the public API exported by `fpde` and `fpde.core`.

## `FPDEEngine`

Use `FPDEEngine` for repeated explanations, batch explanations, Hyb-FPDE, grid search, and validation-based lambda selection.

### `FPDEEngine.fit`

```python theme={null}
FPDEEngine.fit(X_train, y_train, model=None, baseline=None)
```

Fits reusable FPDE state from training data.

| Parameter  | Description                                                                         |
| ---------- | ----------------------------------------------------------------------------------- |
| `X_train`  | Training feature matrix with shape `(n_samples, n_features)`.                       |
| `y_train`  | Training labels with one label per row in `X_train`.                                |
| `model`    | Optional classifier. Required later when an operation needs `predict_proba`.        |
| `baseline` | Optional replacement vector for perturbation curves. Defaults to the training mean. |

Returns an `FPDEEngine`.

### `engine.explain_one`

```python theme={null}
engine.explain_one(
    x,
    *,
    lambda_hyb,
    normalize="l1",
    anchor_strategy="mean",
    eps=1e-12,
    model=None,
)
```

Explains one sample with fixed-lambda Hyb-FPDE.
Returns `(attributions, details)`.

The `details` dictionary includes `target_label`, `rival_label`, `target_probability`, `lambda_hyb`, `evidence`, `exactness_residual`, `positive_score`, and `negative_score`.

### `engine.explain_batch`

```python theme={null}
engine.explain_batch(
    X,
    *,
    lambda_hyb,
    normalize="l1",
    anchor_strategy="mean",
    include_details=True,
    eps=1e-12,
    model=None,
)
```

Explains many samples with fixed-lambda Hyb-FPDE.
Returns `(attribution_matrix, details)`.
If `include_details=False`, `details` is an empty list.

### `engine.explain_matrix`

```python theme={null}
engine.explain_matrix(
    X,
    *,
    lambda_hyb,
    normalize="l1",
    anchor_strategy="mean",
    eps=1e-12,
    model=None,
)
```

Returns only the attribution matrix for a batch.

### `engine.grid_search`

```python theme={null}
engine.grid_search(
    X_eval,
    *,
    predictor=None,
    objective="blackbox_agreement",
    fpde_mode_grid=("diff", "cos", "hyb_grid"),
    normalize_grid=("l1",),
    lambda_hyb_grid=...,
    anchor_strategy_grid=("mean",),
    include_explicit_diff_cos=True,
    max_eval_samples=None,
    eps=1e-12,
    verbose=False,
)
```

Searches Diff-FPDE, Cos-FPDE, and Hyb-FPDE candidate settings.
Returns a `HybFPDEGridSearchResult`.

### `engine.select_lambda`

```python theme={null}
engine.select_lambda(
    X_val,
    *,
    lambda_hyb_grid=...,
    fractions=(0.0, 0.05, 0.1, 0.2, 0.3, 0.5, 0.7, 1.0),
    normalize="l1",
    anchor_strategy="mean",
    eps=1e-12,
    max_working_bytes=268435456,
    model=None,
)
```

Selects `lambda_hyb` by held-out deletion and insertion validation.
Returns a `HybFPDEValidationSelectionResult`.

## Prototype helpers

### `class_mean_prototypes`

```python theme={null}
class_mean_prototypes(X, y)
```

Builds one mean prototype per class.
Returns `(prototypes, labels)`.

### `select_prototype_pair`

```python theme={null}
select_prototype_pair(
    x,
    prototypes,
    prototype_labels,
    *,
    positive_label,
    negative_label=None,
    mode="diff",
    anchor=None,
    eps=1e-12,
)
```

Selects the positive and negative prototype indices for a local contrast.
Returns `(positive_index, negative_index)`.

### `prepare_fpde_context`

```python theme={null}
prepare_fpde_context(X_train, y_train, *, baseline=None)
```

Precomputes reusable prototypes, anchors, baseline, and feature metadata.
Returns an `FPDEContext`.

## Explanation functions

Use these functions when you want direct control over prototypes and labels.

### `diff_fpde`

```python theme={null}
diff_fpde(
    x,
    p_pos,
    p_neg,
    *,
    positive_label="positive",
    negative_label="negative",
    positive_prototype_index=-1,
    negative_prototype_index=-1,
)
```

Computes a Diff-FPDE explanation for one target/rival prototype pair.

### `cos_fpde`

```python theme={null}
cos_fpde(
    x,
    p_pos,
    p_neg,
    *,
    anchor=None,
    eps=1e-12,
    positive_label="positive",
    negative_label="negative",
    positive_prototype_index=-1,
    negative_prototype_index=-1,
)
```

Computes a Cos-FPDE explanation for one target/rival prototype pair.

### `explain_with_selected_prototypes`

```python theme={null}
explain_with_selected_prototypes(
    x,
    prototypes,
    prototype_labels,
    *,
    positive_label,
    negative_label=None,
    mode="diff",
    anchor=None,
    eps=1e-12,
)
```

Selects prototypes and computes a public Diff-FPDE or Cos-FPDE explanation.
Use `FPDEEngine` for Hyb-FPDE.

## Metrics and probability helpers

### `regularized_cosine`

```python theme={null}
regularized_cosine(u, v, eps=1e-12)
```

Returns cosine similarity with epsilon-regularized norms.

### `top_two_labels`

```python theme={null}
top_two_labels(model, x)
```

Returns `(target_label, rival_label, probability_vector)` for one sample.
`model` must implement `predict_proba` and expose `classes_`.

### `predict_proba_for_label`

```python theme={null}
predict_proba_for_label(model, X, label)
```

Returns the `predict_proba(X)` column for `label`.

### `perturbation_curves`

```python theme={null}
perturbation_curves(
    model,
    x,
    attributions,
    target_label,
    baseline,
    fractions=(0.0, 0.05, 0.1, 0.2, 0.3, 0.5, 0.7, 1.0),
)
```

Computes deletion and insertion curves for one attribution vector.
Features are ranked by signed positive attribution in descending order.

## Plotting helpers

The plotting helpers are exported from `fpde` and visualize FPDE attributions, prototype similarities, and perturbation curves with matplotlib.
They require the optional `plot` extra:

```bash theme={null}
python -m pip install "fpde[plot]"
```

Each function returns the matplotlib `Axes` it draws on and does not call `plt.show()` or save files.
Pass an existing `ax=` to draw into a subplot, or omit it to create a new figure.

### `plot_attributions`

```python theme={null}
plot_attributions(
    attributions,
    *,
    feature_names=None,
    top_k=20,
    normalize=False,
    sort=True,
    ax=None,
    title=None,
)
```

Plots a signed horizontal bar chart for a 1D attribution vector or an `FPDEExplanation`.
Positive values support the target class; negative values support the rival class.
Use `top_k` to limit the number of features and `normalize=True` to L1-normalize the displayed values.

### `plot_attribution_waterfall`

```python theme={null}
plot_attribution_waterfall(
    attributions,
    *,
    feature_names=None,
    top_k=10,
    base_value=0.0,
    ax=None,
    title=None,
)
```

Plots a cumulative local explanation from `base_value` to `base_value + sum(attributions)`.
Hidden features (outside `top_k`) are grouped into one `other features` bar.

### `plot_attribution_summary`

```python theme={null}
plot_attribution_summary(
    attributions,
    *,
    feature_values=None,
    feature_names=None,
    top_k=20,
    ax=None,
    title=None,
    cmap="coolwarm",
)
```

Plots a batch attribution matrix as a per-feature distribution, ordered by mean absolute attribution.
Pass `feature_values` with the same shape as `attributions` to color points by the original feature value.

### `plot_attribution_image`

```python theme={null}
plot_attribution_image(
    attributions,
    shape=None,
    *,
    ax=None,
    title=None,
    cmap="coolwarm",
    colorbar=True,
    symmetric=True,
)
```

Plots an attribution vector as a 2D heatmap.
Pass `shape=(height, width)` for flat image vectors; `shape` is optional for already-2D arrays.

### `plot_perturbation_curves`

```python theme={null}
plot_perturbation_curves(curves, *, ax=None, title=None)
```

Plots the deletion and insertion probability curves returned by `perturbation_curves`.
`curves` must contain `fractions`, `deletion_prob`, and `insertion_prob`.

### `plot_local_contributions`

```python theme={null}
plot_local_contributions(
    feature_names,
    contributions,
    values=None,
    *,
    top_k=10,
    sort_by="abs",
    ax=None,
    title=None,
    xlabel="Contribution",
    show_values=True,
    zero_line=True,
)
```

Plots a signed local contribution bar chart from feature names and one attribution vector.
Pass `values` to label each bar with the corresponding feature value.

### `prepare_local_contribution_data`

```python theme={null}
prepare_local_contribution_data(
    feature_names,
    contributions,
    values=None,
    *,
    top_k=10,
    sort_by="abs",
)
```

Returns a list of row dictionaries (`feature`, `display_name`, `contribution`, `abs_contribution`, `direction`, `direction_label`) suitable for rendering FPDE local attributions in a custom UI.

### `plot_prototype_similarity_distribution`

```python theme={null}
plot_prototype_similarity_distribution(
    X,
    target_prototype,
    *,
    rival_prototype=None,
    x=None,
    metric="cosine",
    bins=30,
    ax=None,
    title=None,
)
```

Plots the distribution of similarities from rows in `X` to the target prototype.
Pass `rival_prototype` to overlay the rival distribution and `x` to mark the explained sample.
`metric` is `"cosine"` or `"negative_euclidean"`.

## `fpde.plots` namespace

`fpde.plots` provides a compact matplotlib API for FPDE contribution arrays inspired by SHAP's plotting layout.
Pass `show=False` to receive an `Axes` without displaying, then save with `ax.figure.savefig(...)`.

```python theme={null}
from fpde.plots import FPDEPlotExplanation, bar, beeswarm, scatter, waterfall
```

| Function              | Description                                                                                                                                      |
| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| `FPDEPlotExplanation` | Lightweight container with `values`, `base_values`, `data`, `feature_names`, `output_names`, and `predictions`.                                  |
| `bar`                 | Plots local or global contribution importance. A 1D vector is treated as one local explanation; a 2D matrix is summarized by feature importance. |
| `beeswarm`            | Plots per-sample contributions grouped by feature. Points are colored by feature value when `data` is provided.                                  |
| `scatter`             | Plots one feature's original value against its FPDE contribution. `feature` may be an integer index or a name from `feature_names`.              |
| `waterfall`           | Plots one contribution vector from `base_value` to `prediction`. Hidden features are grouped into `other features`.                              |

## Result objects

| Object                             | Contains                                                                                                                                     |
| ---------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
| `FPDEExplanation`                  | `mode`, `evidence`, `attributions`, `positive_score`, `negative_score`, labels, prototype indices, `exactness_residual`, and method details. |
| `FPDEContext`                      | Prototypes, prototype labels, mean anchor, zero anchor, baseline, and feature count.                                                         |
| `HybFPDEGridSearchResult`          | `best_config`, `best_score`, `rows`, `objective`, `n_candidates`, and `n_eval_samples`.                                                      |
| `HybFPDEValidationSelectionResult` | `best_lambda`, `best_config`, `rows`, and `n_eval_samples`.                                                                                  |

## Common errors

| Error                                | Cause                                                               | Fix                                                                                  |
| ------------------------------------ | ------------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
| `model must implement predict_proba` | A model-dependent operation was called without probability support. | Pass a fitted classifier with `predict_proba`.                                       |
| `model must expose classes_`         | The model does not expose class labels.                             | Use a scikit-learn-style classifier or add compatible `classes_` metadata.           |
| `feature dimension mismatch`         | Input vectors do not match the fitted training feature count.       | Apply the same preprocessing pipeline to training, validation, and explanation data. |
| `lambda_hyb must be in [0, 1]`       | The Hyb-FPDE mixture weight is outside the valid range.             | Pass a finite value from 0.0 to 1.0.                                                 |
| `eps must be positive`               | Cosine regularization was zero or negative.                         | Use a positive `eps`, such as `1e-12`.                                               |
