"""
=============================================================================
Lecture 3 · 脚本 02：梯度：指向上坡的向量（讲义 §2）
=============================================================================

【这个脚本要回答的问题】
    1. 梯度和方向导数是什么关系？（方向导数 = 梯度和方向的内积）
    2. 为什么梯度指向最陡的上坡？（把所有方向都试一遍）
    3. 梯度和法线有什么关系？（高度场的法线、隐式曲面的法线都来自梯度）
    4. 沿着梯度走能找到最高点吗？步子该多大？

【运行】python3 02_gradient.py        （约 1 秒）
【输出】out/02_gradient_field.png、out/02_terrain.png、out/02_gradient_walk.png
"""

import os

import numpy as np

import course_path
course_path.use("lecture01", "lecture02")
import calc_tools as ct
import console
import image_io
import plot2d


def hills(p):
    """
    一个有两座山的高度函数：两个高斯之和。

    【参数】p：(..., 2) 数组，最后一维是 (x, y)
    【返回】(...) 数组，高度
    """
    x, y = p[..., 0], p[..., 1]
    return 1.0 * np.exp(-((x - 0.7) ** 2 + (y - 0.4) ** 2) / 0.5) + 0.6 * np.exp(-((x + 0.8) ** 2 + (y + 0.5) ** 2) / 0.35)


def hills_gradient(p):
    """
    hills 的解析梯度。

    【思路】链式法则：d/dx exp(g) = exp(g) · dg/dx。
    【参数】p：长度 2 的数组
    【返回】长度 2 的数组
    """
    x, y = p
    a = 1.0 * np.exp(-((x - 0.7) ** 2 + (y - 0.4) ** 2) / 0.5)
    b = 0.6 * np.exp(-((x + 0.8) ** 2 + (y + 0.5) ** 2) / 0.35)
    return np.array([a * (-2.0 * (x - 0.7) / 0.5) + b * (-2.0 * (x + 0.8) / 0.35),
                     a * (-2.0 * (y - 0.4) / 0.5) + b * (-2.0 * (y + 0.5) / 0.35)])


def section_directional():
    """第 1 节：方向导数 = ⟨梯度, 方向⟩，以及最陡方向。"""
    console.print_header("1. 梯度和方向导数：把所有方向都试一遍")
    p = np.array([0.1, 0.5])
    g = hills_gradient(p)
    print(f"  位置 p = {p.tolist()}，梯度 ∇f = {np.round(g, 4).tolist()}，|∇f| = {np.linalg.norm(g):.4f}")
    print(f"  梯度的解析值和数值差分比较，最大相对误差：{ct.check_gradient(hills, hills_gradient, lambda r: r.uniform(-2, 2, size=2), np.random.default_rng(1)):.1e}\n")
    rows = []
    for deg in (0, 30, 60, 90, 120, 150, 180, 240, 300):
        t = np.radians(deg)
        u = np.array([np.cos(t), np.sin(t)])
        rows.append([f"{deg}°", f"{ct.directional(hills, p, u):+.5f}", f"{g @ u:+.5f}"])
    console.print_table(["方向", "方向导数（走一小步量出来的）", "⟨∇f, u⟩"], rows)

    angles = np.radians(np.arange(0.0, 360.0, 0.25))
    values = np.array([ct.directional(hills, p, np.array([np.cos(t), np.sin(t)])) for t in angles])
    best = float(np.degrees(angles[int(np.argmax(values))]))
    gdir = float(np.degrees(np.arctan2(g[1], g[0]))) % 360.0
    print(f"\n  试遍所有方向（每 0.25° 一个）：变化最快的方向是 {best:.2f}°，变化率 {values.max():.4f}。")
    print(f"  梯度的方向是 {gdir:.2f}°，|∇f| = {np.linalg.norm(g):.4f}。")
    print("  观察：两者吻合。因为 ⟨∇f, u⟩ = |∇f| cos θ，cos θ 在 θ = 0 时最大：沿梯度方向走，上升最快；")
    print("        反方向下降最快；垂直于梯度走，高度不变（这就是等高线的方向）。")


def section_field():
    """
    第 2 节：把梯度场画出来：箭头垂直于等高线。

    【输出】out/02_gradient_field.png。
    """
    xs = np.linspace(-2.0, 2.0, 81)
    ys = np.linspace(-1.5, 1.5, 61)
    grid = np.stack(np.meshgrid(xs, ys), axis=-1)
    z = hills(grid)
    c = plot2d.Canvas2D((-2.0, 2.0), (-1.5, 1.5), 480)
    c.heatmap(z)
    for level in np.arange(0.1, 1.0, 0.1):
        c.contour(xs, ys, z, float(level), plot2d.COLORS["black"], 1.0)
    for x in np.arange(-1.8, 2.0, 0.3):
        for y in np.arange(-1.35, 1.5, 0.3):
            p = np.array([x, y])
            g = hills_gradient(p)
            if np.linalg.norm(g) > 0.03:
                c.arrow(p, p + 0.22 * g / max(np.linalg.norm(g), 0.6), plot2d.COLORS["red"], 1.5, head=5.0)
    image_io.save_png(os.path.join(course_path.out_dir(), "02_gradient_field.png"), c.image())
    print("  输出 out/02_gradient_field.png：亮的地方高；红箭头是梯度，处处垂直于等高线，指向上坡")


# 地形由一组不同频率、不同方向的正弦波叠加而成。频率每次乘 1.7，振幅相应缩小（分形噪声的最简单写法）。
_TERRAIN_RNG = np.random.default_rng(11)
_TERRAIN_FREQ = 0.9 * 1.7 ** np.arange(9.0)
_TERRAIN_ANGLE = _TERRAIN_RNG.uniform(0.0, 2.0 * np.pi, size=9)
_TERRAIN_PHASE = _TERRAIN_RNG.uniform(0.0, 2.0 * np.pi, size=9)
_TERRAIN_AMP = 0.42 / 1.7 ** np.arange(9.0) ** 1.15


def terrain(x, y):
    """
    一个程序化的地形：9 个不同频率、不同方向的正弦波之和。

    【参数】x、y：同形状数组
    【返回】高度数组
    """
    z = np.zeros_like(x)
    for f, t, p, a in zip(_TERRAIN_FREQ, _TERRAIN_ANGLE, _TERRAIN_PHASE, _TERRAIN_AMP):
        z = z + a * np.sin(f * (np.cos(t) * x + np.sin(t) * y) + p)
    return z


def terrain_gradient(x, y):
    """
    terrain 的解析梯度：对每一项用链式法则，内层函数的导数把频率和方向带了出来。

    【参数】x、y：同形状数组
    【返回】(hx, hy)
    """
    hx, hy = np.zeros_like(x), np.zeros_like(x)
    for f, t, p, a in zip(_TERRAIN_FREQ, _TERRAIN_ANGLE, _TERRAIN_PHASE, _TERRAIN_AMP):
        c = a * f * np.cos(f * (np.cos(t) * x + np.sin(t) * y) + p)
        hx = hx + c * np.cos(t)
        hy = hy + c * np.sin(t)
    return hx, hy


def section_normals():
    """
    第 3 节：梯度给出法线：高度场和隐式曲面。

    【思路】
        高度场 z = h(x, y)：把它看成隐式曲面 F(x, y, z) = z − h(x, y) = 0，
            梯度 ∇F = (−h_x, −h_y, 1) 垂直于曲面，这就是法线。
        隐式曲面 F(p) = 0：等值面上任意切向走一步 F 不变，所以 ⟨∇F, 切向⟩ = 0，梯度就是法线。
        这正是第 13 讲（隐式几何）用来给 SDF 算法线的办法。
    【输出】out/02_terrain.png：高度图、用法线着色的结果、解析和差分法线的差异。
    """
    console.print_header("3. 梯度给出法线：把高度场照亮")
    n = 256
    xs = np.linspace(-3.0, 3.0, n)
    h = xs[1] - xs[0]
    xx, yy = np.meshgrid(xs, xs)
    z = terrain(xx, yy)
    hx, hy = terrain_gradient(xx, yy)
    fx, fy = ct.grad2d(z, h)

    def lit(gx, gy):
        normal = np.stack([-gx, -gy, np.ones_like(gx)], axis=-1)
        normal /= np.linalg.norm(normal, axis=-1, keepdims=True)
        light = np.array([0.5, 0.6, 0.62])
        return np.clip(normal @ (light / np.linalg.norm(light)), 0.0, 1.0), normal

    shaded, nor = lit(hx, hy)
    shaded_fd, nor_fd = lit(fx, fy)
    angle = np.degrees(np.arccos(np.clip((nor * nor_fd).sum(axis=-1), -1.0, 1.0)))
    print(f"  {n}×{n} 的高度场。解析梯度和中心差分算出的法线，夹角最大 {ct.inner(angle).max():.3f}°，平均 {ct.inner(angle).mean():.4f}°。")
    image_io.save_png(os.path.join(course_path.out_dir(), "02_terrain.png"), image_io.image_grid(
        [plot2d.label((z - z.min()) / (z.max() - z.min()), "height"),
         plot2d.label(image_io.srgb_encode(0.08 + 0.92 * shaded), "n . l shading"),
         plot2d.label(np.clip(angle / 2.0, 0.0, 1.0), "normal error")], gap=8))

    # 隐式曲面：单位球和圆环，比较数值梯度和解析法线
    rng = np.random.default_rng(2)
    rows = []
    R, r = 1.0, 0.4
    sphere = lambda p: np.linalg.norm(p) - 1.0
    torus = lambda p: np.hypot(np.hypot(p[0], p[2]) - R, p[1]) - r
    sphere_points = rng.normal(size=(500, 3))
    sphere_points /= np.linalg.norm(sphere_points, axis=1, keepdims=True)
    u, v = rng.uniform(0.0, 2.0 * np.pi, size=(2, 500))
    ring = np.stack([np.sin(u), np.zeros_like(u), np.cos(u)], axis=1)
    tube = np.cos(v)[:, None] * ring + np.sin(v)[:, None] * np.array([0.0, 1.0, 0.0])
    torus_points = R * ring + r * tube
    for name, f, points, truth in [("球 |p| − 1", sphere, sphere_points, sphere_points), ("圆环", torus, torus_points, tube)]:
        worst_angle, worst_value = 0.0, 0.0
        for p, t in zip(points, truth):
            g = ct.gradient(f, p, 1e-5)
            g = g / np.linalg.norm(g)
            worst_angle = max(worst_angle, float(np.degrees(np.arccos(np.clip(g @ t, -1.0, 1.0)))))
            worst_value = max(worst_value, abs(float(f(p))))
        rows.append([name, f"{worst_value:.1e}", f"{worst_angle:.2e}°"])
    print()
    console.print_table(["隐式曲面 F(p) = 0", "曲面上 |F| 的最大值", "∇F 和解析法线的最大夹角"], rows)
    print("\n  观察：不知道法线公式也没关系，只要能算 F，在曲面上差分就能得到法线。这是光线步进（第 13 讲）里的标准做法。")
    print("  输出 out/02_terrain.png：左边高度，中间 n·l 着色（法线全部来自梯度），右边两种法线的差异（放大显示）")


def section_walk():
    """
    第 4 节：沿着梯度走：爬山。

    【思路】每步走 x ← x + η∇f(x)。η（步长）是唯一的参数：太小走不动，太大会冲过头。
        从不同的起点出发，还可能到达不同的山顶（局部极大）。
    【输出】out/02_gradient_walk.png。
    """
    console.print_header("4. 沿着梯度走：步子该多大")
    xs = np.linspace(-2.0, 2.0, 81)
    ys = np.linspace(-1.5, 1.5, 61)
    z = hills(np.stack(np.meshgrid(xs, ys), axis=-1))
    c = plot2d.Canvas2D((-2.0, 2.0), (-1.5, 1.5), 480)
    c.heatmap(z)
    for level in np.arange(0.1, 1.0, 0.2):
        c.contour(xs, ys, z, float(level), plot2d.COLORS["gray"], 1.0)
    rows = []
    cases = [("太小", 0.02, (-0.2, 1.2), plot2d.COLORS["blue"]), ("合适", 0.3, (-0.2, 1.2), plot2d.COLORS["green"]),
             ("太大", 1.4, (-0.2, 1.2), plot2d.COLORS["red"]), ("换个起点", 0.3, (-1.5, -1.2), plot2d.COLORS["orange"])]
    for name, eta, start, color in sorted(cases, key=lambda item: -item[1]):      # 步长大的先画，免得盖住其他路径
        p = np.array(start, dtype=np.float64)
        path = [p.copy()]
        for _ in range(60):
            p = p + eta * hills_gradient(p)
            path.append(p.copy())
        path = np.array(path)
        c.polyline(path[:14] if eta > 1.0 else path, color, 1.2 if eta > 1.0 else 2.2)
        c.dot(path[0], color, 3.0)
        rows.append([name, eta, str(start), f"{hills(path[5]):.4f}", f"{hills(path[60]):.4f}", str(np.round(path[60], 3).tolist())])
    console.print_table(["情形", "步长 η", "起点", "走 5 步的高度", "走 60 步的高度", "终点"], rows, align=["<", ">", "<", ">", ">", "<"])
    image_io.save_png(os.path.join(course_path.out_dir(), "02_gradient_walk.png"), c.image())
    print("\n  观察：步长太小，60 步后还在半山腰；太大，一步冲过山顶，四处乱跳，60 步后的高度比半山腰还低。")
    print("        换个起点就爬上了另一座山：梯度只有局部信息，只能保证局部最优（第 30 讲详细讲）。")
    print("  输出 out/02_gradient_walk.png")


def main():
    section_directional()
    section_field()
    section_normals()
    section_walk()


if __name__ == "__main__":
    main()
