Does light charge the quons? › Files cited on the page › the trials
reflection_grid.py
"""reflection_grid.py - trial 5 of the charging-quons work (lock: papers/Lock_reflection_grid_2026-11-12.md).
Doug (12 November 2026, evening): the finer quons "have to be a smaller reflection of the larger quon lattice, so it has
to fill all space at a smaller grid". Where does each quon come to rest in such an even grid, how strongly is it held
there against light's long sideways wave, can the grid itself stay even under electric forces alone, and what does it do
in time? A numerical check of derivations, not a candidate mechanism.
Units as in trials 1, 2 and 4 (Gaussian lattice units): coarse spacing d = 1, quon charge q = 1, one quon per cell at the
origin, Coulomb energy 1/r. Stiffnesses K_T are in units of the continuum's pull along the beam, 4 pi n q^2 = 4 pi; the
force-constant matrices of R3 and R4 are in absolute units (energy per length squared).
Run: ~/aspden-review-venv/bin/python3 reflection_grid.py > reflection_grid_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 = []
B_ASPDEN = 0.036135562 # Aspden's quon radius b/d (aether_units.py U05)
SC_MIN = 0.0927 # least hold for a stable simple cubic lattice (trial 2, C4: lowest eigenvalue at M, -0.09269)
A_HALF = (3 / (8 * math.pi)) ** (1 / 3) # ball radius, in finer spacings, that fills half a finer cell (0.492373)
A_ONE = (3 / (4 * math.pi)) ** (1 / 3) # ball radius, in finer spacings, that fills one finer cell (0.620350)
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"
# ------------------------------------------------------------------ copied from finer_grids.py (trial 4)
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)
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
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 rigid_case(A, Bs):
"""K_T by both paths: (K_T Fourier, (sigma_at - sigma_avg)/3 real, H, isotropy defect)."""
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))))
return d.mean(), tr / 3, H, iso
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
# ------------------------------------------------------------------ closed forms (D1, D2)
def theta(x, alt):
"""Jacobi's theta3(x) = sum_n x^(n^2) (alt False) or theta4(x) = sum_n (-1)^n x^(n^2) (alt True)."""
s, n = 1.0, 1
while True:
t = x ** (n * n)
if t < 1e-22:
return s
s += 2 * t * ((-1) ** n if alt else 1)
n += 1
def KT_on(NS, k=1.0):
return k / 3 * (theta(math.exp(-2 * math.pi**2 * NS**2), False) ** 3 - 1)
def KT_between(NS, k=1.0):
return k / 3 * (theta(math.exp(-2 * math.pi**2 * NS**2), True) ** 3 - 1)
def KT_ball_point(aN):
"""D2: a uniform ball (radius a) holding only its own point-like finer quon (aN < 1), k = 1."""
yf = 4 * math.pi / 3 * aN**3
return (1 / yf - 1) / 3, yf
def F_ball(x):
return 3 * (np.sin(x) - x * np.cos(x)) / x**3
def mvecs(M):
h = np.arange(-M, M + 1)
m = np.array(list(itertools.product(h, h, h)), float)
return m[np.any(m != 0, axis=1)]
print("Trial 5: Doug's finer grid as a smaller copy of the quon lattice, filling all space "
"(lock: papers/Lock_reflection_grid_2026-11-12.md)")
print("Units: spacing d = 1, quon charge q = 1, Coulomb energy 1/r; K_T 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; the quons carry 1/(1 + K_T) of light.")
# ------------------------------------------------------------------ R2a first (R1 and R3 use N*S*)
print("\nR2a The hold on a finer quon, Gaussian charges (k = 1, s2 = 0.1/N): two paths and the theta-function closed form")
print(" N N*S K_T (Fourier) K_T (real) closed form |F - c| |r - c| isotropy H")
w2f, w2r = 0.0, 0.0
for N in (4, 8):
for NS in (0.1, 0.2, 0.3, 0.4, 0.5, 0.6):
s2 = 0.1 / N
s1 = math.sqrt(max(NS**2 - 0.01, 0.0)) / N
kt, kr, H, iso = rigid_case(quon(s1), [even(N, 0.0, -1.0, s2, "level 2")])
kc = KT_on(NS)
w2f, w2r = max(w2f, abs(kt - kc)), max(w2r, abs(kr - kc))
print(f" {N:3d} {NS:4.2f} {kt:+.12e} {kr:+.12e} {kc:+.12e} {abs(kt-kc):.1e} {abs(kr-kc):.1e} {iso:.1e} {H}")
show("R2a", "largest |Fourier - closed form| and |real - closed form| (expected below 1e-8)",
f"{w2f:.1e}, {w2r:.1e} {check('R2a paths', w2f < 1e-8 and w2r < 1e-8)}")
lo, hi = 0.2, 0.5
for _ in range(200):
mid = 0.5 * (lo + hi)
if KT_on(mid) > 1 / 3:
lo = mid
else:
hi = mid
NSS = 0.5 * (lo + hi)
show("", "N*S* where K_T = 1/3 (f = 1/4), by bisection on the closed form (expected 0.3217 to 1e-4)",
f"{NSS:.8f} {check('R2a N*S*', abs(NSS - 0.3217) < 1e-4)}")
print(f" for comparison, between finer quons at N*S*: K_T = {KT_between(NSS):+.6f}; the partner alone, "
f"((2 pi (N S*)^2)^-1.5 - 1)/3 = {((2*math.pi*NSS**2)**-1.5 - 1)/3:+.6f}")
# ------------------------------------------------------------------ R1
print("\nR1 Where the quon rests: E(u) - E(0) on the offsets u = (i, j, l)/(16N), 0 <= i <= j <= l <= 8 (k = 1, N = 4)")
N1 = 4
wedge = np.array([(i, j, l) for i in range(9) for j in range(i, 9) for l in range(j, 9)], float)
def dE_scan(coef, m):
"""E(u) - E(0) = (k/(pi N^2)) sum_m coef_m (1 - cos(2 pi m.n/16)) at each wedge offset n (k = 1)."""
out = np.empty(len(wedge))
for t, n in enumerate(wedge):
out[t] = np.sum(coef * (1 - np.cos(TWO_PI * (m @ n) / 16)))
return out / (math.pi * N1**2)
r1_ok = True
cases = [("Gaussian", 0.1, None), ("Gaussian", 0.3217, None), ("Gaussian", 1.0, None),
("ball", None, A_HALF), ("ball", None, 14 * B_ASPDEN), ("ball", None, 0.8)]
print(" shape N*S or a*N lowest E(u)-E(0) at u != 0 at offset (i,j,l) at the cube centre expected")
for shape, NS, aN in cases:
if shape == "Gaussian":
M = int(math.ceil(math.sqrt(CUT / (2 * math.pi**2 * NS**2)))) + 1
m = mvecs(M)
mm2 = np.einsum("ni,ni->n", m, m)
coef = np.exp(-2 * math.pi**2 * NS**2 * mm2) / mm2
par = NS
else:
s2N = 0.05
M = int(math.ceil(math.sqrt(CUT / (2 * math.pi**2 * s2N**2)))) + 1
m = mvecs(M)
mm2 = np.einsum("ni,ni->n", m, m)
coef = F_ball(TWO_PI * np.sqrt(mm2) * aN) * np.exp(-2 * math.pi**2 * s2N**2 * mm2) / mm2
par = aN
dE = dE_scan(coef, m)
nz = np.any(wedge != 0, axis=1)
t = np.argmin(np.where(nz, dE, np.inf))
lowest, at = dE[t], tuple(int(x) for x in wedge[t])
centre = dE[-1]
if shape == "ball" and aN == 0.8:
exp_txt = "reported"
tg = np.argmin(dE)
print(f" {shape:9s} {par:.4f} {lowest:+.6e} {str(at):16s} {centre:+.6e} {exp_txt}"
f" (global minimum {dE[tg]:+.3e} at {tuple(int(x) for x in wedge[tg])})")
continue
ok = lowest > 0
r1_ok &= ok
print(f" {shape:9s} {par:.4f} {lowest:+.6e} {str(at):16s} {centre:+.6e} > 0: {ok}")
show("R1", "the lowest energy at u = 0 (on a finer quon) in every predicted case", f"{check('R1', r1_ok)}")
# ------------------------------------------------------------------ R2b
print("\nR2b The hold on a finer quon, the quon's charge a uniform ball (k = 1, N = 4, finer quons Gaussian, s2 = 0.02/N)")
print(" a*N y_f K_T (real) K_T (Fourier) |r - F| point formula (1/y_f - 1)/3 rel. dev.")
N2 = 4
s2N = 0.02
fin = grid(N2, 0.0)
w2b_paths, w2b_point, signs = 0.0, 0.0, []
def KT_ball_fourier(aN):
M = int(math.ceil(math.sqrt(CUT / (2 * math.pi**2 * s2N**2)))) + 1
h = np.arange(-M, M + 1)
h2, h3 = (x.ravel() for x in np.meshgrid(h, h, indexing="ij"))
tot = 0.0
for h1 in h:
m2 = (h1 * h1 + h2 * h2 + h3 * h3).astype(float)
m2 = m2[m2 > 0]
x = TWO_PI * np.sqrt(m2) * aN
tot += np.sum(F_ball(x) * np.exp(-2 * math.pi**2 * s2N**2 * m2))
return tot / 3
for aN in (0.1, 0.2, 0.3, 0.4, A_HALF, 0.55, 0.6, 0.65, 0.7, 0.8, 0.9, 1.1, 1.3, 1.5):
a = aN / N2
vb = 4 * math.pi / 3 * a**3
sig = 0.0
for R in itertools.product((-1, 0, 1), repeat=3):
sig += np.sum(p_ball(np.linalg.norm(fin - np.array(R, float), axis=1), a, s2N / N2)) / N2**3
sig /= vb
kr = (sig - 1) / 3
kf = KT_ball_fourier(aN)
w2b_paths = max(w2b_paths, abs(kr - kf))
signs.append((aN, kr))
if aN < 1:
kp, yf = KT_ball_point(aN)
dev = abs(kr / kp - 1)
w2b_point = max(w2b_point, dev)
print(f" {aN:.4f} {yf:.6f} {kr:+.12e} {kf:+.12e} {abs(kr-kf):.1e} {kp:+.12e} {dev:.1e}")
else:
print(f" {aN:.4f} {4*math.pi/3*aN**3:.6f} {kr:+.12e} {kf:+.12e} {abs(kr-kf):.1e} (more than one finer quon inside)")
show("R2b", "largest |real - Fourier| (expected below 1e-8)", f"{w2b_paths:.1e} {check('R2b paths', w2b_paths < 1e-8)}")
show("", "largest relative deviation from (1/y_f - 1)/3 for a*N < 1 (expected below 1e-4)",
f"{w2b_point:.1e} {check('R2b point', w2b_point < 1e-4)}")
chg = [(signs[i][0], signs[i + 1][0]) for i in range(len(signs) - 1) if signs[i][1] * signs[i + 1][1] < 0]
print(f" K_T changes sign between a*N = {', '.join(f'{x:.4f} and {y:.4f}' for x, y in chg)}; "
f"the point formula gives zero at a*N = {A_ONE:.6f} (the ball fills one finer cell)")
# ------------------------------------------------------------------ R2c
print("\nR2c Aspden's quon radius b/d = 0.036135562 (U05) on a grid N times finer, k = 1, the quon's charge filling its ball")
print(" N a*N y_f K_T quons' share of light simple cubic stable (K_T >= 0.0927)")
stable = []
for N in range(2, 21):
aN = N * B_ASPDEN
kp, yf = KT_ball_point(aN)
share = f"{1/(1+kp):.4f}" if kp > 0 else "none (pushed off)"
st = kp >= SC_MIN
if st:
stable.append(N)
print(f" {N:3d} {aN:.5f} {yf:.6f} {kp:+.6f} {share:22s} {st}")
Nstar = A_HALF / B_ASPDEN
print(f" N* = {A_HALF:.6f}/{B_ASPDEN} = {Nstar:.4f} (K_T = 1/3, f = 1/4); the hold is positive for N < "
f"{A_ONE/B_ASPDEN:.3f}")
ok2c = abs(Nstar - 13.6) < 0.1 and stable == list(range(2, 16))
show("R2c", "N* (expected 13.6 to 0.1); whole N with a stable simple cubic lattice and a positive hold (expected 2..15)",
f"{Nstar:.3f}; {stable[0]}..{stable[-1]} {check('R2c', ok2c)}")
# ------------------------------------------------------------------ R2d
print("\nR2d Out of register: the mean of K_T(u) over the 16^3 offsets of a finer cell (Gaussians, N = 4, N*S = 0.3217)")
M = int(math.ceil(math.sqrt(CUT / (2 * math.pi**2 * 0.3217**2)))) + 1
m = mvecs(M)
c = np.exp(-2 * math.pi**2 * 0.3217**2 * np.einsum("ni,ni->n", m, m)) / 3
offs = np.array(list(itertools.product(range(16), repeat=3)), float)
KTu = np.array([np.sum(c * np.cos(TWO_PI * (m @ n) / 16)) for n in offs])
show("R2d", "|mean K_T(u)| (expected below 1e-12); for comparison K_T at u = 0 and at the cube centre",
f"{abs(KTu.mean()):.1e} ({KTu[0]:+.6f}, {KTu[int(np.where((offs == 8).all(1))[0][0])]:+.6f}) "
f"{check('R2d', abs(KTu.mean()) < 1e-12)}")
# ------------------------------------------------------------------ the Gaussian-charge Ewald sums (R3, R4)
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)]
NSER = 12
def ser_coef(b, eta):
"""Taylor coefficients c_n of g(r) = [erf(r/b) - erf(eta r)]/r = sum_n c_n r^(2n)."""
n = np.arange(NSER + 1)
fact = np.array([math.factorial(int(i)) for i in n], float)
return 2 / math.sqrt(math.pi) * (-1.0) ** n / (fact * (2 * n + 1)) * (b ** -(2.0 * n + 1) - eta ** (2.0 * n + 1))
def g_val(r, b, eta):
r = np.asarray(r, float)
out = np.empty_like(r)
small = r < 0.3 * min(b, 1 / eta)
if np.any(small):
c = ser_coef(b, eta)
r2 = r[small] ** 2
out[small] = sum(c[n] * r2**n for n in range(NSER + 1))
big = ~small
if np.any(big):
rb = r[big]
out[big] = (erfc(eta * rb) - erfc(rb / b)) / rb
return out
def AB(r, b, eta):
"""For g(r) = [erf(r/b) - erf(eta r)]/r: A = (g'' - g'/r)/r^2 and B = g'/r, so that the Hessian is A r r^T + B I."""
r = np.asarray(r, float)
A = np.empty_like(r)
B = np.empty_like(r)
small = r < 0.3 * min(b, 1 / eta)
if np.any(small):
c = ser_coef(b, eta)
r2 = r[small] ** 2
B[small] = sum(2 * n * c[n] * r2 ** (n - 1) for n in range(1, NSER + 1))
A[small] = sum(4 * n * (n - 1) * c[n] * r2 ** (n - 2) for n in range(2, NSER + 1))
big = ~small
if np.any(big):
rb = r[big]
h = erfc(eta * rb) - erfc(rb / b)
e1, e2 = np.exp(-(rb / b) ** 2), np.exp(-(eta * rb) ** 2)
h1 = 2 / math.sqrt(math.pi) * (e1 / b - eta * e2)
h2 = 2 / math.sqrt(math.pi) * (-2 * rb / b**3 * e1 + 2 * eta**3 * rb * e2)
B[big] = h1 / rb**2 - h / rb**3
A[big] = (h2 / rb - 3 * h1 / rb**2 + 3 * h / rb**3) / rb**2
return A, B
def T_gauss(rij, k, eta, same, b):
"""T(k) = sum'_R exp(i k.R) d_a d_b [erf(r/b)/r] at r = rij - R (Gaussian charges), by an Ewald split; same: the
R = 0 term excluded (i = j); the k + G = 0 term omitted (as trial 4's T_block)."""
Rl = RL0 if same else RL
d = rij[None, :] - Rl
A, B = AB(np.linalg.norm(d, axis=1), b, eta)
H = A[:, None, None] * np.einsum("ni,nj->nij", d, d) + B[:, None, None] * np.eye(3)
real = np.einsum("n,nij->ij", np.exp(1j * (Rl @ k)), H)
K = GL + k
K2 = np.einsum("ni,ni->n", K, K)
msk = K2 > 1e-14
K, K2 = K[msk], K2[msk]
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 T_plain(rij, k, same, S2, Gp):
"""The same T(k) by a plain reciprocal sum of the Gaussian pair potential, no Ewald split: -4 pi sum_G
exp(-S2 K^2/2)/K^2 K K^T exp(i K.rij), K = G + k, K = 0 omitted; same: the R = 0 self term removed."""
K = Gp + k
K2 = np.einsum("ni,ni->n", K, K)
msk = K2 > 1e-14
K, K2 = K[msk], K2[msk]
T = -4 * np.pi * np.einsum("n,ni,nj->ij", np.exp(-S2 * K2 / 2) / K2 * np.exp(1j * (K @ rij)), K, K)
if same:
T = T + 4 * np.pi / 3 * (2 * np.pi * S2) ** -1.5 * np.eye(3)
return T
def phi_build(pos, q, s, k, Tfun):
"""Force-constant matrix: P_ij = -q_i q_j T_ij(k) + delta_ij sum_l q_i q_l T_il(0)."""
n = len(pos)
z = np.zeros(3)
P = np.zeros((3 * n, 3 * n), complex)
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] * Tfun(pos[i] - pos[j], k, i == j, s[i]**2 + s[j]**2)
ons += q[i] * q[j] * Tfun(pos[i] - pos[j], z, i == j, s[i]**2 + s[j]**2)
P[3*i:3*i+3, 3*i:3*i+3] += ons
return P
def trace_overlap(pos, q, s, k):
"""D4: 4 pi [sum_i q_i^2 sum_{R != 0} cos(k.R) rho_ii(R) - sum_i q_i sum'_{l,R} q_l rho_il(r_i - r_l - R)], less
4 pi sum_i q_i^2 at k = 0 exactly; returns the total and each charge's share."""
n = len(pos)
share = np.zeros(n)
for i in range(n):
for l in range(n):
S2 = s[i]**2 + s[l]**2
d = pos[i] - pos[l] - RL
g = (2 * np.pi * S2) ** -1.5 * np.exp(-np.einsum("ni,ni->n", d, d) / (2 * S2))
if i == l:
z0 = np.all(RL == 0, axis=1)
share[i] += q[i] ** 2 * np.sum(np.cos(RL[~z0] @ k) * g[~z0]) - q[i] * q[l] * np.sum(g[~z0])
else:
share[i] -= q[i] * q[l] * np.sum(g)
if np.all(k == 0):
share[i] -= q[i] ** 2
return 4 * np.pi * share.sum(), 4 * np.pi * share
def stack(N, NS):
"""The quon (index 0) on the even grid: finer quon j at (i, j, l)/N, index 1 is the one under the quon."""
s2 = 0.1 / N
s1 = math.sqrt((NS / N) ** 2 - s2**2)
pos = np.vstack([np.zeros((1, 3)), grid(N, 0.0)])
q = np.concatenate([[1.0], np.full(N**3, -1.0 / N**3)])
s = np.concatenate([[s1], np.full(N**3, s2)])
return pos, q, s
# ------------------------------------------------------------------ R4's Ewald energy and forces (written separately)
ETA_MD = 2.6
R2L = np.array(list(itertools.product(range(-2, 3), repeat=3)), float)
G5 = TWO_PI * np.array([v for v in itertools.product(range(-5, 6), repeat=3) if any(v)], float)
G5sq = np.einsum("ni,ni->n", G5, G5)
AG5 = np.exp(-G5sq / (4 * ETA_MD**2)) / G5sq
def energy_forces(pos, q, s, bonds=(), kappa=0.0):
"""Ewald energy (less constants) and forces for Gaussian charges in one periodic cell, plus springs [P]."""
n = len(pos)
E = 0.0
F = np.zeros((n, 3))
for i in range(n):
for j in range(i + 1, n):
b = math.sqrt(2 * (s[i]**2 + s[j]**2))
dij = pos[i] - pos[j]
dij = dij - np.round(dij)
d = dij[None, :] + R2L
r = np.linalg.norm(d, axis=1)
E += q[i] * q[j] * np.sum(g_val(r, b, ETA_MD))
A, B = AB(r, b, ETA_MD)
f = -q[i] * q[j] * np.sum(B[:, None] * d, axis=0)
F[i] += f
F[j] -= f
ph = np.exp(1j * (G5 @ pos.T)) # (nG, n)
S = ph @ q # S(G) = sum_j q_j exp(i G.r_j)
E += 2 * np.pi * np.sum(AG5 * np.abs(S) ** 2)
F += 4 * np.pi * q[:, None] * np.einsum("g,ga,gi->ia", AG5, G5, np.imag(ph * np.conj(S)[:, None]))
for a, bb, R, dv in bonds:
i, j = 1 + a, 1 + bb
d = pos[j] + R - pos[i]
L, L0 = np.linalg.norm(d), np.linalg.norm(dv)
E += 0.5 * kappa * (L - L0) ** 2
f = kappa * (L - L0) * d / L
F[i] += f
F[j] -= f
return E, F
def spring_bonds(N):
"""Nearest and next-nearest bonds of the finer grid: (a, b, R, dv) with site b + R = site a + dv."""
pos = grid(N, 0.0)
half = [np.array(v, float) / N for v in ((1, 0, 0), (0, 1, 0), (0, 0, 1), (1, 1, 0), (1, -1, 0), (1, 0, 1),
(1, 0, -1), (0, 1, 1), (0, 1, -1))]
bonds = []
for a, ra in enumerate(pos):
for dv in half:
rb = ra + dv
fr = rb - np.floor(rb + 1e-12)
bidx = int(np.argmin(np.linalg.norm(pos - fr, axis=1)))
bonds.append((a, bidx, np.round(rb - pos[bidx]), dv))
return bonds
def phi_springs(n, bonds, kappa, k):
P = np.zeros((3 * n, 3 * n), complex)
for a, bb, R, dv in bonds:
i, j = 1 + a, 1 + bb
e = dv / np.linalg.norm(dv)
D = kappa * np.outer(e, e)
P[3*i:3*i+3, 3*i:3*i+3] += D
P[3*j:3*j+3, 3*j:3*j+3] += D
P[3*i:3*i+3, 3*j:3*j+3] -= D * np.exp(1j * (k @ R))
P[3*j:3*j+3, 3*i:3*i+3] -= D * np.exp(-1j * (k @ R))
return P
# ------------------------------------------------------------------ R3: is the even grid at rest?
print("\nR3 The rest of the grid. Is the even grid at rest at all? Forces at the even arrangement (R4's Ewald code)")
print(" N largest |F| on a finer quon at site cosine with the way to the quon finer quons above 1e-6 of it"
" largest |F| at a centre of inversion / largest")
rest_ok = True
for N in (3, 4):
pos, q, s = stack(N, NSS)
E0, F0 = energy_forces(pos, q, s)
fn = np.linalg.norm(F0[1:], axis=1)
sites = pos[1:]
inv = np.all(np.abs(2 * sites - np.round(2 * sites)) < 1e-9, axis=1)
big = int(np.argmax(fn))
to_q = -(sites[big] - np.round(sites[big]))
cosv = F0[1 + big] @ to_q / (np.linalg.norm(F0[1 + big]) * np.linalg.norm(to_q))
near = abs(np.linalg.norm(to_q) - 1 / N) < 1e-9
inv_ratio = np.max(fn[inv]) / fn[big]
nabove = int(np.sum(fn > 1e-6 * fn[big]))
ok = inv_ratio < 1e-10 and near and cosv > 0.99
rest_ok &= ok
print(f" {N:3d} {fn[big]:.6e} {tuple(np.round(sites[big]*N).astype(int))} {cosv:+.6f}"
f" {nabove} of {N**3} ({int(np.sum(~inv))} not at a centre) {inv_ratio:.1e}")
show("R3", "force zero at the centres of inversion; the largest next to a quon, pointing at it", f"{check('R3 rest', rest_ok)}")
# ------------------------------------------------------------------ R3: stability where it is at rest (N = 2)
print(f"\nR3 Stability at N = 2 (every charge at a centre of inversion): s2 = 0.05, s1 = {math.sqrt((NSS/2)**2 - 0.05**2):.6f}"
" (K_T = 1/3); Ewald eta = 2.0, 2.6 and a plain reciprocal sum")
pos, q, s = stack(2, NSS)
n = len(pos)
S2min = 2 * 0.05**2
Hp = int(math.ceil(math.sqrt(2 * CUT / S2min) / TWO_PI)) + 1
Gp = TWO_PI * np.array(list(itertools.product(range(-Hp, Hp + 1), repeat=3)), float)
print(f" plain sum: reciprocal vectors within +-{Hp} per axis ({len(Gp)} vectors)")
Tf = {2.0: lambda r, k, same, S2: T_gauss(r, k, 2.0, same, math.sqrt(2 * S2)),
2.6: lambda r, k, same, S2: T_gauss(r, k, 2.6, same, math.sqrt(2 * S2)),
"plain": lambda r, k, same, S2: T_plain(r, k, same, S2, Gp)}
kpts = {"Gamma": (0, 0, 0), "(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)}
nonpartner = list(range(2, n))
w3i, w3ii, w3iii_tr, r3iii, r3iv = 0.0, 0.0, 0.0, True, True
PG = None
print(" k lowest lam highest lam negatives/27 eta 2.0 vs 2.6 vs plain trace identity"
" lowest of the non-partner blocks")
for kn, kv in kpts.items():
kv = np.array(kv, float)
Ps = {key: phi_build(pos, q, s, kv, f) for key, f in Tf.items()}
lam = {key: np.linalg.eigvalsh(0.5 * (P + P.conj().T)) for key, P in Ps.items()}
Ssum = np.sum(np.abs(lam[2.0]))
d_eta = np.max(np.abs(lam[2.0] - lam[2.6])) / Ssum
d_pl = np.max(np.abs(lam[2.0] - lam["plain"])) / Ssum
w3i = max(w3i, d_eta, d_pl)
trP = np.trace(Ps[2.0]).real
tro, shares = trace_overlap(pos, q, s, kv)
w3ii = max(w3ii, abs(trP - tro) / Ssum)
blk_low = []
for i in nonpartner:
Bi = Ps[2.0][3*i:3*i+3, 3*i:3*i+3]
w3iii_tr = max(w3iii_tr, abs(np.trace(Bi).real - shares[i]) / Ssum)
blk_low.append(np.linalg.eigvalsh(0.5 * (Bi + Bi.conj().T))[0])
if kn in ("X", "M", "(0.3,0.7,1.1)"):
r3iii &= max(blk_low) < 0
neg = int(np.sum(lam[2.0] < -1e-9 * Ssum))
r3iv &= lam[2.0][0] < 0
print(f" {kn:14s} {lam[2.0][0]:+.6e} {lam[2.0][-1]:+.6e} {neg:4d} {d_eta:.1e} {d_pl:.1e}"
f" {abs(trP - tro)/Ssum:.1e} {min(blk_low):+.3e} .. {max(blk_low):+.3e}")
if kn == "Gamma":
PG = Ps[2.6].real.copy()
cm_all = max(abs(np.tile(np.eye(3)[ax], n) @ Ps[2.0].real @ np.tile(np.eye(3)[ax], n)) for ax in range(3)) / Ssum
if kn == "(1e-3,0,0)":
pyy = Ps[2.0][1, 1].real
show("R3", "(i) eigenvalues: eta 2.0 vs 2.6 and vs the plain sum, / sum|lam| (expected below 1e-8)",
f"{w3i:.1e} {check('R3 i', w3i < 1e-8)}")
show("", "(ii) trace against the overlap formula, / sum|lam| (expected below 1e-8)", f"{w3ii:.1e} {check('R3 ii', w3ii < 1e-8)}")
show("", "(iii) non-partner blocks: trace = their share (/ sum|lam|), lowest eigenvalue negative at X, M, general",
f"{w3iii_tr:.1e}, {r3iii} {check('R3 iii', w3iii_tr < 1e-8 and r3iii)}")
show("", "(iv) the lowest eigenvalue of Phi negative at every k", f"{r3iv} {check('R3 iv', r3iv)}")
kt_c = KT_on(NSS)
rel5 = abs(pyy / (4 * np.pi * kt_c) - 1)
show("", f"(v) the quon's y-y entry at (1e-3,0,0) / (4 pi K_T = {4*np.pi*kt_c:.8f}) - 1 (expected below 1e-5)",
f"{rel5:.1e} {check('R3 v a', rel5 < 1e-5)}")
show("", " at Gamma, every charge moved the same way, / sum|lam| (expected below 1e-10)",
f"{cm_all:.1e} {check('R3 v b', cm_all < 1e-10)}")
# ------------------------------------------------------------------ R3b: springs keep the grid's shape [P]
print("\nR3b Springs between nearest and next-nearest finer neighbours (a stand-in for whatever keeps the grid's shape) [P]")
bonds = spring_bonds(2)
print(f" {len(bonds)} bonds per cell; lowest eigenvalue of Phi + springs at each k (eta = 2.6)")
print(" kappa " + " ".join(f"{kn:>13s}" for kn in kpts))
PE = {kn: phi_build(pos, q, s, np.array(kv, float), Tf[2.6]) for kn, kv in kpts.items()}
r3b_ok = True
for kappa in (0.0, 1.0, 10.0, 100.0, 1000.0):
row = []
for kn, kv in kpts.items():
P = PE[kn] + phi_springs(n, bonds, kappa, np.array(kv, float))
lam = np.linalg.eigvalsh(0.5 * (P + P.conj().T))
row.append(lam[0])
if kappa == 1000.0:
r3b_ok &= lam[0] > -1e-8 * np.sum(np.abs(lam))
print(f" {kappa:7.0f} " + " ".join(f"{x:+.6e}" for x in row))
U = np.zeros(3 * n)
U[3 + 1::3] = 1.0 # every finer quon moved along y, the quon not
spr_rig = abs(U @ phi_springs(n, bonds, 1000.0, np.zeros(3)).real @ U) / 1000.0
show("R3b", "at kappa = 1000: lowest eigenvalue above -1e-8 sum|lam| at every k", f"{r3b_ok} {check('R3b stable', r3b_ok)}")
show("", "springs' energy for the whole finer grid moved as one, / kappa (expected below 1e-12)",
f"{spr_rig:.1e} {check('R3b rigid', spr_rig < 1e-12)}")
# ------------------------------------------------------------------ R4: in time
print("\nR4 In time: the N = 2 stack in one periodic cell (k = 0 only), Ewald eta = 2.6, velocity Verlet, dt = 0.002;")
print(" masses: the quon 1, each finer quon 1/8 (in proportion to charge) [M]")
mass = np.concatenate([[1.0], np.full(8, 1 / 8)])
pos0 = pos.copy()
rng = np.random.default_rng(7)
xr = pos0 + 0.05 * rng.standard_normal(pos0.shape)
E_, F_ = energy_forces(xr, q, s)
h = 1e-5
Ffd = np.zeros_like(F_)
for i in range(n):
for a in range(3):
xp, xm = xr.copy(), xr.copy()
xp[i, a] += h
xm[i, a] -= h
Ffd[i, a] = -(energy_forces(xp, q, s)[0] - energy_forces(xm, q, s)[0]) / (2 * h)
rf = np.max(np.abs(Ffd - F_)) / np.max(np.abs(F_))
Hfd = np.zeros((3 * n, 3 * n))
for j in range(n):
for b_ in range(3):
xp, xm = pos0.copy(), pos0.copy()
xp[j, b_] += h
xm[j, b_] -= h
Hfd[:, 3 * j + b_] = -(energy_forces(xp, q, s)[1] - energy_forces(xm, q, s)[1]).ravel() / (2 * h)
rH = np.max(np.abs(Hfd - PG)) / np.max(np.abs(PG))
show("R4a", "forces vs finite differences of the energy, relative (expected below 1e-6)", f"{rf:.1e} {check('R4a F', rf < 1e-6)}")
show("", "Hessian by finite differences of the forces vs R3's Phi(Gamma), / largest entry (expected below 1e-5)",
f"{rH:.1e} {check('R4a H', rH < 1e-5)}")
Minv = np.repeat(1 / np.sqrt(mass), 3)
lmw = np.linalg.eigvalsh(Minv[:, None] * PG * Minv[None, :])
gam = math.sqrt(-lmw[0])
print(f" mass-weighted Phi(Gamma): lowest eigenvalue {lmw[0]:+.6e}, so the growth rate sqrt(-lambda) = {gam:.6f};"
f" next distinct: {lmw[np.argmax(lmw > lmw[0] * (1 - 1e-6))]:+.6e}")
def run(kappa_, zeta, tmax, stop_rms=None, every=1):
rng = np.random.default_rng(12)
u = rng.standard_normal(pos0.shape)
u -= (mass[:, None] * u).sum(0) / mass.sum()
u *= 1e-7 / math.sqrt(np.mean(np.sum(u * u, 1)))
x = pos0 + u
v = np.zeros_like(x)
bd = bonds if kappa_ > 0 else ()
E, F = energy_forces(x, q, s, bd, kappa_)
E0 = E
dt = 0.002
hist = []
nstep = int(round(tmax / dt))
for it in range(nstep + 1):
t = it * dt
disp = x[1:] - pos0[1:]
rms = math.sqrt(np.mean(np.sum(disp * disp, 1)))
ke = 0.5 * np.sum(mass[:, None] * v * v)
if it % every == 0:
dq = x[1:] - x[0]
dq -= np.round(dq)
hist.append((t, rms, math.sqrt(np.mean(np.sum(dq * dq, 1))), E, ke))
if stop_rms is not None and rms > stop_rms:
break
if it == nstep:
break
vh = v + 0.5 * dt * (F / mass[:, None] - zeta * v)
x = x + dt * vh
E, F = energy_forces(x, q, s, bd, kappa_)
v = (vh + 0.5 * dt * F / mass[:, None]) / (1 + 0.5 * zeta * dt)
return np.array(hist), x, E0
h4b, x4b, E04b = run(0.0, 0.0, 50.0, stop_rms=0.02)
tt, rr = h4b[:, 0], h4b[:, 1]
win = (rr > 1e-5) & (rr < 1e-3)
gfit = np.polyfit(tt[win], np.log(rr[win]), 1)[0]
etot = h4b[:, 3] + h4b[:, 4]
dEmax = np.max(np.abs(etot - etot[0]))
print(f" R4b ran to t = {tt[-1]:.3f} (finer rms displacement {rr[-1]:.4f}); fit window t = {tt[win][0]:.3f} .. {tt[win][-1]:.3f}")
show("R4b", f"fitted growth rate / predicted {gam:.6f} - 1 (expected within 5%)",
f"{gfit:.6f}, {gfit/gam - 1:+.2e} {check('R4b rate', abs(gfit/gam - 1) < 0.05)}")
show("", "largest change of the total energy / final kinetic energy (expected below 1e-3)",
f"{dEmax/h4b[-1, 4]:.1e} {check('R4b energy', dEmax < 1e-3 * h4b[-1, 4])}")
h4c, x4c, _ = run(1000.0, 0.0, 20.0, every=50)
show("R4c", "with springs (kappa = 1000), the largest finer rms displacement to t = 20 (expected below 1e-6)",
f"{np.max(h4c[:, 1]):.2e} {check('R4c', np.max(h4c[:, 1]) < 1e-6)}")
h4d, x4d, E04d = run(0.0, 1.0, 100.0, every=50)
dq = x4d[1:] - x4d[0]
dq -= np.round(dq)
dist = np.linalg.norm(dq, axis=1)
S2q = s[0]**2 + 0.05**2
sig_end = 0.0
for R in itertools.product((-1, 0, 1), repeat=3):
dd = dq - np.array(R, float)
sig_end += np.sum((1 / 8) * (2 * np.pi * S2q) ** -1.5 * np.exp(-np.sum(dd * dd, 1) / (2 * S2q)))
y_th = 8 * math.pi**1.5 * s[0]**3
print("R4d Where it goes (reported only; no springs, friction zeta = 1, to t = 100):")
print(f" finer quons' distance from the quon: start rms {h4d[0, 2]:.4f}, end rms {math.sqrt(np.mean(dist**2)):.4f},"
f" largest {dist.max():.4f} (the quon's charge has rms width s1 = {s[0]:.4f})")
print(f" electric energy: start {h4d[0, 3]:+.6f}, end {h4d[-1, 3]:+.6f}; kinetic energy at the end {h4d[-1, 4]:.1e}")
print(f" end state's K_T, a third of the trace by trial 4's real-space path: {(sig_end - 1)/3:+.4f}; Thomson's"
f" (1/y - 1)/3 with y = 8 pi^1.5 s1^3 = {y_th:.4f}: {(1/y_th - 1)/3:+.4f}")
print(" end positions relative to the quon (nearest image):")
for j in range(8):
print(f" finer quon from {tuple(np.round(pos0[1 + j] * 2).astype(int))}/2: ({dq[j,0]:+.4f}, {dq[j,1]:+.4f}, {dq[j,2]:+.4f})"
f" distance {dist[j]:.4f}")
np.savez("reflection_grid_R4d.npz", t=h4d[:, 0], rms_from_quon=h4d[:, 2], E=h4d[:, 3], ke=h4d[:, 4],
t_b=h4b[:, 0], rms_b=h4b[:, 1])
print(f"\nPass criteria: {'all met' if not FAIL else 'NOT MET: ' + ', '.join(FAIL)} (run time {time.time() - T_START:.0f} s)")