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

fable_tools.py

In the investigation at sim/charge_wave/check_reflection_fable/fable_tools.py · last changed in commit 87fc6d0, 12 November 2026 · 11,249 bytes · the folder as a zip


"""fable_tools.py - the seventh reviewer's own tools for checking trial 5 (reflection_grid.py).

Written from scratch from the derivations below; nothing is copied from the trial's script.

Model: charges q_i with Gaussian shapes (rms s_i per axis) in a cubic periodic cell of side L. The pair energy of two
Gaussians is q_i q_j erf(r/b_ij)/r with b_ij^2 = 2 (s_i^2 + s_j^2) (the convolution of the two Gaussians has variance
s_i^2 + s_j^2; the potential of a Gaussian charge of variance S^2 is erf(r/(S sqrt 2))/r). Gaussian units, Coulomb 1/r.

Ewald split: erf(r/b)/r = [erf(r/b) - erf(eta r)]/r + erf(eta r)/r. The first term is short-ranged (summed over images in
real space); the second is the potential of a Gaussian of variance 1/(2 eta^2), summed in reciprocal space:
  sum_R erf(eta |r - R|)/|r - R| = (4 pi/V) sum_{K != 0} exp(-K^2/(4 eta^2))/K^2 exp(i K.r)   (K = 0 dropped: neutral cell).
Self terms: for i = j the R = 0 term of the long-range part is erf(eta r)/r at r -> 0 = 2 eta/sqrt(pi) (energy) and its
Hessian -(4 eta^3/(3 sqrt pi)) I; both are removed.

Force-constant (dynamical) matrix of a Bloch wave, Phi_{i a, j b}(k) = sum_R e^{i k.R} d^2 E / d u_{i a}(0) d u_{j b}(R):
  Phi_ij(k) = -q_i q_j T_ij(k) + delta_ij sum_l q_i q_l T_il(0),
  T_ij(k) = sum'_R e^{i k.R} Hess[erf(r/b_ij)/r](r_i - r_j - R)   (R = 0 excluded when i = j).
"""
import itertools, math
import numpy as np
from scipy.special import erf, erfc

SQPI = math.sqrt(math.pi)


def taylor_coef(b, eta, nmax=14):
    """g(r) = [erf(r/b) - erf(eta r)]/r = sum_n c_n r^{2n}."""
    n = np.arange(nmax + 1)
    fact = np.array([math.factorial(int(i)) for i in n], float)
    return (2 / SQPI) * (-1.0) ** n / (fact * (2 * n + 1)) * (b ** (-(2.0 * n + 1)) - eta ** (2.0 * n + 1))


def short_g_dg(r, b, eta):
    """g(r) and g'(r)/r for the short-range pair function g = [erfc(eta r) - erfc(r/b)]/r (vectorised)."""
    r = np.asarray(r, float)
    g = np.empty_like(r)
    B = np.empty_like(r)
    rc = 0.25 * min(b, 1 / eta)
    sm = r < rc
    if np.any(sm):
        c = taylor_coef(b, eta)
        r2 = r[sm] ** 2
        g[sm] = sum(c[n] * r2 ** n for n in range(len(c)))
        B[sm] = sum(2 * n * c[n] * r2 ** (n - 1) for n in range(1, len(c)))
    bg = ~sm
    if np.any(bg):
        rr = r[bg]
        h = erfc(eta * rr) - erfc(rr / b)
        h1 = (2 / SQPI) * (np.exp(-(rr / b) ** 2) / b - eta * np.exp(-(eta * rr) ** 2))   # h'(r)
        g[bg] = h / rr
        B[bg] = (h1 * rr - h) / rr ** 3                                                   # g'/r
    return g, B


def short_AB(r, b, eta):
    """A = (g'' - g'/r)/r^2 and B = g'/r, so that Hess g = A r r^T + B I."""
    r = np.asarray(r, float)
    A = np.empty_like(r)
    B = np.empty_like(r)
    rc = 0.25 * min(b, 1 / eta)
    sm = r < rc
    if np.any(sm):
        c = taylor_coef(b, eta)
        r2 = r[sm] ** 2
        B[sm] = sum(2 * n * c[n] * r2 ** (n - 1) for n in range(1, len(c)))
        A[sm] = sum(4 * n * (n - 1) * c[n] * r2 ** (n - 2) for n in range(2, len(c)))
    bg = ~sm
    if np.any(bg):
        rr = r[bg]
        e1 = np.exp(-(rr / b) ** 2)
        e2 = np.exp(-(eta * rr) ** 2)
        h = erfc(eta * rr) - erfc(rr / b)
        h1 = (2 / SQPI) * (e1 / b - eta * e2)
        h2 = (2 / SQPI) * (-2 * rr / b ** 3 * e1 + 2 * eta ** 3 * rr * e2)
        g1 = h1 / rr - h / rr ** 2                           # g'
        g2 = h2 / rr - 2 * h1 / rr ** 2 + 2 * h / rr ** 3    # g''
        B[bg] = g1 / rr
        A[bg] = (g2 - g1 / rr) / rr ** 2
    return A, B


class Ewald:
    """Energy, forces and Bloch force-constant matrix for Gaussian charges in a cubic cell of side L."""

    def __init__(self, L, q, s, eta, rcells, gmax):
        self.L = float(L)
        self.V = self.L ** 3
        self.q = np.asarray(q, float)
        self.s = np.asarray(s, float)
        self.n = len(self.q)
        self.eta = float(eta)
        rng = range(-rcells, rcells + 1)
        self.RL = self.L * np.array(list(itertools.product(rng, repeat=3)), float)
        self.RL0 = self.RL[np.any(self.RL != 0, axis=1)]
        g = range(-gmax, gmax + 1)
        self.GL = (2 * np.pi / self.L) * np.array(list(itertools.product(g, repeat=3)), float)
        self.GL0 = self.GL[np.any(self.GL != 0, axis=1)]
        G2 = np.einsum("ni,ni->n", self.GL0, self.GL0)
        self.AG = np.exp(-G2 / (4 * self.eta ** 2)) / G2
        self.b = np.sqrt(2 * (self.s[:, None] ** 2 + self.s[None, :] ** 2))

    # ---------------------------------------------------------------- energy and forces
    def energy_forces(self, pos):
        pos = np.asarray(pos, float)
        n, q, eta = self.n, self.q, self.eta
        E = 0.0
        F = np.zeros((n, 3))
        for i in range(n):
            for j in range(i, n):
                b = self.b[i, j]
                d0 = pos[i] - pos[j]
                d0 = d0 - self.L * np.round(d0 / self.L)
                if i == j:
                    d = d0[None, :] + self.RL0
                    r = np.linalg.norm(d, axis=1)
                    g, B = short_g_dg(r, b, eta)
                    E += 0.5 * q[i] * q[j] * np.sum(g)        # own images, each pair once
                    E += 0.5 * q[i] ** 2 * taylor_coef(b, eta)[0]   # R = 0 self term of the short-range part (constant)
                else:
                    d = d0[None, :] + self.RL
                    r = np.linalg.norm(d, axis=1)
                    g, B = short_g_dg(r, b, eta)
                    E += q[i] * q[j] * np.sum(g)
                    f = -q[i] * q[j] * (B[:, None] * d).sum(0)
                    F[i] += f
                    F[j] -= f
        ph = np.exp(1j * (self.GL0 @ pos.T))                   # (nG, n)
        S = ph @ q
        E += (2 * np.pi / self.V) * np.sum(self.AG * np.abs(S) ** 2)
        E -= (eta / SQPI) * np.sum(q ** 2)                     # R = 0 self term of the long-range part
        F += (4 * np.pi / self.V) * q[:, None] * np.einsum("g,ga,gi->ia", self.AG, self.GL0, np.imag(np.conj(S)[:, None] * ph))
        return E, F

    def energy_forces_fast(self, pos):
        """The same energy and forces with every pair handled at once (for the supercell time runs); checked against
        energy_forces at a random configuration in check_time_fable.py."""
        pos = np.asarray(pos, float)
        n, q, eta = self.n, self.q, self.eta
        iu, ju = np.triu_indices(n, 1)
        d0 = pos[iu] - pos[ju]
        d0 = d0 - self.L * np.round(d0 / self.L)
        d = d0[:, None, :] + self.RL[None, :, :]                       # (npair, nimg, 3)
        r = np.linalg.norm(d, axis=2)
        E = 0.0
        F = np.zeros((n, 3))
        # group pairs by their width b (few distinct values)
        bpair = self.b[iu, ju]
        for bval in np.unique(bpair):
            m = bpair == bval
            g, B = short_g_dg(r[m].ravel(), bval, eta)
            g = g.reshape(r[m].shape)
            B = B.reshape(r[m].shape)
            qq = q[iu[m]] * q[ju[m]]
            E += np.sum(qq * g.sum(1))
            f = -qq[:, None] * np.einsum("pn,pni->pi", B, d[m])
            np.add.at(F, iu[m], f)
            np.add.at(F, ju[m], -f)
        # own images (i = j), energy only (their force contribution cancels by symmetry), plus constants
        for i in range(n):
            b = self.b[i, i]
            r0 = np.linalg.norm(self.RL0, axis=1)
            g, _ = short_g_dg(r0, b, eta)
            E += 0.5 * q[i] ** 2 * np.sum(g) + 0.5 * q[i] ** 2 * taylor_coef(b, eta)[0]
        ph = np.exp(1j * (self.GL0 @ pos.T))
        S = ph @ q
        E += (2 * np.pi / self.V) * np.sum(self.AG * np.abs(S) ** 2)
        E -= (eta / SQPI) * np.sum(q ** 2)
        F += (4 * np.pi / self.V) * q[:, None] * np.einsum("g,ga,gi->ia", self.AG, self.GL0, np.imag(np.conj(S)[:, None] * ph))
        return E, F

    # ---------------------------------------------------------------- Bloch force-constant matrix
    def T(self, rij, k, same, b):
        k = np.asarray(k, float)
        Rl = self.RL0 if same else self.RL
        d = rij[None, :] - Rl
        r = np.linalg.norm(d, axis=1)
        A, B = short_AB(r, b, self.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 = self.GL + k
        K2 = np.einsum("ni,ni->n", K, K)
        m = K2 > 1e-20
        K, K2 = K[m], K2[m]
        rec = -(4 * np.pi / self.V) * np.einsum("n,ni,nj->ij", np.exp(-K2 / (4 * self.eta ** 2)) / K2 * np.exp(1j * (K @ rij)), K, K)
        T = real + rec
        if same:
            T = T + (4 * self.eta ** 3 / (3 * SQPI)) * np.eye(3)
        return T

    def phi(self, pos, k):
        pos = np.asarray(pos, float)
        n, q = self.n, self.q
        k = np.asarray(k, float)
        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):
                rij = pos[i] - pos[j]
                P[3*i:3*i+3, 3*j:3*j+3] = -q[i] * q[j] * self.T(rij, k, i == j, self.b[i, j])
                ons += q[i] * q[j] * self.T(rij, z, i == j, self.b[i, j])
            P[3*i:3*i+3, 3*i:3*i+3] += ons
        return P


def gauss_overlap_sum(pos, q, s, L, k, rcells=4):
    """Trace identity: 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) ],
    with rho_il the convolution of the two Gaussians (variance s_i^2 + s_l^2); at k = 0 exactly, less 4 pi sum q_i^2.
    Returns the total and the share of each charge (the trace of its own block)."""
    pos = np.asarray(pos, float)
    n = len(q)
    rng = range(-rcells, rcells + 1)
    RL = L * np.array(list(itertools.product(rng, repeat=3)), float)
    nz = np.any(RL != 0, axis=1)
    share = np.zeros(n)
    k = np.asarray(k, float)
    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:
                share[i] += q[i] ** 2 * np.sum(np.cos(RL[nz] @ k) * g[nz]) - q[i] * q[l] * np.sum(g[nz])
            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, s2N=0.1):
    """The N = 2.. stack of trial 5: quon (index 0) at the origin, charge 1, Gaussian s1; N^3 finer quons at (i,j,l)/N,
    charge -1/N^3 each, Gaussian s2 = s2N/N; s1 set so that the combined width N*S = NS."""
    s2 = s2N / N
    s1 = math.sqrt((NS / N) ** 2 - s2 ** 2)
    ax = np.arange(N) / N
    fin = np.array(list(itertools.product(ax, ax, ax)))
    pos = np.vstack([np.zeros((1, 3)), fin])
    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


def theta3(x):
    s, n = 1.0, 1
    while True:
        t = x ** (n * n)
        if t < 1e-30:
            return s
        s += 2 * t
        n += 1


def theta4(x):
    s, n = 1.0, 1
    while True:
        t = x ** (n * n)
        if t < 1e-30:
            return s
        s += 2 * t * (-1) ** n
        n += 1