Does light charge the quons? › Files cited on the page › the trials

thinning_to_vacuum.py

In the investigation at sim/matter_light/thinning_to_vacuum.py · last changed in commit 1e4811f, 22 November 2026 · 75,486 bytes · runnable copies in the scripts zip


"""Trial 22: from glass to vacuum, Cherenkov light, and the setting Sun (22 November 2026).

Lock: papers/Lock_thinning_to_vacuum_2026-11-22.md, committed with this script before the run. Every choice is the lock's.
Trial 20's molecular model of light in matter (polarizable molecules sitting in the ordinary vacuum; Lorentz's local field;
Lorentz-Lorenz; the Sellmeier form read as the lossless oscillator sum, each resonance a hold) is carried from glass to air, from air
down to the vacuum of the laboratory and of space, and into two things air does with light: Cherenkov light from a charge moving
faster than light's phase speed in it, and the bending and reddening of the setting Sun. The vacuum's own measured and predicted
responses (free electrons in space; the Casimir and Euler-Heisenberg effects) are set beside the thinned gas, and vacuum Cherenkov
radiation is used as the test of an aether in which matter's limiting speed and light's differ. An analogue exercise for the
charging-quons page; there is no pass or fail; the lock's section 6 fixes the form of each lesson (V1 to V8), printed at the end.
Run: OMP_NUM_THREADS=1 ~/aspden-review-venv/bin/python3 thinning_to_vacuum.py > thinning_to_vacuum_out.txt   (numpy, scipy). A few minutes
(the ray traces are Python loops). It writes nothing but its stdout. Labels: [S] standard physics, [I] measured input, [D] derived, [M] modelling choice, [P] proposed;
"from memory" marks a number not read at source during this trial. Sources: sources/thinning_to_vacuum_2026-11-22/FETCH_LOG.md.
"""
import os
import subprocess
import numpy as np
import scipy
from scipy import constants as K
from scipy.integrate import quad
from scipy.optimize import brentq


def say(s=""):
    print(s)


checks = []


def check(name, ok, detail=""):
    checks.append((name, bool(ok)))
    say(f"   CHECK {'pass' if ok else 'FAIL'}: {name} {detail}")


try:
    here = os.path.dirname(os.path.abspath(__file__))
    head = subprocess.run(["git", "rev-parse", "HEAD"], capture_output=True, text=True, timeout=10, cwd=here).stdout.strip()
except Exception as exc:                                   # the script still runs outside the repository
    head = f"(not available: {exc.__class__.__name__})"
say("Trial 22: from glass to vacuum, Cherenkov light, and the setting Sun. Lock: papers/Lock_thinning_to_vacuum_2026-11-22.md")
say(f"git HEAD at run: {head}; numpy {np.__version__}; scipy {scipy.__version__}")

# ---------------- constants [S], CODATA 2018 via scipy ----------------
c, h, hbar, e, me, mp, eps0, mu0, kB, NA, G = K.c, K.h, K.hbar, K.e, K.m_e, K.m_p, K.epsilon_0, K.mu_0, K.k, K.N_A, K.G
alpha_fs = K.fine_structure
a0 = K.physical_constants['Bohr radius'][0]
ME_MEV = K.physical_constants['electron mass energy equivalent in MeV'][0]
MMU_MEV = K.physical_constants['muon mass energy equivalent in MeV'][0]
MP_MEV = K.physical_constants['proton mass energy equivalent in MeV'][0]
MPI_MEV = 139.57039                                        # [I] PDG 2024 listing, pi+-: 139.57039 +- 0.00018 MeV
hc_eVum = h * c / e * 1e6                                  # eV um
hbarc_eVm = hbar * c / e                                   # eV m
PC, AU, YR = K.parsec, K.au, K.Julian_year
GLY = c * YR * 1e9
ARCMIN = np.pi / (180 * 60)

# ---------------- inputs [I]; sources in the lock, section 3 and FETCH_LOG.md ----------------
# refractiveindex.info 'formula 6' for gases: n - 1 = C0 + sum_i C_i/(D_i - sigma^2), sigma = 1/lam in 1/um (lam in um)
# Air, Ciddor 1996 (Appl. Opt. 35, 1566): dry standard air, 15 C, 101325 Pa, 450 ppm CO2; 0.23 to 1.69 um
AIR_CIDDOR = (0.0, 0.05792105, 238.0185, 0.00167917, 57.362)
# Air, Peck and Reeder 1972 (JOSA 62, 958): 15 C, 101325 Pa; 0.185 to 1.7 um
AIR_PECK_REEDER = (8.06051e-5, 2.480990e-2, 132.274, 1.74557e-4, 39.32957)
# Air, Birch and Downs 1994 (Metrologia 31, 315), the modified Edlen dispersion for standard air (15 C, 101325 Pa, dry, 450 ppm)
AIR_BIRCH_DOWNS = (8342.54e-8, 2406147e-8, 130.0, 15998e-8, 38.9)
# The gases: coefficients, reference temperature (K) and pressure (Pa), range (um), mole fraction in dry air [S, from memory: USSA 1976
# composition N2 0.78084, O2 0.209476, Ar 0.00934; CO2 set to Ciddor's 450 ppm; the rest (Ne, He, Kr, CH4, H2) 3e-5 together, left out]
GASES = {
    "N2": dict(coef=(6.497378e-5, 3.0738649e-2, 144.0), T=288.15, P=101325.0, rng=(0.4679, 2.0587), x=0.78084,
               src="Peck and Khanna 1966 (JOSA 56, 1059), 15 C"),
    "O2": dict(coef=(1.181494e-4, 9.708931e-3, 75.4), T=293.15, P=101325.0, rng=(0.4, 1.8), x=0.209476,
               src="Zhang, Lu and Wang 2008 (Appl. Opt. 47, 3143), 20 C"),
    "Ar": dict(coef=(6.432135e-5, 2.8606021e-2, 144.0), T=288.15, P=101325.0, rng=(0.4679, 2.0587), x=0.00934,
               src="Peck and Fisher 1964 (JOSA 54, 1362), 15 C"),
    "CO2": dict(coef=(0.0, 1.54489e-6, 0.0584738, 0.083091927, 210.9241, 0.002876419, 60.122959), T=273.15, P=101325.0,
                rng=(0.48, 1.82), x=0.00045, src="Old, Gentili and Peck 1971 (JOSA 61, 89), 0 C"),
    "He": dict(coef=(0.0, 0.01470091, 423.98), T=273.15, P=101325.0, rng=(0.48, 2.06), x=0.0,
               src="Mansfield and Peck 1969 (JOSA 59, 199), 0 C"),
}
# Water vapour, Ciddor's form: n_ws - 1 = 1.022e-8 (w0 + w1 s^2 + w2 s^4 + w3 s^6) at 20 C, 1333 Pa
H2O_VAP_W = (295.235, 2.6422, -0.032380, 0.004028)
# Liquid water, Daimon and Masumura 2007 (20 C) and Schott N-BK7: trial 20's inputs [I], the Sellmeier form n^2 - 1 = sum B lam^2/(lam^2 - C)
H2O_B = np.array([5.684027565e-1, 1.726177391e-1, 2.086189578e-2, 1.130748688e-1])
H2O_C = np.array([5.101829712e-3, 1.821153936e-2, 2.620722293e-2, 1.069792721e1])
BK7_B = np.array([1.03961212, 0.231792344, 1.01046945])
BK7_C = np.array([0.00600069867, 0.0200179144, 103.560653])
# Fraunhofer lines, um
LAM_C, LAM_D, LAM_F = 0.6562725, 0.5875618, 0.4861327
# Rayleigh: measured N2 cross-section 5.1e-31 m^2 at 532 nm (Sneep and Ubachs 2005, as cited by Wikipedia) [I, secondary];
# King (depolarization) factors [S, from memory: Bodhaine et al. 1999]: air 1.048, N2 1.034
SIGMA_N2_532_MEAS, FK_AIR, FK_N2 = 5.1e-31, 1.048, 1.034
TAU_R_550_MEM = 0.0973                                     # Rayleigh optical depth of a standard atmosphere at 550 nm [from memory]
# US Standard Atmosphere 1976 [I; the NTRS scan was fetched but is not machine-readable; its layer table is read from two secondary pages]
G0, RSTAR, M0, R0_GEO = 9.80665, 8.31432, 28.9644e-3, 6356766.0     # g0, R*, M0 (kg/mol), the radius of the geopotential conversion [from memory]
H_B = (0.0, 11000.0, 20000.0, 32000.0, 47000.0, 51000.0, 71000.0, 84852.0)   # geopotential layer bases, m
L_B = (-6.5e-3, 0.0, 1.0e-3, 2.8e-3, 0.0, -2.8e-3, -2.0e-3)                 # K/m
P_B_TABLE = (101325.0, 22632.1, 5474.89, 868.019, 110.906, 66.9389, 3.95642)  # the table's layer-base pressures, Pa
T_TOP_TABLE = 186.946                                      # K at 84.852 km
R_EARTH = 6371.0e3                                         # m, mean radius [S, from memory]
RHO_S = 101325.0 * M0 / (RSTAR * 288.15)                   # the standard's sea-level density, 1.2250 kg/m^3
# Refraction references [I, secondary (Wikipedia, 'Atmospheric refraction' and 'Air mass')]: Bennett 1982 (1010 hPa, 10 C);
# Kasten and Young 1989 (air mass about 38 at the horizon); the Sun's semi-diameter 16' (the sunset convention)
BENNETT_P, BENNETT_T = 101000.0, 283.15
X_HORIZON_KY = 38.0
SUN_SEMI_ARCMIN = 16.0
# Cherenkov [S; PDG 2024 eq. 34.43-34.44]: d2N/dEdx = (alpha z^2/hbar c) sin^2 theta = 370 sin^2 theta /(eV cm);
# Cherenkov's Nobel lecture (1958): 200 to 300 photons per cm in the visible [I]; de Naurois and Mazin 2015: angle about 1.5 deg at
# sea level and 0.2 deg at 30 km, (n - 1) = 2.92e-4 (P/P0)(288.15 K/T) [I]; electron threshold about 21 MeV at sea level [from memory]
PDG_370 = 370.0
# Vacuum Cherenkov and the vacuum's own effects [I, read at source unless marked]
CG_BOUND = 1e-23            # Coleman and Glashow 1999: c_p - c_gamma < 1e-23 from protons to 1e20 eV
SG_BOUND, SG_E_BOUND = 1.3e-15, 1.3e-13   # Stecker and Glashow 2001: 20 TeV photons (not Cherenkov); ~1 TeV cosmic-ray electrons
KS_KAPPA, KS_E_AUGER, KS_M_FE = 6e-20, 2.12e20, 52e9      # Klinkhamer and Schreck 2008: kappa_tr < 6e-20 from a 212 EeV Auger event taken as iron
KS_KAPPA_NEG = 9e-16        # their photon-decay side, from 30 TeV H.E.S.S. photons
LHAASO_E2_LIV = 1.27e24     # LHAASO 2021: second-order LIV scale above 1.27e24 eV (photon decay; superluminal photons)
E_HESS_ELECTRON = 40e12     # H.E.S.S. 2024: cosmic-ray electrons measured to 40 TeV
E_LHAASO_PHOTON = 1.1e15    # LHAASO 2021: 1.1 PeV photons from the Crab, so electrons of at least that energy [D; inferred, not detected: lock A3]
E_FLYS_EYE = 3.2e20         # Bird et al. 1995: 320 +- 90 EeV
FERMI_EQG2 = 1.3e20         # Vasileiou et al. 2013: E_QG,2 > 1.3e11 GeV (subluminal, GRB 090510)
A_E_PVLAS = 1.32e-24        # PVLAS 2020: A_e = 2 alpha^2 hbar^3/(45 mu0 me^4 c^5) in 1/T^2; n_par = 1 + 7 A_e B^2, n_perp = 1 + 4 A_e B^2
PVLAS_DN, PVLAS_DN_ERR, PVLAS_B = 12e-23, 17e-23, 2.5      # measured vacuum birefringence at 2.5 T
WIKI_SCHARNHORST = 1e-36    # Wikipedia's figure for 1 um [secondary]
# Space [I, secondary unless marked]: solar wind 3 to 10 per cm^3 at 1 AU; ISM average 1e6 per m^3; warm ionized medium 0.2 to 0.5
# per cm^3 over 20 to 50% of the volume; intergalactic about one proton per four cubic metres (Wikipedia). Crab pulsar DM 56.7712
# pc/cm^3 and parallax 0.53 mas (ATNF catalogue); the ionosphere's peak 1e12 /m^3 and interplanetary neutral hydrogen 1e5 /m^3 [from memory]
N_E_SOLAR_WIND, N_H_ISM, DM_CRAB, PX_CRAB_MAS, N_E_IONO, N_H_INTERPLANETARY = 7e6, 1e6, 56.7712, 0.53, 1e12, 1e5
OMEGA_B_H2, Y_P, F_IGM = 0.0224, 0.245, 0.84              # Planck 2018 baryon density, helium fraction, diffuse fraction [from memory]
OMEGA_B_MACQUART = 0.051                                   # Macquart et al. 2020: Omega_b = 0.051 h70^-1 from FRB dispersion [I]
# The record (trial 20's inputs): GRB 090510 limit (a), the cosmology, U15's bound, the shares, the laboratory's speed
GRB_DT, GRB_E, GRB_ELOW, GRB_Z, H0_KMSMPC, OM = 0.859, 28e9, 0.1e6, 0.903, 67.4, 0.3153
REC_ERES = 3.0e19
REC_F = (0.25, 0.085)
REC_T17_ELECTRON, REC_T17_PROTON = 2.6e-15, 1e-23
V_LAB = 369.82e3
E_SUN = 716.0                                              # V/m rms, sunlight (the record's section 8.2)
# Modelling choices [M]
LAB_T = 293.15
LAB_PRESSURES = ((101325.0, "1 atm"), (1.0e4, "0.1 atm"), (1.0e3, "0.01 atm"), (1.0, "1 Pa (rough vacuum)"),
                 (1.0e-4, "1e-4 Pa (high vacuum)"), (1.0e-7, "1e-7 Pa (ultra-high vacuum)"), (1.0e-10, "1e-10 Pa (extreme vacuum)"))
OBS_LAT_DEG = 40.0
Z_TOP = 120e3
LAM_SUNSET = 0.55                                          # um, the reference wavelength of the refraction tables
D_SPACING_FRACTION, N_DIPOLES = 1 / 20, 8000               # the dipole array: spacing lam_medium/20, 8000 dipoles (400 wavelengths)


# ---------------- the Sellmeier form (trial 20) and the gas form [S, D] ----------------
def n2_of(lam, B, C):
    lam = np.asarray(lam, dtype=float)
    lam2 = lam[..., None] ** 2
    return 1.0 + np.sum(B * lam2 / (lam2 - C), axis=-1)


def n_of(lam, B, C):
    return np.sqrt(n2_of(lam, B, C))


def dn_dlam(lam, B, C):
    lam = np.asarray(lam, dtype=float)
    lam2 = lam[..., None] ** 2
    return np.sum(-2.0 * B * C * lam[..., None] / (lam2 - C) ** 2, axis=-1) / (2.0 * n_of(lam, B, C))


def gas_n1(lam_um, coef):
    """n - 1 for a gas in refractiveindex.info's form 6: C0 + sum C_i/(D_i - 1/lam^2), lam in um. C0 is a term with its hold at
    infinite frequency (no inertia); each other term is an oscillator with its hold at lam_i = 1/sqrt(D_i) [S, D]."""
    s2 = 1.0 / np.asarray(lam_um, dtype=float) ** 2
    out = coef[0] + 0.0 * s2
    for i in range(1, len(coef), 2):
        out = out + coef[i] / (coef[i + 1] - s2)
    return out


def gas_dn1_dlam(lam_um, coef):
    lam = np.asarray(lam_um, dtype=float)
    s2 = 1.0 / lam ** 2
    out = 0.0 * lam
    for i in range(1, len(coef), 2):
        out = out - coef[i] * 2.0 * s2 / lam / (coef[i + 1] - s2) ** 2
    return out


def holds_eV(coef):
    """The holds (resonance energies) of the gas form, in eV, and the constant term."""
    return [hc_eVum * np.sqrt(coef[i + 1]) for i in range(1, len(coef), 2)], coef[0]


def water_vapour_n1(lam_um):
    s2 = 1.0 / np.asarray(lam_um, dtype=float) ** 2
    w0, w1, w2, w3 = H2O_VAP_W
    return 1.022e-8 * (w0 + w1 * s2 + w2 * s2 ** 2 + w3 * s2 ** 3)


def ciddor_Z(T, p, xw):
    """BIPM compressibility of moist air (Ciddor 1996, eq. 12) [I]."""
    t = T - 273.15
    a0_, a1, a2 = 1.58123e-6, -2.9331e-8, 1.1043e-10
    b0, b1, c0, c1, d, e_ = 5.707e-6, -2.051e-8, 1.9898e-4, -2.376e-6, 1.83e-11, -0.765e-8
    return 1 - (p / T) * (a0_ + a1 * t + a2 * t ** 2 + (b0 + b1 * t) * xw + (c0 + c1 * t) * xw ** 2) + (p / T) ** 2 * (d + e_ * xw ** 2)


def ciddor_n(lam_um, T, p, hum, xc_ppm):
    """Ciddor's refractive index of air [I, as copied in refractiveindex.info's script]: lam in um, T in K, p in Pa, hum the fractional
    humidity, xc the CO2 content in ppm. Each term is physics: the dry air's refractivity scales with the dry air's density, the water
    vapour's with its own, both measured at reference states; the density comes from the gas law with the BIPM compressibility."""
    lam_um = np.asarray(lam_um, dtype=float)
    s2 = 1.0 / lam_um ** 2
    t = T - 273.15
    R = 8.314510                                           # Ciddor's gas constant (differs from CODATA 2018 by 7e-7 relative)
    A, B, C, D = 1.2378847e-5, -1.9121316e-2, 33.93711047, -6.3431645e3
    svp = np.exp(A * T ** 2 + B * T + C + D / T) if t >= 0 else 10 ** (-2663.5 / T + 12.537)
    f = 1.00062 + 3.14e-8 * p + 5.6e-7 * t ** 2
    xw = f * hum * svp / p
    nas = 1 + (5792105.0 / (238.0185 - s2) + 167917.0 / (57.362 - s2)) * 1e-8
    naxs = 1 + (nas - 1) * (1 + 0.534e-6 * (xc_ppm - 450))
    nws = 1 + 1.022 * (295.235 + 2.6422 * s2 - 0.032380 * s2 ** 2 + 0.004028 * s2 ** 3) * 1e-8
    Ma = 1e-3 * (28.9635 + 12.011e-6 * (xc_ppm - 400))
    Mw = 0.018015
    rho_axs = 101325 * Ma / (ciddor_Z(288.15, 101325, 0) * R * 288.15)
    rho_ws = 1333 * Mw / (ciddor_Z(293.15, 1333, 1) * R * 293.15)
    Z = ciddor_Z(T, p, xw)
    rho_a = p * Ma / (Z * R * T) * (1 - xw)
    rho_w = p * Mw / (Z * R * T) * xw
    return 1 + (rho_a / rho_axs) * (naxs - 1) + (rho_w / rho_ws) * (nws - 1)


def n_std_air(lam_um):
    return ciddor_n(lam_um, 288.15, 101325.0, 0.0, 450.0)


def ll_y(n):
    """Lorentz-Lorenz function (n^2 - 1)/(n^2 + 2) = N alpha/(3 eps0) [S]."""
    return (n * n - 1) / (n * n + 2)


def n_from_y(y, local_field=True):
    """n from y = N alpha/(3 eps0): with Lorentz's local field n^2 = (1 + 2y)/(1 - y); without it n^2 = 1 + 3y [S]."""
    return np.sqrt((1 + 2 * y) / (1 - y)) if local_field else np.sqrt(1 + 3 * y)


def rayleigh_sigma(lam_m, n, N, Fk):
    """Rayleigh cross-section per molecule, 24 pi^3 ((n^2 - 1)/(n^2 + 2))^2 Fk/(lam^4 N^2) [S]: the dilute form of trial 20's
    (8 pi/3) k^4 (alpha/4 pi eps0)^2, with S = 1 (independent molecules) and the King factor Fk for the molecules' anisotropy."""
    return 24 * np.pi ** 3 * ll_y(n) ** 2 * Fk / (lam_m ** 4 * N ** 2)


# ---------------- the US Standard Atmosphere 1976 as a profile [I, S] ----------------
class Atmosphere:
    """Temperature linear in geopotential height within each layer, hydrostatic, ideal gas, fixed composition (M0) [S; the 1976
    model below 86 km]. T0 and P0 at sea level are parameters [M]: the standard has 288.15 K and 101325 Pa; other values keep the
    lapse rates and layer tops. Above 84.852 km geopotential an isothermal tail is used [M]; its density is below 1e-5 of the surface's."""

    def __init__(self, T0=288.15, P0=101325.0):
        self.T0, self.P0 = T0, P0
        Tb, Pb = [T0], [P0]
        for i in range(7):
            T, P, L, dH = Tb[-1], Pb[-1], L_B[i], H_B[i + 1] - H_B[i]
            if L == 0.0:
                Tn, Pn = T, P * np.exp(-G0 * M0 * dH / (RSTAR * T))
            else:
                Tn = T + L * dH
                Pn = P * (Tn / T) ** (-G0 * M0 / (RSTAR * L))
            Tb.append(Tn)
            Pb.append(Pn)
        self.Tb, self.Pb = Tb, Pb

    def state_H(self, H):
        """T (K), P (Pa), rho (kg/m^3), drho/dH (kg/m^4) at geopotential height H (m)."""
        i = 0
        while i < 6 and H > H_B[i + 1]:
            i += 1
        T, P, L, dH = self.Tb[i], self.Pb[i], L_B[i], H - H_B[i]
        if H > H_B[7]:
            T, P, L, dH = self.Tb[7], self.Pb[7], 0.0, H - H_B[7]
        if L == 0.0:
            Tn, Pn = T, P * np.exp(-G0 * M0 * dH / (RSTAR * T))
        else:
            Tn = T + L * dH
            Pn = P * (Tn / T) ** (-G0 * M0 / (RSTAR * L))
        rho = Pn * M0 / (RSTAR * Tn)
        drho_dH = -rho * (M0 * G0 / (RSTAR * Tn) + L / Tn)       # from dP/dH = -rho g0 and dT/dH = L
        return Tn, Pn, rho, drho_dH

    def state_z(self, z):
        """The same at geometric altitude z (m): H = R0 z/(R0 + z), drho/dz = drho/dH (R0/(R0 + z))^2 [S]."""
        H = R0_GEO * z / (R0_GEO + z)
        T, P, rho, drho_dH = self.state_H(H)
        return T, P, rho, drho_dH * (R0_GEO / (R0_GEO + z)) ** 2


Z_BREAKS = [R0_GEO * Hb / (R0_GEO - Hb) for Hb in H_B[1:]]   # geometric altitudes of the layer bases


def A_of_lam(lam_um):
    """(n - 1) per unit density: Ciddor's standard air divided by the standard's sea-level density [M: Lorentz-Lorenz scaling]."""
    return (float(n_std_air(lam_um)) - 1.0) / RHO_S


def refraction_rad(h_app_deg, lam_um, atm, z_obs=0.0, z_top=Z_TOP):
    """Astronomical refraction for the apparent altitude h_app, by the ray integral in a spherically layered atmosphere [S]:
    R = int C/sqrt(u^2 - C^2) (-dn/dz)/n dz, with u = n(z)(R_E + z) and C = n(z_obs)(R_E + z_obs) cos(h_app) (Bouguer's invariant,
    Snell's law for spherical layers); z = z_obs + t^2 removes the horizon's square-root singularity."""
    A = A_of_lam(lam_um)
    rho0 = atm.state_z(z_obs)[2]
    n0 = 1.0 + A * rho0
    C = n0 * (R_EARTH + z_obs) * np.cos(np.radians(h_app_deg))

    def f(t):
        z = z_obs + t * t
        T, P, rho, drho = atm.state_z(z)
        n = 1.0 + A * rho
        u = n * (R_EARTH + z)
        s = u * u - C * C
        if s <= 0.0:
            return 0.0
        return C / np.sqrt(s) * (-A * drho / n) * 2.0 * t

    pts = [np.sqrt(zb - z_obs) for zb in Z_BREAKS if z_obs < zb < z_top]
    return quad(f, 0.0, np.sqrt(z_top - z_obs), points=pts, limit=500, epsabs=1e-12, epsrel=1e-9)[0]


def refraction_arcmin(h_app_deg, lam_um, atm, z_obs=0.0):
    return refraction_rad(h_app_deg, lam_um, atm, z_obs) / ARCMIN


def column_density(atm, z_obs=0.0, z_top=Z_TOP):
    """int rho dz from the observer up (kg/m^2) [S]."""
    pts = [zb for zb in Z_BREAKS if z_obs < zb < z_top]
    return quad(lambda z: atm.state_z(z)[2], z_obs, z_top, points=pts, limit=500)[0]


def air_mass(h_app_deg, lam_um, atm, z_obs=0.0, z_top=Z_TOP):
    """Relative air mass along the refracted ray, int rho ds / int rho dz, with ds = u dz/sqrt(u^2 - C^2) [S]."""
    A = A_of_lam(lam_um)
    rho0 = atm.state_z(z_obs)[2]
    C = (1.0 + A * rho0) * (R_EARTH + z_obs) * np.cos(np.radians(h_app_deg))

    def f(t):
        z = z_obs + t * t
        rho = atm.state_z(z)[2]
        u = (1.0 + A * rho) * (R_EARTH + z)
        s = u * u - C * C
        if s <= 0.0:
            return 0.0
        return rho * u / np.sqrt(s) * 2.0 * t

    pts = [np.sqrt(zb - z_obs) for zb in Z_BREAKS if z_obs < zb < z_top]
    slant = quad(f, 0.0, np.sqrt(z_top - z_obs), points=pts, limit=500, epsabs=1e-9, epsrel=1e-9)[0]
    return slant / column_density(atm, z_obs, z_top)


def bennett_arcmin(h_app_deg, P=BENNETT_P, T=BENNETT_T):
    """Bennett's 1982 formula, R = cot(h + 7.31/(h + 4.4)) arcmin for 1010 hPa and 10 C, scaled by (P/1010 hPa)(283.15 K/T) [I, secondary]."""
    hh = np.asarray(h_app_deg, dtype=float)
    R = 1.0 / np.tan(np.radians(hh + 7.31 / (hh + 4.4)))
    return R * (P / BENNETT_P) * (BENNETT_T / T)


def kasten_young(h_app_deg):
    z = 90.0 - h_app_deg
    return 1.0 / (np.cos(np.radians(z)) + 0.50572 * (6.07995 + 90.0 - z) ** -1.6364)


# ---------------- Cherenkov [S] ----------------
def sin2_cone(n1, beta):
    """sin^2 theta_c = 1 - 1/(beta^2 n^2), from n - 1 = n1 without cancellation: (beta^2 n^2 - 1)/(beta^2 n^2) with
    beta^2 n^2 - 1 = beta^2 n1 (2 + n1) - (1 - beta^2) [D]."""
    b2 = beta * beta
    num = b2 * n1 * (2.0 + n1) - (1.0 - b2)
    return num / (1.0 + num) if num > 0.0 else 0.0


def photons_per_m(n1fun, beta, lam1_m, lam2_m, z=1):
    """Frank-Tamm: int 2 pi alpha z^2/lam^2 (1 - 1/(beta^2 n^2)) dlam over the band, where beta n > 1 [S; PDG eq. 34.44]. n1fun gives n - 1."""
    def f(lam):
        return 2 * np.pi * alpha_fs * z * z / lam ** 2 * sin2_cone(n1fun(lam), beta)
    return quad(f, lam1_m, lam2_m, limit=200)[0]


def energy_per_m_eV(n1fun, beta, lam1_m, lam2_m, z=1):
    def f(lam):
        return (hc_eVum * 1e-6 / lam) * 2 * np.pi * alpha_fs * z * z / lam ** 2 * sin2_cone(n1fun(lam), beta)
    return quad(f, lam1_m, lam2_m, limit=200)[0]


def n_water(lam_m):
    return float(n_of(lam_m * 1e6, H2O_B, H2O_C))


def n1_water(lam_m):
    return n_water(lam_m) - 1.0


def n_bk7(lam_m):
    return float(n_of(lam_m * 1e6, BK7_B, BK7_C))


def n1_bk7(lam_m):
    return n_bk7(lam_m) - 1.0


def make_n1_air(T, p):
    """n - 1 of dry air at (T, p) from Ciddor's formula [I]."""
    return lambda lam_m: float(ciddor_n(lam_m * 1e6, T, p, 0.0, 450.0)) - 1.0


def threshold_gamma(n):
    return n / np.sqrt(n * n - 1.0)


def threshold_from_n1(n1):
    """gamma_th and beta_th from n - 1 = n1, written to avoid cancellation for tiny n1: n^2 - 1 = n1 (2 + n1) [D]."""
    n2m1 = n1 * (2.0 + n1)
    return (1.0 + n1) / np.sqrt(n2m1), 1.0 / (1.0 + n1)


def delta_bound(M_eV, E_eV):
    """The vacuum's n - 1 at which a particle of mass M and energy E is just at threshold: 1/beta - 1, computed stably [D]."""
    inv_g2 = (M_eV / E_eV) ** 2
    one_minus_beta = inv_g2 / (1.0 + np.sqrt(1.0 - inv_g2))
    return one_minus_beta / (1.0 - one_minus_beta)


def array_peak(beta_n, kd, N):
    """The far field of N dipoles along a line, spaced d, each driven when the charge passes (phase omega z/v): the array factor
    |sum_j exp(i psi j)|^2/N^2 with psi = k d (1/(beta n) - cos theta). Returns the peak angle (deg) and the normalized peak [D]."""
    th = np.radians(np.arange(0.0, 90.0001, 0.01))
    psi = kd * (1.0 / beta_n - np.cos(th))
    half = psi / 2.0
    with np.errstate(divide='ignore', invalid='ignore'):
        S = np.where(np.abs(np.sin(half)) < 1e-15, 1.0, (np.sin(N * half) / (N * np.sin(half))) ** 2)
    i = int(np.argmax(S))
    return np.degrees(th[i]), float(S[i])


def relay_delta(Eg, Eres, f):
    """n - 1 and n^2 - 1 of the record's one-oscillator relay, n^2 = f + (1 - f)/(1 - x^2), x = E_gamma/E_res, stable for small x [M, D]."""
    x2 = (np.asarray(Eg, dtype=float) / Eres) ** 2
    n2m1 = (1.0 - f) * x2 / (1.0 - x2)
    return n2m1 / (np.sqrt(1.0 + n2m1) + 1.0), n2m1


def emission_margin(E, y, M, Eres, f):
    """Four-momentum conservation for e -> e + photon(E_g = yE) with the photon's index n(E_g) and the electron's ordinary dispersion:
    cos theta = (1/(beta n))(1 + (n^2 - 1) y/2) (Ginzburg's quantum form of the Cherenkov condition). Emission is possible when
    cos theta <= 1. Returns b - a - c - ac, the sign of 1 - cos theta, with a = 1/beta - 1, b = n - 1, c = (n^2 - 1) y/2 [D]."""
    inv_g2 = (M / E) ** 2
    omb = inv_g2 / (1.0 + np.sqrt(1.0 - inv_g2))
    a = omb / (1.0 - omb)
    b, n2m1 = relay_delta(y * E, Eres, f)
    cc = n2m1 * y / 2.0
    return b - a - cc - a * cc


def analytic_threshold(M, Eres, f):
    """E_th = (27/4)^(1/4) sqrt(M E_res) (1 - f)^(-1/4): the hardest photon that pays, at E_g = 2E/3 [D]."""
    return (27.0 / 4.0) ** 0.25 * np.sqrt(M * Eres) * (1.0 - f) ** -0.25


def numeric_threshold(M, Eres, f):
    ys = np.linspace(0.02, 0.98, 1921)

    def Gmax(E):
        return float(np.max(emission_margin(E, ys, M, Eres, f)))
    Ea = analytic_threshold(M, Eres, f)
    return brentq(Gmax, 0.5 * Ea, 2.0 * Ea, xtol=1e-6 * Ea, rtol=1e-12, maxiter=200)


def classical_loss_eV_per_m(E, M, Eres, f):
    """Classical Frank-Tamm energy loss (alpha/hbar c) int E_g (1 - 1/(beta^2 n^2)) dE_g over the photon energies where beta n > 1,
    up to E_g = E (the recoil is ignored: an estimate of the rate once above threshold) [D]."""
    inv_g2 = (M / E) ** 2

    def s_of(Eg):
        b, n2m1 = relay_delta(Eg, Eres, f)
        num = n2m1 * (1.0 - inv_g2) - inv_g2               # beta^2 n^2 - 1
        return num / (1.0 + num)

    def f_int(Eg):
        s = s_of(Eg)
        return Eg * s if s > 0 else 0.0
    # where does emission start? beta^2 n^2 = 1 -> n^2 - 1 = inv_g2/(1 - inv_g2)
    x2_min = inv_g2 / (1.0 - inv_g2) / ((1.0 - f) + inv_g2 / (1.0 - inv_g2))
    Eg_min = Eres * np.sqrt(x2_min)
    if Eg_min >= E:
        return 0.0, Eg_min
    val = quad(f_int, Eg_min, E, limit=200)[0]
    return alpha_fs / hbarc_eVm * val, Eg_min


# ======================================================================================
# the derived constants of air at 1 atm, 15 C
N_ATM = 101325.0 / (kB * 288.15)                           # molecules per m^3 at 15 C, 1 atm (ideal gas)
n_d_air = float(n_std_air(LAM_D))
n_F_air = float(n_std_air(LAM_F))
n_C_air = float(n_std_air(LAM_C))
y_air_d = ll_y(n_d_air)
y_per_molecule = y_air_d / N_ATM                           # N alpha/(3 eps0) per molecule per m^3, at the d line
alpha_air_A3 = 3 * y_air_d / (4 * np.pi * N_ATM) * 1e30
atm_std = Atmosphere()

say("\n=== Code checks ===")
# K1: air assembled from its molecules against Ciddor and Peck-Reeder
def mixture_n1(lam_um, T=288.15, P=101325.0):
    """Lorentz-Lorenz additivity: y_mix = sum x_i y_i, each gas's y scaled from its reference state by the ideal gas law [S, M]."""
    y = 0.0
    for g, d in GASES.items():
        if d["x"] == 0.0:
            continue
        n_i = 1.0 + float(gas_n1(lam_um, d["coef"]))
        y_i = ll_y(n_i) * (P / d["P"]) * (d["T"] / T)
        y += d["x"] * y_i
    return n_from_y(y) - 1.0


k1 = max(abs(mixture_n1(lam) - (float(n_std_air(lam)) - 1.0)) for lam in (0.5, LAM_D, 0.633, 0.7))
check("K1 dry air assembled from N2, O2, Ar and CO2 (Lorentz-Lorenz additivity) agrees with Ciddor's air to 1e-6 in n - 1 at 500 to 700 nm",
      k1 < 1e-6, f"(largest difference {k1:.2e}; mixture {mixture_n1(0.633):.6e}, Ciddor {float(n_std_air(0.633))-1:.6e} at 633 nm)")

# K2: Rayleigh cross-section of N2 at 532 nm against the measured value
N_N2_ref = GASES["N2"]["P"] / (kB * GASES["N2"]["T"])
n_N2_532 = 1.0 + float(gas_n1(0.532, GASES["N2"]["coef"]))
sig_N2_532 = rayleigh_sigma(0.532e-6, n_N2_532, N_N2_ref, FK_N2)
check("K2 N2's Rayleigh cross-section from its refractivity (with the King factor) is within 5% of the measured 5.1e-31 m^2 at 532 nm",
      abs(sig_N2_532 / SIGMA_N2_532_MEAS - 1) < 0.05, f"({sig_N2_532:.3e} m^2; {sig_N2_532/SIGMA_N2_532_MEAS - 1:+.1%})")

# K3: the dispersion-measure constant
k_DM = e ** 2 / (8 * np.pi ** 2 * eps0 * me * c)                           # s m^2 (delay = k_DM * DM[m^-2] / nu^2)
k_DM_ms = k_DM * (PC * 1e6) / 1e18 * 1e3                                   # ms per (pc cm^-3) at 1 GHz
check("K3 the plasma delay constant e^2/(8 pi^2 eps0 me c) equals 4.148808 ms GHz^2 per pc/cm^3 (Lorimer and Kramer, from memory) to 1e-4",
      abs(k_DM_ms / 4.148808 - 1) < 1e-4, f"({k_DM_ms:.6f} ms)")

# K4: the dipole array: coherence on the cone
kd = 2 * np.pi * D_SPACING_FRACTION
th_pk, S_pk = array_peak(0.9 * n_water(0.4e-6), kd, N_DIPOLES)
th_c_expected = np.degrees(np.arccos(1.0 / (0.9 * n_water(0.4e-6))))
th_sub, S_sub = array_peak(0.7 * n_water(0.4e-6), kd, N_DIPOLES)      # beta n = 0.93: below threshold
check("K4 the molecules' wavelets add coherently only on the cone cos theta = 1/(beta n) (peak within 0.1 deg, beta = 0.9 in water) and not at"
      " all below threshold (beta = 0.7: normalized peak below 1e-3)",
      abs(th_pk - th_c_expected) < 0.1 and S_sub < 1e-3,
      f"(peak at {th_pk:.2f} deg against {th_c_expected:.2f}; normalized peak {S_pk:.3f} above and {S_sub:.1e} below threshold)")

# K5: the gas threshold momentum scales as 1/sqrt(P)
p_sqrtP = []
for P in (101325.0, 10132.5, 1013.25, 101.325, 10.1325):
    n1 = float(ciddor_n(0.4, 293.15, P, 0.0, 450.0)) - 1.0
    gam, bet = threshold_from_n1(n1)
    p_th = MPI_MEV * gam * bet                           # MeV/c
    p_sqrtP.append(p_th * np.sqrt(P))
k5 = (max(p_sqrtP) - min(p_sqrtP)) / p_sqrtP[0]
check("K5 the Cherenkov threshold momentum of a gas scales as P^(-1/2) from 1 atm to 1e-4 atm to 1e-3", k5 < 1e-3, f"(spread {k5:.1e})")

# K6: Klinkhamer and Schreck's threshold against the Cherenkov formula
kap = KS_KAPPA
n2m1_ks = 2 * kap / (1 - kap)
d_ks = n2m1_ks / 2.0
d_ks = n2m1_ks / (2.0 + d_ks)
E_ks = KS_M_FE * np.sqrt((1 + kap) / (2 * kap))          # their eq. 9a with xi = 2 kappa
E_ch = KS_M_FE * (1 + d_ks) / np.sqrt(d_ks * (2 + d_ks))
check("K6 Klinkhamer and Schreck's vacuum-Cherenkov threshold M sqrt((1 + xi/2)/xi), xi = 2 kappa, is the Cherenkov threshold gamma_th = n/sqrt(n^2 - 1)"
      " with n^2 = (1 + kappa)/(1 - kappa), to 1e-10", abs(E_ks / E_ch - 1) < 1e-10, f"({E_ks:.6e} eV against {E_ch:.6e} eV)")

# K7: the non-dispersive relay threshold against trial 17's E0/sqrt(1 - f)
s17 = 1e-6
f17 = 1 - s17
d17 = 1 / np.sqrt(f17) - 1
E_th_delta = ME_MEV * (1 + d17) / np.sqrt(d17 * (2 + d17))
E_th_t17 = ME_MEV / np.sqrt(1 - f17)
check("K7 with the relay's bare speed c/sqrt(f) as matter's limit (reading R-i), the Cherenkov threshold M n_v/sqrt(n_v^2 - 1) with n_v = 1/sqrt(f)"
      " equals trial 17's E0/sqrt(1 - f) to 1e-5 at 1 - f = 1e-6", abs(E_th_delta / E_th_t17 - 1) < 1e-5, f"({abs(E_th_delta/E_th_t17-1):.1e})")

# K8: the dispersive threshold, numerical against analytic
E_num = numeric_threshold(ME_MEV * 1e6, REC_ERES, 0.0)
E_ana = analytic_threshold(ME_MEV * 1e6, REC_ERES, 0.0)
E_num_f = numeric_threshold(ME_MEV * 1e6, REC_ERES, 0.25)
E_ana_f = analytic_threshold(ME_MEV * 1e6, REC_ERES, 0.25)
check("K8 the vacuum-Cherenkov threshold in the relay's dispersive index, from four-momentum conservation maximized over the photon's energy,"
      " equals (27/4)^(1/4) sqrt(M E_res)(1 - f)^(-1/4) to 1e-3 (f = 0 and 1/4)",
      abs(E_num / E_ana - 1) < 1e-3 and abs(E_num_f / E_ana_f - 1) < 1e-3, f"({E_num:.4e} vs {E_ana:.4e} eV; {E_num_f:.4e} vs {E_ana_f:.4e} eV)")

# K9: the standard atmosphere's layer pressures
k9 = max(abs(atm_std.Pb[i] / P_B_TABLE[i] - 1) for i in range(7))
check("K9 the layer model reproduces the 1976 table's pressures at the six layer bases to 2e-5 and its 186.946 K at 84.852 km to 1e-5",
      k9 < 2e-5 and abs(atm_std.Tb[7] / T_TOP_TABLE - 1) < 1e-5, f"(largest pressure difference {k9:.1e}; T_top = {atm_std.Tb[7]:.3f} K)")

# K10: Lorentz-Lorenz density scaling against Ciddor's full formula at 5 km
T5, P5, rho5, _ = atm_std.state_z(5000.0)
n_scaled = 1.0 + A_of_lam(LAM_SUNSET) * rho5
n_cidd = float(ciddor_n(LAM_SUNSET, T5, P5, 0.0, 450.0))
check("K10 n - 1 scaled with density from the standard's sea level agrees with Ciddor's full (T, p) formula at 5 km to 2e-8 in n",
      abs(n_scaled - n_cidd) < 2e-8, f"({n_scaled - 1:.6e} vs {n_cidd - 1:.6e}; T = {T5:.2f} K, P = {P5:.0f} Pa)")

# K11: the ray trace against Bennett's formula (scaled to the standard's 15 C, 1013.25 hPa); the tolerances are the spread between
# standard profiles and tables (about 1' at the horizon, a few per cent at 10 deg)
tol_bennett = {0.0: 2.0, 2.0: 0.6, 5.0: 0.3, 10.0: 0.2, 20.0: 0.1, 45.0: 0.05}
diffs = {}
for hh, tol in tol_bennett.items():
    diffs[hh] = refraction_arcmin(hh, LAM_SUNSET, atm_std) - float(bennett_arcmin(hh, 101325.0, 288.15))
check("K11 the ray trace through the standard atmosphere agrees with Bennett's formula (scaled to 15 C, 1013.25 hPa) within 2' at the horizon,"
      " 0.6' at 2 deg, 0.3' at 5 deg, 0.2' at 10 deg, 0.1' at 20 deg and 0.05' at 45 deg",
      all(abs(diffs[hh]) < tol for hh, tol in tol_bennett.items()),
      "(" + "; ".join(f"{hh:g} deg: {diffs[hh]:+.3f}'" for hh in tol_bennett) + ")")

# K12: the horizon air mass
X0 = air_mass(0.0, LAM_SUNSET, atm_std)
check("K12 the air mass along the ray at the horizon is within 10% of Kasten and Young's 38", abs(X0 / X_HORIZON_KY - 1) < 0.10, f"({X0:.2f})")

# K13: at 45 degrees the refraction scales with n0 - 1 between a cold and a warm sea level
atm_cold, atm_warm = Atmosphere(T0=273.15), Atmosphere(T0=303.15)
r45_cold, r45_warm = refraction_arcmin(45.0, LAM_SUNSET, atm_cold), refraction_arcmin(45.0, LAM_SUNSET, atm_warm)
ratio_n1 = atm_cold.state_z(0.0)[2] / atm_warm.state_z(0.0)[2]
check("K13 at 45 deg the refraction scales as the observer's n0 - 1 (the density ratio 303.15/273.15) to 1e-3 between a 0 C and a 30 C sea level",
      abs((r45_cold / r45_warm) / ratio_n1 - 1) < 1e-3, f"(ratio {r45_cold/r45_warm:.5f} against {ratio_n1:.5f})")

# K14: the Frank-Tamm band integral against the PDG's 370 sin^2 theta per eV per cm
n_const = 1.333
dN_int = photons_per_m(lambda lam: n_const - 1.0, 1.0, 300e-9, 600e-9) / 100.0       # per cm
dE_band = hc_eVum / 0.300 - hc_eVum / 0.600                                            # eV
dN_pdg = PDG_370 * (1 - 1 / n_const ** 2) * dE_band
check("K14 the Frank-Tamm integral over 300 to 600 nm at fixed n equals the PDG's 370 sin^2 theta photons per eV per cm within 1%",
      abs(dN_int / dN_pdg - 1) < 0.01, f"({dN_int:.1f} vs {dN_pdg:.1f} per cm; alpha/(hbar c) = {alpha_fs/hbarc_eVm/100:.1f} per eV per cm)")

# K15: the Euler-Heisenberg constant
A_e = 2 * alpha_fs ** 2 * hbar ** 3 / (45 * mu0 * me ** 4 * c ** 5)
check("K15 the Euler-Heisenberg constant 2 alpha^2 hbar^3/(45 mu0 me^4 c^5) equals PVLAS's 1.32e-24 /T^2 within 1%",
      abs(A_e / A_E_PVLAS - 1) < 0.01, f"({A_e:.4e} /T^2)")

# ======================================================================================
say("\n=== Q1. Air from its molecules, at 1 atm and 15 C ===")
say(f"N = P/(k_B T) = {N_ATM:.4e} molecules per m^3; spacing N^(-1/3) = {N_ATM**(-1/3)*1e9:.3f} nm (glass: 0.34 nm) [S].")
say("Each gas's polarizability from its refractivity by Lorentz-Lorenz, and the holds of its fit (the hold is the pull of the nucleus and the"
    " other electrons on the displaced cloud; its energy is a far-ultraviolet transition) [I -> D]:")
say(f"{'gas':>5} {'n - 1 (589 nm, ref.)':>21} {'T_ref':>6} {'alpha/(4 pi eps0), A^3':>23} {'holds (eV)':>22} {'constant term':>14} {'x in air':>9}   source")
for gname, d in GASES.items():
    n1 = float(gas_n1(LAM_D, d["coef"]))
    Nref = d["P"] / (kB * d["T"])
    apol = 3 * ll_y(1 + n1) / (4 * np.pi * Nref) * 1e30
    holds, c0 = holds_eV(d["coef"])
    say(f"{gname:>5} {n1:21.4e} {d['T']:6.2f} {apol:23.3f} {', '.join(f'{E:.2f}' for E in holds):>22} {c0:14.3e} {d['x']:9.6f}   {d['src']}")
wv = float(water_vapour_n1(LAM_D))
N_wv = 1333.0 / (kB * 293.15)
say(f"{'H2O':>5} {wv:21.4e} {293.15:6.2f} {3*ll_y(1+wv)/(4*np.pi*N_wv)*1e30:23.3f} {'(polynomial fit)':>22} {'-':>14} {'(humidity)':>9}   Ciddor's water-vapour term, 20 C, 1333 Pa")
say(f"   Hydrogen atoms, for space: alpha/(4 pi eps0) = (9/2) a0^3 = {4.5*a0**3*1e30:.4f} A^3 exactly [S].")
say(f"\nAir (Ciddor's standard air) at the d line: n - 1 = {n_d_air-1:.6e}; alpha/(4 pi eps0) = {alpha_air_A3:.3f} A^3 per molecule [D];")
say(f"   Peck and Reeder: {float(gas_n1(LAM_D, AIR_PECK_REEDER)):.6e}; Birch and Downs (Edlen): {float(gas_n1(LAM_D, AIR_BIRCH_DOWNS)):.6e};"
    f" the four gases assembled: {mixture_n1(LAM_D):.6e} (K1).")
hc_, c0c = holds_eV(AIR_CIDDOR)
hp_, c0p = holds_eV(AIR_PECK_REEDER)
say(f"   Ciddor's two holds: {hc_[0]:.2f} and {hc_[1]:.2f} eV (no constant term); Peck and Reeder's: {hp_[0]:.2f} and {hp_[1]:.2f} eV plus a constant"
    f" {c0p:.3e}, {c0p/(n_d_air-1):.1%} of n - 1: a response with no inertia and no dispersion, a fit's stand-in for far-ultraviolet strength [D].")
E_d = hc_eVum / LAM_D
say(f"   Light at the d line, {E_d:.3f} eV, lies {hc_[1]/E_d:.1f} and {hc_[0]/E_d:.1f} times below Ciddor's holds (glass: 4.2 and 7.6 times, trial 20).")
# the local field
n_ind = n_from_y(y_air_d, local_field=False)
lf_term = n_d_air - n_ind
say(f"\nLorentz's local field in a gas [S, D]: y = N alpha/(3 eps0) = {y_air_d:.4e} at 1 atm ({y_air_d:.1e} of the way to the polarization"
    f" catastrophe; glass 0.30).")
say(f"   With the local field n^2 = (1 + 2y)/(1 - y); without it n^2 = 1 + 3y. The difference in n is {lf_term:.2e} at 1 atm, {lf_term/(n_d_air-1):.1e} of n - 1,")
say(f"   and it falls as the square of the density: it equals 1e-8 (the formulas' own accuracy, from memory) at {np.sqrt(1e-8/lf_term):.2f} atm and 1e-10 at"
    f" {np.sqrt(1e-10/lf_term):.3f} atm. The measured check on it in gases is the second refractivity virial coefficient (from memory: of order 1 cm^6/mol^2"
    f" for N2, 1e-5 of the first term at 1 atm).")
# shares
f_air = 1 / n_d_air ** 2
say(f"\nThe record's shares [D]: the bare space (the vacuum between the molecules) carries f = 1/n^2 = {f_air:.6f} of eps at 1 atm; the molecules"
    f" 1 - f = {1-f_air:.3e}; their energy share (1 - f)/2 = {(1-f_air)/2:.3e} (glass 0.283; the relay's quons 0.375 at f = 1/4).")
# dispersion
V_air = (n_d_air - 1) / (n_F_air - n_C_air)
dn_d = float((n_std_air(LAM_D + 1e-4) - n_std_air(LAM_D - 1e-4)) / 2e-4)
ng_air = n_d_air - LAM_D * dn_d
say(f"Dispersion [D]: n_F - n_C = {n_F_air - n_C_air:.3e}; V = (n_d - 1)/(n_F - n_C) = {V_air:.1f} (glass 64); n_g - n = {ng_air - n_d_air:.2e} at the d line,"
    f" {(ng_air-1)/(n_d_air-1):.4f} of n - 1 above it.")
# scattering
sig_air_550 = rayleigh_sigma(0.55e-6, float(n_std_air(0.55)), N_ATM, FK_AIR)
h_air_550 = N_ATM * sig_air_550
col_std = column_density(atm_std)
Ncol_std = col_std / (M0 / NA)
tau_550 = sig_air_550 * Ncol_std
say(f"Scattering [S, D]: Rayleigh cross-section per molecule at 550 nm {sig_air_550:.3e} m^2 (King factor {FK_AIR}, from memory); extinction at sea level"
    f" {h_air_550:.3e} /m, mean free path {1/h_air_550/1e3:.1f} km;")
say(f"   the vertical column {Ncol_std:.4e} molecules/m^2 gives a Rayleigh optical depth {tau_550:.4f} at 550 nm (from memory, about {TAU_R_550_MEM}); S = 1:"
    f" the molecules scatter independently, as a gas should (glass: S = 0.03, trial 20).")
say("Absorption [S]: air's own holds lie in the far ultraviolet (N2 below 100 nm, O2's Schumann-Runge bands below 200 nm), so the gases are lossless in the"
    " visible as glass is; what the real sky absorbs in the visible is ozone's Chappuis band (vertical optical depth about 0.03 at 600 nm for 300 DU, from"
    " memory) and O2's narrow bands, each in proportion to its own density.")

# ======================================================================================
say("\n=== Q2. Thinning the matter: from 1 atm to the vacuum of space ===")
say("Every quantity of a dilute gas is linear in N (n - 1, the dispersion, 1 - f, the scattering and absorption per length), except Lorentz's local"
    " field, which is quadratic and already at 1e-8 at 1 atm [S, D]. Air's molecules per m^3 and hydrogen atoms for space; electrons are the plasma rows.")
sig_air_d = rayleigh_sigma(LAM_D * 1e-6, n_d_air, N_ATM, FK_AIR)
sigH_d = 24 * np.pi ** 3 * ((4 * np.pi / 3) * 4.5 * a0 ** 3) ** 2 / (LAM_D * 1e-6) ** 4      # per H atom, y = (4 pi/3) N alpha'
rows = []
for P, label in LAB_PRESSURES:
    N = P / (kB * LAB_T)
    rows.append((label + f", {LAB_T - 273.15:.0f} C", N, N * y_per_molecule, N * sig_air_d, "air"))
T10, P10, _, _ = atm_std.state_z(10000.0)
N10 = P10 / (kB * T10)
rows.insert(1, (f"10 km (shower maximum): {P10/1e2:.0f} hPa, {T10:.0f} K", N10, N10 * y_per_molecule, N10 * sig_air_d, "air"))
T30, P30, _, _ = atm_std.state_z(30000.0)
N30 = P30 / (kB * T30)
rows.insert(2, (f"30 km: {P30/1e2:.1f} hPa, {T30:.0f} K", N30, N30 * y_per_molecule, N30 * sig_air_d, "air"))
yH = (4 * np.pi / 3) * 4.5 * a0 ** 3
rows.append(("interplanetary neutral H, 1e5 /m^3 (from memory)", N_H_INTERPLANETARY, N_H_INTERPLANETARY * yH, N_H_INTERPLANETARY * sigH_d, "H"))
rows.append(("interstellar, 1e6 H per m^3 (average)", N_H_ISM, N_H_ISM * yH, N_H_ISM * sigH_d, "H"))
rho_crit = 3 * (H0_KMSMPC * 1e3 / (1e6 * PC)) ** 2 / (8 * np.pi * G)
n_b0 = OMEGA_B_H2 / (H0_KMSMPC / 100) ** 2 * rho_crit / mp
rows.append((f"intergalactic, all baryons as neutral H, {n_b0:.2f} /m^3 (it is ionized)", n_b0, n_b0 * yH, n_b0 * sigH_d, "H"))
say(f"{'medium':>58} {'N (1/m^3)':>10} {'n - 1 (589 nm)':>14} {'n_F - n_C':>10} {'1 - f':>10} {'local field':>11} {'scatter 1/m':>11} {'mean free path':>22}")
for label, N, y, hsc, kind in rows:
    n_ll = n_from_y(y)
    n1 = n_ll - 1
    disp = (n_F_air - n_C_air) * N / N_ATM if kind == "air" else n1 * (n_F_air - n_C_air) / (n_d_air - 1)
    lf = n_ll - n_from_y(y, local_field=False)
    mfp = 1 / hsc
    if mfp < 1e9:
        mfp_s = f"{mfp:.3e} m"
    elif mfp < 1e13:
        mfp_s = f"{mfp/c:.3e} light-s"
    elif mfp < 1e17:
        mfp_s = f"{mfp/AU:.3e} AU"
    else:
        mfp_s = f"{mfp/PC:.3e} pc"
    say(f"{label:>58} {N:10.2e} {n1:14.3e} {disp:10.2e} {1-1/n_ll**2:10.2e} {lf:11.1e} {hsc:11.2e} {mfp_s:>22}")
say("   (The local-field column is n with Lorentz's field minus n without it. Dispersion and scattering are the gas's own, with S = 1; for the hydrogen"
    " rows the dispersion is scaled from air's ratio, a stand-in.)")
# comparisons
H0 = H0_KMSMPC * 1e3 / (1e6 * PC)


def hub(z):
    return np.sqrt(OM * (1 + z) ** 3 + 1 - OM)


T0 = quad(lambda z: 1 / hub(z), 0, GRB_Z)[0] / H0
T2 = quad(lambda z: (1 + z) ** 2 / hub(z), 0, GRB_Z)[0] / H0
lim2 = GRB_DT / T2
k_vac_max = (hc_eVum * 1e-6 / GRB_E) / (4 * np.pi * c * T0)
dn_EH_25 = 3 * A_e * PVLAS_B ** 2
lamC_bar = hbar / (me * c)
dn_sch_1um = -(11 * np.pi ** 2 / 8100) * alpha_fs ** 2 * (lamC_bar / 1e-6) ** 4
n1_per_N = (n_d_air - 1) / N_ATM
say(f"\nWhere air's n - 1 would equal the vacuum's own numbers [D]: the molecules per m^3 at which (n - 1) at 589 nm equals")
for name, val in (("Euler-Heisenberg's birefringence at 2.5 T (PVLAS's field), 3 A_e B^2", dn_EH_25),
                  ("the Scharnhorst shift between plates 1 um apart", abs(dn_sch_1um)),
                  ("GRB 090510's allowed group-index difference, 0.1 MeV to 28 GeV (the record)", lim2),
                  ("Klinkhamer and Schreck's bound on an isotropic vacuum index, 6e-20", KS_KAPPA),
                  ("Coleman and Glashow's bound on c_p - c_gamma, 1e-23", CG_BOUND)):
    Nx = val / n1_per_N
    say(f"   {name}: {val:.1e} -> N = {Nx:.1e} /m^3 = {Nx*kB*LAB_T:.1e} Pa at 20 C")
say(f"   An extreme laboratory vacuum (1e-10 Pa) still carries n - 1 = {1e-10/(kB*LAB_T)*n1_per_N:.1e}: above the vacuum's own allowed dispersion;"
    f" the interstellar gas's {N_H_ISM*yH*1.5:.1e} matches Euler-Heisenberg's effect in PVLAS's magnet; nothing in space thins below the Scharnhorst"
    f" shift except by being ionized, when the free electrons take over (Q3).")
say("\nIn the record's relay terms [D]: the bare space of the gas is the vacuum at c throughout; the gas's share 1 - f falls linearly to zero, the"
    " medium's speed rises to the bare speed, and the limit is eps0 itself, untouched. Thinning matter measures matter's contribution; it never"
    " reaches inside eps0. A relay vacuum would be a gas whose density n and stiffness K cannot be changed by any experiment.")

# ======================================================================================
say("\n=== Q3. Space is not empty: the free electrons ===")
say("A free electron is an oscillator with no hold (K = 0, its resonance at zero frequency): n^2 = 1 - omega_p^2/omega^2, so n < 1 and the"
    " dispersion falls as 1/omega^2 [S]. Bound charges give n > 1 with dispersion rising towards their holds (Q1). Both live in space.")
omega_opt = 2 * np.pi * c / (LAM_D * 1e-6)
plasma_rows = (("ionosphere F-layer peak, 1e12 /m^3 (from memory)", N_E_IONO), ("solar wind at 1 AU, 7e6 /m^3 (3 to 10 per cm^3)", N_E_SOLAR_WIND),
               ("interstellar (from the Crab's DM and distance, below)", None), (f"intergalactic, {n_b0:.2f} baryons/m^3, ionized", None))
d_crab = 1e3 / PX_CRAB_MAS * PC                                 # m (parallax 0.53 mas -> 1.89 kpc)
n_e_ism = DM_CRAB * PC * 1e6 / d_crab                           # electrons per m^3
n_e_igm = F_IGM * (1 - Y_P / 2) * n_b0
say(f"{'medium':>58} {'n_e (1/m^3)':>11} {'f_p':>10} {'n - 1 (589 nm)':>14} {'n - 1 (1.4 GHz)':>15} {'n - 1 (100 MHz)':>15}")
for label, ne in plasma_rows:
    if ne is None:
        ne = n_e_ism if label.startswith("interstellar") else n_e_igm
    wp2 = ne * e ** 2 / (eps0 * me)
    fp = np.sqrt(wp2) / (2 * np.pi)
    vals = [-wp2 / (2 * w ** 2) for w in (omega_opt, 2 * np.pi * 1.4e9, 2 * np.pi * 1e8)]
    fps = f"{fp:.2e} Hz" if fp < 1e3 else (f"{fp/1e3:.2f} kHz" if fp < 1e6 else f"{fp/1e6:.2f} MHz")
    say(f"{label:>58} {ne:11.2e} {fps:>10} {vals[0]:14.2e} {vals[1]:15.2e} {vals[2]:15.2e}")
say(f"   The Crab pulsar: DM = {DM_CRAB} pc/cm^3 (ATNF), parallax {PX_CRAB_MAS} mas -> {d_crab/PC:.0f} pc, mean n_e = {n_e_ism*1e-6:.3f} /cm^3 along the line of"
    f" sight [D from I]; its pulse arrives {k_DM*DM_CRAB*PC*1e6*(1/0.4e9**2 - 1/1.4e9**2):.3f} s later at 400 MHz than at 1.4 GHz [D].")
say("   Below f_p nothing propagates: the ionosphere reflects radio below about 10 MHz, which is U34's plasma gap in the sky (Aspden's charged lattice"
    " would do the same to light below hundreds of keV).")
# the intergalactic medium through FRBs
DM_z = lambda z: c * n_e_igm * quad(lambda zz: (1 + zz) / hub(zz), 0, z)[0] / H0 / (PC * 1e6)   # pc cm^-3
say(f"\nThe intergalactic electrons [D, from memory: Omega_b h^2 = {OMEGA_B_H2}, Y_p = {Y_P}, diffuse fraction {F_IGM}]: n_e = {n_e_igm:.3f} /m^3 today;"
    f" the dispersion measure to z = 1 is {DM_z(1.0):.0f} pc/cm^3 and to GRB 090510's z = {GRB_Z} {DM_z(GRB_Z):.0f} pc/cm^3 (the Macquart relation; the FRB"
    f" measurement gives Omega_b = {OMEGA_B_MACQUART} h70^-1).")
nu_low = GRB_ELOW * e / h
dt_plasma = k_DM * DM_z(GRB_Z) * PC * 1e6 * (1 / nu_low ** 2 - (GRB_ELOW / GRB_E) ** 2 / nu_low ** 2)
say(f"   The plasma delay of GRB 090510's 0.1 MeV light behind its 28 GeV photon over that path: {dt_plasma:.1e} s, against the measured |dt| < {GRB_DT} s and the"
    f" vacuum's allowed group-index difference {lim2:.2e} [D]. The real medium of space does not touch the record's test of the vacuum.")
say(f"   At 1.4 GHz the same path would delay by {k_DM*DM_z(GRB_Z)*PC*1e6/1.4e9**2:.2f} s: space's own dispersion is 1e20 times the vacuum's allowed one, but with the"
    f" opposite sign and the opposite energy dependence (falling as 1/E^2 where the relay's rises as E^2).")
wp2_ism = n_e_ism * e ** 2 / (eps0 * me)
say(f"   The interstellar plasma's n - 1 at 28 GeV: {-wp2_ism/(2*(GRB_E*e/hbar)**2):.1e}; the interstellar atoms' at 589 nm: {N_H_ISM*yH*1.5:.1e}.")

# ======================================================================================
say("\n=== Q4. The vacuum's own effects: what can be changed, and by how much ===")
say("The two knobs the real vacuum offers are boundaries and fields; neither is a density [S].")
say(f"Scharnhorst [I, Scharnhorst 1998 eq. 10]: between plates L apart, n_perp(0) = 1 - (11 pi^2/8100) alpha^2 (hbar/(m c L))^4 for low frequencies:")
for L in (1e-6, 1e-7, 1e-8):
    dn = -(11 * np.pi ** 2 / 8100) * alpha_fs ** 2 * (lamC_bar / L) ** 4
    say(f"   L = {L*1e9:.0f} nm: n - 1 = {dn:.2e} (light faster than c by that fraction)")
say(f"   Wikipedia's 'one part in 1e36 for 1 um' [secondary] disagrees with the formula ({dn_sch_1um:.1e} at 1 um; 1e-36 is the formula's value at"
    f" {(abs(dn_sch_1um)/WIKI_SCHARNHORST)**0.25*1e-6*1e6:.1f} um); the formula from the primary review is used.")
say("   Its sign is a thinned gas's: the plates remove modes, the vacuum's response falls, n falls below 1. It is the only known way to make the vacuum"
    " 'thinner', and it is 1e-32. The front velocity stays c by the Kramers-Kronig argument (Scharnhorst 1998).")
B_c = me ** 2 * c ** 2 / (e * hbar)
say(f"\nEuler-Heisenberg [I, PVLAS 2020]: A_e = {A_e:.3e} /T^2 (K15); n_par = 1 + 7 A_e B^2, n_perp = 1 + 4 A_e B^2; birefringence 3 A_e B^2:")
for B in (1.0, PVLAS_B, 1e4):
    say(f"   B = {B:g} T: n_par - 1 = {7*A_e*B**2:.2e}, n_perp - 1 = {4*A_e*B**2:.2e}, dn = {3*A_e*B**2:.2e}")
say(f"   PVLAS measured dn = ({PVLAS_DN*1e23:.0f} +- {PVLAS_DN_ERR*1e23:.0f}) x 1e-23 at {PVLAS_B} T against QED's {dn_EH_25:.2e}: not yet seen, consistent. The critical"
    f" field B_c = m^2 c^2/(e hbar) = {B_c:.3e} T; the weak-field form holds below it.")
B_sun = E_SUN / c
say(f"   In sunlight (E_rms = {E_SUN:.0f} V/m, B = E/c = {B_sun:.1e} T) the vacuum's own nonlinearity is dn ~ {3*A_e*B_sun**2:.1e}: the vacuum is linear to that part,"
    " where glass in the same light is linear to 1e-9 (trial 20's electron shift).")
say("   Its sign is a medium's: a field polarizes the vacuum's virtual pairs and n rises above 1, with no dispersion below the electron's 511 keV,"
    " the vacuum's own hold.")
say(f"\nBeside them, the record's bounds on the vacuum [the record]: group-index difference below {lim2:.1e} between 0.1 MeV and 28 GeV, extinction"
    f" coefficient below {k_vac_max:.1e} at 28 GeV, hold above {REC_ERES:.1e} eV (U15).")

# ======================================================================================
say("\n=== Q5. Cherenkov light in the molecular picture ===")
say("A charge moving at v = beta c polarizes each molecule it passes; each molecule re-radiates a wavelet at c/n. Along the track the wavelets have"
    " the phase omega z/v at birth and travel k z cos theta to a distant observer; they add coherently only where omega/v = k cos theta, that is"
    f" cos theta = 1/(beta n) (K4: the array of {N_DIPOLES} dipoles peaks at {th_pk:.2f} deg against {th_c_expected:.2f} deg for beta = 0.9 in water;"
    f" for beta = 0.7 the normalized sum is {S_sub:.1e}: nothing adds up). The work the charge does against the field of the molecules it has polarized is"
    " the light: Frank and Tamm's d2N/dx dlam = 2 pi alpha z^2/lam^2 (1 - 1/(beta^2 n^2)) [S]. Each factor is physics: alpha z^2 for the charge that does"
    " the polarizing and the field it feels back, 1/lam^2 because shorter waves have more dipoles per wavelength in step, and sin^2 theta = 1 - 1/(beta^2 n^2)"
    " for the part of the wavelets that reaches the cone.")
say("Ginzburg's quantum correction (the photon's recoil) is of order E_gamma/E: below 1e-5 for electrons in matter (Frank's Nobel lecture) and it is used"
    " in Q6, where it matters.")
say(f"\nWater (Daimon and Masumura 2007, 20 C) [I -> D]:")
say(f"{'beta':>6} {'theta (400 nm)':>14} {'theta (600 nm)':>14} {'photons/cm 300-600 nm':>22} {'photons/cm 400-700 nm':>22} {'energy 300-600 nm (keV/cm)':>27}")
beta_th_w = 1 / n_water(0.4e-6)
for beta in (1.0, 0.95, 0.9, 0.8, beta_th_w * 1.001):
    th4 = np.degrees(np.arccos(min(1.0, 1 / (beta * n_water(0.4e-6)))))
    th6 = np.degrees(np.arccos(min(1.0, 1 / (beta * n_water(0.6e-6)))))
    N36 = photons_per_m(n1_water, beta, 300e-9, 600e-9) / 100
    N47 = photons_per_m(n1_water, beta, 400e-9, 700e-9) / 100
    W36 = energy_per_m_eV(n1_water, beta, 300e-9, 600e-9) / 100 / 1e3
    say(f"{beta:6.4f} {th4:14.2f} {th6:14.2f} {N36:22.1f} {N47:22.1f} {W36:27.3f}")
say(f"   Threshold beta = 1/n = {beta_th_w:.4f} at 400 nm (electron kinetic energy {(threshold_gamma(n_water(0.4e-6))-1)*ME_MEV*1e3:.0f} keV); Cherenkov's lecture:"
    f" 200 to 300 photons per cm in the visible [I]; the angle-velocity law was measured 'in complete agreement' (Cherenkov 1958).")
say(f"\nGlass (N-BK7) [I -> D] at beta = 1: theta = {np.degrees(np.arccos(1/n_bk7(0.4e-6))):.2f} deg (400 nm), {np.degrees(np.arccos(1/n_bk7(0.6e-6))):.2f} deg (600 nm);"
    f" {photons_per_m(n1_bk7, 1.0, 300e-9, 600e-9)/100:.1f} photons/cm in 300 to 600 nm; threshold electron kinetic energy"
    f" {(threshold_gamma(n_bk7(0.4e-6))-1)*ME_MEV*1e3:.0f} keV.")
n1_air_sl = make_n1_air(288.15, 101325.0)
n1_air_400 = n1_air_sl(0.4e-6)
gam_air, bet_air = threshold_from_n1(n1_air_400)
say(f"\nAir at sea level (Ciddor, 15 C, 1013.25 hPa, dry) [I -> D]: n - 1 = {n1_air_400:.4e} at 400 nm; at beta = 1 the cone half-angle is"
    f" {np.degrees(np.arccos(1/(1+n1_air_400))):.3f} deg = sqrt(2(n - 1)) (de Naurois and Mazin: about 1.5 deg at sea level);")
say(f"   gamma_th = {gam_air:.2f}: thresholds e {gam_air*ME_MEV:.1f} MeV (about 21 MeV, from memory), mu {gam_air*MMU_MEV/1e3:.2f} GeV, pi {gam_air*MPI_MEV/1e3:.2f} GeV,"
    f" p {gam_air*MP_MEV/1e3:.1f} GeV (total energies);")
say(f"   {photons_per_m(n1_air_sl, 1.0, 300e-9, 600e-9):.1f} photons per metre in 300 to 600 nm at beta = 1 (the light of cosmic-ray showers).")
say(f"\nAir and gases at falling pressure [D]: the threshold energy E_th = gamma_th M c^2 with gamma_th = n/sqrt(n^2 - 1) ~ 1/sqrt(2(n - 1)), so"
    " E_th rises as 1/sqrt(density) and the yield falls as the density (K5), which is how gas Cherenkov counters are tuned.")
say(f"{'medium':>44} {'n - 1 (400 nm)':>14} {'gamma_th':>9} {'E_th e (MeV)':>12} {'E_th mu (GeV)':>13} {'E_th pi (GeV)':>13} {'E_th p (GeV)':>12} {'1 - beta_th':>11} {'photons/m':>9}")
gas_rows = [(f"air, {label}, 20 C", make_n1_air(LAB_T, P)) for P, label in LAB_PRESSURES[:6]]
for z_km in (0.0, 5.0, 10.0, 20.0, 30.0):
    Tz, Pz, _, _ = atm_std.state_z(z_km * 1e3)
    gas_rows.append((f"air, {z_km:.0f} km: {Pz/100:.1f} hPa, {Tz:.0f} K", make_n1_air(Tz, Pz)))
gas_rows = sorted(gas_rows, key=lambda r: -r[1](0.4e-6))
for gname in ("He", "N2", "Ar", "CO2"):
    d = GASES[gname]
    coef, Tr = d["coef"], d["T"]
    gas_rows.append((f"{gname}, 1 atm, {Tr - 273.15:.0f} C (counter gas)", lambda lam_m, coef=coef: float(gas_n1(lam_m * 1e6, coef))))
for label, n1f in gas_rows:
    n1 = n1f(0.4e-6)
    gam, bet = threshold_from_n1(n1)
    say(f"{label:>44} {n1:14.3e} {gam:9.3g} {gam*ME_MEV:12.4g} {gam*MMU_MEV/1e3:13.4g} {gam*MPI_MEV/1e3:13.4g} {gam*MP_MEV/1e3:12.4g} {1-bet:11.2e}"
        f" {photons_per_m(n1f, 1.0, 300e-9, 600e-9):9.3g}")
say("   As the density goes to zero: n -> 1, beta_th = 1/n -> 1 and E_th -> infinity. There is no Cherenkov light in an empty vacuum, because nothing in"
    " it can be polarized by the passing charge and radiate [S, D]. Cherenkov light exists in matter only because the particle's limiting speed is set"
    " by the vacuum (c) while light's phase speed in matter is set by the molecules (c/n).")

# ======================================================================================
say("\n=== Q6. Vacuum Cherenkov radiation: the test an aether must pass ===")
say("If the vacuum carried light slower than the limiting speed of charged particles, by a vacuum index n_v = 1 + delta, every charged particle"
    " above E_th = M n_v/sqrt(n_v^2 - 1) ~ M/sqrt(2 delta) would radiate and stop (Coleman and Glashow 1999; the rate is fast, Q6c). The particles seen bound"
    " delta [S; I]:")
say(f"{'particle and energy':>62} {'M (eV)':>10} {'delta < (n_v - 1)':>17} {'1 - f allowed (R-i)':>19}   source")
bounds = (("electron, 40 TeV (cosmic-ray electron spectrum)", ME_MEV * 1e6, E_HESS_ELECTRON, "H.E.S.S. 2024 [I]"),
          ("electron, 1.1 PeV (the Crab's PeV photons need electrons of at least that energy)", ME_MEV * 1e6, E_LHAASO_PHOTON, "LHAASO 2021 [I, D]"),
          ("proton, 3.2e20 eV", MP_MEV * 1e6, E_FLYS_EYE, "Fly's Eye 1995 [I]"),
          ("proton, 2.12e20 eV (Auger hybrid event, taken as a proton)", MP_MEV * 1e6, KS_E_AUGER, "Klinkhamer and Schreck 2008 [I]"),
          ("iron nucleus, 2.12e20 eV (the same event taken as iron, M = 52 GeV)", KS_M_FE, KS_E_AUGER, "Klinkhamer and Schreck 2008 [I]"))
for label, M, E, src in bounds:
    d = delta_bound(M, E)
    say(f"{label:>62} {M:10.3e} {d:17.2e} {2*d:19.2e}   {src}")
say(f"   Published: Coleman and Glashow c_p - c_gamma < {CG_BOUND:.0e} (protons to 1e20 eV); Klinkhamer and Schreck kappa_tr < {KS_KAPPA:.0e} (98% CL, iron"
    f" assumed, energy lowered by its error) and -kappa_tr < {KS_KAPPA_NEG:.0e} (photon decay, 30 TeV photons); Stecker and Glashow {SG_BOUND:.1e} from 20 TeV"
    f" photons' absorption (not Cherenkov) and {SG_E_BOUND:.1e} from 1 TeV electrons; the record's trial 17: {REC_T17_ELECTRON:.1e} (electrons) and about"
    f" {REC_T17_PROTON:.0e} (protons, F2).")
say("   Both signs are tested: a vacuum with n_v > 1 (light slower than matter's limit) by vacuum Cherenkov radiation; n_v < 1 (light faster) by photon"
    f" decay to pairs, which LHAASO's 1.4 PeV photons bound (second-order scale above {LHAASO_E2_LIV:.1e} eV). The relay's sign is the first.")
say("\nQ6a. The record's relay, non-dispersive part [D]. Its bare space carries light at c/sqrt(f); the medium carries it at c. If matter's limiting"
    " speed were the bare speed (trial 17's reading R-i), the vacuum index seen by matter would be n_v = 1/sqrt(f):")
for f in REC_F:
    d = 1 / np.sqrt(f) - 1
    say(f"   f = {f}: n_v - 1 = {d:.3f}; electrons radiate above {ME_MEV*(1+d)/np.sqrt(d*(2+d)):.3f} MeV total energy, protons above {MP_MEV*(1+d)/np.sqrt(d*(2+d))/1e3:.3f} GeV:"
        f" excluded by the proton bound by a factor {d/delta_bound(MP_MEV*1e6, E_FLYS_EYE):.0e}.")
share_max = 2 * delta_bound(MP_MEV * 1e6, E_FLYS_EYE)
say(f"   Under R-i the quons' share of eps0 would have to be below 1 - f = {share_max:.1e} (Fly's Eye), {2*delta_bound(MP_MEV*1e6, KS_E_AUGER):.1e} (Auger as a proton),"
    f" {2*delta_bound(ME_MEV*1e6, E_LHAASO_PHOTON):.1e} (the Crab's electrons, inferred): trial 17's verdict (F2: about {REC_T17_PROTON:.0e}) recomputed (K7).")
say("\nQ6b. The record's relay, dispersive part [D]. Below its hold the relay's index rises as n^2 = f + (1 - f)/(1 - x^2), x = E_gamma/E_res. If a"
    " charged particle keeps light's low-energy speed as its limit but its own ordinary dispersion while the photon takes the relay's (reading R-iii [M],"
    " the lock's amendment A1), four-momentum conservation lets it"
    " radiate a photon of energy yE when delta(yE)(1 - y) > M^2/(2E^2); the hardest photon that pays has y = 2/3 and the threshold is")
say(f"   E_th = (27/4)^(1/4) sqrt(M E_res) (1 - f)^(-1/4) (K8).")
say(f"{'E_res (eV)':>12} {'f':>6} {'E_th electron':>14} {'E_th proton':>12} {'loss length of a 40 TeV electron':>34} {'of a 1.1 PeV electron':>22}")
for Eres in (REC_ERES, 1e21, 1e24, 1e25):
    for f in (0.0, 0.25):
        Eth_e = analytic_threshold(ME_MEV * 1e6, Eres, f)
        Eth_p = analytic_threshold(MP_MEV * 1e6, Eres, f)
        out = []
        for Ee in (E_HESS_ELECTRON, E_LHAASO_PHOTON):
            dEdx, Egmin = classical_loss_eV_per_m(Ee, ME_MEV * 1e6, Eres, f)
            out.append(f"{Ee/dEdx:.1e} m" if dEdx > 0 else "no emission")
        say(f"{Eres:12.1e} {f:6.2f} {Eth_e/1e12:11.3g} TeV {Eth_p/1e12:9.3g} TeV {out[0]:>34} {out[1]:>22}")
Eres_min_hess = {f: np.sqrt(4 / 27) * np.sqrt(1 - f) * E_HESS_ELECTRON ** 2 / (ME_MEV * 1e6) for f in (0.0, 0.25)}
Eres_min_crab = {f: np.sqrt(4 / 27) * np.sqrt(1 - f) * E_LHAASO_PHOTON ** 2 / (ME_MEV * 1e6) for f in (0.0, 0.25)}
say(f"   With U15's hold ({REC_ERES:.1e} eV) electrons above {analytic_threshold(ME_MEV*1e6, REC_ERES, 0.0)/1e12:.0f} TeV would radiate (f = 0). The electrons seen push the hold up:"
    f" E_res > {Eres_min_hess[0.0]:.1e} eV from H.E.S.S.'s 40 TeV, E_res > {Eres_min_crab[0.0]:.1e} eV from the Crab's PeV electrons (inferred; f = 0;"
    f" {Eres_min_crab[0.25]:.1e} at f = 1/4): {Eres_min_crab[0.0]/REC_ERES:.0e} times U15's bound, if matter does not share the relay's dispersion.")
say("   If matter shares it (reading R-ii: the particle's inertia is its own dressed field, with the same dispersion as light's), a photon of energy"
    " yE is always slower than the electron that would emit it, and nothing radiates: the test is blind by construction, as trial 17 found for the"
    " bare speed. Fermi's time-of-flight bound (E_QG,2 > 1.3e20 eV, subluminal quadratic) does not depend on that choice.")
say("\nQ6c. How fast a vacuum-Cherenkov loss would be [D, classical Frank-Tamm]: see the loss lengths above; once above threshold an electron loses its energy"
    " within metres or less, so a source at any astronomical distance delivers none above threshold. The bounds are therefore the thresholds themselves.")
say("\nQ6d. The test in one sentence [D]: Cherenkov light in matter exists because matter slows light but not the particle. The same light in the vacuum"
    " would mean the vacuum slows light but not the particle; its absence to 1e-23 says that whatever sets light's speed in the vacuum sets matter's"
    " limiting speed too, to that part. That is trial 17's result, now with the cosmic-ray numbers at source.")

# ======================================================================================
say("\n=== Q7. The setting Sun ===")
say("Ray trace through the US Standard Atmosphere 1976 (K9), with n - 1 from Ciddor's air scaled by density (K10); refraction R(h) for the apparent"
    " altitude h, by Bouguer's invariant n r sin z = const [S].")
h_list = (0.0, 0.25, 0.5, 1.0, 2.0, 5.0, 10.0, 20.0, 45.0, 90.0)
say(f"{'apparent altitude':>18} {'R (550 nm), arcmin':>18} {'Bennett (scaled)':>17} {'Wikipedia table (10 C)':>23} {'air mass X':>10}")
wiki = {0.0: 35.4, 2.0: 18.4, 5.0: 9.9, 10.0: 5.3, 45.0: "<1", 90.0: 0.0}
R_std = {}
for hh in h_list:
    R_std[hh] = refraction_arcmin(hh, LAM_SUNSET, atm_std)
    X = air_mass(hh, LAM_SUNSET, atm_std) if hh < 89.0 else 1.0
    say(f"{hh:18.2f} {R_std[hh]:18.3f} {float(bennett_arcmin(hh, 101325.0, 288.15)):17.3f} {str(wiki.get(hh, '')):>23} {X:10.3f}")
say(f"   At 45 deg the rule R = (n0 - 1) tan z gives {(n_d_air-1)/ARCMIN:.3f}' (n0 - 1 of the standard air at 589 nm): the refraction above 20 deg is the"
    " observer's own n - 1 times tan z; near the horizon it is the whole profile [S, D].")
# the Sun
D_sun = 2 * SUN_SEMI_ARCMIN
R0_std = R_std[0.0]
h_up = brentq(lambda hu: hu - refraction_arcmin(hu / 60.0, LAM_SUNSET, atm_std) + R0_std - D_sun, 0.0, D_sun, xtol=1e-6)
flat = D_sun - h_up
rate_40 = 0.25 * np.cos(np.radians(OBS_LAT_DEG))
rate_0 = 0.25
say(f"\nThe Sun (diameter {D_sun:.0f}', its semi-diameter 16' by the sunset convention) with its lower limb apparently on the horizon: the upper limb appears at"
    f" {h_up:.2f}', so the disc is flattened by {flat:.2f}' ({flat/D_sun:.1%}; Wikipedia: about 5', 1/6) [D].")
say(f"   The delay of sunset: the upper limb disappears when its true altitude is -R(0) = {-R0_std:.1f}' instead of 0. At the equinox the Sun sinks at"
    f" 0.25' per second times cos(latitude): {rate_40:.4f}'/s at {OBS_LAT_DEG:.0f} deg, so sunset is {R0_std/rate_40:.0f} s = {R0_std/rate_40/60:.1f} min late;"
    f" at the equator {R0_std/rate_0:.0f} s [D, M]. The convention's true altitude of the centre at sunset, -(R + 16') = {-(R0_std+16):.0f}'.")
# colours
R_col = {lam: refraction_arcmin(0.0, lam, atm_std) for lam in (0.45, 0.53, 0.65, 0.70)}
say(f"   The colours at the horizon [D]: R(450 nm) = {R_col[0.45]:.2f}', R(530) = {R_col[0.53]:.2f}', R(650) = {R_col[0.65]:.2f}', R(700) = {R_col[0.70]:.2f}';"
    f" green above red by {(R_col[0.53]-R_col[0.65])*60:.0f}\" and blue above red by {(R_col[0.45]-R_col[0.70])*60:.0f}\": the green flash, which lasts about"
    f" {(R_col[0.53]-R_col[0.65])/rate_40:.1f} s at {OBS_LAT_DEG:.0f} deg (Wikipedia: no more than about two seconds). It is the holds' dispersion (Q1) made visible.")
# reddening
tau_b = rayleigh_sigma(0.45e-6, float(n_std_air(0.45)), N_ATM, FK_AIR) * Ncol_std
tau_r = rayleigh_sigma(0.65e-6, float(n_std_air(0.65)), N_ATM, FK_AIR) * Ncol_std
say(f"   Reddening [D]: Rayleigh optical depths {tau_b:.4f} (450 nm) and {tau_r:.4f} (650 nm) vertically; through X = {X0:.1f} air masses at the horizon the"
    f" transmittances are {np.exp(-X0*tau_b):.2e} (blue) and {np.exp(-X0*tau_r):.3f} (red), a ratio of {np.exp(-X0*(tau_r-tau_b)):.0f}; overhead {np.exp(-tau_b):.3f} and"
    f" {np.exp(-tau_r):.3f}. This is the molecules scattering independently (S = 1). Ozone and aerosols redden further (not modelled).")
# observers
say(f"\nThe observer's place and weather [D, M: the same lapse rates, the sea-level T0 and P0 changed; the observer inside the standard profile]:")
say(f"{'observer':>44} {'P (hPa)':>8} {'T (K)':>7} {'R(0)':>7} {'R(0.5)':>7} {'R(5)':>7} {'R(45)':>7} {'X(0)':>6} {'flatten':>8} {'delay 40N (s)':>13} {'green-red (\")':>13}")
cases = (("sea level, standard (15 C, 1013.25 hPa)", atm_std, 0.0), ("mountain, 4000 m", atm_std, 4000.0), ("aircraft, 11000 m", atm_std, 11000.0),
         ("sea level, 0 C", atm_cold, 0.0), ("sea level, 30 C", atm_warm, 0.0), ("sea level, 15 C, 990 hPa", Atmosphere(P0=99000.0), 0.0),
         ("sea level, 15 C, 1030 hPa", Atmosphere(P0=103000.0), 0.0))
for label, atm, zobs in cases:
    Tz, Pz, _, _ = atm.state_z(zobs)
    R0_ = refraction_arcmin(0.0, LAM_SUNSET, atm, zobs)
    Rh = refraction_arcmin(0.5, LAM_SUNSET, atm, zobs)
    R5 = refraction_arcmin(5.0, LAM_SUNSET, atm, zobs)
    R45 = refraction_arcmin(45.0, LAM_SUNSET, atm, zobs)
    Xh = air_mass(0.0, LAM_SUNSET, atm, zobs)
    hu = brentq(lambda hu: hu - refraction_arcmin(hu / 60.0, LAM_SUNSET, atm, zobs) + R0_ - D_sun, 0.0, D_sun, xtol=1e-6)
    gr = (refraction_arcmin(0.0, 0.53, atm, zobs) - refraction_arcmin(0.0, 0.65, atm, zobs)) * 60
    say(f"{label:>44} {Pz/100:8.1f} {Tz:7.2f} {R0_:7.2f} {Rh:7.2f} {R5:7.3f} {R45:7.3f} {Xh:6.1f} {D_sun-hu:8.2f} {R0_/rate_40:13.0f} {gr:13.0f}")
say(f"   Bennett's rule scales the whole table by (P/1010 hPa)(283.15 K/T): density. At 45 deg the ray trace does the same (K13). At the horizon it does"
    f" not: a colder atmosphere is also thinner (its scale height falls with T), so R(0) rises faster than 1/T; from 30 C to 0 C the density ratio is"
    f" {ratio_n1:.3f} and the horizon refraction ratio {refraction_arcmin(0.0, LAM_SUNSET, atm_cold)/refraction_arcmin(0.0, LAM_SUNSET, atm_warm):.3f} [D].")
say("   Above the atmosphere's bulk (the aircraft) the refraction and the flattening fall with the density at the observer, and the horizon air mass with it:"
    " the Sun sets whiter, rounder and later by less.")

# ======================================================================================
say("\n=== Lessons, in the lock's form (section 6) ===")
say(f"V1. Air is glass thinned about a thousandfold in density: holds of the same kind (Ciddor's {hc_[1]:.1f} and {hc_[0]:.1f} eV, {hc_[1]/E_d:.1f} and {hc_[0]/E_d:.1f} times above yellow light),"
    f" the same Lorentz-Lorenz rule (its four gases assembled give Ciddor's air to {k1:.0e}, K1), the same shares with f = 1/n^2: the molecules carry"
    f" {1-f_air:.1e} of eps at 1 atm and (1 - f)/2 = {(1-f_air)/2:.1e} of the energy. Lorentz's local field is {lf_term:.0e} in n at 1 atm and falls as the"
    f" density squared: in a gas each molecule answers the applied field alone, and the medium is the sum of its molecules.")
say(f"    A gas's dispersion is the holds' ({V_air:.0f} against glass's 64 for V), its scattering is its molecules' acting independently (S = 1: {h_air_550:.1e} /m, a"
    f" mean free path of {1/h_air_550/1e3:.0f} km at 550 nm, a Rayleigh optical depth {tau_550:.3f}; K2 ties the formula to N2's measured cross-section), and its"
    f" visible absorption is nil but for trace gases: every term maps to a molecule.")
say(f"V2. Thinning is linear and never reaches eps0. From 1 atm to 1e-10 Pa n - 1 falls from {n_d_air-1:.1e} to {1e-10/(kB*LAB_T)*n1_per_N:.1e}, the dispersion, the share"
    f" 1 - f, the scattering and the absorption with it, all in proportion to N; the bare space is the vacuum at c throughout and f -> 1. The limit is eps0,"
    f" not an explanation of it: nothing in a thinned gas tells what eps0 is made of. The vacuum's own effects sit where air's n - 1 would be at"
    f" {dn_EH_25/n1_per_N:.0e} /m^3 (Euler-Heisenberg at 2.5 T: interstellar density) and {abs(dn_sch_1um)/n1_per_N:.0e} /m^3 (Scharnhorst at 1 um: below intergalactic);"
    f" the vacuum's allowed dispersion (GRB 090510) at {lim2/n1_per_N:.0e} /m^3, an extreme laboratory vacuum's density.")
say(f"V3. Space is a plasma, and a plasma is the one medium whose hold is at zero: n < 1, with the dispersion falling as 1/E^2. The interstellar electrons"
    f" ({n_e_ism*1e-6:.3f} /cm^3 from the Crab's dispersion measure) give n - 1 = {-wp2_ism/(2*(2*np.pi*1.4e9)**2):.1e} at 1.4 GHz and {-wp2_ism/(2*(GRB_E*e/hbar)**2):.0e} at 28 GeV;"
    f" the intergalactic electrons ({n_e_igm:.2f} /m^3, measured through FRB dispersion) delay GRB 090510's 0.1 MeV light behind its 28 GeV photon by {dt_plasma:.0e} s."
    f" The real medium of space is measured, it is a plasma, and it leaves the record's vacuum test untouched. Aspden's charged lattice would be this medium"
    f" with its plasma frequency at hundreds of keV (U34), as the ionosphere is to radio below 10 MHz.")
say(f"V4. The vacuum has two knobs and no density. Boundaries lower its index (Scharnhorst: {dn_sch_1um:.0e} at 1 um; the sign of a thinned gas; the front stays at c);"
    f" fields raise it (Euler-Heisenberg: {dn_EH_25:.0e} at 2.5 T, a medium's sign, with the hold at 511 keV; PVLAS has not yet seen it). Both are responses of"
    f" the vacuum's own charges, the virtual pairs, and both are 1e-23 or less. A relay vacuum is a gas whose density and stiffness no experiment can change:"
    f" what can be tested is only its dispersion (the record's {lim2:.0e}), its loss ({k_vac_max:.0e}) and, through matter, its frame (V6).")
say(f"V5. Cherenkov light is the molecular model's own prediction. The passing charge polarizes the molecules; their wavelets add on the cone cos theta = 1/(beta n)"
    f" and nowhere else (K4), and the work the charge does against their field is Frank and Tamm's light. Water: {photons_per_m(n1_water, 1.0, 300e-9, 600e-9)/100:.0f} photons/cm in"
    f" 300 to 600 nm at beta = 1 ({photons_per_m(n1_water, 1.0, 400e-9, 700e-9)/100:.0f} in 400 to 700 nm; Cherenkov's 200 to 300 in the visible), at"
    f" {np.degrees(np.arccos(1/n_water(0.5e-6))):.1f} deg; glass {photons_per_m(n1_bk7, 1.0, 300e-9, 600e-9)/100:.0f}/cm at {np.degrees(np.arccos(1/n_bk7(0.5e-6))):.1f} deg;"
    f" air at sea level {photons_per_m(n1_air_sl, 1.0, 300e-9, 600e-9):.0f}/m at {np.degrees(np.arccos(1/(1+n1_air_400))):.2f} deg with the electron threshold at"
    f" {gam_air*ME_MEV:.0f} MeV (muon {gam_air*MMU_MEV/1e3:.1f} GeV, pion {gam_air*MPI_MEV/1e3:.1f} GeV, proton {gam_air*MP_MEV/1e3:.0f} GeV).")
n1_air_30 = make_n1_air(T30, P30)(0.4e-6)
say(f"    With pressure the threshold rises as 1/sqrt(density) and the yield falls as the density (K5); at 30 km the cone is {np.degrees(np.arccos(1/(1+n1_air_30))):.2f} deg"
    f" and the electron threshold {threshold_from_n1(n1_air_30)[0]*ME_MEV:.0f} MeV. As the density goes to zero the threshold speed goes to c: no"
    f" Cherenkov light in the vacuum, because nothing in it is polarized by the charge.")
say(f"V6. The vacuum-Cherenkov test. Cherenkov light in matter exists because matter slows light but not the particle. Its absence in the vacuum, for"
    f" protons to {E_FLYS_EYE:.1e} eV and electrons to {E_LHAASO_PHOTON:.1e} eV, says light's speed in the vacuum and matter's limiting speed agree to"
    f" {delta_bound(MP_MEV*1e6, E_FLYS_EYE):.0e} (non-dispersive). For the record's relay under reading R-i that is 1 - f < {share_max:.0e} (trial 17's F2 recomputed, K7),"
    f" where the relay needs 1 - f of 0.75 to 0.915. For its dispersive part, under reading R-iii (matter's limit is light's low-energy speed, its dispersion its own; lock A1), the hold must lie above {Eres_min_crab[0.0]:.0e} eV, {Eres_min_crab[0.0]/REC_ERES:.0e} times"
    f" U15's bound (K8). Under R-ii, where matter is made of the relay's fields and shares its speed and dispersion, nothing radiates and the test is blind,"
    f" as trial 17 found: the test can see a frame only through a speed matter does not share.")
say(f"V7. The setting Sun is the molecular model's n - 1 and its gradient, nothing more. Through the standard atmosphere the ray bends by {R0_std:.1f}' at the horizon"
    f" (Bennett {float(bennett_arcmin(0.0, 101325.0, 288.15)):.1f}', tables 34' to 35.4'), {R_std[5.0]:.1f}' at 5 deg, {R_std[10.0]:.2f}' at 10 deg, {R_std[45.0]:.2f}' at 45 deg and 0 at the"
    f" zenith (K11); the Sun is flattened by {flat:.1f}' and sets {R0_std/rate_40/60:.1f} min late at {OBS_LAT_DEG:.0f} deg latitude; the green flash is the holds' dispersion,"
    f" {(R_col[0.53]-R_col[0.65])*60:.0f}\" between green and red at the horizon, lasting about {(R_col[0.53]-R_col[0.65])/rate_40:.0f} s; the red Sun is the molecules'"
    f" independent scattering through {X0:.0f} air masses (K12), blue transmitted at {np.exp(-X0*tau_b):.0e} against red at {np.exp(-X0*tau_r):.2f}.")
say(f"    The observer's pressure and temperature move everything in proportion to the density at the observer above 20 deg (K13) and faster than that at"
    f" the horizon, where the whole profile's thickness counts: 0 C against 30 C gives {refraction_arcmin(0.0, LAM_SUNSET, atm_cold)/refraction_arcmin(0.0, LAM_SUNSET, atm_warm):.2f} times"
    f" the horizon refraction for {ratio_n1:.2f} times the density.")
say("V8. What the exercise teaches the aether work:")
say("    1. Matter's optics is additive and linear in its density; thinning it to nothing recovers eps0 exactly and explains nothing about eps0. A vacuum"
    " medium cannot be studied by thinning, only by its dispersion, its loss, its nonlinearity, its response to boundaries, and its frame.")
say("    2. The real vacuum has measured and predicted responses, and they are those of its own bound charges, the virtual pairs: boundaries lower its index"
    " (1e-32), fields raise it (1e-23), with the hold at 511 keV and no dispersion below it; that is Model A's vacuum, matched, with no frame.")
say("    3. Space itself is a plasma, the one medium with its hold at zero; it is measured through pulsars and FRBs, it has n < 1, and Aspden's charged lattice"
    " would be a plasma of the same kind with its cutoff at hundreds of keV (U34). The sky's radio reflection is that physics at 10 MHz.")
say(f"    4. Cherenkov light is what a medium does to a charge faster than its light. The molecular model predicts it, with its yield, angle and threshold, in"
    f" water, glass and air at every pressure, and predicts its absence in the vacuum. Its absence for cosmic rays says light's speed and matter's limit agree"
    f" to 1e-23: a relay vacuum whose bare speed matter followed is excluded (1 - f < {share_max:.0e}), and one whose dispersion matter did not share needs its"
    f" hold above {Eres_min_crab[0.0]:.0e} eV. Only a relay whose speed and dispersion matter fully shares survives, and that one has no test here.")
say("    5. The setting Sun, the green flash and the red horizon are the same model (n - 1, its gradient, its dispersion, its molecules' independent scattering);"
    " nothing in them needs or sees the vacuum's own structure.")
say("    If any numbered point is not supported by the numbers above, that is to be stated instead.")

say(f"\nChecks: {sum(ok for _, ok in checks)} of {len(checks)} pass.")
for name, ok in checks:
    if not ok:
        say(f"   FAILED: {name}")