python类assert_almost_equal()的实例源码

test_class_converter.py 文件源码 项目:sdaopt 作者: sgubianpm 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def test_convert_func_calling():
    from benchmark.convert2r import GOClass2RConverter
    count = 0
    notok = 0
    for name, klass in goclass():
        print('Calling function: {0}'.format(name))
        count += 1
        try:
            gocc = GOClass2RConverter(klass)
            #with nostdout():
            res = gocc.fun(gocc.xglob)
            npt.assert_almost_equal(gocc.fglob, res[0], decimal=4)
        except Exception as e:
            print(e)
            notok += 1
            continue
    print("R func call that failed: {0} ratio: {1}".format(notok, (count-notok)*100/count))
test_utilities.py 文件源码 项目:redmapper 作者: erykoff 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def runTest(self):
        """
        This tests the functionality of the redmapper.utilities
        spline against the spline output values from a spline
        implemented in IDL found in RM 6.3.1 DR8.
        """
        # create test data
        # these numbers are from redMaPPer 6.3.1, DR8
        xx = np.array([0.05,0.15,0.25,0.35,0.45,0.60],dtype=np.float64)
        yy = np.array([15.685568,17.980721,18.934799,19.671671,19.796223,20.117981], dtype=np.float64)

        # will want to add error checking and exceptions to CubicSpline

        spl=redmapper.utilities.CubicSpline(xx, yy)
        vals=spl(np.array([0.01, 0.44, 0.55, 0.665]))

        # these numbers are also from redMaPPer 6.3.1, DR8
        testing.assert_almost_equal(vals,np.array([14.648017,19.792828,19.973761,20.301322],dtype=np.float64),decimal=6)
test_utilities.py 文件源码 项目:redmapper 作者: erykoff 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def runTest(self):
        """
        This tests the MStar function found in the utilities
        class at two different decimal levels.
        """
        # make sure invalid raises proper exception
        self.assertRaises(IOError,redmapper.utilities.MStar,'blah','junk')

        # make an SDSS test...
        ms = redmapper.utilities.MStar('sdss','i03')

        mstar = ms([0.1,0.2,0.3,0.4,0.5])
        # test against IDL...
        testing.assert_almost_equal(mstar,np.array([16.2375,17.8500,18.8281,19.5878,20.1751]),decimal=4)
        # and against regressions...
        testing.assert_almost_equal(mstar,np.array([ 16.23748776,  17.85000035,  18.82812871,  19.58783337,  20.17514801]))
test_utils_controversialissues.py 文件源码 项目:cptm 作者: NLeSC 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def test_contrastive_opinions_prob_distr():
    """Verify that the sum of all columns == 1.0 (probability distribution)"""
    params = {
        "inputData": "/home/jvdzwaan/data/tmp/test/*",
        "outDir": "cptm/tests/data/{}",
        "nTopics": 20
    }
    topics = load_topics(params)
    opinions = load_opinions(params)
    nks = load('cptm/tests/data/nks_20.npy')
    co = contrastive_opinions('carrot', topics, opinions, nks)

    s = co.sum(axis=0)

    for v in s:
        yield assert_almost_equal, v, 1.0
test_roadgen3d.py 文件源码 项目:derplearning 作者: John-Ellis 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def test_cart2Spherical(self):
        four_corners3d_mm = np.zeros( (4, 3) )
        four_corners3d_mm[:, 0] = self.four_corners_mm[1, :]
        four_corners3d_mm[:, 1] = -self.four_corners_mm[0, :]
        four_corners3d_mm[:, 2] = self.test0.cam_height

        four_corners_angles = np.zeros( (4, 2) )
        four_corners_angles[:, 1] = [self.test0.cam_arc_x/2, -self.test0.cam_arc_x/2,
                                        -self.test0.cam_arc_x/2, self.test0.cam_arc_x/2 ]
        four_corners_angles[:, 0] = [np.pi/2 - self.test0.cam_vlim_crop_y,
                                     np.pi/2 - self.test0.cam_vlim_crop_y,
                                     np.pi/2 - self.test0.cam_to_ground_arc,
                                     self.test0.cam_tilt_y - self.test0.cam_arc_y]


        npt.assert_almost_equal(self.test0.cart2Spherical(np.array([[1,0,0]]) ), [[1, 0, 0]])
        npt.assert_almost_equal(self.test0.cart2Spherical(
            np.array([[0,0,2]]) ), [[2, np.pi/2, 0]], decimal=4)
        npt.assert_almost_equal(self.test0.cart2Spherical(
            np.array([[0,2,0]]) ), [[2, 0, np.pi/2]], decimal=4)
        npt.assert_almost_equal(self.test0.cart2Spherical( four_corners3d_mm )[:,1:], four_corners_angles, decimal=4)

    #checks to make sure the named function generates the appropriate rotational matrix
test_xrft.py 文件源码 项目:xrft 作者: rabernat 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def test_dft_4d():
    """Test the discrete Fourier transform on 2D data"""
    N = 16
    da = xr.DataArray(np.random.rand(N,N,N,N),
                    dims=['time','z','y','x'],
                    coords={'time':range(N),'z':range(N),
                            'y':range(N),'x':range(N)}
                     )
    ft = xrft.dft(da, shift=False)
    npt.assert_almost_equal(ft.values, np.fft.fftn(da.values))

    with pytest.raises(NotImplementedError):
        xrft.dft(da, detrend='linear')
    with pytest.raises(NotImplementedError):
        xrft.dft(da, dim=['time','y','x'], detrend='linear')

    da_prime = xrft.detrendn(da[:,0].values, [0,1,2]) # cubic detrend over time, y, and x
    npt.assert_almost_equal(xrft.dft(da[:,0].drop('z'),
                                    dim=['time','y','x'],
                                    shift=False, detrend='linear'
                                    ).values,
                            np.fft.fftn(da_prime))
test_xrft.py 文件源码 项目:xrft 作者: rabernat 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def test_dft_3d_dask():
    """Test the discrete Fourier transform on 3D dask array data"""
    N=16
    da = xr.DataArray(np.random.rand(N,N,N), dims=['time','x','y'],
                      coords={'time':range(N),'x':range(N),
                              'y':range(N)}
                     )
    daft = xrft.dft(da.chunk({'time': 1}), dim=['x','y'], shift=False)
    # assert hasattr(daft.data, 'dask')
    npt.assert_almost_equal(daft.values,
                        np.fft.fftn(da.chunk({'time': 1}).values, axes=[1,2])
                           )

    with pytest.raises(ValueError):
        xrft.dft(da.chunk({'time': 1, 'x': 1}), dim=['x'])

    daft = xrft.dft(da.chunk({'x': 1}), dim=['time'],
                    shift=False, detrend='linear')
    # assert hasattr(daft.data, 'dask')
    da_prime = sps.detrend(da.chunk({'x': 1}), axis=0)
    npt.assert_almost_equal(daft.values,
                        np.fft.fftn(da_prime, axes=[0])
                           )
test_xrft.py 文件源码 项目:xrft 作者: rabernat 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def test_power_spectrum_dask():
    """Test the power spectrum function on dask data"""
    N = 16
    dim = ['x','y']
    da = xr.DataArray(np.random.rand(2,N,N), dims=['time','x','y'],
                      coords={'time':range(2),'x':range(N),
                              'y':range(N)}).chunk({'time': 1}
                     )
    ps = xrft.power_spectrum(da, dim=dim, density=False)
    daft = xrft.dft(da, dim=['x','y'])
    npt.assert_almost_equal(ps.values, (daft * np.conj(daft)).real.values)

    ps = xrft.power_spectrum(da, dim=dim, window=True, detrend='constant')
    daft = xrft.dft(da, dim=dim, window=True, detrend='constant')
    coord = list(daft.coords)
    test = (daft * np.conj(daft)).real/N**4
    for i in dim:
        test /= daft['freq_' + i + '_spacing']
    npt.assert_almost_equal(ps.values, test)
    npt.assert_almost_equal(np.ma.masked_invalid(ps).mask.sum(), 0.)
test_gaussian_components_diag.py 文件源码 项目:segmentalist 作者: kamperh 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def test_log_prod_students_t():

    np.random.seed(1)

    # Prior
    D = 10
    m_0 = 5*np.random.rand(D) - 2
    k_0 = np.random.randint(15)
    v_0 = D + np.random.randint(5)
    S_0 = 2*np.random.rand(D) + 3
    prior = NIW(m_0=m_0, k_0=k_0, v_0=v_0, S_0=S_0)

    # GMM we will use to access `_log_prod_students_t`
    x = 3*np.random.rand(D) + 4
    gmm = GaussianComponentsDiag(np.array([x]), prior)

    expected_prior = np.sum(
        [students_t(x[i], m_0[i], S_0[i]*(k_0 + 1)/(k_0 * v_0), v_0) for i in range(len(x))]
        )

    npt.assert_almost_equal(gmm.log_prior(0), expected_prior)
test_bigram_lms.py 文件源码 项目:segmentalist 作者: kamperh 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def test_bigram_smooth_lm():
    intrp_lambda = 0.1
    a = 1.
    b = 2.
    K = 5.
    lm = BigramSmoothLM(intrp_lambda, a, b, K)
    data = [
        [1, 1, 3, 4, 0],
        [4, 4],
        [1, 0, 2, 2, 2, 2, 3, 1],
        [3, 3, 1]
        ]
    lm.counts_from_data(data)
    npt.assert_almost_equal(
        lm.prob_i_given_j(1, 3),
        intrp_lambda * lm.prob_i(1) + (1 - intrp_lambda) * (2. + b/K) / (4 + b)
        )
    npt.assert_almost_equal(lm.prob_i(1), (5. + a/K) / (18 + a))
test_bigram_lms.py 文件源码 项目:segmentalist 作者: kamperh 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def test_bigram_smooth_lm_vecs():
    intrp_lambda = 0.1
    a = 1.
    b = 2.
    K = 5.
    lm = BigramSmoothLM(intrp_lambda, a, b, K)
    data = [
        [1, 1, 3, 4, 0],
        [4, 4],
        [1, 0, 2, 2, 2, 2, 3, 1],
        [3, 3, 1]
        ]
    lm.counts_from_data(data)
    prob_vec_i = lm.prob_vec_i()
    for i in range(5):
        assert prob_vec_i[i] == lm.prob_i(i)
    j = 3
    prob_vec_given_j = lm.prob_vec_given_j(j)
    for i in range(5):
        npt.assert_almost_equal(prob_vec_given_j[i], lm.prob_i_given_j(i, j))
test_bigram_lms.py 文件源码 项目:segmentalist 作者: kamperh 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def test_bigram_smooth_lm_log_vecs():
    intrp_lambda = 0.1
    a = 1.
    b = 2.
    K = 5.
    lm = BigramSmoothLM(intrp_lambda, a, b, K)
    data = [
        [1, 1, 3, 4, 0],
        [4, 4],
        [1, 0, 2, 2, 2, 2, 3, 1],
        [3, 3, 1]
        ]
    lm.counts_from_data(data)
    log_prob_vec_i = lm.log_prob_vec_i()
    for i in range(5):
        npt.assert_almost_equal(log_prob_vec_i[i], np.log(lm.prob_i(i)))
    j = 3
    log_prob_vec_given_j = lm.log_prob_vec_given_j(j)
    for i in range(5):
        npt.assert_almost_equal(log_prob_vec_given_j[i], np.log(lm.prob_i_given_j(i, j)))
test_gaussian_components_fixedvar.py 文件源码 项目:segmentalist 作者: kamperh 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def test_log_post_pred():

    np.random.seed(1)

    # Generate data
    X = np.random.rand(11, 10)
    N, D = X.shape

    # Prior
    var = 1*np.random.rand(D)
    mu_0 = 5*np.random.rand(D) - 2
    var_0 = 2*np.random.rand(D)
    prior = FixedVarPrior(var, mu_0, var_0)

    # Setup GMM
    assignments = [0, 0, 0, 1, 0, 1, 3, 4, 3, 2, -1]
    gmm = GaussianComponentsFixedVar(X, prior, assignments=assignments, K_max=X.shape[0])
    expected_log_post_pred = log_post_pred_unvectorized(gmm, 10)

    npt.assert_almost_equal(gmm.log_post_pred(10), expected_log_post_pred)
test_batch_kmeans.py 文件源码 项目:megamix 作者: 14thibea 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def test_step_E(self):
        points = np.random.randn(self.n_points,self.dim)
        KM = Kmeans(self.n_components)
        KM._initialize(points)

        expected_assignements = np.zeros((self.n_points,self.n_components))
        M = dist_matrix(points,KM.means)
        for i in range(self.n_points):
            index_min = np.argmin(M[i]) #the cluster number of the ith point is index_min
            if (isinstance(index_min,np.int64)):
                expected_assignements[i][index_min] = 1
            else: #Happens when two points are equally distant from a cluster mean
                expected_assignements[i][index_min[0]] = 1

        predected_assignements = KM._step_E(points)

        assert_almost_equal(expected_assignements,predected_assignements)
test_batch_kmeans.py 文件源码 项目:megamix 作者: 14thibea 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def test_step_M(self):
        points = np.random.randn(self.n_points,self.dim)
        KM = Kmeans(self.n_components)
        KM._initialize(points)
        assignements = KM._step_E(points)

        expected_means = KM.means.copy()
        for i in range(self.n_components):
            assignements_i = assignements[:,i:i+1]
            n_set = np.sum(assignements_i)
            idx_set,_ = np.where(assignements_i==1)
            sets = points[idx_set]
            if n_set > 0:
                expected_means[i] = np.asarray(np.sum(sets, axis=0)/n_set)


        KM._step_M(points,assignements)

        assert_almost_equal(expected_means,KM.means)
test_streamlines.py 文件源码 项目:pyAFQ 作者: yeatmanlab 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def test_read_write_trk():
    sl = [np.array([[0, 0, 0], [0, 0, 0.5], [0, 0, 1], [0, 0, 1.5]]),
          np.array([[0, 0, 0], [0, 0.5, 0.5], [0, 1, 1]])]

    with nbtmp.InTemporaryDirectory() as tmpdir:
        fname = op.join(tmpdir, 'sl.trk')
        aus.write_trk(fname, sl)
        new_sl = aus.read_trk(fname)
        npt.assert_equal(list(new_sl), sl)

        # What happens if this set of streamlines has some funky affine
        # associated with it?
        aff = np.eye(4) * np.random.rand()
        aff[:3, 3] = np.array([1, 2, 3])
        aff[3, 3] = 1
        # We move the streamlines, and report the inverse of the affine:
        aus.write_trk(fname, move_streamlines(sl, aff),
                      affine=np.linalg.inv(aff))
        # When we read this, we get back what we put in:
        new_sl = aus.read_trk(fname)
        # Compare each streamline:
        for new, old in zip(new_sl, sl):
            npt.assert_almost_equal(new, old, decimal=4)
test_ease2_grid.py 文件源码 项目:ease_grid 作者: TUW-GEO 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def test_EASE2_global_36km():

    test_path = os.path.join(
        os.path.dirname(os.path.abspath(__file__)),
        'test_data')
    test_lat = os.path.join(test_path, 'EASE2_M36km.lats.964x406x1.double')
    test_lon = os.path.join(test_path, 'EASE2_M36km.lons.964x406x1.double')
    egrid = EASE2_grid(36000)
    assert egrid.shape == (406, 964)
    nptest.assert_almost_equal(egrid.x_pixel, egrid.map_scale)
    nptest.assert_almost_equal(egrid.y_pixel, egrid.map_scale)
    nptest.assert_almost_equal(egrid.map_scale, 36032.220840583752)
    lat_should = np.fromfile(test_lat, dtype=np.float64)
    lon_should = np.fromfile(test_lon, dtype=np.float64)
    nptest.assert_almost_equal(egrid.londim,
                               lon_should.reshape((406, 964))[0, :])
    nptest.assert_almost_equal(egrid.latdim,
                               lat_should.reshape((406, 964))[:, 0])
test_ease2_grid.py 文件源码 项目:ease_grid 作者: TUW-GEO 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def test_EASE2_global_25km():

    test_path = os.path.join(
        os.path.dirname(os.path.abspath(__file__)),
        'test_data')
    test_lat = os.path.join(test_path, 'EASE2_M25km.lats.1388x584x1.double')
    test_lon = os.path.join(test_path, 'EASE2_M25km.lons.1388x584x1.double')
    egrid = EASE2_grid(25000, map_scale=25025.2600081)
    assert egrid.shape == (584, 1388)
    nptest.assert_almost_equal(egrid.map_scale, 25025.2600081)
    lat_should = np.fromfile(test_lat, dtype=np.float64)
    lon_should = np.fromfile(test_lon, dtype=np.float64)
    nptest.assert_almost_equal(egrid.londim,
                               lon_should.reshape((584, 1388))[100, :])
    nptest.assert_almost_equal(egrid.latdim,
                               lat_should.reshape((584, 1388))[:, 120])
test_stats.py 文件源码 项目:bayestsa 作者: thalesians 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def test_cor2cov(self):
        cor = SubdiagonalArray.create((-.25, -.5, .3))
        var = (4., 3., 5.)
        cov = stats.cor2cov(cor, var)
        npt.assert_almost_equal(cov, (
                ( 4.        , -0.8660254, -2.23606798),
                (-0.8660254 ,  3.       ,  1.161895  ),
                (-2.23606798,  1.161895 ,  5.        )))
test_stats.py 文件源码 项目:bayestsa 作者: thalesians 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def test_cov2cor(self):
        cov = (( 4.        , -0.8660254, -2.23606798),
               (-0.8660254 ,  3.       ,  1.161895  ),
               (-2.23606798,  1.161895 ,  5.        ))
        cor = stats.cov2cor(cov)
        npt.assert_almost_equal(cor, (
                ( 1.0 , -0.25, -0.5),
                (-0.25,  1.0 ,  0.3),
                (-0.5 ,  0.3 ,  1.0)))


问题


面经


文章

微信
公众号

扫码关注公众号