#!/usr/bin/env python3
"""Nothing Arrives

A digital interpretation of the day's instruction, drawn by program:

    White crayon on a black wall. One grain 1/16 inch wide at the
    center. Then three hundred thousand more, one at a time, each sent
    straight from a chance point on the wall's edge toward the center,
    stopping where it first touches a stopped grain.

The wall is taken as 8 ft square, a lattice of 1/16-inch square grain
cells, 1536 per side. Every grain is one cell. Flights are exact
straight lines to the wall's center, sampled finely enough that the
moving grain's cells form an unbroken chain; a grain stops in the
first cell that touches a stopped grain (edge or corner contact) and
never overlaps. Grains stop strictly one at a time, in order.
"""

import hashlib
import numpy as np
from PIL import Image

SEED = 21                 # the date; one seeded draw stream fixes everything
GRAINS = 300_000          # grains after the first
CELLS = 1536              # 8 ft = 96 in = 1536 sixteenth-inches per side
CENTER = CELLS / 2.0      # wall center point in cell units: (768.0, 768.0)
SEED_CELL = (CELLS // 2, CELLS // 2)   # the cell the center point falls on
RENDER = CELLS            # 1 px per grain; exactly square
DETAIL_CELLS = 384        # render-2: central 24 in x 24 in, 4 px per grain


def launch_points(rng, n):
    """Chance launch points, uniform by distance along the wall's edge,
    and unit directions from each straight to the wall's center."""
    u = rng.random(n) * (4.0 * CELLS)      # perimeter parameter
    side = (u // CELLS).astype(np.int64)   # 0=bottom 1=right 2=top 3=left
    s = u - side * CELLS                   # distance along that side
    x = np.empty(n); y = np.empty(n)
    m = side == 0; x[m] = s[m];            y[m] = 0.0
    m = side == 1; x[m] = CELLS;           y[m] = s[m]
    m = side == 2; x[m] = CELLS - s[m];    y[m] = CELLS
    m = side == 3; x[m] = 0.0;             y[m] = CELLS - s[m]
    dx = CENTER - x; dy = CENTER - y
    norm = np.hypot(dx, dy)
    return x, y, dx / norm, dy / norm, norm


def build():
    """Carry out the instruction. Returns the padded occupancy lattice.

    occp has a 1-cell pad; wall cell (i, j) sits at occp[i+1, j+1].
    Grains stop strictly one at a time: flight k sees the final resting
    place of every grain before it.
    """
    rng = np.random.default_rng(SEED)
    occp = np.zeros((CELLS + 2, CELLS + 2), dtype=np.int8)
    occp[SEED_CELL[0] + 1, SEED_CELL[1] + 1] = 1     # the first grain
    lx, ly, dx, dy, dist = launch_points(rng, GRAINS)

    stops = np.empty((GRAINS, 2), dtype=np.int32)
    stop_dist = np.empty(GRAINS)                     # flight length flown
    for k in range(GRAINS):
        # Step at most 0.9 cell per axis, so the cells the moving grain
        # occupies form an unbroken 8-connected chain: no stopped grain
        # can be passed without a cell that touches it being occupied.
        # The margin below 1.0 keeps floating-point truncation from
        # skipping a cell when a coordinate lands on a cell boundary.
        m = max(abs(dx[k]), abs(dy[k]))
        nsteps = int(np.ceil(dist[k] * m / 0.9))
        stopped = False
        t0 = 0
        while not stopped:
            t1 = min(t0 + 512, nsteps)
            t = np.arange(t0, t1 + 1, dtype=np.float64)
            xs = lx[k] + t * 0.9 * dx[k] / m
            ys = ly[k] + t * 0.9 * dy[k] / m
            # launch points sit on the wall's edge; clip the boundary
            # point into the inside cell it belongs to
            ix = np.clip(xs.astype(np.int64), 0, CELLS - 1) + 1
            iy = np.clip(ys.astype(np.int64), 0, CELLS - 1) + 1
            touch = (
                occp[iy - 1, ix - 1] | occp[iy - 1, ix] | occp[iy - 1, ix + 1]
                | occp[iy, ix - 1]     | occp[iy, ix]     | occp[iy, ix + 1]
                | occp[iy + 1, ix - 1] | occp[iy + 1, ix] | occp[iy + 1, ix + 1]
            )
            hit = np.flatnonzero(touch)
            if hit.size:
                h = hit[0]
                assert occp[iy[h], ix[h]] == 0, "overlap: stop cell occupied"
                occp[iy[h], ix[h]] = 1
                stops[k] = (iy[h] - 1, ix[h] - 1)
                stop_dist[k] = t[h] * 0.9 / m
                stopped = True
            else:
                t0 = t1 + 1
            assert t0 <= nsteps + 1, "flight reached the center untouched"
    assert stops.shape[0] == GRAINS
    return occp, stops, stop_dist


def verify(occp, stops):
    """Checks the construction against the instruction, all asserted."""
    occ = occp[1:-1, 1:-1]
    total = int(occ.sum())
    assert total == GRAINS + 1, (total, GRAINS + 1)
    assert occ[SEED_CELL] == 1, "center grain missing"
    # Every stopped grain touches a stopped grain: at least one occupied
    # 8-neighbor at the moment it stops (earlier grains only grow).
    nb = np.zeros((CELLS, CELLS), dtype=np.int16)
    for a in range(3):
        for b in range(3):
            if (a, b) != (1, 1):
                nb += occp[a:a + CELLS, b:b + CELLS].astype(np.int16)
    assert bool((nb[occ == 1] >= 1).all()), "a grain touches nothing"
    # No two grains in one cell is structural: occ is one mark per cell.
    ys = stops[:, 0]; xs = stops[:, 1]
    r = np.hypot(ys + 0.5 - CENTER, xs + 0.5 - CENTER) / 16.0   # inches
    return dict(total=total, radius_min_in=float(r.min()),
                radius_max_in=float(r.max()),
                edge_stops=int(((xs == 0) | (xs == CELLS - 1)
                                | (ys == 0) | (ys == CELLS - 1)).sum()))


def field_hash(occp):
    return hashlib.sha256(occp[1:-1, 1:-1].tobytes()).hexdigest()


def render(occp):
    occ = occp[1:-1, 1:-1]
    img = Image.fromarray(np.where(occ, 255, 0).astype(np.uint8), "L")
    img.save("render-1.png")                      # whole wall, 1 px per grain
    c0 = (CELLS - DETAIL_CELLS) // 2
    detail = occ[c0:c0 + DETAIL_CELLS, c0:c0 + DETAIL_CELLS]
    d = Image.fromarray(np.where(detail, 255, 0).astype(np.uint8), "L")
    d = d.resize((RENDER, RENDER), Image.NEAREST)  # exactly 2 px per grain
    d.save("render-2.png")
    return img.size, d.size


if __name__ == "__main__":
    occp, stops, stop_dist = build()
    stats = verify(occp, stops)
    h1 = field_hash(occp)
    occp2, _, _ = build()                          # determinism check
    h2 = field_hash(occp2)
    assert h1 == h2, "construction not deterministic"
    s1, s2 = render(occp)
    assert s1 == s2 == (RENDER, RENDER)
    print("grains:", stats["total"])
    print("aggregate radius in inches: min %.3f max %.3f"
          % (stats["radius_min_in"], stats["radius_max_in"]))
    print("grains stopped on the edge:", stats["edge_stops"])
    print("flight lengths in inches: min %.3f median %.3f max %.3f"
          % (stop_dist.min() / 16, np.median(stop_dist) / 16,
             stop_dist.max() / 16))
    print("field sha256:", h1)
    print("determinism: second construction identical")
    print("render-1:", s1, "render-2:", s2)
