Python numpy.allclose() Examples
The following are 30
code examples of numpy.allclose().
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 also want to check out all available functions/classes of the module
numpy
, or try the search function
.
Example #1
Source File: fermionic_simulation_test.py From OpenFermion-Cirq with Apache License 2.0 | 7 votes |
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 #2
Source File: analysis_test.py From OpenFermion-Cirq with Apache License 2.0 | 6 votes |
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 #3
Source File: higham_test.py From OpenFermion-Cirq with Apache License 2.0 | 6 votes |
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 #4
Source File: object_detection_evaluation_test.py From DOTA_models with Apache License 2.0 | 6 votes |
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 #5
Source File: object_detection_evaluation_test.py From DOTA_models with Apache License 2.0 | 6 votes |
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 #6
Source File: fermionic_simulation_test.py From OpenFermion-Cirq with Apache License 2.0 | 6 votes |
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 #7
Source File: filter.py From soccer-matlab with BSD 2-Clause "Simplified" License | 6 votes |
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 #8
Source File: fermionic_simulation_test.py From OpenFermion-Cirq with Apache License 2.0 | 6 votes |
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 #9
Source File: gradient_hf_test.py From OpenFermion-Cirq with Apache License 2.0 | 6 votes |
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 #10
Source File: transform_utils.py From robosuite with MIT License | 6 votes |
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 #11
Source File: tests_regression.py From discomll with Apache License 2.0 | 6 votes |
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 #12
Source File: objective_test.py From OpenFermion-Cirq with Apache License 2.0 | 6 votes |
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 #13
Source File: optimal_givens_decomposition_test.py From OpenFermion-Cirq with Apache License 2.0 | 6 votes |
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 #14
Source File: tests_classification.py From discomll with Apache License 2.0 | 6 votes |
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 #15
Source File: mpi_running_mean_std.py From lirpg with MIT License | 6 votes |
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 #16
Source File: mpi_moments.py From lirpg with MIT License | 6 votes |
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 #17
Source File: fermionic_simulation.py From OpenFermion-Cirq with Apache License 2.0 | 6 votes |
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 #18
Source File: fermionic_simulation_test.py From OpenFermion-Cirq with Apache License 2.0 | 6 votes |
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 #19
Source File: test_molecule.py From QCElemental with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #20
Source File: test_utils_tf.py From neural-fingerprinting with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #21
Source File: optimal_givens_decomposition_test.py From OpenFermion-Cirq with Apache License 2.0 | 6 votes |
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 #22
Source File: fermionic_simulation_test.py From OpenFermion-Cirq with Apache License 2.0 | 6 votes |
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 #23
Source File: test_separator.py From spleeter with MIT License | 6 votes |
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 #24
Source File: transform_utils.py From robosuite with MIT License | 6 votes |
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 #25
Source File: tests_classification.py From discomll with Apache License 2.0 | 6 votes |
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 #26
Source File: fermionic_simulation_test.py From OpenFermion-Cirq with Apache License 2.0 | 5 votes |
def test_fermionic_simulation_gate(gate): ofc.testing.assert_implements_consistent_protocols(gate) generator = gate.qubit_generator_matrix expected_unitary = la.expm(-1j * gate.exponent * generator) actual_unitary = cirq.unitary(gate) assert np.allclose(expected_unitary, actual_unitary) assert_fswap_consistent(gate) assert_permute_consistent(gate) assert_generators_consistent(gate) assert_resolution_consistent(gate) assert_interaction_operator_consistent(gate) assert gate.num_weights() == super(type(gate), gate).num_weights()
Example #27
Source File: fermionic_simulation_test.py From OpenFermion-Cirq with Apache License 2.0 | 5 votes |
def test_cubic_fermionic_simulation_gate_consistency_special(exponent, control): weights = tuple(np.eye(1, 3, control)[0] * 0.5 * np.pi) general_gate = ofc.CubicFermionicSimulationGate(weights, exponent=exponent) general_unitary = cirq.unitary(general_gate) indices = np.dot(list(itertools.product((0, 1), repeat=3)), (2**np.roll(np.arange(3), -control))[::-1]) special_gate = cirq.ControlledGate(cirq.ISWAP**-exponent) special_unitary = ( cirq.unitary(special_gate)[indices[:, np.newaxis], indices]) assert np.allclose(general_unitary, special_unitary)
Example #28
Source File: fermionic_simulation_test.py From OpenFermion-Cirq with Apache License 2.0 | 5 votes |
def assert_fswap_consistent(gate): gate = gate.__copy__() n_qubits = gate.num_qubits() for i in range(n_qubits - 1): fswap = cirq.kron(np.eye(1 << i), cirq.unitary(ofc.FSWAP), np.eye(1 << (n_qubits - i - 2))) assert fswap.shape == (1 << n_qubits,) * 2 generator = gate.qubit_generator_matrix fswapped_generator = np.linalg.multi_dot([fswap, generator, fswap]) gate.fswap(i) assert np.allclose(gate.qubit_generator_matrix, fswapped_generator) for i in (-1, n_qubits): with pytest.raises(ValueError): gate.fswap(i)
Example #29
Source File: util_test.py From OpenFermion-Cirq with Apache License 2.0 | 5 votes |
def test_gen_fswap_unitaries(): fswapu = generate_fswap_unitaries([((0, 1), (2, 3))], 4) true_generator = np.zeros((4, 4), dtype=np.complex128) true_generator[0, 0], true_generator[1, 1] = -1, -1 true_generator[0, 1], true_generator[1, 0] = 1, 1 true_generator[2, 2], true_generator[3, 3] = -1, -1 true_generator[2, 3], true_generator[3, 2] = 1, 1 true_u = sp.linalg.expm(-1j * np.pi * true_generator / 2) assert np.allclose(true_u, fswapu[0])
Example #30
Source File: analysis_test.py From OpenFermion-Cirq with Apache License 2.0 | 5 votes |
def test_energy_from_opdm(): """Build test assuming sampling functions work""" rhf_objective, molecule, parameters, obi, tbi = make_h6_1_3() unitary, energy, _ = rhf_func_generator(rhf_objective) parameters = np.array([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]) initial_opdm = np.diag([1] * 3 + [0] * 3) 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)