Does light charge the quons? › Files cited on the page › check_lattices_fable/
my_lattices.py
"""Independent reproduction of trial 7 (cubic_lattices.py), written from scratch by the tenth reviewer.
Model (as the lock states it): finer quons are unit point charges on a Bravais lattice L (sc, bcc, fcc) at one per unit
volume, with a uniform neutralizing background; the quon's unit charge fills a ball of radius alpha evenly. e(v, alpha) is
the ball's average of the zero-mean lattice potential. The quon rests where e is greatest; the hold tensor there is
K = -Hess(e)/(4 pi) in units of 4 pi n q^2.
Differences from the trial's code, for independence:
- other primitive vectors for bcc and fcc, other Ewald parameters, own real/reciprocal bookkeeping;
- the Hessian by central finite differences (no analytic Hessian);
- the global search on a grid over the symmetry wedge 0 <= x <= y <= z <= a/2 of the conventional cube (step a/32), then
Nelder-Mead refinement of the best distinct candidates (no gradient);
- the energy cross-checked at sample points against a direct Fourier series e = 4 pi sum_G F(G alpha) cos(G.v)/G^2.
Run: ~/aspden-review-venv/bin/python3 my_lattices.py [path to run-3 output] > my_lattices_out.txt
"""
import itertools, math, re, sys, time
import numpy as np
from scipy.optimize import minimize
from scipy.special import erf, erfc
T0 = time.time()
SQPI = math.sqrt(math.pi)
B = 0.036135562
KINDS = ("sc", "bcc", "fcc")
def lattice(kind):
"""Primitive vectors (rows of A) at unit volume per site, and the conventional cube side a."""
if kind == "sc":
a = 1.0
A = np.eye(3)
cent = [np.zeros(3)]
elif kind == "bcc":
a = 2 ** (1 / 3)
A = (a / 2) * np.array([[1, 1, -1], [-1, 1, 1], [1, -1, 1]], float)
cent = [np.zeros(3), np.array([.5, .5, .5])]
else:
a = 4 ** (1 / 3)
A = (a / 2) * np.array([[1, 1, 0], [0, 1, 1], [1, 0, 1]], float)
cent = [np.zeros(3), np.array([.5, .5, 0]), np.array([.5, 0, .5]), np.array([0, .5, .5])]
assert abs(abs(np.linalg.det(A)) - 1) < 1e-12
return a, A, cent
# special sites in units of the conventional cube side; "cubic" = site symmetry is a cubic point group
SPECIAL = {
"sc": {"on a finer quon": (0, 0, 0), "edge midpoint": (.5, 0, 0), "face centre": (.5, .5, 0), "cube centre": (.5, .5, .5)},
"bcc": {"on a finer quon": (0, 0, 0), "octahedral hole": (.5, .5, 0), "tetrahedral hole": (.5, .25, 0)},
"fcc": {"on a finer quon": (0, 0, 0), "octahedral hole": (.5, 0, 0), "tetrahedral hole": (.25, .25, .25)},
}
CUBIC = {"sc": {"on a finer quon", "cube centre"}, "bcc": {"on a finer quon"},
"fcc": {"on a finer quon", "octahedral hole", "tetrahedral hole"}}
class Ewald:
def __init__(self, kind, eta=1.8, rcut=6.0, gcut=None):
self.kind = kind
self.a, self.A, self.cent = lattice(kind)
self.Ainv = np.linalg.inv(self.A)
self.Bm = 2 * np.pi * self.Ainv.T # rows b_i with b_i . a_j = 2 pi delta_ij
self.eta, self.rcut = eta, rcut
n = int(math.ceil((rcut + self.a) / min(np.linalg.norm(self.A, axis=1)))) + 1
R = np.array([i * self.A[0] + j * self.A[1] + l * self.A[2]
for i, j, l in itertools.product(range(-n, n + 1), repeat=3)])
self.R = R[np.linalg.norm(R, axis=1) <= rcut + 0.9 * self.a] # covers rcut around any folded point
gcut = gcut or 10.0 * eta
m = int(math.ceil(gcut / min(np.linalg.norm(self.Bm, axis=1)))) + 1
G = np.array([i * self.Bm[0] + j * self.Bm[1] + l * self.Bm[2]
for i, j, l in itertools.product(range(-m, m + 1), repeat=3) if (i, j, l) != (0, 0, 0)])
G2 = np.einsum("ni,ni->n", G, G)
keep = G2 <= gcut ** 2
self.G, self.G2 = G[keep], G2[keep]
self.cG = 4 * np.pi * np.exp(-self.G2 / (4 * eta ** 2)) / self.G2
self.canon_special = {nm: self.canon(np.array(s, float) * self.a) for nm, s in SPECIAL[kind].items()}
def fold(self, v):
f = np.atleast_2d(v) @ self.Ainv
return (f - np.round(f)) @ self.A
def e(self, V, alpha):
"""Ball-averaged zero-mean potential at the points V (n x 3), ball radius alpha."""
V = self.fold(V)
out = np.empty(len(V))
eta = self.eta
for c0 in range(0, len(V), 512):
Vc = V[c0:c0 + 512]
d = Vc[:, None, :] - self.R[None, :, :]
r = np.sqrt(np.einsum("nmi,nmi->nm", d, d))
inside = r < alpha
rs = np.where(r < 1e-14, 1.0, r)
long_part = np.where(inside | (r > self.rcut), 0.0, erfc(eta * r) / rs)
# inside the ball: ball potential minus the smooth part erf(eta r)/r (the 1/r is replaced by the ball's)
smooth = np.where(r < 1e-14, 2 * eta / SQPI, erf(eta * r) / rs)
ball = np.where(inside, (3 * alpha ** 2 - r ** 2) / (2 * alpha ** 3) - smooth, 0.0)
rec = np.cos(Vc @ self.G.T) @ self.cG
out[c0:c0 + 512] = long_part.sum(1) + ball.sum(1) + rec - np.pi / eta ** 2
return out
def e1(self, v, alpha):
return self.e(np.asarray(v, float)[None, :], alpha)[0]
def psi(self):
"""Regular part of the potential at a site: lim (Phi(r) - 1/r)."""
r = np.linalg.norm(self.R, axis=1)
r = r[(r > 1e-12) & (r <= self.rcut)]
return np.sum(erfc(self.eta * r) / r) - 2 * self.eta / SQPI + self.cG.sum() - np.pi / self.eta ** 2
def hess_fd(self, v, alpha, h=2e-4):
"""Central finite-difference Hessian of e at v (fourth-order stencil)."""
v = np.asarray(v, float)
H = np.zeros((3, 3))
E = np.eye(3)
f0 = self.e1(v, alpha)
for i in range(3):
fp, fm = self.e1(v + h * E[i], alpha), self.e1(v - h * E[i], alpha)
fp2, fm2 = self.e1(v + 2 * h * E[i], alpha), self.e1(v - 2 * h * E[i], alpha)
H[i, i] = (-fp2 + 16 * fp - 30 * f0 + 16 * fm - fm2) / (12 * h * h)
for j in range(i + 1, 3):
pp = self.e1(v + h * E[i] + h * E[j], alpha); mm = self.e1(v - h * E[i] - h * E[j], alpha)
pm = self.e1(v + h * E[i] - h * E[j], alpha); mp = self.e1(v - h * E[i] + h * E[j], alpha)
H[i, j] = H[j, i] = (pp - pm - mp + mm) / (4 * h * h)
return H
def n_in(self, v, alpha):
return int(np.sum(np.linalg.norm(self.R - np.asarray(v)[None, :], axis=1) < alpha))
def edge_margin(self, v, alpha):
"""Smallest |rho - alpha| over lattice points: finite differences are unreliable if it is below a few h."""
return float(np.min(np.abs(np.linalg.norm(self.R - np.asarray(v)[None, :], axis=1) - alpha)))
def canon(self, v):
"""Canonical coordinates of the orbit of v: fold into the conventional cube with every centring, reflect
into 0 <= u <= 1/2 and sort; the lexicographically smallest tuple names the orbit."""
w = np.asarray(v, float) / self.a
best = None
for c in self.cent:
u = np.mod(w + c, 1.0)
u = np.minimum(u, 1.0 - u)
t = tuple(np.round(np.sort(u), 6))
if best is None or t < best:
best = t
return np.array(best)
def name(self, v, tol=2e-4):
cv = self.canon(v)
for nm, cs in self.canon_special.items():
if np.max(np.abs(cv - cs)) < tol:
return nm
return "general (%.4f, %.4f, %.4f)" % tuple(cv)
def wedge(self, step):
"""Grid over 0 <= x <= y <= z <= a/2 of the conventional cube (every point of space has an image there)."""
n = int(round(0.5 / step))
pts = [(i, j, l) for l in range(n + 1) for j in range(l + 1) for i in range(j + 1)]
return np.array(pts, float) * step * self.a
def rest(self, alpha, step=1 / 32, ncand=12):
"""Global maximum of e: wedge grid, then Nelder-Mead from the best distinct grid points, then a check that
no candidate within 1e-9 of the best has a different site name."""
W = self.wedge(step)
ev = self.e(W, alpha)
order = np.argsort(-ev)
cands = []
for idx in order:
p = W[idx]
if all(np.linalg.norm(p - q) > 1.5 * step * self.a for q in cands):
cands.append(p)
if len(cands) >= ncand:
break
best = None
for p in cands:
for start in (p, p + np.array([3e-3, -2e-3, 1e-3]) * self.a): # one symmetric, one off-symmetry start
res = minimize(lambda x: -self.e1(x, alpha), start, method="Nelder-Mead",
options=dict(xatol=1e-9, fatol=1e-14, maxiter=4000, maxfev=8000))
x = self.fold(res.x)[0]
val = -res.fun
if best is None or val > best[1] + 1e-13:
best = (x, val)
x, val = best
nm = self.name(x)
if nm in SPECIAL[self.kind]:
xs = np.array(SPECIAL[self.kind][nm], float) * self.a
if abs(self.e1(xs, alpha) - val) < 1e-9:
x = xs
return x, nm, val
class Dyn:
"""Dynamical matrix of unit point charges on L in a rigid uniform background, units of w_p^2 = 4 pi n q^2/m.
D(k) = [ (4 pi/3) I - S(k) ] / (4 pi), S(k) = sum_{R != 0} Hess(1/r)(R) e^{ik.R} by Ewald."""
def __init__(self, ew, eta=1.4, rcut=7.0):
self.ew, self.eta = ew, eta
n = int(math.ceil(rcut / min(np.linalg.norm(ew.A, axis=1)))) + 1
R = np.array([i * ew.A[0] + j * ew.A[1] + l * ew.A[2]
for i, j, l in itertools.product(range(-n, n + 1), repeat=3) if (i, j, l) != (0, 0, 0)])
r = np.linalg.norm(R, axis=1)
R, r = R[r <= rcut], r[r <= rcut]
self.R = R
# Hessian of f(r) = erfc(eta r)/r: f'' n n^T + (f'/r)(I - n n^T)
x = eta * r
g = np.exp(-x * x) * 2 * eta / SQPI
f1 = -erfc(x) / r ** 2 - g / r
f2 = 2 * erfc(x) / r ** 3 + g * (2 / r ** 2 + 2 * eta ** 2)
nn = np.einsum("ni,nj->nij", R, R) / r[:, None, None] ** 2
self.H = (f2 - f1 / r)[:, None, None] * nn + (f1 / r)[:, None, None] * np.eye(3)
m = 7
self.G = np.array([i * ew.Bm[0] + j * ew.Bm[1] + l * ew.Bm[2] for i, j, l in itertools.product(range(-m, m + 1), repeat=3)])
def D(self, k):
k = np.asarray(k, float)
S = np.einsum("n,nij->ij", np.cos(self.R @ k), self.H)
K = self.G + k
K2 = np.einsum("ni,ni->n", K, K)
msk = K2 > 1e-14
S = S - 4 * np.pi * np.einsum("n,ni,nj->ij", np.exp(-K2[msk] / (4 * self.eta ** 2)) / K2[msk], K[msk], K[msk])
S = S + 4 * self.eta ** 3 / (3 * SQPI) * np.eye(3)
return ((4 * np.pi / 3) * np.eye(3) - S) / (4 * np.pi)
def fourier_e(ew, v, alpha, gmax=220.0):
"""Direct Fourier series for the ball-averaged potential, no Ewald: 4 pi sum_{G != 0} F(G alpha) cos(G.v)/G^2."""
m = int(math.ceil(gmax / min(np.linalg.norm(ew.Bm, axis=1)))) + 1
tot = 0.0
rng = range(-m, m + 1)
for i in rng: # one slab at a time, to bound memory
idx = np.array([(i, j, l) for j in rng for l in rng if (i, j, l) != (0, 0, 0)])
if len(idx) == 0:
continue
G = idx @ ew.Bm
G2 = np.einsum("ni,ni->n", G, G)
keep = G2 <= gmax ** 2
G, G2 = G[keep], G2[keep]
x = np.sqrt(G2) * alpha
F = 3 * (np.sin(x) - x * np.cos(x)) / x ** 3
tot += np.sum(4 * np.pi * F * np.cos(G @ np.asarray(v)) / G2)
return tot
def parse_run(path):
rows = {}
kind = None
for line in open(path, encoding="utf-8"):
m = re.match(r"^ (sc|bcc|fcc) \(stability needs", line)
if m:
kind = m.group(1)
m = re.match(r"\s+(\d+)\s+(\d\.\d{4})\s+(.+?)\s+(\d+)\s+([+-]\d+\.\d{4}) ([+-]\d+\.\d{4}) ([+-]\d+\.\d{4})\s+(\d\.\d{3})\s+(ok|MISS)\s+(pass|fail)", line)
if m and kind:
rows[(kind, int(m.group(1)))] = (m.group(3).strip(), int(m.group(4)),
tuple(float(m.group(i)) for i in (5, 6, 7)), float(m.group(8)), m.group(10) == "pass")
return rows
def main():
run3 = parse_run(sys.argv[1]) if len(sys.argv) > 1 else {}
print("Tenth reviewer's independent reproduction of trial 7 (my_lattices.py)")
EW = {k: Ewald(k) for k in KINDS}
WS_REF = {"sc": -0.880059, "bcc": -0.895929, "fcc": -0.895874}
rs = (3 / (4 * np.pi)) ** (1 / 3)
print("\nA. Lattice facts at one finer quon per unit volume")
for k in KINDS:
ew = EW[k]
r = np.linalg.norm(ew.R, axis=1); r = np.sort(r[r > 1e-12])
shells = []
for d in r:
if not shells or d - shells[-1][0] > 1e-6:
shells.append([d, 1])
else:
shells[-1][1] += 1
print(f" {k}: cube side a = {ew.a:.6f}; shells (distance, count): " + ", ".join(f"({d:.4f}, {c})" for d, c in shells[:6]))
print(f" Madelung: psi = {ew.psi():.6f}; psi r_s / 2 = {ew.psi() * rs / 2:.6f} (reference {WS_REF[k]})"
f"; eta 1.4: {Ewald(k, eta=1.4).psi() * rs / 2:.6f}; eta 2.6: {Ewald(k, eta=2.6).psi() * rs / 2:.6f}")
print("\nB. Energy cross-check: Ewald route against the direct Fourier series (|G| <= 220), sample points.")
print(" The trial's e(v) leaves out the background's curvature over the ball, 2 pi alpha^2 / 5, a constant in v;")
print(" the Fourier series is the true ball average, so the two should differ by exactly that constant.")
rng = np.random.default_rng(3)
for k in KINDS:
ew = EW[k]
for alpha in (0.4924, 0.9):
v = ew.fold(rng.uniform(-0.5, 0.5, 3) * ew.a)[0]
e1 = ew.e1(v, alpha) + 2 * np.pi * alpha ** 2 / 5; e2 = fourier_e(ew, v, alpha)
e3 = Ewald(k, eta=2.6, rcut=5.0).e1(v, alpha) + 2 * np.pi * alpha ** 2 / 5
print(f" {k}: alpha {alpha}, v = ({v[0]:+.4f}, {v[1]:+.4f}, {v[2]:+.4f}): Ewald + const {e1:.8f}, Fourier {e2:.8f} (diff {e1 - e2:+.1e}), Ewald eta 2.6 {e3:.8f} (diff {e1 - e3:+.1e})")
# also on a site
e1 = ew.e1(np.zeros(3), 0.4924) + 2 * np.pi * 0.4924 ** 2 / 5; e2 = fourier_e(ew, np.zeros(3), 0.4924)
print(f" {k}: alpha 0.4924 on a finer quon: Ewald + const {e1:.8f}, Fourier {e2:.8f} (diff {e1 - e2:+.1e})")
print("\nC. The quon lattice's own waves (dynamical matrix, units of w_p^2, continuum held rigid)")
LMIN = {}
for k in KINDS:
ew = EW[k]
dy, dy2 = Dyn(ew), Dyn(ew, eta=2.0)
kr = rng.uniform(-0.5, 0.5, (3, 3)) @ ew.Bm
tr = max(abs(np.trace(dy.D(q)) - 1) for q in kr)
dd = max(np.max(np.abs(dy.D(q) - dy2.D(q))) for q in kr)
t = 2 * np.pi / ew.a
sp = {"sc": {"X": (.5, 0, 0), "M": (.5, .5, 0), "R": (.5, .5, .5)},
"bcc": {"H": (1, 0, 0), "N": (.5, .5, 0), "P": (.5, .5, .5)},
"fcc": {"X": (1, 0, 0), "L": (.5, .5, .5), "W": (1, .5, 0), "K": (.75, .75, 0)}}[k]
lam_min, where = 9.0, None
for i, j, l in itertools.product(range(16), repeat=3):
if (i, j, l) == (0, 0, 0):
continue
w = np.linalg.eigvalsh(dy.D(np.array([i, j, l]) / 16 @ ew.Bm))
if w[0] < lam_min:
lam_min, where = w[0], f"({i},{j},{l})/16 of the reciprocal cell"
for lab, q in sp.items():
w = np.linalg.eigvalsh(dy.D(t * np.array(q, float)))
if w[0] < lam_min:
lam_min, where = w[0], lab
for lab, q in (("[100]", (1, 0, 0)), ("[110]", (1, 1, 0)), ("[111]", (1, 1, 1))):
q = 1e-3 * np.array(q, float) / np.linalg.norm(q)
w = np.linalg.eigvalsh(dy.D(q))
if w[0] < lam_min:
lam_min, where = w[0], f"small k {lab}"
LMIN[k] = lam_min
print(f" {k}: trace-1 {tr:.1e}; eta 1.4 vs 2.0 {dd:.1e}; lowest eigenvalue {lam_min:+.5f} at {where}")
print(" " + "; ".join(f"{lab}: " + " ".join(f"{x:+.5f}" for x in np.linalg.eigvalsh(dy.D(t * np.array(q, float)))) for lab, q in sp.items()))
if k == "bcc":
q = (np.pi / 8) * np.ones(3) / ew.a # Part 1's smallest sampled k (grid offset by pi/16, doubled)
w = np.linalg.eigvalsh(dy.D(q))
print(f" at Part 1's smallest sampled k = (pi/8)(1,1,1)/a: eigenvalues {w[0]:+.5f} {w[1]:+.5f} {w[2]:+.5f}")
for s in (0.05, 0.1, 0.2):
for lab, q in (("[100]", (1, 0, 0)), ("[110]", (1, 1, 0)), ("[111]", (1, 1, 1))):
q = s * np.array(q, float) / np.linalg.norm(q)
w = np.linalg.eigvalsh(dy.D(q))
print(f" |k| = {s} along {lab}: lowest {w[0]:+.6f}, /k^2 = {w[0] / s ** 2:+.4f} (d = 1 here, so beta per (kd)^2)")
print("\nD. Where the quon leaves its finer quon (global maximum of e no longer on a site)")
XO = {}
for k in KINDS:
ew = EW[k]
lo, hi = None, None
a_prev = None
for a in np.arange(0.50, 0.701, 0.01):
x, nm, val = ew.rest(a)
if nm != "on a finer quon":
lo, hi = a_prev, a
break
a_prev = a
while hi - lo > 1e-5:
mid = 0.5 * (lo + hi)
if ew.rest(mid)[1] == "on a finer quon":
lo = mid
else:
hi = mid
XO[k] = 0.5 * (lo + hi)
x, nm, val = ew.rest(hi + 0.003)
print(f" {k}: leaves the site at alpha = {XO[k]:.5f} (N = {XO[k] / B:.3f} at Aspden's radius); just above it rests at {nm}, holding {ew.n_in(x, hi + 0.003)}")
print("\nE. Aspden's radius, N = 2 to 80: my global search against run 3 (name, n inside, hold eigenvalues to 2e-4, verdict)")
PASS, ROWS = {}, {}
mism = []
for k in KINDS:
ew = EW[k]
PASS[k] = []
for N in range(2, 81):
alpha = B * N
x, nm, val = ew.rest(alpha)
H = ew.hess_fd(x, alpha)
lam = np.linalg.eigvalsh(-H / (4 * np.pi))
n = ew.n_in(x, alpha)
kt = lam.mean()
rule = (n / (4 * np.pi / 3 * alpha ** 3) - 1) / 3
margin = ew.edge_margin(x, alpha)
iso = (lam[2] - lam[0]) < 1e-4 * max(1.0, abs(kt))
ok = (nm in CUBIC[k]) and iso and lam[0] > 0 and lam[0] >= -LMIN[k]
if ok:
PASS[k].append(N)
ROWS[(k, N)] = (nm, n, lam, ok)
note = ""
if (k, N) in run3:
onm, on, olam, osh, ook = run3[(k, N)]
same = (onm == nm or (onm.startswith("general") and nm.startswith("general"))) and on == n \
and all(abs(p - q) < 2e-4 for p, q in zip(olam, lam)) and ook == ok
if not same:
mism.append((k, N))
note = f" <-- run 3: {onm} {on} {olam} {'pass' if ook else 'fail'}"
flag = " (edge within 1e-3)" if margin < 1e-3 else ""
print(f" {k} {N:3d} a={alpha:.4f} {nm:34s} n={n:3d} K=({lam[0]:+.4f},{lam[1]:+.4f},{lam[2]:+.4f}) trace-rule diff {kt - rule:+.1e} share {1 / (1 + kt):.3f} {'pass' if ok else 'fail'}{flag}{note}", flush=True)
def groups(xs):
out, s = [], None
for a, b in zip(xs, xs[1:] + [None]):
if s is None:
s = a
if b != a + 1:
out.append(f"{s}" if s == a else f"{s}-{a}"); s = None
return ", ".join(out)
print()
for k in KINDS:
print(f" passing whole numbers, {k}: {groups(PASS[k])}")
print(f" rows differing from run 3 beyond tolerance: {mism if mism else 'none'} ({len(run3)} rows compared)")
print("\nF. The ratio for f = 1/4 in each cubic window: alpha* = (3n/8pi)^(1/3), N* = alpha*/(b/d); does the quon rest there at alpha*?")
for k in KINDS:
ew = EW[k]
wins = sorted({(ROWS[(k, N)][0], ROWS[(k, N)][1]) for N in range(2, 81) if ROWS[(k, N)][3]}, key=lambda t: t[1])
for nm, n in wins:
astar = (3 * n / (8 * np.pi)) ** (1 / 3)
x, nm2, val = ew.rest(astar)
n2 = ew.n_in(x, astar)
Ns = astar / B
near = [N for N in (math.floor(Ns), math.ceil(Ns)) if N in PASS[k]]
shares = ", ".join(f"{N}: {1 / (1 + ROWS[(k, N)][2].mean()):.3f}" for N in near)
print(f" {k}: {nm}, n = {n}: alpha* = {astar:.4f}, N* = {Ns:.3f}; rests there at alpha*: {nm2 == nm and n2 == n} ({nm2}, {n2}); passing neighbours: {shares or 'none'}")
print(f"\nrun time {time.time() - T0:.0f} s")
if __name__ == "__main__":
main()