# GPA1 Multiple Regression
# Module 3 - Holding Other Factors Fixed
# Dataset: GPA1

# GPA1 Multiple Regression
#
# Use GPA1 to estimate college GPA from high-school GPA and ACT. The cells compute results only after the real dataset is installed.

# %% Cell 2
from pathlib import Path

DATASET = "GPA1.DTA"
VARIABLES = ["colGPA", "hsGPA", "ACT"]
DATA_FOLDER = "https://drive.google.com/drive/folders/1_STdcydIcst-opcbwOKRFzUXsgxQgBoS?usp=sharing"

if not Path(DATASET).exists():
    raise FileNotFoundError(
        "Dataset file not installed yet\n"
        f"Dataset: GPA1\n"
        f"Variables needed: {', '.join(VARIABLES)}\n"
        f"Course data folder: {DATA_FOLDER}\n"
        "Admin upload instruction: upload the dataset in Admin -> Datasets and make it available to this notebook."
    )

print("Dataset found:", DATASET)

# %% Cell 3
import pandas as pd
import numpy as np

df = pd.read_stata(DATASET)[VARIABLES].dropna()
print(df.head())
print("Rows used:", len(df))

# %% Cell 4
y = df["colGPA"].to_numpy()
X = np.column_stack([np.ones(len(df)), df[["hsGPA", "ACT"]].to_numpy()])
names = ["intercept", "hsGPA", "ACT"]
beta = np.linalg.lstsq(X, y, rcond=None)[0]
fitted = X @ beta
residuals = y - fitted
r_squared = 1 - np.sum(residuals ** 2) / np.sum((y - y.mean()) ** 2)

for name, value in zip(names, beta):
    print(f"{name}: {value:.4f}")
print("R-squared:", round(r_squared, 4))

# Interpretation
#
# Each slope is read while holding the other included predictor fixed. For example, the high-school GPA coefficient compares students with the same ACT score.
