"""Axisymmetric Navier--Stokes in similarity variables.

The random quadrature acts on the discrete heat semigroup; it does not add
physical noise. The two branches use the same force, with q=0 as reference.

Python >= 3.10, NumPy and SciPy. For example:
    python navier_stokes.py --grid 63 --T 2 --dt .004 --samples 32 --output run.json
"""
from __future__ import annotations

import argparse
import json
import math
import time

import numpy as np
from scipy.fft import dstn, idstn
from scipy.sparse import diags, eye, kron
from scipy.sparse.linalg import LinearOperator, eigs, splu
from scipy.special import expit


def cutoff(rho):
    """C-infinity cutoff equal to one below 3.5 and zero above 4.5."""
    chi = (rho <= 3.5).astype(float)
    mask = (rho > 3.5) & (rho < 4.5)
    s = rho[mask] - 3.5
    chi[mask] = expit(1 / s - 1 / (1 - s))
    return chi


class Ring:
    def __init__(self, n=63, extent=24.0):
        self.n = n
        self.h = extent / (n + 1)
        self.r = np.arange(1, n + 1) * self.h
        self.z = self.r - extent / 2
        self.R, self.Z = np.meshgrid(self.r, self.z)
        R, Z, h = self.R, self.Z, self.h
        I = eye(n, format='csc')
        d = diags([-np.ones(n - 1), np.ones(n - 1)], [-1, 1], shape=(n, n), format='csc') / (2 * h)
        d2 = diags([np.ones(n - 1), -2 * np.ones(n), np.ones(n - 1)], [-1, 0, 1], format='csc') / h**2
        self.Dr = kron(I, d, format='csc')
        self.Dz = kron(d, I, format='csc')
        self.Lap = kron(I, d2, format='csc') + kron(d2, I, format='csc')
        self.D = self.Lap + diags(1 / R.ravel()) @ self.Dr - diags(1 / R.ravel()**2)
        self.D = self.D.tocsc()
        self.lu = splu(self.D)

        rho = np.hypot(R - 12, Z)
        phi = 200 * np.exp(-rho**2 / 2) * cutoff(rho)
        pr, pz = self.derivatives(phi)
        self.Ur = -pz
        self.Uz = pr + phi / R
        self.zeta = (self.D @ phi.ravel()).reshape(n, n)
        self.zeta_r, self.zeta_z = self.derivatives(self.zeta)
        self.kappa = 2 / h * np.sin(np.arange(1, n + 1) * np.pi / (2 * (n + 1)))
        self.base_norm = self.norm(self.Ur, self.Uz)
        self._A = self.D + eye(n * n, format='csc')
        self._A += diags((.5 * R - self.Ur).ravel()) @ self.Dr
        self._A += diags((.5 * Z - self.Uz).ravel()) @ self.Dz
        self._A += diags((self.Ur / R).ravel())
        self._B = diags((self.zeta_r - self.zeta / R).ravel()) @ self.Dz
        self._B -= diags(self.zeta_z.ravel()) @ self.Dr
        self._B -= diags((self.zeta_z / R).ravel())
        self._A = self._A.tocsc()
        self._B = self._B.tocsc()

    def derivatives(self, a):
        ar = np.zeros_like(a)
        az = np.zeros_like(a)
        ar[:, 1:-1] = (a[:, 2:] - a[:, :-2]) / (2 * self.h)
        ar[:, 0] = a[:, 1] / (2 * self.h)
        ar[:, -1] = -a[:, -2] / (2 * self.h)
        az[1:-1] = (a[2:] - a[:-2]) / (2 * self.h)
        az[0] = a[1] / (2 * self.h)
        az[-1] = -a[-2] / (2 * self.h)
        return ar, az

    def velocity(self, q):
        phi = self.lu.solve(np.asarray(q).ravel()).reshape(self.n, self.n)
        pr, pz = self.derivatives(phi)
        return -pz, pr + phi / self.R

    def norm(self, vr, vz):
        return float(np.sqrt(np.sum(2 * np.pi * self.R * (np.abs(vr)**2 + np.abs(vz)**2)) * self.h**2))

    def linear(self, flat):
        return self._A @ flat + self._B @ self.lu.solve(flat)

    def unstable_mode(self, seed=12345):
        """Shift-invert search around several real points; no spectral certification."""
        n2 = self.n**2
        op = LinearOperator((n2, n2), matvec=self.linear, dtype=float)
        rng = np.random.default_rng(seed)
        v0 = rng.normal(size=n2)
        found = []
        for shift in (3.2, 1.5):
            factor = splu(((self._A - shift * eye(n2, format='csc')) @ self.D + self._B).tocsc())
            inv = LinearOperator((n2, n2), matvec=lambda b: self.D @ factor.solve(b), dtype=float)
            values, vectors = eigs(op, k=6, sigma=shift, OPinv=inv, v0=v0, tol=2e-8, maxiter=700)
            for j, lam in enumerate(values):
                if lam.real > 0 and abs(lam.imag) < 1e-7:
                    found.append((lam.real, vectors[:, j].real))
        if not found:
            raise RuntimeError('No real unstable mode was found on this grid. Increase the resolution.')
        lam, eta = max(found, key=lambda item: item[0])
        eta = eta.reshape(self.n, self.n)
        eta /= self.norm(*self.velocity(eta))
        # Fix the sign so changing the quadrature seed does not select another branch.
        if eta.flat[np.argmax(np.abs(eta))] > 0:
            eta = -eta
        residual = np.linalg.norm(self.linear(eta.ravel()) - lam * eta.ravel()) / np.linalg.norm(eta)
        return float(lam), eta, float(residual)

    def remainder(self, q, nonlinear=True):
        qr, qz = self.derivatives(q)
        vr, vz = self.velocity(q)
        R, Z = self.R, self.Z
        out = qr / R - q / R**2 + q
        out += (.5 * R - self.Ur) * qr + (.5 * Z - self.Uz) * qz
        out += self.Ur * q / R - vr * self.zeta_r - vz * self.zeta_z + vr * self.zeta / R
        if nonlinear:
            out += -vr * qr - vz * qz + vr * q / R
        return out

    def heat(self, q, duration, samples, rng):
        if samples:
            normal = rng.normal(size=(samples, 2))
            c1 = np.cos(np.sqrt(2 * duration) * normal[:, 0, None] * self.kappa)
            c2 = np.cos(np.sqrt(2 * duration) * normal[:, 1, None] * self.kappa)
            multiplier = c2.T @ c1 / samples
        else:
            multiplier = np.exp(-duration * (self.kappa[:, None]**2 + self.kappa[None, :]**2))
        return idstn(dstn(q, type=1, norm='ortho') * multiplier, type=1, norm='ortho')

    def step(self, q, dt, samples, rng, nonlinear=True):
        a = self.heat(q, dt / 2, samples, rng)
        k1 = self.remainder(a, nonlinear)
        k2 = self.remainder(a + .5 * dt * k1, nonlinear)
        k3 = self.remainder(a + .5 * dt * k2, nonlinear)
        k4 = self.remainder(a + dt * k3, nonlinear)
        a = a + dt / 6 * (k1 + 2 * k2 + 2 * k3 + k4)
        return self.heat(a, dt / 2, samples, rng)


class MeridianView:
    """A fixed display mesh around the ring, separate from the numerical grid."""
    def __init__(self, model, size=33):
        self.r = np.linspace(6.0, 18.0, size)
        self.z = np.linspace(-6.0, 6.0, size)
        R, Z = np.meshgrid(self.r, self.z)
        ri = (R.ravel() - model.r[0]) / model.h
        zi = (Z.ravel() - model.z[0]) / model.h
        i = np.floor(ri).astype(int)
        j = np.floor(zi).astype(int)
        a, b = ri - i, zi - j
        self.indices = np.array([j * model.n + i, j * model.n + i + 1,
                                 (j + 1) * model.n + i, (j + 1) * model.n + i + 1])
        self.weights = np.array([(1-a)*(1-b), a*(1-b), (1-a)*b, a*b])

    def sample(self, field):
        values = np.sum(np.asarray(field).ravel()[self.indices] * self.weights, axis=0)
        # These are drawing coordinates only; solver states retain full precision.
        return np.round(values, 8)

    def velocity(self, radial, vertical):
        return {'radial': self.sample(radial).tolist(), 'vertical': self.sample(vertical).tolist()}


def simulate(params=None):
    params = {} if params is None else dict(params)
    n = int(params.get('N', params.get('grid', 63)))
    n = max(23, min(191, n))
    samples = int(params.get('samples', 32))
    samples = max(0, min(512, samples))
    T = max(.25, min(32.0, float(params.get('T', 2.0))))
    dt_requested = max(.0005, min(.008, float(params.get('dt', .004))))
    seed = int(params.get('seed', 271828)) % (2**32)
    amplitude = max(1.0, min(300.0, float(params.get('amplitude', 300.0))))
    nonlinear = bool(params.get('nonlinear', True))
    snapshots = max(2, min(121, int(params.get('snapshots', 71))))
    extent = max(24.0, min(40.0, float(params.get('extent', 24.0))))
    model = Ring(n, extent)
    lam, eta, residual = model.unstable_mode()
    # A conservative advective cap for the explicit RK part.
    advective = np.max(np.abs(.5 * model.R - model.Ur) + np.abs(.5 * model.Z - model.Uz))
    dt_cap = .75 * model.h / advective
    steps = math.ceil(T / min(dt_requested, dt_cap))
    dt = T / steps
    rng = np.random.default_rng(seed)
    q = amplitude * np.exp(-lam * T) * eta
    save_at = set(np.linspace(0, steps, min(snapshots, steps + 1)).round().astype(int))
    frames, times = [], []
    view = MeridianView(model)
    baseline = view.velocity(model.Ur, model.Uz)
    branch_fields = []
    max_speed = float(np.max(np.hypot(baseline['radial'], baseline['vertical'])))
    diagnostics = {'velocity_norm': [], 'physical_distance': [], 'linear_distance': [], 'base_physical_norm': [], 'relative_separation': [], 'energy_difference': []}
    started = time.perf_counter()
    peak = 0.0
    for step in range(steps + 1):
        tau = -T + step * dt
        if step in save_at:
            vr, vz = model.velocity(q)
            distance = model.norm(vr, vz)
            frames.append(q.ravel().tolist())
            times.append(float(tau))
            field = view.velocity(model.Ur + vr, model.Uz + vz)
            branch_fields.append(field)
            max_speed = max(max_speed, float(np.max(np.hypot(field['radial'], field['vertical']))))
            diagnostics['velocity_norm'].append(distance)
            diagnostics['physical_distance'].append(float(np.exp(tau / 4) * distance))
            diagnostics['linear_distance'].append(float(amplitude * np.exp((lam + .25) * tau)))
            diagnostics['base_physical_norm'].append(float(np.exp(tau / 4) * model.base_norm))
            diagnostics['relative_separation'].append(distance / model.base_norm)
            difference_energy = np.sum(2 * np.pi * model.R * (model.Ur * vr + model.Uz * vz + .5 * (vr**2 + vz**2))) * model.h**2
            diagnostics['energy_difference'].append(float(difference_energy))
        if step == steps:
            break
        q = model.step(q, dt, samples, rng, nonlinear)
        peak = max(peak, float(np.max(np.abs(q))))
        if not np.all(np.isfinite(q)) or peak > 1e8:
            raise RuntimeError('The computation diverges for these parameters; reduce the time step or amplitude.')
    vr, vz = model.velocity(q)
    return {
        'x': model.r.tolist(), 'y': model.z.tolist(), 'frames': frames, 'times': times,
        'diagnostics': diagnostics,
        'velocities': {'radial': vr.ravel().tolist(), 'vertical': vz.ravel().tolist()},
        'base_velocities': {'radial': model.Ur.ravel().tolist(), 'vertical': model.Uz.ravel().tolist()},
        'total_velocities': {'radial': (model.Ur + vr).ravel().tolist(), 'vertical': (model.Uz + vz).ravel().tolist()},
        'vector_fields': {
            'r': view.r.tolist(), 'z': view.z.tolist(),
            'shape': [len(view.z), len(view.r)],
            'baseline': baseline, 'perturbed': branch_fields,
            'max_speed': max_speed,
            'position_scales': [math.exp(tau / 2) for tau in times],
            'velocity_scales': [math.exp(-tau / 2) for tau in times],
            'streamline_seeds': [[12 + offset, 0.0] for offset in (.65, 1.0, 1.4, 1.8, 2.2, 2.8, 3.4)],
            'meta': {
                'coordinates': 'Self-similar cylindrical coordinates (r, z); no azimuthal velocity.',
                'order': 'Row-major: z rows, r columns.',
                'time_indices': 'The perturbed fields and scale factors use the same indices as times and frames.',
                'baseline_label': 'Baseline U-bar', 'perturbed_label': 'Perturbed U-bar + v',
                'window': 'The display shows 6 <= r <= 18 and -6 <= z <= 6; the solver uses the full domain.',
                'sampling': 'Bilinear sampling of the computed velocities, rounded to 8 decimal places for display.',
                'shared_scale': 'max_speed is the maximum sampled speed of either branch over all saved times.',
                'physical_scaling': 'x = exp(tau/2) xi; u = exp(-tau/2) U. Apply the same factors to both branches.',
                'streamlines': 'Common meridional seeds for instantaneous streamlines. They are not time-dependent particle trajectories.',
                'perturbation_amplified': False
            }
        },
        'meta': {
            'method': 'Centered differences, Strang splitting, RK4 and Gaussian quadrature of the discrete semigroup',
            'grid': n, 'N': n, 'seed': seed, 'samples': samples, 'T': T, 'dt': dt,
            'requested_dt': dt_requested, 'steps': steps, 'amplitude': amplitude,
            'eigenvalue': lam, 'eigen_residual': residual, 'base_velocity_norm': model.base_norm,
            'seconds': time.perf_counter() - started, 'nonlinear': nonlinear,
            'quantity': 'q = ζ − ζ̄', 'time_label': 'τ = log t', 'extent': extent,
            'domain': f'0 < r < {extent:g}, −{extent/2:g} < z < {extent/2:g} ; q = Φq = 0 on the boundary',
            'interpretation': 'Discrete illustration on a truncated domain; neither a certified continuous spectrum nor a proof of Leray non-uniqueness.',
            'spectral_search': 'Real unstable mode found by two shift-invert searches; spectral maximality is not certified.',
            'initial_physical_distance': diagnostics['physical_distance'][0],
            'final_physical_distance': diagnostics['physical_distance'][-1]
        }
    }


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--grid', type=int, default=63)
    parser.add_argument('--T', type=float, default=2)
    parser.add_argument('--dt', type=float, default=.004)
    parser.add_argument('--samples', type=int, default=32, help='0: exact discrete heat multiplier')
    parser.add_argument('--extent', type=float, default=24)
    parser.add_argument('--seed', type=int, default=271828)
    parser.add_argument('--amplitude', type=float, default=300)
    parser.add_argument('--output', default='navier-stokes.json')
    args = vars(parser.parse_args())
    path = args.pop('output')
    result = simulate(args)
    with open(path, 'w', encoding='utf-8') as stream:
        json.dump(result, stream, ensure_ascii=False, allow_nan=False, separators=(',', ':'))
    print(json.dumps(result['meta'], ensure_ascii=False, indent=2))
