Does light charge the quons? › Files cited on the page › check_grids_fable/

check_grids.py

In the investigation at sim/charge_wave/check_grids_fable/check_grids.py · last changed in commit 9b0d406, 12 November 2026 · 27,331 bytes · the folder as a zip


"""check_grids.py - the sixth reviewer's independent checks of trial 4 (sim/charge_wave/finer_grids.py, lock
papers/Lock_finer_grids_2026-11-12.md) and of draft 0.10, section 8.5, of "Does light charge the quons?".

Written from scratch, not from the trial's code:
  A. the rigid-level rule by a THIRD path: a direct real-space lattice sum of the Hessian of the Gaussian-smoothed Coulomb
     energy over complete cubic shells (no Fourier sum, no Parseval), which must give K_T + 1/3 for a quon against charge -1
     (the +1/3 is the cube's depolarisation term, the G = 0 term the transverse wave does not have);
  B. the k -> 0 transverse limit of the full tensor at finite k (the G = 0 term included), to show that the G != 0 sum is
     that limit and that the longitudinal value is K_T + 1 (the trace sum rule L + 2T = sigma_at of trial 2);
  C. C2, C3 and the crossover with my own Fourier code (direct site sums), and the closed form of the C2 residual;
  D. the bunched grid of C4 rebuilt (own bisection), the three pair stiffnesses, and the statics and dielectric response of the
     three-level stack: is the k > 1 arrangement light at c, or a plasma?
  E. the point stacks S2 and S3: own Ewald (eta = 1.5 and 3.0, real cells within +-5, reciprocal within +-8), the trace identity
     term by term, the eigenvalues at X and M against the trial's, and a brute-force Bloch sum with no Ewald at X for S2;
  F. Thomson's atom from a grid (C6a): the deviation predicted from the plums' width alone; C6b by my own geometry;
  G. C7: the plasma dispersion of the unheld case and its mass dependence.
Units as the trial: spacing d = 1, quon charge q = 1, Coulomb energy 1/r (Gaussian lattice units); stiffnesses in units of
4 pi n q^2 = 4 pi unless marked. Run: ~/aspden-review-venv/bin/python3 check_grids.py > check_grids_out.txt
"""
import itertools, math, time
import numpy as np
from scipy.special import erf, erfc

T0 = time.time()
FOURPI = 4 * math.pi

def say(*a):
    print(*a, flush=True)

# ----------------------------------------------------------------------------------------------- levels (own structures)
class Level:
    def __init__(self, pos, c, s, name):
        self.pos = np.atleast_2d(np.asarray(pos, float))
        self.c = np.asarray(c, float).ravel()
        self.s = float(s)
        self.name = name
    @property
    def Q(self):
        return self.c.sum()

def grid_sites(N, off):
    ax = (np.arange(N) + off) / N
    return np.array(list(itertools.product(ax, ax, ax)))

def quon(s):
    return Level([[0, 0, 0]], [1.0], s, "quon")

def even_level(N, off, total, s, name):
    return Level(grid_sites(N, off), np.full(N**3, total / N**3), s, name)

# ----------------------------------------------------------------------------------------------- path 1: Fourier (own)
def rho_G(L, G):
    """Fourier coefficient per cell, rho(G) = sum_j c_j exp(-i G.r_j) exp(-s^2 G^2/2), by a direct site sum (no FFT)."""
    out = np.zeros(len(G), complex)
    for a in range(0, len(G), 800):
        g = G[a:a + 800]
        out[a:a + 800] = np.exp(-1j * (g @ L.pos.T)) @ L.c
    return out * np.exp(-L.s**2 * np.einsum("ni,ni->n", G, G) / 2)

def K_fourier(A, Bs, k=(0.0, 0.0, 0.0), cut=40.0):
    """K = -sum_{k+G != 0} Re[rho_A rho_B*] (k+G)(k+G)^T/|k+G|^2 over G, in units of 4 pi. At k = 0 the G = 0 term is left
    out (the transverse k -> 0 limit); at k != 0 it is kept (the full tensor at that k)."""
    k = np.asarray(k, float)
    smin = min(math.sqrt(A.s**2 + B.s**2) for B in Bs)
    H = int(math.ceil(math.sqrt(2 * cut) / smin / (2 * math.pi))) + 1
    h = np.arange(-H, H + 1)
    hh = np.array(list(itertools.product(h, h, h)), float)
    G = 2 * math.pi * hh + k
    G2 = np.einsum("ni,ni->n", G, G)
    m = G2 > 1e-20
    G, G2 = G[m], G2[m]
    ra = rho_G(A, G)
    rb = sum(rho_G(B, G) for B in Bs)
    w = np.real(ra * np.conj(rb)) / G2
    return -np.einsum("n,ni,nj->ij", w, G, G), H

# ----------------------------------------------------------------------------------------------- path 2: real-space overlap (own)
CELLS = np.array(list(itertools.product(range(-3, 4), repeat=3)), float)      # 343 nearest cells (the trial used 125)

def overlap(A, B):
    """integral over a cell of rho_A rho_B for Gaussian charges = sum_i sum_j sum_R c_i c_j N(r_i - r_j - R; s_A^2 + s_B^2)."""
    s2 = A.s**2 + B.s**2
    norm = (2 * math.pi * s2) ** -1.5
    tot = 0.0
    for R in CELLS:
        d = A.pos[:, None, :] - B.pos[None, :, :] - R
        tot += A.c @ (norm * np.exp(-np.einsum("ijk,ijk->ij", d, d) / (2 * s2))) @ B.c
    return tot

def KT_real(A, Bs):
    """(sigma_at - sigma_avg)/3 generalised: -(1/3) sum_B [integral rho_A rho_B - Q_A Q_B], units of 4 pi."""
    return -sum(overlap(A, B) - A.Q * B.Q for B in Bs) / 3

# ----------------------------------------------------------------------------------------------- path 3: direct Hessian sum (own)
def hess_erf_over_r(rv, sig):
    """Hessian of g(r) = erf(r/(sig sqrt 2))/r, the energy of two unit Gaussians whose widths add to sig^2, at vectors rv."""
    r = np.linalg.norm(rv, axis=1)
    small = r < 1e-9
    rr = np.where(small, 1.0, r)
    pref = math.sqrt(2 / math.pi) / sig
    ex = np.exp(-rr**2 / (2 * sig**2))
    er = erf(rr / (sig * math.sqrt(2)))
    g1 = pref * ex / rr - er / rr**2
    g2 = pref * ex * (-1 / sig**2 - 2 / rr**2) + 2 * er / rr**3
    nn = np.einsum("ni,nj->nij", rv, rv) / rr[:, None, None] ** 2
    out = (g2 - g1 / rr)[:, None, None] * nn + (g1 / rr)[:, None, None] * np.eye(3)
    out[small] = -(FOURPI / 3) * (2 * math.pi * sig**2) ** -1.5 * np.eye(3)      # the r -> 0 limit, isotropic
    return out

def K_direct(A, B, Lmax):
    """sum over the cells R with |R|_inf <= Lmax of sum_ij c_i c_j Hess g(r_i - r_j - R): the energy's second derivative in the
    relative shift of the two rigid levels, summed over a cube. In units of 4 pi. Converges to K_fourier - Q_A Q_B/3."""
    sig = math.sqrt(A.s**2 + B.s**2)
    Rs = np.array(list(itertools.product(range(-Lmax, Lmax + 1), repeat=3)), float)
    K = np.zeros((3, 3))
    for i in range(len(A.pos)):
        d = (A.pos[i][None, None, :] - B.pos[:, None, :] - Rs[None, :, :]).reshape(-1, 3)
        Hs = hess_erf_over_r(d, sig).reshape(len(B.pos), len(Rs), 3, 3)
        K += A.c[i] * np.einsum("j,jnab->ab", B.c, Hs)
    return K / FOURPI

def iso(K):
    d = np.diag(K)
    return d.mean(), max(d.max() - d.min(), np.abs(K - np.diag(d)).max())

# =============================================================================================== A. the rule by a third path
say("A. The rigid-level rule by a third path: direct real-space Hessian sums over cubes (no Fourier sum, no Parseval)")
say("   For a quon (+1) against finer charge -1 the cube sum must tend to K_T + 1/3 (the cube's depolarisation term is the")
say("   G = 0 term, which the sideways wave does not have). Units of 4 pi n q^2.")
cases = []
cases.append(("C3 N=2 k=1 between (point quon between 8 finer points)", quon(0.025), even_level(2, 0.5, -1.0, 0.05, "L2")))
cases.append(("C3 N=2 k=1 on (a finer quon on the quon)", quon(0.025), even_level(2, 0.0, -1.0, 0.05, "L2")))
cases.append(("C2 N=4 k=1 between (wide quon, even grid)", quon(0.2), even_level(4, 0.5, -1.0, 0.075, "L2")))
cases.append(("C2 N=4 k=1 on", quon(0.2), even_level(4, 0.0, -1.0, 0.075, "L2")))
# the crossover point s1 N = 0.3
cases.append(("crossover N=4 k=1 between, s1 N = 0.3", quon(0.075), even_level(4, 0.5, -1.0, 0.025, "L2")))
# C6a N = 8 plums in proportion to the quon's density
y6 = 0.1
s16 = (y6 / (8 * math.pi**1.5)) ** (1 / 3)
r8 = grid_sites(8, 0.5)
dens = sum(np.exp(-np.sum((r8 - np.array(R, float))**2, 1) / (2 * s16**2)) for R in itertools.product((-1, 0, 1), repeat=3))
plums8 = Level(r8, -dens / dens.sum(), 0.15 / 8, "plums N=8")
cases.append(("C6a N=8 (Gaussian quon y = 0.1, plums in proportion to its density)", quon(s16), plums8))
say(f"{'case':70s} {'K_T Fourier':>14s} {'K_T real':>14s} {'cube L=3':>12s} {'L=5':>12s} {'L=7':>12s} {'L=9':>12s}  Fourier+1/3")
worstA = 0.0
for name, A, B in cases:
    KF, H = K_fourier(A, [B])
    kt, isoF = iso(KF)
    kr = KT_real(A, [B])
    row = []
    for L in (3, 5, 7, 9):
        KD = K_direct(A, B, L)
        kd, isoD = iso(KD)
        row.append(kd)
    worstA = max(worstA, abs(row[-1] - (kt + 1 / 3)))
    say(f"{name:70s} {kt:+14.8f} {kr:+14.8f} " + " ".join(f"{x:+12.8f}" for x in row) + f"  {kt + 1/3:+.8f}   (Fourier isotropy {isoF:.0e}, cube L=9 isotropy {isoD:.0e}, H = {H})")
say(f"   largest |cube(L=9) - (K_T + 1/3)| over the cases: {worstA:.1e}  (the cube sum converges from its shells as 1/L^3)")

# =============================================================================================== B. the k -> 0 transverse limit
say("\nB. The full tensor at finite k = (kappa, 0, 0), G = 0 term included: yy and zz must tend to K_T, xx to K_T + 1")
say("   (the longitudinal value; the trace L + 2T = sigma_at is trial 2's sum rule). Case: C4-like bunched grid is below in D;")
say("   here the C3 Earnshaw case and the C6a plums.")
for name, A, B in (cases[0], cases[5]):
    KF0, _ = K_fourier(A, [B])
    kt0, _ = iso(KF0)
    for kap in (0.3, 0.1, 0.03, 0.01):
        Kk, _ = K_fourier(A, [B], k=(kap, 0, 0))
        say(f"   {name[:45]:45s} kappa = {kap:5.2f}: xx = {Kk[0,0]:+.8f}  yy = {Kk[1,1]:+.8f}  zz = {Kk[2,2]:+.8f}   "
            f"(k->0 transverse {kt0:+.8f}, longitudinal {kt0 + 1:+.8f}; off-diagonal {np.abs(Kk - np.diag(np.diag(Kk))).max():.0e})")

# =============================================================================================== C. C2, C3, crossover
say("\nC. C2 and C3 with my own Fourier code, and the closed form of the C2 residual")
say("   C2 residual: for an even grid of N per spacing and k per cell, only G in 2 pi N Z^3 survive; the six nearest give")
say("   K_T = -/+ 2 k exp(-2 pi^2 N^2 (s1^2 + s2^2)) (between/on), so the leftover is proportional to the density k.")
say(f"   {'N':>3s} {'k':>3s} {'placement':9s} {'K_T Fourier (own)':>18s} {'K_T real (own)':>16s} {'closed form':>14s}  trial")
trialC2 = {(4, 1, "between"): -1.104104e-06, (4, 1, "on"): +1.104107e-06, (4, 4, "between"): -4.416416e-06, (4, 4, "on"): +4.416426e-06,
           (4, 16, "between"): -1.766567e-05, (4, 16, "on"): +1.766570e-05, (8, 1, "between"): -1.104104e-06, (8, 1, "on"): +1.104107e-06,
           (8, 4, "between"): -4.416416e-06, (8, 4, "on"): +4.416426e-06, (8, 16, "between"): -1.766567e-05, (8, 16, "on"): +1.766570e-05}
worstC2 = 0.0
for N in (4, 8):
    for k in (1, 4, 16):
        for off, pl in ((0.5, "between"), (0.0, "on")):
            A = quon(0.8 / N)
            Bs = [even_level(N, off, -k, 0.3 / N, "L2")]
            if k > 1:
                Bs.append(even_level(2 * N, 0.5, k - 1, 0.3 / (2 * N), "L3"))
            KF, H = K_fourier(A, Bs)
            kt, _ = iso(KF)
            kr = KT_real(A, Bs)
            closed = (-1 if pl == "between" else 1) * 2 * k * math.exp(-2 * math.pi**2 * N**2 * ((0.8 / N)**2 + (0.3 / N)**2))
            worstC2 = max(worstC2, abs(kt))
            say(f"   {N:3d} {k:3d} {pl:9s} {kt:+18.6e} {kr:+16.6e} {closed:+14.6e}  {trialC2[(N, k, pl)]:+.6e}")
say(f"   largest |K_T| = {worstC2:.2e}; trial 1.77e-05. Width a quon needs (rms, in finer spacings) for the leftover to stay below 1e-3")
say("   at density k, from the closed form with s2 = 0.3/N: " + ", ".join(f"k = {k}: {math.sqrt(max(math.log(2*k/1e-3), 0)/(2*math.pi**2) - 0.09):.2f}" for k in (1, 16, 1e3, 1e6)))

say("   C3, narrow quon (s1 = 0.05/N, s2 = 0.1/N, s3 = 0.05/N):")
for N in (2, 4):
    for k in (1, 4):
        for off, pl in ((0.5, "between"), (0.0, "on")):
            A = quon(0.05 / N)
            Bs = [even_level(N, off, -k, 0.1 / N, "L2")]
            if k > 1:
                Bs.append(even_level(2 * N, 0.5, k - 1, 0.05 / N, "L3"))
            KF, H = K_fourier(A, Bs)
            kt, _ = iso(KF)
            kr = KT_real(A, Bs)
            say(f"   {N:3d} {k:3d} {pl:9s} K_T Fourier {kt:+.7e}  real {kr:+.7e}  sigma_at {-sum(overlap(A, B) for B in Bs):+.6e}")
say("   crossover N = 4, k = 1, s2 = 0.1/N (own Fourier):")
for sN in (0.05, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.8, 1.0):
    vals = []
    for off in (0.5, 0.0):
        KF, _ = K_fourier(quon(sN / 4), [even_level(4, off, -1.0, 0.1 / 4, "L2")])
        vals.append(iso(KF)[0])
    say(f"   s1 N = {sN:4.2f}: between {vals[0]:+.6e}  on {vals[1]:+.6e}")

# =============================================================================================== D. C4 rebuilt; the three-level stack
say("\nD. C4 rebuilt with my own bisection; then the three-level stack's statics and dielectric response")
def bunched(N, k, beta, w=0.2, s=0.3 / 8, off=0.5):
    r = grid_sites(N, off)
    h = sum(np.exp(-np.sum((r - np.array(R, float))**2, 1) / (2 * w * w)) for R in itertools.product((-1, 0, 1), repeat=3))
    wts = 1 + beta * h
    return Level(r, -k * wts / wts.sum(), s, "L2 bunched")

trial_beta = {1: 2.3010893082, 4: 0.4725283160, 16: 0.1130871826}
pair = {}
for k in (1, 4, 16):
    A = quon(0.1)
    L3 = even_level(16, 0.5, k - 1, 0.3 / 16, "L3") if k > 1 else None
    s3at = overlap(A, L3) if L3 else 0.0
    def excess(beta):
        return -overlap(A, bunched(8, k, beta)) - s3at - 1.0
    lo, hi = 0.0, 1.0
    while excess(hi) < 1.0:
        hi *= 2
    for _ in range(200):
        mid = 0.5 * (lo + hi)
        if excess(mid) < 1.0:
            lo = mid
        else:
            hi = mid
        if hi - lo < 1e-15 * hi:
            break
    beta = 0.5 * (lo + hi)
    L2 = bunched(8, k, beta)
    Bs = [L2] + ([L3] if L3 else [])
    KF, H = K_fourier(A, Bs)
    kt, isoF = iso(KF)
    K12, _ = K_fourier(A, [L2]); k12 = iso(K12)[0]
    k13 = k23 = 0.0
    if L3:
        K13, _ = K_fourier(A, [L3]); k13 = iso(K13)[0]
        K23, _ = K_fourier(L2, [L3]); k23 = iso(K23)[0]
    ratio = -overlap(A, L2) / k
    pair[k] = (k12, k13, k23)
    say(f"   k = {k:2d}: beta = {beta:.10f} (trial {trial_beta[k]:.10f}); level 2 at the quon / its average = {ratio:.8f} (1 + 1/k = {1 + 1/k:.6f});")
    say(f"           K_T(quon vs all finer) Fourier = {kt:.10f}, real = {KT_real(A, Bs):.10f}; pair stiffnesses K12 = {k12:+.6e}, K13 = {k13:+.3e}, K23 = {k23:+.6e}"
        + (f"  (K23 / (k(k-1)) = {k23/(k*(k-1)):+.3e})" if L3 else ""))

say("   The stack's statics. Levels 1 (quon, +1), 2 (-k), 3 (+(k-1)); pair stiffnesses as above (units 4 pi). The force on level l")
say("   per cell is -sum_m K_lm (u_l - u_m) + Q_l E. Static response: Lmat u = Q E with Lmat_ll = sum_m K_lm, Lmat_lm = -K_lm.")
say("   Lmat always has the zero mode (1,1,1) (a common shift). A second zero or negative eigenvalue means no static hold: a plasma")
say("   (or an instability) for the mode light drives. Dielectric response chi(w) = Q^T (Lmat - w^2 M)^-1 Q, eps = eps_b + 4 pi chi")
say("   in the trial's Gaussian units (so 4 pi chi in units of 4 pi n q^2 is just chi here).")
for k in (1, 4, 16):
    k12, k13, k23 = pair[k]
    Q = np.array([1.0, -k, k - 1.0])
    Lmat = np.array([[k12 + k13, -k12, -k13], [-k12, k12 + k23, -k23], [-k13, -k23, k13 + k23]])
    ev = np.linalg.eigvalsh(Lmat)
    say(f"   k = {k:2d}: eigenvalues of Lmat = {ev[0]:+.3e}, {ev[1]:+.3e}, {ev[2]:+.3e}")
    # static response: Q is orthogonal to the common mode (neutrality), so chi(0) = sum over the other modes of (v.Q)^2 / w
    w_, V = np.linalg.eigh(Lmat)
    terms = [((V[:, i] @ Q)**2, w_[i]) for i in range(3) if abs(w_[i]) > 1e-10]
    chi0 = sum(a / w for a, w in terms)
    say(f"           static chi(0) in units of n q^2 / (4 pi n q^2) [chi0 = 3 means eps(0) = eps_0 for f = 1/4]: {chi0:+.6f};"
        f" mode weights and stiffnesses: " + ", ".join(f"(v.Q)^2 = {a:.4f} at K = {w:+.3e}" for a, w in terms))
    if k > 1:
        say("           -> the mode (quon + level 2) against level 3 has a stiffness near zero (and negative, from K23 < 0): no static hold,")
        say("              so this arrangement is not light at c; with K13 = K23 = 0 exactly it is a plasma:")
        M12 = 1 + k; M3 = k - 1                           # masses 1 per unit |charge|
        mu = M12 * M3 / (M12 + M3)
        say(f"              free mode charge k - 1 = {k-1}, reduced mass {mu:.4f} (mass 1 per unit charge) -> wp^2 = (k-1)^2/mu = {(k-1)**2/mu:.4f} x 4 pi n q^2/m,")
        say(f"              against the quon-level-2 relative mode's wr^2 = K12 (1/1 + 1/k) = {k12 * (1 + 1/k):.4f} x 4 pi n q^2/m.")
        M = np.diag(np.abs(Q).astype(float))
        for wtest in (1e-2, 1e-3):
            u = np.linalg.solve(Lmat - wtest**2 * M, Q)
            chi = Q @ u
            say(f"              dynamic chi at w^2 = {wtest**2:.0e} (x 4 pi n q^2/m): {chi:+.4e} (negative and large: the driven mode is unstable/free, not held)")

# =============================================================================================== E. the point stacks: own Ewald
say("\nE. The point stacks (C5): own Ewald, eta = 1.5 and 3.0, real cells within +-5, reciprocal within +-8; eigenvalues of the")
say("   force-constant matrix Phi(k) (units q^2/d^3, as the trial prints them); the trace identity term by term.")
def hess_erfc_over_r(rv, eta):
    r = np.linalg.norm(rv, axis=1)
    ex = np.exp(-(eta * r)**2) * 2 * eta / math.sqrt(math.pi)
    f1 = -ex / r - erfc(eta * r) / r**2
    f2 = ex * (2 * eta**2 + 2 / r**2) + 2 * erfc(eta * r) / r**3
    nn = np.einsum("ni,nj->nij", rv, rv) / r[:, None, None] ** 2
    return (f2 - f1 / r)[:, None, None] * nn + (f1 / r)[:, None, None] * np.eye(3)

def make_lattices(Lr, Lg):
    R = np.array(list(itertools.product(range(-Lr, Lr + 1), repeat=3)), float)
    G = 2 * math.pi * np.array(list(itertools.product(range(-Lg, Lg + 1), repeat=3)), float)
    return R, G

def T_ewald(r, k, eta, R, G, same):
    """sum_R e^{ik.R} Hess(1/|r - R|), the R with r - R = 0 left out (same), k + G = 0 left out."""
    Rl = R[np.any(R != 0, axis=1)] if same else R
    x = r[None, :] - Rl
    real = np.einsum("n,nab->ab", np.exp(1j * (Rl @ k)), hess_erfc_over_r(x, eta))
    Kv = G + k
    K2 = np.einsum("ni,ni->n", Kv, Kv)
    m = K2 > 1e-14
    Kv, K2 = Kv[m], K2[m]
    rec = -FOURPI * np.einsum("n,na,nb->ab", np.exp(-K2 / (4 * eta**2)) / K2 * np.exp(1j * (Kv @ r)), Kv, Kv)
    T = real + rec
    if same:
        T = T + (4 * eta**3 / (3 * math.sqrt(math.pi))) * np.eye(3)
    return T

def Phi(pos, q, k, eta, R, G):
    n = len(pos)
    P = np.zeros((3 * n, 3 * n), complex)
    z = np.zeros(3)
    for i in range(n):
        ons = np.zeros((3, 3), complex)
        for j in range(n):
            P[3*i:3*i+3, 3*j:3*j+3] = -q[i] * q[j] * T_ewald(pos[i] - pos[j], k, eta, R, G, i == j)
            ons += q[i] * q[j] * T_ewald(pos[i] - pos[j], z, eta, R, G, i == j)
        P[3*i:3*i+3, 3*i:3*i+3] += ons
    return P

ax2 = np.array([0.25, 0.75]); ax4 = (np.arange(4) + 0.5) / 4
p2 = np.array(list(itertools.product(ax2, ax2, ax2))); p4 = np.array(list(itertools.product(ax4, ax4, ax4)))
S2 = (np.vstack([np.zeros((1, 3)), p2]), np.concatenate([[1.0], np.full(8, -1 / 8)]))
S3 = (np.vstack([np.zeros((1, 3)), p2, p4]), np.concatenate([[1.0], np.full(8, -0.5), np.full(64, 3 / 64)]))
R5, G8 = make_lattices(5, 8)
trialC5 = {("S2", "X"): (-9.526199, 13.41184, 10), ("S2", "M"): (-9.982995, 8.605822, 9), ("S2", "k0"): (-8.784114, 11.88766, 8),
           ("S3", "X"): (-37.59961, 46.05332, 82), ("S3", "M"): (-38.88164, 40.28947, 81)}
say("   the trace identity, term by term (eta = 1.5): Tr T(r; k) for r off-site should be 0 at k != 0 and 4 pi at k = 0 (G = 0 left out);")
for r in (np.array([0.25, 0.25, 0.25]), np.array([0.5, 0.0, 0.0])):
    for k in (np.array([math.pi, 0, 0]), np.array([0.3, 0.7, 1.1]), np.zeros(3)):
        T = T_ewald(r, k, 1.5, R5, G8, False)
        say(f"     r = {r}, k = {np.round(k, 3)}: Tr T = {np.trace(T).real:+.10f}  (4 pi = {FOURPI:.6f})")
T = T_ewald(np.zeros(3), np.array([math.pi, math.pi, 0]), 1.5, R5, G8, True)
say(f"     on-site r = 0, k = M: Tr T = {np.trace(T).real:+.3e}; at k = 0: {np.trace(T_ewald(np.zeros(3), np.zeros(3), 1.5, R5, G8, True)).real:+.6f}")
say("   so Tr Phi = sum_i q_i (sum_j q_j) 4 pi (on-site, k = 0 part) + 0 (k part) = 0 by neutrality: Earnshaw for the whole stack.")
for sname, (pos, q) in (("S2", S2), ("S3", S3)):
    for kname, kv in (("k0", (1e-3, 0, 0)), ("X", (math.pi, 0, 0)), ("M", (math.pi, math.pi, 0))):
        if sname == "S3" and kname == "k0":
            continue
        kv = np.array(kv, float)
        lam = {}
        for eta in (1.5, 3.0):
            P = Phi(pos, q, kv, eta, R5, G8)
            herm = np.abs(P - P.conj().T).max()
            lam[eta] = np.linalg.eigvalsh(0.5 * (P + P.conj().T))
            trP = np.trace(P).real
        S = np.abs(lam[1.5]).sum()
        neg = int((lam[1.5] < -1e-9 * S).sum())
        t = trialC5[(sname, kname)]
        say(f"   {sname} at {kname:2s}: lowest {lam[1.5][0]:+.6f} (trial {t[0]:+.6f}), highest {lam[1.5][-1]:+.6f} (trial {t[1]:+.6f}), negatives {neg}/{3*len(pos)} (trial {t[2]}),"
            f" |Tr|/sum|lam| = {abs(trP)/S:.1e}, eta 1.5 vs 3.0: {np.abs(lam[1.5]-lam[3.0]).max()/S:.1e}, Hermitian to {herm:.0e}")

say("   brute force, no Ewald: S2 at X by a direct Bloch sum of Hessians over cubes |R|_inf <= L (conditionally convergent; the")
say("   k = 0 on-site sums converge over cubes by neutrality). Lowest and highest eigenvalue against the Ewald values above.")
def hess_coulomb(rv):
    r = np.linalg.norm(rv, axis=1)
    nn = np.einsum("ni,nj->nij", rv, rv) / r[:, None, None] ** 2
    return (3 * nn - np.eye(3)) / r[:, None, None] ** 3

def Phi_brute(pos, q, k, L):
    Rs = np.array(list(itertools.product(range(-L, L + 1), repeat=3)), float)
    n = len(pos)
    P = np.zeros((3 * n, 3 * n), complex)
    ph = np.exp(1j * (Rs @ k))
    for i in range(n):
        ons = np.zeros((3, 3))
        for j in range(n):
            x = pos[i] - pos[j] - Rs
            m = np.linalg.norm(x, axis=1) > 1e-12
            Hs = hess_coulomb(x[m])
            P[3*i:3*i+3, 3*j:3*j+3] = -q[i] * q[j] * np.einsum("n,nab->ab", ph[m], Hs)
            ons += q[i] * q[j] * Hs.sum(0)
        P[3*i:3*i+3, 3*i:3*i+3] += ons
    return P
for L in (6, 12, 24):
    P = Phi_brute(S2[0], S2[1], np.array([math.pi, 0, 0]), L)
    lam = np.linalg.eigvalsh(0.5 * (P + P.conj().T))
    say(f"     L = {L:2d}: lowest {lam[0]:+.6f}, highest {lam[-1]:+.6f}, negatives {int((lam < -1e-9*np.abs(lam).sum()).sum())}/27, |Tr|/sum|lam| = {abs(np.trace(P).real)/np.abs(lam).sum():.1e}")

# =============================================================================================== F. Thomson's atom from a grid
say("\nF. C6a: the deviation from (1/y - 1)/3 = 3 predicted from the plums' own width alone (the plum density is the quon's")
say("   Gaussian convolved with the plums' Gaussian, so sigma_at = (1/y) (1 + s2^2/(2 s1^2))^(-3/2)):")
for N, trial in ((8, 2.9490455456), (12, 2.9773546098), (16, 2.9872343557)):
    s2 = 0.15 / N
    pred = ((1 / y6) * (1 + s2**2 / (2 * s16**2)) ** -1.5 - 1) / 3
    say(f"   N = {N:2d}: predicted {pred:.10f}, trial {trial:.10f}, difference {trial - pred:+.1e} (the grid's discreteness)")
say("   so the shortfall is the plums' width, not the grid; in the limit of point plums the rule gives 3 exactly.")
say("   C6b by my own geometry (uniform ball y = 1/2, equal plums at the grid sites inside, s2 = 0.05/N; the share of each plum's")
say("   Gaussian inside the ball by a numerical radial integral, not the closed form):")
a6 = (3 / (8 * math.pi)) ** (1 / 3)
def share_inside_numeric(r0, a, s, nrad=2000):
    """share of a Gaussian (rms s per axis) centred at distance r0 from the ball's centre that lies inside radius a, by the
    radial integral of the Gaussian's spherical shell average: 4 pi r^2 <rho> dr with <rho>(r) = N(r,r0,s) averaged over angles."""
    r = np.linspace(0, a, nrad + 1)[1:]
    r0 = np.maximum(r0, 1e-12)[:, None]
    rr = r[None, :]
    # angular average of exp(-|r - r0|^2/2s^2) over the sphere of radius r: exp(-(r^2 + r0^2)/2s^2) sinh(r r0/s^2)/(r r0/s^2)
    xr = rr * r0 / s**2
    ang = np.exp(-(rr**2 + r0**2) / (2 * s**2) + np.abs(xr)) * (1 - np.exp(-2 * np.abs(xr))) / (2 * np.abs(xr))
    dens = (2 * math.pi * s**2) ** -1.5 * ang
    return np.trapezoid(4 * math.pi * rr**2 * dens, r, axis=1)
for N, trial in ((10, 0.33326204), (20, 0.32500579), (40, 0.33115117)):
    r = grid_sites(N, 0.5); r = r - np.round(r)
    d = np.linalg.norm(r, axis=1); r = r[d < a6]
    c = 1.0 / len(r)
    sig = 0.0
    s2b = 0.05 / N
    for R in itertools.product((-1, 0, 1), repeat=3):
        dist = np.linalg.norm(r - np.array(R, float), axis=1)
        deep = dist < a6 - 8 * s2b                       # whole Gaussian inside: share 1 (to 1e-14)
        edge = np.abs(dist - a6) <= 8 * s2b              # straddling the edge: numerical share
        sig += c * deep.sum()
        for a0 in range(0, int(edge.sum()), 4000):
            sig += c * share_inside_numeric(dist[edge][a0:a0 + 4000], a6, s2b).sum()
    sig /= (4 / 3) * math.pi * a6**3
    say(f"   N = {N:2d}: plums {len(r):6d}, sigma_at = {sig:.8f}, K_T = {(sig - 1)/3:.8f} (trial {trial:.8f}), /(1/3) - 1 = {(sig-1) - 1:+.3e}")
say("   what the plums' width costs: a plum at the edge keeps only part of its charge inside; the trial's post hoc reading stands.")
say("   Thomson's atom as the rigid-level limit: inside a uniform ball the field is linear, so a rigid shift of the plums changes")
say("   the force on each by the same amount per unit charge; to first order the bunch does not deform, and the rigid-level")
say("   stiffness is exact up to the neighbouring cells' field gradients (second order in the bunch's size over the spacing).")

# =============================================================================================== G. C7: the plasma dispersion
say("\nG. C7: the unheld case as a plasma. eps(w) = f + wq^2/(wr^2 - w^2) with wr = 0: eps = f - wq^2/w^2; k^2 = w^2 eps.")
W0 = 2 * math.pi / 100; f = 0.25; wrB = 10 * W0; wq2 = 0.75 * wrB**2
wp = math.sqrt(wq2 / f)
kap = math.sqrt(wq2 - f * W0**2)
say(f"   cutoff (plasma) frequency wp = sqrt(wq^2/f) = {wp:.5f} = {wp/W0:.3f} w0; the light at w0 is below it: evanescent, kappa = sqrt(wq^2 - f w0^2) = {kap:.4f} per cell")
say(f"   (trial: continuum 0.5432, measured 0.5368 between 5 and 20 cells). Over 3000 cells exp(-kappa 3000) = 10^{-kap*3000/math.log(10):.0f}: the 7.7e-11")
say("   measured is the scheme's numerical floor, not the evanescent tail. 'Does not pass' holds for light below wp; above wp the")
say("   unheld medium is transparent with eps < f (phase speed above the bare c/sqrt f), as any plasma. wp depends on the masses:")
say("   wp^2 = n q^2/(eps_b mu) with mu the reduced mass of the two levels; here it is case B's choice (wq^2 = 0.75 (10 w0)^2), i.e.")
say("   wp = 17.3 w0. For Aspden's quons the record's plasma frequency is 361 keV (continuum held) or 511 keV (both frames, U34);")
say("   under U44's masses a finer level's is higher still (3^k x 361 keV), so for all light below the hard X-ray range the claim holds.")
# the held case: light at c at low frequency, phase speed at w0
eps_held = f + wq2 / (wrB**2 - W0**2)
say(f"   held case (w_r = 10 w0): eps(w0) = {eps_held:.6f}, phase speed {1/math.sqrt(eps_held):.4f} (trial 3 case B: 0.9962).")

say(f"\n(run time {time.time() - T0:.0f} s)")