Python numpy.allclose() Examples

The following are 30 code examples for showing how to use numpy.allclose(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module numpy , or try the search function .

Example 1
Project: neural-fingerprinting   Author: StephanZheng   File: test_utils_tf.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_clip_eta_goldilocks(self):
        # Test that the clipping handles perturbations that are
        # too small, just right, and too big correctly
        eta = tf.constant([[2.], [3.], [4.]])
        assert eta.dtype == tf.float32, eta.dtype
        eps = 3.
        for ord_arg in [np.inf, 1, 2]:
            for sign in [-1., 1.]:
                clipped = clip_eta(eta * sign, ord_arg, eps)
                clipped_value = self.sess.run(clipped)
                gold = sign * np.array([[2.], [3.], [3.]])
                self.assertClose(clipped_value, gold)
                grad, = tf.gradients(clipped, eta)
                grad_value = self.sess.run(grad)
                # Note: the second 1. is debatable (the left-sided derivative
                # and the right-sided derivative do not match, so formally
                # the derivative is not defined). This test makes sure that
                # we at least handle this oddity consistently across all the
                # argument values we test
                gold = sign * np.array([[1.], [1.], [0.]])
                assert np.allclose(grad_value, gold) 
Example 2
Project: spleeter   Author: deezer   File: test_separator.py    License: MIT License 6 votes vote down vote up
def test_separate(test_file, configuration, backend):
    """ Test separation from raw data. """
    with tf.Session() as sess:
        instruments = MODEL_TO_INST[configuration]
        adapter = get_default_audio_adapter()
        waveform, _ = adapter.load(test_file)
        separator = Separator(configuration, stft_backend=backend)
        prediction = separator.separate(waveform, test_file)
        assert len(prediction) == len(instruments)
        for instrument in instruments:
            assert instrument in prediction
        for instrument in instruments:
            track = prediction[instrument]
            assert waveform.shape[:-1] == track.shape[:-1]
            assert not np.allclose(waveform, track)
            for compared in instruments:
                if instrument != compared:
                    assert not np.allclose(track, prediction[compared]) 
Example 3
Project: discomll   Author: romanorac   File: tests_classification.py    License: Apache License 2.0 6 votes vote down vote up
def test_naivebayes_breastcancer(self):
        # python -m unittest tests_classification.Tests_Classification.test_naivebayes_breastcancer
        from discomll.classification import naivebayes
        train_data1, test_data1 = datasets.breastcancer_disc_orange()
        train_data2, test_data2 = datasets.breastcancer_disc_discomll()

        for m in range(3):
            learner = Orange.classification.bayes.NaiveLearner(m=m)
            classifier = learner(train_data1)
            predictions1 = [classifier(inst, Orange.classification.Classifier.GetBoth) for inst in test_data1]
            predictions1_target = [v[0].value for v in predictions1]
            predictions1_probs = [v[1].values() for v in predictions1]

            fitmodel_url = naivebayes.fit(train_data2)
            predictions_url = naivebayes.predict(test_data2, fitmodel_url, m=m)
            predictions2_target = []
            predictions2_probs = []
            for k, v in result_iterator(predictions_url):
                predictions2_target.append(v[0])
                predictions2_probs.append(v[1])

            self.assertListEqual(predictions1_target, predictions2_target)
            self.assertTrue(np.allclose(predictions1_probs, predictions2_probs)) 
Example 4
Project: discomll   Author: romanorac   File: tests_classification.py    License: Apache License 2.0 6 votes vote down vote up
def test_naivebayes_breastcancer_cont(self):
        # python -m unittest tests_classification.Tests_Classification.test_naivebayes_breastcancer_cont
        from sklearn.naive_bayes import GaussianNB
        from discomll.classification import naivebayes

        x_train, y_train, x_test, y_test = datasets.breastcancer_cont(replication=1)
        train_data, test_data = datasets.breastcancer_cont_discomll(replication=1)

        clf = GaussianNB()
        probs_log1 = clf.fit(x_train, y_train).predict_proba(x_test)

        fitmodel_url = naivebayes.fit(train_data)
        prediction_url = naivebayes.predict(test_data, fitmodel_url)
        probs_log2 = [v[1] for _, v in result_iterator(prediction_url)]

        self.assertTrue(np.allclose(probs_log1, probs_log2, atol=1e-8)) 
Example 5
Project: discomll   Author: romanorac   File: tests_regression.py    License: Apache License 2.0 6 votes vote down vote up
def test_lwlr(self):
        # python -m unittest tests_regression.Tests_Regression.test_lwlr
        import locally_weighted_linear_regression as lwlr1
        from discomll.regression import locally_weighted_linear_regression as lwlr2

        x_train, y_train, x_test, y_test = datasets.regression_data()
        train_data, test_data = datasets.regression_data_discomll()

        lwlr1 = lwlr1.Locally_Weighted_Linear_Regression()
        taus = [1, 10, 25]
        sorted_indices = np.argsort([str(el) for el in x_test[:, 1].tolist()])

        for tau in taus:
            thetas1, estimation1 = lwlr1.fit(x_train, y_train, x_test, tau=tau)
            thetas1, estimation1 = np.array(thetas1)[sorted_indices], np.array(estimation1)[sorted_indices]

            results = lwlr2.fit_predict(train_data, test_data, tau=tau)
            thetas2, estimation2 = [], []

            for x_id, (est, thetas) in result_iterator(results):
                estimation2.append(est)
                thetas2.append(thetas)

            self.assertTrue(np.allclose(thetas1, thetas2, atol=1e-8))
            self.assertTrue(np.allclose(estimation1, estimation2, atol=1e-3)) 
Example 6
Project: DOTA_models   Author: ringringyi   File: object_detection_evaluation_test.py    License: Apache License 2.0 6 votes vote down vote up
def test_add_single_ground_truth_image_info(self):
    expected_num_gt_instances_per_class = np.array([3, 1, 2], dtype=int)
    expected_num_gt_imgs_per_class = np.array([2, 1, 2], dtype=int)
    self.assertTrue(np.array_equal(expected_num_gt_instances_per_class,
                                   self.od_eval.num_gt_instances_per_class))
    self.assertTrue(np.array_equal(expected_num_gt_imgs_per_class,
                                   self.od_eval.num_gt_imgs_per_class))
    groundtruth_boxes2 = np.array([[10, 10, 11, 11], [500, 500, 510, 510],
                                   [10, 10, 12, 12]], dtype=float)
    self.assertTrue(np.allclose(self.od_eval.groundtruth_boxes["img2"],
                                groundtruth_boxes2))
    groundtruth_is_difficult_list2 = np.array([False, True, False], dtype=bool)
    self.assertTrue(np.allclose(
        self.od_eval.groundtruth_is_difficult_list["img2"],
        groundtruth_is_difficult_list2))
    groundtruth_class_labels1 = np.array([0, 2, 0], dtype=int)
    self.assertTrue(np.array_equal(self.od_eval.groundtruth_class_labels[
        "img1"], groundtruth_class_labels1)) 
Example 7
Project: DOTA_models   Author: ringringyi   File: object_detection_evaluation_test.py    License: Apache License 2.0 6 votes vote down vote up
def test_add_single_detected_image_info(self):
    expected_scores_per_class = [[np.array([0.8, 0.7], dtype=float)], [],
                                 [np.array([0.9], dtype=float)]]
    expected_tp_fp_labels_per_class = [[np.array([0, 1], dtype=bool)], [],
                                       [np.array([0], dtype=bool)]]
    expected_num_images_correctly_detected_per_class = np.array([0, 0, 0],
                                                                dtype=int)
    for i in range(self.od_eval.num_class):
      for j in range(len(expected_scores_per_class[i])):
        self.assertTrue(np.allclose(expected_scores_per_class[i][j],
                                    self.od_eval.scores_per_class[i][j]))
        self.assertTrue(np.array_equal(expected_tp_fp_labels_per_class[i][
            j], self.od_eval.tp_fp_labels_per_class[i][j]))
    self.assertTrue(np.array_equal(
        expected_num_images_correctly_detected_per_class,
        self.od_eval.num_images_correctly_detected_per_class)) 
Example 8
Project: soccer-matlab   Author: utra-robosoccer   File: filter.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_combining_stat():
    for shape in [(), (3,), (3, 4)]:
        li = []
        rs1 = RunningStat(shape)
        rs2 = RunningStat(shape)
        rs = RunningStat(shape)
        for _ in range(5):
            val = np.random.randn(*shape)
            rs1.push(val)
            rs.push(val)
            li.append(val)
        for _ in range(9):
            rs2.push(val)
            rs.push(val)
            li.append(val)
        rs1.update(rs2)
        assert np.allclose(rs.mean, rs1.mean)
        assert np.allclose(rs.std, rs1.std) 
Example 9
Project: OpenFermion-Cirq   Author: quantumlib   File: optimal_givens_decomposition_test.py    License: Apache License 2.0 6 votes vote down vote up
def test_givens_inverse():
    r"""
    The Givens rotation in OpenFermion is defined as

    .. math::

        \begin{pmatrix}
            \cos(\theta) & -e^{i \varphi} \sin(\theta) \\
            \sin(\theta) &     e^{i \varphi} \cos(\theta)
        \end{pmatrix}.

    confirm numerically its hermitian conjugate is it's inverse
    """
    a = numpy.random.random() + 1j * numpy.random.random()
    b = numpy.random.random() + 1j * numpy.random.random()
    ab_rotation = givens_matrix_elements(a, b, which='right')

    assert numpy.allclose(ab_rotation.dot(numpy.conj(ab_rotation).T),
                          numpy.eye(2))
    assert numpy.allclose(numpy.conj(ab_rotation).T.dot(ab_rotation),
                          numpy.eye(2)) 
Example 10
Project: OpenFermion-Cirq   Author: quantumlib   File: optimal_givens_decomposition_test.py    License: Apache License 2.0 6 votes vote down vote up
def test_circuit_generation_and_accuracy():
    for dim in range(2, 10):
        qubits = cirq.LineQubit.range(dim)
        u_generator = numpy.random.random(
            (dim, dim)) + 1j * numpy.random.random((dim, dim))
        u_generator = u_generator - numpy.conj(u_generator).T
        assert numpy.allclose(-1 * u_generator, numpy.conj(u_generator).T)

        unitary = scipy.linalg.expm(u_generator)
        circuit = cirq.Circuit()
        circuit.append(optimal_givens_decomposition(qubits, unitary))

        fermion_generator = QubitOperator(()) * 0.0
        for i, j in product(range(dim), repeat=2):
            fermion_generator += jordan_wigner(
                FermionOperator(((i, 1), (j, 0)), u_generator[i, j]))

        true_unitary = scipy.linalg.expm(
            get_sparse_operator(fermion_generator).toarray())
        assert numpy.allclose(true_unitary.conj().T.dot(true_unitary),
                              numpy.eye(2 ** dim, dtype=complex))

        test_unitary = cirq.unitary(circuit)
        assert numpy.isclose(
            abs(numpy.trace(true_unitary.conj().T.dot(test_unitary))), 2 ** dim) 
Example 11
Project: OpenFermion-Cirq   Author: quantumlib   File: fermionic_simulation.py    License: Apache License 2.0 6 votes vote down vote up
def _eigen_components(self):
        components = [(0, np.diag([1, 1, 1, 0, 1, 0, 0, 1]))]
        nontrivial_part = np.zeros((3, 3), dtype=np.complex128)
        for ij, w in zip([(1, 2), (0, 2), (0, 1)], self.weights):
            nontrivial_part[ij] = w
            nontrivial_part[ij[::-1]] = w.conjugate()
        assert np.allclose(nontrivial_part, nontrivial_part.conj().T)
        eig_vals, eig_vecs = np.linalg.eigh(nontrivial_part)
        for eig_val, eig_vec in zip(eig_vals, eig_vecs.T):
            exp_factor = -eig_val / np.pi
            proj = np.zeros((8, 8), dtype=np.complex128)
            nontrivial_indices = np.array([3, 5, 6], dtype=np.intp)
            proj[nontrivial_indices[:, np.newaxis], nontrivial_indices] = (
                np.outer(eig_vec.conjugate(), eig_vec))
            components.append((exp_factor, proj))
        return components 
Example 12
Project: OpenFermion-Cirq   Author: quantumlib   File: fermionic_simulation_test.py    License: Apache License 2.0 6 votes vote down vote up
def assert_permute_consistent(gate):
    gate = gate.__copy__()
    n_qubits = gate.num_qubits()
    qubits = cirq.LineQubit.range(n_qubits)
    for pos in itertools.permutations(range(n_qubits)):
        permuted_gate = gate.__copy__()
        gate.permute(pos)
        assert permuted_gate.permuted(pos) == gate
        actual_unitary = cirq.unitary(permuted_gate)

        ops = [
            cca.LinearPermutationGate(n_qubits, dict(zip(range(n_qubits), pos)),
                                      ofc.FSWAP)(*qubits),
            gate(*qubits),
            cca.LinearPermutationGate(n_qubits, dict(zip(pos, range(n_qubits))),
                                      ofc.FSWAP)(*qubits)
        ]
        circuit = cirq.Circuit(ops)
        expected_unitary = cirq.unitary(circuit)
        assert np.allclose(actual_unitary, expected_unitary)

    with pytest.raises(ValueError):
        gate.permute(range(1, n_qubits))
    with pytest.raises(ValueError):
        gate.permute([1] * n_qubits) 
Example 13
Project: OpenFermion-Cirq   Author: quantumlib   File: fermionic_simulation_test.py    License: Apache License 2.0 6 votes vote down vote up
def assert_interaction_operator_consistent(gate):
    interaction_op = gate.interaction_operator_generator()
    other_gate = gate.from_interaction_operator(operator=interaction_op)
    if other_gate is None:
        assert np.allclose(gate.weights, 0)
    else:
        assert cirq.approx_eq(gate, other_gate)
    interaction_op = openfermion.normal_ordered(interaction_op)
    other_interaction_op = openfermion.InteractionOperator.zero(
        interaction_op.n_qubits)
    super(type(gate),
          gate).interaction_operator_generator(operator=other_interaction_op)
    other_interaction_op = openfermion.normal_ordered(interaction_op)
    assert interaction_op == other_interaction_op

    other_interaction_op = super(type(gate),
                                 gate).interaction_operator_generator()
    other_interaction_op = openfermion.normal_ordered(interaction_op)
    assert interaction_op == other_interaction_op 
Example 14
Project: OpenFermion-Cirq   Author: quantumlib   File: fermionic_simulation_test.py    License: Apache License 2.0 6 votes vote down vote up
def test_quadratic_fermionic_simulation_gate_unitary(weights, exponent):
    generator = np.zeros((4, 4), dtype=np.complex128)
    # w0 |10><01| + h.c.
    generator[2, 1] = weights[0]
    generator[1, 2] = weights[0].conjugate()
    # w1 |11><11|
    generator[3, 3] = weights[1]
    expected_unitary = la.expm(-1j * exponent * generator)

    gate = ofc.QuadraticFermionicSimulationGate(weights, exponent=exponent)
    actual_unitary = cirq.unitary(gate)

    assert np.allclose(expected_unitary, actual_unitary)

    symbolic_gate = (ofc.QuadraticFermionicSimulationGate(
        (sympy.Symbol('w0'), sympy.Symbol('w1')), exponent=sympy.Symbol('t')))
    qubits = cirq.LineQubit.range(2)
    circuit = cirq.Circuit(symbolic_gate._decompose_(qubits))
    resolver = {'w0': weights[0], 'w1': weights[1], 't': exponent}
    resolved_circuit = cirq.resolve_parameters(circuit, resolver)
    decomp_unitary = resolved_circuit.unitary(qubit_order=qubits)

    assert np.allclose(expected_unitary, decomp_unitary) 
Example 15
Project: OpenFermion-Cirq   Author: quantumlib   File: fermionic_simulation_test.py    License: Apache License 2.0 6 votes vote down vote up
def test_cubic_fermionic_simulation_gate_consistency_docstring(
        weights, exponent):
    generator = np.zeros((8, 8), dtype=np.complex128)
    # w0 |110><101| + h.c.
    generator[6, 5] = weights[0]
    generator[5, 6] = weights[0].conjugate()
    # w1 |110><011| + h.c.
    generator[6, 3] = weights[1]
    generator[3, 6] = weights[1].conjugate()
    # w2 |101><011| + h.c.
    generator[5, 3] = weights[2]
    generator[3, 5] = weights[2].conjugate()
    expected_unitary = la.expm(-1j * exponent * generator)

    gate = ofc.CubicFermionicSimulationGate(weights, exponent=exponent)
    actual_unitary = cirq.unitary(gate)

    assert np.allclose(expected_unitary, actual_unitary) 
Example 16
Project: OpenFermion-Cirq   Author: quantumlib   File: fermionic_simulation_test.py    License: Apache License 2.0 6 votes vote down vote up
def test_quartic_fermionic_simulation_unitary(weights, exponent):
    generator = np.zeros((1 << 4,) * 2, dtype=np.complex128)

    # w0 |1001><0110| + h.c.
    generator[9, 6] = weights[0]
    generator[6, 9] = weights[0].conjugate()
    # w1 |1010><0101| + h.c.
    generator[10, 5] = weights[1]
    generator[5, 10] = weights[1].conjugate()
    # w2 |1100><0011| + h.c.
    generator[12, 3] = weights[2]
    generator[3, 12] = weights[2].conjugate()
    expected_unitary = la.expm(-1j * exponent * generator)

    gate = ofc.QuarticFermionicSimulationGate(weights, exponent=exponent)
    actual_unitary = cirq.unitary(gate)

    assert np.allclose(expected_unitary, actual_unitary) 
Example 17
Project: OpenFermion-Cirq   Author: quantumlib   File: analysis_test.py    License: Apache License 2.0 6 votes vote down vote up
def test_energy_from_opdm_odd_qubit():
    """Build test assuming sampling functions work"""

    rhf_objective, molecule, parameters, obi, tbi = make_h3_2_5()
    unitary, energy, _ = rhf_func_generator(rhf_objective)

    parameters = np.array([0.1, 0.2])
    initial_opdm = np.diag([1] * 1 + [0] * 2)
    print(initial_opdm)
    final_opdm = unitary(parameters) @ initial_opdm @ unitary(
        parameters).conj().T
    test_energy = energy_from_opdm(final_opdm,
                                   constant=molecule.nuclear_repulsion,
                                   one_body_tensor=obi,
                                   two_body_tensor=tbi)
    true_energy = energy(parameters)
    assert np.allclose(test_energy, true_energy) 
Example 18
Project: OpenFermion-Cirq   Author: quantumlib   File: objective_test.py    License: Apache License 2.0 6 votes vote down vote up
def test_get_matrix_of_eigs():
    """
    Generate the matrix of [exp(i (li - lj)) - 1] / (i(li - lj)
    :return:
    """
    lam_vals = np.random.randn(4) + 1j * np.random.randn(4)
    mat_eigs = np.zeros((lam_vals.shape[0],
                         lam_vals.shape[0]),
                         dtype=np.complex128)
    for i, j in product(range(lam_vals.shape[0]), repeat=2):
        if np.isclose(abs(lam_vals[i] - lam_vals[j]), 0):
            mat_eigs[i, j] = 1
        else:
            mat_eigs[i, j] = (np.exp(1j * (lam_vals[i] - lam_vals[j])) - 1) / (
                        1j * (lam_vals[i] - lam_vals[j]))

    test_mat_eigs = get_matrix_of_eigs(lam_vals)
    assert np.allclose(test_mat_eigs, mat_eigs) 
Example 19
Project: OpenFermion-Cirq   Author: quantumlib   File: gradient_hf_test.py    License: Apache License 2.0 6 votes vote down vote up
def test_rhf_func_gen():
    rhf_objective, molecule, parameters, _, _ = make_h6_1_3()
    ansatz, energy, _ = rhf_func_generator(rhf_objective)
    assert np.isclose(molecule.hf_energy, energy(parameters))

    ansatz, energy, _, opdm_func = rhf_func_generator(
        rhf_objective, initial_occ_vec=[1] * 3 + [0] * 3, get_opdm_func=True)
    assert np.isclose(molecule.hf_energy, energy(parameters))
    test_opdm = opdm_func(parameters)
    u = ansatz(parameters)
    initial_opdm = np.diag([1] * 3 + [0] * 3)
    final_odpm = u @ initial_opdm @ u.T
    assert np.allclose(test_opdm, final_odpm)

    result = rhf_minimization(rhf_objective, initial_guess=parameters)
    assert np.allclose(result.x, parameters) 
Example 20
Project: OpenFermion-Cirq   Author: quantumlib   File: higham_test.py    License: Apache License 2.0 6 votes vote down vote up
def test_matrix_2_tensor():
    dim = 10
    np.random.seed(42)
    mat = np.random.random((dim**2, dim**2))
    mat = 0.5 * (mat + mat.T)
    tensor = map_to_tensor(mat)
    for p, q, r, s in product(range(dim), repeat=4):
        assert np.isclose(tensor[p, q, r, s], mat[p * dim + q, r * dim + s])

    test_mat = map_to_matrix(tensor)
    assert np.allclose(test_mat, mat)

    with pytest.raises(TypeError):
        map_to_tensor(np.zeros((4, 4, 4, 4)))

    with pytest.raises(TypeError):
        map_to_matrix(np.zeros((4, 4))) 
Example 21
Project: robosuite   Author: StanfordVL   File: transform_utils.py    License: MIT License 6 votes vote down vote up
def quat_multiply(quaternion1, quaternion0):
    """Return multiplication of two quaternions.
    >>> q = quat_multiply([1, -2, 3, 4], [-5, 6, 7, 8])
    >>> np.allclose(q, [-44, -14, 48, 28])
    True
    """
    x0, y0, z0, w0 = quaternion0
    x1, y1, z1, w1 = quaternion1
    return np.array(
        (
            x1 * w0 + y1 * z0 - z1 * y0 + w1 * x0,
            -x1 * z0 + y1 * w0 + z1 * x0 + w1 * y0,
            x1 * y0 - y1 * x0 + z1 * w0 + w1 * z0,
            -x1 * x0 - y1 * y0 - z1 * z0 + w1 * w0,
        ),
        dtype=np.float32,
    ) 
Example 22
Project: robosuite   Author: StanfordVL   File: transform_utils.py    License: MIT License 6 votes vote down vote up
def random_quat(rand=None):
    """Return uniform random unit quaternion.
    rand: array like or None
        Three independent random variables that are uniformly distributed
        between 0 and 1.
    >>> q = random_quat()
    >>> np.allclose(1.0, vector_norm(q))
    True
    >>> q = random_quat(np.random.random(3))
    >>> q.shape
    (4,)
    """
    if rand is None:
        rand = np.random.rand(3)
    else:
        assert len(rand) == 3
    r1 = np.sqrt(1.0 - rand[0])
    r2 = np.sqrt(rand[0])
    pi2 = math.pi * 2.0
    t1 = pi2 * rand[1]
    t2 = pi2 * rand[2]
    return np.array(
        (np.sin(t1) * r1, np.cos(t1) * r1, np.sin(t2) * r2, np.cos(t2) * r2),
        dtype=np.float32,
    ) 
Example 23
Project: QCElemental   Author: MolSSI   File: test_molecule.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_water_minima_fragment():

    mol = water_dimer_minima.copy()
    frag_0 = mol.get_fragment(0, orient=True)
    frag_1 = mol.get_fragment(1, orient=True)
    assert frag_0.get_hash() == "5f31757232a9a594c46073082534ca8a6806d367"
    assert frag_1.get_hash() == "bdc1f75bd1b7b999ff24783d7c1673452b91beb9"

    frag_0_1 = mol.get_fragment(0, 1)
    frag_1_0 = mol.get_fragment(1, 0)

    assert np.array_equal(mol.symbols[:3], frag_0.symbols)
    assert np.allclose(mol.masses[:3], frag_0.masses)

    assert np.array_equal(mol.symbols, frag_0_1.symbols)
    assert np.allclose(mol.geometry, frag_0_1.geometry)

    assert np.array_equal(np.hstack((mol.symbols[3:], mol.symbols[:3])), frag_1_0.symbols)
    assert np.allclose(np.hstack((mol.masses[3:], mol.masses[:3])), frag_1_0.masses) 
Example 24
Project: lirpg   Author: Hwhitetooth   File: mpi_moments.py    License: MIT License 6 votes vote down vote up
def _helper_runningmeanstd():
    comm = MPI.COMM_WORLD
    np.random.seed(0)
    for (triple,axis) in [
        ((np.random.randn(3), np.random.randn(4), np.random.randn(5)),0),
        ((np.random.randn(3,2), np.random.randn(4,2), np.random.randn(5,2)),0),
        ((np.random.randn(2,3), np.random.randn(2,4), np.random.randn(2,4)),1),
        ]:


        x = np.concatenate(triple, axis=axis)
        ms1 = [x.mean(axis=axis), x.std(axis=axis), x.shape[axis]]


        ms2 = mpi_moments(triple[comm.Get_rank()],axis=axis)

        for (a1,a2) in zipsame(ms1, ms2):
            print(a1, a2)
            assert np.allclose(a1, a2)
            print("ok!") 
Example 25
Project: lirpg   Author: Hwhitetooth   File: mpi_running_mean_std.py    License: MIT License 6 votes vote down vote up
def test_runningmeanstd():
    for (x1, x2, x3) in [
        (np.random.randn(3), np.random.randn(4), np.random.randn(5)),
        (np.random.randn(3,2), np.random.randn(4,2), np.random.randn(5,2)),
        ]:

        rms = RunningMeanStd(epsilon=0.0, shape=x1.shape[1:])
        U.initialize()

        x = np.concatenate([x1, x2, x3], axis=0)
        ms1 = [x.mean(axis=0), x.std(axis=0)]
        rms.update(x1)
        rms.update(x2)
        rms.update(x3)
        ms2 = [rms.mean.eval(), rms.std.eval()]

        assert np.allclose(ms1, ms2) 
Example 26
Project: aospy   Author: spencerahill   File: calc.py    License: Apache License 2.0 5 votes vote down vote up
def _add_grid_attributes(self, ds):
        """Add model grid attributes to a dataset"""
        for name_int, names_ext in self._grid_attrs.items():
            ds_coord_name = set(names_ext).intersection(set(ds.coords) |
                                                        set(ds.data_vars))
            model_attr = getattr(self.model, name_int, None)
            if ds_coord_name and (model_attr is not None):
                # Force coords to have desired name.
                ds = ds.rename({list(ds_coord_name)[0]: name_int})
                ds = ds.set_coords(name_int)
                if not np.array_equal(ds[name_int], model_attr):
                    if np.allclose(ds[name_int], model_attr):
                        msg = ("Values for '{0}' are nearly (but not exactly) "
                               "the same in the Run {1} and the Model {2}.  "
                               "Therefore replacing Run's values with the "
                               "model's.".format(name_int, self.run,
                                                 self.model))
                        logging.info(msg)
                        ds[name_int].values = model_attr.values
                    else:
                        msg = ("Model coordinates for '{0}' do not match those"
                               " in Run: {1} vs. {2}"
                               "".format(name_int, ds[name_int], model_attr))
                        logging.info(msg)

            else:
                # Bring in coord from model object if it exists.
                ds = ds.load()
                if model_attr is not None:
                    ds[name_int] = model_attr
                    ds = ds.set_coords(name_int)
            if (self.dtype_in_vert == 'pressure' and
                    internal_names.PLEVEL_STR in ds.coords):
                self.pressure = ds.level
        return ds 
Example 27
Project: mmdetection   Author: open-mmlab   File: test_transform.py    License: Apache License 2.0 5 votes vote down vote up
def test_normalize():
    img_norm_cfg = dict(
        mean=[123.675, 116.28, 103.53],
        std=[58.395, 57.12, 57.375],
        to_rgb=True)
    transform = dict(type='Normalize', **img_norm_cfg)
    transform = build_from_cfg(transform, PIPELINES)
    results = dict()
    img = mmcv.imread(
        osp.join(osp.dirname(__file__), '../data/color.jpg'), 'color')
    original_img = copy.deepcopy(img)
    results['img'] = img
    results['img2'] = copy.deepcopy(img)
    results['img_shape'] = img.shape
    results['ori_shape'] = img.shape
    # Set initial values for default meta_keys
    results['pad_shape'] = img.shape
    results['scale_factor'] = 1.0
    results['img_fields'] = ['img', 'img2']

    results = transform(results)
    assert np.equal(results['img'], results['img2']).all()

    mean = np.array(img_norm_cfg['mean'])
    std = np.array(img_norm_cfg['std'])
    converted_img = (original_img[..., ::-1] - mean) / std
    assert np.allclose(results['img'], converted_img) 
Example 28
Project: neural-fingerprinting   Author: StephanZheng   File: test_utils_keras.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_get_logits(self):
        import tensorflow as tf
        model = KerasModelWrapper(self.model)
        x = tf.placeholder(tf.float32, shape=(None, 100))
        preds = model.get_probs(x)
        logits = model.get_logits(x)

        x_val = np.random.rand(2, 100)
        tf.global_variables_initializer().run(session=self.sess)
        p_val, logits = self.sess.run([preds, logits], feed_dict={x: x_val})
        p_gt = np.exp(logits)/np.sum(np.exp(logits), axis=1, keepdims=True)
        self.assertTrue(np.allclose(p_val, p_gt, atol=1e-6)) 
Example 29
Project: neural-fingerprinting   Author: StephanZheng   File: test_utils_keras.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_get_probs(self):
        import tensorflow as tf
        model = KerasModelWrapper(self.model)
        x = tf.placeholder(tf.float32, shape=(None, 100))
        preds = model.get_probs(x)

        x_val = np.random.rand(2, 100)
        tf.global_variables_initializer().run(session=self.sess)
        p_val = self.sess.run(preds, feed_dict={x: x_val})
        self.assertTrue(np.allclose(np.sum(p_val, axis=1), 1, atol=1e-6))
        self.assertTrue(np.all(p_val>=0))
        self.assertTrue(np.all(p_val<=1)) 
Example 30
Project: neural-fingerprinting   Author: StephanZheng   File: test_utils_tf.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_l2_batch_normalize(self):
        with tf.Session() as sess:
            x = tf.random_normal((100, 1000))
            x_norm = sess.run(utils_tf.l2_batch_normalize(x))
            self.assertTrue(
                np.allclose(np.sum(x_norm**2, axis=1), 1, atol=1e-6))