def test_tf_gradient_correctness_with_symbols(self, n_qubits, batch_size, inner_dim_size): """Tests that tf.gradient of inner_product works with symbols.""" symbol_names = ['alpha', 'beta', 'gamma'] n_params = len(symbol_names) qubits = cirq.GridQubit.rect(1, n_qubits) circuit_batch, resolver_batch = \ util.random_symbol_circuit_resolver_batch( qubits, symbol_names, batch_size) other_batch = [0 for i in range(batch_size)] for i in range(len(other_batch)): other_batch[i] = copy.deepcopy(circuit_batch) for j in range(len(other_batch[i])): other_batch[i][j] = cirq.resolve_parameters( circuit_batch[i], resolver_batch[i]) symbol_values_array = np.array( [[resolver[symbol] for symbol in symbol_names] for resolver in resolver_batch]) programs = util.convert_to_tensor(circuit_batch) other_programs = util.convert_to_tensor(other_batch) symbol_names_tensor = tf.convert_to_tensor(symbol_names, dtype=tf.dtypes.string) symbol_values = tf.convert_to_tensor(symbol_values_array) with tf.GradientTape() as tape: tape.watch(symbol_values) ip = fidelity_op.fidelity(programs, symbol_names_tensor, symbol_values, other_programs) out = tape.gradient(ip, symbol_values) out_arr = np.zeros((batch_size, n_params), dtype=np.complex64) # dx came from _GRAD_EPS of core/src/adj_util.cc dx = 5e-3 for i in range(batch_size): for k, name in enumerate(symbol_names): if name in resolver_batch[i].param_dict: new_resolver = copy.deepcopy(resolver_batch[i]) new_resolver.param_dict[name] += dx final_circuit_p = cirq.resolve_parameters( circuit_batch[i], new_resolver) new_resolver = copy.deepcopy(resolver_batch[i]) new_resolver.param_dict[name] -= dx final_circuit_m = cirq.resolve_parameters( circuit_batch[i], new_resolver) final_wf_p = cirq.final_state_vector(final_circuit_p) final_wf_m = cirq.final_state_vector(final_circuit_m) # Performs central finite difference. for j in range(inner_dim_size): internal_wf = cirq.final_state_vector(other_batch[i][j]) fid_p = cirq.fidelity(final_wf_p, internal_wf) fid_m = cirq.fidelity(final_wf_m, internal_wf) grad_fid = 0.5 * (fid_p - fid_m) / dx out_arr[i][k] += grad_fid self.assertAllClose(out, out_arr, atol=1e-3) self.assertDTypeEqual(out, tf.float32.as_numpy_dtype)
def test_fidelity_invariant_under_unitary_transformation(): np.testing.assert_allclose( cirq.fidelity(cirq.density_matrix(MAT1), MAT2, qid_shape=(15, )), cirq.fidelity(cirq.density_matrix(U @ MAT1 @ U.T.conj()), U @ MAT2 @ U.T.conj(), qid_shape=(15, )), )
def test_fidelity_ints(): assert cirq.fidelity(3, 4) == 0.0 assert cirq.fidelity(4, 4) == 1.0 with pytest.raises(ValueError, match='non-negative'): _ = cirq.fidelity(-1, 2) with pytest.raises(ValueError, match='maximum'): _ = cirq.fidelity(4, 1, qid_shape=(2, )) with pytest.raises(ValueError, match='maximum'): _ = cirq.fidelity(1, 4, qid_shape=(2, ))
def test_fidelity_product_states(): a, b = cirq.LineQubit.range(2) np.testing.assert_allclose( cirq.fidelity(cirq.KET_ZERO(a) * cirq.KET_ZERO(b), cirq.KET_ZERO(a) * cirq.KET_ZERO(b)), 1.0 ) np.testing.assert_allclose( cirq.fidelity(cirq.KET_ZERO(a) * cirq.KET_ZERO(b), cirq.KET_ZERO(a) * cirq.KET_ONE(b)), 0.0, atol=1e-7, ) np.testing.assert_allclose( cirq.fidelity(cirq.KET_ZERO(a) * cirq.KET_ZERO(b), cirq.KET_ZERO(a) * cirq.KET_PLUS(b)), 0.5 ) np.testing.assert_allclose( cirq.fidelity(cirq.KET_ONE(a) * cirq.KET_ONE(b), cirq.KET_MINUS(a) * cirq.KET_PLUS(b)), 0.25 ) np.testing.assert_allclose( cirq.fidelity(cirq.KET_MINUS(a) * cirq.KET_PLUS(b), cirq.KET_MINUS(a) * cirq.KET_PLUS(b)), 1.0, ) np.testing.assert_allclose( cirq.fidelity(cirq.KET_MINUS(a) * cirq.KET_PLUS(b), cirq.KET_PLUS(a) * cirq.KET_MINUS(b)), 0.0, atol=1e-7, ) with pytest.raises(ValueError, match='Mismatched'): _ = cirq.fidelity(cirq.KET_MINUS(a), cirq.KET_PLUS(a) * cirq.KET_MINUS(b)) with pytest.raises(ValueError, match='qid shape'): _ = cirq.fidelity( cirq.KET_MINUS(a) * cirq.KET_PLUS(b), cirq.KET_PLUS(a) * cirq.KET_MINUS(b), qid_shape=(4,), )
def qft_qem_vag( gdata: Any, nnp: Tensor, preset: Sequence[int], n: int = 3, p_idle: float = 0.2, p_sep: float = 0.02, ) -> Tuple[Tensor, Tensor]: # gdata = None if gdata is None: prepend = unitary_design(n) else: prepend = gdata s = cirq.DensityMatrixSimulator() cset = get_op_pool() placeholder = [cset[j] for j in preset] qftc = qft_circuit(n) ideal = prepend + qftc pdm = s.simulate(ideal).final_density_matrix ncq = gapfilling(qftc, placeholder) ncq = noisyfy(ncq, p_idle=p_idle, p_sep=p_sep) ncq = prepend + ncq ndm = s.simulate(ncq).final_density_matrix loss = -cirq.fidelity(pdm, ndm) return tf.constant(loss, dtype=tf.float32), tf.zeros_like(nnp)
def test_fidelity_commuting_matrices(): d1 = np.random.uniform(size=N) d1 /= np.sum(d1) d2 = np.random.uniform(size=N) d2 /= np.sum(d2) mat1 = cirq.density_matrix(U @ np.diag(d1) @ U.T.conj()) mat2 = U @ np.diag(d2) @ U.T.conj() np.testing.assert_allclose(cirq.fidelity(mat1, mat2, qid_shape=(15, )), np.sum(np.sqrt(d1 * d2))**2)
def test_fidelity_symmetric(): np.testing.assert_allclose(cirq.fidelity(VEC1, VEC2), cirq.fidelity(VEC2, VEC1)) np.testing.assert_allclose(cirq.fidelity(VEC1, MAT1), cirq.fidelity(MAT1, VEC1)) np.testing.assert_allclose( cirq.fidelity(cirq.density_matrix(MAT1), MAT2), cirq.fidelity(cirq.density_matrix(MAT2), MAT1), )
def test_fidelity_between_zero_and_one(): assert 0 <= cirq.fidelity(VEC1, VEC2, qid_shape=(15, )) <= 1 assert 0 <= cirq.fidelity(VEC1, MAT1, qid_shape=(15, )) <= 1 assert 0 <= cirq.fidelity( cirq.density_matrix(MAT1), MAT2, qid_shape=(15, )) <= 1
def test_fidelity_bad_shape(): with pytest.raises(ValueError, match='Invalid quantum state'): _ = cirq.fidelity(np.array([[[1.0]]]), np.array([[[1.0]]]), qid_shape=(1, ))
def get_generator_fidelity_grid(generated): return [GeneratorsFidelityGrid(generated[i][1], generated[j][1], cirq.fidelity(generated[i][2], generated[j][2]), cirq.fidelity(generated[i][3], generated[j][3])) for i in range(len(generated)) for j in range(len(generated)) if i != j]
def test_fidelity_numpy_arrays(): vec1 = np.array([1, 0, 0, 0, 0, 0, 0, 0], dtype=np.complex64) vec2 = np.array([1, 0, 0, 0], dtype=np.complex64) tensor1 = np.reshape(vec1, (2, 2, 2)) tensor2 = np.reshape(vec2, (2, 2)) mat1 = np.outer(vec1, vec1.conj()) np.testing.assert_allclose(cirq.fidelity(vec1, vec1), 1) np.testing.assert_allclose(cirq.fidelity(vec1, tensor1), 1) np.testing.assert_allclose(cirq.fidelity(tensor1, vec1), 1) np.testing.assert_allclose(cirq.fidelity(vec1, mat1), 1) np.testing.assert_allclose(cirq.fidelity(tensor1, mat1), 1) np.testing.assert_allclose( cirq.fidelity(tensor2, tensor2, qid_shape=(2, 2)), 1) np.testing.assert_allclose(cirq.fidelity(mat1, mat1, qid_shape=(8, )), 1) with pytest.raises(ValueError, match='dimension'): _ = cirq.fidelity(vec1, vec1, qid_shape=(4, )) with pytest.raises(ValueError, match='Mismatched'): _ = cirq.fidelity(vec1, vec2) with pytest.raises(ValueError, match='ambiguous'): _ = cirq.fidelity(tensor2, tensor2) with pytest.raises(ValueError, match='ambiguous'): _ = cirq.fidelity(mat1, mat1)
def test_fidelity_between_zero_and_one(): assert 0 <= cirq.fidelity(VEC1, VEC2) <= 1 assert 0 <= cirq.fidelity(VEC1, MAT1) <= 1 assert 0 <= cirq.fidelity(cirq.density_matrix(MAT1), MAT2) <= 1
def get_fidelity_grid(generated, real): return [FidelityGrid(pg, lg, pr, lr, cirq.fidelity(g, r), cirq.fidelity(abs_g, abs_r)) for pr, lr, r, abs_r in real for pg, lg, g, abs_g in generated]
def test_fidelity_between_zero_and_one(): assert 0 <= cirq.fidelity(VEC1, VEC2) <= 1 assert 0 <= cirq.fidelity(VEC1, MAT1) <= 1 assert 0 <= cirq.fidelity(MAT1, MAT2) <= 1
def test_fidelity_bad_shape(): with pytest.raises(ValueError, match='dimensional'): _ = cirq.fidelity(np.array([[[1.0]]]), np.array([[[1.0]]]))
def test_fidelity_known_values(): vec1 = np.array([1, 1j, -1, -1j]) * 0.5 vec2 = np.array([1, -1, 1, -1]) * 0.5 mat1 = np.outer(vec1, vec1.conj()) mat2 = np.outer(vec2, vec2.conj()) mat3 = 0.3 * mat1 + 0.7 * mat2 np.testing.assert_allclose(cirq.fidelity(vec1, vec1), 1) np.testing.assert_allclose(cirq.fidelity(vec2, vec2), 1) np.testing.assert_allclose(cirq.fidelity(mat1, mat1), 1) np.testing.assert_allclose(cirq.fidelity(mat2, mat2), 1) np.testing.assert_allclose(cirq.fidelity(vec1, mat1), 1) np.testing.assert_allclose(cirq.fidelity(mat2, vec2), 1) np.testing.assert_allclose(cirq.fidelity(vec1, vec2), 0) np.testing.assert_allclose(cirq.fidelity(vec1, mat2), 0) np.testing.assert_allclose(cirq.fidelity(mat1, vec2), 0) np.testing.assert_allclose(cirq.fidelity(vec1, mat3), 0.3) np.testing.assert_allclose(cirq.fidelity(mat3, vec2), 0.7)
def test_fidelity_invariant_under_unitary_transformation(): np.testing.assert_allclose( cirq.fidelity(MAT1, MAT2), cirq.fidelity(U @ MAT1 @ U.T.conj(), U @ MAT2 @ U.T.conj()))
def test_fidelity_known_values(): vec1 = np.array([1, 1j, -1, -1j]) * 0.5 vec2 = np.array([1, -1, 1, -1], dtype=np.complex128) * 0.5 vec3 = np.array([1, 0, 0, 0], dtype=np.complex128) tensor1 = np.reshape(vec1, (2, 2)) mat1 = cirq.density_matrix(np.outer(vec1, vec1.conj())) mat2 = cirq.density_matrix(np.outer(vec2, vec2.conj())) mat3 = 0.3 * mat1.density_matrix() + 0.7 * mat2.density_matrix() np.testing.assert_allclose(cirq.fidelity(vec1, vec1, qid_shape=(4, )), 1) np.testing.assert_allclose(cirq.fidelity(vec2, vec2, qid_shape=(4, )), 1) np.testing.assert_allclose(cirq.fidelity(vec1, vec3, qid_shape=(4, )), 0.25) np.testing.assert_allclose(cirq.fidelity(vec1, tensor1, qid_shape=(4, )), 1) np.testing.assert_allclose(cirq.fidelity(tensor1, vec1, qid_shape=(2, 2)), 1) np.testing.assert_allclose(cirq.fidelity(mat1, mat1, qid_shape=(2, 2)), 1) np.testing.assert_allclose(cirq.fidelity(mat2, mat2, qid_shape=(2, 2)), 1) np.testing.assert_allclose(cirq.fidelity(vec1, mat1, qid_shape=(2, 2)), 1) np.testing.assert_allclose(cirq.fidelity(mat2, vec2, qid_shape=(2, 2)), 1) np.testing.assert_allclose(cirq.fidelity(vec1, vec2, qid_shape=(4, )), 0) np.testing.assert_allclose(cirq.fidelity(vec1, mat2, qid_shape=(2, 2)), 0) np.testing.assert_allclose(cirq.fidelity(mat1, vec2, qid_shape=(2, 2)), 0) np.testing.assert_allclose(cirq.fidelity(vec1, mat3, qid_shape=(2, 2)), 0.3) np.testing.assert_allclose(cirq.fidelity(tensor1, mat3, qid_shape=(2, 2)), 0.3) np.testing.assert_allclose(cirq.fidelity(mat3, tensor1, qid_shape=(2, 2)), 0.3) np.testing.assert_allclose(cirq.fidelity(mat3, vec2, qid_shape=(2, 2)), 0.7)
def test_fidelity_fail_inference(): state_vector = cirq.one_hot(shape=(4,), dtype=np.complex128) state_tensor = np.reshape(state_vector, (2, 2)) with pytest.raises(ValueError, match='Please specify'): _ = cirq.fidelity(state_tensor, 4)