#!/usr/bin/env python3
"""From white noise to the 333 Brusselator film: simulate, slide back, average.

The film obeys one rule: slide the picture by a third of the box, and it matches
itself a third of a period later. So take frames a third of a period apart, slide
them back, and average. What obeys the rule survives, as three copies of one picture.
Anything ticking in unison is caught at three phases 120 degrees apart, and cancels.

    python3 twisted_average.py [seed]        needs only NumPy; about 7 s on one core
"""
import sys

import numpy as np

N, L = 36, 40.0     # a triangular mesh of N x N nodes, in a repeating box of side L
a, b = 1.0, 2.3     # the Brusselator's constants; both chemicals diffuse at rate 1
dt = 0.02           # the longest time step


def rate(q):
    """How fast the chemicals q = (u, v) are changing: diffusion plus reaction."""
    u, v = q
    neighbours = [(0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (-1, -1)]
    laplacian = (sum(np.roll(q, d, (1, 2)) for d in neighbours) - 6 * q) * 2 / (3 * (L / N) ** 2)
    return laplacian + np.array([a - (b + 1) * u + u * u * v, b * u - u * u * v])


def simulate(q, t):
    """Run time forward by t (fourth-order Runge-Kutta)."""
    steps = int(np.ceil(t / dt))
    h = t / steps
    for _ in range(steps):
        k1 = rate(q)
        k2 = rate(q + h / 2 * k1)
        k3 = rate(q + h / 2 * k2)
        k4 = rate(q + h * k3)
        q = q + h / 6 * (k1 + 2 * k2 + 2 * k3 + k4)
    return q


def slide(q):
    """Slide the picture by a third of the box. On the film this costs T/3 of time."""
    return np.roll(q, (-N // 3, -2 * N // 3), (1, 2))


def turn(q):
    """Turn the picture 120 degrees about the origin. On the film this costs no time."""
    y, x = np.indices((N, N))
    return q[:, (x - y) % N, -y % N]


def find_film(q, T=6.355, tol=1e-10):
    """Return one frame of the film, its period T, and the number of sweeps it took."""
    q = (q + turn(q) + turn(turn(q))) / 3           # costs no time, so impose it once and it stays
    for sweep in range(1, 400):
        q = simulate(q, T)                          # one free period: what decays, decays
        third = simulate(q, T / 3)
        two_thirds = simulate(third, T / 3)

        lag = slide(third) - q                      # zero on the film
        if np.sqrt(np.mean(lag * lag)) < tol:
            return q, T, sweep

        # T is off by 3 x lag / speed. Move it gently, since at first it's all noise.
        speed = rate(q)
        T -= np.clip(3 * np.sum(lag * speed) / np.sum(speed * speed), -0.1, 0.1)

        # What obeys the rule survives the average; what ticks in unison cancels.
        q = (q + slide(third) + slide(slide(two_thirds))) / 3
    raise RuntimeError('no convergence')


if __name__ == '__main__':
    seed = int(sys.argv[1]) if len(sys.argv) > 1 else 1
    rest = np.array([a, b / a])[:, None, None]
    noise = np.random.default_rng(seed).standard_normal((2, N, N))
    frame, T, sweeps = find_film(rest + 0.1 * noise)
    print(f'seed {seed}: T = {T:.10f} after {sweeps} sweeps (the published film: 6.3901599186)')
