From 65e1feca512eb39ea558489f0c9fe522877967b2 Mon Sep 17 00:00:00 2001 From: Kiyam Lin Date: Wed, 23 Apr 2025 15:36:15 +0000 Subject: [PATCH 01/12] initial commit of levin non-limber implementation for glass, does the non-limber in comoving distance first and makes use of the geometric mean --- glass/spectra.py | 175 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 175 insertions(+) create mode 100644 glass/spectra.py diff --git a/glass/spectra.py b/glass/spectra.py new file mode 100644 index 000000000..56bee9040 --- /dev/null +++ b/glass/spectra.py @@ -0,0 +1,175 @@ +import numpy as np +import pylevin as levin +from tqdm import tqdm +from scipy.interpolate import RectBivariateSpline, UnivariateSpline + +def make_pk_interpolators(pk, k, z) -> RectBivariateSpline: + """ + Spline interpolator for the matter power spectrum. + + Parameters + ---------- + pk + 3D matter power spectrum. + k + Array of wavenumbers corresponding to 3D matter power spectrum values. + z + Array of redshifts corresponding to 3D matter power spectrum values. + + Returns + ------- + RectBivariateSpline object to interpolate the 3D matter power spectrum. + + """ + + pkz_interp = RectBivariateSpline(k, z, pk) + return pkz_interp + +def make_shell_interpolator(shell_z, + shell_weights, + cosmo + ) -> list[UnivariateSpline]: + """ + Spline interpolator for comoving shells. + + Parameters + ---------- + shell_z + The redshift boundaries for concentric matter shells. + shell_weights + The weights of the shells. + cosmo + Cosmology object to calculate the comoving distances. + + Returns + ------- + A list the length of the number of shells with each element being a UnivariateSpline for that shell. + + """ + + chi = cosmo.comoving_distance(shell_z) + dzdchi = UnivariateSpline(chi, shell_z, k=2, s=0).derivative()(chi) + shell_interp = [UnivariateSpline(chi, shell*dzdchi, k=2, s=0) for shell in shell_weights] + return shell_interp + +def make_glass_shell_interpolator(ws, cosmo) -> list[UnivariateSpline]: + """ + Spline interpolator for comoving shells. + + Parameters + ---------- + ws + Glass shells. + cosmo + Cosmology object to calculate the comoving distances. + + Returns + ------- + A list the length of the number of shells with each element being a UnivariateSpline for that shell. + + """ + return [UnivariateSpline(cosmo.comoving_distance(ws[i].za) * (1+ws[i].za), ws[i].wa, k=2, s=0, ext=1) for i in range(len(ws))] + +def get_cls(num_shells, + ell_min, # can be set to 1 + ell_max, + pk_interpolator, + shells_interpolate, + chi_lims, + N_thread = 4, #number of threads used for hyperthreading + n_sub = 8, #number of collocation points in each bisection + n_bisec_max = 64, #maximum number of bisections used + rel_acc = 1e-10, #relative accuracy target + boost_bessel = True, #should the bessel functions be calculated with boost instead of GSL, higher accuracy at high Bessel orders + verbose = False, #should the code talk to you? + lev_list = None + ): + """ + Calculates Cls using the geometric approximation and performing the integral in comoving distance first. + + Parameters + ---------- + num_shells + The number of shells. + ell_min + The minimum ell value. + ell_max + The maximum ell value. + pk_interpolator + The interpolator for the matter power spectrum. + shells_interpolate + The interpolator for the comoving shells. + chi_lims + The comoving distance limits for the shells. + N_thread + The number of threads used for hyperthreading. + n_sub + The number of collocation points in each bisection. + n_bisec_max + The maximum number of bisections used. + rel_acc + The relative accuracy target. + boost_bessel + Should the bessel functions be calculated with boost instead of GSL, higher accuracy at high Bessel orders. + verbose + Should the code talk to you? + lev_list + List of Levin objects to load. If None, new Levin objects are created. Useful for speeding up the calculation if we have at hand already calculated bisections. + + Returns + ------- + shell_cls + A 3D array of the shell cls. + shell_cls_dict + A dictionary with the shell cls labelled by the shell pair number. + lev_list + A list of Levin objects. If lev_list is None, this will be a list of new Levin objects created during the calculation. If lev_list is not None, this will be the same list passed in as lev_list. + """ + + # Some levin definitions + integral_type = 0 + logx = True # Tells the code to create a logarithmic spline in x for f(x) + logy = True # Tells the code to create a logarithmic spline in y for y = f(x) + + ell = np.unique((np.geomspace(ell_min, ell_max)).astype(int)) + + if lev_list is None: + lev_list = [] + load_levin = False + else: + lev_list + load_levin = True + + N_int = int(2e3) + k_int = np.geomspace(1e-4, 10, N_int) + inner_int = np.zeros((num_shells, len(ell), len(k_int))) + flat_idx = 0 + for idx_shell in (tqdm(np.arange(num_shells))): + chi_int = np.linspace(chi_lims[idx_shell], chi_lims[idx_shell + 1], 50) + pk_nl_new = np.zeros((len(chi_int), len(k_int))) + pk_nl_new[:,:] = np.sqrt(pk_interpolator(k_int, chi_int)).T*(shells_interpolate[idx_shell](chi_int))[:, None] + lower_limit = chi_int[0]*np.ones_like(k_int) + upper_limit = chi_int[-1]*np.ones_like(k_int) + + for i_ell, val_ell in enumerate(ell): + if load_levin is True: + lev = lev_list[flat_idx] + else: + lev = levin.pylevin(integral_type, chi_int, pk_nl_new, logx, logy, N_thread, True) + lev.set_levin(n_sub, n_bisec_max, rel_acc, boost_bessel, verbose) + + ell_values = (val_ell*np.ones_like(k_int)).astype(int) + lev.levin_integrate_bessel_single(lower_limit, upper_limit, k_int, ell_values, inner_int[idx_shell, i_ell,:]) + flat_idx += 1 + + if load_levin is False: + lev_list.append(lev) + + shell_cls = 2/np.pi*np.trapezoid(inner_int[:, None, :, :] * inner_int[None, : ,: ,:]*k_int**2,k_int, axis = -1) + + shell_cls_dict = {} + for i in range(len(chi_lims) - 1): + for j in range(len(chi_lims) - 1): + shell_cls_dict[f'W{i+1}xW{j+1}'] = shell_cls[i, j, :] + + return shell_cls, shell_cls_dict, lev_list \ No newline at end of file From 485c29cc42f05c96f94a0c0af7b9d806681c583e Mon Sep 17 00:00:00 2001 From: "Patrick J. Roddy" Date: Wed, 7 May 2025 11:55:55 +0100 Subject: [PATCH 02/12] Auto fix linting --- glass/spectra.py | 123 +++++++++++++++++++++++++++++------------------ 1 file changed, 76 insertions(+), 47 deletions(-) diff --git a/glass/spectra.py b/glass/spectra.py index 56bee9040..bfe3e0faa 100644 --- a/glass/spectra.py +++ b/glass/spectra.py @@ -1,7 +1,8 @@ import numpy as np import pylevin as levin -from tqdm import tqdm from scipy.interpolate import RectBivariateSpline, UnivariateSpline +from tqdm import tqdm + def make_pk_interpolators(pk, k, z) -> RectBivariateSpline: """ @@ -11,7 +12,7 @@ def make_pk_interpolators(pk, k, z) -> RectBivariateSpline: ---------- pk 3D matter power spectrum. - k + k Array of wavenumbers corresponding to 3D matter power spectrum values. z Array of redshifts corresponding to 3D matter power spectrum values. @@ -21,14 +22,11 @@ def make_pk_interpolators(pk, k, z) -> RectBivariateSpline: RectBivariateSpline object to interpolate the 3D matter power spectrum. """ - pkz_interp = RectBivariateSpline(k, z, pk) return pkz_interp - -def make_shell_interpolator(shell_z, - shell_weights, - cosmo - ) -> list[UnivariateSpline]: + + +def make_shell_interpolator(shell_z, shell_weights, cosmo) -> list[UnivariateSpline]: """ Spline interpolator for comoving shells. @@ -46,12 +44,14 @@ def make_shell_interpolator(shell_z, A list the length of the number of shells with each element being a UnivariateSpline for that shell. """ - chi = cosmo.comoving_distance(shell_z) dzdchi = UnivariateSpline(chi, shell_z, k=2, s=0).derivative()(chi) - shell_interp = [UnivariateSpline(chi, shell*dzdchi, k=2, s=0) for shell in shell_weights] + shell_interp = [ + UnivariateSpline(chi, shell * dzdchi, k=2, s=0) for shell in shell_weights + ] return shell_interp + def make_glass_shell_interpolator(ws, cosmo) -> list[UnivariateSpline]: """ Spline interpolator for comoving shells. @@ -68,22 +68,33 @@ def make_glass_shell_interpolator(ws, cosmo) -> list[UnivariateSpline]: A list the length of the number of shells with each element being a UnivariateSpline for that shell. """ - return [UnivariateSpline(cosmo.comoving_distance(ws[i].za) * (1+ws[i].za), ws[i].wa, k=2, s=0, ext=1) for i in range(len(ws))] - -def get_cls(num_shells, - ell_min, # can be set to 1 - ell_max, - pk_interpolator, - shells_interpolate, - chi_lims, - N_thread = 4, #number of threads used for hyperthreading - n_sub = 8, #number of collocation points in each bisection - n_bisec_max = 64, #maximum number of bisections used - rel_acc = 1e-10, #relative accuracy target - boost_bessel = True, #should the bessel functions be calculated with boost instead of GSL, higher accuracy at high Bessel orders - verbose = False, #should the code talk to you? - lev_list = None - ): + return [ + UnivariateSpline( + cosmo.comoving_distance(ws[i].za) * (1 + ws[i].za), + ws[i].wa, + k=2, + s=0, + ext=1, + ) + for i in range(len(ws)) + ] + + +def get_cls( + num_shells, + ell_min, # can be set to 1 + ell_max, + pk_interpolator, + shells_interpolate, + chi_lims, + N_thread=4, # number of threads used for hyperthreading + n_sub=8, # number of collocation points in each bisection + n_bisec_max=64, # maximum number of bisections used + rel_acc=1e-10, # relative accuracy target + boost_bessel=True, # should the bessel functions be calculated with boost instead of GSL, higher accuracy at high Bessel orders + verbose=False, # should the code talk to you? + lev_list=None, +): """ Calculates Cls using the geometric approximation and performing the integral in comoving distance first. @@ -125,51 +136,69 @@ def get_cls(num_shells, lev_list A list of Levin objects. If lev_list is None, this will be a list of new Levin objects created during the calculation. If lev_list is not None, this will be the same list passed in as lev_list. """ - # Some levin definitions integral_type = 0 - logx = True # Tells the code to create a logarithmic spline in x for f(x) - logy = True # Tells the code to create a logarithmic spline in y for y = f(x) - + logx = True # Tells the code to create a logarithmic spline in x for f(x) + logy = True # Tells the code to create a logarithmic spline in y for y = f(x) + ell = np.unique((np.geomspace(ell_min, ell_max)).astype(int)) - + if lev_list is None: lev_list = [] load_levin = False else: lev_list load_levin = True - + N_int = int(2e3) k_int = np.geomspace(1e-4, 10, N_int) inner_int = np.zeros((num_shells, len(ell), len(k_int))) flat_idx = 0 - for idx_shell in (tqdm(np.arange(num_shells))): + for idx_shell in tqdm(np.arange(num_shells)): chi_int = np.linspace(chi_lims[idx_shell], chi_lims[idx_shell + 1], 50) pk_nl_new = np.zeros((len(chi_int), len(k_int))) - pk_nl_new[:,:] = np.sqrt(pk_interpolator(k_int, chi_int)).T*(shells_interpolate[idx_shell](chi_int))[:, None] - lower_limit = chi_int[0]*np.ones_like(k_int) - upper_limit = chi_int[-1]*np.ones_like(k_int) - + pk_nl_new[:, :] = ( + np.sqrt(pk_interpolator(k_int, chi_int)).T + * (shells_interpolate[idx_shell](chi_int))[:, None] + ) + lower_limit = chi_int[0] * np.ones_like(k_int) + upper_limit = chi_int[-1] * np.ones_like(k_int) + for i_ell, val_ell in enumerate(ell): if load_levin is True: lev = lev_list[flat_idx] else: - lev = levin.pylevin(integral_type, chi_int, pk_nl_new, logx, logy, N_thread, True) + lev = levin.pylevin( + integral_type, chi_int, pk_nl_new, logx, logy, N_thread, True + ) lev.set_levin(n_sub, n_bisec_max, rel_acc, boost_bessel, verbose) - - ell_values = (val_ell*np.ones_like(k_int)).astype(int) - lev.levin_integrate_bessel_single(lower_limit, upper_limit, k_int, ell_values, inner_int[idx_shell, i_ell,:]) + + ell_values = (val_ell * np.ones_like(k_int)).astype(int) + lev.levin_integrate_bessel_single( + lower_limit, + upper_limit, + k_int, + ell_values, + inner_int[idx_shell, i_ell, :], + ) flat_idx += 1 - + if load_levin is False: lev_list.append(lev) - shell_cls = 2/np.pi*np.trapezoid(inner_int[:, None, :, :] * inner_int[None, : ,: ,:]*k_int**2,k_int, axis = -1) - + shell_cls = ( + 2 + / np.pi + * np.trapezoid( + inner_int[:, None, :, :] * inner_int[None, :, :, :] * k_int**2, + k_int, + axis=-1, + ) + ) + shell_cls_dict = {} for i in range(len(chi_lims) - 1): for j in range(len(chi_lims) - 1): - shell_cls_dict[f'W{i+1}xW{j+1}'] = shell_cls[i, j, :] - - return shell_cls, shell_cls_dict, lev_list \ No newline at end of file + shell_cls_dict[f"W{i + 1}xW{j + 1}"] = shell_cls[i, j, :] + + return shell_cls, shell_cls_dict, lev_list From 62c8412bf6ea369ccfb81f6476f782c5b7925bdf Mon Sep 17 00:00:00 2001 From: "Patrick J. Roddy" Date: Wed, 7 May 2025 12:11:06 +0100 Subject: [PATCH 03/12] Fix line lengths --- glass/spectra.py | 39 +++++++++++++++++++++++++++------------ 1 file changed, 27 insertions(+), 12 deletions(-) diff --git a/glass/spectra.py b/glass/spectra.py index bfe3e0faa..b256c03d2 100644 --- a/glass/spectra.py +++ b/glass/spectra.py @@ -41,7 +41,8 @@ def make_shell_interpolator(shell_z, shell_weights, cosmo) -> list[UnivariateSpl Returns ------- - A list the length of the number of shells with each element being a UnivariateSpline for that shell. + A list the length of the number of shells with each element being a + UnivariateSpline for that shell. """ chi = cosmo.comoving_distance(shell_z) @@ -65,7 +66,8 @@ def make_glass_shell_interpolator(ws, cosmo) -> list[UnivariateSpline]: Returns ------- - A list the length of the number of shells with each element being a UnivariateSpline for that shell. + A list the length of the number of shells with each element being a + UnivariateSpline for that shell. """ return [ @@ -87,16 +89,24 @@ def get_cls( pk_interpolator, shells_interpolate, chi_lims, - N_thread=4, # number of threads used for hyperthreading - n_sub=8, # number of collocation points in each bisection - n_bisec_max=64, # maximum number of bisections used - rel_acc=1e-10, # relative accuracy target - boost_bessel=True, # should the bessel functions be calculated with boost instead of GSL, higher accuracy at high Bessel orders - verbose=False, # should the code talk to you? + # number of threads used for hyperthreading + N_thread: int = 4, + # number of collocation points in each bisection + n_sub: int = 8, + # maximum number of bisections used + n_bisec_max: int = 64, + # relative accuracy target + rel_acc: float = 1e-10, + # should the bessel functions be calculated with boost instead of GSL, + # higher accuracy at high Bessel orders + boost_bessel: bool = True, + # should the code talk to you? + verbose: bool = False, lev_list=None, ): """ - Calculates Cls using the geometric approximation and performing the integral in comoving distance first. + Calculates Cls using the geometric approximation and performing the integral + in comoving distance first. Parameters ---------- @@ -121,11 +131,14 @@ def get_cls( rel_acc The relative accuracy target. boost_bessel - Should the bessel functions be calculated with boost instead of GSL, higher accuracy at high Bessel orders. + Should the bessel functions be calculated with boost instead of GSL, + higher accuracy at high Bessel orders. verbose Should the code talk to you? lev_list - List of Levin objects to load. If None, new Levin objects are created. Useful for speeding up the calculation if we have at hand already calculated bisections. + List of Levin objects to load. If None, new Levin objects are created. + Useful for speeding up the calculation if we have at hand already + calculated bisections. Returns ------- @@ -134,7 +147,9 @@ def get_cls( shell_cls_dict A dictionary with the shell cls labelled by the shell pair number. lev_list - A list of Levin objects. If lev_list is None, this will be a list of new Levin objects created during the calculation. If lev_list is not None, this will be the same list passed in as lev_list. + A list of Levin objects. If lev_list is None, this will be a list of new + Levin objects created during the calculation. If lev_list is not None, + this will be the same list passed in as lev_list. """ # Some levin definitions integral_type = 0 From 2411eb071410ac3c9fce74b8c098384967adb963 Mon Sep 17 00:00:00 2001 From: "Patrick J. Roddy" Date: Wed, 7 May 2025 12:13:27 +0100 Subject: [PATCH 04/12] Revert "Fix line lengths" This reverts commit 14d2eda7f7990fc123699c64795d0c8baaa42d6b. --- glass/spectra.py | 39 ++++++++++++--------------------------- 1 file changed, 12 insertions(+), 27 deletions(-) diff --git a/glass/spectra.py b/glass/spectra.py index b256c03d2..bfe3e0faa 100644 --- a/glass/spectra.py +++ b/glass/spectra.py @@ -41,8 +41,7 @@ def make_shell_interpolator(shell_z, shell_weights, cosmo) -> list[UnivariateSpl Returns ------- - A list the length of the number of shells with each element being a - UnivariateSpline for that shell. + A list the length of the number of shells with each element being a UnivariateSpline for that shell. """ chi = cosmo.comoving_distance(shell_z) @@ -66,8 +65,7 @@ def make_glass_shell_interpolator(ws, cosmo) -> list[UnivariateSpline]: Returns ------- - A list the length of the number of shells with each element being a - UnivariateSpline for that shell. + A list the length of the number of shells with each element being a UnivariateSpline for that shell. """ return [ @@ -89,24 +87,16 @@ def get_cls( pk_interpolator, shells_interpolate, chi_lims, - # number of threads used for hyperthreading - N_thread: int = 4, - # number of collocation points in each bisection - n_sub: int = 8, - # maximum number of bisections used - n_bisec_max: int = 64, - # relative accuracy target - rel_acc: float = 1e-10, - # should the bessel functions be calculated with boost instead of GSL, - # higher accuracy at high Bessel orders - boost_bessel: bool = True, - # should the code talk to you? - verbose: bool = False, + N_thread=4, # number of threads used for hyperthreading + n_sub=8, # number of collocation points in each bisection + n_bisec_max=64, # maximum number of bisections used + rel_acc=1e-10, # relative accuracy target + boost_bessel=True, # should the bessel functions be calculated with boost instead of GSL, higher accuracy at high Bessel orders + verbose=False, # should the code talk to you? lev_list=None, ): """ - Calculates Cls using the geometric approximation and performing the integral - in comoving distance first. + Calculates Cls using the geometric approximation and performing the integral in comoving distance first. Parameters ---------- @@ -131,14 +121,11 @@ def get_cls( rel_acc The relative accuracy target. boost_bessel - Should the bessel functions be calculated with boost instead of GSL, - higher accuracy at high Bessel orders. + Should the bessel functions be calculated with boost instead of GSL, higher accuracy at high Bessel orders. verbose Should the code talk to you? lev_list - List of Levin objects to load. If None, new Levin objects are created. - Useful for speeding up the calculation if we have at hand already - calculated bisections. + List of Levin objects to load. If None, new Levin objects are created. Useful for speeding up the calculation if we have at hand already calculated bisections. Returns ------- @@ -147,9 +134,7 @@ def get_cls( shell_cls_dict A dictionary with the shell cls labelled by the shell pair number. lev_list - A list of Levin objects. If lev_list is None, this will be a list of new - Levin objects created during the calculation. If lev_list is not None, - this will be the same list passed in as lev_list. + A list of Levin objects. If lev_list is None, this will be a list of new Levin objects created during the calculation. If lev_list is not None, this will be the same list passed in as lev_list. """ # Some levin definitions integral_type = 0 From dbb04945e68491a6814191a27931ca78f04ee7c8 Mon Sep 17 00:00:00 2001 From: "Patrick J. Roddy" Date: Wed, 7 May 2025 12:16:10 +0100 Subject: [PATCH 05/12] Fix line lengths --- glass/spectra.py | 39 +++++++++++++++++++++++++++------------ 1 file changed, 27 insertions(+), 12 deletions(-) diff --git a/glass/spectra.py b/glass/spectra.py index bfe3e0faa..dfe4cb879 100644 --- a/glass/spectra.py +++ b/glass/spectra.py @@ -41,7 +41,8 @@ def make_shell_interpolator(shell_z, shell_weights, cosmo) -> list[UnivariateSpl Returns ------- - A list the length of the number of shells with each element being a UnivariateSpline for that shell. + A list the length of the number of shells with each element being a + UnivariateSpline for that shell. """ chi = cosmo.comoving_distance(shell_z) @@ -65,7 +66,8 @@ def make_glass_shell_interpolator(ws, cosmo) -> list[UnivariateSpline]: Returns ------- - A list the length of the number of shells with each element being a UnivariateSpline for that shell. + A list the length of the number of shells with each element being a + UnivariateSpline for that shell. """ return [ @@ -87,16 +89,24 @@ def get_cls( pk_interpolator, shells_interpolate, chi_lims, - N_thread=4, # number of threads used for hyperthreading - n_sub=8, # number of collocation points in each bisection - n_bisec_max=64, # maximum number of bisections used - rel_acc=1e-10, # relative accuracy target - boost_bessel=True, # should the bessel functions be calculated with boost instead of GSL, higher accuracy at high Bessel orders - verbose=False, # should the code talk to you? + # number of threads used for hyperthreading + N_thread=4, + # number of collocation points in each bisection + n_sub=8, + # maximum number of bisections used + n_bisec_max=64, + # relative accuracy target + rel_acc=1e-10, + # should the bessel functions be calculated with boost instead of GSL, + # higher accuracy at high Bessel orders + boost_bessel=True, + # should the code talk to you? + verbose=False, lev_list=None, ): """ - Calculates Cls using the geometric approximation and performing the integral in comoving distance first. + Calculates Cls using the geometric approximation and performing the integral + in comoving distance first. Parameters ---------- @@ -121,11 +131,14 @@ def get_cls( rel_acc The relative accuracy target. boost_bessel - Should the bessel functions be calculated with boost instead of GSL, higher accuracy at high Bessel orders. + Should the bessel functions be calculated with boost instead of GSL, + higher accuracy at high Bessel orders. verbose Should the code talk to you? lev_list - List of Levin objects to load. If None, new Levin objects are created. Useful for speeding up the calculation if we have at hand already calculated bisections. + List of Levin objects to load. If None, new Levin objects are created. + Useful for speeding up the calculation if we have at hand already + calculated bisections. Returns ------- @@ -134,7 +147,9 @@ def get_cls( shell_cls_dict A dictionary with the shell cls labelled by the shell pair number. lev_list - A list of Levin objects. If lev_list is None, this will be a list of new Levin objects created during the calculation. If lev_list is not None, this will be the same list passed in as lev_list. + A list of Levin objects. If lev_list is None, this will be a list of new + Levin objects created during the calculation. If lev_list is not None, + this will be the same list passed in as lev_list. """ # Some levin definitions integral_type = 0 From 04428e646fda8e5d05c7bf0ffa9b24e6ddcf4367 Mon Sep 17 00:00:00 2001 From: "Patrick J. Roddy" Date: Wed, 7 May 2025 12:18:19 +0100 Subject: [PATCH 06/12] Use `itertools.product` --- glass/spectra.py | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/glass/spectra.py b/glass/spectra.py index dfe4cb879..081bd59d5 100644 --- a/glass/spectra.py +++ b/glass/spectra.py @@ -1,3 +1,5 @@ +import itertools + import numpy as np import pylevin as levin from scipy.interpolate import RectBivariateSpline, UnivariateSpline @@ -211,9 +213,10 @@ def get_cls( ) ) - shell_cls_dict = {} - for i in range(len(chi_lims) - 1): - for j in range(len(chi_lims) - 1): - shell_cls_dict[f"W{i + 1}xW{j + 1}"] = shell_cls[i, j, :] - + shell_cls_dict = { + f"W{i + 1}xW{j + 1}": shell_cls[i, j, :] + for i, j in itertools.product( + range(len(chi_lims) - 1), range(len(chi_lims) - 1) + ) + } return shell_cls, shell_cls_dict, lev_list From 472dc1b4a296ebd177edbc2ac7a92ba10ae1bd26 Mon Sep 17 00:00:00 2001 From: "Patrick J. Roddy" Date: Wed, 7 May 2025 12:50:24 +0100 Subject: [PATCH 07/12] Add some typing --- glass/spectra.py | 36 +++++++++++++++++++++++------------- 1 file changed, 23 insertions(+), 13 deletions(-) diff --git a/glass/spectra.py b/glass/spectra.py index 081bd59d5..e3c45e01e 100644 --- a/glass/spectra.py +++ b/glass/spectra.py @@ -1,12 +1,20 @@ import itertools +from typing import TYPE_CHECKING import numpy as np import pylevin as levin from scipy.interpolate import RectBivariateSpline, UnivariateSpline from tqdm import tqdm +if TYPE_CHECKING: + from numpy.typing import NDArray -def make_pk_interpolators(pk, k, z) -> RectBivariateSpline: + from cosmology import Cosmology + + +def make_pk_interpolators( + pk, k: NDArray[float], z: NDArray[float] +) -> RectBivariateSpline: """ Spline interpolator for the matter power spectrum. @@ -28,7 +36,9 @@ def make_pk_interpolators(pk, k, z) -> RectBivariateSpline: return pkz_interp -def make_shell_interpolator(shell_z, shell_weights, cosmo) -> list[UnivariateSpline]: +def make_shell_interpolator( + shell_z, shell_weights, cosmo: Cosmology +) -> list[UnivariateSpline]: """ Spline interpolator for comoving shells. @@ -55,7 +65,7 @@ def make_shell_interpolator(shell_z, shell_weights, cosmo) -> list[UnivariateSpl return shell_interp -def make_glass_shell_interpolator(ws, cosmo) -> list[UnivariateSpline]: +def make_glass_shell_interpolator(ws, cosmo: Cosmology) -> list[UnivariateSpline]: """ Spline interpolator for comoving shells. @@ -84,26 +94,26 @@ def make_glass_shell_interpolator(ws, cosmo) -> list[UnivariateSpline]: ] -def get_cls( - num_shells, - ell_min, # can be set to 1 - ell_max, +def get_cls( # noqa: PLR0913 + num_shells: int, + ell_min: int, # can be set to 1 + ell_max: int, pk_interpolator, shells_interpolate, chi_lims, # number of threads used for hyperthreading - N_thread=4, + N_thread: int = 4, # number of collocation points in each bisection - n_sub=8, + n_sub: int = 8, # maximum number of bisections used - n_bisec_max=64, + n_bisec_max: int = 64, # relative accuracy target - rel_acc=1e-10, + rel_acc: float = 1e-10, # should the bessel functions be calculated with boost instead of GSL, # higher accuracy at high Bessel orders - boost_bessel=True, + boost_bessel: bool = True, # should the code talk to you? - verbose=False, + verbose: bool = False, lev_list=None, ): """ From 59e72d4f8e99d9cf87fcc8704bbc6987c3cb8712 Mon Sep 17 00:00:00 2001 From: Kiyam Lin Date: Tue, 24 Nov 2026 08:41:00 +0000 Subject: [PATCH 08/12] gh-609: Rewrite non-Limber shell spectra as a port of the validated 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 --- docs/reference/index.rst | 1 + docs/reference/spectra.rst | 1 + glass/spectra.py | 414 +++++++++++++++++++------------------ pyproject.toml | 3 + tests/core/test_spectra.py | 74 +++++++ 5 files changed, 291 insertions(+), 202 deletions(-) create mode 100644 docs/reference/spectra.rst create mode 100644 tests/core/test_spectra.py diff --git a/docs/reference/index.rst b/docs/reference/index.rst index df26f9692..587b79e35 100644 --- a/docs/reference/index.rst +++ b/docs/reference/index.rst @@ -6,6 +6,7 @@ Function reference :maxdepth: 1 shells + spectra fields points shapes diff --git a/docs/reference/spectra.rst b/docs/reference/spectra.rst new file mode 100644 index 000000000..1e696807d --- /dev/null +++ b/docs/reference/spectra.rst @@ -0,0 +1 @@ +.. automodule:: glass.spectra diff --git a/glass/spectra.py b/glass/spectra.py index e3c45e01e..ad6595a25 100644 --- a/glass/spectra.py +++ b/glass/spectra.py @@ -1,232 +1,242 @@ -import itertools -from typing import TYPE_CHECKING +""" +Spectra +======= -import numpy as np -import pylevin as levin -from scipy.interpolate import RectBivariateSpline, UnivariateSpline -from tqdm import tqdm +.. currentmodule:: glass.spectra -if TYPE_CHECKING: - from numpy.typing import NDArray +Angular power spectra of GLASS matter shells without the Limber +approximation, using the Levin method for the Bessel integrals as +implemented by `pylevin `_. - from cosmology import Cosmology +This module requires the optional ``pylevin`` and ``scipy`` packages +and is not imported by ``import glass``. +.. autofunction:: nonlimber_cls -def make_pk_interpolators( - pk, k: NDArray[float], z: NDArray[float] -) -> RectBivariateSpline: - """ - Spline interpolator for the matter power spectrum. +""" # noqa: D400 - Parameters - ---------- - pk - 3D matter power spectrum. - k - Array of wavenumbers corresponding to 3D matter power spectrum values. - z - Array of redshifts corresponding to 3D matter power spectrum values. - - Returns - ------- - RectBivariateSpline object to interpolate the 3D matter power spectrum. +from __future__ import annotations - """ - pkz_interp = RectBivariateSpline(k, z, pk) - return pkz_interp +__lazy_modules__ = [ + "pylevin", + "scipy.interpolate", +] +import functools +import os +from typing import TYPE_CHECKING -def make_shell_interpolator( - shell_z, shell_weights, cosmo: Cosmology -) -> list[UnivariateSpline]: - """ - Spline interpolator for comoving shells. +import numpy as np +import pylevin +from scipy.interpolate import CubicSpline - Parameters - ---------- - shell_z - The redshift boundaries for concentric matter shells. - shell_weights - The weights of the shells. - cosmo - Cosmology object to calculate the comoving distances. +if TYPE_CHECKING: + from collections.abc import Callable, Sequence - Returns - ------- - A list the length of the number of shells with each element being a - UnivariateSpline for that shell. + from numpy.typing import NDArray - """ - chi = cosmo.comoving_distance(shell_z) - dzdchi = UnivariateSpline(chi, shell_z, k=2, s=0).derivative()(chi) - shell_interp = [ - UnivariateSpline(chi, shell * dzdchi, k=2, s=0) for shell in shell_weights - ] - return shell_interp + from glass.cosmology import Cosmology + from glass.shells import RadialWindow -def make_glass_shell_interpolator(ws, cosmo: Cosmology) -> list[UnivariateSpline]: +def _levin( # noqa: PLR0913 + ks: NDArray[np.float64], + ncol: int = 8, + *, + window: tuple[NDArray[np.float64], NDArray[np.float64], NDArray[np.float64]], + pk: Callable[..., NDArray[np.float64]], + ell: int, + nthread: int, +) -> NDArray[np.float64]: """ - Spline interpolator for comoving shells. + Compute the inner integral I(ell, k) of one shell at the given k. - Parameters - ---------- - ws - Glass shells. - cosmo - Cosmology object to calculate the comoving distances. + A new pylevin instance is created per call, since instances cache + their solution. + """ + za, chi, kernel = window + f = np.sqrt(pk(za, ks)) * kernel[:, None] + lp = pylevin.pylevin(0, chi, f, True, True, nthread, True) # noqa: FBT003 + # n_col, n_bisec, rel_acc, super_accurate (False aborts), verbose, + # tol_abs (>0 stops early) + lp.set_levin(ncol, 32, 1e-4, True, False, 0.0) # noqa: FBT003 + out = np.zeros(len(ks)) + lp.levin_integrate_bessel_single( + np.full(len(ks), chi[0]), + np.full(len(ks), chi[-1]), + ks, + np.full(len(ks), int(ell)), + out, + ) + return out - Returns - ------- - A list the length of the number of shells with each element being a - UnivariateSpline for that shell. +def _robust( + call: Callable[..., NDArray[np.float64]], + ks: NDArray[np.float64], + tol: float = 1e-4, +) -> NDArray[np.float64]: """ - return [ - UnivariateSpline( - cosmo.comoving_distance(ws[i].za) * (1 + ws[i].za), - ws[i].wa, - k=2, - s=0, - ext=1, - ) - for i in range(len(ws)) - ] - - -def get_cls( # noqa: PLR0913 - num_shells: int, - ell_min: int, # can be set to 1 - ell_max: int, - pk_interpolator, - shells_interpolate, - chi_lims, - # number of threads used for hyperthreading - N_thread: int = 4, - # number of collocation points in each bisection - n_sub: int = 8, - # maximum number of bisections used - n_bisec_max: int = 64, - # relative accuracy target - rel_acc: float = 1e-10, - # should the bessel functions be calculated with boost instead of GSL, - # higher accuracy at high Bessel orders - boost_bessel: bool = True, - # should the code talk to you? - verbose: bool = False, - lev_list=None, -): + Compute I(ell, k) robustly against rare pylevin glitches. + + pylevin returns garbage at rare isolated k (deterministic, any size, + up to several per cent of the amplitude, and flipped by 1e-16 input + changes). Each n_col has its own glitches, and I(k) is not smooth on + the k grid at high l, so neighbour tests cannot find them. Compute + every k at n_col 8 and 6; where they disagree by more than *tol* + times the 98th percentile amplitude, also compute n_col 10 and take + the median of the three. pylevin pairs n_col (9 == 10, 11 == 12), so + alternates must be even steps apart. """ - Calculates Cls using the geometric approximation and performing the integral - in comoving distance first. + if not len(ks): + return np.zeros(0) + i8, i6 = call(ks, 8), call(ks, 6) + j = np.nonzero(np.abs(i8 - i6) > tol * np.quantile(np.abs(i8), 0.98))[0] + if len(j): + i8[j] = np.median(np.stack([i8[j], i6[j], call(ks[j], 10)]), axis=0) + return i8 + + +def nonlimber_cls( # noqa: PLR0913 + pk: Callable[..., NDArray[np.float64]], + cosmo: Cosmology, + ws: Sequence[RadialWindow], + lmax: int, + *, + nthread: int | None = None, + density: float = 217, + q: float = 30.0, +) -> list[NDArray[np.float64]]: + r""" + Compute the angular power spectra of matter shells without Limber. + + For each shell :math:`a` with kernel :math:`K_a(\chi)`, normalised + to unit integral in comoving distance, the inner integral + + .. math:: + + I_a(\ell, k) = \int \! d\chi \, K_a(\chi) \sqrt{P(k, z)} + \, j_\ell(k \chi) + + is computed with the Levin method, and the angular power spectra + are + + .. math:: + + C_{ab}(\ell) = \frac{2}{\pi} \int \! dk \, k^2 \, + I_a(\ell, k) \, I_b(\ell, k) \;. + + The non-Limber integrals are computed at every :math:`\ell < 20`, + at every second value of the combined grid of :math:`\ell \in [20, + 29]` and 75 log-spaced values up to *lmax*, and at *lmax*. In + between, the smooth relative correction :math:`(C - C^{\rm L}) / + \sqrt{C^{\rm L}_{aa} C^{\rm L}_{bb}}` is splined in :math:`\log\ell` + on top of the Limber spectra :math:`C^{\rm L}`, which are computed + at every :math:`\ell`. Parameters ---------- - num_shells - The number of shells. - ell_min - The minimum ell value. - ell_max - The maximum ell value. - pk_interpolator - The interpolator for the matter power spectrum. - shells_interpolate - The interpolator for the comoving shells. - chi_lims - The comoving distance limits for the shells. - N_thread - The number of threads used for hyperthreading. - n_sub - The number of collocation points in each bisection. - n_bisec_max - The maximum number of bisections used. - rel_acc - The relative accuracy target. - boost_bessel - Should the bessel functions be calculated with boost instead of GSL, - higher accuracy at high Bessel orders. - verbose - Should the code talk to you? - lev_list - List of Levin objects to load. If None, new Levin objects are created. - Useful for speeding up the calculation if we have at hand already - calculated bisections. + pk + The matter power spectrum as a function ``pk(z, k)`` of 1-D + arrays of redshift and wavenumber, returning an array of shape + ``(z.size, k.size)``, e.g. the ``P`` method of a CAMB matter + power interpolator. Wavenumbers are in units of the inverse of + the distance units of *cosmo*. + cosmo + Cosmology for comoving distances and the Hubble function. The + integration grid in wavenumber, from 1e-4 to 100, assumes + distances in Mpc. + ws + Radial windows of the matter shells. The power spectrum *pk* + must reach the redshift of the last shell. + lmax + Maximum angular mode number. + nthread + Number of threads for pylevin. Defaults to the + ``SLURM_CPUS_PER_TASK`` environment variable if set, or the + number of CPUs otherwise. + density + Number of wavenumber grid points per e-fold. + q + The k-support of shell :math:`a` is cut to + :math:`[0.3 \, \nu / \chi_{\max}, \max(3 \nu / \chi_{\min}, + q / \Delta\chi)]` with :math:`\nu = \ell + 1/2`. Returns ------- - shell_cls - A 3D array of the shell cls. - shell_cls_dict - A dictionary with the shell cls labelled by the shell pair number. - lev_list - A list of Levin objects. If lev_list is None, this will be a list of new - Levin objects created during the calculation. If lev_list is not None, - this will be the same list passed in as lev_list. + The angular power spectra for :math:`\ell = 0, \ldots, l_{\max}` + in GLASS order (for i in 0..n-1, for j in i..0), with + :math:`C(\ell = 0) = 0`. + """ - # Some levin definitions - integral_type = 0 - logx = True # Tells the code to create a logarithmic spline in x for f(x) - logy = True # Tells the code to create a logarithmic spline in y for y = f(x) - - ell = np.unique((np.geomspace(ell_min, ell_max)).astype(int)) - - if lev_list is None: - lev_list = [] - load_levin = False - else: - lev_list - load_levin = True - - N_int = int(2e3) - k_int = np.geomspace(1e-4, 10, N_int) - inner_int = np.zeros((num_shells, len(ell), len(k_int))) - flat_idx = 0 - for idx_shell in tqdm(np.arange(num_shells)): - chi_int = np.linspace(chi_lims[idx_shell], chi_lims[idx_shell + 1], 50) - pk_nl_new = np.zeros((len(chi_int), len(k_int))) - pk_nl_new[:, :] = ( - np.sqrt(pk_interpolator(k_int, chi_int)).T - * (shells_interpolate[idx_shell](chi_int))[:, None] - ) - lower_limit = chi_int[0] * np.ones_like(k_int) - upper_limit = chi_int[-1] * np.ones_like(k_int) - - for i_ell, val_ell in enumerate(ell): - if load_levin is True: - lev = lev_list[flat_idx] - else: - lev = levin.pylevin( - integral_type, chi_int, pk_nl_new, logx, logy, N_thread, True - ) - lev.set_levin(n_sub, n_bisec_max, rel_acc, boost_bessel, verbose) - - ell_values = (val_ell * np.ones_like(k_int)).astype(int) - lev.levin_integrate_bessel_single( - lower_limit, - upper_limit, - k_int, - ell_values, - inner_int[idx_shell, i_ell, :], - ) - flat_idx += 1 - - if load_levin is False: - lev_list.append(lev) - - shell_cls = ( - 2 - / np.pi - * np.trapezoid( - inner_int[:, None, :, :] * inner_int[None, :, :, :] * k_int**2, - k_int, - axis=-1, - ) + nthread = int( + nthread or os.environ.get("SLURM_CPUS_PER_TASK") or os.cpu_count() or 1 ) + dh = cosmo.hubble_distance + + shells = [] + for w in ws: + za = np.linspace(w.za[0], w.za[-1], 400) + kernel = np.interp(za, w.za, w.wa) * cosmo.H_over_H0(za) / dh + chi = cosmo.comoving_distance(za) + kernel /= np.trapezoid(kernel, chi) + # drop zero endpoints (log spline in pylevin) + shells.append((za[1:-1], chi[1:-1], kernel[1:-1])) + n = len(shells) + + # non-Limber at sparse l on a shared log k grid; shell a only on k in + # [0.3 nu/chi_hi, max(3 nu/chi_lo, q/dchi)] + ell_all = np.unique( + np.r_[np.arange(2, 30), np.geomspace(30, lmax, 75).astype(int)], + ) + ell = np.union1d(np.r_[np.arange(1, 20), ell_all[::2]], [lmax]) + k = np.geomspace(1e-4, 100.0, int(density * np.log(1e6)) + 1) + inner = np.zeros((n, len(ell), len(k))) + for a, (za, chi, kernel) in enumerate(shells): + for i, el in enumerate(ell): + m = (k >= 0.3 * (el + 0.5) / chi[-1]) & ( + k <= max(3 * (el + 0.5) / chi[0], q / (chi[-1] - chi[0])) + ) - shell_cls_dict = { - f"W{i + 1}xW{j + 1}": shell_cls[i, j, :] - for i, j in itertools.product( - range(len(chi_lims) - 1), range(len(chi_lims) - 1) + call = functools.partial( + _levin, + window=(za, chi, kernel), + pk=pk, + ell=el, + nthread=nthread, + ) + inner[a, i, m] = _robust(call, k[m]) + cl = np.empty((n, n, len(ell))) + for i in range(len(ell)): # per l keeps the (n, n, nk) temporary small + cl[..., i] = ( + 2 + / np.pi + * np.trapezoid(inner[:, None, i] * inner[None, :, i] * k**2, k, axis=-1) ) - } - return shell_cls, shell_cls_dict, lev_list + + # Limber at every l = 1..lmax + 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) + / dh + ) + 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))]) + limber = ( + (kf[:, None] * kf[None, :] * (np.gradient(chif) / chif**2)).reshape(n * n, -1) + @ pf + ).reshape(n, n, -1) + + d = np.arange(n) + nrm = np.sqrt(limber[d, d][:, None] * limber[d, d][None, :]) + s = ell - 1 # index of the computed l in lf + full = limber + nrm * CubicSpline( + np.log(ell), + (cl - limber[..., s]) / nrm[..., s], + axis=-1, + )(np.log(lf)) + full[..., s] = cl # exact at the computed l + return [np.r_[0.0, full[i, j]] for i in range(n) for j in range(i, -1, -1)] diff --git a/pyproject.toml b/pyproject.toml index 5c2d57260..9876e25f1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -310,6 +310,9 @@ spaces_indent_inline_array = 4 trailing_comma_inline_array = true [tool.ty] +analysis.allowed-unresolved-imports = [ + "pylevin", # sdist only (needs GSL and Boost), not in the typechecking group +] analysis.respect-type-ignore-comments = false rules = { all = "error", invalid-argument-type = "ignore" } src.include = [ diff --git a/tests/core/test_spectra.py b/tests/core/test_spectra.py new file mode 100644 index 000000000..519fec338 --- /dev/null +++ b/tests/core/test_spectra.py @@ -0,0 +1,74 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +import numpy as np +import pytest + +pytest.importorskip("pylevin", reason="tests require pylevin") +pytest.importorskip("scipy", reason="tests require scipy") + +from scipy.special import spherical_jn + +import glass +import glass.spectra + +if TYPE_CHECKING: + from glass._types import FloatArray + + +class FlatLCDM: + """Flat LCDM cosmology with distances in Mpc.""" + + hubble_distance = 299792.458 / 70.0 + Omega_m0 = 0.3 + + def H_over_H0(self, z: FloatArray) -> FloatArray: # noqa: N802 + """Dimensionless Hubble function.""" + return np.sqrt(self.Omega_m0 * (1 + z) ** 3 + 1 - self.Omega_m0) + + def comoving_distance(self, z: FloatArray) -> FloatArray: + """Comoving distance in Mpc.""" + zg = np.linspace(0.0, np.max(z), 2001) + f = 1 / self.H_over_H0(zg) + dc = np.r_[0.0, np.cumsum((f[1:] + f[:-1]) / 2 * np.diff(zg))] + return self.hubble_distance * np.interp(z, zg, dc) + + +def pk(z: FloatArray, k: FloatArray) -> FloatArray: + """Smooth power spectrum, growing with redshift like D(z)^2 ~ 1/(1+z)^2.""" + return (2e4 * k / (1 + (k / 0.02) ** 2) ** 1.4) / (1 + z[:, None]) ** 2 + + +def test_nonlimber_cls() -> None: + cosmo = FlatLCDM() + ws = glass.linear_windows(np.asarray([0.0, 0.2, 0.4, 0.6])) + lmax = 40 + + # q = 100: the default k-support cut is tuned for ~200 Mpc shells and + # leaves ~1% on the l = 2 cross of these ~1000 Mpc wide shells + cls = glass.spectra.nonlimber_cls(pk, cosmo, ws, lmax, nthread=1, q=100.0) + + # GLASS order: (0, 0), (1, 1), (1, 0) + assert len(cls) == 3 + for cl in cls: + assert cl.shape == (lmax + 1,) + assert cl[0] == 0.0 + assert np.all(cls[0][1:] > 0) + assert np.all(cls[1][1:] > 0) + assert np.all(cls[2][1:] ** 2 < cls[0][1:] * cls[1][1:]) + + # brute-force non-Limber at a few low l, where Limber is far off + k = np.geomspace(1e-4, 1.0, 4000) + for ell in [2, 5, 12]: + inner = [] + for w in ws: + z = np.linspace(w.za[0], w.za[-1], 2000) + chi = cosmo.comoving_distance(z) + kern = np.interp(z, w.za, w.wa) * cosmo.H_over_H0(z) / cosmo.hubble_distance + kern /= np.trapezoid(kern, chi) + f = kern[:, None] * np.sqrt(pk(z, k)) * spherical_jn(ell, k * chi[:, None]) + inner.append(np.trapezoid(f, chi, axis=0)) + for cl, (a, b) in zip(cls, [(0, 0), (1, 1), (1, 0)], strict=True): + expect = 2 / np.pi * np.trapezoid(k**2 * inner[a] * inner[b], k) + np.testing.assert_allclose(cl[ell], expect, rtol=3e-3) From 69d6669896161988b0a5c195ca6fc0ce8e6d1750 Mon Sep 17 00:00:00 2001 From: Kiyam Lin Date: Tue, 24 Nov 2026 09:06:24 +0000 Subject: [PATCH 09/12] gh-609: Add `robust` switch to `nonlimber_cls` 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 --- glass/spectra.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/glass/spectra.py b/glass/spectra.py index ad6595a25..c244906a3 100644 --- a/glass/spectra.py +++ b/glass/spectra.py @@ -106,6 +106,7 @@ def nonlimber_cls( # noqa: PLR0913 nthread: int | None = None, density: float = 217, q: float = 30.0, + robust: bool = True, ) -> list[NDArray[np.float64]]: r""" Compute the angular power spectra of matter shells without Limber. @@ -161,6 +162,12 @@ def nonlimber_cls( # noqa: PLR0913 The k-support of shell :math:`a` is cut to :math:`[0.3 \, \nu / \chi_{\max}, \max(3 \nu / \chi_{\min}, q / \Delta\chi)]` with :math:`\nu = \ell + 1/2`. + robust + Guard against rare isolated pylevin errors by solving each + wavenumber twice and taking a median of three where the two + disagree. This doubles the cost. The errors reach a few per cent + of single shell spectra, but in tests sums over many shells, such + as lensing spectra, changed by less than 1e-4 without it. Returns ------- @@ -205,7 +212,7 @@ def nonlimber_cls( # noqa: PLR0913 ell=el, nthread=nthread, ) - inner[a, i, m] = _robust(call, k[m]) + inner[a, i, m] = _robust(call, k[m]) if robust else call(k[m]) cl = np.empty((n, n, len(ell))) for i in range(len(ell)): # per l keeps the (n, n, nk) temporary small cl[..., i] = ( From a6d1c777531b42f51b79be846203d285a41c29a6 Mon Sep 17 00:00:00 2001 From: Kiyam Lin Date: Fri, 27 Nov 2026 16:33:58 +0000 Subject: [PATCH 10/12] gh-609: Add `nonlimber_plan` to precompute non-Limber quadrature 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 --- glass/spectra.py | 368 +++++++++++++++++++++++++++++++++---- tests/core/test_spectra.py | 72 +++++++- 2 files changed, 402 insertions(+), 38 deletions(-) diff --git a/glass/spectra.py b/glass/spectra.py index c244906a3..889ac98c7 100644 --- a/glass/spectra.py +++ b/glass/spectra.py @@ -12,6 +12,9 @@ and is not imported by ``import glass``. .. autofunction:: nonlimber_cls +.. autofunction:: nonlimber_plan +.. autoclass:: NonLimberPlan + :members: save, load """ # noqa: D400 @@ -22,12 +25,14 @@ "scipy.interpolate", ] +import dataclasses import functools import os from typing import TYPE_CHECKING import numpy as np import pylevin +from scipy import sparse from scipy.interpolate import CubicSpline if TYPE_CHECKING: @@ -35,7 +40,7 @@ from numpy.typing import NDArray - from glass.cosmology import Cosmology + from glass.cosmology import Cosmology, CosmologyWithInverseComovingDistance from glass.shells import RadialWindow @@ -97,6 +102,297 @@ def _robust( return i8 +def _ell_grid(lmax: int) -> NDArray[np.int_]: + """Multipoles at which the non-Limber integrals are computed.""" + ell_all = np.unique( + np.r_[np.arange(2, 30), np.geomspace(30, lmax, 75).astype(int)], + ) + return np.union1d(np.r_[np.arange(1, 20), ell_all[::2]], [lmax]) + + +def _k_grid(density: float) -> NDArray[np.float64]: + """Shared log wavenumber grid from 1e-4 to 100.""" + return np.geomspace(1e-4, 100.0, int(density * np.log(1e6)) + 1) + + +def _k_mask( + k: NDArray[np.float64], + ell: int, + lo: float, + hi: float, + q: float, +) -> NDArray[np.bool_]: + """K-support [0.3 nu/hi, max(3 nu/lo, q/(hi - lo))] of a shell on [lo, hi].""" + nu = ell + 0.5 + kmax = 3 * nu / lo if lo > 0 else np.inf + return (k >= 0.3 * nu / hi) & (k <= max(kmax, q / (hi - lo))) + + +def _knots( + a: int, + dx: float, + nknot: int, +) -> tuple[NDArray[np.float64], NDArray[np.float64]]: + """Knots of the two halves of shell *a* on [a dx, (a + 2) dx].""" + left = np.linspace(a * dx, (a + 1) * dx, nknot) + right = np.linspace((a + 1) * dx, (a + 2) * dx, nknot) + return left, right + + +def _basis( + x: NDArray[np.float64], + left: NDArray[np.float64], + right: NDArray[np.float64], +) -> NDArray[np.float64]: + """ + Evaluate the piecewise cubic basis of a shell at *x*. + + Not-a-knot cubic splines on the two halves of the shell, joined + continuously at the kink of the triangular window. Column *j* is + the spline of unit value at the *j*-th of the ``2 nknot - 1`` knots. + """ + n = len(left) + basis = np.zeros((len(x), 2 * n - 1)) + lm = x <= left[-1] + basis[lm, :n] = CubicSpline(left, np.eye(n))(x[lm]) + basis[~lm, n - 1 :] = CubicSpline(right, np.eye(n))(x[~lm]) + return basis + + +def _rule( # noqa: PLR0913 + chi: NDArray[np.float64], + f: NDArray[np.float64], + ks: NDArray[np.float64], + ell: int, + knots: tuple[NDArray[np.float64], NDArray[np.float64]], + *, + ncol: int, + nthread: int, +) -> tuple[NDArray[np.float64], NDArray[np.float64]]: + """ + Compute pylevin quadrature rules for the integrals of *f* at *ks*. + + The first call determines the subintervals, the second stores the + rules. Returns the rules combined with the basis of the *knots* into + a matrix from integrand values at the knots to integrals, and the + integrals of *f*. + """ + lp = pylevin.pylevin(0, chi, f, True, True, nthread, True) # noqa: FBT003 + lp.set_levin(ncol, 32, 1e-4, True, False, 0.0) # noqa: FBT003 + out = np.zeros(len(ks)) + args = ( + np.full(len(ks), chi[0]), + np.full(len(ks), chi[-1]), + ks, + np.full(len(ks), int(ell)), + out, + ) + lp.levin_integrate_bessel_single(*args) + lp.levin_integrate_bessel_single(*args) + x, w, offsets = lp.get_quadrature() + row = np.repeat(np.arange(len(ks)), np.diff(offsets)) + rule = sparse.csr_matrix((w, (row, np.arange(len(x)))), shape=(len(ks), len(x))) + return np.asarray(rule @ _basis(np.asarray(x), *knots)), out + + +@dataclasses.dataclass(frozen=True) +class NonLimberPlan: + """ + Precomputed quadrature of :func:`nonlimber_cls`. + + Created by :func:`nonlimber_plan`. For shell *a* and the *i*-th + computed multipole, ``rules[a][i]`` is a tuple ``(start, stop, w)``: + the inner integrals at the wavenumbers ``k[start:stop]`` of the grid + are ``w @ g``, with ``g`` the integrand at the knots of the shell. + """ + + dx: float + lmax: int + nknot: int + density: float + q: float + rules: list[list[tuple[int, int, NDArray[np.float64]]]] + + def save(self, path: str) -> None: + """Save the plan to a ``.npz`` file.""" + arrays = { + f"{a}_{i}": w + for a, rules in enumerate(self.rules) + for i, (_, _, w) in enumerate(rules) + } + starts = np.array([[r[0] for r in rules] for rules in self.rules]) + np.savez( + path, + meta=np.array([self.dx, self.lmax, self.nknot, self.density, self.q]), + starts=starts, + **arrays, + ) + + @classmethod + def load(cls, path: str) -> NonLimberPlan: + """Load a plan saved with :meth:`save`.""" + with np.load(path) as f: + dx, lmax, nknot, density, q = f["meta"] + rules = [] + for a, starts in enumerate(f["starts"]): + rules_a = [] + for i, start in enumerate(starts): + w = f[f"{a}_{i}"] + rules_a.append((int(start), int(start) + len(w), w)) + rules.append(rules_a) + return cls(float(dx), int(lmax), int(nknot), float(density), float(q), rules) + + +def nonlimber_plan( # noqa: PLR0913 + pk: Callable[..., NDArray[np.float64]], + cosmo: CosmologyWithInverseComovingDistance, + lmax: int, + nshells: int, + *, + dx: float = 200.0, + nknot: int = 16, + nthread: int | None = None, + density: float = 217, + q: float = 30.0, + robust: bool = True, + tol: float = 1e-4, +) -> NonLimberPlan: + r""" + Precompute the quadrature of :func:`nonlimber_cls` for many cosmologies. + + With :func:`glass.distance_grid` and :func:`glass.linear_windows`, + shell :math:`a` spans :math:`[a \, \Delta x, (a + 2) \, \Delta x]` in + comoving distance in every cosmology, with the kink of its window at + :math:`(a + 1) \, \Delta x`, since every edge of the grid is a + multiple of :math:`\Delta x`. The adaptive quadrature rules of + pylevin for the inner integrals of each shell are therefore + computed once, for a representative integrand: a triangular window + times :math:`\sqrt{P(k, z)}` of the reference cosmology. They are + combined with a piecewise cubic spline in comoving distance, with + *nknot* knots on each half of the shell, into one matrix per shell + and multipole. With the plan, :func:`nonlimber_cls` only evaluates + the integrand at the knots, which is hundreds of times faster than + solving the integrals. + + This requires pylevin 2.0 or later, which exports quadrature rules. + + Parameters + ---------- + pk + Matter power spectrum of the reference cosmology, as for + :func:`nonlimber_cls`. It must reach the redshift of comoving + distance :math:`(n + 1) \, \Delta x` for *n* shells. + cosmo + Reference cosmology, with inverse comoving distance. + lmax + Maximum angular mode number. + nshells + Number of shells to plan for: the largest number of shells of + the cosmologies the plan will be used for. + dx + Comoving distance spacing of the shell grid, as given to + :func:`glass.distance_grid`. + nknot + Number of spline knots on each half of a shell. + nthread + Number of threads for pylevin, as for :func:`nonlimber_cls`. + density, q + Wavenumber grid density and k-support cut, as for + :func:`nonlimber_cls`. + robust + Guard the rules against rare isolated pylevin errors, which a + plan would repeat for every cosmology. The rules are computed + with ``n_col`` 8 and 6; where their integrals disagree by more + than *tol* times the 98th percentile amplitude, they are also + computed with ``n_col`` 10, and the rule with the median integral + is kept. + tol + Tolerance of the robust check. + + Returns + ------- + The plan for :func:`nonlimber_cls`. + + """ + if not hasattr(pylevin.pylevin, "get_quadrature"): + msg = "nonlimber_plan requires pylevin 2.0 or later" + raise ImportError(msg) + nthread = int( + nthread or os.environ.get("SLURM_CPUS_PER_TASK") or os.cpu_count() or 1 + ) + ell, k = _ell_grid(lmax), _k_grid(density) + rules = [] + for a in range(nshells): + lo, mid, hi = a * dx, (a + 1) * dx, (a + 2) * dx + chi = np.linspace(lo, hi, 400)[1:-1] + sqrtp = np.sqrt(pk(cosmo.inv_comoving_distance(chi), k)) + tri = (1 - np.abs(chi - mid) / dx)[:, None] + knots = _knots(a, dx, nknot) + rules_a = [] + for el in ell: + idx = np.nonzero(_k_mask(k, el, lo, hi, q))[0] + start, stop = int(idx[0]), int(idx[-1]) + 1 + ks, f = k[start:stop], tri * sqrtp[:, start:stop] + w, i8 = _rule(chi, f, ks, el, knots, ncol=8, nthread=nthread) + if robust: + w6, i6 = _rule(chi, f, ks, el, knots, ncol=6, nthread=nthread) + j = np.nonzero(np.abs(i8 - i6) > tol * np.quantile(np.abs(i8), 0.98))[0] + if len(j): + w10, i10 = _rule( + chi, f[:, j], ks[j], el, knots, ncol=10, nthread=nthread + ) + vals = np.stack([i8[j], i6[j], i10]) + med = np.argsort(vals, axis=0)[1] + w[j] = np.choose(med[:, None], [w[j], w6[j], w10]) + rules_a.append((start, stop, w)) + rules.append(rules_a) + return NonLimberPlan( + float(dx), int(lmax), int(nknot), float(density), float(q), rules + ) + + +def _planned_inner( + plan: NonLimberPlan, + pk: Callable[..., NDArray[np.float64]], + cosmo: CosmologyWithInverseComovingDistance, + ws: Sequence[RadialWindow], + k: NDArray[np.float64], +) -> NDArray[np.float64]: + """Inner integrals I_a(ell, k) of all shells from a plan.""" + if len(ws) > len(plan.rules): + msg = f"plan has {len(plan.rules)} shells, but there are {len(ws)}" + raise ValueError(msg) + dh = cosmo.hubble_distance + inner = np.zeros((len(ws), len(plan.rules[0]), len(k))) + for a, w in enumerate(ws): + z_edges = np.array([w.za[0], w.za[np.argmax(w.wa)], w.za[-1]]) + if not np.allclose( + cosmo.comoving_distance(z_edges), + plan.dx * (a + np.arange(3)), + rtol=1e-6, + atol=1e-6 * plan.dx, + ): + msg = ( + f"shell {a} is not on the comoving grid of the plan with " + f"spacing {plan.dx}; use glass.distance_grid with dx={plan.dx}" + " and glass.linear_windows" + ) + raise ValueError(msg) + left, right = _knots(a, plan.dx, plan.nknot) + z = cosmo.inv_comoving_distance(np.r_[left, right[1:]]) + # unit normalisation in comoving distance, on the same grid as without plan + za = np.linspace(w.za[0], w.za[-1], 400) + norm = np.trapezoid( + np.interp(za, w.za, w.wa) * cosmo.H_over_H0(za) / dh, + cosmo.comoving_distance(za), + ) + kernel = np.interp(z, w.za, w.wa) * cosmo.H_over_H0(z) / dh / norm + g = kernel[:, None] * np.sqrt(pk(z, k)) + for i, (start, stop, wm) in enumerate(plan.rules[a]): + inner[a, i, start:stop] = np.einsum("kj,jk->k", wm, g[:, start:stop]) + return inner + + def nonlimber_cls( # noqa: PLR0913 pk: Callable[..., NDArray[np.float64]], cosmo: Cosmology, @@ -107,6 +403,7 @@ def nonlimber_cls( # noqa: PLR0913 density: float = 217, q: float = 30.0, robust: bool = True, + plan: NonLimberPlan | None = None, ) -> list[NDArray[np.float64]]: r""" Compute the angular power spectra of matter shells without Limber. @@ -168,6 +465,11 @@ def nonlimber_cls( # noqa: PLR0913 disagree. This doubles the cost. The errors reach a few per cent of single shell spectra, but in tests sums over many shells, such as lensing spectra, changed by less than 1e-4 without it. + plan + Precomputed quadrature from :func:`nonlimber_plan`. The shells + must then lie on its comoving grid, and *lmax*, *density* and *q* + are taken from the plan; *nthread* and *robust* are not used. + The cosmology needs the inverse comoving distance. Returns ------- @@ -176,43 +478,41 @@ def nonlimber_cls( # noqa: PLR0913 :math:`C(\ell = 0) = 0`. """ - nthread = int( - nthread or os.environ.get("SLURM_CPUS_PER_TASK") or os.cpu_count() or 1 - ) dh = cosmo.hubble_distance - - shells = [] - for w in ws: - za = np.linspace(w.za[0], w.za[-1], 400) - kernel = np.interp(za, w.za, w.wa) * cosmo.H_over_H0(za) / dh - chi = cosmo.comoving_distance(za) - kernel /= np.trapezoid(kernel, chi) - # drop zero endpoints (log spline in pylevin) - shells.append((za[1:-1], chi[1:-1], kernel[1:-1])) - n = len(shells) + n = len(ws) + if plan is not None: + if lmax != plan.lmax: + msg = f"plan is for lmax={plan.lmax}, not {lmax}" + raise ValueError(msg) + density, q = plan.density, plan.q # non-Limber at sparse l on a shared log k grid; shell a only on k in # [0.3 nu/chi_hi, max(3 nu/chi_lo, q/dchi)] - ell_all = np.unique( - np.r_[np.arange(2, 30), np.geomspace(30, lmax, 75).astype(int)], - ) - ell = np.union1d(np.r_[np.arange(1, 20), ell_all[::2]], [lmax]) - k = np.geomspace(1e-4, 100.0, int(density * np.log(1e6)) + 1) - inner = np.zeros((n, len(ell), len(k))) - for a, (za, chi, kernel) in enumerate(shells): - for i, el in enumerate(ell): - m = (k >= 0.3 * (el + 0.5) / chi[-1]) & ( - k <= max(3 * (el + 0.5) / chi[0], q / (chi[-1] - chi[0])) - ) - - call = functools.partial( - _levin, - window=(za, chi, kernel), - pk=pk, - ell=el, - nthread=nthread, - ) - inner[a, i, m] = _robust(call, k[m]) if robust else call(k[m]) + ell, k = _ell_grid(lmax), _k_grid(density) + if plan is not None: + inner = _planned_inner(plan, pk, cosmo, ws, k) + else: + nthread = int( + nthread or os.environ.get("SLURM_CPUS_PER_TASK") or os.cpu_count() or 1 + ) + inner = np.zeros((n, len(ell), len(k))) + for a, w in enumerate(ws): + za = np.linspace(w.za[0], w.za[-1], 400) + kernel = np.interp(za, w.za, w.wa) * cosmo.H_over_H0(za) / dh + chi = cosmo.comoving_distance(za) + kernel /= np.trapezoid(kernel, chi) + # drop zero endpoints (log spline in pylevin) + za, chi, kernel = za[1:-1], chi[1:-1], kernel[1:-1] + for i, el in enumerate(ell): + m = _k_mask(k, el, chi[0], chi[-1], q) + call = functools.partial( + _levin, + window=(za, chi, kernel), + pk=pk, + ell=el, + nthread=nthread, + ) + inner[a, i, m] = _robust(call, k[m]) if robust else call(k[m]) cl = np.empty((n, n, len(ell))) for i in range(len(ell)): # per l keeps the (n, n, nk) temporary small cl[..., i] = ( diff --git a/tests/core/test_spectra.py b/tests/core/test_spectra.py index 519fec338..1222e74dd 100644 --- a/tests/core/test_spectra.py +++ b/tests/core/test_spectra.py @@ -27,12 +27,20 @@ def H_over_H0(self, z: FloatArray) -> FloatArray: # noqa: N802 """Dimensionless Hubble function.""" return np.sqrt(self.Omega_m0 * (1 + z) ** 3 + 1 - self.Omega_m0) + _zg = np.linspace(0.0, 3.0, 6001) + + def _dc(self) -> FloatArray: + f = 1 / self.H_over_H0(self._zg) + dc = np.r_[0.0, np.cumsum((f[1:] + f[:-1]) / 2 * np.diff(self._zg))] + return self.hubble_distance * dc + def comoving_distance(self, z: FloatArray) -> FloatArray: """Comoving distance in Mpc.""" - zg = np.linspace(0.0, np.max(z), 2001) - f = 1 / self.H_over_H0(zg) - dc = np.r_[0.0, np.cumsum((f[1:] + f[:-1]) / 2 * np.diff(zg))] - return self.hubble_distance * np.interp(z, zg, dc) + return np.interp(z, self._zg, self._dc()) + + def inv_comoving_distance(self, x: FloatArray) -> FloatArray: + """Redshift of comoving distance in Mpc.""" + return np.interp(x, self._dc(), self._zg) def pk(z: FloatArray, k: FloatArray) -> FloatArray: @@ -72,3 +80,59 @@ def test_nonlimber_cls() -> None: for cl, (a, b) in zip(cls, [(0, 0), (1, 1), (1, 0)], strict=True): expect = 2 / np.pi * np.trapezoid(k**2 * inner[a] * inner[b], k) np.testing.assert_allclose(cl[ell], expect, rtol=3e-3) + + +def assert_close_spectra( + cls: list[FloatArray], ref: list[FloatArray], tol: float +) -> None: + """|cls - ref| <= tol sqrt(ref_aa ref_bb) for every pair in GLASS order.""" + n = int((np.sqrt(8 * len(ref) + 1) - 1) / 2) + pairs = [(i, j) for i in range(n) for j in range(i, -1, -1)] + auto = {i: ref[pairs.index((i, i))][1:] for i in range(n)} + for cl, cr, (i, j) in zip(cls, ref, pairs, strict=True): + assert np.all(np.abs(cl[1:] - cr[1:]) <= tol * np.sqrt(auto[i] * auto[j])), ( + i, + j, + ) + + +def test_nonlimber_plan(tmp_path) -> None: + cosmo = FlatLCDM() + zgrid = glass.distance_grid(cosmo, 0.0, 0.25, dx=200.0) + ws = glass.linear_windows(zgrid) + lmax = 40 + # a coarse wavenumber grid for speed: plan and direct use the same one + kw = {"nthread": 1, "density": 80} + + plan = glass.spectra.nonlimber_plan(pk, cosmo, lmax, len(ws) + 1, **kw) + assert len(plan.rules) == len(ws) + 1 + + direct = glass.spectra.nonlimber_cls(pk, cosmo, ws, lmax, **kw) + planned = glass.spectra.nonlimber_cls(pk, cosmo, ws, lmax, plan=plan) + assert len(planned) == len(direct) + assert_close_spectra(planned, direct, 1e-3) + + # the plan is cosmology-independent: a different P(k) still agrees + def pk2(z: FloatArray, k: FloatArray) -> FloatArray: + return 1.5 * pk(z, k) * (1 + 0.3 * np.sin(np.log(k))) / (1 + z[:, None]) + + direct = glass.spectra.nonlimber_cls(pk2, cosmo, ws, lmax, **kw) + planned = glass.spectra.nonlimber_cls(pk2, cosmo, ws, lmax, plan=plan) + assert_close_spectra(planned, direct, 1e-3) + + # save and load + plan.save(tmp_path / "plan.npz") + loaded = glass.spectra.NonLimberPlan.load(tmp_path / "plan.npz") + again = glass.spectra.nonlimber_cls(pk, cosmo, ws, lmax, plan=loaded) + for cp, ca in zip( + glass.spectra.nonlimber_cls(pk, cosmo, ws, lmax, plan=plan), again, strict=True + ): + np.testing.assert_array_equal(cp, ca) + + # shells off the grid of the plan + with pytest.raises(ValueError, match="not on the comoving grid"): + glass.spectra.nonlimber_cls( + pk, cosmo, glass.linear_windows(zgrid * 1.01), lmax, plan=plan + ) + with pytest.raises(ValueError, match="lmax"): + glass.spectra.nonlimber_cls(pk, cosmo, ws, lmax + 1, plan=plan) From 80439d21a9672a4caa94c43855fe813001425d74 Mon Sep 17 00:00:00 2001 From: Kiyam Lin Date: Sat, 28 Nov 2026 18:09:13 +0000 Subject: [PATCH 11/12] gh-609: Plan half shells in one pylevin instance, require pylevin 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 --- glass/spectra.py | 296 +++++++++++++++++++++---------------- tests/core/test_spectra.py | 116 ++++++++++++++- 2 files changed, 281 insertions(+), 131 deletions(-) diff --git a/glass/spectra.py b/glass/spectra.py index 889ac98c7..3e3e3185c 100644 --- a/glass/spectra.py +++ b/glass/spectra.py @@ -8,8 +8,8 @@ approximation, using the Levin method for the Bessel integrals as implemented by `pylevin `_. -This module requires the optional ``pylevin`` and ``scipy`` packages -and is not imported by ``import glass``. +This module requires the optional ``pylevin`` (2.0.1 or later) and +``scipy`` packages and is not imported by ``import glass``. .. autofunction:: nonlimber_cls .. autofunction:: nonlimber_plan @@ -27,7 +27,10 @@ import dataclasses import functools +import importlib.metadata +import itertools import os +import re from typing import TYPE_CHECKING import numpy as np @@ -35,6 +38,12 @@ from scipy import sparse from scipy.interpolate import CubicSpline +# 2.0 exports quadrature rules, 2.0.1 refines unresolved integrands +_PYLEVIN = re.match(r"(\d+)\.(\d+)\.(\d+)", importlib.metadata.version("pylevin")) +if _PYLEVIN is None or tuple(map(int, _PYLEVIN.groups())) < (2, 0, 1): + msg = "glass.spectra requires pylevin 2.0.1 or later" + raise ImportError(msg) + if TYPE_CHECKING: from collections.abc import Callable, Sequence @@ -84,10 +93,11 @@ def _robust( """ Compute I(ell, k) robustly against rare pylevin glitches. - pylevin returns garbage at rare isolated k (deterministic, any size, - up to several per cent of the amplitude, and flipped by 1e-16 input - changes). Each n_col has its own glitches, and I(k) is not smooth on - the k grid at high l, so neighbour tests cannot find them. Compute + pylevin returns wrong values at rare isolated k (deterministic, and + flipped by 1e-16 input changes). With 2.0.1 they reach 3e-3 of the + amplitude at n_col 8 and 3e-2 at n_col 6 in tests. Each n_col has + its own glitches, and I(k) is not smooth on the k grid at high l, + so neighbour tests cannot find them. Compute every k at n_col 8 and 6; where they disagree by more than *tol* times the 98th percentile amplitude, also compute n_col 10 and take the median of the three. pylevin pairs n_col (9 == 10, 11 == 12), so @@ -128,82 +138,69 @@ def _k_mask( return (k >= 0.3 * nu / hi) & (k <= max(kmax, q / (hi - lo))) -def _knots( - a: int, - dx: float, - nknot: int, -) -> tuple[NDArray[np.float64], NDArray[np.float64]]: - """Knots of the two halves of shell *a* on [a dx, (a + 2) dx].""" - left = np.linspace(a * dx, (a + 1) * dx, nknot) - right = np.linspace((a + 1) * dx, (a + 2) * dx, nknot) - return left, right - - -def _basis( +def _rules( # noqa: PLR0913, PLR0917 x: NDArray[np.float64], - left: NDArray[np.float64], - right: NDArray[np.float64], -) -> NDArray[np.float64]: - """ - Evaluate the piecewise cubic basis of a shell at *x*. - - Not-a-knot cubic splines on the two halves of the shell, joined - continuously at the kink of the triangular window. Column *j* is - the spline of unit value at the *j*-th of the ``2 nknot - 1`` knots. - """ - n = len(left) - basis = np.zeros((len(x), 2 * n - 1)) - lm = x <= left[-1] - basis[lm, :n] = CubicSpline(left, np.eye(n))(x[lm]) - basis[~lm, n - 1 :] = CubicSpline(right, np.eye(n))(x[~lm]) - return basis - - -def _rule( # noqa: PLR0913 - chi: NDArray[np.float64], f: NDArray[np.float64], + lo: NDArray[np.float64], + hi: NDArray[np.float64], ks: NDArray[np.float64], - ell: int, - knots: tuple[NDArray[np.float64], NDArray[np.float64]], + ells: NDArray[np.int_], + integrand: NDArray[np.int_], *, ncol: int, nthread: int, -) -> tuple[NDArray[np.float64], NDArray[np.float64]]: +) -> tuple[NDArray[np.float64], NDArray[np.float64], NDArray[np.int_], NDArray]: """ - Compute pylevin quadrature rules for the integrals of *f* at *ks*. - - The first call determines the subintervals, the second stores the - rules. Returns the rules combined with the basis of the *knots* into - a matrix from integrand values at the knots to integrals, and the - integrals of *f*. + Compute pylevin quadrature rules for many integrals at once. + + Integral *p* is of column ``integrand[p]`` of *f* times the Bessel + function of order ``ells[p]`` at ``ks[p] x``, from ``lo[p]`` to + ``hi[p]``, as in one diagonal pylevin instance with an integrand + map. The first call determines the subintervals, the second stores + the rules. Returns the nodes, weights and offsets of the rules, and + the integrals. """ - lp = pylevin.pylevin(0, chi, f, True, True, nthread, True) # noqa: FBT003 + lp = pylevin.pylevin(0, x, f, False, False, nthread, True) # noqa: FBT003 lp.set_levin(ncol, 32, 1e-4, True, False, 0.0) # noqa: FBT003 out = np.zeros(len(ks)) - args = ( - np.full(len(ks), chi[0]), - np.full(len(ks), chi[-1]), - ks, - np.full(len(ks), int(ell)), - out, + for _ in range(2): + lp.levin_integrate_bessel_single(lo, hi, ks, ells, out, integrand=integrand) + nodes, weights, offsets = lp.get_quadrature() + return np.asarray(nodes), np.asarray(weights), np.asarray(offsets), out + + +def _rule_matrix( + nodes: NDArray[np.float64], + weights: NDArray[np.float64], + offsets: NDArray[np.int_], + knots: NDArray[np.float64], +) -> NDArray[np.float64]: + """ + Combine rules with the not-a-knot cubic spline through *knots*. + + The rules are those of the integrals between *offsets*. Returns the + matrix from integrand values at the knots to integrals. + """ + n = len(offsets) - 1 + s = slice(offsets[0], offsets[-1]) + row = np.repeat(np.arange(n), np.diff(offsets)) + rule = sparse.csr_matrix( + (weights[s], (row, np.arange(len(row)))), shape=(n, len(row)) ) - lp.levin_integrate_bessel_single(*args) - lp.levin_integrate_bessel_single(*args) - x, w, offsets = lp.get_quadrature() - row = np.repeat(np.arange(len(ks)), np.diff(offsets)) - rule = sparse.csr_matrix((w, (row, np.arange(len(x)))), shape=(len(ks), len(x))) - return np.asarray(rule @ _basis(np.asarray(x), *knots)), out + return np.asarray(rule @ CubicSpline(knots, np.eye(len(knots)))(nodes[s])) @dataclasses.dataclass(frozen=True) class NonLimberPlan: - """ + r""" Precomputed quadrature of :func:`nonlimber_cls`. - Created by :func:`nonlimber_plan`. For shell *a* and the *i*-th - computed multipole, ``rules[a][i]`` is a tuple ``(start, stop, w)``: - the inner integrals at the wavenumbers ``k[start:stop]`` of the grid - are ``w @ g``, with ``g`` the integrand at the knots of the shell. + Created by :func:`nonlimber_plan`. The rules are for the half shells + :math:`[b \, \Delta x, (b + 1) \, \Delta x]`. For half *b* and the + *i*-th computed multipole, ``rules[b][i]`` is a tuple + ``(start, stop, w)``: the integrals over the half at the wavenumbers + ``k[start:stop]`` of the grid are ``w @ g``, with ``g`` the integrand + at the knots of the half. """ dx: float @@ -213,11 +210,16 @@ class NonLimberPlan: q: float rules: list[list[tuple[int, int, NDArray[np.float64]]]] + @property + def nshells(self) -> int: + """Number of shells the plan is for.""" + return len(self.rules) - 1 + def save(self, path: str) -> None: """Save the plan to a ``.npz`` file.""" arrays = { - f"{a}_{i}": w - for a, rules in enumerate(self.rules) + f"{b}_{i}": w + for b, rules in enumerate(self.rules) for i, (_, _, w) in enumerate(rules) } starts = np.array([[r[0] for r in rules] for rules in self.rules]) @@ -234,12 +236,12 @@ def load(cls, path: str) -> NonLimberPlan: with np.load(path) as f: dx, lmax, nknot, density, q = f["meta"] rules = [] - for a, starts in enumerate(f["starts"]): - rules_a = [] + for b, starts in enumerate(f["starts"]): + rules_b = [] for i, start in enumerate(starts): - w = f[f"{a}_{i}"] - rules_a.append((int(start), int(start) + len(w), w)) - rules.append(rules_a) + w = f[f"{b}_{i}"] + rules_b.append((int(start), int(start) + len(w), w)) + rules.append(rules_b) return cls(float(dx), int(lmax), int(nknot), float(density), float(q), rules) @@ -264,17 +266,16 @@ def nonlimber_plan( # noqa: PLR0913 shell :math:`a` spans :math:`[a \, \Delta x, (a + 2) \, \Delta x]` in comoving distance in every cosmology, with the kink of its window at :math:`(a + 1) \, \Delta x`, since every edge of the grid is a - multiple of :math:`\Delta x`. The adaptive quadrature rules of - pylevin for the inner integrals of each shell are therefore - computed once, for a representative integrand: a triangular window - times :math:`\sqrt{P(k, z)}` of the reference cosmology. They are - combined with a piecewise cubic spline in comoving distance, with - *nknot* knots on each half of the shell, into one matrix per shell - and multipole. With the plan, :func:`nonlimber_cls` only evaluates - the integrand at the knots, which is hundreds of times faster than - solving the integrals. - - This requires pylevin 2.0 or later, which exports quadrature rules. + multiple of :math:`\Delta x`. The inner integrals of each shell are + the sums of integrals over its two halves, each of which is shared + with a neighbouring shell. The adaptive quadrature rules of pylevin + for the halves are therefore computed once, in one diagonal pylevin + instance with one representative integrand per wavenumber: + :math:`\sqrt{P(k, z)}` of the reference cosmology. They are combined + with a cubic spline in comoving distance, with *nknot* knots on each + half, into one matrix per half and multipole. With the plan, + :func:`nonlimber_cls` only evaluates the integrand at the knots, + which is hundreds of times faster than solving the integrals. Parameters ---------- @@ -314,38 +315,74 @@ def nonlimber_plan( # noqa: PLR0913 The plan for :func:`nonlimber_cls`. """ - if not hasattr(pylevin.pylevin, "get_quadrature"): - msg = "nonlimber_plan requires pylevin 2.0 or later" - raise ImportError(msg) nthread = int( nthread or os.environ.get("SLURM_CPUS_PER_TASK") or os.cpu_count() or 1 ) ell, k = _ell_grid(lmax), _k_grid(density) - rules = [] - for a in range(nshells): - lo, mid, hi = a * dx, (a + 1) * dx, (a + 2) * dx - chi = np.linspace(lo, hi, 400)[1:-1] - sqrtp = np.sqrt(pk(cosmo.inv_comoving_distance(chi), k)) - tri = (1 - np.abs(chi - mid) / dx)[:, None] - knots = _knots(a, dx, nknot) - rules_a = [] + nhalf, nell = nshells + 1, len(ell) + + # wavenumbers of half b at ell: those of the shells b - 1 and b + ranges = [] + for b in range(nhalf): for el in ell: - idx = np.nonzero(_k_mask(k, el, lo, hi, q))[0] - start, stop = int(idx[0]), int(idx[-1]) + 1 - ks, f = k[start:stop], tri * sqrtp[:, start:stop] - w, i8 = _rule(chi, f, ks, el, knots, ncol=8, nthread=nthread) - if robust: - w6, i6 = _rule(chi, f, ks, el, knots, ncol=6, nthread=nthread) - j = np.nonzero(np.abs(i8 - i6) > tol * np.quantile(np.abs(i8), 0.98))[0] - if len(j): - w10, i10 = _rule( - chi, f[:, j], ks[j], el, knots, ncol=10, nthread=nthread - ) - vals = np.stack([i8[j], i6[j], i10]) - med = np.argsort(vals, axis=0)[1] - w[j] = np.choose(med[:, None], [w[j], w6[j], w10]) - rules_a.append((start, stop, w)) - rules.append(rules_a) + m = np.zeros(len(k), dtype=bool) + for a in range(max(b - 1, 0), min(b, nshells - 1) + 1): + m |= _k_mask(k, el, a * dx, (a + 2) * dx, q) + idx = np.nonzero(m)[0] + ranges.append((int(idx[0]), int(idx[-1]) + 1)) + counts = [stop - start for start, stop in ranges] + bounds = np.r_[0, np.cumsum(counts)] + kidx = np.concatenate([np.arange(start, stop) for start, stop in ranges]) + half = np.repeat(np.repeat(np.arange(nhalf), nell), counts) + + # one integrand per wavenumber, on all halves + x = np.linspace(0.0, nhalf * dx, 100 * nhalf + 1) + f = np.sqrt(pk(cosmo.inv_comoving_distance(x), k)) + solve = functools.partial(_rules, x, f, nthread=nthread) + args = ( + # boost's j_ell fails at nodes rounded below 0 + np.maximum(half * dx, 1e-6 * dx), + (half + 1) * dx, + k[kidx], + np.repeat(np.tile(ell, nhalf), counts), + kidx, + ) + rules8 = solve(*args, ncol=8) + + # robust: per integral, the rule of the median of n_col 8, 6, 10 + choice: dict[int, tuple] = {} + if robust: + rules6 = solve(*args, ncol=6) + i8, i6 = rules8[3], rules6[3] + bad = np.concatenate([ + np.abs(i8[v0:v1] - i6[v0:v1]) > tol * np.quantile(np.abs(i8[v0:v1]), 0.98) + for v0, v1 in itertools.pairwise(bounds) + ]) + j = np.nonzero(bad)[0] + if len(j): + rules10 = solve(*(arg[j] for arg in args), ncol=10) + vals = np.stack([i8[j], i6[j], rules10[3]]) + for jj, (v, med) in enumerate( + zip(j, np.argsort(vals, axis=0)[1], strict=True) + ): + if med == 1: + choice[int(v)] = (rules6, v) + elif med == 2: + choice[int(v)] = (rules10, jj) + + rules = [] + for b in range(nhalf): + knots = np.linspace(b * dx, (b + 1) * dx, nknot) + v0, v1 = bounds[b * nell], bounds[(b + 1) * nell] + w = _rule_matrix(*rules8[:2], rules8[2][v0 : v1 + 1], knots) + for v in range(v0, v1): + if v in choice: + (nodes, weights, offsets, _), p = choice[v] + w[v - v0] = _rule_matrix(nodes, weights, offsets[p : p + 2], knots)[0] + rules.append([ + (start, stop, w[bounds[b * nell + i] - v0 : bounds[b * nell + i + 1] - v0]) + for i, (start, stop) in enumerate(ranges[b * nell : (b + 1) * nell]) + ]) return NonLimberPlan( float(dx), int(lmax), int(nknot), float(density), float(q), rules ) @@ -359,27 +396,33 @@ def _planned_inner( k: NDArray[np.float64], ) -> NDArray[np.float64]: """Inner integrals I_a(ell, k) of all shells from a plan.""" - if len(ws) > len(plan.rules): - msg = f"plan has {len(plan.rules)} shells, but there are {len(ws)}" + if len(ws) > plan.nshells: + msg = f"plan has {plan.nshells} shells, but there are {len(ws)}" raise ValueError(msg) - dh = cosmo.hubble_distance - inner = np.zeros((len(ws), len(plan.rules[0]), len(k))) + dh, dx, nknot = cosmo.hubble_distance, plan.dx, plan.nknot + ell = _ell_grid(plan.lmax) + inner = np.zeros((len(ws), len(ell), len(k))) for a, w in enumerate(ws): z_edges = np.array([w.za[0], w.za[np.argmax(w.wa)], w.za[-1]]) if not np.allclose( cosmo.comoving_distance(z_edges), - plan.dx * (a + np.arange(3)), + dx * (a + np.arange(3)), rtol=1e-6, - atol=1e-6 * plan.dx, + atol=1e-6 * dx, ): msg = ( f"shell {a} is not on the comoving grid of the plan with " - f"spacing {plan.dx}; use glass.distance_grid with dx={plan.dx}" + f"spacing {dx}; use glass.distance_grid with dx={dx}" " and glass.linear_windows" ) raise ValueError(msg) - left, right = _knots(a, plan.dx, plan.nknot) - z = cosmo.inv_comoving_distance(np.r_[left, right[1:]]) + # knots of the two halves; the middle one is in both + z = cosmo.inv_comoving_distance( + np.r_[ + np.linspace(a * dx, (a + 1) * dx, nknot), + np.linspace((a + 1) * dx, (a + 2) * dx, nknot), + ] + ) # unit normalisation in comoving distance, on the same grid as without plan za = np.linspace(w.za[0], w.za[-1], 400) norm = np.trapezoid( @@ -388,8 +431,14 @@ def _planned_inner( ) kernel = np.interp(z, w.za, w.wa) * cosmo.H_over_H0(z) / dh / norm g = kernel[:, None] * np.sqrt(pk(z, k)) - for i, (start, stop, wm) in enumerate(plan.rules[a]): - inner[a, i, start:stop] = np.einsum("kj,jk->k", wm, g[:, start:stop]) + for i, el in enumerate(ell): + idx = np.nonzero(_k_mask(k, el, a * dx, (a + 2) * dx, plan.q))[0] + start, stop = int(idx[0]), int(idx[-1]) + 1 + for b, gb in ((a, g[:nknot]), (a + 1, g[nknot:])): + s, _, wm = plan.rules[b][i] + inner[a, i, start:stop] += np.einsum( + "kj,jk->k", wm[start - s : stop - s], gb[:, start:stop] + ) return inner @@ -462,9 +511,8 @@ def nonlimber_cls( # noqa: PLR0913 robust Guard against rare isolated pylevin errors by solving each wavenumber twice and taking a median of three where the two - disagree. This doubles the cost. The errors reach a few per cent - of single shell spectra, but in tests sums over many shells, such - as lensing spectra, changed by less than 1e-4 without it. + disagree. This doubles the cost. With pylevin 2.0.1, the errors + reach 3e-3 of the amplitude of single shell integrals in tests. plan Precomputed quadrature from :func:`nonlimber_plan`. The shells must then lie on its comoving grid, and *lmax*, *density* and *q* diff --git a/tests/core/test_spectra.py b/tests/core/test_spectra.py index 1222e74dd..bc5e90c1b 100644 --- a/tests/core/test_spectra.py +++ b/tests/core/test_spectra.py @@ -8,6 +8,7 @@ pytest.importorskip("pylevin", reason="tests require pylevin") pytest.importorskip("scipy", reason="tests require scipy") +from scipy.interpolate import RegularGridInterpolator from scipy.special import spherical_jn import glass @@ -83,17 +84,19 @@ def test_nonlimber_cls() -> None: def assert_close_spectra( - cls: list[FloatArray], ref: list[FloatArray], tol: float + cls: list[FloatArray], + ref: list[FloatArray], + tol: float | FloatArray, + lmin: int = 1, ) -> None: """|cls - ref| <= tol sqrt(ref_aa ref_bb) for every pair in GLASS order.""" n = int((np.sqrt(8 * len(ref) + 1) - 1) / 2) pairs = [(i, j) for i in range(n) for j in range(i, -1, -1)] - auto = {i: ref[pairs.index((i, i))][1:] for i in range(n)} + auto = {i: ref[pairs.index((i, i))][lmin:] for i in range(n)} + tol = np.broadcast_to(tol, ref[0].shape)[lmin:] for cl, cr, (i, j) in zip(cls, ref, pairs, strict=True): - assert np.all(np.abs(cl[1:] - cr[1:]) <= tol * np.sqrt(auto[i] * auto[j])), ( - i, - j, - ) + err = np.abs(cl[lmin:] - cr[lmin:]) + assert np.all(err <= tol * np.sqrt(auto[i] * auto[j])), (i, j) def test_nonlimber_plan(tmp_path) -> None: @@ -105,7 +108,7 @@ def test_nonlimber_plan(tmp_path) -> None: kw = {"nthread": 1, "density": 80} plan = glass.spectra.nonlimber_plan(pk, cosmo, lmax, len(ws) + 1, **kw) - assert len(plan.rules) == len(ws) + 1 + assert plan.nshells == len(ws) + 1 direct = glass.spectra.nonlimber_cls(pk, cosmo, ws, lmax, **kw) planned = glass.spectra.nonlimber_cls(pk, cosmo, ws, lmax, plan=plan) @@ -136,3 +139,102 @@ def pk2(z: FloatArray, k: FloatArray) -> FloatArray: ) with pytest.raises(ValueError, match="lmax"): glass.spectra.nonlimber_cls(pk, cosmo, ws, lmax + 1, plan=plan) + + +def test_nonlimber_cls_camb() -> None: + """Compare with the non-Limber number counts of CAMB at high accuracy.""" + camb = pytest.importorskip("camb", reason="test requires camb") + from camb.sources import SplinedSourceWindow + + pars = camb.set_params( + H0=67.5, + ombh2=0.022, + omch2=0.122, + mnu=0.0, + num_massive_neutrinos=0, + As=2.1e-9, + ns=0.965, + WantCls=False, + ) + pars.Want_CMB = False + pars.NonLinear = camb.model.NonLinear_none + bg = camb.get_background(pars) + + class CambCosmology: + hubble_distance = 299792.458 / pars.H0 + + def H_over_H0(self, z: FloatArray) -> FloatArray: # noqa: N802 + return np.asarray(bg.hubble_parameter(z)) / pars.H0 + + def comoving_distance(self, z: FloatArray) -> FloatArray: + return np.asarray(bg.comoving_radial_distance(z)) + + def inv_comoving_distance(self, x: FloatArray) -> FloatArray: + return np.asarray(bg.redshift_at_comoving_radial_distance(x)) + + cosmo = CambCosmology() + ws = glass.linear_windows(glass.distance_grid(cosmo, 0.0, 0.3, dx=200.0)) + lmax = 100 + + # CAMB's density source is synchronous gauge CDM transformed to + # Newtonian gauge, d_N = d_c + 3 (aH/k)^2 v_N, which changes l = 2 by + # 1%: apply the same transformation to P(k) through the transfers + zmax = ws[-1].za[-1] + 0.1 + p = camb.get_matter_power_interpolator( + pars, + nonlinear=False, + hubble_units=False, + k_hunit=False, + kmax=100.0, + zmax=zmax, + var1="delta_cdm", + var2="delta_cdm", + extrap_kmax=True, + ) + zs = np.linspace(zmax, 0.0, 40) + tp = pars.copy() + tp.set_matter_power(redshifts=list(zs), kmax=10.0) + tr = camb.get_results(tp).get_matter_transfer_data() + dc = tr.transfer_data[camb.model.Transfer_cdm - 1] + vn = tr.transfer_data[camb.model.Transfer_Newt_vel_cdm - 1] + ah = np.asarray(bg.hubble_parameter(zs)) / (1 + zs) / 299792.458 + ratio = 1 + 3 * ah**2 * vn / (tr.q[:, None] ** 2 * dc) + gauge = RegularGridInterpolator((np.log(tr.q), zs[::-1]), ratio[:, ::-1]) + + def pk_newtonian(z: FloatArray, k: FloatArray) -> FloatArray: + lk = np.clip(np.log(k), np.log(tr.q[0]), np.log(tr.q[-1])) + lk_, z_ = np.meshgrid(lk, z) + return p.P(z, k, grid=True) * gauge((lk_, z_)) ** 2 + + cls = glass.spectra.nonlimber_cls(pk_newtonian, cosmo, ws, lmax) + + # number counts of the density term only, without Limber + pars.WantCls = True + pars.set_accuracy(AccuracyBoost=3, lSampleBoost=50, lAccuracyBoost=3) + pars.set_for_lmax(lmax, lens_potential_accuracy=0) + pars.SourceTerms.limber_windows = False + pars.SourceTerms.counts_density = True + for term in ( + "redshift", + "lensing", + "velocity", + "radial", + "timedelay", + "ISW", + "potential", + "evolve", + ): + setattr(pars.SourceTerms, f"counts_{term}", False) + pars.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 + ] + cd = camb.get_results(pars).get_source_cls_dict(raw_cl=True, lmax=lmax) + n = len(ws) + ref = [cd[f"W{i + 1}xW{j + 1}"] for i in range(n) for j in range(i, -1, -1)] + + assert_close_spectra(cls, ref, 2e-3, lmin=2) From 1da468c441478e4bae2fa6f653f6288efa968b90 Mon Sep 17 00:00:00 2001 From: Kiyam Lin Date: Thu, 3 Dec 2026 09:07:32 +0000 Subject: [PATCH 12/12] gh-609: Require pylevin 2.1.0 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 --- glass/spectra.py | 39 +++++++++++++++++++++++---------------- 1 file changed, 23 insertions(+), 16 deletions(-) diff --git a/glass/spectra.py b/glass/spectra.py index 3e3e3185c..439b83971 100644 --- a/glass/spectra.py +++ b/glass/spectra.py @@ -8,7 +8,7 @@ approximation, using the Levin method for the Bessel integrals as implemented by `pylevin `_. -This module requires the optional ``pylevin`` (2.0.1 or later) and +This module requires the optional ``pylevin`` (2.1.0 or later) and ``scipy`` packages and is not imported by ``import glass``. .. autofunction:: nonlimber_cls @@ -38,10 +38,11 @@ from scipy import sparse from scipy.interpolate import CubicSpline -# 2.0 exports quadrature rules, 2.0.1 refines unresolved integrands +# 2.0 exports quadrature rules, 2.0.1 refines unresolved integrands, +# 2.1.0 stores the rules in the first call _PYLEVIN = re.match(r"(\d+)\.(\d+)\.(\d+)", importlib.metadata.version("pylevin")) -if _PYLEVIN is None or tuple(map(int, _PYLEVIN.groups())) < (2, 0, 1): - msg = "glass.spectra requires pylevin 2.0.1 or later" +if _PYLEVIN is None or tuple(map(int, _PYLEVIN.groups())) < (2, 1, 0): + msg = "glass.spectra requires pylevin 2.1.0 or later" raise ImportError(msg) if TYPE_CHECKING: @@ -71,9 +72,17 @@ def _levin( # noqa: PLR0913 za, chi, kernel = window f = np.sqrt(pk(za, ks)) * kernel[:, None] lp = pylevin.pylevin(0, chi, f, True, True, nthread, True) # noqa: FBT003 - # n_col, n_bisec, rel_acc, super_accurate (False aborts), verbose, - # tol_abs (>0 stops early) - lp.set_levin(ncol, 32, 1e-4, True, False, 0.0) # noqa: FBT003 + # n_col, n_bisec, rel_acc; gsl Bessel functions abort, tol_abs > 0 stops + # early, and one call needs no stored rules + lp.set_levin( + ncol, + 32, + 1e-4, + super_accurate=True, + verbose=False, + tol_abs_in=0.0, + store_first_call=False, + ) out = np.zeros(len(ks)) lp.levin_integrate_bessel_single( np.full(len(ks), chi[0]), @@ -94,7 +103,7 @@ def _robust( Compute I(ell, k) robustly against rare pylevin glitches. pylevin returns wrong values at rare isolated k (deterministic, and - flipped by 1e-16 input changes). With 2.0.1 they reach 3e-3 of the + flipped by 1e-16 input changes). With 2.1.0 they reach 6e-3 of the amplitude at n_col 8 and 3e-2 at n_col 6 in tests. Each n_col has its own glitches, and I(k) is not smooth on the k grid at high l, so neighbour tests cannot find them. Compute @@ -156,15 +165,14 @@ def _rules( # noqa: PLR0913, PLR0917 Integral *p* is of column ``integrand[p]`` of *f* times the Bessel function of order ``ells[p]`` at ``ks[p] x``, from ``lo[p]`` to ``hi[p]``, as in one diagonal pylevin instance with an integrand - map. The first call determines the subintervals, the second stores - the rules. Returns the nodes, weights and offsets of the rules, and + map. The call determines the subintervals and stores the rules. + Returns the nodes, weights and offsets of the rules, and the integrals. """ lp = pylevin.pylevin(0, x, f, False, False, nthread, True) # noqa: FBT003 lp.set_levin(ncol, 32, 1e-4, True, False, 0.0) # noqa: FBT003 out = np.zeros(len(ks)) - for _ in range(2): - lp.levin_integrate_bessel_single(lo, hi, ks, ells, out, integrand=integrand) + lp.levin_integrate_bessel_single(lo, hi, ks, ells, out, integrand=integrand) nodes, weights, offsets = lp.get_quadrature() return np.asarray(nodes), np.asarray(weights), np.asarray(offsets), out @@ -340,8 +348,7 @@ def nonlimber_plan( # noqa: PLR0913 f = np.sqrt(pk(cosmo.inv_comoving_distance(x), k)) solve = functools.partial(_rules, x, f, nthread=nthread) args = ( - # boost's j_ell fails at nodes rounded below 0 - np.maximum(half * dx, 1e-6 * dx), + half * dx, (half + 1) * dx, k[kidx], np.repeat(np.tile(ell, nhalf), counts), @@ -511,8 +518,8 @@ def nonlimber_cls( # noqa: PLR0913 robust Guard against rare isolated pylevin errors by solving each wavenumber twice and taking a median of three where the two - disagree. This doubles the cost. With pylevin 2.0.1, the errors - reach 3e-3 of the amplitude of single shell integrals in tests. + disagree. This doubles the cost. With pylevin 2.1.0, the errors + reach 6e-3 of the amplitude of single shell integrals in tests. plan Precomputed quadrature from :func:`nonlimber_plan`. The shells must then lie on its comoving grid, and *lmax*, *density* and *q*