Does light charge the quons? › Files cited on the page › check_trial24_fable/
r33_nist_intercepts.py
#!/usr/bin/env python3
"""Thirty-third reviewer, trial 24, blind part (a): n - 1 against pressure for N2, Ar, He
from the NIST dataset (Egan and Yang 2023, doi:10.18434/mds2-3054), extrapolated to zero pressure.
Own code; the author's script was not read before this was written.
Usage: python3 -I r33_nist_intercepts.py <path to nist_npT/unzipped>
Model [M] (own choice): per gas and isotherm j, with x = n - 1 and p_iso = p * T_j / T (T_j the isotherm's mean
temperature; first-order ideal-gas normalisation of the small temperature scatter):
p_iso = e0 + a1 x + a2 x^2 + a3 x^3 (N2, Ar: cubic; He: quadratic, a3 = 0; both also reported the other way)
This is the paper's Eq. 5 written as a plain polynomial (a1 = A, a2 = A B, a3 = A C, e0 = eps_p).
Intercept at zero pressure, in refractivity: i0 = -e0 / a1.
Also the inverse regression, x = i0' + b1 p + b2 p^2 + b3 p^3, as a cross-check of i0.
Error model [M] (own choice):
1. Weights 1/sigma_p^2 with sigma_p = sqrt(0.060^2 + (1.9e-6 p)^2) Pa, the data provider's own weights
(plotNitrogen.py, read as text, not run) [I].
2. Statistical error: cluster bootstrap over pressure SETTINGS (the five repeats at a setting are resampled together,
because they share the gauge state and the gas charge), 3000 resamples, seed 33. Percentile-free: the standard
deviation of the bootstrap intercepts.
3. Systematic floor, quoted separately and added in quadrature for the final limit: the paper's two named pressure
offsets, 54 mPa (piston-gauge mass) and 60 mPa (cavity temperature), i.e. 0.081 Pa, common to an isotherm.
Combined per gas: inverse-variance weighted mean over isotherms; error scaled by the Birge ratio when above 1.
"""
import sys, os, math
import numpy as np
RNG_SEED = 33
NBOOT = 3000
NOMINAL_C = [20, 30, 40, 60, 80, 100, 120, 140, 160]
R = 8.314462618
C_LIGHT = 299792458.0
def read_gas(path):
rows = []
with open(path, encoding='utf-8', errors='replace') as f:
for line in f:
parts = line.strip().split(',')
if len(parts) != 3:
continue
try:
t, p, r = float(parts[0]), float(parts[1]), float(parts[2])
except ValueError:
continue
rows.append((t, p, r * 1e-8))
a = np.array(rows)
return a[:, 0], a[:, 1], a[:, 2]
def settings(p):
"""Cluster indices for pressure settings: consecutive sorted pressures within 0.1 %."""
order = np.argsort(p)
lab = np.zeros(len(p), dtype=int)
k = 0
last = None
for i in order:
if last is not None and abs(p[i] - last) / last > 1e-3:
k += 1
lab[i] = k
last = p[i]
return lab
def wpolyfit(x, y, w, deg):
"""Weighted LS for y = sum_k c_k x^k, k = 0..deg. Returns coefficients (c0 first) and covariance (scaled by chi2/dof)."""
X = np.vander(x, deg + 1, increasing=True)
sw = np.sqrt(w)
Xw = X * sw[:, None]
yw = y * sw
coef, res, rank, sv = np.linalg.lstsq(Xw, yw, rcond=None)
r = yw - Xw @ coef
dof = len(y) - (deg + 1)
chi2 = float(r @ r)
cov = np.linalg.inv(Xw.T @ Xw) * (chi2 / dof if dof > 0 else 1.0)
return coef, cov, chi2, dof
def fit_isotherm(x, p_iso, w, deg):
coef, cov, chi2, dof = wpolyfit(x, p_iso, w, deg)
e0, a1 = coef[0], coef[1]
i0 = -e0 / a1
# error of i0 from covariance (first order)
g = np.zeros(deg + 1)
g[0] = -1.0 / a1
g[1] = e0 / a1 ** 2
si0 = math.sqrt(abs(float(g @ cov @ g)))
return dict(coef=coef, e0=e0, se0=math.sqrt(cov[0, 0]), a1=a1, i0=i0, si0_cov=si0, chi2=chi2, dof=dof)
def inverse_fit(x, p_iso, deg):
# unweighted inverse regression x = i0' + b1 (p/1e5) + ... (pressure scaled for conditioning)
X = np.vander(p_iso / 1e5, deg + 1, increasing=True)
coef, *_ = np.linalg.lstsq(X, x, rcond=None)
return coef[0], coef[1] / 1e5
def analyse_gas(name, t, p, r, deg_primary, extra_degs, rng, inject=0.0, scale=1.0):
r = r.copy()
if inject != 0.0:
r = r + inject
if scale != 1.0:
r = (1.0 + r) * scale - 1.0 # multiply the index n, not n-1 (used for the ratio check elsewhere)
T = t + 273.15
iso = np.array([int(np.argmin([abs(tt - n) for n in NOMINAL_C])) for tt in t])
out = []
for j in range(len(NOMINAL_C)):
m = iso == j
if m.sum() == 0:
continue
Tj = T[m].mean()
p_iso = p[m] * Tj / T[m]
x = r[m]
w = 1.0 / (0.060 ** 2 + (1.9e-6 * p[m]) ** 2)
lab = settings(p[m])
nset = lab.max() + 1
res = {}
for deg in [deg_primary] + extra_degs:
f = fit_isotherm(x, p_iso, w, deg)
# cluster bootstrap over settings
boots = []
ndraw = 0
while len(boots) < NBOOT and ndraw < 20 * NBOOT:
ndraw += 1
pick = rng.integers(0, nset, nset)
if len(set(pick.tolist())) < deg + 2:
continue # too few distinct settings to fit this degree; redraw
idx = np.concatenate([np.where(lab == s)[0] for s in pick])
fb = fit_isotherm(x[idx], p_iso[idx], w[idx], deg)
boots.append(fb['i0'])
f['si0_boot'] = float(np.std(boots))
f['i0_inv'], f['b1_inv'] = inverse_fit(x, p_iso, deg)
res[deg] = f
out.append(dict(j=j, Tnom=NOMINAL_C[j], Tj=Tj, n=int(m.sum()), nset=nset, res=res))
return out
def combine(vals, errs):
w = 1.0 / np.array(errs) ** 2
mean = float(np.sum(w * np.array(vals)) / np.sum(w))
err = float(1.0 / math.sqrt(np.sum(w)))
chi2 = float(np.sum(w * (np.array(vals) - mean) ** 2))
dof = len(vals) - 1
birge = math.sqrt(chi2 / dof) if dof > 0 else 1.0
return mean, err, chi2, dof, birge
def main():
base = sys.argv[1]
files = {
'nitrogen': os.path.join(base, 'nitrogen', 'data-nitrogen-2062.csv'),
'argon': os.path.join(base, 'argon', 'data-argon-2062.csv'),
'helium': os.path.join(base, 'helium', 'data-helium-2062.csv'),
}
degs = {'nitrogen': (3, [2, 1]), 'argon': (3, [2, 1]), 'helium': (2, [3, 1])}
SYS_FLOOR_PA = math.sqrt(0.054 ** 2 + 0.060 ** 2)
print("# r33 NIST intercepts: own fit, own error model (see docstring). Seed", RNG_SEED, "bootstraps", NBOOT)
print(f"# systematic floor per isotherm (paper's 54 and 60 mPa in quadrature): {SYS_FLOOR_PA:.3f} Pa")
summary = {}
for gas, path in files.items():
t, p, r = read_gas(path)
print(f"\n## {gas}: {len(t)} points, p {p.min():.0f} to {p.max():.0f} Pa, T {t.min():.2f} to {t.max():.2f} C")
rng = np.random.default_rng(RNG_SEED)
degp, extra = degs[gas]
out = analyse_gas(gas, t, p, r, degp, extra, rng)
print(f"primary fit degree {degp}. Columns: T_nom | n | settings | A=a1 (Pa) | eps_p (Pa) +- cov | i0 (1e-10) +- cov +- boot | i0 inverse (1e-10) | chi2/dof || straight-line i0 (1e-10) | quadratic i0 (1e-10)")
vals, errs, vals_pa, errs_pa = [], [], [], []
for o in out:
f = o['res'][degp]
alt = {d: o['res'][d]['i0'] for d in extra}
sb = max(f['si0_boot'], f['si0_cov'])
print(f"{o['Tnom']:4d} | {o['n']:3d} | {o['nset']:2d} | {f['a1']:.6e} | {f['e0']:+.4f} +- {f['se0']:.4f} | "
f"{f['i0']*1e10:+.3f} +- {f['si0_cov']*1e10:.3f} +- {f['si0_boot']*1e10:.3f} | {f['i0_inv']*1e10:+.3f} | "
f"{f['chi2']/f['dof']:.2f} || " + " | ".join(f"deg{d}: {alt[d]*1e10:+.2f}" for d in extra))
vals.append(f['i0']); errs.append(sb)
vals_pa.append(f['e0']); errs_pa.append(sb * f['a1'])
mean, err, chi2, dof, birge = combine(vals, errs)
err_s = err * max(1.0, birge)
mean_pa, err_pa, chi2_pa, dof_pa, birge_pa = combine(vals_pa, errs_pa)
err_pa_s = err_pa * max(1.0, birge_pa)
A20 = out[0]['res'][degp]['a1']
print(f"combined {gas}: i0 = {mean*1e10:+.3f} +- {err*1e10:.3f} (x1e-10), Birge {birge:.2f} -> +- {err_s*1e10:.3f}; "
f"chi2/dof of the nine = {chi2/dof:.2f}")
print(f"combined {gas} in pascals: eps_p = {mean_pa:+.4f} +- {err_pa:.4f} Pa, Birge {birge_pa:.2f} -> +- {err_pa_s:.4f} Pa; "
f"chi2/dof = {chi2_pa/dof_pa:.2f}")
sys_ref = SYS_FLOOR_PA / A20
print(f" A at 20 C = {A20:.6e} Pa per unit refractivity; 0.1 Pa = {0.1/A20*1e10:.3f} x1e-10; "
f"systematic floor {SYS_FLOOR_PA:.3f} Pa = {sys_ref*1e10:.3f} x1e-10")
tot = math.sqrt(err_s ** 2 + sys_ref ** 2)
print(f" |i0| + 2 sigma_stat = {(abs(mean) + 2*err_s)*1e10:.3f} x1e-10; with systematic floor: |i0| + 2 sqrt(stat^2+sys^2) = {(abs(mean)+2*tot)*1e10:.3f} x1e-10")
print(f" n-1 at 101325 Pa, 20 C from A (linear term only) = {101325/A20:.5e}")
summary[gas] = dict(mean=mean, err=err_s, mean_pa=mean_pa, err_pa=err_pa_s, A20=A20, chi2=chi2, dof=dof)
# Cross-gas comparison
print("\n## Cross-gas comparison (VA2 logic, own numbers)")
g = ['nitrogen', 'argon', 'helium']
v = [summary[k]['mean'] for k in g]; e = [summary[k]['err'] for k in g]
m, er, c2, d, b = combine(v, e)
print(f"i0 in refractivity across gases: mean {m*1e10:+.3f} +- {er*1e10:.3f} x1e-10, chi2/dof = {c2/d:.2f}")
v = [summary[k]['mean_pa'] for k in g]; e = [summary[k]['err_pa'] for k in g]
m, er, c2, d, b = combine(v, e)
print(f"eps_p in pascals across gases: mean {m:+.4f} +- {er:.4f} Pa, chi2/dof = {c2/d:.2f}")
for k in g:
print(f" {k}: i0/sigma = {summary[k]['mean']/summary[k]['err']:+.2f}; eps_p/sigma = {summary[k]['mean_pa']/summary[k]['err_pa']:+.2f}")
# GAMOR's constant and NIST 2016 as refractivity (nitrogen A at 20 C)
A = summary['nitrogen']['A20']
print(f"\n## GAMOR a = 0.108(6) Pa as nitrogen refractivity at 20 C: {0.108/A:.3e} (+- {0.006/A:.1e}); "
f"NIST 2016 2.0 mPa (k=2): {0.002/A:.3e}; ratio GAMOR/NIST2016 = {0.108/0.002:.0f}")
print(f" paper's own multi-isotherm eps_p (argon): 10 mPa mean, 41 mPa average statistical uncertainty [I] = "
f"{0.010/summary['argon']['A20']:.2e} +- {0.041/summary['argon']['A20']:.2e} in refractivity")
# Injection test (own): add +1e-9 and -1e-9 to every n-1; the intercepts must move by that amount
print("\n## Injection test: shift every n-1 by +1e-9 then -1e-9; primary-fit intercept shift per gas (20 C isotherm and combined)")
for gas, path in files.items():
t, p, r = read_gas(path)
degp, extra = degs[gas]
base_rng = np.random.default_rng(RNG_SEED)
o0 = analyse_gas(gas, t, p, r, degp, [], base_rng)
for inj in (+1e-9, -1e-9):
rng = np.random.default_rng(RNG_SEED)
o1 = analyse_gas(gas, t, p, r, degp, [], rng, inject=inj)
shifts = [(o1[j]['res'][degp]['i0'] - o0[j]['res'][degp]['i0']) for j in range(len(o0))]
print(f" {gas} inject {inj:+.0e}: mean shift {np.mean(shifts):+.4e}, min {min(shifts):+.4e}, max {max(shifts):+.4e}; "
f"recovered/injected = {np.mean(shifts)/inj:.5f}")
# E3 blindness: multiply every index (gas and vacuum) by 1+1e-6; the measured quantity is n_gas/n_vac - 1
print("\n## E3 blindness by number: n_gas/n_vac with both multiplied by (1 + 1e-6)")
t, p, r = read_gas(files['nitrogen'])
n_gas = 1.0 + r
n_vac = 1.0
f = 1.0 + 1e-6
ratio0 = n_gas / n_vac
ratio1 = (n_gas * f) / (n_vac * f)
print(f" max |ratio change| over {len(r)} nitrogen points = {np.max(np.abs(ratio1 - ratio0)):.1e} (floating point only)")
if __name__ == '__main__':
main()