def test_serializable_device_str_named_qubits(): device = cg.SerializableDevice( qubits=[cirq.NamedQubit('a'), cirq.NamedQubit('b')], gate_definitions={}) assert device.__class__.__name__ in str(device)
def test_toggles_measurements(): a = cirq.NamedQubit('a') b = cirq.NamedQubit('b') x = sympy.Symbol('x') # Single. assert_optimizes( before=quick_circuit( [cirq.PhasedXPowGate(phase_exponent=0.25).on(a)], [cirq.measure(a, b)], ), expected=quick_circuit( [], [cirq.measure(a, b, invert_mask=(True, ))], ), ) assert_optimizes( before=quick_circuit( [cirq.PhasedXPowGate(phase_exponent=0.25).on(b)], [cirq.measure(a, b)], ), expected=quick_circuit( [], [cirq.measure(a, b, invert_mask=(False, True))], ), ) assert_optimizes( before=quick_circuit( [cirq.PhasedXPowGate(phase_exponent=x).on(b)], [cirq.measure(a, b)], ), expected=quick_circuit( [], [cirq.measure(a, b, invert_mask=(False, True))], ), eject_parameterized=True, ) # Multiple. assert_optimizes( before=quick_circuit( [cirq.PhasedXPowGate(phase_exponent=0.25).on(a)], [cirq.PhasedXPowGate(phase_exponent=0.25).on(b)], [cirq.measure(a, b)], ), expected=quick_circuit( [], [], [cirq.measure(a, b, invert_mask=(True, True))], ), ) # Xmon. assert_optimizes( before=quick_circuit( [cirq.PhasedXPowGate(phase_exponent=0.25).on(a)], [cirq.measure(a, b, key='t')], ), expected=quick_circuit( [], [cirq.measure(a, b, invert_mask=(True, ), key='t')], ), )
def test_phases_partial_ws(): q = cirq.NamedQubit('q') x = sympy.Symbol('x') y = sympy.Symbol('y') z = sympy.Symbol('z') assert_optimizes( before=quick_circuit( [cirq.X(q)], [cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(q)], ), expected=quick_circuit( [], [cirq.PhasedXPowGate(phase_exponent=-0.25, exponent=0.5).on(q)], [cirq.X(q)], ), ) assert_optimizes( before=quick_circuit( [cirq.PhasedXPowGate(phase_exponent=0.25).on(q)], [cirq.X(q)**0.5], ), expected=quick_circuit( [], [cirq.PhasedXPowGate(phase_exponent=0.5, exponent=0.5).on(q)], [cirq.PhasedXPowGate(phase_exponent=0.25).on(q)], ), ) assert_optimizes( before=quick_circuit( [cirq.PhasedXPowGate(phase_exponent=0.25).on(q)], [cirq.PhasedXPowGate(phase_exponent=0.5, exponent=0.75).on(q)], ), expected=quick_circuit( [], [cirq.X(q)**0.75], [cirq.PhasedXPowGate(phase_exponent=0.25).on(q)], ), ) assert_optimizes( before=quick_circuit( [cirq.X(q)], [cirq.PhasedXPowGate(exponent=-0.25, phase_exponent=0.5).on(q)]), expected=quick_circuit( [], [cirq.PhasedXPowGate(exponent=-0.25, phase_exponent=-0.5).on(q)], [cirq.X(q)], ), ) assert_optimizes( before=quick_circuit( [cirq.PhasedXPowGate(phase_exponent=x).on(q)], [cirq.PhasedXPowGate(phase_exponent=y, exponent=z).on(q)], ), expected=quick_circuit( [], [cirq.PhasedXPowGate(phase_exponent=2 * x - y, exponent=z).on(q)], [cirq.PhasedXPowGate(phase_exponent=x).on(q)], ), eject_parameterized=True, )
def test_single_z_stays(): q = cirq.NamedQubit('q') assert_optimizes( before=cirq.Circuit([cirq.Moment([cirq.Z(q)**0.5])]), expected=cirq.Circuit([cirq.Moment([cirq.Z(q)**0.5])]), )
def test_moment_text_diagram(): a, b, c, d = cirq.GridQubit.rect(2, 2) m = cirq.Moment(cirq.CZ(a, b), cirq.CNOT(c, d)) assert (str(m).strip() == """ ╷ 0 1 ╶─┼───── 0 │ @─@ │ 1 │ @─X │ """.strip()) m = cirq.Moment(cirq.CZ(a, b), cirq.CNOT(c, d)) cirq.testing.assert_has_diagram( m, """ ╷ None 0 1 ╶──┼────────── aa │ │ 0 │ @─@ │ 1 │ @─X │ """, extra_qubits=[cirq.NamedQubit("aa")], ) m = cirq.Moment(cirq.S(c), cirq.ISWAP(a, d)) cirq.testing.assert_has_diagram( m, """ ╷ 0 1 ╶─┼───────────── 0 │ iSwap─┐ │ │ 1 │ S iSwap │ """, ) m = cirq.Moment(cirq.S(c)**0.1, cirq.ISWAP(a, d)**0.5) cirq.testing.assert_has_diagram( m, """ ╷ 0 1 ╶─┼───────────────── 0 │ iSwap^0.5─┐ │ │ 1 │ Z^0.05 iSwap │ """, ) a, b, c = cirq.LineQubit.range(3) m = cirq.Moment(cirq.X(a), cirq.SWAP(b, c)) cirq.testing.assert_has_diagram( m, """ ╷ a b c ╶─┼─────── 0 │ X │ 1 │ ×─┐ │ │ 2 │ × │ """, xy_breakdown_func=lambda q: ('abc'[q.x], q.x), ) class EmptyGate(cirq.Gate): def _num_qubits_(self) -> int: return 1 def __str__(self): return 'Empty' m = cirq.Moment(EmptyGate().on(a)) cirq.testing.assert_has_diagram( m, """ ╷ 0 ╶─┼─────── 0 │ Empty │ """, )
def test_cnot_keyword_too_few_arguments(): a = cirq.NamedQubit('a') with pytest.raises(ValueError): _ = cirq.CNOT(control=a)
def test_cnot_unknown_keyword_argument(): a = cirq.NamedQubit('a') b = cirq.NamedQubit('b') with pytest.raises(ValueError): _ = cirq.CNOT(target=a, controlled=b)
class TestOperationValidation: """Nativity and validation of various operations.""" @pytest.mark.parametrize('gate', native_1q_gates) @pytest.mark.parametrize('q', [0, 2, 3]) def test_native_single_qubit_gates(self, apollo, gate, q): """Native operations must pass validation.""" apollo.validate_operation(gate(apollo.qubits[q])) apollo.validate_operation(gate(apollo.qubits[q]).with_tags('tag_foo')) @pytest.mark.parametrize('gate', native_2q_gates) def test_native_two_qubit_gates(self, apollo, gate): """Native operations must pass validation.""" q0, q1 = apollo.qubits[:2] apollo.validate_operation(gate(q0, q1)) apollo.validate_operation(gate(q1, q0)) @pytest.mark.parametrize('meas', [ cirq.measure, lambda q: cirq.measure(q, key='test'), ]) def test_native_measurements(self, apollo, meas): """Native operations must pass validation.""" apollo.validate_operation(meas(apollo.qubits[0])) @pytest.mark.parametrize('gate', non_native_1q_gates) def test_non_native_single_qubit_gates(self, apollo, gate): """Non-native operations must not pass validation.""" q0 = apollo.qubits[0] with pytest.raises(ValueError, match='Unsupported gate type'): apollo.validate_operation(gate(q0)) with pytest.raises(ValueError, match='Unsupported gate type'): apollo.validate_operation(gate(q0).with_tags('tag_foo')) @pytest.mark.parametrize('gate', non_native_2q_gates) def test_non_native_two_qubit_gates(self, apollo, gate): """Non-native operations must not pass validation.""" q0, q1 = apollo.qubits[:2] with pytest.raises(ValueError, match='Unsupported gate type'): apollo.validate_operation(gate(q0, q1)) with pytest.raises(ValueError, match='Unsupported gate type'): apollo.validate_operation(gate(q1, q0)) @pytest.mark.parametrize('qubit', [ cirq.NamedQubit('xxx'), cirq.GridQubit(0, 1), ]) def test_qubits_not_on_device(self, apollo, qubit): """Gates operating on qubits not on device must not pass validation.""" with pytest.raises(ValueError, match='Qubit not on device'): apollo.validate_operation(cirq.X(qubit)) @pytest.mark.parametrize('gate', native_2q_gates) def test_qubits_not_connected(self, apollo, gate): """Native two-qubit gates operating on non-connected qubits must not pass validation.""" q0, _, q2 = apollo.qubits[:3] with pytest.raises(ValueError, match='Unsupported qubit connectivity'): apollo.validate_operation(gate(q0, q2)) with pytest.raises(ValueError, match='Unsupported qubit connectivity'): apollo.validate_operation(gate(q2, q0))
def test_inverse_matrix(gate): q0 = cirq.NamedQubit('q0') mat = cirq.Circuit.from_ops(gate(q0)).to_unitary_matrix() mat_inv = cirq.Circuit.from_ops(gate.inverse()(q0)).to_unitary_matrix() assert_allclose_up_to_global_phase(mat, mat_inv.T.conj(), rtol=1e-7, atol=1e-7)
def test_no_symbolic_qasm_but_fails_gracefully(): q = cirq.NamedQubit('q') v = cirq.PhasedXPowGate(phase_exponent=cirq.Symbol('p')).on(q) assert cirq.qasm(v, args=cirq.QasmArgs(), default=None) is None
def qubits(self): return [ cirq.NamedQubit('Alice'), cirq.NamedQubit('Bob'), cirq.NamedQubit('Charlie'), cirq.NamedQubit('Dan'), cirq.NamedQubit('Eve'), cirq.NamedQubit('Faythe'), cirq.NamedQubit('Grace'), cirq.NamedQubit('Heidi'), cirq.NamedQubit('Ivan'), cirq.NamedQubit('Judy'), cirq.NamedQubit('Kiuas'), cirq.NamedQubit('Leon'), cirq.NamedQubit('Mallory'), cirq.NamedQubit('Niaj'), cirq.NamedQubit('Olivia'), cirq.NamedQubit('Peggy'), cirq.NamedQubit('Quant'), cirq.NamedQubit('Rupert'), cirq.NamedQubit('Sybil'), cirq.NamedQubit('Trent') ]
def _make_qubits(n): return [cirq.NamedQubit('q{}'.format(i)) for i in range(n)]
def test_contains(qubit_pauli_map): other = cirq.NamedQubit('other') pauli_string = PauliString(qubit_pauli_map) for key in qubit_pauli_map: assert key in pauli_string assert other not in pauli_string
def test_imports_cirq_by_default(): cirq.testing.assert_equivalent_repr(cirq.NamedQubit('a'))
def test_bitstring_accumulator_equality(): et = cirq.testing.EqualsTester() bitstrings = np.array( [ [0, 0], [0, 1], [1, 0], [1, 1], ], dtype=np.uint8, ) chunksizes = np.asarray([4]) timestamps = np.asarray([datetime.datetime.now()]) a = cirq.NamedQubit('a') b = cirq.NamedQubit('b') qubit_to_index = {a: 0, b: 1} obs = cirq.Z(a) * cirq.Z(b) * 10 setting = cw.InitObsSetting(init_state=cirq.Z(a) * cirq.Z(b), observable=obs) meas_spec = _MeasurementSpec(setting, {}) cirq.testing.assert_equivalent_repr( cw.BitstringAccumulator( meas_spec=meas_spec, simul_settings=[setting], qubit_to_index=qubit_to_index, bitstrings=bitstrings.copy(), chunksizes=chunksizes.copy(), timestamps=timestamps.copy(), )) et.add_equality_group( cw.BitstringAccumulator( meas_spec=meas_spec, simul_settings=[setting], qubit_to_index=qubit_to_index, bitstrings=bitstrings.copy(), chunksizes=chunksizes.copy(), timestamps=timestamps.copy(), ), cw.BitstringAccumulator( meas_spec=meas_spec, simul_settings=[setting], qubit_to_index=qubit_to_index, bitstrings=bitstrings.copy(), chunksizes=chunksizes.copy(), timestamps=timestamps.copy(), ), ) time.sleep(1) timestamps = np.asarray([datetime.datetime.now()]) et.add_equality_group( cw.BitstringAccumulator( meas_spec=meas_spec, simul_settings=[setting], qubit_to_index=qubit_to_index, bitstrings=bitstrings, chunksizes=chunksizes, timestamps=timestamps, )) et.add_equality_group( cw.BitstringAccumulator( meas_spec=_MeasurementSpec(setting, {'a': 2}), simul_settings=[setting], qubit_to_index=qubit_to_index, bitstrings=bitstrings, chunksizes=chunksizes, timestamps=timestamps, )) bitstrings = bitstrings.copy() bitstrings[0] = [1, 1] et.add_equality_group( cw.BitstringAccumulator( meas_spec=meas_spec, simul_settings=[setting], qubit_to_index=qubit_to_index, bitstrings=bitstrings, chunksizes=chunksizes, timestamps=timestamps, )) chunksizes = np.asarray([2, 2]) timestamps = np.asarray(list(timestamps) * 2) et.add_equality_group( cw.BitstringAccumulator( meas_spec=meas_spec, simul_settings=[setting], qubit_to_index=qubit_to_index, bitstrings=bitstrings, chunksizes=chunksizes, timestamps=timestamps, ))
return np.array([[2, 3], [5, 7]]) def __eq__(self, other): return isinstance(other, type(self)) def __repr__(self): return ('cirq.ops.controlled_gate_test.' 'GateAllocatingNewSpaceForResult()') class RestrictedGate(cirq.SingleQubitGate): def __str__(self): return 'Restricted' q = cirq.NamedQubit('q') p = cirq.NamedQubit('p') q3 = q.with_dimension(3) p3 = p.with_dimension(3) CY = cirq.ControlledGate(cirq.Y) SCY = cirq.ControlledGate(cirq.Y, [q]) CCH = cirq.ControlledGate(cirq.ControlledGate(cirq.H)) SCSCH = cirq.ControlledGate(cirq.H, [q, p], 2) CRestricted = cirq.ControlledGate(RestrictedGate()) SCRestricted = cirq.ControlledGate(RestrictedGate(), [q]) C0Y = cirq.ControlledGate(cirq.Y, control_values=[0]) SC0Y = cirq.ControlledGate(cirq.Y, [q], control_values=[0]) C0C1H = cirq.ControlledGate(cirq.ControlledGate(cirq.H, control_values=[1]), control_values=[0])
def test_bitstring_accumulator_stats(): bitstrings = np.array( [ [0, 0], [0, 1], [1, 0], [1, 1], ], dtype=np.uint8, ) chunksizes = np.asarray([4]) timestamps = np.asarray([datetime.datetime.now()]) a = cirq.NamedQubit('a') b = cirq.NamedQubit('b') qubit_to_index = {a: 0, b: 1} settings = list( cw.observables_to_settings( [cirq.Z(a) * cirq.Z(b) * 7, cirq.Z(a) * 5, cirq.Z(b) * 3], qubits=[a, b])) meas_spec = _MeasurementSpec(settings[0], {}) bsa = cw.BitstringAccumulator( meas_spec=meas_spec, simul_settings=settings, qubit_to_index=qubit_to_index, bitstrings=bitstrings, chunksizes=chunksizes, timestamps=timestamps, ) # There are three observables, each with mean 0 because # the four 2-bit strings have even numbers of a) ones in the # first position b) ones in the second position c) even parity # pairs. np.testing.assert_allclose([0, 0, 0], bsa.means()) # Covariance: Sum[(x - xbar)(y - ybar)] / (N-1) # where xbar and ybar are 0, per above. Each individual observed # value is +-1, so (x-xbar)(y-bar) is +-1 (neglecting observable coefficients) # For off-diagonal elements, there are two +1 and two -1 terms for each entry # so the total contribution is zero, and the matrix is diagonal should_be = np.array([ [4 * 7**2, 0, 0], [0, 4 * 5**2, 0], [0, 0, 4 * 3**2], ]) should_be = should_be / (4 - 1) # covariance formula should_be = should_be / 4 # cov of the distribution of sample mean np.testing.assert_allclose(should_be, bsa.covariance()) for setting, var in zip(settings, [4 * 7**2, 4 * 5**2, 4 * 3**2]): np.testing.assert_allclose(0, bsa.mean(setting)) np.testing.assert_allclose(var / 4 / (4 - 1), bsa.variance(setting)) np.testing.assert_allclose(np.sqrt(var / 4 / (4 - 1)), bsa.stderr(setting)) bad_obs = [cirq.X(a) * cirq.X(b)] bad_setting = list(cw.observables_to_settings(bad_obs, qubits=[a, b]))[0] with pytest.raises(ValueError): bsa.mean(bad_setting)
def test_validate_args(): a = cirq.NamedQubit('a') b = cirq.NamedQubit('b') c = cirq.NamedQubit('c') # Need a control qubit. with pytest.raises(ValueError): CRestricted.validate_args([]) with pytest.raises(ValueError): CRestricted.validate_args([a]) CRestricted.validate_args([a, b]) # Does not need a control qubit. It's already specified. SCRestricted.validate_args([a]) with pytest.raises(ValueError): SCRestricted.validate_args([a, b]) # CY is a two-qubit operation (control + single-qubit sub gate). with pytest.raises(ValueError): CY.validate_args([a]) with pytest.raises(ValueError): CY.validate_args([a, b, c]) CY.validate_args([a, b]) # SCY is a two-qubit operation (control + single-qubit sub gate). # Control qubit is already specified. with pytest.raises(ValueError): SCY.validate_args([]) with pytest.raises(ValueError): SCY.validate_args([a, b, c]) with pytest.raises(ValueError): SCY.validate_args([a, b]) SCY.validate_args([a]) # Applies when creating operations. with pytest.raises(ValueError): _ = CY.on() with pytest.raises(ValueError): _ = CY.on(a) with pytest.raises(ValueError): _ = CY.on(a, b, c) _ = CY.on(a, b) # Applies when creating operations. Control qubit is already specified. with pytest.raises(ValueError): _ = SCY.on() with pytest.raises(ValueError): _ = SCY.on(a, b, c) with pytest.raises(ValueError): _ = SCY.on(a, b) _ = SCY.on(a) # Applies when creating operations. with pytest.raises(ValueError): _ = CCH.on() with pytest.raises(ValueError): _ = CCH.on(a) with pytest.raises(ValueError): _ = CCH.on(a, b) # Applies when creating operations. Control qubits are already specified. with pytest.raises(ValueError): _ = SCSCH.on() with pytest.raises(ValueError): _ = SCSCH.on(a, b, c) with pytest.raises(ValueError): _ = SCSCH.on(a, b) _ = SCSCH.on(a) # Applies when creating operations. Control qids have different dimensions. with pytest.raises(ValueError, match="dimensions that don't match"): _ = CY.on(q3, b) with pytest.raises(ValueError, match="dimensions that don't match"): _ = C2Y.on(a, b) with pytest.raises(ValueError, match="dimensions that don't match"): _ = C2C2H.on(a, b, c) _ = C2C2H.on(q3, p3, a)
def test_cnot_mixed_keyword_and_positional_arguments(): a = cirq.NamedQubit('a') b = cirq.NamedQubit('b') with pytest.raises(ValueError): _ = cirq.CNOT(a, target=b)
def _make_qubits(n): return [cirq.NamedQubit(f'q{i}') for i in range(n)]
def test_cnot_decompose(): a = cirq.NamedQubit('a') b = cirq.NamedQubit('b') assert cirq.decompose_once(cirq.CNOT(a, b)**sympy.Symbol('x')) is not None
def test_repr(): a = cirq.NamedQubit('a') b = cirq.NamedQubit('b') original = Moment([cirq.CZ(a, b)]) cirq.testing.assert_equivalent_repr(original)
def test_bool(): assert not cirq.Moment() a = cirq.NamedQubit('a') assert cirq.Moment([cirq.X(a)])
import pytest import cirq import recirq.quantum_chess.mcpe_utils as mcpe from recirq.quantum_chess.swap_updater import SwapUpdater, generate_decomposed_swap import recirq.quantum_chess.quantum_moves as qm # Logical qubits q0 - q5. q = list(cirq.NamedQubit(f'q{i}') for i in range(6)) # Qubits corresponding to figure 9 in # https://ieeexplore.ieee.org/abstract/document/8976109. # Coupling graph looks something like: # Q0 = Q1 = Q2 # || || || # Q3 = Q4 = Q5 FIGURE_9A_PHYSICAL_QUBITS = cirq.GridQubit.rect(2, 3) # Circuit from figure 9a in # https://ieeexplore.ieee.org/abstract/document/8976109. FIGURE_9A_CIRCUIT = cirq.Circuit(cirq.CNOT(q[0], q[2]), cirq.CNOT(q[5], q[2]), cirq.CNOT(q[0], q[5]), cirq.CNOT(q[4], q[0]), cirq.CNOT(q[0], q[3]), cirq.CNOT(q[5], q[0]), cirq.CNOT(q[3], q[1])) def test_example_9_candidate_swaps(): Q = FIGURE_9A_PHYSICAL_QUBITS initial_mapping = dict(zip(q, Q)) updater = SwapUpdater(FIGURE_9A_CIRCUIT, Q, initial_mapping) gate = cirq.CNOT(Q[0], Q[2])
def test_crosses_czs(): a = cirq.NamedQubit('a') b = cirq.NamedQubit('b') x = sympy.Symbol('x') y = sympy.Symbol('y') z = sympy.Symbol('z') # Full CZ. assert_optimizes( before=quick_circuit( [cirq.PhasedXPowGate(phase_exponent=0.25).on(a)], [cirq.CZ(a, b)], ), expected=quick_circuit( [cirq.Z(b)], [cirq.CZ(a, b)], [cirq.PhasedXPowGate(phase_exponent=0.25).on(a)], ), ) assert_optimizes( before=quick_circuit( [cirq.PhasedXPowGate(phase_exponent=0.125).on(a)], [cirq.CZ(b, a)], ), expected=quick_circuit( [cirq.Z(b)], [cirq.CZ(a, b)], [cirq.PhasedXPowGate(phase_exponent=0.125).on(a)], ), ) assert_optimizes( before=quick_circuit( [cirq.PhasedXPowGate(phase_exponent=x).on(a)], [cirq.CZ(b, a)], ), expected=quick_circuit( [cirq.Z(b)], [cirq.CZ(a, b)], [cirq.PhasedXPowGate(phase_exponent=x).on(a)], ), eject_parameterized=True, ) # Partial CZ. assert_optimizes( before=quick_circuit( [cirq.X(a)], [cirq.CZ(a, b)**0.25], ), expected=quick_circuit( [cirq.Z(b)**0.25], [cirq.CZ(a, b)**-0.25], [cirq.X(a)], ), ) assert_optimizes( before=quick_circuit( [cirq.X(a)], [cirq.CZ(a, b)**x], ), expected=quick_circuit( [cirq.Z(b)**x], [cirq.CZ(a, b)**-x], [cirq.X(a)], ), eject_parameterized=True, ) # Double cross. assert_optimizes( before=quick_circuit( [cirq.PhasedXPowGate(phase_exponent=0.125).on(a)], [cirq.PhasedXPowGate(phase_exponent=0.375).on(b)], [cirq.CZ(a, b)**0.25], ), expected=quick_circuit( [], [], [cirq.CZ(a, b)**0.25], [ cirq.PhasedXPowGate(phase_exponent=0.5).on(b), cirq.PhasedXPowGate(phase_exponent=0.25).on(a), ], ), ) assert_optimizes( before=quick_circuit( [cirq.PhasedXPowGate(phase_exponent=x).on(a)], [cirq.PhasedXPowGate(phase_exponent=y).on(b)], [cirq.CZ(a, b)**z], ), expected=quick_circuit( [], [], [cirq.CZ(a, b)**z], [ cirq.PhasedXPowGate(phase_exponent=y + z / 2).on(b), cirq.PhasedXPowGate(phase_exponent=x + z / 2).on(a), ], ), eject_parameterized=True, )
''' Quantum Digital Cooling (QDC) implementation with cirq and openfermion. ''' from typing import Union, Callable, Sequence import numpy as np import cirq from openfermion import ops, transforms from ._quantum_simulated_system import QuantumSimulatedSystem from .qdcutils import (logsweep_params, trotter_number_weakcoupling_step, perp_norm, opt_delta_factor) FRIDGE = cirq.NamedQubit('fridge') # **************************** # *** QDC STEPS AND CYCLES *** # **************************** def qdc_step(HS_step_f: Callable[[float], cirq.Circuit], coupl_step_f: Callable[[float, float], cirq.Circuit], epsilon: float, gamma: float, t: float, qdc_trotter_number: int, HS_trotter_factor: int = 1) -> cirq.Circuit: ''' Circuit implementing a generic 2nd-order trotterized QDC step.
def test_cancels_other_full_w(): q = cirq.NamedQubit('q') x = sympy.Symbol('x') y = sympy.Symbol('y') assert_optimizes( before=quick_circuit( [cirq.PhasedXPowGate(phase_exponent=0.25).on(q)], [cirq.PhasedXPowGate(phase_exponent=0.25).on(q)], ), expected=quick_circuit( [], [], ), ) assert_optimizes( before=quick_circuit( [cirq.PhasedXPowGate(phase_exponent=x).on(q)], [cirq.PhasedXPowGate(phase_exponent=x).on(q)], ), expected=quick_circuit( [], [], ), eject_parameterized=True, ) assert_optimizes( before=quick_circuit( [cirq.PhasedXPowGate(phase_exponent=0.25).on(q)], [cirq.PhasedXPowGate(phase_exponent=0.125).on(q)], ), expected=quick_circuit( [], [cirq.Z(q)**-0.25], ), ) assert_optimizes( before=quick_circuit( [cirq.X(q)], [cirq.PhasedXPowGate(phase_exponent=0.25).on(q)], ), expected=quick_circuit( [], [cirq.Z(q)**0.5], ), ) assert_optimizes( before=quick_circuit( [cirq.PhasedXPowGate(phase_exponent=0.25).on(q)], [cirq.X(q)], ), expected=quick_circuit( [], [cirq.Z(q)**-0.5], ), ) assert_optimizes( before=quick_circuit( [cirq.PhasedXPowGate(phase_exponent=x).on(q)], [cirq.PhasedXPowGate(phase_exponent=y).on(q)], ), expected=quick_circuit( [], [cirq.Z(q)**(2 * (y - x))], ), eject_parameterized=True, )
def test_decompose(gate, gate_equiv): q0 = cirq.NamedQubit('q0') mat = cirq.Circuit.from_ops(gate(q0), ).to_unitary_matrix() mat_check = cirq.Circuit.from_ops(gate_equiv(q0), ).to_unitary_matrix() assert_allclose_up_to_global_phase(mat, mat_check, rtol=1e-7, atol=1e-7)
def test_absorbs_z(): q = cirq.NamedQubit('q') x = sympy.Symbol('x') # Full Z. assert_optimizes( before=quick_circuit( [cirq.PhasedXPowGate(phase_exponent=0.125).on(q)], [cirq.Z(q)], ), expected=quick_circuit( [cirq.PhasedXPowGate(phase_exponent=0.625).on(q)], [], ), ) # Partial Z. assert_optimizes( before=quick_circuit( [cirq.PhasedXPowGate(phase_exponent=0.125).on(q)], [cirq.S(q)], ), expected=quick_circuit( [cirq.PhasedXPowGate(phase_exponent=0.375).on(q)], [], ), ) # parameterized Z. assert_optimizes( before=quick_circuit( [cirq.PhasedXPowGate(phase_exponent=0.125).on(q)], [cirq.Z(q)**x], ), expected=quick_circuit( [cirq.PhasedXPowGate(phase_exponent=0.125 + x / 2).on(q)], [], ), eject_parameterized=True, ) assert_optimizes( before=quick_circuit( [cirq.PhasedXPowGate(phase_exponent=0.125).on(q)], [cirq.Z(q)**(x + 1)], ), expected=quick_circuit( [cirq.PhasedXPowGate(phase_exponent=0.625 + x / 2).on(q)], [], ), eject_parameterized=True, ) # Multiple Zs. assert_optimizes( before=quick_circuit( [cirq.PhasedXPowGate(phase_exponent=0.125).on(q)], [cirq.S(q)], [cirq.T(q)**-1], ), expected=quick_circuit( [cirq.PhasedXPowGate(phase_exponent=0.25).on(q)], [], [], ), ) # Multiple Parameterized Zs. assert_optimizes( before=quick_circuit( [cirq.PhasedXPowGate(phase_exponent=0.125).on(q)], [cirq.S(q)**x], [cirq.T(q)**-x], ), expected=quick_circuit( [cirq.PhasedXPowGate(phase_exponent=0.125 + x * 0.125).on(q)], [], [], ), eject_parameterized=True, ) # Parameterized Phase and Partial Z assert_optimizes( before=quick_circuit( [cirq.PhasedXPowGate(phase_exponent=x).on(q)], [cirq.S(q)], ), expected=quick_circuit( [cirq.PhasedXPowGate(phase_exponent=x + 0.25).on(q)], [], ), eject_parameterized=True, )
# count_h_of_circuit(cir), # count_t_of_circuit(cir)) # qopt.CancelNghHadamards(transfer_flag=False).optimize_circuit(cir) # qopt.CancelNghCNOTs(transfer_flag=False) \ # .apply_until_nothing_changes(cir, count_cnot_of_circuit) # # qopt.CommuteTGatesToStart().optimize_circuit(cir) # cirq.optimizers.DropEmptyMoments().optimize_circuit(cir) # print(cir) # print(count_t_depth_of_circuit(cir), # count_cnot_of_circuit(cir), # count_h_of_circuit(cir), # count_t_of_circuit(cir)) # # print(l) # # print(count_t_of_circuit(cir)) qubits = [cirq.NamedQubit("a" + str(i)) for i in range(3)] # cir=cirq.Circuit() # cir.append(cirq.CNOT(qubits[0], qubits[1])) # cir.append(cirq.T(qubits[0])) # cir.append(cirq.H(qubits[1])) # cir.append(cirq.H(qubits[1])) # cir.append(cirq.CNOT(qubits[0], qubits[1])) # cir.append(cirq.CNOT(qubits[0], qubits[1])) # cir.append(cirq.CNOT(qubits[0], qubits[1])) # qopt.CommuteTGatesToStart().optimize_circuit(cir) # miscutils.flag_operations(cir, [cirq.ops.H]) # qopt.CancelNghHadamards(transfer_flag=True).optimize_circuit(cir) # qopt.CancelNghCNOTs(transfer_flag=True) \ # .apply_until_nothing_changes(cir, count_cnot_of_circuit) mo = [cirq.Moment([cirq.TOFFOLI(qubits[0], qubits[1], qubits[2])])]