Repository navigation
Conversation
|
@paddyroddy, I just saw your changes on this — the implementation needs some further investigation before merging, marking as draft. |
I was just linting/typing, but I'll leave what I have for now |
… non-limber in comoving distance first and makes use of the geometric mean
This reverts commit 14d2eda.
…lidated pylevin recipe Replace the earlier draft with `glass.spectra.nonlimber_cls(pk, cosmo, ws, lmax)`, which returns GLASS-ordered shell C_l for l = 0..lmax: - Inner Levin integrals I_a(l, k) use a new pylevin instance per call, because instances cache their solution. They are cut to each shell's k-support [0.3 nu/chi_max, max(3 nu/chi_min, q/dchi)]. - Each k is computed at n_col 8 and 6. Where they disagree, a third n_col 10 solution is added and the median of the three is taken. This guards against pylevin's rare isolated glitches, which neighbour tests cannot detect. - Non-Limber is computed at sparse l. The smooth correction to Limber is splined in log l and added to Limber at every l. - pk(z, k) is any callable (e.g. a CAMB matter power interpolator). cosmo is a GLASS Cosmology. The module is optional (pylevin and scipy) and not imported by `import glass`. Add a test against brute-force spherical Bessel quadrature and a docs page. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The median-of-three guard against pylevin's isolated errors doubles the cost. Sums over many shells, such as lensing spectra, move by less than 1e-4 without it, so allow it to be turned off. The default stays on. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ture Shells from `distance_grid` and `linear_windows` lie on the same comoving grid in every cosmology, so the pylevin quadrature rules of each shell can be computed once and reused. `nonlimber_plan` stores them, combined with a piecewise cubic spline basis, as a `NonLimberPlan` that can be saved and loaded. With `plan=`, `nonlimber_cls` only evaluates the integrand at the spline knots. For 16 shells and lmax=500 the planned spectra are ~300x faster than the direct computation and agree to 3e-4 of sqrt(C_aa C_bb). Requires pylevin 2.0 for `get_quadrature`. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…levin 2.0.1, test against CAMB - Require pylevin 2.0.1, which refines subintervals where the integrand is not resolved. Isolated glitches remain (up to 3e-3 of the amplitude at n_col 8), so `robust` stays. - `nonlimber_plan` computes rules per half shell [b dx, (b + 1) dx], each shared by two neighbouring shells, in one diagonal pylevin instance per n_col with an integrand map onto one sqrt(P) column per wavenumber, as in the pylevin tutorials. Plan build for 16 shells at lmax 500: 213 s -> 73 s, same 2.8e-4 agreement with direct. - `nonlimber_cls` without a plan only builds shells and threads it uses. - New `test_nonlimber_cls_camb` compares with CAMB non-Limber number counts (density term, AccuracyBoost 3, lSampleBoost 50). CAMB's density is Newtonian gauge, which changes l = 2 by ~1%; with the same gauge term applied to P(k) the spectra agree to 2e-3 of sqrt(C_aa C_bb). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
pylevin 2.1.0 stores the quadrature rules in the first call, so the plan needs one call per instance. The direct path solves once and sets `store_first_call=False`, which would otherwise slow it by 50%. Pieces starting at x = 0 now use interpolatory quadrature, so the plan integrates from 0. The old 1e-6 dx lower bound was off by up to 2e-3 in a few integrals. At KiDS depth (32 shells to z = 3.1, lmax 2048) the robust spectra agree with 2.0.1 to 3e-5 and the plan to 4e-4; the CAMB comparison is unchanged. pylevin 2.1.0 still has isolated glitches (up to 6e-3 at n_col 8), so `robust` stays the default. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Validation against CAMB at KiDS depthThis covers the commits now on this branch: Setup
Max |ΔC| / √(C_aa C_bb) over all pairs, by ℓ band
Where Limber is wrong by 15–67%, GLASS agrees with CAMB to about 1e-3. The two larger residuals are not from the Levin integration: GLASS follows pure Limber there.
In a smaller run (9 shells to z = 0.52, ℓ ≤ 200, pylevin 2.1.0 vs 2.0.1Same setup, GLASS only, max |ΔC| / √(C_aa C_bb) against the 2.0.1
The CAMB comparison is unchanged to three digits.
Timings (32 cores, Xeon Gold 6148)
Validation script (kids_depth.py)"""Validate glass.spectra.nonlimber_cls at full KiDS depth against CAMB non-Limber counts.
Shells: glass.distance_grid(cosmo, 0, 3.0, dx=200) + linear_windows, lmax=2048 (as kids levin_cache.py).
CAMB reference: number counts, density term only, no Limber, AccuracyBoost/lAccuracyBoost = --acc.
CAMB's density is Newtonian gauge (d_c + 3 (aH/k)^2 v_N): the same factor is applied to GLASS's P(k).
GLASS variants: direct robust, direct single solve, plan built from a different reference cosmology,
and pure Limber (baseline). All results are saved to <out>.npz; comparison is printed.
python kids_depth.py --config linear|nonlinear --out DIR [--acc 3] [--lsample 1] [--lmax 2048]
"""
import argparse, time, json
import numpy as np
import camb
from camb import model
from camb.sources import SplinedSourceWindow
from scipy.interpolate import RegularGridInterpolator
import glass, glass.spectra
ap = argparse.ArgumentParser()
ap.add_argument("--config", choices=["linear", "nonlinear"], required=True)
ap.add_argument("--out", required=True)
ap.add_argument("--acc", type=float, default=3.0)
ap.add_argument("--lsample", type=float, default=1.0)
ap.add_argument("--lmax", type=int, default=2048)
ap.add_argument("--zmax", type=float, default=3.0)
args = ap.parse_args()
C = 299792.458
T0 = time.time()
def log(*a): print(f"[{time.time() - T0:8.1f}s]", *a, flush=True)
FID = dict(H0=67.5, ombh2=0.022, omch2=0.122, As=2.1e-9, ns=0.965, WantCls=False)
if args.config == "linear":
FID.update(mnu=0.0, num_massive_neutrinos=0)
else:
FID.update(mnu=0.06)
def make_pars(**kw):
p = camb.set_params(**kw)
p.Want_CMB = False
if args.config == "nonlinear":
p.NonLinear = model.NonLinear_both
p.NonLinearModel.set_params(halofit_version="mead2020_feedback", HMCode_logT_AGN=7.8)
else:
p.NonLinear = model.NonLinear_none
return p
class CambCosmology:
def __init__(self, pars):
self.bg = camb.get_background(pars)
self.H0 = pars.H0
self.hubble_distance = C / pars.H0
def H_over_H0(self, z): return np.asarray(self.bg.hubble_parameter(z)) / self.H0
def comoving_distance(self, z): return np.asarray(self.bg.comoving_radial_distance(z))
def inv_comoving_distance(self, x): return np.asarray(self.bg.redshift_at_comoving_radial_distance(x))
def matter_pk(pars, zmax, gauge):
"""sqrt-able P(z, k) in Mpc units for CDM, optionally times the Newtonian gauge factor squared."""
nl = args.config == "nonlinear"
pi = camb.get_matter_power_interpolator(pars, nonlinear=nl, hubble_units=False, k_hunit=False, kmax=100.0,
zmax=zmax, var1="delta_cdm", var2="delta_cdm", extrap_kmax=True)
if not gauge:
return lambda z, k: pi.P(z, k, grid=True)
zs = np.linspace(zmax, 0.0, 120)
tp = pars.copy()
tp.NonLinear = model.NonLinear_none
tp.set_matter_power(redshifts=list(zs), kmax=10.0)
tr = camb.get_results(tp).get_matter_transfer_data()
dc = tr.transfer_data[model.Transfer_cdm - 1]
vn = tr.transfer_data[model.Transfer_Newt_vel_cdm - 1]
bg = camb.get_background(pars)
ah = np.asarray(bg.hubble_parameter(zs)) / (1 + zs) / C
ratio = 1 + 3 * ah**2 * vn / (tr.q[:, None] ** 2 * dc)
g = RegularGridInterpolator((np.log(tr.q), zs[::-1]), ratio[:, ::-1])
def pk(z, k):
lk = np.clip(np.log(k), np.log(tr.q[0]), np.log(tr.q[-1]))
lk_, z_ = np.meshgrid(lk, z)
return pi.P(z, k, grid=True) * g((lk_, z_)) ** 2
return pk
lmax = args.lmax
pars = make_pars(**FID)
cosmo = CambCosmology(pars)
zb = glass.distance_grid(cosmo, 0.0, args.zmax, dx=200.0)
ws = glass.linear_windows(zb)
n = len(ws)
zmax = float(ws[-1].za[-1]) + 0.2
log(f"config={args.config} acc={args.acc} lsample={args.lsample}: {n} shells to z={zb[-1]:.3f}, lmax={lmax}")
pk = matter_pk(pars, zmax, gauge=True)
res = {"zb": zb, "lmax": lmax}
t = time.time(); res["robust"] = np.array(glass.spectra.nonlimber_cls(pk, cosmo, ws, lmax)); log(f"direct robust {time.time() - t:.0f}s")
t = time.time(); res["single"] = np.array(glass.spectra.nonlimber_cls(pk, cosmo, ws, lmax, robust=False)); log(f"direct single {time.time() - t:.0f}s")
# plan from a different reference cosmology (linear, no neutrinos, other omch2/h/As); only its rules are kept
ref_kw = dict(H0=72.0, ombh2=0.0224, omch2=0.110, As=1.9e-9, ns=0.97, mnu=0.0, num_massive_neutrinos=0, WantCls=False)
ref_pars = camb.set_params(**ref_kw); ref_pars.Want_CMB = False; ref_pars.NonLinear = model.NonLinear_none
ref_cosmo = CambCosmology(ref_pars)
nplan = n + 1
ref_zmax = float(ref_cosmo.inv_comoving_distance((nplan + 1) * 200.0)) + 0.1
ref_pi = camb.get_matter_power_interpolator(ref_pars, nonlinear=False, hubble_units=False, k_hunit=False, kmax=100.0,
zmax=ref_zmax, var1="delta_cdm", var2="delta_cdm", extrap_kmax=True)
t = time.time()
plan = glass.spectra.nonlimber_plan(lambda z, k: ref_pi.P(z, k, grid=True), ref_cosmo, lmax, nplan)
log(f"plan build {time.time() - t:.0f}s")
t = time.time(); res["plan"] = np.array(glass.spectra.nonlimber_cls(pk, cosmo, ws, lmax, plan=plan)); log(f"planned {time.time() - t:.1f}s")
np.savez(f"{args.out}/glass_{args.config}.npz", **res)
# pure Limber, the same Limber part nonlimber_cls uses: run it with no non-Limber correction is not exposed,
# so compute it directly here
zf = np.linspace(1e-4, ws[-1].za[-1], 6000)
chif = cosmo.comoving_distance(zf)
kf = np.array([np.interp(zf, w.za, w.wa, left=0, right=0) for w in ws]) * cosmo.H_over_H0(zf) / cosmo.hubble_distance
kf /= np.trapezoid(kf, chif, axis=1)[:, None]
lf = np.arange(1, lmax + 1)
pf = np.array([pk(zf[i:i + 1], (lf + 0.5) / chif[i])[0] for i in range(len(zf))])
lim = ((kf[:, None] * kf[None, :] * (np.gradient(chif) / chif**2)).reshape(n * n, -1) @ pf).reshape(n, n, -1)
pairs = [(i, j) for i in range(n) for j in range(i, -1, -1)]
res["limber"] = np.array([np.r_[0.0, lim[i, j]] for i, j in pairs])
np.savez(f"{args.out}/glass_{args.config}.npz", **res)
log("limber done; starting CAMB")
# CAMB non-Limber number counts, density only
cp = make_pars(**FID)
cp.WantCls = True
cp.set_accuracy(AccuracyBoost=args.acc, lSampleBoost=args.lsample, lAccuracyBoost=args.acc)
cp.set_for_lmax(lmax, lens_potential_accuracy=0)
st = cp.SourceTerms
st.limber_windows = False
st.counts_density = True
for term in ("redshift", "lensing", "velocity", "radial", "timedelay", "ISW", "potential", "evolve"):
setattr(st, f"counts_{term}", False)
cp.SourceWindows = [SplinedSourceWindow(z=np.maximum(w.za, 1e-5), W=w.wa / np.trapezoid(w.wa, w.za), source_type="counts")
for w in ws]
t = time.time()
cd = camb.get_results(cp).get_source_cls_dict(raw_cl=True, lmax=lmax)
log(f"camb {time.time() - t:.0f}s")
camb_cls = np.array([cd[f"W{i + 1}xW{j + 1}"][: lmax + 1] for i, j in pairs])
np.savez(f"{args.out}/camb_{args.config}_acc{args.acc:g}_ls{args.lsample:g}.npz", cls=camb_cls)
# comparison: |X - CAMB| / sqrt(CAMB_aa CAMB_bb), by l band, worst over pairs; and auto ratios
auto = {i: camb_cls[pairs.index((i, i))] for i in range(n)}
norm = np.array([np.sqrt(auto[i] * auto[j]) for i, j in pairs])
bands = [(2, 9), (10, 29), (30, 99), (100, 499), (500, 999), (1000, lmax)]
summary = {}
print(f"\nmax |X - CAMB| / sqrt(C_aa C_bb) over all {len(pairs)} pairs, by l band:")
print(f"{'variant':8s} " + " ".join(f"{f'{a}-{b}':>10s}" for a, b in bands))
for name in ["robust", "single", "plan", "limber"]:
x = res[name]
row = []
for a, b in bands:
e = np.abs(x[:, a:b + 1] - camb_cls[:, a:b + 1]) / norm[:, a:b + 1]
row.append(float(e.max()))
summary[name] = row
print(f"{name:8s} " + " ".join(f"{v:10.2e}" for v in row))
worst = np.abs(res["robust"][:, 2:] - camb_cls[:, 2:]) / norm[:, 2:]
p, l = np.unravel_index(np.argmax(worst), worst.shape)
print(f"\nrobust worst: pair {pairs[p]} at l={l + 2}: {worst[p, l]:.2e}")
print("\nauto ratio robust/CAMB at l = 2, 10, 100, 500, 1000, 2048 (every 4th shell):")
for i in range(0, n, 4):
c, r = res["robust"][pairs.index((i, i))], auto[i]
print(f" shell {i:2d} (z {ws[i].za[0]:.2f}-{ws[i].za[-1]:.2f}):", " ".join(f"{c[l] / r[l]:.4f}" for l in [2, 10, 100, 500, 1000, lmax]))
print("\nplan vs robust:", f"{float((np.abs(res['plan'][:, 1:] - res['robust'][:, 1:]) / norm[:, 1:]).max()):.2e}",
" single vs robust:", f"{float((np.abs(res['single'][:, 1:] - res['robust'][:, 1:]) / norm[:, 1:]).max()):.2e}")
json.dump(summary, open(f"{args.out}/summary_{args.config}.json", "w"), indent=1)
log("done") |
Description
Levin non-limber implementation for GLASS, does the non-Limber integral in comoving distance first and makes use of the geometric approximation
Changelog entry
Added: Method to calculate matter power spectra without the Limber approximation using the Levin method.
Checks