Skip to content

Commit

Permalink
TST: Set seed when using basin hopping
Browse files Browse the repository at this point in the history
Basin hopping uses the global RandomState by default.  Add a fixture
to set the global state to a fixed and then restore it to its original
value after the test has completed.

xref statsmodels#4230
  • Loading branch information
bashtage committed Sep 13, 2018
1 parent 359aeed commit f5c79c8
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 3 deletions.
22 changes: 22 additions & 0 deletions statsmodels/conftest.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import numpy as np
import pytest


Expand Down Expand Up @@ -68,3 +69,24 @@ def close():

yield close
close()


@pytest.fixture()
def reset_randomstate():
"""
Fixture that set the global RandomState to the fixed seed 1
Notes
-----
Used by passing as an argument to the function that uses the global
RandomState
def test_some_plot(reset_randomstate):
<test code>
Returns the state after the test function exits
"""
state = np.random.get_state()
np.random.seed(1)
yield
np.random.set_state(state)
4 changes: 2 additions & 2 deletions statsmodels/discrete/tests/test_count_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,7 @@ def test_t(self):
t_test = self.res1.t_test(unit_matrix)
assert_allclose(self.res1.tvalues, t_test.tvalue)

def test_minimize(self):
def test_minimize(self, reset_randomstate):
# check additional optimizers using the `minimize` option
model = self.res1.model
# use the same start_params, but avoid recomputing
Expand Down Expand Up @@ -380,7 +380,7 @@ def test_fit_regularized(self):
atol=1e-1, rtol=1e-1)

# possibly slow, adds 25 seconds
def test_minimize(self):
def test_minimize(self, reset_randomstate):
# check additional optimizers using the `minimize` option
model = self.res1.model
# use the same start_params, but avoid recomputing
Expand Down
1 change: 1 addition & 0 deletions statsmodels/discrete/tests/test_discrete.py
Original file line number Diff line number Diff line change
Expand Up @@ -424,6 +424,7 @@ def setup_class(cls):
res2.probit()
cls.res2 = res2
fit = Probit(data.endog, data.exog).fit
np.random.seed(1)
cls.res1 = fit(method="basinhopping", disp=0, niter=5,
minimizer={'method' : 'L-BFGS-B', 'tol' : 1e-8})

Expand Down
2 changes: 1 addition & 1 deletion statsmodels/tsa/tests/test_holtwinters.py
Original file line number Diff line number Diff line change
Expand Up @@ -327,7 +327,7 @@ def test_invalid_start_param_length():
mod.fit(start_params=np.array([0.5]))


def test_basin_hopping():
def test_basin_hopping(reset_randomstate):
mod = ExponentialSmoothing(housing_data, trend='add')
res = mod.fit()
res2 = mod.fit(use_basinhopping=True)
Expand Down

0 comments on commit f5c79c8

Please sign in to comment.