#!/usr/bin/env python3
"""
Render diagnostic plots for the Negative Binomial regression example.

Usage:
    Place dataset_nbinomial_regression.csv in the same directory, then run:
        python render_nbinomial_plots.py

Requires: pyinla, pandas, numpy, matplotlib
"""

from __future__ import annotations

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pyinla import pyinla

# ── Fit the model ────────────────────────────────────────────────────────────

df = pd.read_csv("dataset_nbinomial_regression.csv")

model = {
    "response": "y",
    "fixed": ["1", "x"],
}

control = {
    "family": {"variant": 0},
}

result = pyinla(model=model, family="nbinomial", data=df, control=control)

# ── Extract quantities ───────────────────────────────────────────────────────

intercept = float(result.summary_fixed.loc["(Intercept)", "mean"])
slope = float(result.summary_fixed.loc["x", "mean"])

eta_hat = intercept + slope * df["x"].to_numpy()
mu_hat = np.exp(eta_hat)
residuals = df["y"].to_numpy() - mu_hat

# ── Plot 1: Observed vs expected counts ──────────────────────────────────────

fig, ax = plt.subplots(figsize=(6.2, 4.1))
ax.scatter(mu_hat, df["y"], color="#38bdf8", s=46, edgecolor="white", linewidth=0.4, alpha=0.7, label="observations")
max_val = max(mu_hat.max(), df["y"].max())
ax.plot([0, max_val], [0, max_val], color="#f97316", linewidth=2.0, linestyle="--", label="y = x (perfect fit)")
ax.set_xlabel("Expected count (μ)")
ax.set_ylabel("Observed count (y)")
ax.set_title("Negative Binomial regression: observed vs expected counts")
ax.legend(loc="best")
ax.grid(alpha=0.25)
fig.tight_layout()
fig.savefig("negative-binomial-regression-fit.png", dpi=160)
plt.close(fig)

# ── Plot 2: Residuals vs expected counts ─────────────────────────────────────

fig, ax = plt.subplots(figsize=(6.2, 4.1))
ax.scatter(mu_hat, residuals, color="#a78bfa", s=42, edgecolor="white", linewidth=0.35)
ax.axhline(0.0, color="#f97316", linewidth=1.6, linestyle="--", label="zero residual")
ax.set_xlabel("Expected count (μ)")
ax.set_ylabel("Residual (y − μ)")
ax.set_title("Negative Binomial regression: residuals vs expected counts")
ax.legend(loc="upper right")
ax.grid(alpha=0.25)
fig.tight_layout()
fig.savefig("negative-binomial-regression-residuals.png", dpi=160)
plt.close(fig)

print("Plots saved: negative-binomial-regression-fit.png, negative-binomial-regression-residuals.png")
print(f"Recovered: intercept = {intercept:.4f}, slope = {slope:.4f}")
print(result.summary_fixed)
