Python numpy.testing.assert_raises() Examples

The following are 30 code examples of numpy.testing.assert_raises(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module numpy.testing , or try the search function .
Example #1
Source File: test_continuous_extra.py    From Computable with MIT License 6 votes vote down vote up
def test_erlang_runtimewarning():
    # erlang should generate a RuntimeWarning if a non-integer
    # shape parameter is used.
    with warnings.catch_warnings():
        warnings.simplefilter("error", RuntimeWarning)

        # The non-integer shape parameter 1.3 should trigger a RuntimeWarning
        npt.assert_raises(RuntimeWarning,
                          stats.erlang.rvs, 1.3, loc=0, scale=1, size=4)

        # Calling the fit method with `f0` set to an integer should
        # *not* trigger a RuntimeWarning.  It should return the same
        # values as gamma.fit(...).
        data = [0.5, 1.0, 2.0, 4.0]
        result_erlang = stats.erlang.fit(data, f0=1)
        result_gamma = stats.gamma.fit(data, f0=1)
        npt.assert_allclose(result_erlang, result_gamma, rtol=1e-3) 
Example #2
Source File: test_evaluators.py    From attention-lvcsr with MIT License 6 votes vote down vote up
def test_dataset_evaluators():
    X = theano.tensor.matrix('X')
    brick = TestBrick(name='test_brick')
    Y = brick.apply(X)
    graph = ComputationGraph([Y])
    monitor_variables = [v for v in graph.auxiliary_variables]
    validator = DatasetEvaluator(monitor_variables)

    data = [numpy.arange(1, 5, dtype=theano.config.floatX).reshape(2, 2),
            numpy.arange(10, 16, dtype=theano.config.floatX).reshape(3, 2)]
    data_stream = IterableDataset(dict(X=data)).get_example_stream()

    values = validator.evaluate(data_stream)
    assert values['test_brick_apply_V_squared'] == 4
    numpy.testing.assert_allclose(
        values['test_brick_apply_mean_row_mean'], numpy.vstack(data).mean())
    per_batch_mean = numpy.mean([batch.mean() for batch in data])
    numpy.testing.assert_allclose(
        values['test_brick_apply_mean_batch_element'], per_batch_mean)

    with assert_raises(Exception) as ar:
        data_stream = IterableDataset(dict(X2=data)).get_example_stream()
        validator.evaluate(data_stream)
    assert "Not all data sources" in ar.exception.args[0] 
Example #3
Source File: test_bn.py    From attention-lvcsr with MIT License 6 votes vote down vote up
def test_raise_exception_spatial():
    """Test that SpatialBatchNormalization raises an expected exception."""
    # Work around a stupid bug in nose2 that unpacks the tuple into
    # separate arguments.
    sbn1 = SpatialBatchNormalization((5,))
    yield assert_raises, (ValueError, sbn1.allocate)
    sbn2 = SpatialBatchNormalization(3)
    yield assert_raises, (ValueError, sbn2.allocate)

    def do_not_fail(*input_dim):
        try:
            sbn = SpatialBatchNormalization(input_dim)
            sbn.allocate()
        except ValueError:
            assert False

    # Work around a stupid bug in nose2 by passing as *args.
    yield do_not_fail, 5, 4, 3
    yield do_not_fail, 7, 6
    yield do_not_fail, 3, 9, 2, 3 
Example #4
Source File: test_mlemodel.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_predict():
    dates = pd.date_range(start='1980-01-01', end='1981-01-01', freq='AS')
    endog = pd.Series([1,2], index=dates)
    mod = MLEModel(endog, **kwargs)
    res = mod.filter([])

    # Test that predict with start=None, end=None does prediction with full
    # dataset
    predict = res.predict()
    assert_equal(predict.shape, (mod.nobs,))
    assert_allclose(res.get_prediction().predicted_mean, predict)

    # Test a string value to the dynamic option
    assert_allclose(res.predict(dynamic='1981-01-01'), res.predict())

    # Test an invalid date string value to the dynamic option
    # assert_raises(ValueError, res.predict, dynamic='1982-01-01')

    # Test for passing a string to predict when dates are not set
    mod = MLEModel([1,2], **kwargs)
    res = mod.filter([])
    assert_raises(KeyError, res.predict, dynamic='string') 
Example #5
Source File: test_univariate.py    From mne-features with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_pow_freq_bands():
    expected = np.array([0, 0.005, 0, 0, 0.00125]) / 0.00625
    assert_almost_equal(compute_pow_freq_bands(sfreq, data_sin,
                                               psd_method='fft'), expected)
    # Ratios of power in bands:
    # For data_sin, only the usual theta (4Hz - 8Hz) and low gamma
    # (30Hz - 70Hz) bands contain non-zero power.
    fb = np.array([[4., 8.], [30., 70.]])
    expected_pow = np.array([0.005, 0.00125]) / 0.00625
    expected_ratios = np.array([4., 0.25])
    assert_almost_equal(compute_pow_freq_bands(sfreq, data_sin, freq_bands=fb,
                                               ratios='all', psd_method='fft'),
                        np.r_[expected_pow, expected_ratios])
    assert_almost_equal(compute_pow_freq_bands(sfreq, data_sin, freq_bands=fb,
                                               ratios='only',
                                               psd_method='fft'),
                        expected_ratios)
    with assert_raises(ValueError):
        # Invalid `ratios` parameter
        compute_pow_freq_bands(sfreq, data_sin, ratios=['alpha', 'beta']) 
Example #6
Source File: test_feature_extraction.py    From mne-features with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_user_defined_feature_function():
    # User-defined feature function
    @nb.jit()
    def top_feature(arr, gamma=3.14):
        return np.sum(np.power(gamma * arr, 3) - np.power(arr / gamma, 2),
                      axis=-1)
    # Valid feature extraction
    selected_funcs = ['mean', ('top_feature', top_feature)]
    feat = extract_features(data, sfreq, selected_funcs)
    assert_equal(feat.shape, (n_epochs, 2 * n_channels))
    # Changing optional parameter ``gamma`` of ``top_feature``
    feat2 = extract_features(data, sfreq, selected_funcs,
                             funcs_params={'top_feature__gamma': 1.41})
    assert_equal(feat2.shape, (n_epochs, 2 * n_channels))
    # Invalid feature extractions
    with assert_raises(ValueError):
        # Alias is already used
        extract_features(data, sfreq, ['variance', ('mean', top_feature)])
        # Tuple is not of length 2
        extract_features(data, sfreq, ['variance', ('top_feature', top_feature,
                                                    data[:, ::2])])
        # Invalid type
        extract_features(data, sfreq, ['mean', top_feature]) 
Example #7
Source File: test_filters.py    From Computable with MIT License 6 votes vote down vote up
def test_valid_origins():
    """Regression test for #1311."""
    func = lambda x: np.mean(x)
    data = np.array([1,2,3,4,5], dtype=np.float64)
    assert_raises(ValueError, sndi.generic_filter, data, func, size=3,
                  origin=2)
    func2 = lambda x, y: np.mean(x + y)
    assert_raises(ValueError, sndi.generic_filter1d, data, func,
                  filter_size=3, origin=2)
    assert_raises(ValueError, sndi.percentile_filter, data, 0.2, size=3,
                  origin=2)

    for filter in [sndi.uniform_filter, sndi.minimum_filter,
                   sndi.maximum_filter, sndi.maximum_filter1d,
                   sndi.median_filter, sndi.minimum_filter1d]:
        # This should work, since for size == 3, the valid range for origin is
        # -1 to 1.
        list(filter(data, 3, origin=-1))
        list(filter(data, 3, origin=1))
        # Just check this raises an error instead of silently accepting or
        # segfaulting.
        assert_raises(ValueError, filter, data, 3, origin=2) 
Example #8
Source File: test_beamformer.py    From pb_bss with MIT License 5 votes vote down vote up
def test_mvdr_souden_dimensions(self):
        with tc.assert_raises(ValueError):
            super().test_mvdr_souden_dimensions() 
Example #9
Source File: test_mixins.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def test_object(self):
        x = ArrayLike(0)
        obj = object()
        with assert_raises(TypeError):
            x + obj
        with assert_raises(TypeError):
            obj + x
        with assert_raises(TypeError):
            x += obj 
Example #10
Source File: test_beamformer.py    From pb_bss with MIT License 5 votes vote down vote up
def test_difficulties(
            self,
    ):
        get_beamformer = get_mvdr_vector_souden

        for args in [
            (
                self.PhiXX[None, ...] * 0,
                self.PhiNN[None, ...],
            ),
            (
                self.PhiXX[None, ...],
                self.PhiNN[None, ...] * 0,
            ),
            (
                self.PhiXX[None, ...] * 0,
                self.PhiNN[None, ...] * 0,
            ),
        ]:
            w = get_beamformer(*args)
            assert repr(w) == 'array([[0., 0., 0.]])', repr(w)

        for args in [
            (
                self.PhiXX[None, ...] * np.inf,
                self.PhiNN[None, ...],
            ),
            (
                self.PhiXX[None, ...],
                self.PhiNN[None, ...] * np.inf,
            ),
            (
                self.PhiXX[None, ...] * np.inf,
                self.PhiNN[None, ...] * np.inf,
            ),
        ]:
            with tc.assert_raises(AssertionError):
                get_beamformer(*args) 
Example #11
Source File: test_noisyopt.py    From noisyopt with MIT License 5 votes vote down vote up
def test_bisect():
    xtol = 1e-6 

    ## simple tests
    # ascending
    root = noisyopt.bisect(lambda x: x, -2, 2, xtol=xtol,
                           errorcontrol=False)
    npt.assert_allclose(root, 0.0, atol=xtol)

    root = noisyopt.bisect(lambda x: x-1, -2, 2, xtol=xtol,
                           errorcontrol=False)
    npt.assert_allclose(root, 1.0, atol=xtol)

    # descending
    root = noisyopt.bisect(lambda x: -x, -2, 2, xtol=xtol,
                           errorcontrol=False)
    npt.assert_allclose(root, 0.0, atol=xtol)

    ## extrapolate if 0 outside of interval
    root = noisyopt.bisect(lambda x: x, 1, 2, xtol=xtol,
                           errorcontrol=False)
    npt.assert_allclose(root, 0.0, atol=xtol)
    npt.assert_raises(noisyopt.BisectException,
                      noisyopt.bisect, lambda x: x, 1, 2,
                      xtol=xtol, outside='raise', errorcontrol=False)
    
    ## extrapolate with nonlinear function
    root = noisyopt.bisect(lambda x: x+x**2, 1.0, 2, xtol=xtol,
                           errorcontrol=False)
    assert root < 1.0

    ## test with stochastic function
    xtol = 1e-1
    func = lambda x: x - 0.25 + np.random.normal(scale=0.01)
    root = noisyopt.bisect(noisyopt.AveragedFunction(func), -2, 2, xtol=xtol,
                           errorcontrol=True)
    npt.assert_allclose(root, 0.25, atol=xtol) 
Example #12
Source File: test_return_real.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def check_function(self, t):
        if t.__doc__.split()[0] in ['t0', 't4', 's0', 's4']:
            err = 1e-5
        else:
            err = 0.0
        assert_(abs(t(234) - 234.0) <= err)
        assert_(abs(t(234.6) - 234.6) <= err)
        assert_(abs(t(long(234)) - 234.0) <= err)
        assert_(abs(t('234') - 234) <= err)
        assert_(abs(t('234.6') - 234.6) <= err)
        assert_(abs(t(-234) + 234) <= err)
        assert_(abs(t([234]) - 234) <= err)
        assert_(abs(t((234,)) - 234.) <= err)
        assert_(abs(t(array(234)) - 234.) <= err)
        assert_(abs(t(array([234])) - 234.) <= err)
        assert_(abs(t(array([[234]])) - 234.) <= err)
        assert_(abs(t(array([234], 'b')) + 22) <= err)
        assert_(abs(t(array([234], 'h')) - 234.) <= err)
        assert_(abs(t(array([234], 'i')) - 234.) <= err)
        assert_(abs(t(array([234], 'l')) - 234.) <= err)
        assert_(abs(t(array([234], 'B')) - 234.) <= err)
        assert_(abs(t(array([234], 'f')) - 234.) <= err)
        assert_(abs(t(array([234], 'd')) - 234.) <= err)
        if t.__doc__.split()[0] in ['t0', 't4', 's0', 's4']:
            assert_(t(1e200) == t(1e300))  # inf

        #assert_raises(ValueError, t, array([234], 'S1'))
        assert_raises(ValueError, t, 'abc')

        assert_raises(IndexError, t, [])
        assert_raises(IndexError, t, ())

        assert_raises(Exception, t, t)
        assert_raises(Exception, t, {})

        try:
            r = t(10 ** 400)
            assert_(repr(r) in ['inf', 'Infinity'], repr(r))
        except OverflowError:
            pass 
Example #13
Source File: test_return_integer.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def check_function(self, t):
        assert_(t(123) == 123, repr(t(123)))
        assert_(t(123.6) == 123)
        assert_(t(long(123)) == 123)
        assert_(t('123') == 123)
        assert_(t(-123) == -123)
        assert_(t([123]) == 123)
        assert_(t((123,)) == 123)
        assert_(t(array(123)) == 123)
        assert_(t(array([123])) == 123)
        assert_(t(array([[123]])) == 123)
        assert_(t(array([123], 'b')) == 123)
        assert_(t(array([123], 'h')) == 123)
        assert_(t(array([123], 'i')) == 123)
        assert_(t(array([123], 'l')) == 123)
        assert_(t(array([123], 'B')) == 123)
        assert_(t(array([123], 'f')) == 123)
        assert_(t(array([123], 'd')) == 123)

        #assert_raises(ValueError, t, array([123],'S3'))
        assert_raises(ValueError, t, 'abc')

        assert_raises(IndexError, t, [])
        assert_raises(IndexError, t, ())

        assert_raises(Exception, t, t)
        assert_raises(Exception, t, {})

        if t.__doc__.split()[0] in ['t8', 's8']:
            assert_raises(OverflowError, t, 100000000000000000000000)
            assert_raises(OverflowError, t, 10000000011111111111111.23) 
Example #14
Source File: test_errstate.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def test_invalid(self):
        with np.errstate(all='raise', under='ignore'):
            a = -np.arange(3)
            # This should work
            with np.errstate(invalid='ignore'):
                np.sqrt(a)
            # While this should fail!
            with assert_raises(FloatingPointError):
                np.sqrt(a) 
Example #15
Source File: test_errstate.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def test_divide(self):
        with np.errstate(all='raise', under='ignore'):
            a = -np.arange(3)
            # This should work
            with np.errstate(divide='ignore'):
                a // 0
            # While this should fail!
            with assert_raises(FloatingPointError):
                a // 0 
Example #16
Source File: test_mixins.py    From pySINDy with MIT License 5 votes vote down vote up
def test_object(self):
        x = ArrayLike(0)
        obj = object()
        with assert_raises(TypeError):
            x + obj
        with assert_raises(TypeError):
            obj + x
        with assert_raises(TypeError):
            x += obj 
Example #17
Source File: test_return_real.py    From pySINDy with MIT License 5 votes vote down vote up
def check_function(self, t):
        if t.__doc__.split()[0] in ['t0', 't4', 's0', 's4']:
            err = 1e-5
        else:
            err = 0.0
        assert_(abs(t(234) - 234.0) <= err)
        assert_(abs(t(234.6) - 234.6) <= err)
        assert_(abs(t(long(234)) - 234.0) <= err)
        assert_(abs(t('234') - 234) <= err)
        assert_(abs(t('234.6') - 234.6) <= err)
        assert_(abs(t(-234) + 234) <= err)
        assert_(abs(t([234]) - 234) <= err)
        assert_(abs(t((234,)) - 234.) <= err)
        assert_(abs(t(array(234)) - 234.) <= err)
        assert_(abs(t(array([234])) - 234.) <= err)
        assert_(abs(t(array([[234]])) - 234.) <= err)
        assert_(abs(t(array([234], 'b')) + 22) <= err)
        assert_(abs(t(array([234], 'h')) - 234.) <= err)
        assert_(abs(t(array([234], 'i')) - 234.) <= err)
        assert_(abs(t(array([234], 'l')) - 234.) <= err)
        assert_(abs(t(array([234], 'B')) - 234.) <= err)
        assert_(abs(t(array([234], 'f')) - 234.) <= err)
        assert_(abs(t(array([234], 'd')) - 234.) <= err)
        if t.__doc__.split()[0] in ['t0', 't4', 's0', 's4']:
            assert_(t(1e200) == t(1e300))  # inf

        #assert_raises(ValueError, t, array([234], 'S1'))
        assert_raises(ValueError, t, 'abc')

        assert_raises(IndexError, t, [])
        assert_raises(IndexError, t, ())

        assert_raises(Exception, t, t)
        assert_raises(Exception, t, {})

        try:
            r = t(10 ** 400)
            assert_(repr(r) in ['inf', 'Infinity'], repr(r))
        except OverflowError:
            pass 
Example #18
Source File: test_recfunctions.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_autoconversion(self):
        # Tests autoconversion
        adtype = [('A', int), ('B', bool), ('C', float)]
        a = ma.array([(1, 2, 3)], mask=[(0, 1, 0)], dtype=adtype)
        bdtype = [('A', int), ('B', float), ('C', float)]
        b = ma.array([(4, 5, 6)], dtype=bdtype)
        control = ma.array([(1, 2, 3), (4, 5, 6)], mask=[(0, 1, 0), (0, 0, 0)],
                           dtype=bdtype)
        test = stack_arrays((a, b), autoconvert=True)
        assert_equal(test, control)
        assert_equal(test.mask, control.mask)
        with assert_raises(TypeError):
            stack_arrays((a, b), autoconvert=False) 
Example #19
Source File: test_return_integer.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def check_function(self, t):
        assert_(t(123) == 123, repr(t(123)))
        assert_(t(123.6) == 123)
        assert_(t(long(123)) == 123)
        assert_(t('123') == 123)
        assert_(t(-123) == -123)
        assert_(t([123]) == 123)
        assert_(t((123,)) == 123)
        assert_(t(array(123)) == 123)
        assert_(t(array([123])) == 123)
        assert_(t(array([[123]])) == 123)
        assert_(t(array([123], 'b')) == 123)
        assert_(t(array([123], 'h')) == 123)
        assert_(t(array([123], 'i')) == 123)
        assert_(t(array([123], 'l')) == 123)
        assert_(t(array([123], 'B')) == 123)
        assert_(t(array([123], 'f')) == 123)
        assert_(t(array([123], 'd')) == 123)

        #assert_raises(ValueError, t, array([123],'S3'))
        assert_raises(ValueError, t, 'abc')

        assert_raises(IndexError, t, [])
        assert_raises(IndexError, t, ())

        assert_raises(Exception, t, t)
        assert_raises(Exception, t, {})

        if t.__doc__.split()[0] in ['t8', 's8']:
            assert_raises(OverflowError, t, 100000000000000000000000)
            assert_raises(OverflowError, t, 10000000011111111111111.23) 
Example #20
Source File: test_return_real.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def check_function(self, t):
        if t.__doc__.split()[0] in ['t0', 't4', 's0', 's4']:
            err = 1e-5
        else:
            err = 0.0
        assert_(abs(t(234) - 234.0) <= err)
        assert_(abs(t(234.6) - 234.6) <= err)
        assert_(abs(t(long(234)) - 234.0) <= err)
        assert_(abs(t('234') - 234) <= err)
        assert_(abs(t('234.6') - 234.6) <= err)
        assert_(abs(t(-234) + 234) <= err)
        assert_(abs(t([234]) - 234) <= err)
        assert_(abs(t((234,)) - 234.) <= err)
        assert_(abs(t(array(234)) - 234.) <= err)
        assert_(abs(t(array([234])) - 234.) <= err)
        assert_(abs(t(array([[234]])) - 234.) <= err)
        assert_(abs(t(array([234], 'b')) + 22) <= err)
        assert_(abs(t(array([234], 'h')) - 234.) <= err)
        assert_(abs(t(array([234], 'i')) - 234.) <= err)
        assert_(abs(t(array([234], 'l')) - 234.) <= err)
        assert_(abs(t(array([234], 'B')) - 234.) <= err)
        assert_(abs(t(array([234], 'f')) - 234.) <= err)
        assert_(abs(t(array([234], 'd')) - 234.) <= err)
        if t.__doc__.split()[0] in ['t0', 't4', 's0', 's4']:
            assert_(t(1e200) == t(1e300))  # inf

        #assert_raises(ValueError, t, array([234], 'S1'))
        assert_raises(ValueError, t, 'abc')

        assert_raises(IndexError, t, [])
        assert_raises(IndexError, t, ())

        assert_raises(Exception, t, t)
        assert_raises(Exception, t, {})

        try:
            r = t(10 ** 400)
            assert_(repr(r) in ['inf', 'Infinity'], repr(r))
        except OverflowError:
            pass 
Example #21
Source File: test_mixins.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def test_object(self):
        x = ArrayLike(0)
        obj = object()
        with assert_raises(TypeError):
            x + obj
        with assert_raises(TypeError):
            obj + x
        with assert_raises(TypeError):
            x += obj 
Example #22
Source File: test_mixins.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def test_opt_out(self):

        class OptOut(object):
            """Object that opts out of __array_ufunc__."""
            __array_ufunc__ = None

            def __add__(self, other):
                return self

            def __radd__(self, other):
                return self

        array_like = ArrayLike(1)
        opt_out = OptOut()

        # supported operations
        assert_(array_like + opt_out is opt_out)
        assert_(opt_out + array_like is opt_out)

        # not supported
        with assert_raises(TypeError):
            # don't use the Python default, array_like = array_like + opt_out
            array_like += opt_out
        with assert_raises(TypeError):
            array_like - opt_out
        with assert_raises(TypeError):
            opt_out - array_like 
Example #23
Source File: test_utils.py    From mne-features with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_psd_params_checker():
    valid_params = {'welch_n_fft': 2048, 'welch_n_per_seg': 1024}
    assert_equal(valid_params, _psd_params_checker(valid_params))
    assert_equal(dict(), _psd_params_checker(None))
    with assert_raises(ValueError):
        invalid_params1 = {'n_fft': 1024, 'psd_method': 'fft'}
        _psd_params_checker(invalid_params1)
    with assert_raises(ValueError):
        invalid_params2 = [1024, 1024]
        _psd_params_checker(invalid_params2) 
Example #24
Source File: test_feature_extraction.py    From mne-features with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_feature_extractor():
    selected_funcs = ['app_entropy']
    extractor = FeatureExtractor(sfreq=sfreq, selected_funcs=selected_funcs)
    expected_features = extract_features(data, sfreq, selected_funcs)
    assert_almost_equal(expected_features, extractor.fit_transform(data))
    with assert_raises(ValueError):
        FeatureExtractor(
            sfreq=sfreq, selected_funcs=selected_funcs,
            params={'app_entropy__metric': 'sqeuclidean'}).fit_transform(data) 
Example #25
Source File: test_feature_extraction.py    From mne-features with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_wrong_params():
    with assert_raises(ValueError):
        # Negative sfreq
        extract_features(data, -0.1, ['mean'])
    with assert_raises(ValueError):
        # Unknown alias of feature function
        extract_features(data, sfreq, ['power_freq_bands'])
    with assert_raises(ValueError):
        # No alias given
        extract_features(data, sfreq, list())
    with assert_raises(ValueError):
        # Passing optional arguments with unknown alias
        extract_features(data, sfreq, ['higuchi_fd'],
                         {'higuch_fd__kmax': 3}) 
Example #26
Source File: test_univariate.py    From mne-features with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_freq_bands_helper():
    fb1 = np.array([.5, 4, 8, 13, 30, 100])
    fb2 = np.array([[.5, 4], [4, 8], [8, 13], [13, 30], [30, 100]])
    assert_equal(fb2, _freq_bands_helper(256., fb1))
    assert_equal(fb2, _freq_bands_helper(256., fb2))
    with assert_raises(ValueError):
        _freq_bands_helper(128., fb1)
    with assert_raises(ValueError):
        _freq_bands_helper(256., fb2.T) 
Example #27
Source File: test_univariate.py    From mne-features with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_samp_entropy():
    _data = np.array([[1, -1, 1, -1, 0, 1, -1, 1]])
    expected = np.array([log(3)])
    assert_almost_equal(compute_samp_entropy(_data), expected)
    with assert_raises(ValueError):
        # Data for which SampEn is not defined:
        compute_samp_entropy(data1)
        # Wrong `metric` parameter:
        compute_samp_entropy(_data, metric='sqeuclidean') 
Example #28
Source File: test_univariate.py    From mne-features with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_app_entropy():
    expected = np.array([-log(7) + log(6),
                         (2 * log(2) - 7 * log(7)) / 7 + log(6)])
    assert_almost_equal(compute_app_entropy(data1), expected)
    # Note: the approximate entropy should be close to 0 for a
    # regular and predictable time series.
    data3 = np.array([(-1) ** np.arange(int(sfreq))])
    assert_almost_equal(compute_app_entropy(data3), 0, decimal=5)
    # Wrong `metric` parameter:
    with assert_raises(ValueError):
        compute_app_entropy(data[0, :, :], emb=5, metric='sqeuclidean') 
Example #29
Source File: test_references.py    From pyfive with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_chunked_reference_dataset():

    with pyfive.File(REFERENCES_HDF5_FILE) as hfile:

        ref_dataset = hfile['chunked_ref_dataset']
        root_ref = ref_dataset[0]
        dset_ref = ref_dataset[1]
        group_ref = ref_dataset[2]
        null_ref = ref_dataset[3]

        # check references
        root = hfile[root_ref]
        assert root.attrs['root_attr'] == 123

        dset1 = hfile[dset_ref]
        assert_array_equal(dset1[:], [0, 1, 2, 3])
        assert dset1.attrs['dset_attr'] == 456

        group = hfile[group_ref]
        assert group.attrs['group_attr'] == 789

        with assert_raises(ValueError):
            hfile[null_ref]

        assert bool(root_ref)
        assert bool(dset_ref)
        assert bool(group_ref)
        assert not bool(null_ref)


# Region Reference not yet supported by pyfive 
Example #30
Source File: test_references.py    From pyfive with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_reference_dataset():

    with pyfive.File(REFERENCES_HDF5_FILE) as hfile:

        ref_dataset = hfile['ref_dataset']
        root_ref = ref_dataset[0]
        dset_ref = ref_dataset[1]
        group_ref = ref_dataset[2]
        null_ref = ref_dataset[3]

        # check references
        root = hfile[root_ref]
        assert root.attrs['root_attr'] == 123

        dset1 = hfile[dset_ref]
        assert_array_equal(dset1[:], [0, 1, 2, 3])
        assert dset1.attrs['dset_attr'] == 456

        group = hfile[group_ref]
        assert group.attrs['group_attr'] == 789

        with assert_raises(ValueError):
            hfile[null_ref]

        assert bool(root_ref)
        assert bool(dset_ref)
        assert bool(group_ref)
        assert not bool(null_ref)