#!/usr/bin/env python3
"""
PROVENANCE: NUMERICAL
Computation 217 -- what the Bernoulli measure gives the primordial perturbations, and
what it does not: Gaussian as (d_0/lambda)^3, white at the grain, no tilt
=====================================================================================
WHAT THIS DOES.  The cosmology chapter made three statements about primordial
perturbations that no computation carried: that deviations from Gaussianity are
suppressed as O(d_0^2/lambda^2), that the Bernoulli measure gives a near-scale-invariant
Gaussian spectrum, and that the spectrum follows from the near-threshold fluctuation
structure.  This file measures what the measure actually gives on a three-dimensional
lattice of independent grains (P1's Bernoulli measure; comp 211's independence at the
grain) and states the gap between that and the observed primordial spectrum.

  1. GAUSSIANITY.  Coarse-grain a grain-level variable over cubic windows of side
     lambda (in grain units d_0) and measure the skewness and excess kurtosis of the
     window means.  For independent grains the central limit theorem fixes both
     exactly: a window holds N = (lambda/d_0)^3 grains, so the skewness is
     gamma_1 N^(-1/2) = gamma_1 (d_0/lambda)^(3/2) and the excess kurtosis is
     gamma_2 N^(-1) = gamma_2 (d_0/lambda)^3, gamma_1 and gamma_2 being the grain's own
     skewness and excess kurtosis.  The exponent is the number of spatial dimensions,
     not two: the chapter's O(d_0^2/lambda^2) was a guess.  Measured on a skewed grain
     law (Bernoulli(0.1), gamma_1 = 2.67, gamma_2 = 5.11) so that both cumulants are
     visible; P1's symmetric Bernoulli(1/2) has gamma_1 = 0 and the same exponents.
  2. SPECTRUM.  The power spectrum of the grain field is white: flat in k down to the
     grain, fitted slope n = 0 in P(k) ~ k^n, and any local function of the grains (the
     distinction count of eq:pos, measured as the check) is white below the grain scale.
     That is "scale-free" in the sense of carrying no preferred scale, which is what
     independence at the grain means.  It is NOT the near-scale-invariant primordial
     spectrum: in the convention where Harrison--Zeldovich is n = 1 for the density
     contrast, white is n = 0, and Planck 2018 measures the curvature tilt
     n_s = 0.9649 +- 0.0042, one power of k from white and -0.035 from exact scale
     invariance.
  3. THE GAP, STATED.  The amplitude and the tilt of the primordial curvature
     perturbation are not derived here or anywhere in the book: they belong to the
     transfer of grain-scale white noise through the near-threshold epoch to horizon
     scales, the dynamics behind eq:qfluc, which the book does not carry out.  The
     honest content is: Gaussian at leading order with (d_0/lambda)^3 corrections,
     white at the grain, amplitude and tilt open.
  4. TAMPER.  Correlated grains (the same field smoothed over four grain lengths and
     re-thresholded) are what the measure does NOT give: the spectrum is red on the
     smoothed scales and the window statistics Gaussianise more slowly in lambda, so
     the test discriminates independence from correlation.

Reference: Planck Collaboration 2018, A&A 641 (2020) A6, n_s = 0.9649 +- 0.0042.
"""

import numpy as np

L = 256                        # lattice side, in grain units
SEED = 217
P_SKEW = 0.1                   # a skewed grain law, so both cumulants are visible
N_S_PLANCK, N_S_ERR = 0.9649, 0.0042


def rule(ch="-", n=88):
    print(ch * n)


def window_stats(field, lam):
    """Skewness and excess kurtosis of the means over cubic windows of side lam."""
    n = (field.shape[0] // lam) * lam
    f = field[:n, :n, :n]
    b = f.reshape(n // lam, lam, n // lam, lam, n // lam, lam).mean(axis=(1, 3, 5))
    x = b.ravel() - b.mean()
    m2 = np.mean(x ** 2)
    return np.mean(x ** 3) / m2 ** 1.5, np.mean(x ** 4) / m2 ** 2 - 3.0, b.size


def radial_spectrum(field, kmin=0.03, kmax=0.5):
    """Radially averaged power spectrum P(k) of a cubic field; k in cycles per grain."""
    f = field - field.mean()
    P = np.abs(np.fft.rfftn(f)) ** 2 / f.size
    n = f.shape[0]
    kx = np.fft.fftfreq(n)
    kz = np.fft.rfftfreq(n)
    KX, KY, KZ = np.meshgrid(kx, kx, kz, indexing="ij")
    K = np.sqrt(KX ** 2 + KY ** 2 + KZ ** 2)
    edges = np.linspace(0.0, 0.5, 41)
    which = np.digitize(K.ravel(), edges) - 1
    Pr = np.bincount(which, weights=P.ravel(), minlength=len(edges))[:-1]
    Nr = np.bincount(which, minlength=len(edges))[:-1]
    kc = 0.5 * (edges[1:] + edges[:-1])
    good = (Nr > 0) & (kc > kmin) & (kc < kmax)
    return kc[good], Pr[good] / Nr[good]


def fit_slope(x, y):
    return np.polyfit(np.log(x), np.log(np.abs(y)), 1)[0]


def gaussian_smooth(field, sigma):
    F = np.fft.fftn(field)
    k = np.fft.fftfreq(field.shape[0])
    KX, KY, KZ = np.meshgrid(k, k, k, indexing="ij")
    G = np.exp(-2.0 * (np.pi * sigma) ** 2 * (KX ** 2 + KY ** 2 + KZ ** 2))
    return np.real(np.fft.ifftn(F * G))


def main():
    rng = np.random.default_rng(SEED)
    rule("=")
    print("  COMPUTATION 217: the Bernoulli measure's primordial statistics, measured")
    rule("=")
    print(f"  lattice {L}^3 independent grains, seed {SEED}")

    # ---- 1. Gaussianity versus window size ------------------------------------
    rule()
    print(f"  1.  GAUSSIANITY OF WINDOW MEANS on a skewed grain law, Bernoulli({P_SKEW})")
    rule()
    p = P_SKEW
    g1 = (1 - 2 * p) / np.sqrt(p * (1 - p))
    g2 = (1 - 6 * p * (1 - p)) / (p * (1 - p))
    skewed = (rng.random((L, L, L)) < p).astype(np.float32)
    print(f"      grain law: skewness gamma_1 = {g1:.3f}, excess kurtosis gamma_2 = {g2:.3f}")
    print(f"      {'lambda/d_0':>10} {'windows':>9} {'skew meas':>10} {'skew CLT':>9} {'kurt meas':>10} {'kurt CLT':>9}")
    lams = [1, 2, 4, 8]
    sk, ku = [], []
    for lam in lams:
        s, k, nb = window_stats(skewed, lam)
        sk.append(s); ku.append(k)
        print(f"      {lam:>10d} {nb:>9d} {s:>10.4f} {g1 / lam ** 1.5:>9.4f} {k:>10.4f} {g2 / lam ** 3:>9.4f}")
    p_sk = fit_slope(np.array(lams, float), np.array(sk))
    p_ku = fit_slope(np.array(lams[:3], float), np.array(ku[:3]))
    print()
    print(f"      fitted skewness      ~ (lambda/d_0)^({p_sk:.2f})   CLT: -3/2  (N^-1/2, N = (lambda/d_0)^3)")
    print(f"      fitted exc. kurtosis ~ (lambda/d_0)^({p_ku:.2f})   CLT: -3    (N^-1; fitted on lambda <= 4,")
    print("                                                     beyond which the kurtosis is below")
    print("                                                     the sampling noise of the windows)")
    print("      the chapter's O(d_0^2/lambda^2) is replaced by (d_0/lambda)^3 for the kurtosis")
    print("      and (d_0/lambda)^(3/2) for the skewness: the exponent is the number of spatial")
    print("      dimensions, by the central limit theorem over the grains in a window")
    ok1 = abs(p_sk + 1.5) < 0.15 and abs(p_ku + 3.0) < 0.3
    print(f"      exponents within 0.15 of -3/2 and 0.3 of -3                     : {ok1}")

    # ---- 2. The spectrum is white ----------------------------------------------
    rule()
    print("  2.  POWER SPECTRUM: white at the grain, fitted slope n in P(k) ~ k^n")
    rule()
    bits = rng.integers(0, 2, size=(L, L, L), dtype=np.int8)
    kc, Pk = radial_spectrum(bits.astype(np.float32))
    n_bits = fit_slope(kc, Pk)
    print(f"      the grain field, Bernoulli(1/2): {len(kc)} bins, k = {kc[0]:.3f} to {kc[-1]:.3f} cycles/grain")
    print(f"        fitted slope n = {n_bits:+.4f}   (white: 0);  max/min over the bins {Pk.max() / Pk.min():.3f}")
    # a local function of the grains: the distinction count of eq:pos (0 to 6)
    sub = bits[:128, :128, :128]
    dens = np.zeros(sub.shape, dtype=np.float32)
    for ax in range(3):
        dens += (sub != np.roll(sub, 1, axis=ax))
        dens += (sub != np.roll(sub, -1, axis=ax))
    kd, Pd = radial_spectrum(dens, kmin=0.03, kmax=0.12)
    n_dens = fit_slope(kd, Pd)
    print(f"      the distinction count (a local function of the grains), k < 0.12 cycles/grain:")
    print(f"        fitted slope n = {n_dens:+.4f}   (white below the grain scale; the stencil")
    print("        shapes the spectrum only within a few grains of the cutoff)")
    ok2 = abs(n_bits) < 0.02 and abs(n_dens) < 0.1
    print(f"      both flat                                                       : {ok2}")
    print()
    print("      In the convention where Harrison-Zeldovich is n = 1 for the density contrast,")
    print("      white is n = 0: one power of k from scale invariance.  Planck 2018 measures the")
    print(f"      curvature tilt n_s = {N_S_PLANCK} +- {N_S_ERR}, {N_S_PLANCK - 1:+.4f} from exact scale")
    print("      invariance.  Independence at the grain gives neither the Harrison-Zeldovich")
    print("      power nor the tilt; both belong to the transfer through the near-threshold")
    print("      epoch, which this book does not derive.")

    # ---- 3. Tamper: correlated grains ------------------------------------------
    rule()
    print("  3.  TAMPER: the same grains smoothed over four grain lengths and re-thresholded")
    rule()
    sm = gaussian_smooth(sub.astype(np.float64), 4.0)
    corr = (sm > np.median(sm)).astype(np.float32)
    kc2, Pk2 = radial_spectrum(corr, kmin=0.03, kmax=0.25)
    n_corr = fit_slope(kc2, Pk2)
    skc, kuc = [], []
    for lam in lams:
        s, k, nb = window_stats(corr, lam)
        skc.append(s); kuc.append(k)
    p_kuc = fit_slope(np.array(lams[:3], float), np.array(kuc[:3]))
    print(f"      fitted spectral slope on the smoothed scales n = {n_corr:+.3f}   (red: well below 0)")
    print(f"      exc. kurtosis of window means ~ (lambda/d_0)^({p_kuc:.2f}) against {p_ku:.2f} for")
    print("      independent grains: correlated grains Gaussianise more slowly in lambda")
    ok3 = n_corr < -1.0 and p_kuc > p_ku + 1.0
    print(f"      the test discriminates independence from correlation             : {ok3}")

    # ---- 4. Verdict --------------------------------------------------------------
    rule("=")
    print("  VERDICT")
    rule("=")
    print("  The Bernoulli measure gives primordial fluctuations that are Gaussian at leading")
    print("  order, the skewness falling as (d_0/lambda)^(3/2) and the excess kurtosis as")
    print("  (d_0/lambda)^3, and a spectrum that is white at the grain, n = 0.  The")
    print("  Harrison-Zeldovich power and the measured tilt n_s - 1 = -0.035 are not given by")
    print("  the measure: they belong to the transfer from the grain to the horizon, which is")
    print("  open.  The chapter's O(d_0^2/lambda^2) and 'near-scale-invariant from the Bernoulli")
    print("  measure' are withdrawn in favour of these statements.")
    print(f"  all three checks pass: {ok1 and ok2 and ok3}")
    return ok1 and ok2 and ok3


if __name__ == "__main__":
    import sys
    if not main():
        sys.exit(1)
