"""
RAO STATISTICS — MULTIPLE LINEAR REGRESSION & RESIDUAL DIAGNOSTICS
Computational Laboratory: statsmodels & scipy
Website: https://rao-statistics.vercel.app
"""

import numpy as np
import pandas as pd
import scipy.stats as stats
import statsmodels.api as sm
from statsmodels.formula.api import ols
from statsmodels.stats.outliers_influence import variance_inflation_factor

# 1. Load / Prepare Dataset
try:
    df = pd.read_csv("concrete_compressive_strength_experiment.csv")
except Exception:
    np.random.seed(42)
    n = 30
    w_c = np.random.uniform(0.35, 0.60, n)
    fly_ash = np.random.uniform(0, 100, n)
    strength = 75 - 65 * w_c + 0.12 * fly_ash + np.random.normal(0, 2.5, n)
    df = pd.DataFrame({"strength_mpa": strength, "w_c_ratio": w_c, "fly_ash": fly_ash})

# 2. Fit Ordinary Least Squares (OLS) Model
formula = "strength_mpa ~ w_c_ratio + fly_ash"
model = ols(formula, data=df).fit()
print("=" * 70)
print("RAO STATISTICS: OLS REGRESSION SUMMARY")
print("=" * 70)
print(model.summary())

# 3. Multicollinearity Check: Variance Inflation Factor (VIF)
X = df[["w_c_ratio", "fly_ash"]]
X_const = sm.add_constant(X)
vif_series = pd.Series(
    [variance_inflation_factor(X_const.values, i) for i in range(X_const.shape[1])],
    index=X_const.columns,
)
print("\n" + "=" * 70)
print("VARIANCE INFLATION FACTORS (VIF)")
print(vif_series)

# 4. Residual Normality Diagnostics
residuals = model.resid
jb_stat, jb_pvalue, _, _ = sm.stats.stattools.jarque_bera(residuals)
sw_stat, sw_pvalue = stats.shapiro(residuals)
print("\n" + "=" * 70)
print(f"Shapiro-Wilk Test: W = {sw_stat:.4f}, p = {sw_pvalue:.4f}")
print(f"Jarque-Bera Test:  JB = {jb_stat:.4f}, p = {jb_pvalue:.4f}")
