#!/usr/bin/env python3
"""
Render diagnostic plots for the Weibull distribution regression example (variant 0).

Usage:
    Place dataset_weibull_v0.csv in the same directory, then run:
        python render_weibull_plots.py

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

from __future__ import annotations

import math
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_weibull_v0.csv")

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

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

result = pyinla(model=model, family="weibull", 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()
lambda_hat = np.exp(eta_hat)

# For variant 0, E[y] = lambda^(-1/alpha) * Gamma(1 + 1/alpha)
alpha_hat = float(result.summary_hyperpar.iloc[0]["mean"])
mu_hat = lambda_hat ** (-1 / alpha_hat) * math.gamma(1 + 1 / alpha_hat)
residuals = df["y"].to_numpy() - mu_hat

# ── Plot 1: Observed vs fitted mean ─────────────────────────────────────────

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("Fitted mean (μ)")
ax.set_ylabel("Observed (y)")
ax.set_title("Weibull regression (v0): observed vs fitted mean")
ax.legend(loc="best")
ax.grid(alpha=0.25)
fig.tight_layout()
fig.savefig("weibull-regression-fit.png", dpi=160)
plt.close(fig)

# ── Plot 2: Residuals vs fitted mean ────────────────────────────────────────

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("Fitted mean (μ)")
ax.set_ylabel("Residual (y − μ)")
ax.set_title("Weibull regression (v0): residuals vs fitted mean")
ax.legend(loc="upper right")
ax.grid(alpha=0.25)
fig.tight_layout()
fig.savefig("weibull-regression-residuals.png", dpi=160)
plt.close(fig)

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