Skip to content

Commit

Permalink
926 Add utility to fix random seed locally
Browse files Browse the repository at this point in the history
#926

[author: gonzaponte]

This is useful for some tests.

[reviewer: jahernando]

Approved
  • Loading branch information
jahernando authored and carhc committed Dec 27, 2024
2 parents 703865a + b871042 commit a15daa4
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
11 changes: 11 additions & 0 deletions invisible_cities/core/core_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
This module includes utility functions.
"""
import time
from contextlib import contextmanager

import numpy as np

Expand Down Expand Up @@ -345,3 +346,13 @@ def find_nearest(array : np.ndarray,
"""
idx = (np.abs(array - value)).argmin()
return array[idx]


@contextmanager
def fix_random_seed(seed):
state = np.random.get_state()
np.random.seed(seed)
try:
yield
finally:
np.random.set_state(state)
26 changes: 26 additions & 0 deletions invisible_cities/core/core_functions_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -385,3 +385,29 @@ def test_find_nearest(x, value):

idx = np.argwhere(dmin==diff)[0]
assert x[idx] == nearest


@mark.parametrize( "seed expected".split()
, ( ( 1, 0.4170220047025740)
, ( 11, 0.1802696888767692)
, (111, 0.6121701756176187)))
def test_fix_random_seed_expected(seed, expected):
with core.fix_random_seed(seed):
got = np.random.rand()
assert np.isclose(got, expected)


def test_fix_random_seed_resets():
seed = 123456789

value0 = np.random.rand()
with core.fix_random_seed(seed): value1 = np.random.rand()
value2 = np.random.rand()
with core.fix_random_seed(seed): value3 = np.random.rand()

assert not np.isclose(value0, value1)
assert not np.isclose(value0, value2)
assert not np.isclose(value0, value3)
assert not np.isclose(value1, value2)
assert np.isclose(value1, value3)
assert not np.isclose(value2, value3)

0 comments on commit a15daa4

Please sign in to comment.