"""
=====================================================
Rare and unseen parent values
=====================================================

An AnDE component estimates one distribution per combination of class and
super-parent value. When a combination is rare, or never appears in the
training data, that estimate is unreliable. Two parameters control what the
ensemble does about it.

A continuous attribute $x$ separates the classes well. A categorical
attribute, the operating mode of a machine, takes the values A and B
almost always. Mode C appears only four times in training, always with
class 0. The figure shows what the model predicts for an instance in
mode C as $x$ moves from the region of class 0 to the region of class 1,
next to the same curve for the frequent mode A.

The two parameters are the following:

-   ``unseen_state``: what to use for a combination never seen in training,
    here (class 1, mode C). ``"laplace"`` uses the smoothed estimate of an
    empty cell, which for a continuous attribute is the pooled Gaussian of
    the whole dataset. ``"backoff"`` reuses the estimate of the class,
    $P(x \\mid y)$, as Naive Bayes would.
-   ``min_parent_count``: the minimum number of training instances that a
    super-parent value needs for its component to take part in a prediction.
    Raising it removes the component of mode C altogether, the rule of the
    original AODE.
"""

# Author: The scikit-bayes Developers
# SPDX-License-Identifier: BSD-3-Clause

import matplotlib.pyplot as plt
import numpy as np

from skbn import AnDE

rng = np.random.RandomState(42)
n_samples = 600

y = rng.randint(0, 2, size=n_samples)
x = rng.normal(loc=np.where(y == 1, 1.5, -1.5), scale=1.0)
mode = rng.randint(0, 2, size=n_samples)  # Modes A (0) and B (1)

# Mode C (2): four instances, all of class 0
x_rare = rng.normal(loc=-1.5, scale=1.0, size=4)
X = np.column_stack(
    [np.concatenate([x, x_rare]), np.concatenate([mode, np.full(4, 2)])]
)
y = np.concatenate([y, np.zeros(4, dtype=int)])

# Model and line style; all are AnDE and share its colour
base = dict(n_dependence=1, categorical_features=[1])
configs = {
    "Laplace (default)": (AnDE(unseen_state="laplace", **base), "-"),
    "Back-off to the class": (AnDE(unseen_state="backoff", **base), "--"),
    "Minimum parent count of 30": (AnDE(min_parent_count=30, **base), "-."),
}
color = "#0072B2"
for model, _ in configs.values():
    model.fit(X, y)

# Queries: x along its range, with the mode fixed
x_grid = np.linspace(-5, 5, 300)
queries = {
    "Mode A, frequent": np.column_stack([x_grid, np.zeros_like(x_grid)]),
    "Mode C, four training instances of class 0": np.column_stack(
        [x_grid, np.full_like(x_grid, 2)]
    ),
}

fig, axes = plt.subplots(1, 2, figsize=(11, 4.4), sharey=True)

for ax, (title, Q) in zip(axes, queries.items()):
    for name, (model, style) in configs.items():
        ax.plot(x_grid, model.predict_proba(Q)[:, 1], color=color, ls=style, label=name)
    ax.axhline(0.5, color="#999999", ls=":", lw=1)
    ax.set_title(title)
    ax.set_xlabel("Continuous attribute $x$")

# Training instances of mode C
axes[1].scatter(
    x_rare,
    np.full(4, 0.02),
    c="#1A1A1A",
    marker="o",
    s=40,
    edgecolors="w",
    zorder=5,
    label="Training instances in mode C",
)

axes[0].set_ylabel("Probability of class 1")
fig.legend(*axes[1].get_legend_handles_labels(), loc="outside lower center", ncol=4)

fig.suptitle("Predictions for a frequent and for a rare parent value")
plt.show()
