"""Example 6 — 2D heat equation (5-point stencil, Jacobi).

Concepts: 2D grid, boundary conditions, double buffering (ping-pong),
several kernel launches without going back to the host.

    python examples/06_heat_2d.py [device]
"""

import numpy as np
from common import choose_device, size

import unigpu as gpu


@gpu.jit
def time_step(u, v, alpha):
    x, y = gpu.grid(2)
    ny, nx = u.shape
    if 0 < x < nx - 1 and 0 < y < ny - 1:
        laplacian = u[y - 1, x] + u[y + 1, x] + u[y, x - 1] + u[y, x + 1] - 4 * u[y, x]
        v[y, x] = u[y, x] + alpha * laplacian
    elif x < nx and y < ny:
        v[y, x] = u[y, x]          # edges: fixed temperature


def heat_numpy(u, steps, alpha=0.2):
    """The same time steps with NumPy, on the whole array at once (reference)."""
    reference = u.copy()
    for _ in range(steps):
        following = reference.copy()
        following[1:-1, 1:-1] = reference[1:-1, 1:-1] + alpha * (
            reference[:-2, 1:-1] + reference[2:, 1:-1] + reference[1:-1, :-2]
            + reference[1:-1, 2:] - 4 * reference[1:-1, 1:-1])
        reference = following
    return reference


def main():
    """Run the example on the device given as an argument (the best one otherwise)."""
    choose_device()
    n, steps = size(256, 24), size(500, 10)
    u = np.zeros((n, n), np.float32)
    u[n // 4: 3 * n // 4, n // 4: 3 * n // 4] = 100.0   # hot square in the middle
    d_u, d_v = gpu.to_device(u), gpu.to_device(u)

    block, grid = (16, 16), ((n + 15) // 16, (n + 15) // 16)
    for _ in range(steps):
        time_step[grid, block](d_u, d_v, np.float32(0.2))
        d_u, d_v = d_v, d_u                                    # swap the buffers
    result = d_u.copy_to_host()

    assert np.allclose(result, heat_numpy(u, steps), atol=1e-3)   # check
    print(f"OK — mean temperature: {result.mean():.3f}")


if __name__ == "__main__":
    main()
