def test_param_resolver_param_dict(): exp_w = cg.ExpWGate(half_turns=cirq.Symbol('a'), axis_half_turns=0.0) circuit = cirq.Circuit() circuit.append(exp_w(Q1)) resolver = cirq.ParamResolver({'a': 0.5}) simulator = cg.XmonSimulator() result = simulator.run(circuit, resolver) assert result.params.param_dict == {'a': 0.5}
def test_param_resolver_param_dict(): exp_w = cirq.PhasedXPowGate(exponent=cirq.Symbol('a'), phase_exponent=0.0) circuit = cirq.Circuit() circuit.append(exp_w(Q1)) resolver = cirq.ParamResolver({'a': 0.5}) simulator = cg.XmonSimulator() result = simulator.run(circuit, resolver) assert result.params.param_dict == {'a': 0.5}
def test_parameterizable_effect(): q = cirq.NamedQubit('q') r = cirq.ParamResolver({'a': 0.5}) op1 = cirq.GateOperation(cirq.RotZGate(half_turns=cirq.Symbol('a')), [q]) assert cirq.is_parameterized(op1) op2 = cirq.resolve_parameters(op1, r) assert not cirq.is_parameterized(op2) assert op2 == cirq.S.on(q)
def test_param_resolver_exp_w_half_turns(): exp_w = cg.ExpWGate(half_turns=cirq.Symbol('a'), axis_half_turns=0.0) circuit = cirq.Circuit() circuit.append(exp_w(Q1)) resolver = cirq.ParamResolver({'a': -0.5}) result = compute_gate(circuit, resolver) amp = 1.0 / math.sqrt(2) np.testing.assert_almost_equal( result, np.array([[amp, amp * 1j], [amp * 1j, amp]]))
def test_param_resolver_exp_11_half_turns(): circuit = cirq.Circuit() circuit.append(cirq.CZ(Q1, Q2)**cirq.Symbol('a')) resolver = cirq.ParamResolver({'a': 0.5}) result = compute_gate(circuit, resolver, num_qubits=2) # Slight hack: doesn't depend on order of qubits. np.testing.assert_almost_equal( result, np.diag([1, 1, 1, cmath.exp(1j * math.pi * 0.5)]))
def test_circuit_param_and_reps(): sim = cg.XmonSimulator() circuit = bit_flip_circuit(cirq.Symbol('a'), cirq.Symbol('b')) resolvers = [cirq.ParamResolver({'a': b1, 'b': b2}) for b1 in range(2) for b2 in range(2)] all_trials = sim.run_sweep(circuit, params=resolvers, repetitions=3) assert len(all_trials) == 4 for result in all_trials: assert result.repetitions == 3 expect_a = result.params['a'] == 1 expect_b = result.params['b'] == 1 np.testing.assert_equal(result.measurements['q1'], [[expect_a]] * 3) np.testing.assert_equal(result.measurements['q2'], [[expect_b]] * 3) # All parameters explored. assert (set(itertools.product([0, 1], [0, 1])) == {(r.params['a'], r.params['b']) for r in all_trials})
def test_partial_reflection_as_self_inverse(): ex = cirq.Extensions() h0 = DummyGate(half_turns=0) h1 = DummyGate(half_turns=1) ha = DummyGate(half_turns=cirq.Symbol('a')) assert ex.try_cast(cirq.ReversibleEffect, h0) is h0 assert ex.try_cast(cirq.ReversibleEffect, h1) is h1 assert ex.try_cast(cirq.ReversibleEffect, ha) is None
def test_z_matrix(): assert np.allclose(cirq.unitary(cirq.Z), np.array([[1, 0], [0, -1]])) assert np.allclose(cirq.unitary(cirq.Z**0.5), np.array([[1, 0], [0, 1j]])) assert np.allclose(cirq.unitary(cirq.Z**0), np.array([[1, 0], [0, 1]])) assert np.allclose(cirq.unitary(cirq.Z**-0.5), np.array([[1, 0], [0, -1j]])) cirq.testing.assert_apply_unitary_to_tensor_is_consistent_with_unitary( val=cirq.Z, exponents=[1, 0.5, -0.25, cirq.Symbol('s')])
def test_h_matrix(): sqrt = cirq.unitary(cirq.H**0.5) m = np.dot(sqrt, sqrt) assert np.allclose(m, cirq.unitary(cirq.H), atol=1e-8) cirq.testing.assert_apply_unitary_to_tensor_is_consistent_with_unitary( val=cirq.H, exponents=[1, -0.5, 0.5, 0.25, -0.25, 0.1, cirq.Symbol('s')])
def test_approx_eq(): assert cirq.approx_eq(CExpZinGate(1.5), CExpZinGate(1.5), atol=0.1) assert cirq.approx_eq(CExpZinGate(1.5), CExpZinGate(1.7), atol=0.3) assert not cirq.approx_eq(CExpZinGate(1.5), CExpZinGate(1.7), atol=0.1) assert cirq.approx_eq(ZGateDef(exponent=1.5), ZGateDef(exponent=1.5), atol=0.1) assert not cirq.approx_eq( CExpZinGate(1.5), ZGateDef(exponent=1.5), atol=0.1) assert not cirq.approx_eq( ZGateDef(exponent=1.5), ZGateDef(exponent=cirq.Symbol('a')), atol=0.1) assert cirq.approx_eq(CExpZinGate(cirq.Symbol('a')), CExpZinGate(cirq.Symbol('a')), atol=0.1) assert not cirq.approx_eq( CExpZinGate(cirq.Symbol('a')), CExpZinGate(cirq.Symbol('b')), atol=0.1)
def test_eq(): eq = cirq.testing.EqualsTester() eq.make_equality_group(lambda: CExpZinGate(quarter_turns=0.1)) eq.add_equality_group(CExpZinGate(0), CExpZinGate(4), CExpZinGate(-4)) # Equates by canonicalized period. eq.add_equality_group(CExpZinGate(1.5), CExpZinGate(41.5)) eq.add_equality_group(CExpZinGate(3.5), CExpZinGate(-0.5)) eq.add_equality_group(CExpZinGate(2.5)) eq.add_equality_group(CExpZinGate(2.25)) eq.make_equality_group(lambda: cirq.Symbol('a')) eq.add_equality_group(cirq.Symbol('b')) eq.add_equality_group(ZGateDef(exponent=0.5, global_shift=0.0)) eq.add_equality_group(ZGateDef(exponent=-0.5, global_shift=0.0)) eq.add_equality_group(ZGateDef(exponent=0.5, global_shift=0.5)) eq.add_equality_group(ZGateDef(exponent=1.0, global_shift=0.5))
def test_parameterizable(): a = cirq.Symbol('a') qubits = cirq.LineQubit.range(3) cz = cirq.ControlledOperation(qubits[0], cirq.Z(qubits[1])) cza = cirq.ControlledOperation(qubits[0], cirq.ZPowGate(exponent=a)(qubits[1])) assert cirq.is_parameterized(cza) assert not cirq.is_parameterized(cz) assert cirq.resolve_parameters(cza, cirq.ParamResolver({'a': 1})) == cz
def test_decomposes_despite_symbol(): q0, q1 = cirq.NamedQubit('q0'), cirq.NamedQubit('q1') gate = cirq.PauliInteractionGate(cirq.Pauli.Z, False, cirq.Pauli.X, False, half_turns=cirq.Symbol('x')) op_tree = gate.default_decompose([q0, q1]) ops = tuple(cirq.flatten_op_tree(op_tree)) assert ops
def test_depolarizer_multiple_realizations(): q1 = cirq.NamedQubit('q1') q2 = cirq.NamedQubit('q2') cnot = Job(cirq.Circuit([ cirq.Moment([cirq.CNOT(q1, q2)]), ])) all_errors3 = DepolarizerChannel(probability=1.0, realizations=3) p0 = cirq.Symbol(DepolarizerChannel._parameter_name + '0') p1 = cirq.Symbol(DepolarizerChannel._parameter_name + '1') error_sweep = (cirq.Points(p0.name, [1.0, 1.0, 1.0]) + cirq.Points(p1.name, [1.0, 1.0, 1.0])) cnot_then_z3 = Job( cirq.Circuit([ cirq.Moment([cirq.CNOT(q1, q2)]), cirq.Moment([cirq.Z(q1)**p0, cirq.Z(q2)**p1]) ]), cnot.sweep * error_sweep) assert all_errors3.transform_job(cnot) == cnot_then_z3
def test_two_qubit_extrapolate(): cz2 = cirq.TwoQubitMatrixGate(np.diag([1, 1, 1, 1j])) cz4 = cirq.TwoQubitMatrixGate(np.diag([1, 1, 1, (1 + 1j) * np.sqrt(0.5)])) i = cirq.TwoQubitMatrixGate(np.eye(4)) assert (cz2**0).approx_eq(i) assert (cz4**0).approx_eq(i) assert (cz2**0.5).approx_eq(cz4) with pytest.raises(TypeError): _ = cz2**cirq.Symbol('a')
def test_param_resolver_exp_w_axis_half_turns(): exp_w = cirq.PhasedXPowGate( exponent=1.0, phase_exponent=cirq.Symbol('a')) circuit = cirq.Circuit() circuit.append(exp_w(Q1)) resolver = cirq.ParamResolver({'a': 0.5}) result = compute_gate(circuit, resolver) np.testing.assert_almost_equal(result, np.array([[0, -1], [1, 0]]))
def test_pow(): assert CExpZinGate(0.25)**2 == CExpZinGate(0.5) assert CExpZinGate(0.25)**-1 == CExpZinGate(-0.25) assert CExpZinGate(0.25)**0 == CExpZinGate(0) with pytest.raises(TypeError): _ = CExpZinGate(cirq.Symbol('a'))**1.5 assert ZGateDef(exponent=0.25)**2 == ZGateDef(exponent=0.5) assert ZGateDef(exponent=0.25, global_shift_in_half_turns=0.5)**2 == ZGateDef( exponent=0.5, global_shift_in_half_turns=0.5)
def test_param_resolver_exp_z_half_turns(): exp_z = cg.ExpZGate(half_turns=cirq.Symbol('a')) circuit = cirq.Circuit() circuit.append(exp_z(Q1)) resolver = cirq.ParamResolver({'a': -0.5}) result = compute_gate(circuit, resolver) np.testing.assert_almost_equal( result, np.array([[cmath.exp(1j * math.pi * 0.25), 0], [0, cmath.exp(-1j * math.pi * 0.25)]]))
def test_run_sweeps_param_resolvers(dtype): q0, q1 = cirq.LineQubit.range(2) simulator = cirq.Simulator(dtype=dtype) for b0 in [0, 1]: for b1 in [0, 1]: circuit = cirq.Circuit.from_ops((cirq.X**cirq.Symbol('b0'))(q0), (cirq.X**cirq.Symbol('b1'))(q1), cirq.measure(q0), cirq.measure(q1)) params = [cirq.ParamResolver({'b0': b0, 'b1': b1}), cirq.ParamResolver({'b0': b1, 'b1': b0})] results = simulator.run_sweep(circuit, params=params) assert len(results) == 2 np.testing.assert_equal(results[0].measurements, {'0': [[b0]], '1': [[b1]] }) np.testing.assert_equal(results[1].measurements, {'0': [[b1]], '1': [[b0]] }) assert results[0].params == params[0] assert results[1].params == params[1]
def test_iswap_matrix(): cirq.testing.assert_allclose_up_to_global_phase(cirq.unitary(cirq.ISWAP), np.array([[1, 0, 0, 0], [0, 0, 1j, 0], [0, 1j, 0, 0], [0, 0, 0, 1]]), atol=1e-8) cirq.testing.assert_apply_unitary_to_tensor_is_consistent_with_unitary( val=cirq.ISWAP, exponents=[1, 0.5, -0.25, cirq.Symbol('s')])
def test_parameterized_value_from_proto(): from_proto = cg.XmonGate.parameterized_value_from_proto_dict m1 = {'raw': 5} assert from_proto(m1) == 5 with pytest.raises(ValueError): from_proto({}) m3 = {'parameter_key': 'rr'} assert from_proto(m3) == cirq.Symbol('rr')
def _get_unitary_symbols(self): """Returns a list of symbols required for the unitary ansatz.""" # TODO: take into account the number of layers in the unitary # this should change how num_angles_required_for_unitary() is called # and the implementation of this method should change # the input arguments to this method should also include the number # of layers, as should num_angles_required_for_unitary() num_symbols_required = self.num_angles_required_for_unitary() return np.array( [cirq.Symbol(ii) for ii in range(num_symbols_required)] )
def test_w_diagram_chars(): q = cirq.GridQubit(0, 1) c = cirq.Circuit.from_ops( cg.ExpWGate(axis_half_turns=0).on(q), cg.ExpWGate(axis_half_turns=0.25).on(q), cg.ExpWGate(axis_half_turns=0.5).on(q), cg.ExpWGate(axis_half_turns=cirq.Symbol('a')).on(q), ) assert c.to_text_diagram() == """ (0, 1): ───X───W(0.25)───Y───W(a)─── """.strip()
def test_split_operator_trotter_ansatz_params(): ansatz = SplitOperatorTrotterAnsatz(hubbard_hamiltonian) assert (set(ansatz.params()) == { cirq.Symbol(name) for name in { 'U_0_0', 'U_1_0', 'U_6_0', 'U_7_0', 'V_0_1_0', 'V_2_3_0', 'V_4_5_0', 'V_6_7_0' } }) ansatz = SplitOperatorTrotterAnsatz(hubbard_hamiltonian, iterations=2) assert (set(ansatz.params()) == { cirq.Symbol(name) for name in { 'U_0_0', 'U_1_0', 'U_6_0', 'U_7_0', 'V_0_1_0', 'V_2_3_0', 'V_4_5_0', 'V_6_7_0', 'U_0_1', 'U_1_1', 'U_6_1', 'U_7_1', 'V_0_1_1', 'V_2_3_1', 'V_4_5_1', 'V_6_7_1' } })
def test_depolarizer_parameterized_gates(): q1 = cirq.NamedQubit('q1') q2 = cirq.NamedQubit('q2') cnot_param = cirq.Symbol('cnot_turns') cnot_gate = cirq.CZ(q1, q2)**cnot_param job_sweep = cirq.Points('cnot_turns', [0.5]) cnot = Job(cirq.Circuit([cirq.Moment([cnot_gate])]), job_sweep) all_errors = DepolarizerChannel(probability=1.0) p0 = cirq.Symbol(DepolarizerChannel._parameter_name + '0') p1 = cirq.Symbol(DepolarizerChannel._parameter_name + '1') error_sweep = cirq.Points(p0.name, [1.0]) + cirq.Points(p1.name, [1.0]) cnot_then_z = Job( cirq.Circuit([ cirq.Moment([cnot_gate]), cirq.Moment([cirq.Z(q1)**p0, cirq.Z(q2)**p1]) ]), job_sweep * error_sweep) assert all_errors.transform_job(cnot) == cnot_then_z
def test_w_diagram_chars(): q = cirq.GridQubit(0, 1) c = cirq.Circuit.from_ops( cg.ExpWGate(phase_exponent=0).on(q), cg.ExpWGate(phase_exponent=0.25).on(q), cg.ExpWGate(phase_exponent=0.5).on(q), cg.ExpWGate(phase_exponent=cirq.Symbol('a')).on(q), ) cirq.testing.assert_has_diagram(c, """ (0, 1): ───X───W(0.25)───Y───W(a)─── """)
def test_blocked_by_unknown_and_symbols(): a = cirq.NamedQubit('a') b = cirq.NamedQubit('b') assert_optimizes( before=quick_circuit( [cirq.X(a)], [cirq.SWAP(a, b)], [cirq.X(a)], ), expected=quick_circuit( [cirq.X(a)], [cirq.SWAP(a, b)], [cirq.X(a)], )) assert_optimizes( before=quick_circuit( [cirq.X(a)], [cirq.Z(a)**cirq.Symbol('z')], [cirq.X(a)], ), expected=quick_circuit( [cirq.X(a)], [cirq.Z(a)**cirq.Symbol('z')], [cirq.X(a)], ), compare_unitaries=False) assert_optimizes( before=quick_circuit( [cirq.X(a)], [cirq.CZ(a, b)**cirq.Symbol('z')], [cirq.X(a)], ), expected=quick_circuit( [cirq.X(a)], [cirq.CZ(a, b)**cirq.Symbol('z')], [cirq.X(a)], ), compare_unitaries=False)
def test_blocked_by_unknown_and_symbols(): a = cirq.NamedQubit('a') b = cirq.NamedQubit('b') assert_optimizes( before=quick_circuit( [cg.ExpWGate().on(a)], [cirq.SWAP(a, b)], [cg.ExpWGate().on(a)], ), expected=quick_circuit( [cg.ExpWGate().on(a)], [cirq.SWAP(a, b)], [cg.ExpWGate().on(a)], )) assert_optimizes( before=quick_circuit( [cg.ExpWGate().on(a)], [cg.ExpZGate(half_turns=cirq.Symbol('z')).on(a)], [cg.ExpWGate().on(a)], ), expected=quick_circuit( [cg.ExpWGate().on(a)], [cg.ExpZGate(half_turns=cirq.Symbol('z')).on(a)], [cg.ExpWGate().on(a)], ), compare_unitaries=False) assert_optimizes( before=quick_circuit( [cg.ExpWGate().on(a)], [cg.Exp11Gate(half_turns=cirq.Symbol('z')).on(a, b)], [cg.ExpWGate().on(a)], ), expected=quick_circuit( [cg.ExpWGate().on(a)], [cg.Exp11Gate(half_turns=cirq.Symbol('z')).on(a, b)], [cg.ExpWGate().on(a)], ), compare_unitaries=False)
def test_swap_network_trotter_ansatz_params(): ansatz = SwapNetworkTrotterAnsatz(hubbard_hamiltonian) assert (set(ansatz.params()) == { cirq.Symbol(name) for name in { 'T_0_2_0', 'T_4_6_0', 'T_1_3_0', 'T_5_7_0', 'T_0_4_0', 'T_2_6_0', 'T_1_5_0', 'T_3_7_0', 'V_0_1_0', 'V_2_3_0', 'V_4_5_0', 'V_6_7_0' } }) ansatz = SwapNetworkTrotterAnsatz(hubbard_hamiltonian, iterations=2) assert (set(ansatz.params()) == { cirq.Symbol(name) for name in { 'T_0_2_0', 'T_4_6_0', 'T_1_3_0', 'T_5_7_0', 'T_0_4_0', 'T_2_6_0', 'T_1_5_0', 'T_3_7_0', 'V_0_1_0', 'V_2_3_0', 'V_4_5_0', 'V_6_7_0', 'T_0_2_1', 'T_4_6_1', 'T_1_3_1', 'T_5_7_1', 'T_0_4_1', 'T_2_6_1', 'T_1_5_1', 'T_3_7_1', 'V_0_1_1', 'V_2_3_1', 'V_4_5_1', 'V_6_7_1' } })
def test_matrix(): np.testing.assert_allclose(cirq.unitary(CExpZinGate(1)), np.diag([1, 1, 1j, -1j]), atol=1e-8) np.testing.assert_allclose(cirq.unitary(CExpZinGate(2)), np.diag([1, 1, -1, -1]), atol=1e-8) np.testing.assert_allclose(cirq.unitary(CExpZinGate(3)), np.diag([1, 1, -1j, 1j]), atol=1e-8) np.testing.assert_allclose(cirq.unitary(CExpZinGate(4)), np.diag([1, 1, 1, 1]), atol=1e-8) np.testing.assert_allclose(cirq.unitary(CExpZinGate(0.00001)), cirq.unitary(CExpZinGate(3.99999)), atol=1e-4) assert not np.allclose(cirq.unitary(CExpZinGate(0.00001)), cirq.unitary(CExpZinGate(1.99999)), atol=1e-4) assert cirq.unitary(CExpZinGate(cirq.Symbol('a')), None) is None np.testing.assert_allclose(cirq.unitary(ZGateDef(exponent=0)), np.eye(2), atol=1e-8) np.testing.assert_allclose(cirq.unitary(ZGateDef(exponent=1)), np.diag([1, -1]), atol=1e-8) np.testing.assert_allclose(cirq.unitary(ZGateDef(exponent=0.5)), np.diag([1, 1j]), atol=1e-8) np.testing.assert_allclose(cirq.unitary( ZGateDef(exponent=1, global_shift_in_half_turns=0.5)), np.diag([1j, -1j]), atol=1e-8) np.testing.assert_allclose(cirq.unitary( ZGateDef(exponent=0.5, global_shift_in_half_turns=0.5)), np.diag([1 + 1j, -1 + 1j]) / np.sqrt(2), atol=1e-8) np.testing.assert_allclose(cirq.unitary( ZGateDef(exponent=0.5, global_shift_in_half_turns=-0.5)), np.diag([1 - 1j, 1 + 1j]) / np.sqrt(2), atol=1e-8)