Example #1
0
def test_gate_equality():
    eq = cirq.testing.EqualsTester()
    eq.add_equality_group(cirq.CSwapGate(), cirq.CSwapGate())
    eq.add_equality_group(cirq.CZPowGate(), cirq.CZPowGate())
    eq.add_equality_group(cirq.CCXPowGate(), cirq.CCXPowGate(),
                          cirq.CCNotPowGate())
    eq.add_equality_group(cirq.CCZPowGate(), cirq.CCZPowGate())
Example #2
0
def test_rot_gates_eq():
    eq = cirq.testing.EqualsTester()
    gates = [
        lambda p: cirq.CZ**p,
        lambda p: cirq.X**p,
        lambda p: cirq.Y**p,
        lambda p: cirq.Z**p,
        lambda p: cirq.CNOT**p,
    ]
    for gate in gates:
        eq.add_equality_group(gate(3.5),
                              gate(-0.5))
        eq.make_equality_group(lambda: gate(0))
        eq.make_equality_group(lambda: gate(0.5))

    eq.add_equality_group(cirq.XPowGate(), cirq.XPowGate(exponent=1), cirq.X)
    eq.add_equality_group(cirq.YPowGate(), cirq.YPowGate(exponent=1), cirq.Y)
    eq.add_equality_group(cirq.ZPowGate(), cirq.ZPowGate(exponent=1), cirq.Z)
    eq.add_equality_group(cirq.ZPowGate(exponent=1,
                                        global_shift=-0.5),
                          cirq.ZPowGate(exponent=5,
                                        global_shift=-0.5))
    eq.add_equality_group(cirq.ZPowGate(exponent=3,
                                        global_shift=-0.5))
    eq.add_equality_group(cirq.ZPowGate(exponent=1,
                                        global_shift=-0.1))
    eq.add_equality_group(cirq.ZPowGate(exponent=5,
                                        global_shift=-0.1))
    eq.add_equality_group(cirq.CNotPowGate(),
                          cirq.CNotPowGate(exponent=1),
                          cirq.CNOT)
    eq.add_equality_group(cirq.CZPowGate(),
                          cirq.CZPowGate(exponent=1), cirq.CZ)
def test_not_decompose_czs():
    circuit = cirq.Circuit(
        cirq.CZPowGate(exponent=1, global_shift=-0.5).on(*cirq.LineQubit.range(2))
    )
    circ_orig = circuit.copy()
    cirq.MergeInteractions(allow_partial_czs=False).optimize_circuit(circuit)
    assert circ_orig == circuit
def test_dont_allow_partial_czs():
    q0, q1 = cirq.LineQubit.range(2)
    circuit = cirq.Circuit(
        cirq.CZ(q0, q1),
        cirq.CZPowGate(exponent=1, global_shift=-0.5).on(q0, q1),
    )
    c_orig = cirq.Circuit(circuit)
    with cirq.testing.assert_deprecated("Use cirq.optimize_for_target_gateset",
                                        deadline='v1.0'):
        cirq.ConvertToCzAndSingleGates().optimize_circuit(circuit)
    assert circuit == c_orig

    circuit = cirq.Circuit(cirq.CZ(q0, q1)**0.5, )
    c_orig = cirq.Circuit(circuit)
    with cirq.testing.assert_deprecated("Use cirq.optimize_for_target_gateset",
                                        deadline='v1.0'):
        cirq.ConvertToCzAndSingleGates(
            ignore_failures=True).optimize_circuit(circuit)

    assert sum(1 for op in circuit.all_operations() if len(op.qubits) > 1) == 2
    assert sum(1 for op in circuit.all_operations()
               if isinstance(op.gate, cirq.CZPowGate)) == 2
    assert all(op.gate.exponent % 2 == 1 for op in circuit.all_operations()
               if isinstance(op.gate, cirq.CZPowGate))
    cirq.testing.assert_allclose_up_to_global_phase(circuit.unitary(),
                                                    c_orig.unitary(),
                                                    atol=1e-7)
Example #5
0
def rot_11_layer(jc, jr, half_turns):
    rot1 = cirq.CZPowGate(exponent=half_turns)
    for i, r in enumerate(jr):
        for j, jr_ij in enumerate(r):
            if jr_ij < 0:
                yield (cirq.X(cirq.GridQubit(i, j)))
                yield (cirq.X(cirq.GridQubit(i + 1, j)))
            yield (rot1(cirq.GridQubit(i, j), cirq.GridQubit(i + 1, j)))
            yield (cirq.CZ(cirq.GridQubit(i, j), cirq.GridQubit(i + 1,
                                                                j)))  #change 1
            yield (cirq.CZ(cirq.GridQubit(i, j), cirq.GridQubit(i + 1,
                                                                j)))  #chang 2
            if jr_ij < 0:
                yield (cirq.X(cirq.GridQubit(i, j)))
                yield (cirq.X(cirq.GridQubit(i + 1, j)))

    for i, c in enumerate(jc):
        for j, jc_ij in enumerate(c):
            if jc_ij < 0:
                yield (cirq.X(cirq.GridQubit(i, j)))
                yield (cirq.X(cirq.GridQubit(i, j + 1)))
            yield (rot1(cirq.GridQubit(i, j), cirq.GridQubit(i, j + 1)))
            yield (cirq.CZ(cirq.GridQubit(i, j),
                           cirq.GridQubit(i, j + 1)))  #change 3
            yield (cirq.CZ(cirq.GridQubit(i, j),
                           cirq.GridQubit(i, j + 1)))  #chang 4
            if jc_ij < 0:
                yield (cirq.X(cirq.GridQubit(i, j)))
                yield (cirq.X(cirq.GridQubit(i, j + 1)))
Example #6
0
def test_serialize_deserialize_cz_gate(gate, exponent):
    gate_set = cg.SerializableGateSet('test', [cgc.CZ_SERIALIZER],
                                      [cgc.CZ_POW_DESERIALIZER])
    proto = op_proto({
        'gate': {
            'id': 'cz'
        },
        'args': {
            'half_turns': {
                'arg_value': {
                    'float_value': exponent
                }
            }
        },
        'qubits': [{
            'id': '5_4'
        }, {
            'id': '5_5'
        }]
    })
    q1 = cirq.GridQubit(5, 4)
    q2 = cirq.GridQubit(5, 5)
    op = cirq.CZPowGate(exponent=exponent)
    assert gate_set.serialize_op(gate(q1, q2)) == proto
    cirq.testing.assert_allclose_up_to_global_phase(
        cirq.unitary(gate_set.deserialize_op(proto)),
        cirq.unitary(op),
        atol=1e-7,
    )
Example #7
0
def export_to_cirq(obj):
    """Imports a gate, operation or circuit from Cirq.

  Args:
      obj: the object to be exported to Cirq.

  Returns:
      the exported Cirq object (an instance of cirq.Circuit, cirq.GateOperation,
      or a subclass of cirq.Gate).

  Raises:
      TypeError: if export is not supported for the given type.
      ValueError: if the object cannot be exported successfully.
  """

    if isinstance(obj, circuit.PhasedXGate):
        return cirq.PhasedXPowGate(exponent=obj.get_rotation_angle() / np.pi,
                                   phase_exponent=obj.get_phase_angle() /
                                   np.pi)
    elif isinstance(obj, circuit.RotZGate):
        return cirq.ZPowGate(exponent=obj.get_rotation_angle() / np.pi)
    elif isinstance(obj, circuit.ControlledZGate):
        return cirq.CZPowGate(exponent=1.0)
    elif isinstance(obj, circuit.MatrixGate):
        return cirq.MatrixGate(obj.get_operator())
    elif isinstance(obj, circuit.Operation):
        return cirq.GateOperation(
            export_to_cirq(obj.get_gate()),
            [cirq.LineQubit(qubit) for qubit in obj.get_qubits()])
    elif isinstance(obj, circuit.Circuit):
        return cirq.Circuit(export_to_cirq(operation) for operation in obj)
    else:
        raise TypeError('unknown type: %s' % type(obj).__name__)
Example #8
0
def test_deserialize_exp_11(half_turns):
    with cirq.testing.assert_deprecated('SerializableGateSet',
                                        deadline='v0.16',
                                        count=1):
        serialized_op = op_proto({
            'gate': {
                'id': 'cz'
            },
            'args': {
                'half_turns': {
                    'arg_value': {
                        'float_value': half_turns
                    }
                }
            },
            'qubits': [{
                'id': '1_2'
            }, {
                'id': '2_2'
            }],
        })
        c = cirq.GridQubit(1, 2)
        t = cirq.GridQubit(2, 2)
        expected = cirq.CZPowGate(exponent=half_turns)(c, t)
        assert cg.XMON.deserialize_op(serialized_op) == expected
Example #9
0
def test_fsim_iswap_cphase(theta, phi):
    q0, q1 = cirq.NamedQubit('q0'), cirq.NamedQubit('q1')
    iswap = cirq.ISWAP**(-theta * 2 / np.pi)
    cphase = cirq.CZPowGate(exponent=-phi / np.pi)
    iswap_cphase = cirq.Circuit((iswap.on(q0, q1), cphase.on(q0, q1)))
    fsim = cirq.FSimGate(theta=theta, phi=phi)
    assert np.allclose(cirq.unitary(iswap_cphase), cirq.unitary(fsim))
Example #10
0
  def test_import_partial_cz_error(self):
    partial_cz = cirq.CZPowGate(exponent=0.37)

    with self.assertRaisesRegex(
        ValueError,
        r'partial ControlledZ gates are not supported'):
      cirq_converter.import_from_cirq(partial_cz)
def test_serialize_deserialize_cz_gate(gate, exponent, phys_z):
    gate_set = cg.SerializableGateSet('test', [cgc.CZ_SERIALIZER],
                                      [cgc.CZ_POW_DESERIALIZER])
    proto = op_proto({
        'gate': {
            'id': 'cz'
        },
        'args': {
            'half_turns': {
                'arg_value': {
                    'float_value': exponent
                }
            },
            **_phys_z_args(phys_z),
        },
        'qubits': [{
            'id': '5_4'
        }, {
            'id': '5_5'
        }],
    })
    q1 = cirq.GridQubit(5, 4)
    q2 = cirq.GridQubit(5, 5)
    op = gate(q1, q2)
    if phys_z:
        op = op.with_tags(cg.PhysicalZTag())
    assert gate_set.serialize_op(op) == proto
    deserialized_op = gate_set.deserialize_op(proto)
    expected_gate = cirq.CZPowGate(exponent=exponent)
    cirq.testing.assert_allclose_up_to_global_phase(
        cirq.unitary(deserialized_op),
        cirq.unitary(expected_gate),
        atol=1e-7,
    )
    assert_phys_z_tag(phys_z, deserialized_op)
Example #12
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)
Example #13
0
def get_match_circuit() -> cirq.Circuit:
    qubits = [cirq.LineQubit(i) for i in range(9)]

    g = cirq.CZPowGate(exponent=0.1)
    zz = cirq.ZZPowGate(exponent=0.3)
    px = cirq.PhasedXPowGate(phase_exponent=0.6, exponent=0.2)
    circ = cirq.Circuit(
        [
            cirq.H(qubits[0]),
            cirq.X(qubits[1]),
            cirq.Y(qubits[2]),
            cirq.Z(qubits[3]),
            cirq.S(qubits[4]),
            cirq.CNOT(qubits[1], qubits[4]),
            cirq.T(qubits[3]),
            cirq.CNOT(qubits[6], qubits[8]),
            cirq.I(qubits[5]),
            cirq.XPowGate(exponent=0.1)(qubits[5]),
            cirq.YPowGate(exponent=0.1)(qubits[6]),
            cirq.ZPowGate(exponent=0.1)(qubits[7]),
            g(qubits[2], qubits[3]),
            zz(qubits[3], qubits[4]),
            px(qubits[6]),
            cirq.CZ(qubits[2], qubits[3]),
            cirq.ISWAP(qubits[4], qubits[5]),
            cirq.FSimGate(1.4, 0.7)(qubits[6], qubits[7]),
            cirq.google.SYC(qubits[3], qubits[0]),
            cirq.PhasedISwapPowGate(phase_exponent=0.7, exponent=0.8)(
                qubits[3], qubits[4]),
            cirq.GlobalPhaseOperation(1j),
            cirq.measure_each(*qubits[3:-2]),
        ],
        strategy=InsertStrategy.EARLIEST,
    )
    return circ
Example #14
0
def test_valid_cphase_exponents(theta, phi):
    fsim_gate = cirq.FSimGate(theta=theta, phi=phi)
    valid_exponent_intervals = cirq.compute_cphase_exponents_for_fsim_decomposition(fsim_gate)
    assert valid_exponent_intervals

    for min_exponent, max_exponent in valid_exponent_intervals:
        margin = 1e-8
        min_exponent += margin
        max_exponent -= margin
        assert min_exponent < max_exponent
        for exponent in np.linspace(min_exponent, max_exponent, 3):
            for d in (-2, 0, 4):
                cphase_gate = cirq.CZPowGate(exponent=exponent + d)
                assert_decomposition_valid(cphase_gate, fsim_gate=fsim_gate)
                cphase_gate = cirq.CZPowGate(exponent=-exponent + d)
                assert_decomposition_valid(cphase_gate, fsim_gate=fsim_gate)
def test_allow_partial_czs():
    q0, q1 = cirq.LineQubit.range(2)
    circuit = cirq.Circuit(
        cirq.CZ(q0, q1)**0.5,
        cirq.CZPowGate(exponent=0.5, global_shift=-0.5).on(q0, q1),
    )
    c_orig = cirq.Circuit(circuit)
    cirq.ConvertToCzAndSingleGates(
        allow_partial_czs=True).optimize_circuit(circuit)

    assert circuit == c_orig

    # yapf: disable
    circuit2 = cirq.Circuit(
        cirq.MatrixGate((np.array([[1, 0, 0, 0],
                                           [0, 1, 0, 0],
                                           [0, 0, 1, 0],
                                           [0, 0, 0, 1j]]))).on(q0, q1))
    # yapf: enable
    cirq.ConvertToCzAndSingleGates(
        allow_partial_czs=True).optimize_circuit(circuit2)
    two_qubit_ops = list(
        circuit2.findall_operations(lambda e: len(e.qubits) == 2))
    assert len(two_qubit_ops) == 1
    gate = two_qubit_ops[0][1].gate
    assert isinstance(gate, cirq.ops.CZPowGate) and gate.exponent == 0.5
Example #16
0
    def controlled(self,
                   num_controls: int = None,
                   control_values: Optional[Sequence[
                       Union[int, Collection[int]]]] = None,
                   control_qid_shape: Optional[Tuple[int, ...]] = None
                  ) -> raw_types.Gate:
        """
        Constructs CZPowGate from controlled ZPowGate when applicable.

        This method is a specialized controlled method for ZPowGate. It
        overrides the default behavior of returning a ControlledGate by
        transforming the underlying controlled gate to a CZPowGate and
        removing the last specified control qubit (which acts first
        semantically).  If this is a gate with multiple control qubits, it will
        now be a ControlledGate with one less control.

        This behavior only occurs when the last control qubit is a default-type
        control qubit. A default-type control qubit is one with shape of 2 (not
        a generic qudit) and where the control is satisfied by the qubit being
        ON, as opposed to OFF.

        (Note that a CZPowGate is, by definition, a controlled-ZPowGate.)
        """
        result = super().controlled(num_controls, control_values,
                                    control_qid_shape)
        if (isinstance(result, controlled_gate.ControlledGate) and
                result.control_values[-1] == (1,) and
                result.control_qid_shape[-1] == 2):
            return cirq.CZPowGate(exponent=self._exponent,
                                  global_shift=self._global_shift).controlled(
                                      result.num_controls() - 1,
                                      result.control_values[:-1],
                                      result.control_qid_shape[:-1])
        return result
Example #17
0
    def rot_11_layer(jr, jc, half_turns):
        """Yields rotations about |11> conditioned on the jr and jc fields."""
        cz_gate = cirq.CZPowGate(exponent=half_turns)
        for i, jr_row in enumerate(jr):
            for j, jr_ij in enumerate(jr_row):
                q = cirq.GridQubit(i, j)
                q_1 = cirq.GridQubit(i + 1, j)
                if jr_ij == -1:
                    yield cirq.X(q)
                    yield cirq.X(q_1)
                yield cz_gate(q, q_1)
                if jr_ij == -1:
                    yield cirq.X(q)
                    yield cirq.X(q_1)

        for i, jc_row in enumerate(jc):
            for j, jc_ij in enumerate(jc_row):
                q = cirq.GridQubit(i, j)
                q_1 = cirq.GridQubit(i, j + 1)
                if jc_ij == -1:
                    yield cirq.X(q)
                    yield cirq.X(q_1)
                yield cz_gate(q, q_1)
                if jc_ij == -1:
                    yield cirq.X(q)
                    yield cirq.X(q_1)
Example #18
0
 def _convert_to_cz(self,
                    g: POSSIBLE_FSIM_GATES) -> Optional[cirq.CZPowGate]:
     if isinstance(g, cirq.CZPowGate):
         return g
     cg = self._convert_to_fsim(g)
     return (None if
             (cg is None or not self._approx_eq_or_symbol(cg.theta, 0)) else
             cirq.CZPowGate(exponent=-cg.phi / np.pi))
Example #19
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)
Example #20
0
def fsim_gate(a, b, theta, phi):
    """FSimGate has a default decomposition in cirq to XXPowGate and YYPowGate,
    which is an awkward decomposition for this gate set.
    Decompose into ISWAP and CZ instead."""
    if theta != 0.0:
        yield cirq.ISWAP(a, b)**(-2 * theta / np.pi)
    if phi != 0.0:
        yield cirq.CZPowGate(exponent=-phi / np.pi)(a, b)
    def _decompose_(self, qubits):
        a, b, c, d = qubits

        weights_to_exponents = (self._exponent / 4.) * np.array([
            [1, -1, 1],
            [1, 1, -1],
            [-1, 1, 1]
        ])
        exponents = weights_to_exponents.dot(self.weights)

        basis_change = list(cirq.flatten_op_tree([
            cirq.CNOT(b, a),
            cirq.CNOT(c, b),
            cirq.CNOT(d, c),
            cirq.CNOT(c, b),
            cirq.CNOT(b, a),
            cirq.CNOT(a, b),
            cirq.CNOT(b, c),
            cirq.CNOT(a, b),
            [cirq.X(c), cirq.X(d)],
            [cirq.CNOT(c, d), cirq.CNOT(d, c)],
            [cirq.X(c), cirq.X(d)],
            ]))

        controlled_Zs = list(cirq.flatten_op_tree([
            cirq.CZPowGate(exponent=exponents[0])(b, c),
            cirq.CNOT(a, b),
            cirq.CZPowGate(exponent=exponents[1])(b, c),
            cirq.CNOT(b, a),
            cirq.CNOT(a, b),
            cirq.CZPowGate(exponent=exponents[2])(b, c)
            ]))

        controlled_swaps = [
            [cirq.CNOT(c, d), cirq.H(c)],
            cirq.CNOT(d, c),
            controlled_Zs,
            cirq.CNOT(d, c),
            [cirq.inverse(op) for op in reversed(controlled_Zs)],
            [cirq.H(c), cirq.CNOT(c, d)],
            ]

        yield basis_change
        yield controlled_swaps
        yield basis_change[::-1]
    def test_gate_matrices_ising(self, t):
        """Verify that the Ising gates work as expected."""

        CZ = cirq.CZPowGate(exponent=t)._unitary_()
        s = 1 - t / 2
        L = cirq.rz(-np.pi * s)._unitary_()
        assert np.allclose(
            np.exp(-1j * np.pi / 2 * s) *
            np.kron(L, L) @ ig.IsingGate(exponent=s)._unitary_(), CZ)
 def controlled(
     self,
     num_controls: int = None,
     control_values: Optional[Sequence[Union[int, Collection[int]]]] = None,
     control_qid_shape: Optional[Tuple[int, ...]] = None,
 ) -> 'cirq.Gate':
     ret = super().controlled(num_controls, control_values, control_qid_shape)
     if num_controls == 1 and control_values is None:
         return cirq.CZPowGate(exponent=self._exponent, global_shift=self._global_shift)
     return ret
 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)
def test_cphase():
    """Test if the sqrt_iswap synthesis for a cphase rotation is correct"""
    thetas = np.linspace(0, 2 * np.pi, 100)
    qubits = [cirq.NamedQubit('a'), cirq.NamedQubit('b')]
    for theta in thetas:
        expected = cirq.CZPowGate(exponent=theta)
        decomposition = cgoc.cphase_to_sqrt_iswap(qubits[0], qubits[1], theta)
        actual = cirq.Circuit(decomposition)
        expected_unitary = cirq.unitary(expected)
        actual_unitary = cirq.unitary(actual)
        np.testing.assert_allclose(expected_unitary, actual_unitary, atol=1e-7)
Example #26
0
def test_z_control():
    # Single qubit control on Z gives a CZ
    assert cirq.Z.controlled() == cirq.CZ
    assert cirq.Z.controlled(num_controls=1) == cirq.CZ
    assert cirq.Z.controlled(control_values=((1, ), )) == cirq.CZ
    assert cirq.Z.controlled(control_qid_shape=(2, )) == cirq.CZ

    # Also works for any ZPow.
    assert cirq.ZPowGate(exponent=5).controlled() == cirq.CZPowGate(exponent=5)

    # For multi-qudit controls, if the last control is a qubit with control
    # value 1, construct a CZ leaving the rest of the controls as is.
    assert cirq.Z.controlled().controlled() == cirq.ControlledGate(
        cirq.CZ, num_controls=1)
    assert cirq.Z.controlled(num_controls=2) == cirq.ControlledGate(
        cirq.CZ, num_controls=1)
    assert cirq.Z.controlled(control_values=((0, ), (0, ),
                                             (1, ))) == cirq.ControlledGate(
                                                 cirq.CZ,
                                                 num_controls=2,
                                                 control_values=((0, ), (0, )))
    assert cirq.Z.controlled(control_qid_shape=(3, 3,
                                                2)) == cirq.ControlledGate(
                                                    cirq.CZ,
                                                    num_controls=2,
                                                    control_qid_shape=(3, 3))
    assert cirq.Z.controlled(control_qid_shape=(2, )).controlled(
        control_qid_shape=(3, )).controlled(
            control_qid_shape=(4, )) == cirq.ControlledGate(
                cirq.CZ, num_controls=2, control_qid_shape=(3, 4))

    # When a control_value 1 qubit is not acting first, results in a regular
    # ControlledGate on Z instance.
    assert cirq.Z.controlled(num_controls=1,
                             control_qid_shape=(3, )) == cirq.ControlledGate(
                                 cirq.Z,
                                 num_controls=1,
                                 control_qid_shape=(3, ))
    assert cirq.Z.controlled(control_values=((0, ), (1, ),
                                             (0, ))) == cirq.ControlledGate(
                                                 cirq.Z,
                                                 num_controls=3,
                                                 control_values=((0, ), (1, ),
                                                                 (0, )))
    assert cirq.Z.controlled(control_qid_shape=(3, 2,
                                                3)) == cirq.ControlledGate(
                                                    cirq.Z,
                                                    num_controls=3,
                                                    control_qid_shape=(3, 2,
                                                                       3))
    assert cirq.Z.controlled(control_qid_shape=(3, )).controlled(
        control_qid_shape=(2, )).controlled(
            control_qid_shape=(4, )) == cirq.ControlledGate(
                cirq.Z, num_controls=3, control_qid_shape=(3, 2, 4))
Example #27
0
def sycamore_circuit(num_qubits, depth, reg):
    gateSequence = [0, 3, 2, 1, 2, 1, 0, 3]
    single_bit_gates = sqrtx, sqrty, sqrtw
    circ = cirq.Circuit()

    colLen = math.floor(math.sqrt(num_qubits))
    while (((num_qubits / colLen) * colLen) != num_qubits):
        colLen = colLen - 1
    rowLen = num_qubits // colLen

    lastSingleBitGates = []

    for i in range(depth):
        # Single bit gates
        singleBitGates = []
        for j in range(num_qubits):
            gate = random.choice(single_bit_gates)
            if len(lastSingleBitGates) > 0:
                while gate == lastSingleBitGates[j]:
                    gate = random.choice(single_bit_gates)
            circ.append(gate(reg[j]))
            singleBitGates.append(gate)

        lastSingleBitGates = singleBitGates

        gate = gateSequence[0]
        gateSequence.pop(0)
        gateSequence.append(gate)

        for row in range(1, rowLen, 2):
            for col in range(0, colLen):
                tempRow = row
                tempCol = col

                tempRow = tempRow + (1 if (gate & 2) else -1)
                if colLen != 1:
                    tempCol = tempCol + (1 if (gate & 1) else 0)

                if (tempRow < 0) or (tempCol < 0) or (tempRow >= rowLen) or (
                        tempCol >= colLen):
                    continue

                b1 = row * colLen + col
                b2 = tempRow * colLen + tempCol

                # Two bit gates
                circ.append(
                    cirq.CZPowGate(exponent=1 / 6).on(reg[b1], reg[b2]))
                circ.append(cirq.ISWAP(reg[b1], reg[b2]))

    for j in range(num_qubits):
        circ.append(cirq.measure(reg[j]))

    return circ
Example #28
0
def test_not_decompose_czs():
    circuit = cirq.Circuit(
        cirq.CZPowGate(exponent=1,
                       global_shift=-0.5).on(*cirq.LineQubit.range(2)))
    circ_orig = circuit.copy()
    with cirq.testing.assert_deprecated("Use cirq.optimize_for_target_gateset",
                                        deadline='v1.0',
                                        count=2):
        cirq.MergeInteractions(
            allow_partial_czs=False).optimize_circuit(circuit)
    assert circ_orig == circuit
Example #29
0
 def one_and_two_body_interaction_reversed_order(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 v_symbol in param_set:
         yield cirq.CZPowGate(exponent=v_symbol).on(a, b)
     if w_symbol in param_set:
         yield YXXYPowGate(exponent=w_symbol).on(a, b)
     if t_symbol in param_set:
         yield XXYYPowGate(exponent=t_symbol).on(a, b)
 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)