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

finer_grids_repro_copy.py

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


"""finer_grids.py - trial 4 of the charging-quons work (lock: papers/Lock_finer_grids_2026-11-12.md).

Doug's finer grids (12 November 2026, afternoon): below Aspden's quons sits a lattice of quons of opposite charge on a much
finer grid, perhaps several such levels, with the density open. Does such a grid hold the quons against light's sideways
push, at any density and with any number of levels, and how does it relate to Thomson's atom (section 8.5, row 6)?
A numerical check of derivations, not a candidate mechanism.
Units as in trials 1 and 2 (Gaussian lattice units): coarse spacing d = 1, quon charge q = 1, one quon per cell at the
origin, Coulomb energy 1/r. Stiffnesses are in units of the continuum's pull along the beam, 4 pi n q^2 = 4 pi.
Run: ~/aspden-review-venv/bin/python3 finer_grids.py > finer_grids_out.txt
"""
import itertools, math, time
import numpy as np
from scipy.special import erfc, erf

T_START = time.time()
TWO_PI = 2 * np.pi
CUT = 41.4                     # Fourier sums run until exp(-(s_a^2 + s_b^2) G^2 / 2) < exp(-41.4) = 1e-18
FAIL = []

def show(tag, text, val=""):
    print(f"  {tag:5s} {text:<96s} {val}")

def check(name, ok):
    if not ok:
        FAIL.append(name)
    return "pass" if ok else "MISS"

# ------------------------------------------------------------------ levels
def grid(N, off):
    ax = (np.arange(N) + off) / N
    return np.array(list(itertools.product(ax, ax, ax)))          # same order as c.ravel() for c[i, j, l]

def level(N, off, c, s, name):
    """A level: N sites per spacing (N^3 per cell) at ((i, j, l) + off)/N, charges c[i, j, l], Gaussian rms width s."""
    c = np.asarray(c, float).reshape(N, N, N)
    return dict(N=N, off=off, c=c, s=s, name=name, fft=np.fft.fftn(c), pos=grid(N, off))

def quon(s1):
    return level(1, 0.0, [1.0], s1, "quon")

def even(N, off, total, s, name):
    return level(N, off, np.full((N, N, N), total / N**3), s, name)

# ------------------------------------------------------------------ the Fourier path
def rho_G(L, hh, G2):
    """Fourier coefficient per cell of a level's density at G = 2 pi hh (hh integer rows)."""
    N = L["N"]
    S = L["fft"][hh[:, 0] % N, hh[:, 1] % N, hh[:, 2] % N]        # sum_m c[m] exp(-2 pi i m.h/N)
    phase = np.exp(-2j * np.pi * L["off"] * hh.sum(1) / N)
    return np.exp(-L["s"] ** 2 * G2 / 2) * phase * S

def K_fourier(A, Bs):
    """Stiffness tensor (units 4 pi n q^2) between level A and the levels Bs moving together, in a long sideways wave:
    K = -sum_{G != 0} Re[rho_A(G) rho_B(G)*] G G^T / G^2, with rho_B the sum over Bs."""
    smin = min(math.sqrt(A["s"] ** 2 + B["s"] ** 2) for B in Bs)
    H = int(math.ceil(math.sqrt(2 * CUT) / smin / TWO_PI)) + 1
    h = np.arange(-H, H + 1)
    h2, h3 = (x.ravel() for x in np.meshgrid(h, h, indexing="ij"))
    K = np.zeros((3, 3))
    for h1 in h:
        hh = np.stack([np.full_like(h2, h1), h2, h3], 1)
        G = TWO_PI * hh
        G2 = np.einsum("ni,ni->n", G, G)
        m = G2 > 0
        hh, G, G2 = hh[m], G[m], G2[m]
        ra = rho_G(A, hh, G2)
        rb = sum(rho_G(B, hh, G2) for B in Bs)
        w = np.real(ra * np.conj(rb)) / G2
        K -= np.einsum("n,ni,nj->ij", w, G, G)
    return K, H

# ------------------------------------------------------------------ the real-space path
IMG = np.array(list(itertools.product(range(-2, 3), repeat=3)), float)     # the 125 nearest cells

def overlap(A, B):
    """Integral over one cell of rho_A rho_B for Gaussian charges: sum_i sum_j sum_R c_i c_j g(r_i - r_j - R)."""
    ca, cb = A["c"].ravel(), B["c"].ravel()
    s2 = A["s"] ** 2 + B["s"] ** 2
    norm = (2 * np.pi * s2) ** -1.5
    tot = 0.0
    for R in IMG:
        d = A["pos"][:, None, :] - B["pos"][None, :, :] - R
        tot += ca @ (norm * np.exp(-np.einsum("ijk,ijk->ij", d, d) / (2 * s2))) @ cb
    return tot

def trace_rule(A, Bs):
    """Trace of the stiffness (units 4 pi n q^2) by the real-space path: sum over Bs of Q_A Q_B - integral rho_A rho_B."""
    QA = A["c"].sum()
    return sum(QA * B["c"].sum() - overlap(A, B) for B in Bs)

def sigma_at(A, Bs):
    """The finer levels' net opposite charge density averaged over the quon's charge (the quon has charge +1)."""
    return -sum(overlap(A, B) for B in Bs)

WORST_C1 = [0.0, 0.0]
def rigid_case(A, Bs):
    """K_T by both paths; records the C1 disagreements. Returns (K_T Fourier, (sigma_at - sigma_avg)/3 real, H)."""
    K, H = K_fourier(A, Bs)
    tr = trace_rule(A, Bs)
    d = np.diag(K)
    iso = max(np.max(d) - np.min(d), np.max(np.abs(K - np.diag(d))))
    WORST_C1[0] = max(WORST_C1[0], iso)
    WORST_C1[1] = max(WORST_C1[1], abs(d.mean() - tr / 3))
    return d.mean(), tr / 3, H, iso

print("Trial 4: Doug's finer grids, at any density and with any number of levels (lock: papers/Lock_finer_grids_2026-11-12.md)")
print("Units: spacing d = 1, quon charge q = 1, Coulomb energy 1/r; stiffness in units of 4 pi n q^2 (the continuum's pull")
print("along the beam). Light at c with f = 1/4 needs K_T = f/(1 - f) = 1/3.")

# ------------------------------------------------------------------ C2
print("\nC2  An even finer grid around a quon wider than its spacing (s1 = 0.8/N, s2 = 0.3/N, s3 = 0.3/(2N)), several densities")
print("       N    k   placement   K_T (Fourier)      (sig_at - sig_avg)/3 (real)   |difference|   isotropy    H")
worst2 = 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(N, off, -k, 0.3 / N, "level 2")]
            if k > 1:
                Bs.append(even(2 * N, 0.5, k - 1, 0.3 / (2 * N), "level 3"))
            kt, kr, H, iso = rigid_case(A, Bs)
            worst2 = max(worst2, abs(kt))
            print(f"     {N:3d} {k:4d}   {pl:8s}  {kt:+.6e}      {kr:+.6e}                  {abs(kt-kr):.1e}      {iso:.1e}   {H}")
show("C2", "largest |K_T| (expected below 1e-3; f = 1/4 needs 1/3)", f"{worst2:.2e}  {check('C2', worst2 < 1e-3)}")

# ------------------------------------------------------------------ C3
print("\nC3  A narrow quon in an even finer grid (s1 = 0.05/N, s2 = 0.1/N, s3 = 0.05/N)")
print("       N    k   placement   K_T (Fourier)      (sig_at - sig_avg)/3 (real)   sigma_at        H")
worst3 = 0.0
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(N, off, -k, 0.1 / N, "level 2")]
            if k > 1:
                Bs.append(even(2 * N, 0.5, k - 1, 0.05 / N, "level 3"))
            kt, kr, H, iso = rigid_case(A, Bs)
            if pl == "between":
                worst3 = max(worst3, abs(kt + 1 / 3))
            print(f"     {N:3d} {k:4d}   {pl:8s}  {kt:+.6e}      {kr:+.6e}                  {sigma_at(A, Bs):.6e}   {H}")
show("C3", "'between': largest |K_T + 1/3| (expected below 1e-4: Earnshaw's case, row 2)", f"{worst3:.2e}  {check('C3', worst3 < 1e-4)}")
print("     The crossover (reported only): N = 4, k = 1, s2 = 0.1/N; K_T against the quon's width s1 in units of the finer spacing")
print("     s1*N     K_T between      K_T on")
for sN in (0.05, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.8, 1.0):
    row = []
    for off in (0.5, 0.0):
        A = quon(sN / 4)
        kt, kr, H, iso = rigid_case(A, [even(4, off, -1.0, 0.1 / 4, "level 2")])
        row.append(kt)
    print(f"     {sN:4.2f}   {row[0]:+.6e}   {row[1]:+.6e}")

# ------------------------------------------------------------------ C4
print("\nC4  A bunched finer grid for f = 1/4 at several densities (N = 8, s1 = 0.1, s2 = 0.3/8, 'between'; level 3 even, s3 = 0.3/16)")
def bunched(N, k, beta, w=0.2, s=0.3 / 8, off=0.5):
    r = grid(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(N, off, -k * wts / wts.sum(), s, "level 2 (bunched)")

print("        k   beta              level 2 at the quon / its average   1 + 1/k     K_T (Fourier)     K_T (real)      K_23 (Fourier, real)")
worst4a, worst4b = 0.0, 0.0
for k in (1, 4, 16):
    A = quon(0.1)
    L3 = [even(16, 0.5, k - 1, 0.3 / 16, "level 3")] if k > 1 else []
    s3at = sum(overlap(A, B) for B in L3)                    # level 3's density at the quon (same sign as the quon)
    def excess(beta):
        return -overlap(A, bunched(8, k, beta)) - s3at - 1.0  # net opposite density at the quon minus its average
    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)
    ratio = -overlap(A, L2) / k
    kt, kr, H, iso = rigid_case(A, [L2] + L3)
    worst4a = max(worst4a, abs(kt - 1 / 3))
    worst4b = max(worst4b, abs(ratio - (1 + 1 / k)))
    k23 = ""
    if L3:
        K23, H23 = K_fourier(L2, L3)
        k23 = f"{np.mean(np.diag(K23)):+.3e}, {trace_rule(L2, L3) / 3:+.3e}"
    print(f"     {k:4d}   {beta:.10f}    {ratio:.8f}                       {1 + 1/k:.6f}    {kt:.10f}    {kr:.10f}    {k23}")
show("C4", "largest |K_T - 1/3| (Fourier path; expected below 1e-8)", f"{worst4a:.2e}  {check('C4a', worst4a < 1e-8)}")
show("", "largest |level 2 at the quon / its average - (1 + 1/k)| (expected below 1e-3)", f"{worst4b:.2e}  {check('C4b', worst4b < 1e-3)}")

# ------------------------------------------------------------------ C6a
print("\nC6a Thomson's atom from a finer grid: a Gaussian quon of effective volume y = 8 pi^1.5 s1^3 = 0.1, the finer charges")
print("    in proportion to the quon's density at each site (total -1), s2 = 0.15/N; expected K_T within 3% of (1/y - 1)/3 = 3")
y6 = 0.1
s16 = (y6 / (8 * math.pi ** 1.5)) ** (1 / 3)
print(f"     s1 = {s16:.6f}; overlap of neighbouring quons' charges ~ exp(-1/(4 s1^2)) = {math.exp(-1/(4*s16*s16)):.1e}")
print("       N   K_T (Fourier)     K_T (real)      / 3 - 1")
worst6a, prev = 0.0, None
mono = True
for N in (8, 12, 16):
    r = grid(N, 0.5)
    dens = sum(np.exp(-np.sum((r - np.array(R, float)) ** 2, 1) / (2 * s16 * s16)) for R in itertools.product((-1, 0, 1), repeat=3))
    L2 = level(N, 0.5, -dens / dens.sum(), 0.15 / N, "plums")
    A = quon(s16)
    kt, kr, H, iso = rigid_case(A, [L2])
    dev = kt / 3 - 1
    worst6a = max(worst6a, abs(dev))
    if prev is not None and abs(dev) >= abs(prev):
        mono = False
    prev = dev
    print(f"     {N:3d}   {kt:.10f}    {kr:.10f}    {dev:+.3e}")
show("C6a", "largest |K_T/3 - 1| (expected below 0.03, falling with N)", f"{worst6a:.2e}  {check('C6a', worst6a < 0.03 and mono)}")

# ------------------------------------------------------------------ C6b
print("\nC6b Thomson's atom from a finer grid: the quon's charge a uniform ball of radius a (y = 1/2), the finer charges at the")
print("    grid sites inside it, equal, total -1, s2 = 0.05/N (real-space path); expected K_T near (1/y - 1)/3 = 1/3")
a6 = (3 / (8 * math.pi)) ** (1 / 3)
def p_ball(r0, a, s):
    """Share of a 3D Gaussian (rms s per axis, centred r0 from the ball's centre) inside a ball of radius a."""
    r0 = np.maximum(r0, 1e-12)
    t1 = 0.5 * (erf((a - r0) / (math.sqrt(2) * s)) + erf((a + r0) / (math.sqrt(2) * s)))
    t2 = s / (r0 * math.sqrt(2 * math.pi)) * (np.exp(-(a - r0) ** 2 / (2 * s * s)) - np.exp(-(a + r0) ** 2 / (2 * s * s)))
    return t1 - t2
print(f"     a = {a6:.6f}")
print("       N   plums    sigma_at        K_T            / (1/3) - 1")
res6b = {}
for N in (10, 20, 40):
    r = grid(N, 0.5)
    r = r - np.round(r)                                   # nearest image of each site
    r = r[np.linalg.norm(r, axis=1) < a6]
    c = np.full(len(r), 1.0 / len(r))
    sig = 0.0
    for R in itertools.product((-1, 0, 1), repeat=3):
        sig += np.sum(c * p_ball(np.linalg.norm(r - np.array(R, float), axis=1), a6, 0.05 / N))
    sig /= (4 / 3) * math.pi * a6 ** 3
    kt = (sig - 1) / 3
    res6b[N] = kt * 3 - 1
    print(f"     {N:3d}  {len(r):6d}   {sig:.8f}    {kt:.8f}     {kt*3 - 1:+.3e}")
ok6b = abs(res6b[10]) < 0.05 and abs(res6b[40]) < 0.02
show("C6b", "|K_T/(1/3) - 1| at N = 10 (expected below 0.05) and N = 40 (below 0.02)",
     f"{abs(res6b[10]):.2e}, {abs(res6b[40]):.2e}  {check('C6b', ok6b)}")

show("C1", "largest isotropy defect of K (diagonal spread, off-diagonal), expected below 1e-9",
     f"{WORST_C1[0]:.2e}  {check('C1a', WORST_C1[0] < 1e-9)}")
show("", "largest |K_T(Fourier) - (sig_at - sig_avg)/3 (real)|, expected below 1e-8",
     f"{WORST_C1[1]:.2e}  {check('C1b', WORST_C1[1] < 1e-8)}")

# ------------------------------------------------------------------ C5
print("\nC5  The stack obeys Earnshaw: all quons free, point charges, Ewald sums (real cells within +-4, reciprocal within +-6)")
# copied from relay_stiffness.py (itself copied unchanged from lattice_dynamics.py)
def hess_short(Rv, eta):
    """d_a d_b [erfc(eta r)/r] at each vector (array n x 3 x 3)."""
    r = np.linalg.norm(Rv, axis=1)
    ex = np.exp(-(eta * r) ** 2) * 2 * eta / math.sqrt(math.pi)
    f1 = -erfc(eta * r) / r**2 - ex / r                       # f'
    f2 = 2 * erfc(eta * r) / r**3 + ex * (2 / r**2 + 2 * eta**2)  # f''
    xx = np.einsum('ni,nj->nij', Rv, Rv) / r[:, None, None] ** 2
    return (f2 - f1 / r)[:, None, None] * xx + (f1 / r)[:, None, None] * np.eye(3)

RL = np.array(list(itertools.product(range(-4, 5), repeat=3)), float)
GL = TWO_PI * np.array(list(itertools.product(range(-6, 7), repeat=3)), float)
RL0 = RL[np.any(RL != 0, axis=1)]

def T_block(rij, k, eta, same):
    """T(k) = sum'_R exp(i k.R) d_a d_b (1/r) at r = rij - R, by Ewald; same: the R = 0 term excluded (i = j);
    the k + G = 0 term omitted."""
    Rl = RL0 if same else RL
    real = np.einsum("n,nij->ij", np.exp(1j * (Rl @ k)), hess_short(rij[None, :] - Rl, eta))
    K = GL + k
    K2 = np.einsum("ni,ni->n", K, K)
    m = K2 > 1e-14
    K, K2 = K[m], K2[m]
    rec = -4 * np.pi * np.einsum("n,ni,nj->ij", np.exp(-K2 / (4 * eta**2)) / K2 * np.exp(1j * (K @ rij)), K, K)
    T = real + rec
    if same:
        T = T + 4 * eta**3 / (3 * math.sqrt(math.pi)) * np.eye(3)
    return T

def phi_matrix(pos, q, k, eta, onsite):
    n = len(pos)
    P = np.zeros((3 * n, 3 * n), complex)
    for i in range(n):
        for j in range(n):
            P[3*i:3*i+3, 3*j:3*j+3] = -q[i] * q[j] * T_block(pos[i] - pos[j], k, eta, i == j)
        P[3*i:3*i+3, 3*i:3*i+3] += onsite[i]
    return P

def onsite_terms(pos, q, eta):
    z = np.zeros(3)
    return [sum(q[i] * q[l] * T_block(pos[i] - pos[l], z, eta, i == l) for l in range(len(pos))) for i in range(len(pos))]

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)))
stacks = {
    "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)])),
}
kpts = {"(1e-3,0,0)": (1e-3, 0, 0), "X": (np.pi, 0, 0), "M": (np.pi, np.pi, 0), "R": (np.pi, np.pi, np.pi),
        "(0.3,0.7,1.1)": (0.3, 0.7, 1.1)}
worst5a, worst5c, all_neg = 0.0, 0.0, True
for name, (pos, q) in stacks.items():
    print(f"     stack {name}: {len(pos)} quons per cell, total charge {q.sum():+.1e}")
    print("       k               Tr(Phi)/sum|lam|   lowest lam      highest lam     negatives/{0}   eta-independence".format(3 * len(pos)))
    ons = {eta: onsite_terms(pos, q, eta) for eta in (2.0, 2.6)}
    for kn, kv in kpts.items():
        kv = np.array(kv, float)
        lam = {}
        for eta in (2.0, 2.6):
            P = phi_matrix(pos, q, kv, eta, ons[eta])
            herm = np.max(np.abs(P - P.conj().T))
            lam[eta] = np.linalg.eigvalsh(0.5 * (P + P.conj().T))
            if eta == 2.0:
                trP = np.trace(P).real
        S = np.sum(np.abs(lam[2.0]))
        ratio = abs(trP) / S
        dl = np.max(np.abs(lam[2.0] - lam[2.6])) / S
        worst5a = max(worst5a, ratio)
        worst5c = max(worst5c, dl)
        neg = int(np.sum(lam[2.0] < -1e-9 * S))
        all_neg &= lam[2.0][0] < 0
        print(f"       {kn:14s}  {ratio:.2e}          {lam[2.0][0]:+.6e}   {lam[2.0][-1]:+.6e}   {neg:4d}            {dl:.1e}   (Hermitian to {herm:.0e})")
show("C5", "largest |Tr Phi| / sum|lambda| (expected below 1e-8)", f"{worst5a:.2e}  {check('C5a', worst5a < 1e-8)}")
show("", "lowest eigenvalue negative at every k, both stacks", f"{all_neg}  {check('C5b', all_neg)}")
show("", "largest eigenvalue change between eta = 2.0 and 2.6, / sum|lambda| (expected below 1e-8)",
     f"{worst5c:.2e}  {check('C5c', worst5c < 1e-8)}")

# ------------------------------------------------------------------ C7
print("\nC7  In time, all four of Maxwell's equations (trial 3's scheme, copied from relay_in_time.py): case B's light and quons,")
print("    held (w_r = 10 w0) and unheld (w_r = 0, an even grid's relative mode: no stiffness)")
W0 = 2 * np.pi / 100
SIG, T0, TEND = 500.0, 3000.0, 20000.0
JL, JR = -10000, 20000

def run_time(f, wr, wq2, probes=(5, 20, 3000)):
    eb = f
    dt = 0.5 * math.sqrt(f)
    N = JR - JL + 1; j0 = -JL
    idx = [j0 + p for p in probes]
    E = np.zeros(N); B = np.zeros(N - 1); P = np.zeros(N); Pm = np.zeros(N)
    nsteps = int(math.ceil(TEND / dt))
    peak = np.zeros(len(probes))
    for n in range(nsteps):
        Bn = B - dt * (E[1:] - E[:-1])                                   # Faraday, B at n+1/2
        Pn = 2 * P - Pm + dt * dt * (wq2 * E - wr * wr * P)              # the quons' law of motion
        En = E.copy()
        En[1:-1] = E[1:-1] - (dt / eb) * (Bn[1:] - Bn[:-1]) - (Pn[1:-1] - P[1:-1]) / eb   # Ampere-Maxwell
        ts = (n + 0.5) * dt
        En[j0] -= (dt / eb) * math.exp(-(ts - T0) ** 2 / (2 * SIG**2)) * math.sin(W0 * ts)
        En[0] = En[-1] = 0.0
        peak = np.maximum(peak, np.abs(E[idx]))
        Pm, P, E, B = P, Pn, En, Bn
    return peak

wr_B = 10 * W0
held = run_time(0.25, wr_B, 0.75 * wr_B**2)
unheld = run_time(0.25, 0.0, 0.75 * wr_B**2)
print("       probe (cells from the source)    held: largest |E|     unheld: largest |E|")
for p, a, b in zip((5, 20, 3000), held, unheld):
    print(f"       {p:6d}                           {a:.6e}          {b:.6e}")
kap = math.log(unheld[0] / unheld[1]) / 15
print(f"       unheld decay rate between 5 and 20 cells: {kap:.4f} per cell (continuum plasma value "
      f"{math.sqrt(0.75 * wr_B**2 - 0.25 * W0**2):.4f})")
r7 = unheld[2] / held[2]
show("C7", "unheld / held largest |E| at 3000 cells (expected below 1e-6: the light does not pass)",
     f"{r7:.2e}  {check('C7', r7 < 1e-6)}")

print(f"\nPass criteria: {'all met' if not FAIL else 'NOT MET: ' + ', '.join(FAIL)}   (run time {time.time() - T_START:.0f} s)")