Skip to content

Commit cd5b442

Browse files
committed
Error handling for unallocated transfers; setuptools requirements
1 parent 22f9f21 commit cd5b442

File tree

8 files changed

+41
-16
lines changed

8 files changed

+41
-16
lines changed

.github/workflows/tests.yml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,9 @@ jobs:
1313
- name: "Latest Python 3.x"
1414
os: ubuntu-latest
1515
python-version: 3.x
16-
- name: "OS X Python 3.9"
16+
- name: "OS X Python 3.10"
1717
os: macos-latest
18-
python-version: 3.9
18+
python-version: 3.10
1919
- name: "Windows Python 3.12"
2020
os: windows-latest
2121
python-version: 3.12

camb/baseconfig.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -318,7 +318,7 @@ class AllocatableArrayDouble(_AllocatableArray):
318318
AllocatableArrayDouble._set_allocatable_1D_array.argtypes = [POINTER(AllocatableArrayDouble), numpy_1d, POINTER(c_int)]
319319

320320

321-
def fortran_array(c_pointer, shape, dtype=np.float64, order='F', own_data=True):
321+
def fortran_array(c_pointer, shape, dtype: type =np.float64, order='F', own_data=True):
322322
if not hasattr(shape, '__len__'):
323323
shape = np.atleast_1d(shape)
324324
arr_size = np.prod(shape[:]) * np.dtype(dtype).itemsize
@@ -640,7 +640,7 @@ def __reduce__(self):
640640

641641
def __getstate__(self) -> dict:
642642
state = {}
643-
for field_name, field_type in self.get_all_fields():
643+
for field_name, _ in self.get_all_fields():
644644
obj = getattr(self, field_name)
645645
if isinstance(obj, (ctypes.Array, np.ndarray, _ArrayOfAllocatable)):
646646
state[field_name] = list(obj[:len(obj)])
@@ -685,6 +685,12 @@ class F2003Class(CAMB_Structure):
685685

686686
__slots__ = ()
687687

688+
# _fields_ store ctypes fields, but here overridden
689+
_fields_: list[tuple[str, type] | tuple[str, type, str]]
690+
691+
# _methods_ for calling fortran functions name, arguments and optional return value
692+
_methods_: list[tuple[str, list, type] | tuple[str, list]]
693+
688694
# pointer to fortran class; generated once per instance using _fortran_selfpointer_function then replaced with
689695
# the actual value
690696
fortran_self = _FortranSelf()

camb/results.py

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -90,8 +90,8 @@ class MatterTransferData:
9090

9191
nq: int
9292
q: np.ndarray
93-
sigma_8: np.ndarray
94-
sigma2_vdelta_8: np.ndarray
93+
sigma_8: np.ndarray | None
94+
sigma2_vdelta_8: np.ndarray | None
9595
transfer_data: np.ndarray
9696

9797
def transfer_z(self, name, z_index=0):
@@ -372,8 +372,7 @@ def _CMB_unit(self, CMB_unit):
372372

373373
def _scale_cls(self, cls, CMB_unit=None, raw_cl=False, lens_potential=False):
374374
if raw_cl:
375-
ls = np.arange(1, cls.shape[0])[..., np.newaxis]
376-
ls = np.float64(ls * (ls + 1))
375+
ls = np.arange(1, cls.shape[0], dtype=np.float64)[..., np.newaxis]
377376
if lens_potential:
378377
cls[1:, 0] /= ls[:, 0] ** 2 / (2 * np.pi)
379378
cls[1:, 1:] /= ls ** (3. / 2) / (2 * np.pi)
@@ -739,6 +738,8 @@ def get_linear_matter_power_spectrum(self, var1=None, var2=None, hubble_units=Tr
739738
num_k = c_int(0)
740739
CAMBdata_mattertransferks(byref(self), byref(num_k), np.array([]))
741740
nk = num_k.value
741+
if not nk:
742+
raise CAMBError('No k values available for matter power spectrum')
742743

743744
ks = np.empty(nk, dtype=np.float64)
744745
CAMBdata_mattertransferks(byref(self), byref(num_k), ks)
@@ -754,9 +755,9 @@ def get_linear_matter_power_spectrum(self, var1=None, var2=None, hubble_units=Tr
754755
PK = np.empty((nz, nk))
755756
if nonlinear:
756757
CAMBdata_GetNonLinearMatterPower(byref(self), PK, byref(var1), byref(var2), byref(hubble_units))
757-
config.check_global_error('get_[non]linear_matter_power_spectrum')
758758
else:
759759
CAMBdata_GetLinearMatterPower(byref(self), PK, byref(var1), byref(var2), byref(hubble_units))
760+
config.check_global_error('get_[non]linear_matter_power_spectrum')
760761

761762
z = self.Params.Transfer.PK_redshifts[:nz]
762763
z.reverse()
@@ -945,6 +946,10 @@ def get_matter_power_interpolator(self, nonlinear=True, var1=None, var2=None, hu
945946
class PKInterpolator(RectBivariateSpline):
946947
islog: bool
947948
logsign: int
949+
kmin : float
950+
kmax : float
951+
zmin : float
952+
zmax : float
948953

949954
def P(self, z, kh, grid=None):
950955
if grid is None:
@@ -1395,7 +1400,7 @@ def angular_diameter_distance2(self, z1, z2):
13951400
else:
13961401
return self.f_AngularDiameterDistance2(byref(c_double(z1)), byref(c_double(z2)))
13971402

1398-
def comoving_radial_distance(self, z, tol=1e-4):
1403+
def comoving_radial_distance(self, z: float, tol=1e-4):
13991404
"""
14001405
Get comoving radial distance from us to redshift z in Mpc. This is efficient for arrays.
14011406

camb/tests/camb_test.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')))
1212
import camb
1313
from camb import model, correlations, bbn, dark_energy, initialpower
14-
from camb.baseconfig import CAMBParamRangeError, CAMBValueError
14+
from camb.baseconfig import CAMBParamRangeError, CAMBValueError, CAMBError
1515

1616
fast = 'ci fast' in os.getenv("GITHUB_ACTIONS", '')
1717

@@ -250,6 +250,15 @@ def testBackground(self):
250250
self.assertAlmostEqual(d, data.conformal_time_a1_a2(0, 1))
251251
self.assertAlmostEqual(d, sum(data.conformal_time_a1_a2([0, 0.5], [0.5, 1])))
252252

253+
def testErrors(self):
254+
redshifts = np.logspace(-1, np.log10(1089))
255+
pars = camb.set_params(H0=67.5, ombh2=0.022, omch2=0.122, As=2e-9, ns=0.95,
256+
redshifts=redshifts, kmax=0.1)
257+
258+
results = camb.get_background(pars)
259+
with self.assertRaises(CAMBError):
260+
results.get_matter_power_interpolator()
261+
253262
def testEvolution(self):
254263
redshifts = [0.4, 31.5]
255264
pars = camb.set_params(H0=67.5, ombh2=0.022, omch2=0.122, As=2e-9, ns=0.95,

fortran/camb_python.f90

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -307,6 +307,11 @@ subroutine CAMBdata_GetMatterTransferks(State, nk, ks)
307307
real(dl) ks(nk)
308308

309309
if (nk/=0) then
310+
if (.not. allocated(State%MT%TransferData)) then
311+
global_error_flag = error_allocation
312+
global_error_message = 'TransferData not allocated: make sure transfer functions computed'
313+
return
314+
end if
310315
ks = State%MT%TransferData(Transfer_kh,:,1) * (State%CP%H0/100)
311316
end if
312317
nk = State%MT%num_q_trans

fortran/config.f90

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ module config
6060
integer, parameter :: error_darkenergy=6
6161
integer, parameter :: error_ini=7
6262
integer, parameter :: error_nonlinear=8
63+
integer, parameter :: error_allocation=9
6364

6465
contains
6566

pyproject.toml

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
[build-system]
2-
requires = ["setuptools", "packaging", "wheel"]
2+
requires = ["setuptools>=77", "packaging>=24", "wheel"]
33
build-backend = "setuptools.build_meta"
44

55
[project]
@@ -13,21 +13,20 @@ readme = "docs/README_pypi.rst"
1313
license = "LicenseRef-LGPLv3-arxiv"
1414
license-files = ["LICENCE.txt"]
1515
dynamic = ["version"]
16-
requires-python = ">=3.9.0"
16+
requires-python = ">=3.10.0"
1717
classifiers = [
1818
"Development Status :: 5 - Production/Stable",
1919
"Operating System :: OS Independent",
2020
"Environment :: Console",
2121
"Intended Audience :: Science/Research",
2222
"Topic :: Scientific/Engineering :: Astronomy",
23-
"Programming Language :: Python :: 3.9",
2423
"Programming Language :: Python :: 3.10",
2524
"Programming Language :: Python :: 3.11",
2625
"Programming Language :: Python :: 3.12",
2726
"Programming Language :: Python :: 3.13"
2827
]
2928
dependencies = [
30-
"numpy", "scipy>=1.0", "sympy>=1.0", "packaging"
29+
"numpy", "scipy>=1.0", "sympy>=1.0", "packaging>=24"
3130
]
3231

3332
[project.optional-dependencies]

requirements.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
numpy
22
sympy>=1.0
33
scipy>=1.0
4-
packaging
4+
packaging>=24

0 commit comments

Comments
 (0)