"""第6.2讲第36—38页：用CVXPY投影，比较三个固定步长。"""
from pathlib import Path
import json
import os
import sys
import time

# 使用本机已准备好的课程运行环境。
local_packages = Path(r"D:\PGS1\.codex_work\7113_course_teaching\python_libs")
if local_packages.is_dir():
    sys.path.insert(0, str(local_packages))
os.environ.setdefault("MPLBACKEND", "Agg")

import numpy as np
import cvxpy as cp
import matplotlib.pyplot as plt

ROOT = Path(__file__).resolve().parent.parent
DEMAND = 10.0
A = np.array([4.0, 25.0, 50.0])


def objective(x):
    """交通势函数；梯度等于当前路线耗时。"""
    return np.sum(A * x + x**3 / 3)


def costs(x):
    return A + x**2


def frank_wolfe_gap(x):
    """用同一指标比较不同算法：越小越接近约束最优性条件。"""
    c = costs(x)
    y = np.zeros(3)
    y[np.argmin(c)] = DEMAND
    return float(c @ (x - y))


def exact_simplex_projection(y):
    """独立核对CVXPY结果：非负且总量为10的单纯形投影。"""
    ordered = np.sort(y)[::-1]
    thresholds = (np.cumsum(ordered) - DEMAND) / np.arange(1, 4)
    rho = np.flatnonzero(ordered - thresholds > 0)[-1]
    return np.maximum(y - thresholds[rho], 0)


# z是投影后的流量；target是在可行域外也允许出现的试探点。
z = cp.Variable(3)
target = cp.Parameter(3)
projection_problem = cp.Problem(
    cp.Minimize(cp.sum_squares(z - target)),
    [z >= 0, cp.sum(z) == DEMAND],
)


def project(y):
    target.value = y
    projection_problem.solve(
        solver="CLARABEL",
        tol_gap_abs=1e-12,
        tol_gap_rel=1e-12,
        tol_feas=1e-12,
        max_iter=200,
    )
    if projection_problem.status not in ("optimal", "optimal_inaccurate"):
        raise RuntimeError(projection_problem.status)
    return np.asarray(z.value).copy()


def solve(step_size, updates=100):
    x = np.ones(3) * DEMAND / 3
    gaps = [max(frank_wolfe_gap(x), 0)]
    max_projection_error = 0.0
    max_flow_error = 0.0
    min_flow = float(np.min(x))
    for _ in range(updates):
        # 1. 沿负梯度试走，结果可能不满足流量约束。
        y = x - step_size * costs(x)
        # 2. 解最近点QP，把流量投影回可行域。
        x = project(y)
        # 3. 记录停止指标、可行性与独立投影核对结果。
        gaps.append(max(frank_wolfe_gap(x), 0))
        max_projection_error = max(
            max_projection_error,
            float(np.max(np.abs(x - exact_simplex_projection(y)))),
        )
        max_flow_error = max(max_flow_error, abs(float(np.sum(x)) - DEMAND))
        min_flow = min(min_flow, float(np.min(x)))
    return x, np.asarray(gaps), {
        "max_projection_error": max_projection_error,
        "max_total_flow_error": max_flow_error,
        "min_flow": min_flow,
    }


if __name__ == "__main__":
    output = ROOT / "运行结果"
    output.mkdir(exist_ok=True)
    records = []
    plt.figure(figsize=(8, 5))
    for step_size in (0.005, 0.05, 0.5):
        started = time.perf_counter()
        x, gaps, checks = solve(step_size)
        record = {
            "step_size": step_size,
            "updates": len(gaps) - 1,
            "final_x": x.tolist(),
            "final_costs": costs(x).tolist(),
            "final_objective": float(objective(x)),
            "final_gap": float(gaps[-1]),
            "seconds": time.perf_counter() - started,
            **checks,
        }
        records.append(record)
        print(json.dumps(record, ensure_ascii=False))
        plt.semilogy(np.arange(len(gaps)), np.maximum(gaps, 1e-13),
                     label=f"step size {step_size}")
    plt.xlabel("Number of updates")
    plt.ylabel("Frank-Wolfe gap")
    plt.legend()
    plt.tight_layout()
    image = output / "PGD_三种步长.png"
    plt.savefig(image, dpi=160)
    checks_path = ROOT / "_制作" / "week10_pgd_checks.json"
    checks_path.write_text(
        json.dumps({"runs": records, "figure": str(image)}, ensure_ascii=False, indent=2),
        encoding="utf-8",
    )
    print("Saved:", image)
