Python numpy.testing.assert_equal() Examples

The following are code examples for showing how to use numpy.testing.assert_equal(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: sklearn-xarray   Author: phausamann   File: test_target.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_constructor():

    from sklearn_xarray.utils import convert_to_ndarray

    coord_1 = ['a']*51 + ['b']*49
    coord_2 = list(range(10))*10

    X_ds = xr.Dataset(
        {'var_1': (['sample', 'feature'], np.random.random((100, 10)))},
        coords={'sample': range(100), 'feature': range(10),
                'coord_1': (['sample'], coord_1),
                'coord_2': (['sample'], coord_2)}
    )

    target = Target(transform_func=convert_to_ndarray)
    target.assign_to(X_ds)

    npt.assert_equal(target.values, np.array(X_ds.var_1))

    target = Target(coord='coord_1', transformer=LabelBinarizer())(X_ds)

    npt.assert_equal(
        target.values, LabelBinarizer().fit_transform(coord_1)) 
Example 2
Project: sklearn-xarray   Author: phausamann   File: test_target.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_array():

    coord_1 = ['a']*51 + ['b']*49
    coord_2 = list(range(10))*10

    X_ds = xr.Dataset(
        {'var_1': (['sample', 'feature'], np.random.random((100, 10)))},
        coords={'sample': range(100), 'feature': range(10),
                'coord_1': (['sample'], coord_1),
                'coord_2': (['sample'], coord_2)}
    )

    target = Target(
        coord='coord_1', transform_func=LabelBinarizer().fit_transform,
        lazy=True)(X_ds)

    npt.assert_equal(np.array(target), LabelBinarizer().fit_transform(coord_1)) 
Example 3
Project: sklearn-xarray   Author: phausamann   File: test_target.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_shape_and_ndim():

    coord_1 = ['a']*51 + ['b']*49
    coord_2 = list(range(10))*10

    X_ds = xr.Dataset(
        {'var_1': (['sample', 'feature'], np.random.random((100, 10)))},
        coords={'sample': range(100), 'feature': range(10),
                'coord_1': (['sample'], coord_1),
                'coord_2': (['sample'], coord_2)}
    )

    target = Target(
        coord='coord_1', transform_func=LabelBinarizer().fit_transform)(X_ds)

    npt.assert_equal(
        target.shape, LabelBinarizer().fit_transform(coord_1).shape)

    npt.assert_equal(
        target.ndim, LabelBinarizer().fit_transform(coord_1).ndim) 
Example 4
Project: sklearn-xarray   Author: phausamann   File: test_target.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_multidim_coord():

    coord_1 = np.tile(['a']*51 + ['b']*49, (10, 1)).T
    coord_2 = np.random.random((100, 10, 10))

    X_ds = xr.Dataset(
        {'var_1': (['sample', 'feat_1', 'feat_2'],
                   np.random.random((100, 10, 10)))},
        coords={'sample': range(100), 'feature': range(10),
                'coord_1': (['sample', 'feat_1'], coord_1),
                'coord_2': (['sample', 'feat_1', 'feat_2'], coord_2)}
    )

    target_1 = Target(
        coord='coord_1', transform_func=LabelBinarizer().fit_transform,
        dim='sample')(X_ds)
    target_2 = Target(
        coord='coord_2', dim=['sample', 'feat_1'], reduce_func=np.mean)(X_ds)

    npt.assert_equal(target_1, LabelBinarizer().fit_transform(coord_1[:, 0]))
    npt.assert_equal(target_2, np.mean(coord_2, 2)) 
Example 5
Project: sklearn-xarray   Author: phausamann   File: test_preprocessing.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_concatenate():

    X_ds = xr.Dataset(
        {'var_1': (['sample', 'feature'], np.random.random((100, 10))),
         'var_2': (['sample', 'feature'], np.random.random((100, 10))),
         'var_3': (['sample', 'feature'], np.random.random((100, 10)))},
        coords={'sample': range(100), 'feature': range(10)}
    )

    Xt_da, concatenator = concatenate(
        X_ds, return_array=True, return_estimator=True)

    assert Xt_da.shape == (100, 30)

    xrt.assert_allclose(concatenator.inverse_transform(Xt_da), X_ds)

    Xt_ds2, concatenator2 = concatenate(
        X_ds, variables=['var_1', 'var_2'], new_index_func=np.arange,
        return_estimator=True)

    assert Xt_ds2.Feature.shape == (100, 20)
    npt.assert_equal(Xt_ds2.feature.values, np.arange(20))

    xrt.assert_allclose(concatenator2.inverse_transform(Xt_ds2), X_ds) 
Example 6
Project: sklearn-xarray   Author: phausamann   File: test_common.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_dummy_estimator(self):

        estimator = wrap(DummyEstimator())

        # test DataArray
        X_da = self.X.var_2d

        estimator.fit(X_da)
        yp = estimator.predict(X_da)

        assert_equal(yp, X_da)

        # test Dataset
        X_ds = self.X

        estimator.fit(X_ds)
        yp = estimator.predict(X_ds)

        assert_equal(yp, X_ds) 
Example 7
Project: sklearn-xarray   Author: phausamann   File: test_common.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_dummy_transformer(self):

        estimator = wrap(DummyTransformer())

        # test DataArray
        X_da = self.X.var_2d

        estimator.fit(X_da)
        yp = estimator.transform(X_da)

        assert_equal(yp, X_da)

        # test Dataset
        X_ds = self.X

        estimator.fit(X_ds)
        yp = estimator.transform(X_ds)

        assert_equal(yp, X_ds) 
Example 8
Project: sklearn-xarray   Author: phausamann   File: test_common.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_ndim_dummy_estimator(self):

        estimator = wrap(DummyEstimator())

        # test DataArray
        X_da = self.X.var_3d

        estimator.fit(X_da)
        yp = estimator.predict(X_da)

        assert_equal(yp, X_da)

        # test Dataset
        X_ds = self.X

        estimator.fit(X_ds)
        yp = estimator.predict(X_ds)

        assert_equal(yp, X_ds) 
Example 9
Project: sklearn-xarray   Author: phausamann   File: test_common.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_sample_dim(self):

        from sklearn.decomposition import PCA

        estimator = wrap(
            PCA(n_components=5), reshapes='feat_1', sample_dim='sample')

        # test DataArray
        X_da = self.X.var_2d

        Xt_da = estimator.fit_transform(X_da)
        Xr_da = estimator.inverse_transform(Xt_da)

        npt.assert_equal(Xt_da.shape, (100, 5))
        npt.assert_equal(Xr_da.shape, (100, 10))

        # test Dataset
        X_ds = self.X.var_2d.to_dataset()

        Xt = estimator.fit_transform(X_ds)

        npt.assert_equal(Xt.var_2d.shape, (100, 5)) 
Example 10
Project: LaserTOF   Author: kyleuckert   File: test_mem_overlap.py    MIT License 6 votes vote down vote up
def check_may_share_memory_exact(a, b):
    got = np.may_share_memory(a, b, max_work=MAY_SHARE_EXACT)

    assert_equal(np.may_share_memory(a, b),
                 np.may_share_memory(a, b, max_work=MAY_SHARE_BOUNDS))

    a.fill(0)
    b.fill(0)
    a.fill(1)
    exact = b.any()

    err_msg = ""
    if got != exact:
        err_msg = "    " + "\n    ".join([
            "base_a - base_b = %r" % (a.__array_interface__['data'][0] - b.__array_interface__['data'][0],),
            "shape_a = %r" % (a.shape,),
            "shape_b = %r" % (b.shape,),
            "strides_a = %r" % (a.strides,),
            "strides_b = %r" % (b.strides,),
            "size_a = %r" % (a.size,),
            "size_b = %r" % (b.size,)
        ])

    assert_equal(got, exact, err_msg=err_msg) 
Example 11
Project: LaserTOF   Author: kyleuckert   File: test_mem_overlap.py    MIT License 6 votes vote down vote up
def check_internal_overlap(a, manual_expected=None):
    got = internal_overlap(a)

    # Brute-force check
    m = set()
    ranges = tuple(xrange(n) for n in a.shape)
    for v in itertools.product(*ranges):
        offset = sum(s*w for s, w in zip(a.strides, v))
        if offset in m:
            expected = True
            break
        else:
            m.add(offset)
    else:
        expected = False

    # Compare
    if got != expected:
        assert_equal(got, expected, err_msg=repr((a.strides, a.shape)))
    if manual_expected is not None and expected != manual_expected:
        assert_equal(expected, manual_expected)
    return got 
Example 12
Project: LaserTOF   Author: kyleuckert   File: test_extint128.py    MIT License 6 votes vote down vote up
def test_divmod_128_64():
    with exc_iter(INT128_VALUES, INT64_POS_VALUES) as it:
        for a, b in it:
            if a >= 0:
                c, cr = divmod(a, b)
            else:
                c, cr = divmod(-a, b)
                c = -c
                cr = -cr

            d, dr = mt.extint_divmod_128_64(a, b)

            if c != d or d != dr or b*d + dr != a:
                assert_equal(d, c)
                assert_equal(dr, cr)
                assert_equal(b*d + dr, a) 
Example 13
Project: LaserTOF   Author: kyleuckert   File: common_tests.py    MIT License 6 votes vote down vote up
def check_edge_support(distfn, args):
    # Make sure that x=self.a and self.b are handled correctly.
    x = [distfn.a, distfn.b]
    if isinstance(distfn, stats.rv_discrete):
        x = [distfn.a - 1, distfn.b]

    npt.assert_equal(distfn.cdf(x, *args), [0.0, 1.0])
    npt.assert_equal(distfn.sf(x, *args), [1.0, 0.0])

    if distfn.name not in ('skellam', 'dlaplace'):
        # with a = -inf, log(0) generates warnings
        npt.assert_equal(distfn.logcdf(x, *args), [-np.inf, 0.0])
        npt.assert_equal(distfn.logsf(x, *args), [0.0, -np.inf])

    npt.assert_equal(distfn.ppf([0.0, 1.0], *args), x)
    npt.assert_equal(distfn.isf([0.0, 1.0], *args), x[::-1])

    # out-of-bounds for isf & ppf
    npt.assert_(np.isnan(distfn.isf([-1, 2], *args)).all())
    npt.assert_(np.isnan(distfn.ppf([-1, 2], *args)).all()) 
Example 14
Project: LaserTOF   Author: kyleuckert   File: common_tests.py    MIT License 6 votes vote down vote up
def check_pickling(distfn, args):
    # check that a distribution instance pickles and unpickles
    # pay special attention to the random_state property

    # save the random_state (restore later)
    rndm = distfn.random_state

    distfn.random_state = 1234
    distfn.rvs(*args, size=8)
    s = pickle.dumps(distfn)
    r0 = distfn.rvs(*args, size=8)

    unpickled = pickle.loads(s)
    r1 = unpickled.rvs(*args, size=8)
    npt.assert_equal(r0, r1)

    # also smoke test some methods
    medians = [distfn.ppf(0.5, *args), unpickled.ppf(0.5, *args)]
    npt.assert_equal(medians[0], medians[1])
    npt.assert_equal(distfn.cdf(medians[0], *args),
                     unpickled.cdf(medians[1], *args))

    # restore the random_state
    distfn.random_state = rndm 
Example 15
Project: pulse2percept   Author: pulse2percept   File: test_files.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_load_video_metadata():
    # Load a test example
    reload(files)
    with pytest.raises(OSError):
        metadata = files.load_video_metadata('nothing_there.mp4')

    from skvideo import datasets
    metadata = files.load_video_metadata(datasets.bikes())
    npt.assert_equal(metadata['@codec_name'], 'h264')
    npt.assert_equal(metadata['@duration_ts'], '128000')
    npt.assert_equal(metadata['@r_frame_rate'], '25/1')

    # Trigger an import error
    with mock.patch.dict("sys.modules", {"skvideo": {}, "skvideo.utils": {}}):
        with pytest.raises(ImportError):
            reload(files)
            files.load_video_metadata(datasets.bikes()) 
Example 16
Project: pulse2percept   Author: pulse2percept   File: test_retina.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_BaseModel():
    # Cannot instantiate abstract class
    with pytest.raises(TypeError):
        tm = retina.BaseModel(0.01)

    # Child class must provide `model_cascade()`
    class Incomplete(retina.BaseModel):
        pass
    with pytest.raises(TypeError):
        tm = Incomplete()

    # A complete class
    class Complete(retina.BaseModel):

        def model_cascade(self, inval):
            return inval

    tm = Complete(tsample=0.1)
    npt.assert_equal(tm.tsample, 0.1)
    npt.assert_equal(tm.model_cascade(2.4), 2.4) 
Example 17
Project: pulse2percept   Author: pulse2percept   File: test_retina.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_axon_dist_from_soma():
    # A small grid
    xg, yg = np.meshgrid([-1, 0, 1], [-1, 0, 1], indexing='xy')

    # When axon locations are snapped to the grid, a really short axon should
    # have zero distance to the soma:
    for x_soma in [-1.0, -0.2, 0.51]:
        axon = np.array([[i, i] for i in np.linspace(x_soma, x_soma + 0.01)])
        _, dist = retina.axon_dist_from_soma(axon, xg, yg)
        npt.assert_almost_equal(dist, 0.0)

    # On this simple grid, a diagonal axon should have dist [0, sqrt(2), 2]:
    for sign in [-1.0, 1.0]:
        for num in [10, 20, 50]:
            axon = np.array([[i, i] for i in np.linspace(sign, -sign, num)])
            _, dist = retina.axon_dist_from_soma(axon, xg, yg)
            npt.assert_almost_equal(dist, np.array([0.0, np.sqrt(2), 2.0]))

    # An axon that does not live near the grid should return infinite distance
    axon = np.array([[i, i] for i in np.linspace(1000.0, 1500.0)])
    _, dist = retina.axon_dist_from_soma(axon, xg, yg)
    npt.assert_equal(np.isinf(dist), True) 
Example 18
Project: pulse2percept   Author: pulse2percept   File: test_utils.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_TimeSeries():
    max_val = 2.0
    max_idx = 156
    data_orig = np.random.rand(10, 10, 1000)
    data_orig[4, 4, max_idx] = max_val
    ts = utils.TimeSeries(1.0, data_orig)

    # Make sure function returns largest element
    tmax, vmax = ts.max()
    npt.assert_equal(tmax, max_idx)
    npt.assert_equal(vmax, max_val)

    # Make sure function returns largest frame
    tmax, fmax = ts.max_frame()
    npt.assert_equal(tmax, max_idx)
    npt.assert_equal(fmax.data, data_orig[:, :, max_idx])

    # Make sure getitem works
    npt.assert_equal(isinstance(ts[3], utils.TimeSeries), True)
    npt.assert_equal(ts[3].data, ts.data[3]) 
Example 19
Project: pulse2percept   Author: pulse2percept   File: test_utils.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_gamma():
    tsample = 0.005 / 1000

    with pytest.raises(ValueError):
        t, g = utils.gamma(0, 0.1, tsample)
    with pytest.raises(ValueError):
        t, g = utils.gamma(2, -0.1, tsample)
    with pytest.raises(ValueError):
        t, g = utils.gamma(2, 0.1, -tsample)

    for tau in [0.001, 0.01, 0.1]:
        for n in [1, 2, 5]:
            t, g = utils.gamma(n, tau, tsample)
            npt.assert_equal(np.arange(0, t[-1] + tsample / 2.0, tsample), t)
            if n > 1:
                npt.assert_equal(g[0], 0.0)

            # Make sure area under the curve is normalized
            npt.assert_almost_equal(np.trapz(np.abs(g), dx=tsample), 1.0,
                                    decimal=2)

            # Make sure peak sits correctly
            npt.assert_almost_equal(g.argmax() * tsample, tau * (n - 1)) 
Example 20
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_extint128.py    MIT License 6 votes vote down vote up
def test_safe_binop():
    # Test checked arithmetic routines

    ops = [
        (operator.add, 1),
        (operator.sub, 2),
        (operator.mul, 3)
    ]

    with exc_iter(ops, INT64_VALUES, INT64_VALUES) as it:
        for xop, a, b in it:
            pyop, op = xop
            c = pyop(a, b)

            if not (INT64_MIN <= c <= INT64_MAX):
                assert_raises(OverflowError, mt.extint_safe_binop, a, b, op)
            else:
                d = mt.extint_safe_binop(a, b, op)
                if c != d:
                    # assert_equal is slow
                    assert_equal(d, c) 
Example 21
Project: mmdetection   Author: open-mmlab   File: test_utils.py    Apache License 2.0 5 votes vote down vote up
def test_params_to_string():
    npt.assert_equal(params_to_string(1e9), '1000.0 M')
    npt.assert_equal(params_to_string(2e5), '200.0 k')
    npt.assert_equal(params_to_string(3e-9), '3e-09') 
Example 22
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: onnx_import_test.py    Apache License 2.0 5 votes vote down vote up
def test_bvlc_googlenet():
    """ Tests Googlenet model"""
    model_path, inputs, outputs = get_test_files('bvlc_googlenet')
    logging.info("Translating Googlenet model from ONNX to Mxnet")
    sym, arg_params, aux_params = onnx_mxnet.import_model(model_path)
    metadata = onnx_mxnet.get_model_metadata(model_path)
    assert len(metadata) == 2
    assert metadata.get('input_tensor_data')
    assert metadata.get('input_tensor_data') == [(u'data_0', (1, 3, 224, 224))]
    assert metadata.get('output_tensor_data')
    assert metadata.get('output_tensor_data') == [(u'prob_1', (1, 1000))]
    data_names = [input_name[0] for input_name in metadata.get('input_tensor_data')]

    # run test for each test file
    for input_data, output_data in zip(inputs, outputs):
        # create module
        mod = mx.mod.Module(symbol=sym, data_names=data_names, context=mx.cpu(), label_names=None)
        mod.bind(for_training=False, data_shapes=[(data_names[0], input_data.shape)], label_shapes=None)
        mod.set_params(arg_params=arg_params, aux_params=aux_params,
                       allow_missing=True, allow_extra=True)
        # run inference
        batch = namedtuple('Batch', ['data'])
        mod.forward(batch([mx.nd.array(input_data)]), is_train=False)

        # verify the results
        npt.assert_equal(mod.get_outputs()[0].shape, output_data.shape)
        npt.assert_almost_equal(output_data, mod.get_outputs()[0].asnumpy(), decimal=3)
    logging.info("Googlenet model conversion Successful") 
Example 23
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: onnx_import_test.py    Apache License 2.0 5 votes vote down vote up
def test_bvlc_reference_caffenet():
    """Tests the bvlc cafenet model"""
    model_path, inputs, outputs = get_test_files('bvlc_reference_caffenet')
    logging.info("Translating Caffenet model from ONNX to Mxnet")
    sym, arg_params, aux_params = onnx_mxnet.import_model(model_path)
    metadata = onnx_mxnet.get_model_metadata(model_path)
    assert len(metadata) == 2
    assert metadata.get('input_tensor_data')
    assert metadata.get('input_tensor_data') == [(u'data_0', (1, 3, 224, 224))]
    assert metadata.get('output_tensor_data')
    assert metadata.get('output_tensor_data') == [(u'prob_1', (1, 1000))]
    data_names = [input_name[0] for input_name in metadata.get('input_tensor_data')]

    # run test for each test file
    for input_data, output_data in zip(inputs, outputs):
        # create module
        mod = mx.mod.Module(symbol=sym, data_names=data_names, context=mx.cpu(), label_names=None)
        mod.bind(for_training=False, data_shapes=[(data_names[0], input_data.shape)], label_shapes=None)
        mod.set_params(arg_params=arg_params, aux_params=aux_params,
                       allow_missing=True, allow_extra=True)
        # run inference
        batch = namedtuple('Batch', ['data'])
        mod.forward(batch([mx.nd.array(input_data)]), is_train=False)

        # verify the results
        npt.assert_equal(mod.get_outputs()[0].shape, output_data.shape)
        npt.assert_almost_equal(output_data, mod.get_outputs()[0].asnumpy(), decimal=3)
    logging.info("Caffenet model conversion Successful") 
Example 24
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: onnx_import_test.py    Apache License 2.0 5 votes vote down vote up
def test_bvlc_rcnn_ilsvrc13():
    """Tests the bvlc rcnn model"""
    model_path, inputs, outputs = get_test_files('bvlc_reference_rcnn_ilsvrc13')
    logging.info("Translating rcnn_ilsvrc13 model from ONNX to Mxnet")
    sym, arg_params, aux_params = onnx_mxnet.import_model(model_path)
    metadata = onnx_mxnet.get_model_metadata(model_path)
    assert len(metadata) == 2
    assert metadata.get('input_tensor_data')
    assert metadata.get('input_tensor_data') == [(u'data_0', (1, 3, 224, 224))]
    assert metadata.get('output_tensor_data')
    assert metadata.get('output_tensor_data') == [(u'fc-rcnn_1', (1, 200))]
    data_names = [input_name[0] for input_name in metadata.get('input_tensor_data')]

    # run test for each test file
    for input_data, output_data in zip(inputs, outputs):
        # create module
        mod = mx.mod.Module(symbol=sym, data_names=data_names, context=mx.cpu(), label_names=None)
        mod.bind(for_training=False, data_shapes=[(data_names[0], input_data.shape)], label_shapes=None)
        mod.set_params(arg_params=arg_params, aux_params=aux_params,
                       allow_missing=True, allow_extra=True)
        # run inference
        batch = namedtuple('Batch', ['data'])
        mod.forward(batch([mx.nd.array(input_data)]), is_train=False)

        # verify the results
        npt.assert_equal(mod.get_outputs()[0].shape, output_data.shape)
        npt.assert_almost_equal(output_data, mod.get_outputs()[0].asnumpy(), decimal=3)
    logging.info("rcnn_ilsvrc13 model conversion Successful") 
Example 25
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: mxnet_export_test.py    Apache License 2.0 5 votes vote down vote up
def test_models(model_name, input_shape, output_shape):
    """ Tests Googlenet model for both onnx import and export"""
    model_path, inputs, outputs = get_test_files(model_name)
    logging.info("Translating model from ONNX model zoo to Mxnet")
    sym, arg_params, aux_params = onnx_mxnet.import_model(model_path)
    params = {}
    params.update(arg_params)
    params.update(aux_params)

    dir_path = os.path.dirname(model_path)
    new_model_name = "exported_" + model_name + ".onnx"
    onnx_file = os.path.join(dir_path, new_model_name)

    logging.info("Translating converted model from mxnet to ONNX")
    converted_model_path = onnx_mxnet.export_model(sym, params, [input_shape], np.float32, onnx_file)

    sym, arg_params, aux_params = onnx_mxnet.import_model(converted_model_path)

    metadata = onnx_mxnet.get_model_metadata(converted_model_path)
    assert len(metadata) == 2
    assert metadata.get('input_tensor_data')
    assert metadata.get('input_tensor_data')[0][1] == input_shape
    assert metadata.get('output_tensor_data')
    assert metadata.get('output_tensor_data')[0][1] == output_shape
    data_names = [input_name[0] for input_name in metadata.get('input_tensor_data')]

    logging.info("Running inference on onnx re-import model in mxnet")
    # run test for each test file
    for input_data, output_data in zip(inputs, outputs):
        result = forward_pass(sym, arg_params, aux_params, data_names, input_data)

        # verify the results
        npt.assert_equal(result.shape, output_data.shape)
        npt.assert_almost_equal(output_data, result, decimal=3)
    logging.info(model_name + " conversion successful") 
Example 26
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: mxnet_export_test.py    Apache License 2.0 5 votes vote down vote up
def test_model_accuracy(model_name, input_shape):
    """ Imports ONNX model, runs inference, exports and imports back
        run inference, compare result with the previous inference result"""
    model_path, inputs, outputs = get_test_files(model_name)
    logging.info("Translating model from ONNX model zoo to Mxnet")
    sym, arg_params, aux_params = onnx_mxnet.import_model(model_path)

    metadata = onnx_mxnet.get_model_metadata(model_path)
    data_names = [input_name[0] for input_name in metadata.get('input_tensor_data')]

    expected_result= []
    for input_data, output_data in zip(inputs, outputs):
        result = forward_pass(sym, arg_params, aux_params, data_names, input_data)
        expected_result.append(result)

    params = {}
    params.update(arg_params)
    params.update(aux_params)

    dir_path = os.path.dirname(model_path)
    new_model_name = "exported_" + model_name + ".onnx"
    onnx_file = os.path.join(dir_path, new_model_name)

    logging.info("Translating converted model from mxnet to ONNX")
    converted_model_path = onnx_mxnet.export_model(sym, params, [input_shape], np.float32,
                                                   onnx_file)

    sym, arg_params, aux_params = onnx_mxnet.import_model(converted_model_path)

    metadata = onnx_mxnet.get_model_metadata(converted_model_path)
    data_names = [input_name[0] for input_name in metadata.get('input_tensor_data')]

    actual_result = []
    for input_data, output_data in zip(inputs, outputs):
        result = forward_pass(sym, arg_params, aux_params, data_names, input_data)
        actual_result.append(result)

    # verify the results
    for expected, actual in zip(expected_result, actual_result):
        npt.assert_equal(expected.shape, actual.shape)
        npt.assert_almost_equal(expected, actual, decimal=3) 
Example 27
Project: stfinv   Author: seismology   File: tests_stream.py    GNU General Public License v3.0 5 votes vote down vote up
def test_filter_bad_waveforms():

    CC = dict()

    tr = obspy.Trace(header={'station': 'AAA',
                             'location': '00'})
    st = Stream(traces=tr)
    code = '%s.%s' % (tr.stats.station, tr.stats.location)
    CC[code] = 0.1

    tr = obspy.Trace(header={'station': 'BBB',
                             'location': '00'})
    st.append(tr)
    code = '%s.%s' % (tr.stats.station, tr.stats.location)
    CC[code] = 0.8

    tr = obspy.Trace(header={'station': 'CCC',
                             'location': '00'})
    st.append(tr)
    code = '%s.%s' % (tr.stats.station, tr.stats.location)
    CC[code] = -0.9

    tr = obspy.Trace(header={'station': 'DDD',
                             'location': '00'})
    st.append(tr)
    code = '%s.%s' % (tr.stats.station, tr.stats.location)
    CC[code] = 0.6

    st_filter = st.filter_bad_waveforms(CC=CC, CClim=0.6)

    npt.assert_equal(len(st_filter), 2)
    npt.assert_string_equal(str(st_filter[0].stats.station), 'BBB')
    npt.assert_string_equal(str(st_filter[1].stats.station), 'DDD') 
Example 28
Project: stfinv   Author: seismology   File: tests_stream.py    GNU General Public License v3.0 5 votes vote down vote up
def test_get_synthetics():
    # Try to load 3 stations, out of which 2 are in range for P
    db = instaseis.open_db('syngine://prem_a_20s')
    cat = obspy.read_events('./stfinv/data/virginia.xml')
    st = read('./stfinv/data/dis.II.BFO.00.BHZ')
    st += read('./stfinv/data/dis.GE.DAG..BHZ')
    st += read('./stfinv/data/dis.G.CRZF.00.BHZ')
    st_data, st_syn = st.get_synthetics(db=db, origin=cat[0].origins[0],
                                        out_dir='/tmp')

    npt.assert_equal(len(st_data), 2)
    npt.assert_equal(len(st_syn), 12)

    for istat in range(0, 2):
        channels = ['MPP', 'MRP', 'MRR', 'MRT', 'MTP', 'MTT']
        for channel in channels:
            st_test = st_syn.select(station=st_data[istat].stats.station,
                                    network=st_data[istat].stats.network,
                                    location=st_data[istat].stats.location,
                                    channel=channel)
            npt.assert_equal(len(st_test), 1)

        for tr in st_syn[istat * 6:(istat + 1) * 6]:
            npt.assert_string_equal(str(tr.stats.station),
                                    str(st_data[istat].stats.station))
            npt.assert_string_equal(str(tr.stats.location),
                                    str(st_data[istat].stats.location))
            npt.assert_string_equal(str(tr.stats.network),
                                    str(st_data[istat].stats.network))

            npt.assert_equal(tr.stats.npts, st_data[istat].stats.npts)
            npt.assert_allclose(tr.stats.delta, st_data[istat].stats.delta)
            npt.assert_allclose(float(tr.stats.starttime),
                                float(st_data[istat].stats.starttime)) 
Example 29
Project: geonum   Author: jgliss   File: test_topodata.py    GNU General Public License v3.0 5 votes vote down vote up
def test_srtm():
    acc = tp.SRTMAccess()
    d = acc.get_data(acc._TESTLAT, acc._TESTLON)
    npt.assert_equal(d.data.shape, (2, 2))
    vals = [d.data.std(), d.data.mean(), d.data.min(), d.data.max()]
    
    npt.assert_array_almost_equal(vals, [4.0, 857.0, 853.0, 861.0]) 
Example 30
Project: sklearn-xarray   Author: phausamann   File: test_utils.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_convert_to_ndarray():

    from collections import OrderedDict

    X_ds = xr.Dataset(
        OrderedDict([
            ('var_1', (['sample', 'feature'], np.random.random((100, 10)))),
            ('var_2', (['sample', 'feature'], np.random.random((100, 10))))]),
        coords={'sample': range(100), 'feature': range(10)}
    )

    X_arr = convert_to_ndarray(X_ds)

    npt.assert_equal(X_arr, np.dstack((X_ds.var_1, X_ds.var_2))) 
Example 31
Project: LaserTOF   Author: kyleuckert   File: test_mem_overlap.py    MIT License 5 votes vote down vote up
def test_diophantine_overflow():
    # Smoke test integer overflow detection
    max_intp = np.iinfo(np.intp).max
    max_int64 = np.iinfo(np.int64).max

    if max_int64 <= max_intp:
        # Check that the algorithm works internally in 128-bit;
        # solving this problem requires large intermediate numbers
        A = (max_int64//2, max_int64//2 - 10)
        U = (max_int64//2, max_int64//2 - 10)
        b = 2*(max_int64//2) - 10

        assert_equal(solve_diophantine(A, U, b), (1, 1)) 
Example 32
Project: LaserTOF   Author: kyleuckert   File: test_mem_overlap.py    MIT License 5 votes vote down vote up
def test_shares_memory_api():
    x = np.zeros([4, 5, 6], dtype=np.int8)

    assert_equal(np.shares_memory(x, x), True)
    assert_equal(np.shares_memory(x, x.copy()), False)

    a = x[:,::2,::3]
    b = x[:,::3,::2]
    assert_equal(np.shares_memory(a, b), True)
    assert_equal(np.shares_memory(a, b, max_work=None), True)
    assert_raises(np.TooHardError, np.shares_memory, a, b, max_work=1)
    assert_raises(np.TooHardError, np.shares_memory, a, b, max_work=long(1)) 
Example 33
Project: LaserTOF   Author: kyleuckert   File: test_extint128.py    MIT License 5 votes vote down vote up
def test_to_128():
    with exc_iter(INT64_VALUES) as it:
        for a, in it:
            b = mt.extint_to_128(a)
            if a != b:
                assert_equal(b, a) 
Example 34
Project: LaserTOF   Author: kyleuckert   File: test_extint128.py    MIT License 5 votes vote down vote up
def test_to_64():
    with exc_iter(INT128_VALUES) as it:
        for a, in it:
            if not (INT64_MIN <= a <= INT64_MAX):
                assert_raises(OverflowError, mt.extint_to_64, a)
            else:
                b = mt.extint_to_64(a)
                if a != b:
                    assert_equal(b, a) 
Example 35
Project: LaserTOF   Author: kyleuckert   File: test_extint128.py    MIT License 5 votes vote down vote up
def test_mul_64_64():
    with exc_iter(INT64_VALUES, INT64_VALUES) as it:
        for a, b in it:
            c = a * b
            d = mt.extint_mul_64_64(a, b)
            if c != d:
                assert_equal(d, c) 
Example 36
Project: LaserTOF   Author: kyleuckert   File: test_extint128.py    MIT License 5 votes vote down vote up
def test_add_128():
    with exc_iter(INT128_VALUES, INT128_VALUES) as it:
        for a, b in it:
            c = a + b
            if not (INT128_MIN <= c <= INT128_MAX):
                assert_raises(OverflowError, mt.extint_add_128, a, b)
            else:
                d = mt.extint_add_128(a, b)
                if c != d:
                    assert_equal(d, c) 
Example 37
Project: LaserTOF   Author: kyleuckert   File: test_extint128.py    MIT License 5 votes vote down vote up
def test_sub_128():
    with exc_iter(INT128_VALUES, INT128_VALUES) as it:
        for a, b in it:
            c = a - b
            if not (INT128_MIN <= c <= INT128_MAX):
                assert_raises(OverflowError, mt.extint_sub_128, a, b)
            else:
                d = mt.extint_sub_128(a, b)
                if c != d:
                    assert_equal(d, c) 
Example 38
Project: LaserTOF   Author: kyleuckert   File: test_extint128.py    MIT License 5 votes vote down vote up
def test_shl_128():
    with exc_iter(INT128_VALUES) as it:
        for a, in it:
            if a < 0:
                b = -(((-a) << 1) & (2**128-1))
            else:
                b = (a << 1) & (2**128-1)
            c = mt.extint_shl_128(a)
            if b != c:
                assert_equal(c, b) 
Example 39
Project: LaserTOF   Author: kyleuckert   File: test_extint128.py    MIT License 5 votes vote down vote up
def test_shr_128():
    with exc_iter(INT128_VALUES) as it:
        for a, in it:
            if a < 0:
                b = -((-a) >> 1)
            else:
                b = a >> 1
            c = mt.extint_shr_128(a)
            if b != c:
                assert_equal(c, b) 
Example 40
Project: LaserTOF   Author: kyleuckert   File: test_extint128.py    MIT License 5 votes vote down vote up
def test_gt_128():
    with exc_iter(INT128_VALUES, INT128_VALUES) as it:
        for a, b in it:
            c = a > b
            d = mt.extint_gt_128(a, b)
            if c != d:
                assert_equal(d, c) 
Example 41
Project: LaserTOF   Author: kyleuckert   File: test_extint128.py    MIT License 5 votes vote down vote up
def test_floordiv_128_64():
    with exc_iter(INT128_VALUES, INT64_POS_VALUES) as it:
        for a, b in it:
            c = a // b
            d = mt.extint_floordiv_128_64(a, b)

            if c != d:
                assert_equal(d, c) 
Example 42
Project: LaserTOF   Author: kyleuckert   File: test_doccer.py    MIT License 5 votes vote down vote up
def test_unindent():
    yield assert_equal, doccer.unindent_string(param_doc1), param_doc1
    yield assert_equal, doccer.unindent_string(param_doc2), param_doc2
    yield assert_equal, doccer.unindent_string(param_doc3), param_doc1 
Example 43
Project: LaserTOF   Author: kyleuckert   File: test_doccer.py    MIT License 5 votes vote down vote up
def test_unindent_dict():
    d2 = doccer.unindent_dict(doc_dict)
    yield assert_equal, d2['strtest1'], doc_dict['strtest1']
    yield assert_equal, d2['strtest2'], doc_dict['strtest2']
    yield assert_equal, d2['strtest3'], doc_dict['strtest1'] 
Example 44
Project: LaserTOF   Author: kyleuckert   File: test_doccer.py    MIT License 5 votes vote down vote up
def test_docformat():
    udd = doccer.unindent_dict(doc_dict)
    formatted = doccer.docformat(docstring, udd)
    yield assert_equal, formatted, filled_docstring
    single_doc = 'Single line doc %(strtest1)s'
    formatted = doccer.docformat(single_doc, doc_dict)
    # Note - initial indent of format string does not
    # affect subsequent indent of inserted parameter
    yield assert_equal, formatted, """Single line doc Another test
   with some indent""" 
Example 45
Project: LaserTOF   Author: kyleuckert   File: test_doccer.py    MIT License 5 votes vote down vote up
def test_decorator():
    # with unindentation of parameters
    decorator = doccer.filldoc(doc_dict, True)

    @decorator
    def func():
        """ Docstring
        %(strtest3)s
        """
    yield assert_equal, func.__doc__, """ Docstring
        Another test
           with some indent
        """

    # without unindentation of parameters
    decorator = doccer.filldoc(doc_dict, False)

    @decorator
    def func():
        """ Docstring
        %(strtest3)s
        """
    yield assert_equal, func.__doc__, """ Docstring
            Another test
               with some indent
        """ 
Example 46
Project: LaserTOF   Author: kyleuckert   File: test_doccer.py    MIT License 5 votes vote down vote up
def test_inherit_docstring_from():

    class Foo(object):
        def func(self):
            '''Do something useful.'''
            return

        def func2(self):
            '''Something else.'''

    class Bar(Foo):
        @doccer.inherit_docstring_from(Foo)
        def func(self):
            '''%(super)sABC'''
            return

        @doccer.inherit_docstring_from(Foo)
        def func2(self):
            # No docstring.
            return

    assert_equal(Bar.func.__doc__, Foo.func.__doc__ + 'ABC')
    assert_equal(Bar.func2.__doc__, Foo.func2.__doc__)
    bar = Bar()
    assert_equal(bar.func.__doc__, Foo.func.__doc__ + 'ABC')
    assert_equal(bar.func2.__doc__, Foo.func2.__doc__) 
Example 47
Project: LaserTOF   Author: kyleuckert   File: common_tests.py    MIT License 5 votes vote down vote up
def check_named_args(distfn, x, shape_args, defaults, meths):
    ## Check calling w/ named arguments.

    # check consistency of shapes, numargs and _parse signature
    signature = _getargspec(distfn._parse_args)
    npt.assert_(signature.varargs is None)
    npt.assert_(signature.keywords is None)
    npt.assert_(list(signature.defaults) == list(defaults))

    shape_argnames = signature.args[:-len(defaults)]  # a, b, loc=0, scale=1
    if distfn.shapes:
        shapes_ = distfn.shapes.replace(',', ' ').split()
    else:
        shapes_ = ''
    npt.assert_(len(shapes_) == distfn.numargs)
    npt.assert_(len(shapes_) == len(shape_argnames))

    # check calling w/ named arguments
    shape_args = list(shape_args)

    vals = [meth(x, *shape_args) for meth in meths]
    npt.assert_(np.all(np.isfinite(vals)))

    names, a, k = shape_argnames[:], shape_args[:], {}
    while names:
        k.update({names.pop(): a.pop()})
        v = [meth(x, *a, **k) for meth in meths]
        npt.assert_array_equal(vals, v)
        if 'n' not in k.keys():
            # `n` is first parameter of moment(), so can't be used as named arg
            with warnings.catch_warnings():
                warnings.simplefilter("ignore", UserWarning)
                npt.assert_equal(distfn.moment(1, *a, **k),
                                 distfn.moment(1, *shape_args))

    # unknown arguments should not go through:
    k.update({'kaboom': 42})
    npt.assert_raises(TypeError, distfn.cdf, x, **k) 
Example 48
Project: LaserTOF   Author: kyleuckert   File: common_tests.py    MIT License 5 votes vote down vote up
def check_random_state_property(distfn, args):
    # check the random_state attribute of a distribution *instance*

    # This test fiddles with distfn.random_state. This breaks other tests,
    # hence need to save it and then restore.
    rndm = distfn.random_state

    # baseline: this relies on the global state
    np.random.seed(1234)
    distfn.random_state = None
    r0 = distfn.rvs(*args, size=8)

    # use an explicit instance-level random_state
    distfn.random_state = 1234
    r1 = distfn.rvs(*args, size=8)
    npt.assert_equal(r0, r1)

    distfn.random_state = np.random.RandomState(1234)
    r2 = distfn.rvs(*args, size=8)
    npt.assert_equal(r0, r2)

    # can override the instance-level random_state for an individual .rvs call
    distfn.random_state = 2
    orig_state = distfn.random_state.get_state()

    r3 = distfn.rvs(*args, size=8, random_state=np.random.RandomState(1234))
    npt.assert_equal(r0, r3)

    # ... and that does not alter the instance-level random_state!
    npt.assert_equal(distfn.random_state.get_state(), orig_state)

    # finally, restore the random_state
    distfn.random_state = rndm 
Example 49
Project: LaserTOF   Author: kyleuckert   File: common_tests.py    MIT License 5 votes vote down vote up
def check_rvs_broadcast(distfunc, distname, allargs, shape, shape_only, otype):
    np.random.seed(123)
    sample = distfunc.rvs(*allargs)
    assert_equal(sample.shape, shape, "%s: rvs failed to broadcast" % distname)
    if not shape_only:
        rvs = np.vectorize(lambda *allargs: distfunc.rvs(*allargs), otypes=otype)
        np.random.seed(123)
        expected = rvs(*allargs)
        assert_allclose(sample, expected, rtol=1e-15) 
Example 50
Project: LaserTOF   Author: kyleuckert   File: test_boxcox.py    MIT License 5 votes vote down vote up
def test_boxcox_nonfinite():
    # x < 0  =>  y = nan
    x = np.array([-1, -1, -0.5])
    y = boxcox(x, [0.5, 2.0, -1.5])
    yield assert_equal, y, np.array([np.nan, np.nan, np.nan])

    # x = 0 and lambda <= 0  =>  y = -inf
    x = 0
    y = boxcox(x, [-2.5, 0])
    yield assert_equal, y, np.array([-np.inf, -np.inf])