Skip to content

Commit 1a808c9

Browse files
committed
TST: add tests for saving and loading numpy random generators
1 parent 9757f8a commit 1a808c9

1 file changed

Lines changed: 55 additions & 0 deletions

File tree

test/core/utils_test.py

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,14 @@
11
import unittest
22
import os
33

4+
import dill
45
import numpy as np
56
from astropy import constants
67
import lal
78
import matplotlib.pyplot as plt
9+
import h5py
10+
import json
11+
import pytest
812

913
import bilby
1014
from bilby.core import utils
@@ -412,5 +416,56 @@ def test_integral_func2_irregular_steps(self):
412416
self.assertTrue(np.abs((np.exp(res) - self.func2int) / self.func2int) < 1e-2)
413417

414418

419+
class TestSavingNumpyRandomGenerator(unittest.TestCase):
420+
421+
@pytest.fixture(autouse=True)
422+
def init_outdir(self, tmp_path):
423+
# Use pytest's tmp_path fixture to create a temporary directory
424+
self.outdir = tmp_path / "test"
425+
self.outdir.mkdir()
426+
427+
def setUp(self):
428+
self.filename = "test_random_state.npy"
429+
self.data = {
430+
"rng": np.random.default_rng(),
431+
"seed": 1234,
432+
}
433+
434+
def test_hdf5(self):
435+
with h5py.File(self.outdir / "test.h5", "w") as f:
436+
bilby.core.utils.recursively_save_dict_contents_to_group(
437+
f, "/", self.data
438+
)
439+
a = self.data["rng"].random()
440+
441+
with h5py.File(self.outdir / "test.h5", "r") as f:
442+
data = bilby.core.utils.recursively_load_dict_contents_from_group(f, "/")
443+
444+
b = data["rng"].random()
445+
self.assertEqual(a, b)
446+
447+
def test_json(self):
448+
with open(self.outdir / "test.json", 'w') as file:
449+
json.dump(self.data, file, indent=2, cls=bilby.core.utils.BilbyJsonEncoder)
450+
451+
a = self.data["rng"].random()
452+
453+
with open(self.outdir / "test.json", 'r') as file:
454+
data = json.load(file, object_hook=bilby.core.utils.decode_bilby_json)
455+
456+
b = data["rng"].random()
457+
self.assertEqual(a, b)
458+
459+
def test_pickle(self):
460+
with open(self.outdir / "test.pkl", 'wb') as file:
461+
dill.dump(self.data, file)
462+
a = self.data["rng"].random()
463+
464+
with open(self.outdir / "test.pkl", 'rb') as file:
465+
data = dill.load(file)
466+
b = data["rng"].random()
467+
self.assertEqual(a, b)
468+
469+
415470
if __name__ == "__main__":
416471
unittest.main()

0 commit comments

Comments
 (0)