Skip to content

gh-609: Non-Limber integration of matter power spectra - #608

Draft
Kiyam wants to merge 12 commits into
glass-dev:mainfrom
Kiyam:levin-spectra
Draft

Kiyam wants to merge 12 commits into
glass-dev:mainfrom
Kiyam:levin-spectra

Conversation

@Kiyam

@Kiyam Kiyam commented Apr 23, 2025 •

Copy link
Copy Markdown

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

  • Is your code passing linting?
  • Is your code passing tests?
  • Have you added additional tests (if required)?
  • Have you modified/extended the documentation (if required)?
  • Have you added a one-liner changelog entry above (if required)?

@ntessore ntessore changed the title initial commit of levin non-limber implementation for glass, does the… gh-609: Non-Limber integration of matter power spectra Apr 23, 2025
@ntessore ntessore self-assigned this May 7, 2025
@ntessore
ntessore marked this pull request as draft May 7, 2025 11:18
@ntessore

ntessore commented May 7, 2025

Copy link
Copy Markdown
Collaborator

@paddyroddy, I just saw your changes on this — the implementation needs some further investigation before merging, marking as draft.

@paddyroddy

Copy link
Copy Markdown
Member

@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

@paddyroddy paddyroddy added the not-for-arc Topic is largely science related, so not relevant for ARC to look into label Oct 10, 2025
Kiyam and others added 8 commits November 23, 2026 13:48
… non-limber in comoving distance first and makes use of the geometric mean
…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>
Kiyam and others added 3 commits November 27, 2026 16:33
…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>
@Kiyam

Kiyam commented Dec 3, 2026

Copy link
Copy Markdown
Author

Validation against CAMB at KiDS depth

This covers the commits now on this branch: nonlimber_plan (a6d1c77), the plan rewrite with the CAMB test (80439d2), and pylevin 2.1.0 (1da468c).

Setup

  • Shells: distance_grid(cosmo, 0, 3.0, dx=200) with linear_windows, giving 32 shells to z ≈ 3.1. lmax is 2048 and all 528 pairs are compared.
  • Cosmology: H0 67.5, ombh2 0.022, omch2 0.122, As 2.1e-9, ns 0.965.
    • linear: mν = 0.
    • nonlinear: mν = 0.06, HMcode mead2020_feedback, logT_AGN 7.8.
  • GLASS P(k): CAMB delta_cdm times the squared Newtonian-gauge factor 1 + 3(aH/k)² v_N/δ_c. This matches CAMB's counts_density source, which is in Newtonian gauge. Without the factor, CAMB is 1% higher at ℓ = 2.
  • CAMB reference: non-Limber number counts, density term only, AccuracyBoost = lAccuracyBoost = 3, lSampleBoost = 1.
  • GLASS variants:
    • robust: the default.
    • single: robust=False.
    • plan: a nonlimber_plan built from a different cosmology (H0 72, omch2 0.110, As 1.9e-9).
    • Limber, as a baseline.

Max |ΔC| / √(C_aa C_bb) over all pairs, by ℓ band

ℓ band robust, linear robust, nonlinear Limber, linear / nonlinear
2–9 1.6e-3 1.5e-3 0.67 / 0.67
10–29 7.6e-4 7.8e-4 0.49 / 0.49
30–99 5.4e-3 3.7e-3 0.15 / 0.15
100–499 3.4e-2 1.5e-2 5.8e-2 / 5.8e-2
500–999 4.8e-3 6.6e-3 7.5e-3 / 5.7e-3
1000–2048 2.5e-3 2.2e-2 2.5e-3 / 2.2e-2

single and plan match robust to the digits shown. Against robust, single differs by up to 5e-4 at ℓ > 1000, and the plan from the other cosmology by up to 3.6e-4.

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.

  1. ℓ 100–499: the worst case is 3.4% at pair (9, 9), ℓ ≈ 225, z ≈ 0.5. It is a smooth wiggle over ℓ 200–260, and pure Limber shows the same wiggle. Here k = ℓ/χ ≈ 0.12 Mpc⁻¹, which is the BAO range, and the wiggle is smaller in the nonlinear run where BAO is damped. This points to CAMB's source k-sampling smoothing the BAO relative to the P(k) interpolator. Not confirmed.
  2. Nonlinear, ℓ 1000–2048: GLASS is 1–2% below CAMB at high z. GLASS matches Limber to 3e-4 there, so the difference is in the nonlinear P(k) input, likely CAMB's internal nonlinear scaling of the sources or δ_cdm vs total matter with mν > 0. The linear run agrees to 0.1% at ℓ = 2048.

In a smaller run (9 shells to z = 0.52, ℓ ≤ 200, lSampleBoost = 50), GLASS agrees with CAMB to 1.3e-3 in all bands.

pylevin 2.1.0 vs 2.0.1

Same setup, GLASS only, max |ΔC| / √(C_aa C_bb) against the 2.0.1 robust spectra:

2–9 10–29 30–99 100–499 500–999 1000–2048
robust 1.6e-5 1.6e-5 1.7e-5 1.7e-5 2.6e-5 2.9e-5
plan 9.3e-5 2.0e-4 3.0e-4 3.6e-4 4.7e-5 6.2e-5

The CAMB comparison is unchanged to three digits.

  • Glitches: pylevin 2.1.0 still has rare isolated glitches, up to 6e-3 of the amplitude at n_col 8 and 3e-2 at n_col 6. The robust median holds the error against direct quadrature to 2e-5, so robust stays the default.
  • x = 0: pieces starting at x = 0 now use interpolatory quadrature, so the plan integrates from 0. The old 1e-6 dx bound was off by up to 2e-3 in a few integrals.

Timings (32 cores, Xeon Gold 6148)

step 2.0.1 2.1.0
direct, robust 1146 s 1185 s
direct, single 487 s 523 s
plan build 481 s 404 s
spectra from plan 4.6 s 4.7 s
CAMB, AccuracyBoost 3 17.6 h (linear), 20.2 h (nonlinear)
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")

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

not-for-arc Topic is largely science related, so not relevant for ARC to look into

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants