def test_skope_rules_error(): """Test that it gives proper exception on deficient input.""" X = iris.data y = iris.target y = (y != 0) # Test max_samples assert_raises(ValueError, SkopeRulesClassifier(max_samples=-1).fit, X, y) assert_raises(ValueError, SkopeRulesClassifier(max_samples=0.0).fit, X, y) assert_raises(ValueError, SkopeRulesClassifier(max_samples=2.0).fit, X, y) # explicitly setting max_samples > n_samples should result in a warning. assert_warns(UserWarning, SkopeRulesClassifier(max_samples=1000).fit, X, y) assert_no_warnings(SkopeRulesClassifier(max_samples=np.int64(2)).fit, X, y) assert_raises(ValueError, SkopeRulesClassifier(max_samples='foobar').fit, X, y) assert_raises(ValueError, SkopeRulesClassifier(max_samples=1.5).fit, X, y) assert_raises(ValueError, SkopeRulesClassifier(max_depth_duplication=1.5).fit, X, y) assert_raises(ValueError, SkopeRulesClassifier().fit(X, y).predict, X[:, 1:]) assert_raises(ValueError, SkopeRulesClassifier().fit(X, y).decision_function, X[:, 1:]) assert_raises(ValueError, SkopeRulesClassifier().fit(X, y).rules_vote, X[:, 1:]) assert_raises(ValueError, SkopeRulesClassifier().fit(X, y).score_top_rules, X[:, 1:])
def test_cosmology_output(): """ Check that status messages and other output from Cosmology() object works correctly. """ # Create test cosmology object cosmo = ccl.Cosmology(Omega_c=0.25, Omega_b=0.05, h=0.7, A_s=2.1e-9, n_s=0.96) # Return and print status messages assert_no_warnings(cosmo.status) assert_no_warnings(print, cosmo) # Test status methods for different precomputable quantities assert_(cosmo.has_distances() is False) assert_(cosmo.has_growth() is False) assert_(cosmo.has_power() is False) assert_(cosmo.has_sigma() is False) # Check that quantities can be precomputed assert_no_warnings(cosmo.compute_distances) assert_no_warnings(cosmo.compute_growth) assert_no_warnings(cosmo.compute_power) assert_(cosmo.has_distances() is True) assert_(cosmo.has_growth() is True) assert_(cosmo.has_power() is True)
def test_parameters_mgrowth(): """ Check that valid modified growth inputs are allowed, and invalid ones are rejected. """ zarr = np.linspace(0., 1., 15) dfarr = 0.1 * np.ones(15) f_func = lambda z: 0.1 * z # Valid constructions for omega_g in [None, 0.0, 0.1]: assert_no_warnings( ccl.Cosmology, Omega_c=0.25, Omega_b=0.05, h=0.7, A_s=2.1e-9, n_s=0.96, z_mg=zarr, df_mg=dfarr, Omega_g=omega_g) assert_no_warnings( ccl.Cosmology, Omega_c=0.25, Omega_b=0.05, h=0.7, A_s=2.1e-9, n_s=0.96, z_mg=[0., 0.1, 0.2], df_mg=[0.1, 0.1, 0.1], Omega_g=omega_g) # Invalid constructions assert_raises( ValueError, ccl.Cosmology, Omega_c=0.25, Omega_b=0.05, h=0.7, A_s=2.1e-9, n_s=0.96, z_mg=zarr, Omega_g=omega_g) assert_raises( ValueError, ccl.Cosmology, Omega_c=0.25, Omega_b=0.05, h=0.7, A_s=2.1e-9, n_s=0.96, df_mg=dfarr, Omega_g=omega_g) assert_raises( ValueError, ccl.Cosmology, Omega_c=0.25, Omega_b=0.05, h=0.7, A_s=2.1e-9, n_s=0.96, z_mg=None, df_mg=dfarr, Omega_g=omega_g) assert_raises( ValueError, ccl.Cosmology, Omega_c=0.25, Omega_b=0.05, h=0.7, A_s=2.1e-9, n_s=0.96, z_mg=zarr, df_mg=0.1, Omega_g=omega_g) assert_raises( ValueError, ccl.Cosmology, Omega_c=0.25, Omega_b=0.05, h=0.7, A_s=2.1e-9, n_s=0.96, z_mg=zarr, df_mg=f_func, Omega_g=omega_g) # Mis-matched array sizes and dimensionality assert_raises( ValueError, ccl.Cosmology, Omega_c=0.25, Omega_b=0.05, h=0.7, A_s=2.1e-9, n_s=0.96, z_mg=zarr, df_mg=dfarr[1:], Omega_g=omega_g) assert_raises( ValueError, ccl.Cosmology, Omega_c=0.25, Omega_b=0.05, h=0.7, A_s=2.1e-9, n_s=0.96, z_mg=zarr, df_mg=np.column_stack((dfarr, dfarr)), Omega_g=omega_g)
def test_madelung_random(): """ random """ cell = diag((1., 1., 1.)) r = array([[0., 0., 0.], [.234, .978789, .05]]) invcell = inv(cell).T i = 0 q = array([1, -1]) area = abs(det(cell)) assert_no_warnings(ewaldsum.potential, i, r, q, cell, area, invcell)
def test_a_star1(): maze = np.random.random((25, 25)) # generate random maze for ii in range(0, np.size(maze, axis=0)): for jj in range(0, np.size(maze, axis=1)): if maze[ii][jj] < 0.05: maze[ii][jj] = 1 else: maze[ii][jj] = 0 start = (0, 0) end = (24, 24) # graphs.a_star_search(maze, start, end) test.assert_no_warnings(graphs.a_star_search, maze, start, end)
def test_parameters_missing(): """ Check that errors are raised when compulsory parameters are missing, but not when non-compulsory ones are. """ # Make sure that compulsory parameters are compulsory assert_raises(ValueError, ccl.Parameters, 0.25) assert_raises(ValueError, ccl.Parameters, 0.25, 0.05) assert_raises(ValueError, ccl.Parameters, 0.25, 0.05, 0.7) assert_raises(ValueError, ccl.Parameters, 0.25, 0.05, 0.7, 2.1e-9) assert_raises(ValueError, ccl.Parameters, Omega_c=0.25) assert_raises(ValueError, ccl.Parameters, 0.25, 0.05, 0.7, 2.1e-9, 0.96, Omega_k=None) assert_raises(ValueError, ccl.Parameters, 0.25, 0.05, 0.7, 2.1e-9, 0.96, w0=None) assert_raises(ValueError, ccl.Parameters, 0.25, 0.05, 0.7, 2.1e-9, 0.96, wa=None) assert_raises(ValueError, ccl.Parameters, 0.25, 0.05, 0.7, 2.1e-9, 0.96, N_nu_rel=None) assert_raises(ValueError, ccl.Parameters, 0.25, 0.05, 0.7, 2.1e-9, 0.96, N_nu_mass=None) assert_raises(ValueError, ccl.Parameters, 0.25, 0.05, 0.7, 2.1e-9, 0.96, m_nu=None) # Check that a single missing compulsory parameter is noticed assert_raises(ValueError, ccl.Parameters, Omega_c=0.25, Omega_b=0.05, h=0.7, A_s=2.1e-9) assert_raises(ValueError, ccl.Parameters, Omega_c=0.25, Omega_b=0.05, h=0.7, n_s=0.96) assert_raises(ValueError, ccl.Parameters, Omega_c=0.25, Omega_b=0.05, A_s=2.1e-9, n_s=0.96) assert_raises(ValueError, ccl.Parameters, Omega_c=0.25, h=0.7, A_s=2.1e-9, n_s=0.96) assert_raises(ValueError, ccl.Parameters, Omega_b=0.05, h=0.7, A_s=2.1e-9, n_s=0.96) # Make sure that optional parameters are optional assert_no_warnings(ccl.Parameters, 0.25, 0.05, 0.7, 2.1e-9, 0.96, z_mg=None, df_mg=None) assert_no_warnings(ccl.Parameters, 0.25, 0.05, 0.7, 2.1e-9, 0.96, z_mg=None) assert_no_warnings(ccl.Parameters, 0.25, 0.05, 0.7, 2.1e-9, 0.96, df_mg=None) assert_no_warnings(ccl.Parameters, Omega_c=0.25, Omega_b=0.05, h=0.7, A_s=2.1e-9, n_s=0.96, z_mg=None, df_mg=None) # Check that Cosmology() object can instantiate a Parameters() object itself assert_no_warnings(ccl.Cosmology, Omega_c=0.25, Omega_b=0.05, h=0.7, A_s=2.1e-9, n_s=0.96)
def test_empty(method): def fun(t, y): return np.zeros((0,)) y0 = np.zeros((0,)) sol = assert_no_warnings(solve_ivp, fun, [0, 10], y0, method=method, dense_output=True) assert_equal(sol.sol(10), np.zeros((0,))) assert_equal(sol.sol([1, 2, 3]), np.zeros((0, 3))) sol = assert_no_warnings(solve_ivp, fun, [0, np.inf], y0, method=method, dense_output=True) assert_equal(sol.sol(10), np.zeros((0,))) assert_equal(sol.sol([1, 2, 3]), np.zeros((0, 3)))
def test_empty(): def fun(t, y): return np.zeros((0,)) y0 = np.zeros((0,)) for method in ['RK23', 'RK45', 'Radau', 'BDF']: sol = assert_no_warnings(solve_ivp, fun, [0, 10], y0, method=method, dense_output=True) assert_equal(sol.sol(10), np.zeros((0,))) for method in ['RK23', 'RK45', 'Radau', 'BDF']: sol = assert_no_warnings(solve_ivp, fun, [0, np.inf], y0, method=method, dense_output=True) assert_equal(sol.sol(10), np.zeros((0,)))
def test_gh12696(): # Test that optimize doesn't throw warning gh-12696 with assert_no_warnings(): optimize.fminbound(lambda x: np.array([x**2]), -np.pi, np.pi, disp=False)
def test_empty(): def fun(t, y): return np.zeros((0,)) y0 = np.zeros((0,)) for method in ['RK23', 'RK45', 'Radau', 'BDF', 'LSODA']: sol = assert_no_warnings(solve_ivp, fun, [0, 10], y0, method=method, dense_output=True) assert_equal(sol.sol(10), np.zeros((0,))) assert_equal(sol.sol([1, 2, 3]), np.zeros((0, 3))) for method in ['RK23', 'RK45', 'Radau', 'BDF', 'LSODA']: sol = assert_no_warnings(solve_ivp, fun, [0, np.inf], y0, method=method, dense_output=True) assert_equal(sol.sol(10), np.zeros((0,))) assert_equal(sol.sol([1, 2, 3]), np.zeros((0, 3)))
def test_safe_casting(self): # In old versions of numpy, in-place operations used the 'unsafe' # casting rules. In versions >= 1.10, 'same_kind' is the # default and an exception is raised instead of a warning. # when 'same_kind' is not satisfied. a = np.array([1, 2, 3], dtype=int) # Non-in-place addition is fine assert_array_equal(assert_no_warnings(np.add, a, 1.1), [2.1, 3.1, 4.1]) assert_raises(TypeError, np.add, a, 1.1, out=a) def add_inplace(a, b): a += b assert_raises(TypeError, add_inplace, a, 1.1) # Make sure that explicitly overriding the exception is allowed: assert_no_warnings(np.add, a, 1.1, out=a, casting="unsafe") assert_array_equal(a, [2, 3, 4])
def test_open_view_warning(): # opening many views (without deleting the SurfaceView objects) # should raise a warning about memory usage pytest.warns(UserWarning, _open_views) assert_no_warnings(_open_one_view) reporting.set_max_img_views_before_warning(15) assert_no_warnings(_open_views) reporting.set_max_img_views_before_warning(-1) assert_no_warnings(_open_views) reporting.set_max_img_views_before_warning(None) assert_no_warnings(_open_views) reporting.set_max_img_views_before_warning(6) pytest.warns(UserWarning, _open_views)
def test_overwrite_warns_on_best(): """ There can only be a single callback for each event point, so inserting two (or more) should warn the previous callback for ON_BEST is overwritten. """ mixin = CallbackMixin() with assert_no_warnings(): # first insert is fine.. mixin.on_best(dummy_callback) with assert_warns(OverwriteWarning): # .. but second insert should warn mixin.on_best(dummy_callback)
def test_3D(): grey_img = np.zeros((10, 10)) rgb_img = np.zeros((10, 10, 3)) three_d_img = np.zeros((10, 10, 10)) with assert_no_warnings(): felzenszwalb(grey_img, multichannel=True) felzenszwalb(grey_img, multichannel=False) felzenszwalb(rgb_img, multichannel=True) with assert_warns(RuntimeWarning): felzenszwalb(three_d_img, multichannel=True) with pytest.raises(ValueError): felzenszwalb(rgb_img, multichannel=False) felzenszwalb(three_d_img, multichannel=False)
def test_overwrite_warns_on_best(): """ There can only be a single callback for each event point, so inserting two (or more) should warn the previous callback for ``on_best`` is overwritten. """ alns = get_alns_instance([lambda state, rnd: Zero()], [lambda state, rnd: Zero()]) with assert_no_warnings(): # first insert is fine.. alns.on_best(dummy_callback) with assert_warns(OverwriteWarning): # .. but second insert should warn alns.on_best(dummy_callback)
def test_allnans(self): for f, tgt_value in zip(self.nanfuncs, [0, 1]): # Unlike other nan-functions, sum/prod/cumsum/cumprod don't warn on all nan input with assert_no_warnings(): res = f([np.nan] * 3, axis=None) tgt = tgt_value * np.ones((3)) assert_(np.array_equal(res, tgt), 'result is not %s * np.ones((3))' % (tgt_value)) # Check scalar res = f(np.nan) tgt = tgt_value * np.ones((1)) assert_(np.array_equal(res, tgt), 'result is not %s * np.ones((1))' % (tgt_value)) # Check there is no warning for not all-nan f([0] * 3, axis=None)
def test_allnans(self): for f, tgt_value in zip(self.nanfuncs, [0, 1]): # Unlike other nan-functions, sum/prod/cumsum/cumprod don't warn on all nan input with assert_no_warnings(): res = f([np.nan]*3, axis=None) tgt = tgt_value*np.ones((3)) assert_(np.array_equal(res, tgt), 'result is not %s * np.ones((3))' % (tgt_value)) # Check scalar res = f(np.nan) tgt = tgt_value*np.ones((1)) assert_(np.array_equal(res, tgt), 'result is not %s * np.ones((1))' % (tgt_value)) # Check there is no warning for not all-nan f([0]*3, axis=None)
def test_warn(self): def f(): warnings.warn("yo") return 3 before_filters = sys.modules["warnings"].filters[:] assert_equal(assert_warns(UserWarning, f), 3) after_filters = sys.modules["warnings"].filters assert_raises(AssertionError, assert_no_warnings, f) assert_equal(assert_no_warnings(lambda x: x, 1), 1) # Check that the warnings state is unchanged assert_equal(before_filters, after_filters, "assert_warns does not preserver warnings state")
def test_warn(self): def f(): warnings.warn("yo") return 3 before_filters = sys.modules['warnings'].filters[:] assert_equal(assert_warns(UserWarning, f), 3) after_filters = sys.modules['warnings'].filters assert_raises(AssertionError, assert_no_warnings, f) assert_equal(assert_no_warnings(lambda x: x, 1), 1) # Check that the warnings state is unchanged assert_equal(before_filters, after_filters, "assert_warns does not preserver warnings state")
def test_pickle_bmsm(self): msm = factory.bmsm_double_well(nsamples=10) msm_pickle = pickle.dumps(msm) assert b"version" in msm_pickle from numpy.testing import assert_no_warnings msm_restored = assert_no_warnings(pickle.loads, msm_pickle) # test that we can predict with the restored decision tree classifier model = msm.fetch_model() model_restored = msm_restored.fetch_model() np.testing.assert_equal(model_restored.prior.transition_matrix, model.prior.transition_matrix) assert model_restored.prior.lagtime == model_restored.prior.lagtime
def test_parameters_missing(): """ Check that errors are raised when compulsory parameters are missing, but not when non-compulsory ones are. """ assert_raises(ValueError, ccl.Cosmology, Omega_c=0.25) # Check that a single missing compulsory parameter is noticed assert_raises(ValueError, ccl.Cosmology, Omega_c=0.25, Omega_b=0.05, h=0.7, A_s=2.1e-9) assert_raises(ValueError, ccl.Cosmology, Omega_c=0.25, Omega_b=0.05, h=0.7, n_s=0.96) assert_raises(ValueError, ccl.Cosmology, Omega_c=0.25, Omega_b=0.05, A_s=2.1e-9, n_s=0.96) assert_raises(ValueError, ccl.Cosmology, Omega_c=0.25, h=0.7, A_s=2.1e-9, n_s=0.96) assert_raises(ValueError, ccl.Cosmology, Omega_b=0.05, h=0.7, A_s=2.1e-9, n_s=0.96) # Make sure that compulsory parameters are compulsory assert_raises( ValueError, ccl.Cosmology, Omega_c=0.25, Omega_b=0.05, h=0.7, A_s=2.1e-9, n_s=0.96, Omega_k=None) assert_raises( ValueError, ccl.Cosmology, Omega_c=0.25, Omega_b=0.05, h=0.7, A_s=2.1e-9, n_s=0.96, w0=None) assert_raises( ValueError, ccl.Cosmology, Omega_c=0.25, Omega_b=0.05, h=0.7, A_s=2.1e-9, n_s=0.96, wa=None) # Check that sigma8 vs A_s is handled ok. assert_raises( ValueError, ccl.Cosmology, Omega_c=0.25, Omega_b=0.05, h=0.7, n_s=0.8, A_s=2.1e-9, sigma8=0.7) assert_raises( ValueError, ccl.Cosmology, Omega_c=0.25, Omega_b=0.05, h=0.7, n_s=0.8) # Make sure that optional parameters are optional assert_no_warnings( ccl.Cosmology, Omega_c=0.25, Omega_b=0.05, h=0.7, A_s=2.1e-9, n_s=0.96, z_mg=None, df_mg=None) assert_no_warnings( ccl.Cosmology, Omega_c=0.25, Omega_b=0.05, h=0.7, A_s=2.1e-9, n_s=0.96, z_mg=None) assert_no_warnings( ccl.Cosmology, Omega_c=0.25, Omega_b=0.05, h=0.7, A_s=2.1e-9, n_s=0.96, df_mg=None)
def test_parameters_mgrowth(): """ Check that valid modified growth inputs are allowed, and invalid ones are rejected. """ zarr = np.linspace(0., 1., 15) dfarr = 0.1 * np.ones(15) f_func = lambda z: 0.1 * z # Valid constructions assert_no_warnings(ccl.Parameters, 0.25, 0.05, 0.7, 2.1e-9, 0.96, z_mg=zarr, df_mg=dfarr) assert_no_warnings(ccl.Parameters, 0.25, 0.05, 0.7, 2.1e-9, 0.96, df_mg=dfarr, z_mg=zarr) assert_no_warnings(ccl.Parameters, 0.25, 0.05, 0.7, 2.1e-9, 0.96, w0=-1., z_mg=zarr, df_mg=dfarr) assert_no_warnings(ccl.Parameters, 0.25, 0.05, 0.7, 2.1e-9, 0.96, w0=-1., z_mg=[0., 0.1, 0.2], df_mg=[0.1, 0.1, 0.1]) # Invalid constructions assert_raises(ValueError, ccl.Parameters, 0.25, 0.05, 0.7, 2.1e-9, 0.96, z_mg=zarr) assert_raises(ValueError, ccl.Parameters, 0.25, 0.05, 0.7, 2.1e-9, 0.96, df_mg=dfarr) assert_raises(ValueError, ccl.Parameters, 0.25, 0.05, 0.7, 2.1e-9, 0.96, z_mg=None, df_mg=dfarr) assert_raises(AssertionError, ccl.Parameters, 0.25, 0.05, 0.7, 2.1e-9, 0.96, z_mg=zarr, df_mg=0.1) assert_raises(AssertionError, ccl.Parameters, 0.25, 0.05, 0.7, 2.1e-9, 0.96, z_mg=zarr, df_mg=f_func) # Mis-matched array sizes and dimensionality assert_raises(AssertionError, ccl.Parameters, 0.25, 0.05, 0.7, 2.1e-9, 0.96, z_mg=zarr, df_mg=dfarr[1:]) assert_raises(AssertionError, ccl.Parameters, 0.25, 0.05, 0.7, 2.1e-9, 0.96, z_mg=zarr, df_mg=np.column_stack((dfarr, dfarr)) )
def test_add_operator_same_name_warns_per_type(): """ Adding an operator with the same name as an already added operator (of the same type) should warn that the previous operator will be overwritten. """ alns = ALNS() with assert_no_warnings(): # The same name is allowed for different types of operators. alns.add_destroy_operator(lambda state, rnd: None, "test") alns.add_repair_operator(lambda state, rnd: None, "test") with assert_warns(OverwriteWarning): # Already exists as a destroy operator. alns.add_destroy_operator(lambda state, rnd: None, "test") with assert_warns(OverwriteWarning): # Already exists as a repair operator. alns.add_repair_operator(lambda state, rnd: None, "test")
def test_pipeline_df__init() -> None: """ Test the various init parameters of the pipeline. """ assert_raises(TypeError, PipelineDF) # Check that we can't instantiate pipelines with objects without fit # method assert_raises_regex( TypeError, "Last step of Pipeline should implement fit " "or be the string 'passthrough'" ".*NoFit.*", PipelineDF, [("clf", NoFit())], ) # Smoke test with only an estimator clf = NoTransformerDF() # step names step_svc = "svc" step_anova = "anova" pipe = PipelineDF([(step_svc, clf)]) assert pipe.get_params(deep=True) == dict(svc__a=None, svc__b=None, svc=clf, **pipe.get_params(deep=False)) # Check that params are set pipe.set_params(svc__a=0.1) assert clf.a == 0.1 assert clf.b is None # Smoke test the repr: repr(pipe) # Test with two objects clf = SVCDF() filter1 = SelectKBestDF(f_classif) pipe = PipelineDF([(step_anova, filter1), (step_svc, clf)]) # Check that estimators are not cloned on pipeline construction assert pipe.named_steps[step_anova] is filter1 assert pipe.named_steps[step_svc] is clf # Check that params are set pipe.set_params(svc__C=0.1) assert clf.C == 0.1 # Smoke test the repr: repr(pipe) # Check that params are not set when naming them wrong assert_raises(ValueError, pipe.set_params, anova__C=0.1) # Test clone pipe2 = assert_no_warnings(clone, pipe) assert not pipe.named_steps[step_svc] is pipe2.named_steps[step_svc] # Check that apart from estimators, the parameters are the same def _get_deep_params(_pipe: PipelineDF) -> Mapping[str, Any]: top_level_params = { *_pipe.get_params(deep=False), step_svc, step_anova } return { k: v for k, v in _pipe.get_params(deep=True).items() if k not in top_level_params } params = _get_deep_params(pipe) params2 = _get_deep_params(pipe2) assert params == params2
def no_warnings(): with assert_no_warnings(): warnings.warn("yo")
def test_open_view_warning(): # opening many views (without deleting the SurfaceView objects) # should raise a warning about memory usage assert_warns(UserWarning, _open_views) assert_no_warnings(_open_one_view)
def test_avg_with_2d_image(): img = np.random.randint(0, 255, (10, 10), dtype=np.uint8) labels = np.zeros((10, 10), dtype=np.int64) labels[1:3, 1:3] = 1 labels[6:9, 6:9] = 2 assert_no_warnings(label2rgb, labels, image=img, bg_label=0, kind='avg')
def test_full_default_dtype(self): assert_warns(FutureWarning, np.full, 1, 1) assert_warns(FutureWarning, np.full, 1, None) assert_no_warnings(np.full, 1, 1, float)
def check_cls_nu(cosmo): """ Check that cls functions can be run. """ # Number density input z = np.linspace(0., 1., 200) n = np.exp(-((z-0.5)/0.1)**2) # Bias input b = np.sqrt(1. + z) # ell range input ell_scl = 4 ell_lst = [2, 3, 4, 5, 6, 7, 8, 9] ell_arr = np.arange(2, 10) # Check if power spectrum type is valid for CMB cmb_ok = True if cosmo.configuration.matter_power_spectrum_method \ == ccl.core.matter_power_spectrum_types['emu']: cmb_ok = False # ClTracer test objects lens1 = ccl.ClTracerLensing(cosmo, False, n=n, z=z) lens2 = ccl.ClTracerLensing(cosmo, True, n=(z,n), bias_ia=(z,n), f_red=(z,n)) nc1 = ccl.ClTracerNumberCounts(cosmo, False, False, n=(z,n), bias=(z,b)) # Check that for massive neutrinos including rsd raises an error (not yet implemented) assert_raises(RuntimeError, ccl.ClTracerNumberCounts, cosmo, True, False, n=(z,n), bias=(z,b)) cmbl=ccl.ClTracerCMBLensing(cosmo,1100.) # Check valid ell input is accepted assert_( all_finite(ccl.angular_cl(cosmo, lens1, lens1, ell_scl)) ) assert_( all_finite(ccl.angular_cl(cosmo, lens1, lens1, ell_lst)) ) assert_( all_finite(ccl.angular_cl(cosmo, lens1, lens1, ell_arr)) ) assert_( all_finite(ccl.angular_cl(cosmo, nc1, nc1, ell_scl)) ) assert_( all_finite(ccl.angular_cl(cosmo, nc1, nc1, ell_lst)) ) assert_( all_finite(ccl.angular_cl(cosmo, nc1, nc1, ell_arr)) ) if cmb_ok: assert_( all_finite(ccl.angular_cl(cosmo, cmbl, cmbl, ell_arr)) ) # Check various cross-correlation combinations assert_( all_finite(ccl.angular_cl(cosmo, lens1, lens2, ell_arr)) ) assert_( all_finite(ccl.angular_cl(cosmo, lens1, nc1, ell_arr)) ) if cmb_ok: assert_( all_finite(ccl.angular_cl(cosmo, lens1, cmbl, ell_arr)) ) assert_( all_finite(ccl.angular_cl(cosmo, lens2, nc1, ell_arr)) ) if cmb_ok: assert_( all_finite(ccl.angular_cl(cosmo, lens2, cmbl, ell_arr)) ) if cmb_ok: assert_( all_finite(ccl.angular_cl(cosmo, nc1, cmbl, ell_arr)) ) # Check that reversing order of ClTracer inputs works assert_( all_finite(ccl.angular_cl(cosmo, nc1, lens1, ell_arr)) ) assert_( all_finite(ccl.angular_cl(cosmo, nc1, lens2, ell_arr)) ) # Check get_internal_function() a_scl = 0.5 a_lst = [0.2, 0.4, 0.6, 0.8, 1.] a_arr = np.linspace(0.2, 1., 5) assert_( all_finite(nc1.get_internal_function(cosmo, 'dndz', a_scl)) ) assert_( all_finite(nc1.get_internal_function(cosmo, 'dndz', a_lst)) ) assert_( all_finite(nc1.get_internal_function(cosmo, 'dndz', a_arr)) ) # Check that invalid options raise errors assert_raises(KeyError, nc1.get_internal_function, cosmo, 'x', a_arr) assert_raises(ValueError, ccl.ClTracerNumberCounts, cosmo, True, True, n=(z,n), bias=(z,b)) assert_raises(KeyError, ccl.ClTracer, cosmo, 'x', True, True, n=(z,n), bias=(z,b)) assert_raises(ValueError, ccl.ClTracerLensing, cosmo, has_intrinsic_alignment=True, n=(z,n), bias_ia=(z,n)) assert_no_warnings(ccl.cls._cltracer_obj, nc1) assert_no_warnings(ccl.cls._cltracer_obj, nc1.cltracer) assert_raises(TypeError, ccl.cls._cltracer_obj, None)
def test_parameters_valid_input(): """ Check that valid parameter arguments are accepted. """ assert_no_warnings(ccl.Cosmology, Omega_c=0.25, Omega_b=0.05, h=0.7, A_s=2.1e-9, n_s=0.96) assert_no_warnings(ccl.Cosmology, Omega_c=0.25, Omega_b=0.05, h=0.7, A_s=2.1e-9, n_s=0.96, Omega_k=0.05) assert_no_warnings(ccl.Cosmology, Omega_c=0.25, Omega_b=0.05, h=0.7, A_s=2.1e-9, n_s=0.96, Neff=2.046) assert_no_warnings(ccl.Cosmology, Omega_c=0.25, Omega_b=0.05, h=0.7, A_s=2.1e-9, n_s=0.96, Neff=3.046, m_nu=0.06) assert_no_warnings(ccl.Cosmology, Omega_c=0.25, Omega_b=0.05, h=0.7, A_s=2.1e-9, n_s=0.96, w0=-0.9) assert_no_warnings(ccl.Cosmology, Omega_c=0.25, Omega_b=0.05, h=0.7, A_s=2.1e-9, n_s=0.96, w0=-0.9, wa=0.1) # Check that kwarg order doesn't matter assert_no_warnings(ccl.Cosmology, h=0.7, Omega_c=0.25, Omega_b=0.05, A_s=2.1e-9, n_s=0.96) # Try a set of parameters with non-zero mu0 / Sig0 assert_no_warnings(ccl.Cosmology, h=0.7, Omega_c=0.25, Omega_b=0.05, A_s=2.1e-9, n_s=0.96, mu_0=0.1, sigma_0=0.1)
def check_warn_on_small_data(): t, y, dy = _generate_data(20) model = LombScargleFast() assert_warns(UserWarning, model.score_frequency_grid, 0.8, 0.01, 40) model = LombScargleFast(silence_warnings=True) assert_no_warnings(model.score_frequency_grid, 0.8, 0.01, 40)
def test_parameters_valid_input(): """ Check that valid parameter arguments are accepted. """ assert_no_warnings(ccl.Parameters, 0.25, 0.05, 0.7, 2.1e-9, 0.96) assert_no_warnings(ccl.Parameters, Omega_c=0.25, Omega_b=0.05, h=0.7, A_s=2.1e-9, n_s=0.96) assert_no_warnings(ccl.Parameters, 0.25, 0.05, 0.7, 2.1e-9, 0.96, w0=-0.9) assert_no_warnings(ccl.Parameters, Omega_c=0.25, Omega_b=0.05, h=0.7, A_s=2.1e-9, n_s=0.96, Omega_k=0.05) assert_no_warnings(ccl.Parameters, Omega_c=0.25, Omega_b=0.05, h=0.7, A_s=2.1e-9, n_s=0.96, Neff=2.046) assert_no_warnings(ccl.Parameters, Omega_c=0.25, Omega_b=0.05, h=0.7, A_s=2.1e-9, n_s=0.96, Neff=3.046, m_nu=0.06) assert_no_warnings(ccl.Parameters, Omega_c=0.25, Omega_b=0.05, h=0.7, A_s=2.1e-9, n_s=0.96, w0=-0.9) assert_no_warnings(ccl.Parameters, 0.25, 0.05, 0.7, 2.1e-9, 0.96, w0=-0.9, wa=0.1) assert_no_warnings(ccl.Parameters, Omega_c=0.25, Omega_b=0.05, h=0.7, A_s=2.1e-9, n_s=0.96, w0=-0.9, wa=0.1) # Check that kwarg order doesn't matter assert_no_warnings(ccl.Parameters, h=0.7, Omega_c=0.25, Omega_b=0.05, A_s=2.1e-9, n_s=0.96)
def test_multivariate_normal_method(seed, method): from numpy.random import MT19937 as NPMT19937 random = ExtendedGenerator(NPMT19937(seed)) mean = (0.123456789, 10) cov = [[1, 0], [0, 1]] size = (3, 2) actual = random.multivariate_normal(mean, cov, size, method=method) desired = np.array([ [ [-1.747478062846581, 11.25613495182354], [-0.9967333370066214, 10.342002097029821], ], [ [0.7850019631242964, 11.181113712443013], [0.8901349653255224, 8.873825399642492], ], [ [0.7130260107430003, 9.551628690083056], [0.7127098726541128, 11.991709234143173], ], ]) assert_array_almost_equal(actual, desired, decimal=15) # Check for default size, was raising deprecation warning actual = random.multivariate_normal(mean, cov, method=method) desired = np.array([0.233278563284287, 9.424140804347195]) assert_array_almost_equal(actual, desired, decimal=15) # Check path with scalar size works correctly scalar = random.multivariate_normal(mean, cov, 3, method=method) tuple1d = random.multivariate_normal(mean, cov, (3, ), method=method) assert scalar.shape == tuple1d.shape == (3, 2) # Check that non symmetric covariance input raises exception when # check_valid='raises' if using default svd method. mean = [0, 0] cov = [[1, 2], [1, 2]] assert_raises(ValueError, random.multivariate_normal, mean, cov, check_valid="raise") # Check that non positive-semidefinite covariance warns with # RuntimeWarning cov = [[1, 2], [2, 1]] assert_warns(RuntimeWarning, random.multivariate_normal, mean, cov) assert_warns(RuntimeWarning, random.multivariate_normal, mean, cov, method="eigh") assert_raises(LinAlgError, random.multivariate_normal, mean, cov, method="cholesky") # and that it doesn't warn with RuntimeWarning check_valid='ignore' assert_no_warnings(random.multivariate_normal, mean, cov, check_valid="ignore") # and that it raises with RuntimeWarning check_valid='raises' assert_raises(ValueError, random.multivariate_normal, mean, cov, check_valid="raise") assert_raises( ValueError, random.multivariate_normal, mean, cov, check_valid="raise", method="eigh", ) # check degenerate samples from singular covariance matrix cov = [[1, 1], [1, 1]] if method in ("svd", "eigh"): samples = random.multivariate_normal(mean, cov, size=(3, 2), method=method) assert_array_almost_equal(samples[..., 0], samples[..., 1], decimal=6) else: assert_raises(LinAlgError, random.multivariate_normal, mean, cov, method="cholesky") cov = np.array([[1, 0.1], [0.1, 1]], dtype=np.float32) with suppress_warnings() as sup: random.multivariate_normal(mean, cov, method=method) w = sup.record(RuntimeWarning) assert len(w) == 0 mu = np.zeros(2) cov = np.eye(2) assert random.multivariate_normal(mu, cov, size=3).shape == (3, 2) assert_raises(ValueError, random.multivariate_normal, mean, cov, check_valid="other") assert_raises(ValueError, random.multivariate_normal, np.zeros((2, 1, 1)), cov) assert_raises(ValueError, random.multivariate_normal, mu, np.empty((3, 2))) assert_raises(ValueError, random.multivariate_normal, mu, np.eye(3))