|
1 | 1 | import unittest |
2 | 2 | import os |
3 | 3 |
|
| 4 | +import dill |
4 | 5 | import numpy as np |
5 | 6 | from astropy import constants |
6 | 7 | import lal |
7 | 8 | import matplotlib.pyplot as plt |
| 9 | +import h5py |
| 10 | +import json |
| 11 | +import pytest |
8 | 12 |
|
9 | 13 | import bilby |
10 | 14 | from bilby.core import utils |
@@ -412,5 +416,56 @@ def test_integral_func2_irregular_steps(self): |
412 | 416 | self.assertTrue(np.abs((np.exp(res) - self.func2int) / self.func2int) < 1e-2) |
413 | 417 |
|
414 | 418 |
|
| 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 | + |
415 | 470 | if __name__ == "__main__": |
416 | 471 | unittest.main() |
0 commit comments