"""A thin accretion disk around a rotating (Kerr) black hole, as a distant observer sees it.

Copyright (c) 2026 Hugo Flayac. All rights reserved. You may download and run this script,
modified or not, for the sole purpose of checking the result. Do not redistribute it.

Method. One light ray per pixel is traced backwards from the observer by integrating
Hamilton's equations for null geodesics of the Kerr metric (Boyer-Lindquist coordinates,
Mino time, G = c = M = 1). A ray stops when it crosses the equatorial plane between the
innermost stable circular orbit and the outer edge of the disk, when it falls through the
horizon, or when it escapes. Nothing is painted: the dark centre is the set of rays that
end on the horizon.

Brightness. The disk gas moves on circular geodesics. The observed intensity is g^4 times
the emitted one, where g is the exact frequency shift between gas and observer (Doppler
and gravitational). The emitted profile, r^-3 (1 - sqrt(r_isco / r)), is a simple model of
a thin disk: it sets how fast the disk fades outwards, not where the light goes.

Drawing. The grid on the disk is the disk's own coordinates: circles every 2 M in radius
and spokes every 15 degrees, each drawn where its light actually lands. A flat grid seen
through flat space would be a set of ellipses and straight lines.

Checks printed at the end: the shadow of a non-rotating hole has radius sqrt(27), and the
image does not change when the integration step is halved.

Run:  python kerr-disk-image.py [output_prefix]      (numpy and Pillow; several minutes)
"""

import sys

import numpy as np


def isco(a):
    z1 = 1 + (1 - a * a) ** (1 / 3) * ((1 + a) ** (1 / 3) + (1 - a) ** (1 / 3))
    z2 = np.sqrt(3 * a * a + z1 * z1)
    return 3 + z2 - np.sqrt((3 - z1) * (3 + z1 + 2 * z2))


def trace(a, inclination_deg, width, height, half_width, eps, r_out=22.0, r_obs=300.0):
    """Returns maps of shape (height, width): intensity, frequency shift, radius and azimuth
    of the point of the disk seen in each pixel, and whether the ray fell into the hole."""
    inc = np.radians(inclination_deg)
    alpha, beta = np.meshgrid(
        np.linspace(-half_width, half_width, width),
        np.linspace(half_width * height / width, -half_width * height / width, height),
    )
    alpha, beta = alpha.ravel(), beta.ravel()
    # Constants of motion of the photon that reaches the observer at (alpha, beta).
    L = -alpha * np.sin(inc)
    Q = beta**2 + np.cos(inc) ** 2 * (alpha**2 - a * a)

    n = alpha.size
    r = np.full(n, r_obs)
    th = np.full(n, inc)
    ph = np.zeros(n)
    delta = r * r - 2 * r + a * a
    P = r * r + a * a - a * L
    pr = np.sqrt(np.maximum(P * P - delta * ((L - a) ** 2 + Q), 0)) / delta
    pth = np.sign(beta) * np.sqrt(
        np.maximum(Q - np.cos(th) ** 2 * (L * L / np.sin(th) ** 2 - a * a), 0)
    )

    def rhs(r, th, ph, pr, pth, l):
        s = np.maximum(np.abs(np.sin(th)), 1e-9) * np.where(np.sin(th) < 0, -1.0, 1.0)
        c = np.cos(th)
        d = r * r - 2 * r + a * a
        p = r * r + a * a - a * l
        return (
            d * pr,
            pth,
            l / (s * s) - a + a * p / d,
            -(r - 1) * pr * pr + (2 * p * r * d - p * p * (r - 1)) / (d * d),
            l * l * c / s**3 - a * a * s * c,
        )

    r_in, horizon = isco(a), 1 + np.sqrt(1 - a * a)
    hit_r, hit_ph = np.zeros(n), np.zeros(n)
    captured = np.zeros(n, bool)
    index, l = np.arange(n), L.copy()  # only the rays still travelling are integrated
    for _ in range(int(60 / eps)):
        if index.size == 0:
            break
        y = (r, th, ph, pr, pth)
        h = -eps * r / (r * r + 20.0)  # backwards in Mino time; finer near the hole
        k1 = rhs(*y, l)
        k2 = rhs(*(v + 0.5 * h * k for v, k in zip(y, k1)), l)
        k3 = rhs(*(v + 0.5 * h * k for v, k in zip(y, k2)), l)
        k4 = rhs(*(v + h * k for v, k in zip(y, k3)), l)
        new = [v + h / 6 * (q1 + 2 * q2 + 2 * q3 + q4) for v, q1, q2, q3, q4 in zip(y, k1, k2, k3, k4)]
        # Equatorial crossing between this step and the next, by linear interpolation.
        before, after = th - np.pi / 2, new[1] - np.pi / 2
        crossing = before * after < 0
        t = before / np.where(crossing, before - after, 1.0)
        r_cross = r + (new[0] - r) * t
        on_disk = crossing & (r_cross >= r_in) & (r_cross <= r_out)
        hit_r[index[on_disk]] = r_cross[on_disk]
        hit_ph[index[on_disk]] = (ph + (new[2] - ph) * t)[on_disk]
        r, th, ph, pr, pth = new
        # A ray that passes over a pole comes out on the other side: fold the angle back.
        over = (th < 0) | (th > np.pi)
        th = np.where(th < 0, -th, np.where(th > np.pi, 2 * np.pi - th, th))
        pth, ph = np.where(over, -pth, pth), np.where(over, ph + np.pi, ph)
        fell = r < horizon * 1.01
        captured[index[fell]] = True
        keep = ~(on_disk | fell | (r > r_obs + 1))
        index, l = index[keep], l[keep]
        r, th, ph, pr, pth = r[keep], th[keep], ph[keep], pr[keep], pth[keep]

    hit = hit_r > 0
    rd = np.where(hit, hit_r, r_in + 1.0)
    omega = 1 / (rd**1.5 + a)
    u_t = (rd**1.5 + a) / np.sqrt(rd**3 - 3 * rd**2 + 2 * a * rd**1.5)
    shift = np.where(hit, 1 / (u_t * (1 - omega * L)), 0.0)
    emitted = rd**-3.0 * (1 - np.sqrt(r_in / rd))
    intensity = np.where(hit, shift**4 * emitted, 0.0)
    shape = (height, width)
    return [m.reshape(shape) for m in (intensity, shift, hit_r, hit_ph, captured)]


def grid_lines(radius, azimuth, width_px=1.3):
    """Circles every 2 M and spokes every 15 degrees, with a constant thickness on screen."""
    def stroke(distance, gradient):
        return np.clip(1.5 - distance / np.maximum(gradient, 1e-9) / width_px, 0, 1)

    gy, gx = np.gradient(radius)
    circles = stroke(np.abs(radius - 2 * np.round(radius / 2)), np.hypot(gx, gy))
    step = np.radians(15)
    cy, cx = np.gradient(np.cos(azimuth))
    sy, sx = np.gradient(np.sin(azimuth))
    turn = np.sqrt(cx**2 + cy**2 + sx**2 + sy**2)
    spokes = stroke(np.abs(azimuth - step * np.round(azimuth / step)), turn)
    # No line across the jump between two images of the disk, or outside it.
    smooth = (np.hypot(gx, gy) < 1.5) & (radius > 0)
    return np.maximum(circles, spokes) * smooth


def save_layer(values, path):
    """A white image whose transparency carries the values: the page supplies the colour."""
    from PIL import Image

    alpha = (np.clip(values, 0, 1) * 255).astype(np.uint8)
    rgba = np.dstack([np.full_like(alpha, 255)] * 3 + [alpha])
    Image.fromarray(rgba, "RGBA").save(path, quality=90, method=6)


SPIN, INCLINATION, HALF_WIDTH, R_OUT = 0.9, 84.0, 30.0, 26.0


def main():
    prefix = sys.argv[1] if len(sys.argv) > 1 else "kerr-disk"
    size = (int(sys.argv[2]), int(sys.argv[3])) if len(sys.argv) > 3 else (1600, 720)

    # Check 1: shadow radius of a non-rotating hole, seen edge-on, with no disk.
    captured = trace(0.0, 90.0, 2001, 1, 8.0, 0.02, r_out=0.0)[4]
    edge = np.abs(np.linspace(-8, 8, 2001)[captured[0]]).max()
    print(f"shadow radius at a = 0: {edge:.3f}   (exact: sqrt(27) = {np.sqrt(27):.3f})")

    # Check 2: halving the step must not change the picture.
    coarse = trace(SPIN, INCLINATION, 320, 144, HALF_WIDTH, 0.04, r_out=R_OUT)[0]
    fine = trace(SPIN, INCLINATION, 320, 144, HALF_WIDTH, 0.02, r_out=R_OUT)[0]
    changed = np.abs(coarse - fine) / np.percentile(fine[fine > 0], 99)
    print(f"step halved: median change {np.median(changed):.1e}, 99th percentile {np.percentile(changed, 99):.1e}")

    intensity, shift, radius, azimuth, _ = trace(SPIN, INCLINATION, size[0], size[1], HALF_WIDTH, 0.02, r_out=R_OUT)
    seen = shift[shift > 0]
    print(f"image {size[0]}x{size[1]}: frequency shift from {seen.min():.2f} to {seen.max():.2f}")
    # Brightness on a logarithmic scale, as for a photograph of a very contrasted scene.
    glow = np.log1p(80 * intensity / intensity.max()) / np.log1p(80)
    ink = np.clip(0.62 * glow + grid_lines(radius, azimuth) * (0.2 + 0.55 * glow), 0, 1)
    # Second layer: light from gas moving towards the observer, more opaque the bluer it arrives.
    accent = ink * np.clip((shift - 0.8) / 0.5, 0, 1)
    # The central columns hold the rays that graze the rotation axis, where these coordinates
    # are singular and the integration is unreliable. One column in eighty is filled by
    # linear interpolation between its neighbours on each side.
    mid, band = size[0] // 2, max(1, round(size[0] / 160))
    weight = (np.arange(2 * band) + 1) / (2 * band + 1)
    for layer in (ink, accent):
        left, right = layer[:, mid - band - 1 : mid - band], layer[:, mid + band : mid + band + 1]
        layer[:, mid - band : mid + band] = left * (1 - weight) + right * weight
    save_layer(ink, f"{prefix}-ink.webp")
    save_layer(accent, f"{prefix}-accent.webp")


if __name__ == "__main__":
    main()
