Beispiel #1
0
def test_try_convert_sqrt_iswap_to_fsim_converts_correctly():
    expected = cirq.FSimGate(theta=np.pi / 4, phi=0)
    expected_unitary = cirq.unitary(expected)

    fsim = cirq.FSimGate(theta=np.pi / 4, phi=0)
    assert np.allclose(cirq.unitary(fsim), expected_unitary)
    assert try_convert_sqrt_iswap_to_fsim(fsim) == expected
    assert try_convert_sqrt_iswap_to_fsim(cirq.FSimGate(theta=np.pi / 4, phi=0.1)) is None
    assert try_convert_sqrt_iswap_to_fsim(cirq.FSimGate(theta=np.pi / 3, phi=0)) is None

    phased_fsim = cirq.PhasedFSimGate(theta=np.pi / 4, phi=0)
    assert np.allclose(cirq.unitary(phased_fsim), expected_unitary)
    assert try_convert_sqrt_iswap_to_fsim(phased_fsim) == expected
    assert (
        try_convert_sqrt_iswap_to_fsim(cirq.PhasedFSimGate(theta=np.pi / 4, zeta=0.1, phi=0))
        is None
    )

    iswap_pow = cirq.ISwapPowGate(exponent=-0.5)
    assert np.allclose(cirq.unitary(iswap_pow), expected_unitary)
    assert try_convert_sqrt_iswap_to_fsim(iswap_pow) == expected
    assert try_convert_sqrt_iswap_to_fsim(cirq.ISwapPowGate(exponent=-0.4)) is None

    phased_iswap_pow = cirq.PhasedISwapPowGate(exponent=0.5, phase_exponent=-0.5)
    assert np.allclose(cirq.unitary(phased_iswap_pow), expected_unitary)
    assert try_convert_sqrt_iswap_to_fsim(phased_iswap_pow) == expected
    assert (
        try_convert_sqrt_iswap_to_fsim(cirq.PhasedISwapPowGate(exponent=-0.5, phase_exponent=0.1))
        is None
    )

    assert try_convert_sqrt_iswap_to_fsim(cirq.CZ) is None
Beispiel #2
0
def _complex_test_circuit():
    t = sympy.Symbol('t')
    r = sympy.Symbol('r')
    qubits = cirq.GridQubit.rect(1, 6)
    circuit_batch = [
        cirq.Circuit(
            cirq.Moment([cirq.H(q) for q in qubits]),
            cirq.Moment([
                cirq.X(qubits[4]),
                cirq.PhasedXPowGate(phase_exponent=np.random.random() * t).on(
                    qubits[5]),
                cirq.ISwapPowGate(exponent=np.random.random() * t).on(
                    qubits[0], qubits[1]),
                cirq.FSimGate(theta=np.random.random() * t,
                              phi=np.random.random() * r).on(
                                  qubits[2], qubits[3])
            ]), cirq.Moment([cirq.H(q) for q in qubits])),
        cirq.Circuit(
            cirq.FSimGate(theta=np.random.random() * t,
                          phi=np.random.random() * r).on(*qubits[:2]),
            cirq.FSimGate(theta=np.random.random() * r,
                          phi=np.random.random() * t).on(qubits[1], qubits[0])),
        cirq.Circuit(
            cirq.Moment([
                cirq.ISwapPowGate(exponent=np.random.random() *
                                  t).on(*qubits[:2]),
                cirq.PhasedXPowGate(phase_exponent=np.random.random() * r).on(
                    qubits[2]),
                cirq.ISwapPowGate(exponent=np.random.random() *
                                  r).on(*qubits[3:5])
            ]))
    ]
    return circuit_batch
 def one_and_two_body_interaction(p, q, a, b) -> cirq.OP_TREE:
     th_symbol = LetterWithSubscripts('Th', i)
     tv_symbol = LetterWithSubscripts('Tv', i)
     v_symbol = LetterWithSubscripts('V', i)
     if _is_horizontal_edge(p, q, self.x_dim, self.y_dim,
                            self.periodic):
         yield cirq.ISwapPowGate(exponent=-th_symbol).on(a, b)
     if _is_vertical_edge(p, q, self.x_dim, self.y_dim,
                          self.periodic):
         yield cirq.ISwapPowGate(exponent=-tv_symbol).on(a, b)
     if _are_same_site_opposite_spin(p, q, self.x_dim * self.y_dim):
         yield cirq.CZPowGate(exponent=v_symbol).on(a, b)
Beispiel #4
0
def test_gate_translators_are_consistent():
    def check(gate):
        result1 = try_convert_gate_to_fsim(gate)
        result2 = try_convert_sqrt_iswap_to_fsim(gate)
        assert result1 == result2
        assert result1 is not None

    check(cirq.FSimGate(theta=np.pi / 4, phi=0))
    check(cirq.FSimGate(theta=-np.pi / 4, phi=0))
    check(cirq.FSimGate(theta=7 * np.pi / 4, phi=0))
    check(cirq.PhasedFSimGate(theta=np.pi / 4, phi=0))
    check(cirq.ISwapPowGate(exponent=0.5))
    check(cirq.ISwapPowGate(exponent=-0.5))
    check(cirq.PhasedISwapPowGate(exponent=0.5, phase_exponent=-0.5))
def demo_valkmusa(do_measure=False, use_qsim=False):
    """Run the demo using the Valkmusa architecture."""

    print('\nValkmusa demo\n=============\n')
    device = Valkmusa()
    qasm_program = """
        OPENQASM 2.0;
        include "qelib1.inc";
        qreg q[2];
        creg meas[2];
        U(1.3, 0.4, -0.3) q[1];
        h q[0];
        rx(1.1) q[0];
        cx q[0], q[1];
    """
    if do_measure:
        qasm_program += '\nmeasure q -> meas;'

    circuit = circuit_from_qasm(qasm_program)

    # add some more gates
    q0 = cirq.NamedQubit('q_0')
    q1 = cirq.NamedQubit('q_1')
    circuit.insert(len(circuit) - 1, cirq.ISwapPowGate(exponent=0.4)(q0, q1))

    qubit_mapping = {'q_0': 'QB1', 'q_1': 'QB2'}
    demo(device, circuit, do_measure, use_qsim=use_qsim, qubit_mapping=qubit_mapping)
Beispiel #6
0
def test_equivalent_unitaries():
    """This test covers the factor of pi change. However, it will be skipped
    if pyquil is unavailable for import.

    References:
        https://docs.pytest.org/en/latest/skipping.html#skipping-on-a-missing-import-dependency
    """
    pyquil = pytest.importorskip("pyquil")
    pyquil_simulation_tools = pytest.importorskip("pyquil.simulation.tools")
    q0, q1 = _make_qubits(2)
    operations = [
        cirq.XPowGate(exponent=0.5, global_shift=-0.5)(q0),
        cirq.YPowGate(exponent=0.5, global_shift=-0.5)(q0),
        cirq.ZPowGate(exponent=0.5, global_shift=-0.5)(q0),
        cirq.CZPowGate(exponent=0.5)(q0, q1),
        cirq.ISwapPowGate(exponent=0.5)(q0, q1),
    ]
    output = cirq.QuilOutput(operations, (q0, q1))
    program = pyquil.Program(str(output))
    pyquil_unitary = pyquil_simulation_tools.program_unitary(program,
                                                             n_qubits=2)
    # Qubit ordering differs between pyQuil and Cirq.
    cirq_unitary = cirq.Circuit(cirq.SWAP(q0, q1), operations,
                                cirq.SWAP(q0, q1)).unitary()
    assert np.allclose(pyquil_unitary, cirq_unitary)
 def one_and_two_body_interaction(p, q, a, b) -> cirq.OP_TREE:
     tv_symbol = LetterWithSubscripts('Tv', i)
     t_symbol = LetterWithSubscripts('T', p, q, i)
     w_symbol = LetterWithSubscripts('W', p, q, i)
     v_symbol = LetterWithSubscripts('V', p, q, i)
     if custom_is_vertical_edge(p, q,
                                self.hubbard.lattice.x_dimension,
                                self.hubbard.lattice.y_dimension,
                                self.hubbard.lattice.periodic):
         yield cirq.ISwapPowGate(exponent=-tv_symbol).on(a, b)
     if t_symbol in param_set:
         yield cirq.ISwapPowGate(exponent=-t_symbol).on(a, b)
     if w_symbol in param_set:
         yield cirq.PhasedISwapPowGate(exponent=w_symbol).on(a, b)
     if v_symbol in param_set:
         yield cirq.CZPowGate(exponent=v_symbol).on(a, b)
Beispiel #8
0
 def _decompose_(self, qubits):
     r = 2 * abs(self.weights[0]) / np.pi
     theta = _arg(self.weights[0]) / np.pi
     yield cirq.Z(qubits[0])**-theta
     yield cirq.ISwapPowGate(exponent=-r * self.exponent)(*qubits)
     yield cirq.Z(qubits[0])**theta
     yield cirq.CZPowGate(exponent=-self.weights[1] * self.exponent /
                          np.pi)(*qubits)
Beispiel #9
0
def test_no_touch_single_sqrt_iswap_inv():
    a, b = cirq.LineQubit.range(2)
    circuit = cirq.Circuit([
        cirq.Moment([
            cirq.ISwapPowGate(exponent=-0.5,
                              global_shift=-0.5).on(a, b).with_tags('mytag')
        ])
    ])
    assert_optimizes(before=circuit, expected=circuit, use_sqrt_iswap_inv=True)
    def exp_XX_YY(self,angle,qubit1,qubit2):
        '''
        returns Exp[i*angle*(XX+YY)]
        '''


        return cirq.ISwapPowGate(exponent= (4.0*angle/sympy.pi)).on(qubit1,qubit2)


        return None
 def one_and_two_body_interaction(p, q, a, b) -> cirq.OP_TREE:
     t_symbol = LetterWithSubscripts('T', p, q, i)
     w_symbol = LetterWithSubscripts('W', p, q, i)
     v_symbol = LetterWithSubscripts('V', p, q, i)
     if t_symbol in param_set:
         yield cirq.ISwapPowGate(exponent=-t_symbol).on(a, b)
     if w_symbol in param_set:
         yield cirq.PhasedISwapPowGate(exponent=w_symbol).on(a, b)
     if v_symbol in param_set:
         yield cirq.CZPowGate(exponent=v_symbol).on(a, b)
Beispiel #12
0
    def _decompose_(self, qubits: Sequence['cirq.Qid']) -> 'cirq.OP_TREE':
        if len(qubits) != 2:
            raise ValueError(f'Expected two qubits, got {len(qubits)}')
        a, b = qubits

        yield cirq.Z(a) ** self.phase_exponent
        yield cirq.Z(b) ** -self.phase_exponent
        yield cirq.ISwapPowGate(exponent=self.exponent, global_shift=self.global_shift).on(a, b)
        yield cirq.Z(a) ** -self.phase_exponent
        yield cirq.Z(b) ** self.phase_exponent
 def _convert_to_iswap(
         self, g: POSSIBLE_FSIM_GATES) -> Optional[cirq.ISwapPowGate]:
     if isinstance(g, cirq.ISwapPowGate):
         return g
     if isinstance(g, cirq.PhasedISwapPowGate):
         return g._iswap if self._approx_eq_or_symbol(g.phase_exponent,
                                                      0) else None
     fsim = self._convert_to_fsim(g)
     return (None if
             (fsim is None or not self._approx_eq_or_symbol(fsim.phi, 0))
             else cirq.ISwapPowGate(exponent=-2 * fsim.theta / np.pi))
Beispiel #14
0
def test_phased_iswap_equality():
    eq = cirq.testing.EqualsTester()
    eq.add_equality_group(
        cirq.PhasedISwapPowGate(phase_exponent=0, exponent=0.4),
        cirq.ISWAP**0.4)
    eq.add_equality_group(
        cirq.PhasedISwapPowGate(phase_exponent=0,
                                exponent=0.4,
                                global_shift=0.3),
        cirq.ISwapPowGate(global_shift=0.3)**0.4,
    )
Beispiel #15
0
def gamma_encode(circuit, q0, q1, *args):
    circuit.append(cirq.rx(args[0]).on(q0))
    circuit.append(cirq.ry(args[1]).on(q0))
    circuit.append(cirq.rx(args[2]).on(q1))
    circuit.append(cirq.ry(args[3]).on(q1))
    circuit.append(cirq.ISwapPowGate(exponent=args[4] / π).on(q0, q1))
    circuit.append(cirq.rx(args[5]).on(q0))
    circuit.append(cirq.ry(args[6]).on(q0))
    circuit.append(cirq.rz(args[7]).on(q0))
    circuit.append(cirq.rx(args[8]).on(q1))
    circuit.append(cirq.ry(args[9]).on(q1))
    circuit.append(cirq.ry(args[10]).on(q1))
Beispiel #16
0
 def test_moment_preservation(self):
     """Test Moment-structure preservation."""
     t = sympy.Symbol('t')
     r = sympy.Symbol('r')
     qubits = cirq.GridQubit.rect(1, 6)
     circuit_batch = [
         cirq.Circuit(
             cirq.Moment([cirq.H(q) for q in qubits]),
             cirq.Moment([
                 cirq.X(qubits[4]),
                 cirq.PhasedXPowGate(phase_exponent=np.random.random() *
                                     t).on(qubits[5]),
                 cirq.ISwapPowGate(exponent=np.random.random() * t).on(
                     qubits[0], qubits[1]),
                 cirq.FSimGate(theta=np.random.random() * t,
                               phi=np.random.random() * r).on(
                                   qubits[2], qubits[3])
             ]), cirq.Moment([cirq.H(q) for q in qubits]))
     ]
     inputs = util.convert_to_tensor(circuit_batch)
     outputs = tfq_ps_util_ops.tfq_ps_decompose(inputs)
     decomposed_programs = util.from_tensor(outputs)
     # Now all programs don't have ISWAP & PhasedXPowGate because ISWAP has
     # 3 eigenvalues and PhasedXPowGate doesn't have _eigen_components.
     # Check if two programs are identical.
     rand_resolver = {'t': np.random.random(), 'r': np.random.random()}
     self.assertAllClose(cirq.unitary(
         cirq.resolve_parameters(circuit_batch[0], rand_resolver)),
                         cirq.unitary(
                             cirq.resolve_parameters(decomposed_programs[0],
                                                     rand_resolver)),
                         atol=1e-5)
     # Check if the Moments are conserved.
     max_decomposed_length = 3
     n_non_decomposed_moments = 2
     self.assertEqual(len(decomposed_programs[0]),
                      n_non_decomposed_moments + max_decomposed_length)
     # Total length of Moments = 5
     # The non-decomposed moments should be the same.
     self.assertEqual(decomposed_programs[0][0], circuit_batch[0][0])
     self.assertEqual(decomposed_programs[0][-1], circuit_batch[0][-1])
     # Check paralellized decompose gates in Moment[1]~[3].
     # The target ops are replaced by the first decomposition gates. It means
     # the first Moment has exactly the same number of gate ops.
     self.assertEqual(len(decomposed_programs[0][1]),
                      len(circuit_batch[0][1]))
     # From the second Moments, the Moments only have decomposition gates.
     # In this example, two ISwapPowGate & one PhasedXPowGate are located.
     # Since PhasedXPowGate, ISwapPowGate, FSimGate has 3, 2, 3 result gates
     # Moment[2] have 3 gate ops and Moment[3] have 2 gate ops.
     self.assertEqual(len(decomposed_programs[0][2]), 3)
     self.assertEqual(len(decomposed_programs[0][3]), 2)
Beispiel #17
0
def test_try_convert_syc_or_sqrt_iswap_to_fsim():
    def check_converts(gate: cirq.Gate):
        result = try_convert_syc_or_sqrt_iswap_to_fsim(gate)
        assert np.allclose(cirq.unitary(gate), cirq.unitary(result))

    def check_none(gate: cirq.Gate):
        assert try_convert_syc_or_sqrt_iswap_to_fsim(gate) is None

    check_converts(cirq_google.ops.SYC)
    check_converts(cirq.FSimGate(np.pi / 2, np.pi / 6))
    check_none(cirq.FSimGate(0, np.pi))
    check_converts(cirq.FSimGate(np.pi / 4, 0.0))
    check_none(cirq.FSimGate(0.2, 0.3))
    check_converts(cirq.ISwapPowGate(exponent=0.5))
    check_converts(cirq.ISwapPowGate(exponent=-0.5))
    check_none(cirq.ISwapPowGate(exponent=0.3))
    check_converts(cirq.PhasedFSimGate(theta=np.pi / 4, phi=0.0, chi=0.7))
    check_none(cirq.PhasedFSimGate(theta=0.3, phi=0.4))
    check_converts(cirq.PhasedISwapPowGate(exponent=0.5, phase_exponent=0.75))
    check_none(cirq.PhasedISwapPowGate(exponent=0.4, phase_exponent=0.75))
    check_none(cirq.ops.CZPowGate(exponent=1.0))
    check_none(cirq.CX)
Beispiel #18
0
 def test_iswap_gate_test(self):
     """Test 1 ISwapPowGate decomposition."""
     t = sympy.Symbol('t')
     qubits = cirq.GridQubit.rect(1, 2)
     circuit = cirq.Circuit(
         cirq.ISwapPowGate(exponent=np.random.random() * t).on(*qubits))
     inputs = util.convert_to_tensor([circuit])
     outputs = tfq_ps_util_ops.tfq_ps_decompose(inputs)
     decomposed_programs = util.from_tensor(outputs)
     rand_resolver = {'t': np.random.random()}
     self.assertAllClose(cirq.unitary(
         cirq.resolve_parameters(circuit, rand_resolver)),
                         cirq.unitary(
                             cirq.resolve_parameters(decomposed_programs[0],
                                                     rand_resolver)),
                         atol=1e-5)
Beispiel #19
0
         'qubit_constant_index': [0, 1],
     }),
 ),
 (
     cirq.CZPowGate(exponent=0.5)(Q0, Q1),
     op_proto({
         'czpowgate': {
             'exponent': {
                 'float_value': 0.5
             }
         },
         'qubit_constant_index': [0, 1],
     }),
 ),
 (
     cirq.ISwapPowGate(exponent=0.5)(Q0, Q1),
     op_proto({
         'iswappowgate': {
             'exponent': {
                 'float_value': 0.5
             }
         },
         'qubit_constant_index': [0, 1],
     }),
 ),
 (
     cirq.FSimGate(theta=2 + sympy.Symbol('a'), phi=1)(Q0, Q1),
     op_proto({
         'fsimgate': {
             'theta': {
                 'func': {
    def test_gate_matrices_xy(self, t):
        """Verify that the XY gates work as expected."""

        U = cirq.ISwapPowGate(exponent=t)._unitary_()
        assert np.allclose(ig.XYGate(exponent=-0.5 * t)._unitary_(), U)
Beispiel #21
0
    def test_cirq_qsim_global_shift(self):
        q0 = cirq.GridQubit(1, 1)
        q1 = cirq.GridQubit(1, 0)
        q2 = cirq.GridQubit(0, 1)
        q3 = cirq.GridQubit(0, 0)

        circuit = cirq.Circuit(
            cirq.Moment([
                cirq.H(q0),
                cirq.H(q1),
                cirq.H(q2),
                cirq.H(q3),
            ]),
            cirq.Moment([
                cirq.CXPowGate(exponent=1, global_shift=0.7)(q0, q1),
                cirq.CZPowGate(exponent=1, global_shift=0.9)(q2, q3),
            ]),
            cirq.Moment([
                cirq.XPowGate(exponent=1, global_shift=1.1)(q0),
                cirq.YPowGate(exponent=1, global_shift=1)(q1),
                cirq.ZPowGate(exponent=1, global_shift=0.9)(q2),
                cirq.HPowGate(exponent=1, global_shift=0.8)(q3),
            ]),
            cirq.Moment([
                cirq.XXPowGate(exponent=1, global_shift=0.2)(q0, q1),
                cirq.YYPowGate(exponent=1, global_shift=0.3)(q2, q3),
            ]),
            cirq.Moment([
                cirq.ZPowGate(exponent=0.25, global_shift=0.4)(q0),
                cirq.ZPowGate(exponent=0.5, global_shift=0.5)(q1),
                cirq.YPowGate(exponent=1, global_shift=0.2)(q2),
                cirq.ZPowGate(exponent=1, global_shift=0.3)(q3),
            ]),
            cirq.Moment([
                cirq.ZZPowGate(exponent=1, global_shift=0.2)(q0, q1),
                cirq.SwapPowGate(exponent=1, global_shift=0.3)(q2, q3),
            ]),
            cirq.Moment([
                cirq.XPowGate(exponent=1, global_shift=0)(q0),
                cirq.YPowGate(exponent=1, global_shift=0)(q1),
                cirq.ZPowGate(exponent=1, global_shift=0)(q2),
                cirq.HPowGate(exponent=1, global_shift=0)(q3),
            ]),
            cirq.Moment([
                cirq.ISwapPowGate(exponent=1, global_shift=0.3)(q0, q1),
                cirq.ZZPowGate(exponent=1, global_shift=0.5)(q2, q3),
            ]),
            cirq.Moment([
                cirq.ZPowGate(exponent=0.5, global_shift=0)(q0),
                cirq.ZPowGate(exponent=0.25, global_shift=0)(q1),
                cirq.XPowGate(exponent=0.9, global_shift=0)(q2),
                cirq.YPowGate(exponent=0.8, global_shift=0)(q3),
            ]),
            cirq.Moment([
                cirq.CZPowGate(exponent=0.3, global_shift=0)(q0, q1),
                cirq.CXPowGate(exponent=0.4, global_shift=0)(q2, q3),
            ]),
            cirq.Moment([
                cirq.ZPowGate(exponent=1.3, global_shift=0)(q0),
                cirq.HPowGate(exponent=0.8, global_shift=0)(q1),
                cirq.XPowGate(exponent=0.9, global_shift=0)(q2),
                cirq.YPowGate(exponent=0.4, global_shift=0)(q3),
            ]),
            cirq.Moment([
                cirq.XXPowGate(exponent=0.8, global_shift=0)(q0, q1),
                cirq.YYPowGate(exponent=0.6, global_shift=0)(q2, q3),
            ]),
            cirq.Moment([
                cirq.HPowGate(exponent=0.7, global_shift=0)(q0),
                cirq.ZPowGate(exponent=0.2, global_shift=0)(q1),
                cirq.YPowGate(exponent=0.3, global_shift=0)(q2),
                cirq.XPowGate(exponent=0.7, global_shift=0)(q3),
            ]),
            cirq.Moment([
                cirq.ZZPowGate(exponent=0.1, global_shift=0)(q0, q1),
                cirq.SwapPowGate(exponent=0.6, global_shift=0)(q2, q3),
            ]),
            cirq.Moment([
                cirq.XPowGate(exponent=0.4, global_shift=0)(q0),
                cirq.YPowGate(exponent=0.3, global_shift=0)(q1),
                cirq.ZPowGate(exponent=0.2, global_shift=0)(q2),
                cirq.HPowGate(exponent=0.1, global_shift=0)(q3),
            ]),
            cirq.Moment([
                cirq.ISwapPowGate(exponent=1.3, global_shift=0)(q0, q1),
                cirq.CXPowGate(exponent=0.5, global_shift=0)(q2, q3),
            ]),
            cirq.Moment([
                cirq.H(q0),
                cirq.H(q1),
                cirq.H(q2),
                cirq.H(q3),
            ]),
        )

        simulator = cirq.Simulator()
        cirq_result = simulator.simulate(circuit)

        qsim_simulator = qsimcirq.QSimSimulator()
        qsim_result = qsim_simulator.simulate(circuit)

        assert cirq.linalg.allclose_up_to_global_phase(
            qsim_result.state_vector(), cirq_result.state_vector())
Beispiel #22
0
def _get_circuit_proto_pairs():
    q0 = cirq.GridQubit(0, 0)
    q1 = cirq.GridQubit(0, 1)

    pairs = [
        # HPOW and aliases.
        (cirq.Circuit(cirq.HPowGate(exponent=0.3)(q0)),
         _build_gate_proto("HP",
                           ['exponent', 'exponent_scalar', 'global_shift'],
                           [0.3, 1.0, 0.0], ['0_0'])),
        (cirq.Circuit(cirq.HPowGate(exponent=sympy.Symbol('alpha'))(q0)),
         _build_gate_proto("HP",
                           ['exponent', 'exponent_scalar', 'global_shift'],
                           ['alpha', 1.0, 0.0], ['0_0'])),
        (cirq.Circuit(cirq.HPowGate(exponent=3.1 * sympy.Symbol('alpha'))(q0)),
         _build_gate_proto("HP",
                           ['exponent', 'exponent_scalar', 'global_shift'],
                           ['alpha', 3.1, 0.0], ['0_0'])),
        (cirq.Circuit(cirq.H(q0)),
         _build_gate_proto("HP",
                           ['exponent', 'exponent_scalar', 'global_shift'],
                           [1.0, 1.0, 0.0], ['0_0'])),

        # XPOW and aliases.
        (cirq.Circuit(cirq.XPowGate(exponent=0.3)(q0)),
         _build_gate_proto("XP",
                           ['exponent', 'exponent_scalar', 'global_shift'],
                           [0.3, 1.0, 0.0], ['0_0'])),
        (cirq.Circuit(cirq.XPowGate(exponent=sympy.Symbol('alpha'))(q0)),
         _build_gate_proto("XP",
                           ['exponent', 'exponent_scalar', 'global_shift'],
                           ['alpha', 1.0, 0.0], ['0_0'])),
        (cirq.Circuit(cirq.XPowGate(exponent=3.1 * sympy.Symbol('alpha'))(q0)),
         _build_gate_proto("XP",
                           ['exponent', 'exponent_scalar', 'global_shift'],
                           ['alpha', 3.1, 0.0], ['0_0'])),
        (cirq.Circuit(cirq.X(q0)),
         _build_gate_proto("XP",
                           ['exponent', 'exponent_scalar', 'global_shift'],
                           [1.0, 1.0, 0.0], ['0_0'])),

        # YPOW and aliases
        (cirq.Circuit(cirq.YPowGate(exponent=0.3)(q0)),
         _build_gate_proto("YP",
                           ['exponent', 'exponent_scalar', 'global_shift'],
                           [0.3, 1.0, 0.0], ['0_0'])),
        (cirq.Circuit(cirq.YPowGate(exponent=sympy.Symbol('alpha'))(q0)),
         _build_gate_proto("YP",
                           ['exponent', 'exponent_scalar', 'global_shift'],
                           ['alpha', 1.0, 0.0], ['0_0'])),
        (cirq.Circuit(cirq.YPowGate(exponent=3.1 * sympy.Symbol('alpha'))(q0)),
         _build_gate_proto("YP",
                           ['exponent', 'exponent_scalar', 'global_shift'],
                           ['alpha', 3.1, 0.0], ['0_0'])),
        (cirq.Circuit(cirq.Y(q0)),
         _build_gate_proto("YP",
                           ['exponent', 'exponent_scalar', 'global_shift'],
                           [1.0, 1.0, 0.0], ['0_0'])),

        # ZPOW and aliases.
        (cirq.Circuit(cirq.ZPowGate(exponent=0.3)(q0)),
         _build_gate_proto("ZP",
                           ['exponent', 'exponent_scalar', 'global_shift'],
                           [0.3, 1.0, 0.0], ['0_0'])),
        (cirq.Circuit(cirq.ZPowGate(exponent=sympy.Symbol('alpha'))(q0)),
         _build_gate_proto("ZP",
                           ['exponent', 'exponent_scalar', 'global_shift'],
                           ['alpha', 1.0, 0.0], ['0_0'])),
        (cirq.Circuit(cirq.ZPowGate(exponent=3.1 * sympy.Symbol('alpha'))(q0)),
         _build_gate_proto("ZP",
                           ['exponent', 'exponent_scalar', 'global_shift'],
                           ['alpha', 3.1, 0.0], ['0_0'])),
        (cirq.Circuit(cirq.Z(q0)),
         _build_gate_proto("ZP",
                           ['exponent', 'exponent_scalar', 'global_shift'],
                           [1.0, 1.0, 0.0], ['0_0'])),

        # XXPow and aliases
        (cirq.Circuit(cirq.XXPowGate(exponent=0.3)(q0, q1)),
         _build_gate_proto("XXP",
                           ['exponent', 'exponent_scalar', 'global_shift'],
                           [0.3, 1.0, 0.0], ['0_0', '0_1'])),
        (cirq.Circuit(cirq.XXPowGate(exponent=sympy.Symbol('alpha'))(q0, q1)),
         _build_gate_proto("XXP",
                           ['exponent', 'exponent_scalar', 'global_shift'],
                           ['alpha', 1.0, 0.0], ['0_0', '0_1'])),
        (cirq.Circuit(
            cirq.XXPowGate(exponent=3.1 * sympy.Symbol('alpha'))(q0, q1)),
         _build_gate_proto("XXP",
                           ['exponent', 'exponent_scalar', 'global_shift'],
                           ['alpha', 3.1, 0.0], ['0_0', '0_1'])),
        (cirq.Circuit(cirq.XX(q0, q1)),
         _build_gate_proto("XXP",
                           ['exponent', 'exponent_scalar', 'global_shift'],
                           [1.0, 1.0, 0.0], ['0_0', '0_1'])),

        # YYPow and aliases
        (cirq.Circuit(cirq.YYPowGate(exponent=0.3)(q0, q1)),
         _build_gate_proto("YYP",
                           ['exponent', 'exponent_scalar', 'global_shift'],
                           [0.3, 1.0, 0.0], ['0_0', '0_1'])),
        (cirq.Circuit(cirq.YYPowGate(exponent=sympy.Symbol('alpha'))(q0, q1)),
         _build_gate_proto("YYP",
                           ['exponent', 'exponent_scalar', 'global_shift'],
                           ['alpha', 1.0, 0.0], ['0_0', '0_1'])),
        (cirq.Circuit(
            cirq.YYPowGate(exponent=3.1 * sympy.Symbol('alpha'))(q0, q1)),
         _build_gate_proto("YYP",
                           ['exponent', 'exponent_scalar', 'global_shift'],
                           ['alpha', 3.1, 0.0], ['0_0', '0_1'])),
        (cirq.Circuit(cirq.YY(q0, q1)),
         _build_gate_proto("YYP",
                           ['exponent', 'exponent_scalar', 'global_shift'],
                           [1.0, 1.0, 0.0], ['0_0', '0_1'])),

        # ZZPow and aliases
        (cirq.Circuit(cirq.ZZPowGate(exponent=0.3)(q0, q1)),
         _build_gate_proto("ZZP",
                           ['exponent', 'exponent_scalar', 'global_shift'],
                           [0.3, 1.0, 0.0], ['0_0', '0_1'])),
        (cirq.Circuit(cirq.ZZPowGate(exponent=sympy.Symbol('alpha'))(q0, q1)),
         _build_gate_proto("ZZP",
                           ['exponent', 'exponent_scalar', 'global_shift'],
                           ['alpha', 1.0, 0.0], ['0_0', '0_1'])),
        (cirq.Circuit(
            cirq.ZZPowGate(exponent=3.1 * sympy.Symbol('alpha'))(q0, q1)),
         _build_gate_proto("ZZP",
                           ['exponent', 'exponent_scalar', 'global_shift'],
                           ['alpha', 3.1, 0.0], ['0_0', '0_1'])),
        (cirq.Circuit(cirq.ZZ(q0, q1)),
         _build_gate_proto("ZZP",
                           ['exponent', 'exponent_scalar', 'global_shift'],
                           [1.0, 1.0, 0.0], ['0_0', '0_1'])),

        # CZPow and aliases
        (cirq.Circuit(cirq.CZPowGate(exponent=0.3)(q0, q1)),
         _build_gate_proto("CZP",
                           ['exponent', 'exponent_scalar', 'global_shift'],
                           [0.3, 1.0, 0.0], ['0_0', '0_1'])),
        (cirq.Circuit(cirq.CZPowGate(exponent=sympy.Symbol('alpha'))(q0, q1)),
         _build_gate_proto("CZP",
                           ['exponent', 'exponent_scalar', 'global_shift'],
                           ['alpha', 1.0, 0.0], ['0_0', '0_1'])),
        (cirq.Circuit(
            cirq.CZPowGate(exponent=3.1 * sympy.Symbol('alpha'))(q0, q1)),
         _build_gate_proto("CZP",
                           ['exponent', 'exponent_scalar', 'global_shift'],
                           ['alpha', 3.1, 0.0], ['0_0', '0_1'])),
        (cirq.Circuit(cirq.CZ(q0, q1)),
         _build_gate_proto("CZP",
                           ['exponent', 'exponent_scalar', 'global_shift'],
                           [1.0, 1.0, 0.0], ['0_0', '0_1'])),

        # CNOTPow and aliases
        (cirq.Circuit(cirq.CNotPowGate(exponent=0.3)(q0, q1)),
         _build_gate_proto("CNP",
                           ['exponent', 'exponent_scalar', 'global_shift'],
                           [0.3, 1.0, 0.0], ['0_0', '0_1'])),
        (cirq.Circuit(
            cirq.CNotPowGate(exponent=sympy.Symbol('alpha'))(q0, q1)),
         _build_gate_proto("CNP",
                           ['exponent', 'exponent_scalar', 'global_shift'],
                           ['alpha', 1.0, 0.0], ['0_0', '0_1'])),
        (cirq.Circuit(
            cirq.CNotPowGate(exponent=3.1 * sympy.Symbol('alpha'))(q0, q1)),
         _build_gate_proto("CNP",
                           ['exponent', 'exponent_scalar', 'global_shift'],
                           ['alpha', 3.1, 0.0], ['0_0', '0_1'])),
        (cirq.Circuit(cirq.CNOT(q0, q1)),
         _build_gate_proto("CNP",
                           ['exponent', 'exponent_scalar', 'global_shift'],
                           [1.0, 1.0, 0.0], ['0_0', '0_1'])),

        # SWAPPow and aliases
        (cirq.Circuit(cirq.SwapPowGate(exponent=0.3)(q0, q1)),
         _build_gate_proto("SP",
                           ['exponent', 'exponent_scalar', 'global_shift'],
                           [0.3, 1.0, 0.0], ['0_0', '0_1'])),
        (cirq.Circuit(
            cirq.SwapPowGate(exponent=sympy.Symbol('alpha'))(q0, q1)),
         _build_gate_proto("SP",
                           ['exponent', 'exponent_scalar', 'global_shift'],
                           ['alpha', 1.0, 0.0], ['0_0', '0_1'])),
        (cirq.Circuit(
            cirq.SwapPowGate(exponent=3.1 * sympy.Symbol('alpha'))(q0, q1)),
         _build_gate_proto("SP",
                           ['exponent', 'exponent_scalar', 'global_shift'],
                           ['alpha', 3.1, 0.0], ['0_0', '0_1'])),
        (cirq.Circuit(cirq.SWAP(q0, q1)),
         _build_gate_proto("SP",
                           ['exponent', 'exponent_scalar', 'global_shift'],
                           [1.0, 1.0, 0.0], ['0_0', '0_1'])),

        # ISWAPPow and aliases
        (cirq.Circuit(cirq.ISwapPowGate(exponent=0.3)(q0, q1)),
         _build_gate_proto("ISP",
                           ['exponent', 'exponent_scalar', 'global_shift'],
                           [0.3, 1.0, 0.0], ['0_0', '0_1'])),
        (cirq.Circuit(
            cirq.ISwapPowGate(exponent=sympy.Symbol('alpha'))(q0, q1)),
         _build_gate_proto("ISP",
                           ['exponent', 'exponent_scalar', 'global_shift'],
                           ['alpha', 1.0, 0.0], ['0_0', '0_1'])),
        (cirq.Circuit(
            cirq.ISwapPowGate(exponent=3.1 * sympy.Symbol('alpha'))(q0, q1)),
         _build_gate_proto("ISP",
                           ['exponent', 'exponent_scalar', 'global_shift'],
                           ['alpha', 3.1, 0.0], ['0_0', '0_1'])),
        (cirq.Circuit(cirq.ISWAP(q0, q1)),
         _build_gate_proto("ISP",
                           ['exponent', 'exponent_scalar', 'global_shift'],
                           [1.0, 1.0, 0.0], ['0_0', '0_1'])),

        # PhasedXPow and aliases
        (cirq.Circuit(
            cirq.PhasedXPowGate(phase_exponent=0.9,
                                exponent=0.3,
                                global_shift=0.2)(q0)),
         _build_gate_proto("PXP", [
             'phase_exponent', 'phase_exponent_scalar', 'exponent',
             'exponent_scalar', 'global_shift'
         ], [0.9, 1.0, 0.3, 1.0, 0.2], ['0_0'])),
        (cirq.Circuit(
            cirq.PhasedXPowGate(phase_exponent=sympy.Symbol('alpha'),
                                exponent=0.3)(q0)),
         _build_gate_proto("PXP", [
             'phase_exponent', 'phase_exponent_scalar', 'exponent',
             'exponent_scalar', 'global_shift'
         ], ['alpha', 1.0, 0.3, 1.0, 0.0], ['0_0'])),
        (cirq.Circuit(
            cirq.PhasedXPowGate(phase_exponent=3.1 * sympy.Symbol('alpha'),
                                exponent=0.3)(q0)),
         _build_gate_proto("PXP", [
             'phase_exponent', 'phase_exponent_scalar', 'exponent',
             'exponent_scalar', 'global_shift'
         ], ['alpha', 3.1, 0.3, 1.0, 0.0], ['0_0'])),
        (cirq.Circuit(
            cirq.PhasedXPowGate(phase_exponent=0.9,
                                exponent=sympy.Symbol('beta'))(q0)),
         _build_gate_proto("PXP", [
             'phase_exponent', 'phase_exponent_scalar', 'exponent',
             'exponent_scalar', 'global_shift'
         ], [0.9, 1.0, 'beta', 1.0, 0.0], ['0_0'])),
        (cirq.Circuit(
            cirq.PhasedXPowGate(phase_exponent=0.9,
                                exponent=5.1 * sympy.Symbol('beta'))(q0)),
         _build_gate_proto("PXP", [
             'phase_exponent', 'phase_exponent_scalar', 'exponent',
             'exponent_scalar', 'global_shift'
         ], [0.9, 1.0, 'beta', 5.1, 0.0], ['0_0'])),
        (cirq.Circuit(
            cirq.PhasedXPowGate(phase_exponent=3.1 * sympy.Symbol('alpha'),
                                exponent=5.1 * sympy.Symbol('beta'))(q0)),
         _build_gate_proto("PXP", [
             'phase_exponent', 'phase_exponent_scalar', 'exponent',
             'exponent_scalar', 'global_shift'
         ], ['alpha', 3.1, 'beta', 5.1, 0.0], ['0_0'])),

        # RX, RY, RZ with symbolization is tested in special cases as the
        # string comparison of the float converted sympy.pi does not happen
        # smoothly. See: test_serialize_deserialize_special_case_one_qubit
        (cirq.Circuit(cirq.rx(np.pi)(q0)),
         _build_gate_proto("XP",
                           ['exponent', 'exponent_scalar', 'global_shift'],
                           [1.0, 1.0, -0.5], ['0_0'])),
        (cirq.Circuit(cirq.ry(np.pi)(q0)),
         _build_gate_proto("YP",
                           ['exponent', 'exponent_scalar', 'global_shift'],
                           [1.0, 1.0, -0.5], ['0_0'])),
        (cirq.Circuit(cirq.rz(np.pi)(q0)),
         _build_gate_proto("ZP",
                           ['exponent', 'exponent_scalar', 'global_shift'],
                           [1.0, 1.0, -0.5], ['0_0'])),

        # Identity
        (cirq.Circuit(cirq.I(q0)),
         _build_gate_proto("I", ['unused'], [True], ['0_0'])),

        # FSimGate
        (cirq.Circuit(cirq.FSimGate(theta=0.1, phi=0.2)(q0, q1)),
         _build_gate_proto("FSIM",
                           ['theta', 'theta_scalar', 'phi', 'phi_scalar'],
                           [0.1, 1.0, 0.2, 1.0], ['0_0', '0_1'])),
        (cirq.Circuit(
            cirq.FSimGate(theta=2.1 * sympy.Symbol("alpha"),
                          phi=1.3 * sympy.Symbol("beta"))(q0, q1)),
         _build_gate_proto("FSIM",
                           ['theta', 'theta_scalar', 'phi', 'phi_scalar'],
                           ['alpha', 2.1, 'beta', 1.3], ['0_0', '0_1'])),
    ]

    return pairs
Beispiel #23
0
     cirq.CZ(*cirq.LineQubit.range(2))
 ],
 'GeneralizedAmplitudeDampingChannel':
 cirq.GeneralizedAmplitudeDampingChannel(0.1, 0.2),
 'GlobalPhaseOperation':
 cirq.GlobalPhaseOperation(-1j),
 'GridQubit':
 cirq.GridQubit(10, 11),
 'H':
 cirq.H,
 'HPowGate': [cirq.HPowGate(exponent=-8), cirq.H**0.123],
 'I':
 cirq.I,
 'ISWAP':
 cirq.ISWAP,
 'ISwapPowGate': [cirq.ISwapPowGate(exponent=-8), cirq.ISWAP**0.123],
 'IdentityGate': [
     cirq.I,
     cirq.IdentityGate(num_qubits=5),
     cirq.IdentityGate(num_qubits=5, qid_shape=(3, ) * 5)
 ],
 'IdentityOperation': [
     cirq.IdentityOperation(cirq.LineQubit.range(2)),
     cirq.IdentityOperation(cirq.LineQubit.range(5))
 ],
 'LineQubit': [cirq.LineQubit(0), cirq.LineQubit(123)],
 'LineQid': [cirq.LineQid(0, 1),
             cirq.LineQid(123, 2),
             cirq.LineQid(-4, 5)],
 'MeasurementGate': [
     cirq.MeasurementGate(num_qubits=3, key='z'),
Beispiel #24
0
native_2q_gates = [
    ig.IsingGate(exponent=0.45),
    ig.XYGate(exponent=0.38),
]

non_native_1q_gates = [
    cirq.H,
    cirq.HPowGate(exponent=-0.55),
    cirq.PhasedXZGate(x_exponent=0.2,
                      z_exponent=-0.5,
                      axis_phase_exponent=0.75),
]

non_native_2q_gates = [
    cirq.ISwapPowGate(exponent=0.27),
    cirq.ISWAP,
    cirq.SWAP,
    cirq.CNOT,
    cirq.CXPowGate(exponent=-2.2),
    cirq.CZ,
    cirq.CZPowGate(exponent=1.6),
]


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, adonis, gate, q):
        """Native operations must pass validation."""
Beispiel #25
0
def test_combined_error():
    # Helper function to calculate pauli error from depolarization
    def pauli_error_from_depolarization(pauli_error, t1_ns, duration):
        t2 = 2 * t1_ns
        pauli_error_from_t1 = (1 - np.exp(-duration / t2)) / 2 + (
            1 - np.exp(-duration / t1_ns)) / 4
        if pauli_error >= pauli_error_from_t1:
            return pauli_error - pauli_error_from_t1
        return pauli_error

    t1_ns = 2000.0
    p11 = 0.01

    # Account for floating point errors
    # Needs Cirq issue 3965 to be resolved
    pauli_error = 0.019999999999999962

    # Create qubits and circuit
    qubits = [cirq.LineQubit(0), cirq.LineQubit(1)]
    circuit = cirq.Circuit(
        cirq.Moment([cirq.X(qubits[0])]),
        cirq.Moment([cirq.CNOT(qubits[0], qubits[1])]),
        cirq.Moment([cirq.measure(qubits[0], key='q0')]),
        cirq.Moment([cirq.ISwapPowGate().on_each(qubits)]),
        cirq.Moment([
            cirq.measure(qubits[0], key='q0'),
            cirq.measure(qubits[1], key='q1')
        ]),
    )

    # Create noise model from NoiseProperties object with specified noise
    prop = NoiseProperties(t1_ns=t1_ns, p11=p11, pauli_error=pauli_error)
    noise_model = NoiseModelFromNoiseProperties(prop)

    with pytest.warns(
            RuntimeWarning,
            match='Pauli error from T1 decay is greater than total Pauli error'
    ):
        noisy_circuit = cirq.Circuit(noise_model.noisy_moments(
            circuit, qubits))

    # Insert expected channels to circuit
    expected_circuit = cirq.Circuit(
        cirq.Moment([cirq.X(qubits[0])]),
        cirq.Moment([
            cirq.depolarize(
                pauli_error_from_depolarization(pauli_error, t1_ns, 25.0) /
                3).on_each(qubits)
        ]),
        cirq.Moment(
            [cirq.amplitude_damp(1 - np.exp(-25.0 / t1_ns)).on_each(qubits)]),
        cirq.Moment([cirq.CNOT(qubits[0], qubits[1])]),
        cirq.Moment([
            cirq.depolarize(
                pauli_error_from_depolarization(pauli_error, t1_ns, 25.0) /
                3).on_each(qubits)
        ]),
        cirq.Moment(
            [cirq.amplitude_damp(1 - np.exp(-25.0 / t1_ns)).on_each(qubits)]),
        cirq.Moment([
            cirq.GeneralizedAmplitudeDampingChannel(p=1.0,
                                                    gamma=p11).on(qubits[0])
        ]),
        cirq.Moment([cirq.measure(qubits[0], key='q0')]),
        cirq.Moment([
            cirq.depolarize(
                pauli_error_from_depolarization(pauli_error, t1_ns, 4000.0) /
                3).on_each(qubits)
        ]),
        cirq.Moment([
            cirq.amplitude_damp(1 - np.exp(-4000.0 / t1_ns)).on_each(qubits)
        ]),
        cirq.Moment([cirq.ISwapPowGate().on_each(qubits)]),
        cirq.Moment([
            cirq.depolarize(
                pauli_error_from_depolarization(pauli_error, t1_ns, 32.0) /
                3).on_each(qubits)
        ]),
        cirq.Moment(
            [cirq.amplitude_damp(1 - np.exp(-32.0 / t1_ns)).on_each(qubits)]),
        cirq.Moment([
            cirq.GeneralizedAmplitudeDampingChannel(p=1.0,
                                                    gamma=p11).on_each(qubits)
        ]),
        cirq.Moment([
            cirq.measure(qubits[0], key='q0'),
            cirq.measure(qubits[1], key='q1')
        ]),
        cirq.Moment([
            cirq.depolarize(
                pauli_error_from_depolarization(pauli_error, t1_ns, 4000.0) /
                3).on_each(qubits)
        ]),
        cirq.Moment([
            cirq.amplitude_damp(1 - np.exp(-4000.0 / t1_ns)).on_each(qubits)
        ]),
    )
    assert_equivalent_op_tree(expected_circuit, noisy_circuit)
Beispiel #26
0
def _unitaries_allclose(circuit1, circuit2):
    cirq.testing.assert_circuits_with_terminal_measurements_are_equivalent(
        circuit1, circuit2, atol=1e-6)
    return True


@pytest.mark.parametrize(
    'gate, expected_length',
    [
        (cast(cirq.Gate, cirq.ISWAP), 7),  # cast is for fixing mypy confusion
        (cirq.CZ, 8),
        (cirq.SWAP, 7),
        (cirq.CNOT, 9),
        (cirq.ISWAP**0.5, 1),
        (cirq.ISWAP**-0.5, 1),
        (cirq.ISwapPowGate(exponent=0.5), 1),
        (cirq.ISwapPowGate(exponent=-0.5), 1),
        (cirq.FSimGate(theta=np.pi / 4, phi=0), 1),
        *[(cirq.SwapPowGate(exponent=a), 13)
          for a in np.linspace(0, 2 * np.pi, 20)],
        *[(cirq.CZPowGate(exponent=a), 8)
          for a in np.linspace(0, 2 * np.pi, 20)],
        *[(cirq.ISwapPowGate(exponent=a), 5)
          for a in np.linspace(0, 2 * np.pi, 20)],
        *[(cirq.CNotPowGate(exponent=a), 9)
          for a in np.linspace(0, 2 * np.pi, 20)],
        *[(cirq.FSimGate(theta=a, phi=a), 13)
          for a in np.linspace(0, 2 * np.pi, 20)],
    ],
)
def test_two_qubit_gates(gate: cirq.Gate, expected_length: int):
Beispiel #27
0
    def test_cirq_qsim_all_supported_gates(self):
        q0 = cirq.GridQubit(1, 1)
        q1 = cirq.GridQubit(1, 0)
        q2 = cirq.GridQubit(0, 1)
        q3 = cirq.GridQubit(0, 0)

        circuit = cirq.Circuit(
            cirq.Moment([
                cirq.H(q0),
                cirq.H(q1),
                cirq.H(q2),
                cirq.H(q3),
            ]),
            cirq.Moment([
                cirq.T(q0),
                cirq.T(q1),
                cirq.T(q2),
                cirq.T(q3),
            ]),
            cirq.Moment([
                cirq.CZPowGate(exponent=0.7, global_shift=0.2)(q0, q1),
                cirq.CXPowGate(exponent=1.2, global_shift=0.4)(q2, q3),
            ]),
            cirq.Moment([
                cirq.XPowGate(exponent=0.3, global_shift=1.1)(q0),
                cirq.YPowGate(exponent=0.4, global_shift=1)(q1),
                cirq.ZPowGate(exponent=0.5, global_shift=0.9)(q2),
                cirq.HPowGate(exponent=0.6, global_shift=0.8)(q3),
            ]),
            cirq.Moment([
                cirq.CX(q0, q2),
                cirq.CZ(q1, q3),
            ]),
            cirq.Moment([
                cirq.X(q0),
                cirq.Y(q1),
                cirq.Z(q2),
                cirq.S(q3),
            ]),
            cirq.Moment([
                cirq.XXPowGate(exponent=0.4, global_shift=0.7)(q0, q1),
                cirq.YYPowGate(exponent=0.8, global_shift=0.5)(q2, q3),
            ]),
            cirq.Moment([cirq.I(q0),
                         cirq.I(q1),
                         cirq.IdentityGate(2)(q2, q3)]),
            cirq.Moment([
                cirq.rx(0.7)(q0),
                cirq.ry(0.2)(q1),
                cirq.rz(0.4)(q2),
                cirq.PhasedXPowGate(phase_exponent=0.8,
                                    exponent=0.6,
                                    global_shift=0.3)(q3),
            ]),
            cirq.Moment([
                cirq.ZZPowGate(exponent=0.3, global_shift=1.3)(q0, q2),
                cirq.ISwapPowGate(exponent=0.6, global_shift=1.2)(q1, q3),
            ]),
            cirq.Moment([
                cirq.XPowGate(exponent=0.1, global_shift=0.9)(q0),
                cirq.YPowGate(exponent=0.2, global_shift=1)(q1),
                cirq.ZPowGate(exponent=0.3, global_shift=1.1)(q2),
                cirq.HPowGate(exponent=0.4, global_shift=1.2)(q3),
            ]),
            cirq.Moment([
                cirq.SwapPowGate(exponent=0.2, global_shift=0.9)(q0, q1),
                cirq.PhasedISwapPowGate(phase_exponent=0.8, exponent=0.6)(q2,
                                                                          q3),
            ]),
            cirq.Moment([
                cirq.PhasedXZGate(x_exponent=0.2,
                                  z_exponent=0.3,
                                  axis_phase_exponent=1.4)(q0),
                cirq.T(q1),
                cirq.H(q2),
                cirq.S(q3),
            ]),
            cirq.Moment([
                cirq.SWAP(q0, q2),
                cirq.XX(q1, q3),
            ]),
            cirq.Moment([
                cirq.rx(0.8)(q0),
                cirq.ry(0.9)(q1),
                cirq.rz(1.2)(q2),
                cirq.T(q3),
            ]),
            cirq.Moment([
                cirq.YY(q0, q1),
                cirq.ISWAP(q2, q3),
            ]),
            cirq.Moment([
                cirq.T(q0),
                cirq.Z(q1),
                cirq.Y(q2),
                cirq.X(q3),
            ]),
            cirq.Moment([
                cirq.FSimGate(0.3, 1.7)(q0, q2),
                cirq.ZZ(q1, q3),
            ]),
            cirq.Moment([
                cirq.ry(1.3)(q0),
                cirq.rz(0.4)(q1),
                cirq.rx(0.7)(q2),
                cirq.S(q3),
            ]),
            cirq.Moment([
                cirq.MatrixGate(
                    np.array([[0, -0.5 - 0.5j, -0.5 - 0.5j, 0],
                              [0.5 - 0.5j, 0, 0, -0.5 + 0.5j],
                              [0.5 - 0.5j, 0, 0, 0.5 - 0.5j],
                              [0, -0.5 - 0.5j, 0.5 + 0.5j, 0]]))(q0, q1),
                cirq.MatrixGate(
                    np.array([[0.5 - 0.5j, 0, 0, -0.5 + 0.5j],
                              [0, 0.5 - 0.5j, -0.5 + 0.5j, 0],
                              [0, -0.5 + 0.5j, -0.5 + 0.5j, 0],
                              [0.5 - 0.5j, 0, 0, 0.5 - 0.5j]]))(q2, q3),
            ]),
            cirq.Moment([
                cirq.MatrixGate(np.array([[1, 0], [0, 1j]]))(q0),
                cirq.MatrixGate(np.array([[0, -1j], [1j, 0]]))(q1),
                cirq.MatrixGate(np.array([[0, 1], [1, 0]]))(q2),
                cirq.MatrixGate(np.array([[1, 0], [0, -1]]))(q3),
            ]),
            cirq.Moment([
                cirq.riswap(0.7)(q0, q1),
                cirq.givens(1.2)(q2, q3),
            ]),
            cirq.Moment([
                cirq.H(q0),
                cirq.H(q1),
                cirq.H(q2),
                cirq.H(q3),
            ]),
        )

        simulator = cirq.Simulator()
        cirq_result = simulator.simulate(circuit)

        qsim_simulator = qsimcirq.QSimSimulator()
        qsim_result = qsim_simulator.simulate(circuit)

        assert cirq.linalg.allclose_up_to_global_phase(
            qsim_result.state_vector(), cirq_result.state_vector())
Beispiel #28
0
def test_try_convert_gate_to_fsim():
    def check(gate: cirq.Gate, expected: PhaseCalibratedFSimGate):
        assert np.allclose(cirq.unitary(gate), cirq.unitary(expected))
        assert try_convert_gate_to_fsim(gate) == expected

    check(
        cirq.FSimGate(theta=0.3, phi=0.5),
        PhaseCalibratedFSimGate(cirq.FSimGate(theta=0.3, phi=0.5), 0.0),
    )

    check(
        cirq.FSimGate(7 * np.pi / 4, 0.0),
        PhaseCalibratedFSimGate(cirq.FSimGate(np.pi / 4, 0.0), 0.5),
    )

    check(
        cirq.ISwapPowGate(exponent=-0.5),
        PhaseCalibratedFSimGate(cirq.FSimGate(theta=0.25 * np.pi, phi=0.0),
                                0.0),
    )

    check(
        cirq.ops.ISwapPowGate(exponent=0.8, global_shift=2.5),
        PhaseCalibratedFSimGate(cirq.FSimGate(theta=0.4 * np.pi, phi=0.0),
                                0.5),
    )

    gate = cirq.ops.ISwapPowGate(exponent=0.3, global_shift=0.4)
    assert try_convert_gate_to_fsim(gate) is None

    check(
        cirq.PhasedFSimGate(theta=0.2, phi=0.5, chi=1.5 * np.pi),
        PhaseCalibratedFSimGate(cirq.FSimGate(theta=0.2, phi=0.5), 0.25),
    )

    gate = cirq.PhasedFSimGate(theta=0.2, phi=0.5, zeta=1.5 * np.pi)
    assert try_convert_gate_to_fsim(gate) is None

    check(
        cirq.PhasedISwapPowGate(exponent=-0.5, phase_exponent=0.75),
        PhaseCalibratedFSimGate(cirq.FSimGate(theta=0.25 * np.pi, phi=0.0),
                                0.25),
    )

    check(cirq.CZ,
          PhaseCalibratedFSimGate(cirq.FSimGate(theta=0.0, phi=np.pi), 0.0))

    check(
        cirq.ops.CZPowGate(exponent=0.3),
        PhaseCalibratedFSimGate(cirq.FSimGate(theta=0.0, phi=-0.3 * np.pi),
                                0.0),
    )

    check(
        cirq.ops.CZPowGate(exponent=0.8, global_shift=2.5),
        PhaseCalibratedFSimGate(cirq.FSimGate(theta=0.0, phi=-0.8 * np.pi),
                                0.0),
    )

    gate = cirq.ops.CZPowGate(exponent=0.3, global_shift=0.4)
    assert try_convert_gate_to_fsim(gate) is None

    check(
        cirq_google.ops.SYC,
        PhaseCalibratedFSimGate(cirq.FSimGate(phi=np.pi / 6, theta=np.pi / 2),
                                0.0),
    )

    assert try_convert_gate_to_fsim(cirq.CX) is None

    # Parameterized gates are not supported.
    x = sympy.Symbol('x')
    assert try_convert_gate_to_fsim(cirq.ops.ISwapPowGate(exponent=x)) is None
    assert try_convert_gate_to_fsim(cirq.PhasedFSimGate(theta=x)) is None
    assert try_convert_gate_to_fsim(
        cirq.PhasedISwapPowGate(exponent=x)) is None
    assert try_convert_gate_to_fsim(cirq.CZPowGate(exponent=x)) is None
Beispiel #29
0
    def _deserialize_gate_op(
        self,
        operation_proto: v2.program_pb2.Operation,
        *,
        arg_function_language: str = '',
        constants: Optional[List[v2.program_pb2.Constant]] = None,
        deserialized_constants: Optional[List[Any]] = None,
    ) -> cirq.Operation:
        """Deserialize an Operation from a cirq_google.api.v2.Operation.

        Args:
            operation_proto: A dictionary representing a
                cirq.google.api.v2.Operation proto.
            arg_function_language: The `arg_function_language` field from
                `Program.Language`.
            constants: The list of Constant protos referenced by constant
                table indices in `proto`.
            deserialized_constants: The deserialized contents of `constants`.
                cirq_google.api.v2.Operation proto.

        Returns:
            The deserialized Operation.
        """
        if deserialized_constants is not None:
            qubits = [
                deserialized_constants[q]
                for q in operation_proto.qubit_constant_index
            ]
        else:
            qubits = []
        for q in operation_proto.qubits:
            # Preserve previous functionality in case
            # constants table was not used
            qubits.append(v2.qubit_from_proto_id(q.id))

        which_gate_type = operation_proto.WhichOneof('gate_value')

        if which_gate_type == 'xpowgate':
            op = cirq.XPowGate(exponent=arg_func_langs.float_arg_from_proto(
                operation_proto.xpowgate.exponent,
                arg_function_language=arg_function_language,
                required_arg_name=None,
            ))(*qubits)
        elif which_gate_type == 'ypowgate':
            op = cirq.YPowGate(exponent=arg_func_langs.float_arg_from_proto(
                operation_proto.ypowgate.exponent,
                arg_function_language=arg_function_language,
                required_arg_name=None,
            ))(*qubits)
        elif which_gate_type == 'zpowgate':
            op = cirq.ZPowGate(exponent=arg_func_langs.float_arg_from_proto(
                operation_proto.zpowgate.exponent,
                arg_function_language=arg_function_language,
                required_arg_name=None,
            ))(*qubits)
            if operation_proto.zpowgate.is_physical_z:
                op = op.with_tags(PhysicalZTag())
        elif which_gate_type == 'phasedxpowgate':
            exponent = arg_func_langs.float_arg_from_proto(
                operation_proto.phasedxpowgate.exponent,
                arg_function_language=arg_function_language,
                required_arg_name=None,
            )
            phase_exponent = arg_func_langs.float_arg_from_proto(
                operation_proto.phasedxpowgate.phase_exponent,
                arg_function_language=arg_function_language,
                required_arg_name=None,
            )
            op = cirq.PhasedXPowGate(exponent=exponent,
                                     phase_exponent=phase_exponent)(*qubits)
        elif which_gate_type == 'phasedxzgate':
            x_exponent = arg_func_langs.float_arg_from_proto(
                operation_proto.phasedxzgate.x_exponent,
                arg_function_language=arg_function_language,
                required_arg_name=None,
            )
            z_exponent = arg_func_langs.float_arg_from_proto(
                operation_proto.phasedxzgate.z_exponent,
                arg_function_language=arg_function_language,
                required_arg_name=None,
            )
            axis_phase_exponent = arg_func_langs.float_arg_from_proto(
                operation_proto.phasedxzgate.axis_phase_exponent,
                arg_function_language=arg_function_language,
                required_arg_name=None,
            )
            op = cirq.PhasedXZGate(
                x_exponent=x_exponent,
                z_exponent=z_exponent,
                axis_phase_exponent=axis_phase_exponent,
            )(*qubits)
        elif which_gate_type == 'czpowgate':
            op = cirq.CZPowGate(exponent=arg_func_langs.float_arg_from_proto(
                operation_proto.czpowgate.exponent,
                arg_function_language=arg_function_language,
                required_arg_name=None,
            ))(*qubits)
        elif which_gate_type == 'iswappowgate':
            op = cirq.ISwapPowGate(
                exponent=arg_func_langs.float_arg_from_proto(
                    operation_proto.iswappowgate.exponent,
                    arg_function_language=arg_function_language,
                    required_arg_name=None,
                ))(*qubits)
        elif which_gate_type == 'fsimgate':
            theta = arg_func_langs.float_arg_from_proto(
                operation_proto.fsimgate.theta,
                arg_function_language=arg_function_language,
                required_arg_name=None,
            )
            phi = arg_func_langs.float_arg_from_proto(
                operation_proto.fsimgate.phi,
                arg_function_language=arg_function_language,
                required_arg_name=None,
            )
            if isinstance(theta, (float, sympy.Basic)) and isinstance(
                    phi, (float, sympy.Basic)):
                op = cirq.FSimGate(theta=theta, phi=phi)(*qubits)
            else:
                raise ValueError(
                    'theta and phi must be specified for FSimGate')
        elif which_gate_type == 'measurementgate':
            key = arg_func_langs.arg_from_proto(
                operation_proto.measurementgate.key,
                arg_function_language=arg_function_language,
                required_arg_name=None,
            )
            invert_mask = arg_func_langs.arg_from_proto(
                operation_proto.measurementgate.invert_mask,
                arg_function_language=arg_function_language,
                required_arg_name=None,
            )
            if isinstance(invert_mask, list) and isinstance(key, str):
                op = cirq.MeasurementGate(
                    num_qubits=len(qubits),
                    key=key,
                    invert_mask=tuple(invert_mask))(*qubits)
            else:
                raise ValueError(
                    f'Incorrect types for measurement gate {invert_mask} {key}'
                )

        elif which_gate_type == 'waitgate':
            total_nanos = arg_func_langs.float_arg_from_proto(
                operation_proto.waitgate.duration_nanos,
                arg_function_language=arg_function_language,
                required_arg_name=None,
            )
            op = cirq.WaitGate(duration=cirq.Duration(nanos=total_nanos))(
                *qubits)
        else:
            raise ValueError(
                f'Unsupported serialized gate with type "{which_gate_type}".'
                f'\n\noperation_proto:\n{operation_proto}')

        which = operation_proto.WhichOneof('token')
        if which == 'token_constant_index':
            if not constants:
                raise ValueError('Proto has references to constants table '
                                 'but none was passed in, value ='
                                 f'{operation_proto}')
            op = op.with_tags(
                CalibrationTag(constants[
                    operation_proto.token_constant_index].string_value))
        elif which == 'token_value':
            op = op.with_tags(CalibrationTag(operation_proto.token_value))

        return op
Beispiel #30
0
        {THETA: 0, PHI: 2 * np.pi},
    ),
    (
        cirq.PhasedFSimGate.from_fsim_rz(
            theta=THETA,
            phi=PHI,
            rz_angles_before=(2 * np.pi, 2 * np.pi),
            rz_angles_after=(0, 0),
        ),
        {THETA: 2 * np.pi, PHI: -0.01},
    ),
    *VALID_IDENTITY,
]

VALID_ISWAP_GATES = [
    (cirq.ISwapPowGate(exponent=THETA, global_shift=2.5), {THETA: 0.1}),
    (cirq.PhasedISwapPowGate(exponent=0.1, phase_exponent=PHI), {PHI: 2}),
    (cirq.SQRT_ISWAP_INV ** THETA, {THETA: 0.1}),
    (cirq.FSimGate(theta=THETA, phi=PHI), {THETA: 0.1, PHI: 0}),
    (cirq.FSimGate(theta=-0.4, phi=PHI), {PHI: 2 * np.pi}),
    (
        cirq.PhasedFSimGate.from_fsim_rz(
            theta=10,
            phi=PHI,
            rz_angles_before=(PHI, PHI),
            rz_angles_after=(THETA, THETA),
        ),
        {THETA: 2 * np.pi, PHI: 0},
    ),
    (
        cirq.PhasedFSimGate.from_fsim_rz(