numpy.allclose

Here are the examples of the python api numpy.allclose taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

178 Examples 7

Example 1

Project: oq-hazardlib Source File: geodetic_test.py
    def test_zero_distance(self):
        lon, lat, depth, azimuth = 12, 34, 56, 78
        lons, lats, depths = geodetic.npoints_towards(
            lon, lat, depth, azimuth, hdist=0, vdist=0, npoints=5
        )
        expected_lons = [lon] * 5
        expected_lats = [lat] * 5
        expected_depths = [depth] * 5
        self.assertTrue(numpy.allclose(lons, expected_lons))
        self.assertTrue(numpy.allclose(lats, expected_lats))
        self.assertTrue(numpy.allclose(depths, expected_depths))

Example 2

Project: gensim Source File: test_word2vec.py
    def models_equal(self, model, model2):
        self.assertEqual(len(model.vocab), len(model2.vocab))
        self.assertTrue(numpy.allclose(model.syn0, model2.syn0))
        if model.hs:
            self.assertTrue(numpy.allclose(model.syn1, model2.syn1))
        if model.negative:
            self.assertTrue(numpy.allclose(model.syn1neg, model2.syn1neg))
        most_common_word = max(model.vocab.items(), key=lambda item: item[1].count)[0]
        self.assertTrue(numpy.allclose(model[most_common_word], model2[most_common_word]))

Example 3

Project: pyscf Source File: test_addons.py
    def test_sort_mo_by_irrep(self):
        mc1 = mcscf.CASSCF(mfr, 8, 4)
        mo0 = mcscf.sort_mo_by_irrep(mc1, mfr.mo_coeff, {'E1ux':2, 'E1uy':2, 'E1gx':2, 'E1gy':2})
        mo1 = mcscf.sort_mo_by_irrep(mc1, mfr.mo_coeff, {2:2, 3:2, 6:2, 7:2}, {2:0, 3:0, 6:0, 7:0})
        mo2 = mcscf.sort_mo_by_irrep(mc1, mfr.mo_coeff, (0,0,2,2,0,0,2,2))
        mo3 = mcscf.sort_mo_by_irrep(mc1, mfr.mo_coeff, {'E1ux':2, 'E1uy':2, 2:2, 3:2})
        self.assertTrue(numpy.allclose(mo0, mo1))
        self.assertTrue(numpy.allclose(mo0, mo2))
        self.assertTrue(numpy.allclose(mo0, mo3))

Example 4

Project: gensim Source File: test_lsimodel.py
Function: test_persistence
    def testPersistence(self):
        fname = testfile()
        model = self.model
        model.save(fname)
        model2 = lsimodel.LsiModel.load(fname)
        self.assertEqual(model.num_topics, model2.num_topics)
        self.assertTrue(numpy.allclose(model.projection.u, model2.projection.u))
        self.assertTrue(numpy.allclose(model.projection.s, model2.projection.s))
        tstvec = []
        self.assertTrue(numpy.allclose(model[tstvec], model2[tstvec]))  # try projecting an empty vector

Example 5

Project: mayavi Source File: test_image_plane_widget.py
Function: check
    def check(self):
        script = self.script
        src = script.engine.current_scene.children[0]
        i1, i2, i3 = src.children[0].children[1:]
        assert i1.ipw.plane_orientation == 'x_axes'
        assert numpy.allclose(i1.ipw.center, (0, 31.5, 31.5))
        rng = i1.ipw.reslice_output.point_data.scalars.range
        assert numpy.allclose(rng, (-0.2, 1.0), atol=0.1)
        assert i2.ipw.plane_orientation == 'y_axes'
        assert numpy.allclose(i2.ipw.center, (31.5, 0, 31.5))
        rng = i2.ipw.reslice_output.point_data.scalars.range
        assert numpy.allclose(rng, (-0.2, 1.0), atol=0.1)
        assert i3.ipw.plane_orientation == 'z_axes'
        assert numpy.allclose(i3.ipw.center, (31.5, 31.5, 0))
        rng = i3.ipw.reslice_output.point_data.scalars.range
        assert numpy.allclose(rng, (-0.2, 1.0), atol=0.1)

Example 6

Project: mayavi Source File: test_image_plane_widget.py
Function: check
    def check(self):
        """Do the actual testing."""

        s=self.scene
        src = s.children[0]
        i1, i2, i3 = src.children[0].children[1:]
        self.assertEqual(i1.ipw.plane_orientation,'x_axes')
        self.assertEqual(numpy.allclose(i1.ipw.center, (0, 31.5, 31.5)),True)
        self.assertEqual( i2.ipw.plane_orientation,'y_axes')
        self.assertEqual(numpy.allclose(i2.ipw.center, (31.5, 0, 31.5)),True)
        self.assertEqual(i3.ipw.plane_orientation,'z_axes')
        self.assertEqual( numpy.allclose(i3.ipw.center, (31.5, 31.5, 0)),True)

Example 7

Project: oq-hazardlib Source File: geodetic_test.py
    def test_same_points(self):
        lon, lat, depth = 1.2, 3.4, 5.6
        lons, lats, depths = geodetic.npoints_between(
            lon, lat, depth, lon, lat, depth, npoints=7
        )
        expected_lons = [lon] * 7
        expected_lats = [lat] * 7
        expected_depths = [depth] * 7
        self.assertTrue(numpy.allclose(lons, expected_lons))
        self.assertTrue(numpy.allclose(lats, expected_lats))
        self.assertTrue(numpy.allclose(depths, expected_depths))

Example 8

Project: topical_word_embeddings Source File: test_models.py
    def testLargeMmap(self):
        model = ldamodel.LdaModel(self.corpus, num_topics=2)

        # simulate storing large arrays separately
        model.save(testfile(), sep_limit=0)

        model2 = ldamodel.LdaModel.load(testfile())
        self.assertEqual(model.num_topics, model2.num_topics)
        self.assertTrue(numpy.allclose(model.expElogbeta, model2.expElogbeta))
        tstvec = []
        self.assertTrue(numpy.allclose(model[tstvec], model2[tstvec])) # try projecting an empty vector

        # test loading the large model arrays with mmap
        model2 = ldamodel.LdaModel.load(testfile(), mmap='r')
        self.assertEqual(model.num_topics, model2.num_topics)
        self.assertTrue(numpy.allclose(model.expElogbeta, model2.expElogbeta))
        tstvec = []
        self.assertTrue(numpy.allclose(model[tstvec], model2[tstvec])) # try projecting an empty vector

Example 9

Project: topical_word_embeddings Source File: test_models.py
Function: test_persistence
    def testPersistence(self):
        model = lsimodel.LsiModel(self.corpus, num_topics=2)
        model.save(testfile())
        model2 = lsimodel.LsiModel.load(testfile())
        self.assertEqual(model.num_topics, model2.num_topics)
        self.assertTrue(numpy.allclose(model.projection.u, model2.projection.u))
        self.assertTrue(numpy.allclose(model.projection.s, model2.projection.s))
        tstvec = []
        self.assertTrue(numpy.allclose(model[tstvec], model2[tstvec])) # try projecting an empty vector

Example 10

Project: gensim Source File: test_lsimodel.py
Function: testpersistencecompressed
    def testPersistenceCompressed(self):
        fname = testfile() + '.gz'
        model = self.model
        model.save(fname)
        model2 = lsimodel.LsiModel.load(fname, mmap=None)
        self.assertEqual(model.num_topics, model2.num_topics)
        self.assertTrue(numpy.allclose(model.projection.u, model2.projection.u))
        self.assertTrue(numpy.allclose(model.projection.s, model2.projection.s))
        tstvec = []
        self.assertTrue(numpy.allclose(model[tstvec], model2[tstvec]))  # try projecting an empty vector

Example 11

Project: tract_querier Source File: test_tractography.py
def equal_tracts_data(a, b):
    if set(a.keys()) != set(b.keys()):
        return False

    for k in a.keys():
        v1 = a[k]
        v2 = b[k]
        if isinstance(v1, str) and isinstance(v2, str) and v1 == v2:
            continue
        elif not isinstance(v1, str) and not isinstance(v2, str):
            for t1, t2 in izip(a[k], b[k]):
                if not (len(t1) == len(t2) and allclose(t1, t2)):
                    return False
        else:
            return False
    return True

Example 12

Project: dask Source File: test_linalg.py
Function: check_lu_result
def _check_lu_result(p, l, u, A):
    assert np.allclose(p.dot(l).dot(u), A)

    # check triangulars
    assert np.allclose(l, np.tril(l.compute()))
    assert np.allclose(u, np.triu(u.compute()))

Example 13

Project: drmad Source File: test_graphs.py
Function: test_grad_identity
def test_grad_identity():
    fun = lambda x : x
    df = grad(fun)
    ddf = grad(df)
    assert np.allclose(df(2.0), 1.0)
    assert np.allclose(ddf(2.0), 0.0)

Example 14

Project: simpeg Source File: test_TreeMesh.py
Function: test_get_item
    def test_getitem(self):
        M = Mesh.TreeMesh([4,4])
        M.refine(1)
        assert M.nC == 4
        assert len(M) == M.nC
        assert np.allclose(M[0].center, [0.25,0.25])
        actual = [[0,0],[0.5,0],[0,0.5],[0.5,0.5]]
        for i, n in enumerate(M[0].nodes):
            assert np.allclose(M._gridN[n,:], actual[i])

Example 15

Project: pypcd Source File: test_pypcd.py
def test_ascii_bin1(ascii_pcd_fname, bin_pcd_fname):
    import pypcd
    apc1 = pypcd.point_cloud_from_path(ascii_pcd_fname)
    bpc1 = pypcd.point_cloud_from_path(bin_pcd_fname)
    am = cloud_centroid(apc1)
    bm = cloud_centroid(bpc1)
    assert( np.allclose(am, bm) )

Example 16

Project: yandex-tank Source File: test_test.py
def test_random_split(data):
    dataframes = list(random_split(data))
    assert len(dataframes) > 1
    concatinated = pd.concat(dataframes)
    assert len(concatinated) == len(data), "We did not lose anything"
    assert np.allclose(concatinated.values,
                       data.values), "We did not corrupt the data"

Example 17

Project: codetools Source File: adapted_data_context_test_case.py
Function: test_get_item
    def test_getitem(self):
        """ Is getitem adapted correctly?
        """
        value = self.context['depth']
        desired = self.convert_out(array((20., 30., 40., 50.)))

        self.assertEqual(len(value), 4)
        self.assertTrue(allclose(value, desired))

Example 18

Project: distarray Source File: context.py
Function: allclose
    def allclose(self, a, b, rtol=1e-05, atol=1e-08):

        adist = a.distribution
        bdist = b.distribution

        if not adist.is_compatible(bdist):
            raise ValueError("%r and %r have incompatible distributions.")

        def local_allclose(la, lb, rtol, atol):
            from numpy import allclose
            return allclose(la.ndarray, lb.ndarray, rtol, atol)

        local_results = self.apply(local_allclose, 
                                  (a.key, b.key, rtol, atol),
                                  targets=a.targets)
        return all(local_results)

Example 19

Project: bolt Source File: utils.py
Function: allclose
def allclose(a, b):
    """
    Test that a and b are close and match in shape.

    Parameters
    ----------
    a : ndarray
        First array to check

    b : ndarray
        First array to check
    """
    from numpy import allclose
    return (a.shape == b.shape) and allclose(a, b)

Example 20

Project: EQcorrscan Source File: subspace.py
Function: eq
    def __eq__(self, other):
        if not isinstance(other, Detector):
            return False
        for key in ['name', 'sampling_rate', 'multiplex', 'lowcut', 'highcut',
                    'filt_order', 'dimension', 'stachans']:
            if not self.__getattribute__(key) == other.__getattribute__(key):
                return False
        for key in ['data', 'u', 'v', 'sigma']:
            list_item = self.__getattribute__(key)
            other_list = other.__getattribute__(key)
            if not len(list_item) == len(other_list):
                return False
            for item, other_item in zip(list_item, other_list):
                if not np.allclose(item, other_item):
                    return False
        return True

Example 21

Project: karta Source File: grid_tests.py
    def test_profile(self):
        path = karta.Line([(15.0, 15.0), (1484.0, 1484.0)], crs=karta.crs.Cartesian)
        pts, z = self.rast.profile(path, resolution=42.426406871192853, method="nearest")
        expected = self.rast[:,:].diagonal()
        self.assertEqual(len(pts), 49)
        self.assertTrue(np.allclose(z, expected))
        return

Example 22

Project: pandashells Source File: p_regress_tests.py
    @patch(
        'pandashells.bin.p_regress.sys.argv',
        'p.regress -m y~x --fit'.split())
    @patch('pandashells.bin.p_regress.io_lib.df_to_output')
    @patch('pandashells.bin.p_regress.io_lib.df_from_input')
    def test_cli_fit(self, df_from_input_mock, df_to_output_mock):
        df_in = pd.DataFrame({
            'x': range(1, 101),
            'y': range(1, 101),
        })
        df_from_input_mock.return_value = df_in
        main()

        df_out = df_to_output_mock.call_args_list[0][0][1]
        self.assertTrue(np.allclose(df_out.y, df_out.fit_))
        self.assertTrue(np.allclose(df_out.y * 0, df_out.resid_))

Example 23

Project: spectral Source File: detectors.py
    def test_mf_windowed_target_eq_one(self):
        '''Windowed Matched Filter response of target pixel should be one.'''
        X = self.data[:10, :10, :]
        ij = (3, 3)
        y = spy.matched_filter(X, X[ij], window=(3,7), cov=self.background.cov)
        np.allclose(1, y[ij])

Example 24

Project: tfr Source File: spectrogram_test.py
def test_window_should_be_normalized():
    def assert_ok(size):
        w = create_window(size)
        assert np.allclose(energy(w), len(w))
        assert np.allclose(mean_power(w), 1.0)

    for size in [16, 100, 512, 777, 4096]:
        yield assert_ok, size

Example 25

Project: amen Source File: test_audio.py
Function: test_output
def test_output():
    n, tempfilename = tempfile.mkstemp()
    audio.output(tempfilename, format='WAV')
    new_samples, new_sample_rate = librosa.load(tempfilename, sr=audio.sample_rate)
    os.unlink(tempfilename)

    assert np.allclose(audio.sample_rate, new_sample_rate)
    assert np.allclose(audio.raw_samples, new_samples, rtol=1e-3, atol=1e-4)

Example 26

Project: GPflow Source File: test_conditionals.py
    def test_whiten(self):
        """
        make sure that predicting using the whitened representation is the
        sameas the non-whitened one. 
        """
        
        with self.k.tf_mode():
            K = self.k.K(self.X) + eye(self.num_data) * 1e-6
            L = tf.cholesky(K)
            V = tf.matrix_triangular_solve(L, self.F, lower=True)
            Fstar_mean, Fstar_var = GPflow.conditionals.gp_predict(self.Xs, self.X, self.k, self.F)
            Fstar_w_mean, Fstar_w_var = GPflow.conditionals.gp_predict_whitened(self.Xs, self.X, self.k, V)


        mean1, var1 = tf.Session().run([Fstar_w_mean, Fstar_w_var], feed_dict=self.feed_dict)
        mean2, var2 = tf.Session().run([Fstar_mean, Fstar_var], feed_dict=self.feed_dict)

        self.assertTrue(np.allclose(mean1, mean2, 1e-6, 1e-6)) # TODO: should tolerance be type dependent?
        self.assertTrue(np.allclose(var1, var2, 1e-6, 1e-6))

Example 27

Project: yatsm Source File: test__cusum.py
def test_cusum_OLS(test_data, strucchange_cusum_OLS):
    """ Tested against strucchange 1.5.1
    """
    y = test_data.pop('y')
    X = test_data
    # Test sending pandas
    result = cu.cusum_OLS(X, y)
    assert np.allclose(result.score, strucchange_cusum_OLS[0])
    assert np.allclose(result.pvalue, strucchange_cusum_OLS[1])

    # And ndarray and xarray
    result = cu.cusum_OLS(X.values, xr.DataArray(y, dims=['time']))
    assert np.allclose(result.score, strucchange_cusum_OLS[0])
    assert np.allclose(result.pvalue, strucchange_cusum_OLS[1])

Example 28

Project: pypar Source File: test_calculate_region.py
    def test2(self):
        kmax = 32
        M = N = 5

        real_min = -2.0
        real_max = 1.0
        imag_min = -1.5
        imag_max = 1.5
        A = calculate_region(real_min, real_max,
                imag_min, imag_max, kmax, M, N)

        assert numpy.allclose(A,
                              [[1,  1,  1,  1,  1],
                               [1,  3,  5,  5,  3],
                               [2,  4,  9,  9,  4],
                               [2,  9, 32, 32,  9],
                               [2,  3, 15, 15,  3]])

Example 29

Project: bhmm Source File: _tmatrix_disconnected.py
Function: is_reversible
def is_reversible(P):
    """ Returns if P is reversible on its weakly connected sets """
    import msmtools.analysis as msmana
    # treat each weakly connected set separately
    sets = connected_sets(P, strong=False)
    for s in sets:
        Ps = P[s, :][:, s]
        if not msmana.is_transition_matrix(Ps):
            return False  # isn't even a transition matrix!
        pi = msmana.stationary_distribution(Ps)
        X = pi[:, None] * Ps
        if not np.allclose(X, X.T):
            return False
    # survived.
    return True

Example 30

Project: deepchem Source File: test_basic.py
  def testRDKitDescriptors(self):
    """
    Test simple descriptors.
    """
    descriptors = self.engine([self.mol])
    assert np.allclose(
      descriptors[0, self.engine.descriptors.index('ExactMolWt')], 180,
      atol=0.1)

Example 31

Project: word2gauss Source File: test_embeddings.py
    def _num_grad_check(self, embed, eps, rtol):
        [(dmu, ndmu), (dsigma, ndsigma)] = numerical_grad(embed, 0, 1, eps)
        for ij in [0, 1]:
            self.assertTrue(
                np.allclose(dmu[ij], ndmu[ij], rtol=rtol))
            self.assertTrue(
                np.allclose(dsigma[ij], ndsigma[ij], rtol=rtol))

Example 32

Project: opt_einsum Source File: test_input.py
def test_ellipse_input1():
    string = '...a->...'
    views = build_views(string)

    ein = contract(string, *views, optimize=False)
    opt = contract(views[0], [Ellipsis, 0], [Ellipsis])
    assert np.allclose(ein, opt)

Example 33

Project: lopq Source File: tests.py
Function: test_proto
def test_proto():
    import os

    filename = './temp_proto.lopq'
    m = make_random_model()
    m.export_proto(filename)
    m2 = LOPQModel.load_proto(filename)

    assert_equal(m.V, m2.V)
    assert_equal(m.M, m2.M)
    assert_equal(m.subquantizer_clusters, m2.subquantizer_clusters)

    assert_true(np.allclose(m.Cs[0], m2.Cs[0]))
    assert_true(np.allclose(m.Rs[0], m2.Rs[0]))
    assert_true(np.allclose(m.mus[0], m2.mus[0]))
    assert_true(np.allclose(m.subquantizers[0][0], m.subquantizers[0][0]))

    os.remove(filename)

Example 34

Project: skll Source File: test_featureset.py
@attr('have_pandas')
def test_featureset_creation_from_dataframe_without_labels_with_vectorizer():
    (expected, current) = featureset_creation_from_dataframe_helper(False, True)
    # Directly comparing FeatureSet objects fails here because both sets
    # of labels are all nan when labels isn't specified, and arrays of
    # all nan are not equal to each other.
    # Based off of FeatureSet.__eq__()
    assert (expected.name == current.name and
            (expected.ids == current.ids).all() and
            expected.vectorizer == current.vectorizer and
            np.allclose(expected.features.data,
                        current.features.data,
                        rtol=1e-6) and
            np.all(np.isnan(expected.labels)) and
            np.all(np.isnan(current.labels)))

Example 35

Project: chempy Source File: test_ode.py
@requires('numpy', 'pyodesys')
def test_SpecialFraction():
    k, kprime = 3.142, 2.718
    rsys = _get_SpecialFraction_rsys(k, kprime)

    odesys = get_odesys(rsys, include_params=True)[0]
    c0 = {'H2': 13, 'Br2': 17, 'HBr': 19}
    r = k*c0['H2']*c0['Br2']**(3/2)/(c0['Br2'] + kprime*c0['HBr'])
    ref = rsys.as_per_substance_array({'H2': -r, 'Br2': -r, 'HBr': 2*r})
    res = odesys.f_cb(0, rsys.as_per_substance_array(c0))
    assert np.allclose(res, ref)

Example 36

Project: cesium Source File: test_time_series.py
def test_time_series_init_1d():
    t, m, e = sample_time_series(channels=1)
    ts = TimeSeries(t, m, e)
    assert ts.time.shape == t.shape and np.allclose(ts.time, t)
    assert ts.measurement.shape == m.shape and np.allclose(ts.measurement, m)
    assert ts.error.shape == e.shape and np.allclose(ts.error, e)
    assert ts.n_channels == 1

Example 37

Project: discomll Source File: tests_classification.py
    def test_log_reg_thetas(self):
        # python tests_classification.py Tests_Classification.test_log_reg_thetas
        from discomll.classification import logistic_regression

        train_data1 = datasets.ex4_orange()
        train_data2 = datasets.ex4_discomll()

        lr = Orange.classification.logreg.LogRegFitter_Cholesky(train_data1)
        thetas1 = lr[1]

        thetas_url = logistic_regression.fit(train_data2)
        thetas2 = [v for k, v in result_iterator(thetas_url["logreg_fitmodel"]) if k == "thetas"]

        self.assertTrue(np.allclose(thetas1, thetas2))

Example 38

Project: symengine.py Source File: test_lambdify.py
def test_array_out():
    if not HAVE_NUMPY:  # nosetests work-around
        return
    if sys.version_info[0] < 3:
        return  # requires Py3
    args, exprs, inp, check = _get_array()
    lmb = se.Lambdify(args, exprs)
    out1 = array.array('d', [0]*len(exprs))
    out2 = lmb(inp, out1)
    # Ensure buffer points to still data point:
    assert out1.buffer_info()[0] == out2.__array_interface__['data'][0]
    check(out1)
    check(out2)
    out2[:] = -1
    assert np.allclose(out1[:], [-1]*len(exprs))

Example 39

Project: chemlab Source File: test_io.py
def test_read_xyz():
    df = datafile('tests/data/sulphoxide.xyz')
    mol1 = df.read('molecule')


    df = datafile('/tmp/t.xyz', mode="w")
    df.write('molecule', mol1)

    df = datafile('/tmp/t.xyz', mode="rb")
    mol2 = df.read('molecule')

    assert np.allclose(mol1.r_array, mol2.r_array)
    assert all(mol1.type_array == mol2.type_array)

Example 40

Project: pyhawkes Source File: parents.py
    def _check_EZ(self):
        """
        Check that Z adds up to the correct amount
        :return:
        """
        for Sk, EZk in zip(self.Ss, self.EZ):
            assert np.allclose(Sk, EZk.sum(1))

Example 41

Project: bx-python Source File: pwm_tests.py
Function: test_scoring
def test_scoring():
    m = pwm.FrequencyMatrix.from_rows( ['A','C','G','T'], get_ctcf_rows() )
    # Stormo method
    sm = m.to_stormo_scoring_matrix()
    # Forward matches
    assert allclose( sm.score_string( "AATCACCACCTCCTGGCAGG" )[0], -156.8261261 )
    assert allclose( sm.score_string( "TGCCTGCCTCTGTAGGCTCC" )[0], -128.8106842 )
    assert allclose( sm.score_string( "GTTGCCAGTTGGGGGAAGCA" )[0], 4.65049839 )
    assert allclose( sm.score_string( "GCAGACACCAGGTGGTTCAG" )[0], 1.60168743 )
    # Reverse matches
    rc = sm.reverse_complement()
    assert allclose( rc.score_string( "AATCACCACCTCCTGGCAGG" )[0], 0.014178276062 )
    assert allclose( rc.score_string( "TGCCTGCCTCTGTAGGCTCC" )[0], 0.723828315735 )
    assert allclose( rc.score_string( "GTTGCCAGTTGGGGGAAGCA" )[0], -126.99407196 )
    assert allclose( rc.score_string( "GCAGACACCAGGTGGTTCAG" )[0], -86.9560623169 )
    # Nothing valid
    assert isnan( sm.score_string_with_gaps( "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ) ).all()
    # Too short
    assert isnan( sm.score_string( "TTTT" ) ).all()

Example 42

Project: gala Source File: test_all_builtin.py
    def test_against_triaxial(self):
        other = LeeSutoTriaxialNFWPotential(units=galactic,
                                            v_c=0.35, r_s=12.,
                                            a=1., b=1., c=1.)

        v1 = other.value(self.w0[:3])
        v2 = self.potential.value(self.w0[:3])
        assert np.allclose(v1.value,v2.value)

        a1 = other.gradient(self.w0[:3])
        a2 = self.potential.gradient(self.w0[:3])
        assert np.allclose(a1.value,a2.value)

Example 43

Project: calliope Source File: test_io.py
def verify_solution_integrity(model_solution, solution_from_disk, tempdir):
        # Check whether the two are the same
        np.allclose(model_solution['e_cap'], solution_from_disk['e_cap'])

        # Check that config AttrDict has been deserialized
        assert(solution_from_disk.attrs['config_run'].output.path == tempdir)

Example 44

Project: hickle Source File: test_hickle.py
def test_legacy_hickles():

    try:
        a = load("hickle_1_1_0.hkl")
        b = load("hickle_1_3_0.hkl")
        
        import h5py
        d = h5py.File("hickle_1_1_0.hkl")["data"]["a"][:]
        d2 = h5py.File("hickle_1_3_0.hkl")["data"]["a"][:]
        assert np.allclose(d, a["a"])
        assert np.allclose(d2, b["a"])
        
    except IOError:
        # For travis-CI
        a = load("tests/hickle_1_1_0.hkl")
        b = load("tests/hickle_1_3_0.hkl")
    
    print a 
    print b

Example 45

Project: abstract_rendering Source File: fast_project.py
def report_diffs(a, b, name):
    last_dim = a.shape[1]
    if not np.allclose(a, b):
        for i in range(1, last_dim):
            if not np.allclose(a[:,i], b[:,i]):
                print('%s::%d fails \nc:\n%s != %s\n' %
                      (name, i, str(a[:,i]), str(b[:,i])))

Example 46

Project: pysb Source File: test_simulator_scipy.py
    def test_y0_as_list(self):
        """Test y0 with list of initial conditions"""
        # Test the initials getter method before anything is changed
        assert np.allclose(self.sim.initials[0:3],
                           [ic[1].value for ic in
                            self.model.initial_conditions])

        initials = [10, 20, 0, 0]
        simres = self.sim.run(initials=initials)
        assert np.allclose(self.sim.initials, initials)
        assert np.allclose(simres.observables['A_free'][0], 10)

Example 47

Project: SERT Source File: query.py
def compute_normalised_entropy(distribution, base=2):
    assert distribution.ndim == 2

    assert np.allclose(distribution.sum(axis=1), 1.0)

    entropies = [
        math_utils.entropy(distribution[i, :], base=base, normalize=True)
        for i in range(distribution.shape[0])]

    return entropies

Example 48

Project: scikit-image Source File: test_warps.py
def test_warp_identity():
    img = img_as_float(rgb2gray(data.astronaut()))
    assert len(img.shape) == 2
    assert np.allclose(img, warp(img, AffineTransform(rotation=0)))
    assert not np.allclose(img, warp(img, AffineTransform(rotation=0.1)))
    rgb_img = np.transpose(np.asarray([img, np.zeros_like(img), img]),
                            (1, 2, 0))
    warped_rgb_img = warp(rgb_img, AffineTransform(rotation=0.1))
    assert np.allclose(rgb_img, warp(rgb_img, AffineTransform(rotation=0)))
    assert not np.allclose(rgb_img, warped_rgb_img)
    # assert no cross-talk between bands
    assert np.all(0 == warped_rgb_img[:, :, 1])

Example 49

Project: thunder Source File: test_base.py
def test_repartition(eng):
    if eng is not None:
        data = images.fromlist([array([1, 1]), array([2, 2]), array([3, 3]), array([4, 4]),
                                array([5, 5]), array([6, 6]), array([7, 7]), array([8, 8]),
                                array([9, 9]), array([10, 10]), array([11, 11]), array([12, 12])],
                               engine=eng, npartitions=10)
        assert allclose(data.first(), array([1, 1]))
        assert isinstance(data.first(), (ndarray, generic))
        data = data.repartition(3)
        assert allclose(data.first(), array([1, 1]))

        data = series.fromlist([array([1, 1]), array([2, 2]), array([3, 3]), array([4, 4]),
                                array([5, 5]), array([6, 6]), array([7, 7]), array([8, 8]),
                                array([9, 9]), array([10, 10]), array([11, 11]), array([12, 12])],
                               engine=eng, npartitions=10)
        assert allclose(data.first(), array([1, 1]))
        data = data.repartition(3)
        assert allclose(data.first(), array([1, 1]))
        assert isinstance(data.first(), (ndarray, generic))

Example 50

Project: portfolioopt Source File: test_portfolioopt.py
Function: test_allow_short
    def test_allow_short(self):
        returns, cov_mat, avg_rets = create_test_data()

        calc_weights = pfopt.min_var_portfolio(cov_mat, allow_short=True).values
        exp_weights = [0.29428401463312454, 0.19221716939564482, 0.13820233202108606,
                       0.20879490895467365, 0.16650157499547097]

        self.assertTrue(np.allclose(calc_weights, exp_weights))
See More Examples - Go to Next Page
Page 1 Selected Page 2 Page 3 Page 4