Python numpy.testing.assert_allclose() Examples

The following are code examples for showing how to use numpy.testing.assert_allclose(). 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: stfinv   Author: seismology   File: tests_inversion.py    GNU General Public License v3.0 8 votes vote down vote up
def test_create_Toeplitz():
    from stfinv.utils.inversion import _create_Toeplitz
    # even length
    d1 = np.array([1., 0., 0., 0., 1., 2., 1., 0., 0., 1])
    d2 = np.array([0., 0., 1., 3., 2., 1., 0., 0., 0., 0])

    G = _create_Toeplitz(d2)
    npt.assert_allclose(np.matmul(G, d1),
                        np.convolve(d1, d2, 'same'),
                        atol=1e-7, rtol=1e-7)

    # odd length
    d1 = np.array([1., 0., 0., 0., 1., 2., 1., 0., 0.])
    d2 = np.array([0., 0., 1., 3., 2., 1., 0., 0., 0.])

    G = _create_Toeplitz(d2)
    npt.assert_allclose(np.matmul(G, d1),
                        np.convolve(d1, d2, 'same'),
                        atol=1e-7, rtol=1e-7) 
Example 2
Project: stfinv   Author: seismology   File: tests_inversion.py    GNU General Public License v3.0 6 votes vote down vote up
def test_invert_STF():
    from stfinv.utils.inversion import invert_STF
    tr = obspy.Trace(data=np.array([0., 0., 0., 0., 1., 2., 1., 0., 0.]))
    st_synth = obspy.Stream(tr)
    tr = obspy.Trace(data=np.array([0., 0., 1., 3., 2., 1., 0., 0., 0.]))
    st_synth.append(tr)

    stf_ref = np.array([0., 0., 1., 1., 0., 1., 1., 0., 0.])

    tr = obspy.Trace(data=np.convolve(st_synth[0].data, stf_ref, 'same'))
    st_data = obspy.Stream(tr)
    tr = obspy.Trace(data=np.convolve(st_synth[1].data, stf_ref, 'same'))
    st_data.append(tr)

    stf = invert_STF(st_data, st_synth)

    halflen = (len(stf) + 1) / 2
    stf = np.r_[stf[halflen:], stf[0:halflen]]

    npt.assert_allclose(stf, stf_ref, rtol=1e-7, atol=1e-10) 
Example 3
Project: stfinv   Author: seismology   File: tests_inversion.py    GNU General Public License v3.0 6 votes vote down vote up
def test_invert_STF_dampened():
    from stfinv.utils.inversion import invert_STF
    tr = obspy.Trace(data=np.array([0., 0., 0., 0., 1., 2., 1., 0., 0.]))
    st_synth = obspy.Stream(tr)
    tr = obspy.Trace(data=np.array([0., 0., 1., 3., 2., 1., 0., 0., 0.]))
    st_synth.append(tr)

    stf_ref = np.array([0., 0., 1., 1., 0., 1., 1., 0., 0.])

    tr = obspy.Trace(data=np.convolve(st_synth[0].data, stf_ref, 'same'))
    st_data = obspy.Stream(tr)
    tr = obspy.Trace(data=np.convolve(st_synth[1].data, stf_ref, 'same'))
    st_data.append(tr)

    stf = invert_STF(st_data, st_synth, method='dampened', eps=1e-4)

    npt.assert_allclose(stf, stf_ref, rtol=1e-2, atol=1e-10) 
Example 4
Project: geonum   Author: jgliss   File: test_base_classes.py    GNU General Public License v3.0 6 votes vote down vote up
def test_diffvector():
    p1 = GeoPoint(lat=37.751005, lon=14.993435, altitude=3264.0,
                  auto_topo_access=False)
    p2 = GeoPoint(37.765755,  15.016696, altitude=2820.0,
                  auto_topo_access=False)
    connection_vector = p2 - p1
    
    assert connection_vector.anchor is p1
    
    actual = [connection_vector.azimuth,
              connection_vector.elevation, 
              connection_vector.magnitude]
    
    
    npt.assert_allclose(actual=actual,
                        desired=[51.378677249653983,
                                 -9.6064174085658465,
                                 2.6606074796318557], rtol=1e-7) 
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_preprocess():

    from sklearn.preprocessing import scale

    X_da = xr.DataArray(
        np.random.random((100, 10)),
        coords={'sample': range(100), 'feature': range(10)},
        dims=('sample', 'feature')
    )

    Xt_da_gt = X_da
    Xt_da_gt.data = scale(X_da)

    Xt_da = preprocess(X_da, scale)

    xrt.assert_allclose(Xt_da, Xt_da_gt)

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

    Xt_ds = preprocess(X_ds, scale)

    xrt.assert_allclose(Xt_ds, X_ds.apply(scale)) 
Example 6
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 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_attributes(self):

        estimator = wrap(StandardScaler())

        # check pass-through wrapper
        estimator.fit(self.X.var_2d.values)
        npt.assert_allclose(estimator.mean_, estimator.estimator_.mean_)

        # check DataArray wrapper
        estimator.fit(self.X.var_2d)
        npt.assert_allclose(estimator.mean_, estimator.estimator_.mean_)

        # check Dataset wrapper
        estimator.fit(self.X.var_2d.to_dataset())
        npt.assert_allclose(estimator.mean_['var_2d'],
                            estimator.estimator_dict_['var_2d'].mean_) 
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_wrapped_transformer(self):

        estimator = wrap(StandardScaler())

        # test DataArray
        X_da = self.X.var_2d

        estimator.partial_fit(X_da)

        assert_allclose(
            X_da, estimator.inverse_transform(estimator.transform(X_da)))

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

        estimator.fit(X_ds)

        assert_allclose(
            X_ds, estimator.inverse_transform(estimator.transform(X_ds))) 
Example 9
Project: pyplis   Author: jgliss   File: test_highlevel_examples.py    GNU General Public License v3.0 6 votes vote down vote up
def test_optflow(plume_img, plume_img_next, line):
    """Test optical flow calculation."""
    flow = pyplis.OptflowFarneback()
    flow.set_images(plume_img, plume_img_next)
    flow.calc_flow()
    len_img = flow.get_flow_vector_length_img()
    angle_img = flow.get_flow_orientation_img()
    l = line.convert(plume_img.pyrlevel)
    res = flow.local_flow_params(line=l, dir_multi_gauss=False)
    nominal = [0.658797,
               -41.952854,
               -65.971787,
               22.437565,
               0.128414,
               0.086898,
               28.07,
               0.518644]
    vals = [len_img.mean(),
            angle_img.mean(), res["_dir_mu"],
            res["_dir_sigma"], res["_len_mu_norm"],
            res["_len_sigma_norm"], res["_del_t"],
            res["_significance"]]
    npt.assert_allclose(vals, nominal, rtol=1e-5)
    return flow 
Example 10
Project: pyplis   Author: jgliss   File: ex06_doas_calib.py    GNU General Public License v3.0 6 votes vote down vote up
def test_calib_pears_init(calib):
    calib.fit_calib_data(polyorder=1)
    cc = pyplis.helpers.get_img_maximum(calib.fov.corr_img.img)
    assert cc == (124, 159), cc

    pyrl = calib.fov.pyrlevel
    assert pyrl == 2, pyrl
    res_dict = calib.fov.result_pearson
    npt.assert_allclose([res_dict['rad_rel'],
                         np.max(100 * res_dict['corr_curve'].values)],
                        [3, 95], atol=1)

    fov_ext = calib.fov.pixel_extend(abs_coords=True)
    (fov_x, fov_y) = calib.fov.pixel_position_center(abs_coords=True)

    npt.assert_allclose([fov_ext, fov_x, fov_y],
                        [res_dict['rad_rel'] * 2**pyrl, 636, 496], atol=1)

    npt.assert_allclose(calib.calib_coeffs,
                        [8.58e+18, 2.71e+17], rtol=1e-1) 
Example 11
Project: pyplis   Author: jgliss   File: ex06_doas_calib.py    GNU General Public License v3.0 6 votes vote down vote up
def test_calib_pears_fine(calib):
    cc = pyplis.helpers.get_img_maximum(calib.fov.corr_img.img)
    npt.assert_allclose((186, 180), cc, atol=1)

    pyrl = calib.fov.pyrlevel
    assert pyrl == 0, pyrl
    res_dict = calib.fov.result_pearson
    npt.assert_allclose([res_dict['rad_rel'],
                         np.max(100 * res_dict['corr_curve'].values)],
                        [6, 95], atol=1)

    fov_ext = calib.fov.pixel_extend(abs_coords=True)
    (fov_x, fov_y) = calib.fov.pixel_position_center(abs_coords=True)

    npt.assert_allclose([fov_ext, fov_x, fov_y],
                        [6, 630, 493], atol=1)

    npt.assert_allclose(calib.calib_coeffs,
                        [8.38e+18, 2.92e+17], rtol=1e-1) 
Example 12
Project: pyplis   Author: jgliss   File: ex06_doas_calib.py    GNU General Public License v3.0 6 votes vote down vote up
def test_calib_ifr(calib):
    cc = pyplis.helpers.get_img_maximum(calib.fov.corr_img.img)
    npt.assert_allclose((123, 157), cc, atol=1)

    pyrl = calib.fov.pyrlevel
    assert pyrl == 2, pyrl
    npt.assert_allclose(calib.fov.result_ifr['popt'][1:5],
                        [158.6, 122.9, 15.4, 1.5], rtol=1e-1)

    (fov_x, fov_y) = calib.fov.pixel_position_center(abs_coords=True)

    npt.assert_allclose([fov_x, fov_y, calib_ifr.fov.sigma_x_abs,
                         calib_ifr.fov.sigma_y_abs],
                        [635, 492, 61.5, 41.6], atol=2)

    npt.assert_allclose(calib.calib_coeffs,
                        [9.38e+18, 1.75e+17], rtol=1e-1)


# SCRIPT MAIN FUNCTION 
Example 13
Project: LaserTOF   Author: kyleuckert   File: common_tests.py    MIT License 6 votes vote down vote up
def check_normalization(distfn, args, distname):
    norm_moment = distfn.moment(0, *args)
    npt.assert_allclose(norm_moment, 1.0)

    # this is a temporary plug: either ncf or expect is problematic;
    # best be marked as a knownfail, but I've no clue how to do it.
    if distname == "ncf":
        atol, rtol = 1e-5, 0
    else:
        atol, rtol = 1e-7, 1e-7

    normalization_expect = distfn.expect(lambda x: 1, args=args)
    npt.assert_allclose(normalization_expect, 1.0, atol=atol, rtol=rtol,
            err_msg=distname, verbose=True)

    normalization_cdf = distfn.cdf(distfn.b, *args)
    npt.assert_allclose(normalization_cdf, 1.0) 
Example 14
Project: CLMM   Author: LSSTDESC   File: test_polaraveraging.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_compute_tangential_shear():
    shear1, shear2, phi = 0.15, 0.08, 0.52
    expected_tangential_shear = -0.14492537676438383
    tangential_shear = pa._compute_tangential_shear(shear1, shear2, phi)
    testing.assert_allclose(tangential_shear, expected_tangential_shear)

    shear1 = np.array([0.15, 0.40])
    shear2 = np.array([0.08, 0.30])
    phi = np.array([0.52, 1.23])
    expected_tangential_shear = [-0.14492537676438383, 0.1216189244145496]
    tangential_shear = pa._compute_tangential_shear(shear1, shear2, phi)
    testing.assert_allclose(tangential_shear, expected_tangential_shear)

    # test for reasonable values
    testing.assert_almost_equal(pa._compute_tangential_shear(100., 0., 0.), -100.0)
    testing.assert_almost_equal(pa._compute_tangential_shear(0., 100., np.pi/4.), -100.0)
    testing.assert_almost_equal(pa._compute_tangential_shear(0., 0., 0.3), 0.) 
Example 15
Project: CLMM   Author: LSSTDESC   File: test_modeling_physical_validation.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_get_da():
    """
    Test physical values of Da
    """
    cf = load_validation_config()
    tst.assert_allclose(cf.TEST_CASE['dl'],
                        get_angular_diameter_distance_a(cf.cosmo_ccl,
                                                        cf.TEST_CASE['aexp_cluster']),
                        1e-10)
    tst.assert_allclose(cf.TEST_CASE['ds'],
                        get_angular_diameter_distance_a(cf.cosmo_ccl,
                                                        cf.TEST_CASE['aexp_source']),
                        1e-10)
    tst.assert_allclose(cf.TEST_CASE['dsl'],
                        get_angular_diameter_distance_a(cf.cosmo_ccl,
                                                        cf.TEST_CASE['aexp_source'],
                                                        cf.TEST_CASE['aexp_cluster']),
                        1e-10) 
Example 16
Project: indigo   Author: mbdriscoll   File: test_compat.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_compat_Interp(backend, X, Y, Z, RO, PS, K, n, width):
    pymr = pytest.importorskip('pymr')
    b = backend()

    N = (X, Y, Z, K)
    M = (1, RO, PS, K)
    T = (3, RO, PS)

    import scipy.signal as signal
    beta = 0.1234
    kb = signal.kaiser(2 * n + 1, beta)[n:]

    x = indigo.util.rand64c(*N)
    traj = indigo.util.rand64c(*T).real - 0.5

    G0 = pymr.linop.Interp(M, N, traj, width, kb, dtype=x.dtype)
    y_exp = G0 * pymr.util.vec(x)

    G1 = b.Interp(N[:3], traj, width, kb, dtype=x.dtype)
    y_act = G1 * x.reshape((-1,K), order='F')

    y_act = y_act.flatten(order='F')
    npt.assert_allclose( y_act, y_exp, rtol=1e-2) 
Example 17
Project: indigo   Author: mbdriscoll   File: test_compat.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_compat_conjgrad(backend, N):
    pymr = pytest.importorskip('pymr')
    b = backend()

    A = indigo.util.randM( N, N, 0.5 )
    A = A.H @ A # make positive definite
    y = indigo.util.rand64c( N )
    x0 = np.zeros( N, dtype=np.complex64 )

    A_pmr = pymr.linop.Matrix( A.toarray(), dtype=A.dtype )
    x_exp = pymr.alg.cg(A_pmr, A.H * y, x0, maxiter=40)

    A_indigo = b.SpMatrix(A)
    b.cg(A_indigo, y, x0, maxiter=40)
    x_act = x0.copy()

    npt.assert_allclose(x_act, x_exp, rtol=1e-6) 
Example 18
Project: xrft   Author: xgcm   File: test_xrft.py    MIT License 5 votes vote down vote up
def test_dft_1d(self, test_data_1d):
        """Test the discrete Fourier transform function on one-dimensional data."""

        da = test_data_1d
        Nx = len(da)
        dx = float(da.x[1] - da.x[0]) if 'x' in da.dims else 1

        # defaults with no keyword args
        ft = xrft.dft(da, detrend='constant')
        # check that the frequency dimension was created properly
        assert ft.dims == ('freq_x',)
        # check that the coords are correct
        freq_x_expected = np.fft.fftshift(np.fft.fftfreq(Nx, dx))
        npt.assert_allclose(ft['freq_x'], freq_x_expected)
        # check that a spacing variable was created
        assert ft['freq_x_spacing'] == freq_x_expected[1] - freq_x_expected[0]
        # make sure the function is lazy
        assert isinstance(ft.data, type(da.data))
        # check that the Fourier transform itself is correct
        data = (da - da.mean()).values
        ft_data_expected = np.fft.fftshift(np.fft.fft(data))
        # because the zero frequency component is zero, there is a numerical
        # precision issue. Fixed by setting atol
        npt.assert_allclose(ft_data_expected, ft.values, atol=1e-14)


        # redo without removing mean
        ft = xrft.dft(da)
        ft_data_expected = np.fft.fftshift(np.fft.fft(da))
        npt.assert_allclose(ft_data_expected, ft.values)

        # redo with detrending linear least-square fit
        ft = xrft.dft(da, detrend='linear')
        da_prime = sps.detrend(da.values)
        ft_data_expected = np.fft.fftshift(np.fft.fft(da_prime))
        npt.assert_allclose(ft_data_expected, ft.values, atol=1e-14)

        if 'x' in da and not da.chunks:
            da['x'].values[-1] *= 2
            with pytest.raises(ValueError):
                ft = xrft.dft(da) 
Example 19
Project: xrft   Author: xgcm   File: test_xrft.py    MIT License 5 votes vote down vote up
def test_dft_1d_time(self):
        """Test the discrete Fourier transform function on timeseries data."""
        time = pd.date_range('2000-01-01', '2001-01-01', closed='left')
        Nt = len(time)
        da = xr.DataArray(np.random.rand(Nt), coords=[time], dims=['time'])

        ft = xrft.dft(da)

        # check that frequencies are correct
        dt = (time[1] - time[0]).total_seconds()
        freq_time_expected = np.fft.fftshift(np.fft.fftfreq(Nt, dt))
        npt.assert_allclose(ft['freq_time'], freq_time_expected) 
Example 20
Project: xrft   Author: xgcm   File: test_xrft.py    MIT License 5 votes vote down vote up
def test_dft_real_1d(self, test_data_1d):
        """
        Test the discrete Fourier transform function on one-dimensional data.
        """
        da = test_data_1d
        Nx = len(da)
        dx = float(da.x[1] - da.x[0]) if 'x' in da.dims else 1

        # defaults with no keyword args
        ft = xrft.dft(da, real='x', detrend='constant')
        # check that the frequency dimension was created properly
        assert ft.dims == ('freq_x',)
        # check that the coords are correct
        freq_x_expected = np.fft.rfftfreq(Nx, dx)
        npt.assert_allclose(ft['freq_x'], freq_x_expected)
        # check that a spacing variable was created
        assert ft['freq_x_spacing'] == freq_x_expected[1] - freq_x_expected[0]
        # make sure the function is lazy
        assert isinstance(ft.data, type(da.data))
        # check that the Fourier transform itself is correct
        data = (da - da.mean()).values
        ft_data_expected = np.fft.rfft(data)
        # because the zero frequency component is zero, there is a numerical
        # precision issue. Fixed by setting atol
        npt.assert_allclose(ft_data_expected, ft.values, atol=1e-14)

        with pytest.raises(ValueError):
            xrft.dft(da, real='y', detrend='constant') 
Example 21
Project: xrft   Author: xgcm   File: test_xrft.py    MIT License 5 votes vote down vote up
def test_isotropic_ps_slope(N=512, dL=1., amp=1e1, s=-3.):
    """Test the spectral slope of isotropic power spectrum."""

    theta = xr.DataArray(_synthetic_field(N, dL, amp, s),
                        dims=['y', 'x'],
                        coords={'y':range(N), 'x':range(N)})
    iso_ps = xrft.isotropic_powerspectrum(theta, detrend='constant',
                                         density=True)
    npt.assert_almost_equal(np.ma.masked_invalid(iso_ps[1:]).mask.sum(), 0.)
    y_fit, a, b = xrft.fit_loglog(iso_ps.freq_r.values[4:],
                                 iso_ps.values[4:])

    npt.assert_allclose(a, s, atol=.1) 
Example 22
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: test_contrib_krprod.py    Apache License 2.0 5 votes vote down vote up
def assert_mx_allclose(A, B, **kwds):
    return assert_allclose(A.asnumpy(), B.asnumpy(), **kwds) 
Example 23
Project: stfinv   Author: seismology   File: tests_inversion.py    GNU General Public License v3.0 5 votes vote down vote up
def test_create_Toeplitz_mult():
    from stfinv.utils.inversion import _create_Toeplitz_mult
    tr = obspy.Trace(data=np.array([0., 0., 0., 0., 1., 2., 1., 0., 0.]))
    st = obspy.Stream(tr)
    tr = obspy.Trace(data=np.array([0., 0., 1., 3., 2., 1., 0., 0., 0.]))
    st.append(tr)

    d = np.array([0., 0., 1., 1., 2., 1., 1., 0., 0.])
    G = _create_Toeplitz_mult(st)

    ref = [np.convolve(st[0].data, d, 'same'),
           np.convolve(st[1].data, d, 'same')]
    res = np.matmul(G, d).reshape(2, 9)
    npt.assert_allclose(ref, res, atol=1e-7, rtol=1e-7) 
Example 24
Project: stfinv   Author: seismology   File: tests_stream.py    GNU General Public License v3.0 5 votes vote down vote up
def test_get_station_coordinates():

    st = read('./stfinv/data/data_wo_information.mseed')
    inv = obspy.read_inventory('./stfinv/data/some_stations.xml')

    st.get_station_coordinates()
    for tr in st:
        stats = tr.stats
        stat = inv.select(network=stats.network,
                          station=stats.station,
                          location=stats.location,
                          channel=stats.channel)[0][0]
        npt.assert_allclose(stat.longitude, stats.sac['stlo'], atol=1e-2)
        npt.assert_allclose(stat.latitude, stats.sac['stla'], atol=1e-2) 
Example 25
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 26
Project: stfinv   Author: seismology   File: tests_stream.py    GNU General Public License v3.0 5 votes vote down vote up
def test_shift_waveform():

    data_test = [0, 0, 1, 2, 1, 0, 0]
    tr_test = obspy.Trace(np.array(data_test),
                          header=dict(station='AAA',
                                      location='00',
                                      delta=0.1))
    st_ref = Stream(tr_test)
    tr_test = obspy.Trace(np.array(data_test),
                          header=dict(station='BBB',
                                      location='00',
                                      delta=0.1))
    st_ref.append(tr_test)

    dt = dict()
    dt['AAA.00'] = 0.2
    dt['BBB.00'] = -0.1
    st_shift = st_ref.copy()
    st_shift.shift_waveform(dt)

    # Shift backwards by 0.2 s
    data_ref = [0, 0, 0, 0, 1, 2, 1]
    npt.assert_allclose(st_shift.select(station='AAA')[0].data,
                        data_ref,
                        rtol=1e-5, atol=1e-3,
                        err_msg='Shifted data not as expected')

    # Shift forwards by 0.1 s
    data_ref = [0, 1, 2, 1, 0, 0, 0]
    npt.assert_allclose(st_shift.select(station='BBB')[0].data,
                        data_ref, rtol=1e-5, atol=1e-3,
                        err_msg='Shifted data not as expected') 
Example 27
Project: stfinv   Author: seismology   File: tests_stream.py    GNU General Public License v3.0 5 votes vote down vote up
def test_calc_timeshift():

    data_test = [0, 0, 1, 2, 1, 0, 0]
    tr_test = obspy.Trace(np.array(data_test),
                          header=dict(station='AAA',
                                      location='00',
                                      delta=0.1))
    st_ref = Stream(tr_test)
    tr_test = obspy.Trace(np.array(data_test),
                          header=dict(station='BBB',
                                      location='00',
                                      delta=0.1))
    st_ref.append(tr_test)

    # Shift backwards by 0.2 s
    dt = dict()
    dt['AAA.00'] = 0.2
    dt['BBB.00'] = -0.1
    st_shift = st_ref.copy()
    st_shift.shift_waveform(dt)
    dt_res, CC = st_shift.calc_timeshift(st_ref)

    npt.assert_allclose(dt_res['AAA.00'], dt['AAA.00'], rtol=1e-5)
    npt.assert_allclose(dt_res['BBB.00'], dt['BBB.00'], rtol=1e-5)

    # Shift backwards by 0.2 s, reverse order of traces in stream
    dt = dict()
    dt['AAA.00'] = 0.2
    dt['BBB.00'] = -0.1
    st_shift = st_ref.copy()
    st_shift.shift_waveform(dt)
    st_shift.sort(keys=['station'], reverse=True)
    dt_res, CC = st_shift.calc_timeshift(st_ref)

    npt.assert_allclose(dt_res['AAA.00'], dt['AAA.00'], rtol=1e-5)
    npt.assert_allclose(dt_res['BBB.00'], dt['BBB.00'], rtol=1e-5) 
Example 28
Project: sklearn-xarray   Author: phausamann   File: test_preprocessing.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_transpose():

    # test on DataArray
    X_da = xr.DataArray(
        np.random.random((100, 10)),
        coords={'sample': range(100), 'feature': range(10)},
        dims=('sample', 'feature')
    )

    Xt_da, estimator = transpose(
        X_da, order=['feature', 'sample'], return_estimator=True)

    xrt.assert_allclose(Xt_da, X_da.transpose())

    Xt_da = estimator.inverse_transform(Xt_da)

    xrt.assert_allclose(Xt_da, X_da)

    # test on Dataset with subset of dimensions
    X_ds = xr.Dataset(
        {'var_1': (['sample', 'feat_1', 'feat_2'],
                   np.random.random((100, 10, 5))),
         'var_2': (['feat_2', 'sample'],
                   np.random.random((5, 100)))},
        coords={'sample': range(100), 'feat_1': range(10), 'feat_2': range(5)}
    )

    Xt_ds, estimator = transpose(
        X_ds, order=['sample', 'feat_2'], return_estimator=True)

    xrt.assert_allclose(Xt_ds, X_ds.transpose('sample', 'feat_1', 'feat_2'))

    Xt_ds = estimator.inverse_transform(Xt_ds)

    xrt.assert_allclose(Xt_ds, X_ds) 
Example 29
Project: sklearn-xarray   Author: phausamann   File: test_preprocessing.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_split():

    # test on DataArray with number of samples multiple of new length
    X_da = xr.DataArray(
        np.random.random((100, 10)),
        coords={'sample': range(100), 'feature': range(10),
                'coord_1': (['sample', 'feature'],
                            np.tile('Test', (100, 10)))},
        dims=('sample', 'feature')
    )

    estimator = Splitter(
        new_dim='split_sample', new_len=5, reduce_index='subsample', axis=1,
        keep_coords_as='sample_coord'
    )

    Xt_da = estimator.fit_transform(X_da)

    assert Xt_da.shape == (20, 5, 10)
    npt.assert_allclose(Xt_da[0, :, 0], X_da[:5, 0])

    Xit_da = estimator.inverse_transform(Xt_da)

    xrt.assert_allclose(X_da, Xit_da)

    # test on Dataset with number of samples NOT multiple of new length
    X_ds = xr.Dataset(
        {'var_1': (['sample', 'feature'], np.random.random((100, 10)))},
        coords={'sample': range(100), 'feature': range(10)}
    )

    Xt_ds = split(
        X_ds, new_dim='split_sample', new_len=7, reduce_index='head',
        axis=1, new_index_func=None
    )

    assert Xt_ds['var_1'].shape == (14, 7, 10)
    npt.assert_allclose(Xt_ds.var_1[0, :, 0], X_ds.var_1[:7, 0]) 
Example 30
Project: sklearn-xarray   Author: phausamann   File: test_preprocessing.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_segment():

    X_da = xr.DataArray(
        np.tile(np.arange(10), (100, 1)),
        coords={'sample': range(100), 'feature': range(10),
                'coord_1': (['sample', 'feature'],
                            np.tile('Test', (100, 10)))},
        dims=('sample', 'feature')
    )

    Xt_da, estimator = segment(
        X_da, new_dim='split_sample', new_len=20, step=5, axis=0,
        reduce_index='subsample', keep_coords_as='backup', return_estimator=True
    )

    assert Xt_da.coord_1.shape == (20, 17, 10)
    npt.assert_allclose(Xt_da[:, 0, 0], X_da[:20, 0])

    Xit_da = estimator.inverse_transform(Xt_da)

    xrt.assert_allclose(Xit_da, X_da)

    X_ds = xr.Dataset({
        'var_1': (['sample', 'feat_1', 'feat_2'],
                  np.tile(np.arange(10), (100, 10, 1))),
        'var_2': (['feat_2'], np.random.random((10,)))},
        coords={'sample': range(100), 'feat_1': range(10), 'feat_2': range(10),
                'coord_1': (['sample', 'feat_1'], np.tile('Test', (100, 10)))}
    )

    Xt_ds, estimator = segment(
        X_ds, new_dim='split_sample', new_len=20, step=5, reduce_index='head',
        keep_coords_as='backup', return_estimator=True
    )

    assert Xt_ds.var_1.shape == (17, 10, 10, 20)
    npt.assert_allclose(Xt_ds.var_1[0, 0, 0, :], X_ds.var_1[:20, 0, 0])

    xrt.assert_allclose(estimator.inverse_transform(Xt_ds), X_ds) 
Example 31
Project: sklearn-xarray   Author: phausamann   File: test_preprocessing.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_reduce():

    X_da = xr.DataArray(
        np.random.random((100, 10)),
        coords={'sample': range(100), 'feature': range(10)},
        dims=('sample', 'feature')
    )

    Xt_da = reduce(X_da)

    xrt.assert_allclose(Xt_da, X_da.reduce(np.linalg.norm, dim='feature')) 
Example 32
Project: sklearn-xarray   Author: phausamann   File: test_common.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_reshaping_estimator(self):

        estimator = wrap(
            ReshapingEstimator(new_shape=(-1, 2)),
            reshapes='feat_1'
        )

        # test DataArray
        X_da = self.X.var_2d

        y = X_da[:, :2].drop('feat_1')
        y['dummy'] = y.dummy[:, 0]

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

        assert_allclose(yp, y)

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

        y = X_ds.var_2d[:, :2].drop('feat_1')
        y['dummy'] = y.dummy[:, 0]

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

        assert_allclose(yp, y) 
Example 33
Project: sklearn-xarray   Author: phausamann   File: test_common.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_reshaping_transformer(self):

        estimator = wrap(
            ReshapingEstimator(new_shape=(-1, 2)),
            reshapes='feat_1'
        )

        # test DataArray
        X_da = self.X.var_3d

        y = X_da[:, :2].drop('feat_1')
        y['dummy'] = y.dummy[:, 0]

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

        assert_allclose(yp, y)

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

        y = X_ds.var_2d[:, :2].drop('feat_1')
        y['dummy'] = y.dummy[:, 0]

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

        assert_allclose(yp, y) 
Example 34
Project: sklearn-xarray   Author: phausamann   File: test_common.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_ndim_reshaping_estimator(self):

        estimator = wrap(
            ReshapingEstimator(new_shape=(-1, 5, 0)),
            reshapes={'feature': ['feat_1', 'feat_2']}
        )

        # test DataArray
        X_da = self.X.var_3d

        Xt = X_da[:, :5, 0].drop(
            ['feat_1', 'feat_2']).rename({'feat_1': 'feature'})
        Xt['dummy'] = Xt.dummy[:, 0]

        estimator.fit(X_da)
        Xt_da = estimator.transform(X_da)
        estimator.inverse_transform(Xt_da)

        assert_allclose(Xt_da, Xt)

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

        y = X_ds.var_3d[:, :5, 0].drop(['feat_1', 'feat_2'])
        y = y.rename({'feat_1': 'feature'})
        y['dummy'] = y.dummy[:, 0]

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

        assert_allclose(yp, y) 
Example 35
Project: sklearn-xarray   Author: phausamann   File: test_utils.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_segment_array():

    from sklearn_xarray.utils import segment_array

    arr = np.array([[0, 1, 2, 3],
                    [4, 5, 6, 7],
                    [8, 9, 10, 11],
                    [12, 13, 14, 15]])

    arr_seg_1 = segment_array(arr, axis=1, new_len=3, step=1)
    arr_target_1 = np.array([[[0, 1, 2], [1, 2, 3]],
                             [[4, 5, 6], [5, 6, 7]],
                             [[8, 9, 10], [9, 10, 11]],
                             [[12, 13, 14], [13, 14, 15]]])

    npt.assert_allclose(arr_target_1, arr_seg_1)

    arr_seg_2 = segment_array(arr, axis=1, new_len=2, step=2, new_axis=1)
    arr_target_2 = np.array([[[0, 1], [2, 3]],
                             [[4, 5], [6, 7]],
                             [[8, 9], [10, 11]],
                             [[12, 13], [14, 15]]]).transpose((0, 2, 1))

    npt.assert_allclose(arr_target_2, arr_seg_2)

    arr_seg_3 = segment_array(arr, axis=0, new_len=2, step=1, new_axis=1)
    arr_target_3 = np.array(
        [[[0, 4], [1, 5], [2, 6], [3, 7]],
         [[4, 8], [5, 9], [6, 10], [7, 11]],
         [[8, 12], [9, 13], [10, 14], [11, 15]]]).transpose((0, 2, 1))

    npt.assert_allclose(arr_target_3, arr_seg_3)

    arr_seg_4 = segment_array(arr, axis=1, new_len=3, step=2, new_axis=2)
    arr_target_4 = np.array([[[0, 1, 2]],
                             [[4, 5, 6]],
                             [[8, 9, 10]],
                             [[12, 13, 14]]])

    npt.assert_allclose(arr_target_4, arr_seg_4) 
Example 36
Project: pyplis   Author: jgliss   File: test_highlevel_examples.py    GNU General Public License v3.0 5 votes vote down vote up
def test_setup(setup):
    """Test some properties of the MeasSetup object."""
    s = setup.source
    vals_exact = [setup.save_dir == setup.base_dir,
                  setup.camera.cam_id]
    vals_approx = [sum([sum(x) for x in setup.cell_info_dict.values()]),
                   s.lon + s.lat + s.altitude]

    nominal_exact = [True, "ecII"]
    nominal_approx = [3.798e18, 3381.750]

    npt.assert_array_equal(vals_exact, nominal_exact)
    npt.assert_allclose(vals_approx, nominal_approx, rtol=1e-4) 
Example 37
Project: pyplis   Author: jgliss   File: test_highlevel_examples.py    GNU General Public License v3.0 5 votes vote down vote up
def test_find_viewdir(viewing_direction):
    """Correct viewing direction using location of Etna SE crater."""
    vals = [viewing_direction.cam_azim, viewing_direction.cam_azim_err,
            viewing_direction.cam_elev, viewing_direction.cam_elev_err]
    npt.assert_allclose(actual=vals,
                        desired=[280.21752138146036, 1.0656706289128692,
                                 13.72632050624192, 1.0656684171601736],
                        rtol=1e-7) 
Example 38
Project: pyplis   Author: jgliss   File: test_highlevel_examples.py    GNU General Public License v3.0 5 votes vote down vote up
def test_line(line):
    """Test some features from example retrieval line."""
    n1, n2 = line.normal_vector
    l1 = line.convert(1, [100, 100, 1200, 1024])

    # compute values to be tested
    vals = [line.length(), line.normal_theta, n1, n2,
            l1.length() / line.length(), sum(l1.roi_def)]
    # set nominal values
    nominal = [567, 310.710846671181, -0.7580108737829234, -0.6522419146504225,
               0.5008818342151675, 1212]

    npt.assert_allclose(vals, nominal, rtol=1e-7) 
Example 39
Project: pyplis   Author: jgliss   File: test_highlevel_examples.py    GNU General Public License v3.0 5 votes vote down vote up
def test_geometry(geometry):
    """Test important results from geometrical calculations."""
    res = geometry.compute_all_integration_step_lengths()
    vals = [res[0].mean(), res[1].mean(), res[2].mean()]
    npt.assert_allclose(actual=vals,
                        desired=[2.0292366, 2.0292366, 10909.873],
                        rtol=1e-7) 
Example 40
Project: mmvec   Author: biocore   File: test_method.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_fit(self):
        np.random.seed(1)
        tf.reset_default_graph()
        tf.set_random_seed(0)
        latent_dim = 2
        res_ranks, res_biplot = paired_omics(
            self.microbes, self.metabolites,
            epochs=1000, latent_dim=latent_dim,
            min_feature_count=1, learning_rate=0.1
        )
        res_ranks = clr_inv(res_ranks.T)
        s_r, s_p = spearmanr(np.ravel(res_ranks), np.ravel(self.exp_ranks))

        self.assertGreater(s_r, 0.5)
        self.assertLess(s_p, 1e-2)

        # make sure the biplot is of the correct dimensions
        npt.assert_allclose(
            res_biplot.samples.shape,
            np.array([self.microbes.shape[0], latent_dim]))
        npt.assert_allclose(
            res_biplot.features.shape,
            np.array([self.metabolites.shape[0], latent_dim]))

        # make sure that the biplot has the correct ordering
        self.assertGreater(res_biplot.proportion_explained[0],
                           res_biplot.proportion_explained[1])
        self.assertGreater(res_biplot.eigvals[0],
                           res_biplot.eigvals[1]) 
Example 41
Project: mmvec   Author: biocore   File: test_util.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_split_tables_train_column(self):

        res = split_tables(self.otu_table, self.metabolite_table,
                           metadata=self.metadata, training_column='testing',
                           num_test=10, min_samples=0)

        (train_microbes, test_microbes,
         train_metabolites, test_metabolites) = res

        npt.assert_allclose(train_microbes.shape, np.array([3, 7]))
        npt.assert_allclose(test_microbes.shape, np.array([2, 7]))
        npt.assert_allclose(train_metabolites.shape, np.array([3, 9]))
        npt.assert_allclose(test_metabolites.shape, np.array([2, 9])) 
Example 42
Project: mmvec   Author: biocore   File: test_util.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_split_tables_random(self):
        res = split_tables(self.otu_table, self.metabolite_table,
                           num_test=2, min_samples=0)

        (train_microbes, test_microbes,
         train_metabolites, test_metabolites) = res
        npt.assert_allclose(train_microbes.shape, np.array([3, 7]))
        npt.assert_allclose(test_microbes.shape, np.array([2, 7]))
        npt.assert_allclose(train_metabolites.shape, np.array([3, 9]))
        npt.assert_allclose(test_metabolites.shape, np.array([2, 9])) 
Example 43
Project: mmvec   Author: biocore   File: test_util.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_split_tables_random_filter(self):
        res = split_tables(self.otu_table, self.metabolite_table,
                           num_test=2, min_samples=2)

        (train_microbes, test_microbes,
         train_metabolites, test_metabolites) = res
        npt.assert_allclose(train_microbes.shape, np.array([3, 6]))
        npt.assert_allclose(test_microbes.shape, np.array([2, 6]))
        npt.assert_allclose(train_metabolites.shape, np.array([3, 9]))
        npt.assert_allclose(test_metabolites.shape, np.array([2, 9])) 
Example 44
Project: LaserTOF   Author: kyleuckert   File: common_tests.py    MIT License 5 votes vote down vote up
def check_kurt_expect(distfn, arg, m, v, k, msg):
    if np.isfinite(k):
        m4e = distfn.expect(lambda x: np.power(x-m, 4), arg)
        npt.assert_allclose(m4e, (k + 3.) * np.power(v, 2), atol=1e-5, rtol=1e-5,
                err_msg=msg + ' - kurtosis')
    else:
        npt.assert_(np.isnan(k)) 
Example 45
Project: LaserTOF   Author: kyleuckert   File: common_tests.py    MIT License 5 votes vote down vote up
def check_private_entropy(distfn, args, superclass):
    # compare a generic _entropy with the distribution-specific implementation
    npt.assert_allclose(distfn._entropy(*args),
                        superclass._entropy(distfn, *args)) 
Example 46
Project: LaserTOF   Author: kyleuckert   File: common_tests.py    MIT License 5 votes vote down vote up
def check_cmplx_deriv(distfn, arg):
    # Distributions allow complex arguments.
    def deriv(f, x, *arg):
        x = np.asarray(x)
        h = 1e-10
        return (f(x + h*1j, *arg)/h).imag

    x0 = distfn.ppf([0.25, 0.51, 0.75], *arg)
    x_cast = [x0.astype(tp) for tp in
                        (np.int_, np.float16, np.float32, np.float64)]

    for x in x_cast:
        # casting may have clipped the values, exclude those
        distfn._argcheck(*arg)
        x = x[(distfn.a < x) & (x < distfn.b)]

        pdf, cdf, sf = distfn.pdf(x, *arg), distfn.cdf(x, *arg), distfn.sf(x, *arg)
        assert_allclose(deriv(distfn.cdf, x, *arg), pdf, rtol=1e-5)
        assert_allclose(deriv(distfn.logcdf, x, *arg), pdf/cdf, rtol=1e-5)

        assert_allclose(deriv(distfn.sf, x, *arg), -pdf, rtol=1e-5)
        assert_allclose(deriv(distfn.logsf, x, *arg), -pdf/sf, rtol=1e-5)

        assert_allclose(deriv(distfn.logpdf, x, *arg), 
                        deriv(distfn.pdf, x, *arg) / distfn.pdf(x, *arg),
                        rtol=1e-5) 
Example 47
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 48
Project: LaserTOF   Author: kyleuckert   File: test_discrete_basic.py    MIT License 5 votes vote down vote up
def check_pmf_cdf(distfn, arg, distname):
    if hasattr(distfn, 'xk'):
        index = distfn.xk
    else:
        startind = int(distfn.ppf(0.01, *arg) - 1)
        index = list(range(startind, startind + 10))
    cdfs = distfn.cdf(index, *arg)
    pmfs_cum = distfn.pmf(index, *arg).cumsum()

    atol, rtol = 1e-10, 1e-10
    if distname == 'skellam':    # ncx2 accuracy
        atol, rtol = 1e-5, 1e-5
    npt.assert_allclose(cdfs - cdfs[0], pmfs_cum - pmfs_cum[0],
                        atol=atol, rtol=rtol) 
Example 49
Project: LaserTOF   Author: kyleuckert   File: test_discrete_basic.py    MIT License 5 votes vote down vote up
def check_moment_frozen(distfn, arg, m, k):
    npt.assert_allclose(distfn(*arg).moment(k), m,
                        atol=1e-10, rtol=1e-10) 
Example 50
Project: LaserTOF   Author: kyleuckert   File: test_discrete_basic.py    MIT License 5 votes vote down vote up
def check_oth(distfn, arg, supp, msg):
    # checking other methods of distfn
    npt.assert_allclose(distfn.sf(supp, *arg), 1. - distfn.cdf(supp, *arg),
                        atol=1e-10, rtol=1e-10)

    q = np.linspace(0.01, 0.99, 20)
    npt.assert_allclose(distfn.isf(q, *arg), distfn.ppf(1. - q, *arg),
                        atol=1e-10, rtol=1e-10)

    median_sf = distfn.isf(0.5, *arg)
    npt.assert_(distfn.sf(median_sf - 1, *arg) > 0.5)
    npt.assert_(distfn.cdf(median_sf + 1, *arg) > 0.5)