from __future__ import annotations

import math
from pathlib import Path

import matplotlib.pyplot as plt
import torch

OUTPUT_PATH = Path(__file__).resolve().parent / "fit_comparison.png"


# Step 1: 生成模拟数据
def make_dataset(num_samples: int = 300, seed: int = 42) -> tuple[torch.Tensor, torch.Tensor]:
    torch.manual_seed(seed)

    useful_x = torch.rand(num_samples, 5) * 4 - 2

    x1 = useful_x[:, 0:1]
    x2 = useful_x[:, 1:2]
    x3 = useful_x[:, 2:3]
    x4 = useful_x[:, 3:4]
    x5 = useful_x[:, 4:5]

    y = (
        2.0 * x1
        - 1.5 * x2**2
        + 1.2 * x3 * x4
        + 0.8 * torch.sin(math.pi * x5)
        + 0.6 * x1 * x5
        + 0.3
    )

    y = y + 0.2 * torch.randn(num_samples, 1)

    noise_x = torch.randn(num_samples, 20)

    all_x = torch.cat([useful_x, noise_x], dim=1)
    return all_x, y


# Step 2: 划分训练集和测试集
def train_test_split(
    x: torch.Tensor, y: torch.Tensor, train_size: int, seed: int
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
    generator = torch.Generator().manual_seed(seed)

    # randperm(n) 会生成 0 ~ n-1 的一个随机打乱顺序。
    index = torch.randperm(x.shape[0], generator=generator)

    train_index = index[:train_size]
    test_index = index[train_size:]
    return x[train_index], y[train_index], x[test_index], y[test_index]


# Step 3: 构造不同的特征映射

def underfit_features(x: torch.Tensor) -> torch.Tensor:
    """
    欠拟合版本:
    直接把原始 25 维特征送进线性模型。

    由于真实函数里有平方项、sin 项、乘积项，
    但这里的模型只看到“原始线性输入”，表达能力不够，所以容易欠拟合。
    """
    return x


def good_features(x: torch.Tensor) -> torch.Tensor:
    """
    正常拟合版本:
    按照真实函数的结构，手工构造出更合理的特征。

    这一步的思想是:
    模型本身还是线性模型，但如果特征设计得好，
    线性模型依然可以拟合非线性关系。
    """
    x1 = x[:, 0:1]
    x2 = x[:, 1:2]
    x3 = x[:, 2:3]
    x4 = x[:, 3:4]
    x5 = x[:, 4:5]

    # 这里构造出来的 5 个新特征，和上面真实函数中的结构基本对应。
    # 所以这组特征通常会得到最好的测试结果。
    return torch.cat(
        [x1, x2**2, x3 * x4, torch.sin(math.pi * x5), x1 * x5],
        dim=1,
    )


def overfit_features(x: torch.Tensor) -> torch.Tensor:
    """
    过拟合版本:
    人为构造很多复杂特征，让模型容量变大。

    再配合“很少的训练样本”，模型就可能把训练集记得过于死板，
    于是训练集效果极好，但测试集效果反而下降。
    """
    # 先放入原始特征和平方特征。
    parts = [x, x**2]

    # 再构造很多两两交叉项，比如 x1*x2, x1*x3, x2*x3 ...
    # 这些交叉项会显著增加特征数量，让模型更容易过拟合。
    cross_terms = []
    for i in range(15):
        for j in range(i + 1, 15):
            # x[:, i:i+1] 依旧保持二维列向量形状。
            cross_terms.append(x[:, i : i + 1] * x[:, j : j + 1])

    return torch.cat(parts + cross_terms, dim=1)


# Step 4: 数据标准化
def standardize(
    train_x: torch.Tensor, test_x: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor]:
    mean = train_x.mean(dim=0, keepdim=True)
    std = train_x.std(dim=0, keepdim=True, unbiased=False)

    std[std < 1e-6] = 1.0
    return (train_x - mean) / std, (test_x - mean) / std


# Step 5: 实现损失函数和评价函数
def mse_loss(pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
    return ((pred - target) ** 2).mean()


def rmse(pred: torch.Tensor, target: torch.Tensor) -> float:
    return float(torch.sqrt(mse_loss(pred, target)))


def r2_score(pred: torch.Tensor, target: torch.Tensor) -> float:
    ss_res = ((pred - target) ** 2).sum()
    ss_tot = ((target - target.mean()) ** 2).sum()
    return float(1 - ss_res / ss_tot)


# Step 6: 实现线性模型
def train_linear_model(
    train_x: torch.Tensor,
    train_y: torch.Tensor,
    epochs: int,
    lr: float,
) -> tuple[torch.Tensor, torch.Tensor]:
    w = torch.zeros(train_x.shape[1], 1, requires_grad=True)
    b = torch.zeros(1, requires_grad=True)

    for _ in range(epochs):
        # 前向计算: 根据当前参数得到预测值
        pred = train_x @ w + b

        # 计算损失
        loss = mse_loss(pred, train_y)

        # 反向传播: 自动计算 loss 对 w 和 b 的梯度
        loss.backward()

        with torch.no_grad():
            # 梯度下降:
            # 新参数 = 旧参数 - 学习率 * 梯度
            w -= lr * w.grad
            b -= lr * b.grad

            w.grad.zero_()
            b.grad.zero_()

    return w.detach(), b.detach()


def evaluate_case(
    name: str,
    plot_name: str,
    feature_fn,
    x: torch.Tensor,
    y: torch.Tensor,
    train_size: int,
    epochs: int,
    lr: float,
    seed: int,
) -> dict[str, torch.Tensor | float | str]:
    train_x, train_y, test_x, test_y = train_test_split(x, y, train_size=train_size, seed=seed)

    # 用不同的特征设计方式，制造不同的拟合效果。
    train_x = feature_fn(train_x)
    test_x = feature_fn(test_x)

    # 标准化可以让训练更稳定。
    train_x, test_x = standardize(train_x, test_x)

    # 训练模型，得到最终参数 w 和 b。
    w, b = train_linear_model(train_x, train_y, epochs=epochs, lr=lr)

    # 用训练好的参数分别预测训练集和测试集。
    train_pred = train_x @ w + b
    test_pred = test_x @ w + b

    print(f"\n{name}")
    print(f"train RMSE: {rmse(train_pred, train_y):.4f}, train R2: {r2_score(train_pred, train_y):.4f}")
    print(f"test  RMSE: {rmse(test_pred, test_y):.4f}, test  R2: {r2_score(test_pred, test_y):.4f}")

    # 返回绘图需要的数据。
    return {
        "name": name,
        "plot_name": plot_name,
        "train_rmse": rmse(train_pred, train_y),
        "test_rmse": rmse(test_pred, test_y),
        "train_r2": r2_score(train_pred, train_y),
        "test_r2": r2_score(test_pred, test_y),
    }


# Step 7: 绘图
def draw_result_figure(results: list[dict[str, torch.Tensor | float | str]]) -> None:
    # - 欠拟合: train 和 test 都差
    # - 过拟合: train 很好，但 test 明显变差
    labels = [str(result["plot_name"]) for result in results]
    train_rmse = [float(result["train_rmse"]) for result in results]
    test_rmse = [float(result["test_rmse"]) for result in results]
    train_r2 = [float(result["train_r2"]) for result in results]
    test_r2 = [float(result["test_r2"]) for result in results]

    x = list(range(len(results)))
    width = 0.36

    fig, axes = plt.subplots(1, 2, figsize=(11, 4.6))
    ax_rmse, ax_r2 = axes

    rmse_train_bars = ax_rmse.bar(
        [value - width / 2 for value in x],
        train_rmse,
        width=width,
        label="Train RMSE",
        color="#4C72B0",
    )
    rmse_test_bars = ax_rmse.bar(
        [value + width / 2 for value in x],
        test_rmse,
        width=width,
        label="Test RMSE",
        color="#DD8452",
    )
    ax_rmse.set_title("RMSE Comparison")
    ax_rmse.set_ylabel("RMSE")
    ax_rmse.set_xticks(x)
    ax_rmse.set_xticklabels(labels)
    ax_rmse.grid(axis="y", linestyle="--", alpha=0.4)
    ax_rmse.legend()

    r2_train_bars = ax_r2.bar(
        [value - width / 2 for value in x],
        train_r2,
        width=width,
        label="Train R2",
        color="#55A868",
    )
    r2_test_bars = ax_r2.bar(
        [value + width / 2 for value in x],
        test_r2,
        width=width,
        label="Test R2",
        color="#C44E52",
    )
    ax_r2.set_title("R2 Comparison")
    ax_r2.set_ylabel("R2")
    ax_r2.set_ylim(0.0, 1.08)
    ax_r2.set_xticks(x)
    ax_r2.set_xticklabels(labels)
    ax_r2.grid(axis="y", linestyle="--", alpha=0.4)
    ax_r2.legend()

    for bars, axis, fmt in (
        (rmse_train_bars, ax_rmse, "{:.2f}"),
        (rmse_test_bars, ax_rmse, "{:.2f}"),
        (r2_train_bars, ax_r2, "{:.3f}"),
        (r2_test_bars, ax_r2, "{:.3f}"),
    ):
        for bar in bars:
            height = bar.get_height()
            axis.text(
                bar.get_x() + bar.get_width() / 2,
                height,
                fmt.format(height),
                ha="center",
                va="bottom",
                fontsize=8,
            )

    fig.tight_layout(rect=[0, 0.05, 1, 0.95])
    fig.savefig(OUTPUT_PATH, dpi=200, bbox_inches="tight")
    plt.close(fig)


def main() -> None:
    # 先生成完整数据集。
    x, y = make_dataset()

    # results 用来保存三种实验结果，后面统一画图。
    results = []

    print("真实函数:")
    print("y = 2.0*x1 - 1.5*x2^2 + 1.2*x3*x4 + 0.8*sin(pi*x5) + 0.6*x1*x5 + 0.3")
    print("数据总维度: 25 维 = 5 个有效特征 + 20 个噪声特征")

    # 1. 欠拟合:
    # 训练样本并不少，但模型表达能力不够。
    results.append(
        evaluate_case(
            name="1. 欠拟合",
            plot_name="Underfit",
            feature_fn=underfit_features,
            x=x,
            y=y,
            train_size=200,
            epochs=400,
            lr=0.05,
            seed=1,
        )
    )

    # 2. 正常拟合:
    # 特征设计合理，模型能学到真实规律。
    results.append(
        evaluate_case(
            name="2. 正常拟合",
            plot_name="Good Fit",
            feature_fn=good_features,
            x=x,
            y=y,
            train_size=200,
            epochs=400,
            lr=0.05,
            seed=1,
        )
    )

    # 3. 过拟合:
    # 训练样本太少，但特征非常多、非常复杂，所以模型容易“死记硬背”。
    results.append(
        evaluate_case(
            name="3. 过拟合",
            plot_name="Overfit",
            feature_fn=overfit_features,
            x=x,
            y=y,
            train_size=30,
            epochs=800,
            lr=0.03,
            seed=2,
        )
    )

    draw_result_figure(results)
    print(f"\n图片已保存到: {OUTPUT_PATH}")


if __name__ == "__main__":
    main()
