当前位置: 首页>>代码示例>>Python>>正文


Python tools.assert_almost_equal函数代码示例

本文整理汇总了Python中nose.tools.assert_almost_equal函数的典型用法代码示例。如果您正苦于以下问题:Python assert_almost_equal函数的具体用法?Python assert_almost_equal怎么用?Python assert_almost_equal使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了assert_almost_equal函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_energy

def test_energy():
    # make sure that energy as computed by ssvm is the same as by lp
    np.random.seed(0)
    for inference_method in ["lp", "ad3"]:
        found_fractional = False
        crf = EdgeFeatureGraphCRF(n_states=3,
                                  inference_method=inference_method,
                                  n_edge_features=2)
        while not found_fractional:
            x = np.random.normal(size=(7, 8, 3))
            edge_list = make_grid_edges(x, 4, return_lists=True)
            edges = np.vstack(edge_list)
            edge_features = edge_list_to_features(edge_list)
            x = (x.reshape(-1, 3), edges, edge_features)

            unary_params = np.random.normal(size=(3, 3))
            pw1 = np.random.normal(size=(3, 3))
            pw2 = np.random.normal(size=(3, 3))
            w = np.hstack([unary_params.ravel(), pw1.ravel(), pw2.ravel()])
            res, energy = crf.inference(x, w, relaxed=True, return_energy=True)
            found_fractional = np.any(np.max(res[0], axis=-1) != 1)

            psi = crf.psi(x, res)
            energy_svm = np.dot(psi, w)

            assert_almost_equal(energy, -energy_svm)
            if not found_fractional:
                # exact discrete labels, test non-relaxed version
                res, energy = crf.inference(x, w, relaxed=False,
                                            return_energy=True)
                psi = crf.psi(x, res)
                energy_svm = np.dot(psi, w)

                assert_almost_equal(energy, -energy_svm)
开发者ID:hushell,项目名称:pystruct,代码行数:34,代码来源:test_edge_feature_graph_crf.py

示例2: test_query_resolution

def test_query_resolution():
    bbox = (-180, -90, 180, 90)
    init_res = (4.5, 6.7)
    query = mapnik.Query(mapnik.Box2d(*bbox), init_res)
    r = query.resolution
    assert_almost_equal(r[0], init_res[0], places=7)
    assert_almost_equal(r[1], init_res[1], places=7)
开发者ID:cbenz,项目名称:python-mapnik,代码行数:7,代码来源:query_test.py

示例3: test_keep_top_k_epitopes

def test_keep_top_k_epitopes():
    arg_parser = make_variant_sequences_arg_parser()
    args = arg_parser.parse_args([
        "--vcf", data_path("b16.f10/b16.f10.Phip.vcf"),
        "--bam", data_path("b16.f10/b16.combined.sorted.bam"),
    ])
    reads_generator = allele_reads_generator_from_args(args)
    variants = variant_collection_from_args(args)
    keep_k_epitopes = 3
    core_logic = VaxrankCoreLogic(
        reads_generator=reads_generator,
        mhc_predictor=random_binding_predictor,
        variants=variants,
        vaccine_peptide_length=15,
        padding_around_mutation=5,
        min_alt_rna_reads=1,
        min_variant_sequence_coverage=1,
        variant_sequence_assembly=True,
        max_vaccine_peptides_per_variant=1,
        num_mutant_epitopes_to_keep=keep_k_epitopes)
    ranked_list = core_logic.ranked_vaccine_peptides()

    for variant, vaccine_peptides in ranked_list:
        vaccine_peptide = vaccine_peptides[0]
        eq_(keep_k_epitopes, len(vaccine_peptide.mutant_epitope_predictions))
        # recompute the expected score, make sure the top-k argument from ranked_vaccine_peptides()
        # propagated as expected
        mutant_epitope_score = sum(
            p.logistic_epitope_score() for p in vaccine_peptide.mutant_epitope_predictions)
        assert_almost_equal(mutant_epitope_score, vaccine_peptide.mutant_epitope_score)
开发者ID:hammerlab,项目名称:vaxrank,代码行数:30,代码来源:test_mutant_protein_sequence.py

示例4: test_avoid_nearby_birds

def test_avoid_nearby_birds():
    regression_data=yaml.load(open(os.path.join(os.path.dirname(__file__),'avoid_nearby_boids.yml')))
    boid_data=regression_data["before"]
    avoid_nearby_boids(boid_data)
    for after,before in zip(regression_data["after"],boid_data):
        for after_value,before_value in zip(after,before): 
            assert_almost_equal(after_value,before_value,delta=0.01)
开发者ID:deanscameron,项目名称:bad-boids,代码行数:7,代码来源:test_boids.py

示例5: test_bad_boids_regression

def test_bad_boids_regression():
    regression_data=yaml.load(open(os.path.join(os.path.dirname(__file__),'fixture.yml')))
    boid_data=regression_data["before"]
    update_boids(boid_data)
    for after,before in zip(regression_data["after"],boid_data):
        for after_value,before_value in zip(after,before): 
            assert_almost_equal(after_value,before_value,delta=0.01)
开发者ID:deanscameron,项目名称:bad-boids,代码行数:7,代码来源:test_boids.py

示例6: test_logging

def test_logging():
    iris = load_iris()
    X, y = iris.data, iris.target

    X_ = [(np.atleast_2d(x), np.empty((0, 2), dtype=np.int)) for x in X]
    Y = y.reshape(-1, 1)

    X_train, X_test, y_train, y_test = train_test_split(X_, Y, random_state=1)
    _, file_name = mkstemp()

    pbl = GraphCRF(n_features=4, n_states=3, inference_method=inference_method)
    logger = SaveLogger(file_name)
    svm = NSlackSSVM(pbl, C=100, n_jobs=1, logger=logger)
    svm.fit(X_train, y_train)

    score_current = svm.score(X_test, y_test)
    score_auto_saved = logger.load().score(X_test, y_test)

    alt_file_name = file_name + "alt"
    logger.save(svm, alt_file_name)
    logger.file_name = alt_file_name
    logger.load()
    score_manual_saved = logger.load().score(X_test, y_test)

    assert_less(.97, score_current)
    assert_less(.97, score_auto_saved)
    assert_less(.97, score_manual_saved)
    assert_almost_equal(score_auto_saved, score_manual_saved)
开发者ID:KentChun33333,项目名称:pystruct,代码行数:28,代码来源:test_utils_logging.py

示例7: _check_marginal_samples_match_scores

def _check_marginal_samples_match_scores(server, row, fi):
    row = loom.query.protobuf_to_data_row(row.diff)
    row[fi] = None
    to_sample = [i == fi for i in range(len(row))]
    samples = server.sample(to_sample, row, SAMPLE_COUNT)
    val = samples[0][fi]
    base_score = server.score(row)
    if isinstance(val, bool) or isinstance(val, int):
        probs_dict = {}
        samples = [sample[fi] for sample in samples]
        for sample in set(samples):
            row[fi] = sample
            probs_dict[sample] = numpy.exp(
                server.score(row) - base_score)
        if len(probs_dict) == 1:
            assert_almost_equal(probs_dict[sample], 1., places=SCORE_PLACES)
            return
        if min(probs_dict.values()) < MIN_CATEGORICAL_PROB:
            return
        gof = discrete_goodness_of_fit(samples, probs_dict, plot=True)
    elif isinstance(val, float):
        probs = numpy.exp([
            server.score(sample) - base_score
            for sample in samples
        ])
        samples = [sample[fi] for sample in samples]
        gof = density_goodness_of_fit(samples, probs, plot=True)
    assert_greater(gof, MIN_GOODNESS_OF_FIT)
开发者ID:fritzo,项目名称:loom,代码行数:28,代码来源:test_query_math.py

示例8: test_remove_momentum_rescale_energy_openmm

    def test_remove_momentum_rescale_energy_openmm(self):
        # don't actually need to do everything with OpenMM, but do need to
        # add units
        u_vel = old_div(u.nanometer, u.picosecond)
        u_mass = old_div(u.dalton, u.AVOGADRO_CONSTANT_NA)
        u_energy = old_div(u.kilojoule_per_mole, u.AVOGADRO_CONSTANT_NA)

        velocities = \
                np.array([[1.5, -1.0], [-1.0, 2.0], [0.25, -1.0]]) * u_vel
        masses = np.array([1.0, 1.5, 4.0]) * u_mass
        new_vel = self.openmm_modifier._remove_linear_momentum(
            velocities=velocities,
            masses=masses
        )
        new_momenta = new_vel * masses[:, np.newaxis]
        total_momenta = sum(new_momenta, new_momenta[0])
        assert_array_almost_equal(total_momenta,
                                  np.array([0.0]*2) * u_vel * u_mass)

        new_vel = self.openmm_modifier._rescale_kinetic_energy(
            velocities=velocities,
            masses=masses,
            double_KE=20.0 * u_energy
        )
        new_momenta = new_vel * masses[:, np.newaxis]
        total_momenta = sum(new_momenta, new_momenta[0])
        zero_energy = 0.0 * u_energy
        new_ke = sum(sum(new_momenta * new_vel, zero_energy), zero_energy)
        # tests require that the linear momentum be 0, and KE be correct
        assert_array_almost_equal(total_momenta,
                                  np.array([0.0]*2) * u_vel * u_mass)
        assert_equal(new_ke.unit, (20.0 * u_energy).unit)
        assert_almost_equal(new_ke._value, (20.0 * u_energy)._value)
开发者ID:dwhswenson,项目名称:openpathsampling,代码行数:33,代码来源:test_snapshot_modifier.py

示例9: test_call

    def test_call(self):
        new_toy_snap = self.toy_modifier(self.toy_snapshot)
        assert_array_almost_equal(new_toy_snap.coordinates,
                                  self.toy_snapshot.coordinates)
        new_vel = new_toy_snap.velocities
        old_vel = self.toy_snapshot.velocities
        same_vel = [np.allclose(new_vel[i], old_vel[i]) 
                    for i in range(len(new_vel))]
        assert_equal(Counter(same_vel), Counter({True: 2, False: 1}))
        for new_v, old_v in zip(new_vel, old_vel):
            assert_almost_equal(sum([v**2 for v in new_v]),
                                sum([v**2 for v in old_v]))

        new_omm_snap = self.openmm_modifier(self.openmm_snap)
        n_atoms = len(self.openmm_snap.coordinates)
        assert_array_almost_equal(new_omm_snap.coordinates,
                                  self.openmm_snap.coordinates)
        new_vel = new_omm_snap.velocities
        old_vel = self.openmm_snap.velocities
        same_vel = [np.allclose(new_vel[i], old_vel[i]) 
                    for i in range(len(new_vel))]
        same_vel = [np.allclose(new_vel[i], old_vel[i]) 
                    for i in range(len(new_vel))]
        assert_equal(Counter(same_vel), Counter({True: n_atoms-1, False: 1}))
        u_vel_sq = (old_div(u.nanometers, u.picoseconds))**2
        for new_v, old_v in zip(new_vel, old_vel):
            assert_almost_equal(
                sum([(v**2).value_in_unit(u_vel_sq) for v in new_v]),
                sum([(v**2).value_in_unit(u_vel_sq) for v in old_v])
            )
开发者ID:dwhswenson,项目名称:openpathsampling,代码行数:30,代码来源:test_snapshot_modifier.py

示例10: test_initial_value

def test_initial_value():
    m = Minuit(func3, pedantic=False, x=1., y=2., error_x=3., print_level=0)
    assert_almost_equal(m.args[0], 1.)
    assert_almost_equal(m.args[1], 2.)
    assert_almost_equal(m.values['x'], 1.)
    assert_almost_equal(m.values['y'], 2.)
    assert_almost_equal(m.errors['x'], 3.)
开发者ID:chrisburr,项目名称:iminuit,代码行数:7,代码来源:test_iminuit.py

示例11: test_intercepts_from_means_with_true_normalization

 def test_intercepts_from_means_with_true_normalization(self):
     expected_intercepts = self.true_intercepts_series
     true_normalization = ['m3', 2.0]
     calc_intercepts, calc_mean = wf.intercepts_from_means(
         self.data, true_normalization, self.true_loadings_series)
     assert_series_equal(calc_intercepts, expected_intercepts)
     assert_almost_equal(calc_mean, 0.0, places=2)
开发者ID:suri5471,项目名称:skillmodels,代码行数:7,代码来源:wa_functions_test.py

示例12: check_consistency_in_mesh1d

def check_consistency_in_mesh1d(macro_grid, element_orders, var_list):
    my_mesh1d = Mesh1D(macro_grid, element_orders, var_list)

    # Testing mesh attributes
    numpy.testing.assert_allclose(my_mesh1d.macro_grid, macro_grid)
    numpy.testing.assert_array_equal(my_mesh1d.element_orders, element_orders)
    assert_equal(my_mesh1d.variables, var_list)
    assert_equal(my_mesh1d.dof, (sum(element_orders) + 1) * len(var_list))

    # Testing list of elements
    for idx_var, var in enumerate(var_list):
        for idx_el, element in enumerate(my_mesh1d.elem):
            if idx_var == 0:
                mesh_pos_1 = my_mesh1d.gm[idx_el][element.pos[var]][0]
                mesh_pos_2 = sum(my_mesh1d.elem[el].order for el in range(idx_el))
                numpy.testing.assert_array_equal(mesh_pos_1, mesh_pos_2)
            else:
                mesh_pos_1 = my_mesh1d.gm[idx_el][element.pos[previous_var]] + my_mesh1d.dof_1v
                mesh_pos_2 = my_mesh1d.gm[idx_el][element.pos[var]]
                numpy.testing.assert_array_equal(mesh_pos_1, mesh_pos_2)
        previous_var = var

    # Testing linear and quadratic integration
    domain_integral_a = sum(el.w_1v.dot(el.x_1v) for el in my_mesh1d.elem)
    domain_integral_b = sum(el.w_1v.dot(el.x_1v ** 2) for el in my_mesh1d.elem)
    assert_almost_equal(domain_integral_a, (my_mesh1d.macro_grid[-1]**2 - my_mesh1d.macro_grid[0]**2) / 2)
    assert_almost_equal(domain_integral_b, (my_mesh1d.macro_grid[-1]**3 - my_mesh1d.macro_grid[0]**3) / 3)
开发者ID:alfredocarella,项目名称:speclib,代码行数:27,代码来源:mesh1d_tests.py

示例13: test_fit_background_C

 def test_fit_background_C(self):
     self.m["B_K"].active = False
     self.m.fit_background()
     nt.assert_almost_equal(self.m["Offset"].offset.value,
                            1.71212121212)
     nt.assert_false(self.m["B_K"].active)
     nt.assert_true(self.m["C_K"].active)
开发者ID:jerevon,项目名称:hyperspy,代码行数:7,代码来源:test_eelsmodel.py

示例14: test_generate_og_receptive_field

def test_generate_og_receptive_field():
    xpixels = 500 # simulated screen width
    ypixels = 500 # simulated screen height
    ppd = 1 # simulated visual angle
    scale_factor = 1.0 # simulated stimulus resampling rate
    distance = 5 # standard deviations to compute gauss out to
    xcenter = 0 # x coordinate of the pRF center
    ycenter = 0 # y coordinate of the pRF center
    sigma = 1 # width of the pRF
    
    test_value = 6 # this is the sum of a gaussian given 1 ppd 
                   # and a 1 sigma prf centered on (0,0)
                   
    # generate the visuotopic coordinates
    dx,dy = generate_coordinate_matrices(xpixels,
                                         ypixels,
                                         ppd,
                                         scale_factor)
    
    # generate a pRF at (0,0) and 1 sigma wide
    rf = generate_og_receptive_field(xcenter, ycenter, sigma, dx, dy)
    
    # divide by integral
    rf /= 2 * np.pi * sigma ** 2
    
    # compare the volume of the pRF to a known value
    nt.assert_almost_equal(np.sum(rf),1)
开发者ID:arokem,项目名称:popeye,代码行数:27,代码来源:test_spinach.py

示例15: test_x

 def test_x(self):
     s = session.query(Spot).get(1)
     assert_almost_equal(float(session.scalar(s.spot_location.x)), -88.594586159235689)
     s = session.query(Spot).filter(and_(Spot.spot_location.x < 0, Spot.spot_location.y > 42)).all()
     ok_(s is not None)
     assert_almost_equal(float(session.scalar(functions.x(WKTSpatialElement('POINT(-88.3655256496815 43.1402866687898)', geometry_type=Point.name)))),
                         -88.3655256496815)
开发者ID:ComedianClown,项目名称:geoalchemy,代码行数:7,代码来源:test_oracle.py


注:本文中的nose.tools.assert_almost_equal函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。