Пример #1
0
def matrix_to_sycamore_operations(
        target_qubits: List[cirq.GridQubit],
        matrix: np.ndarray) -> Tuple[cirq.OP_TREE, List[cirq.GridQubit]]:
    """A method to convert a unitary matrix to a list of Sycamore operations.

    This method will return a list of `cirq.Operation`s using the qubits and (optionally) ancilla
    qubits to implement the unitary matrix `matrix` on the target qubits `qubits`.
    The operations are also supported by `cirq.google.gate_sets.SYC_GATESET`.

    Args:
        target_qubits: list of qubits the returned operations will act on. The qubit order defined by the list
            is assumed to be used by the operations to implement `matrix`.
        matrix: a matrix that is guaranteed to be unitary and of size (2**len(qs), 2**len(qs)).
    Returns:
        A tuple of operations and ancilla qubits allocated.
            Operations: In case the matrix is supported, a list of operations `ops` is returned.
                `ops` acts on `qs` qubits and for which `cirq.unitary(ops)` is equal to `matrix` up
                to certain tolerance. In case the matrix is not supported, it might return NotImplemented to
                reduce the noise in the judge output.
            Ancilla qubits: In case ancilla qubits are allocated a list of ancilla qubits. Otherwise
                an empty list.
        .
    """
    def optimize_circuit(circ):
        ouut = []
        converter = cirq.google.ConvertToSycamoreGates()
        for _ in circ.all_operations():
            ouut.append(converter.convert(_))
        return cirq.google.optimized_for_sycamore(
            cirq.Circuit(ouut), optimizer_type="sycamore"), []

    if np.trace(matrix) == len(matrix):
        return [], []

    if len(matrix) == 2:
        try:
            comparison = matrix == cirq.unitary(cirq.Z)
            if (comparison.all()): return cirq.Z(target_qubits[0]), []

            comparison = matrix == cirq.unitary(cirq.X)
            if (comparison.all()): return cirq.X(target_qubits[0]), []

            comparison = matrix == cirq.unitary(cirq.Y)
            if (comparison.all()): return cirq.Y(target_qubits[0]), []

            comparison = matrix == cirq.unitary(cirq.H)
            if (comparison.all()): return cirq.H.on(target_qubits[0]), []

            comparison = matrix == cirq.unitary(cirq.S)
            if (comparison.all()): return cirq.S(target_qubits[0]), []

            comparison = matrix == cirq.unitary(cirq.T)
            if (comparison.all()): return cirq.T(target_qubits[0]), []

        except [TypeError, ValueError]:
            return NotImplemented, []

    if len(matrix) == 4:
        try:
            comparison = matrix == cirq.unitary(cirq.CNOT)
            if (comparison.all()):
                return optimize_circuit(
                    cirq.Circuit(cirq.CNOT(target_qubits[0],
                                           target_qubits[1])))

            comparison = matrix == cirq.unitary(cirq.XX)
            if (comparison.all()):
                return optimize_circuit(
                    cirq.Circuit(cirq.XX(target_qubits[0], target_qubits[1])))

            comparison = matrix == cirq.unitary(cirq.YY)
            if (comparison.all()):
                return optimize_circuit(
                    cirq.Circuit(cirq.YY(target_qubits[0], target_qubits[1])))

            comparison = matrix == cirq.unitary(cirq.ZZ)
            if (comparison.all()):
                return optimize_circuit(
                    cirq.Circuit(cirq.ZZ(target_qubits[0], target_qubits[1])))

            comparison = matrix == cirq.unitary(cirq.google.SYC)
            if (comparison.all()):
                return optimize_circuit(
                    cirq.Circuit(
                        cirq.google.SYC(target_qubits[0], target_qubits[1])))

        except TypeError:
            return NotImplemented, []

    if len(matrix) == 8:
        try:
            comparison = matrix == cirq.unitary(cirq.CCX)
            if (comparison.all()):
                return optimize_circuit(
                    cirq.Circuit(
                        cirq.CCX(target_qubits[0], target_qubits[1],
                                 target_qubits[2])))

            comparison = matrix == cirq.unitary(cirq.CSWAP)
            if (comparison.all()):
                return optimize_circuit(
                    cirq.Circuit(
                        cirq.CSWAP(target_qubits[0], target_qubits[1],
                                   target_qubits[2])))

            comparison = matrix == cirq.unitary(cirq.CCZ)
            if (comparison.all()):
                return optimize_circuit(
                    cirq.Circuit(
                        cirq.CCZ(target_qubits[0], target_qubits[1],
                                 target_qubits[2])))

            comparison = matrix == cirq.unitary(
                cirq.ControlledGate(cirq.ISWAP**0.5, 1))
            if (comparison.all()):
                return cirq.ControlledGate(cirq.ISWAP**0.5, 1)

        except TypeError:
            return NotImplemented, []

    if len(matrix) == 16:
        try:
            comparison = matrix == cirq.unitary(
                cirq.ControlledGate(cirq.ISWAP**0.5, 2))
            if (comparison.all()):
                return optimize_circuit(
                    cirq.Circuit(
                        cirq.ControlledGate(sub_gate=cirq.ISWAP**0.5).on(
                            target_qubits[2], target_qubits[0],
                            target_qubits[1])))

        except TypeError:
            return NotImplemented, []

    return NotImplemented, []
Пример #2
0
# See the License for the specific language governing permissions and
# limitations under the License.

import pytest

import cirq

from cirq.contrib.paulistring import converted_gate_set


@pytest.mark.parametrize(
    'op,expected_ops',
    (
        lambda q0, q1: (
            (cirq.X(q0), cirq.SingleQubitCliffordGate.X(q0)),
            (cirq.Y(q0), cirq.SingleQubitCliffordGate.Y(q0)),
            (cirq.Z(q0), cirq.SingleQubitCliffordGate.Z(q0)),
            (cirq.X(q0) ** 0.5, cirq.SingleQubitCliffordGate.X_sqrt(q0)),
            (cirq.Y(q0) ** 0.5, cirq.SingleQubitCliffordGate.Y_sqrt(q0)),
            (cirq.Z(q0) ** 0.5, cirq.SingleQubitCliffordGate.Z_sqrt(q0)),
            (cirq.X(q0) ** -0.5, cirq.SingleQubitCliffordGate.X_nsqrt(q0)),
            (cirq.Y(q0) ** -0.5, cirq.SingleQubitCliffordGate.Y_nsqrt(q0)),
            (cirq.Z(q0) ** -0.5, cirq.SingleQubitCliffordGate.Z_nsqrt(q0)),
            (cirq.X(q0) ** 0.25, cirq.PauliStringPhasor(cirq.PauliString([cirq.X.on(q0)])) ** 0.25),
            (cirq.Y(q0) ** 0.25, cirq.PauliStringPhasor(cirq.PauliString([cirq.Y.on(q0)])) ** 0.25),
            (cirq.Z(q0) ** 0.25, cirq.PauliStringPhasor(cirq.PauliString([cirq.Z.on(q0)])) ** 0.25),
            (cirq.X(q0) ** 0, ()),
            (cirq.CZ(q0, q1), cirq.CZ(q0, q1)),
            (cirq.measure(q0, q1, key='key'), cirq.measure(q0, q1, key='key')),
        )
    )(cirq.LineQubit(0), cirq.LineQubit(1)),
Q0 = cirq.GridQubit(2, 4)
Q1 = cirq.GridQubit(2, 5)

X_PROTO = op_proto({
    'xpowgate': {
        'exponent': {
            'float_value': 1.0
        }
    },
    'qubit_constant_index': [0],
})

OPERATIONS = [
    (cirq.X(Q0), X_PROTO),
    (
        cirq.Y(Q0),
        op_proto({
            'ypowgate': {
                'exponent': {
                    'float_value': 1.0
                }
            },
            'qubit_constant_index': [0],
        }),
    ),
    (
        cirq.Z(Q0),
        op_proto({
            'zpowgate': {
                'exponent': {
                    'float_value': 1.0
Пример #4
0
def test_readout_correction():
    a = cirq.NamedQubit('a')
    b = cirq.NamedQubit('b')
    ro_bsa, ro_settings, ro_meas_spec_setting = _get_mock_readout_calibration()

    # observables range from 1 to -1 while bitstrings range from 0 to 1
    assert ro_bsa.mean(ro_settings[0]) == 0.8
    assert ro_bsa.mean(ro_settings[1]) == 0.82
    assert np.isclose(ro_bsa.mean(ro_meas_spec_setting), 0.8 * 0.82, atol=0.05)

    bitstrings = np.array(
        [
            [0, 0],
            [0, 0],
            [0, 0],
            [0, 0],
            [0, 0],
            [0, 0],
            [0, 1],
            [1, 1],
        ],
        dtype=np.uint8,
    )
    chunksizes = np.asarray([len(bitstrings)])
    timestamps = np.asarray([datetime.datetime.now()])
    qubit_to_index = {a: 0, b: 1}
    settings = list(
        cw.observables_to_settings(
            [cirq.X(a) * cirq.Y(b),
             cirq.X(a), cirq.Y(b)], qubits=[a, b]))
    meas_spec = _MeasurementSpec(settings[0], {})

    # First, make one with no readout correction
    bsa1 = cw.BitstringAccumulator(
        meas_spec=meas_spec,
        simul_settings=settings,
        qubit_to_index=qubit_to_index,
        bitstrings=bitstrings,
        chunksizes=chunksizes,
        timestamps=timestamps,
    )

    # [XY: one excitation, X: one excitation, Y: two excitations]
    np.testing.assert_allclose([1 - 1 / 4, 1 - 1 / 4, 1 - 2 / 4], bsa1.means())
    np.testing.assert_allclose([0.75, 0.75, 0.5], bsa1.means())

    # Turn on readout correction
    bsa2 = cw.BitstringAccumulator(
        meas_spec=meas_spec,
        simul_settings=settings,
        qubit_to_index=qubit_to_index,
        bitstrings=bitstrings,
        chunksizes=chunksizes,
        timestamps=timestamps,
        readout_calibration=ro_bsa,
    )

    # Readout correction increases variance
    for setting in settings:
        assert bsa2.variance(setting) > bsa1.variance(setting)

    np.testing.assert_allclose([0.75 / (0.8 * 0.82), 0.75 / 0.8, 0.5 / 0.82],
                               bsa2.means(),
                               atol=0.01)

    # Variance becomes singular when readout error is 50/50
    ro_bsa_50_50, _, _ = _get_mock_readout_calibration(qa_0=50, qa_1=50)
    bsa3 = cw.BitstringAccumulator(
        meas_spec=meas_spec,
        simul_settings=settings,
        qubit_to_index=qubit_to_index,
        bitstrings=bitstrings,
        chunksizes=chunksizes,
        timestamps=timestamps,
        readout_calibration=ro_bsa_50_50,
    )
    with pytest.raises(ZeroDivisionError):
        bsa3.means()

    assert bsa3.variance(settings[1]) == np.inf
Пример #5
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_op_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_op_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_op_proto("HP", ['exponent', 'exponent_scalar', 'global_shift'],
                         ['alpha', 3.1, 0.0], ['0_0'])),
        (cirq.Circuit(cirq.H(q0)),
         _build_op_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_op_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_op_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_op_proto("XP", ['exponent', 'exponent_scalar', 'global_shift'],
                         ['alpha', 3.1, 0.0], ['0_0'])),
        (cirq.Circuit(cirq.X(q0)),
         _build_op_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_op_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_op_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_op_proto("YP", ['exponent', 'exponent_scalar', 'global_shift'],
                         ['alpha', 3.1, 0.0], ['0_0'])),
        (cirq.Circuit(cirq.Y(q0)),
         _build_op_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_op_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_op_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_op_proto("ZP", ['exponent', 'exponent_scalar', 'global_shift'],
                         ['alpha', 3.1, 0.0], ['0_0'])),
        (cirq.Circuit(cirq.Z(q0)),
         _build_op_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_op_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_op_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_op_proto("XXP", ['exponent', 'exponent_scalar', 'global_shift'],
                         ['alpha', 3.1, 0.0], ['0_0', '0_1'])),
        (cirq.Circuit(cirq.XX(q0, q1)),
         _build_op_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_op_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_op_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_op_proto("YYP", ['exponent', 'exponent_scalar', 'global_shift'],
                         ['alpha', 3.1, 0.0], ['0_0', '0_1'])),
        (cirq.Circuit(cirq.YY(q0, q1)),
         _build_op_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_op_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_op_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_op_proto("ZZP", ['exponent', 'exponent_scalar', 'global_shift'],
                         ['alpha', 3.1, 0.0], ['0_0', '0_1'])),
        (cirq.Circuit(cirq.ZZ(q0, q1)),
         _build_op_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_op_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_op_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_op_proto("CZP", ['exponent', 'exponent_scalar', 'global_shift'],
                         ['alpha', 3.1, 0.0], ['0_0', '0_1'])),
        (cirq.Circuit(cirq.CZ(q0, q1)),
         _build_op_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_op_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_op_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_op_proto("CNP", ['exponent', 'exponent_scalar', 'global_shift'],
                         ['alpha', 3.1, 0.0], ['0_0', '0_1'])),
        (cirq.Circuit(cirq.CNOT(q0, q1)),
         _build_op_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_op_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_op_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_op_proto("SP", ['exponent', 'exponent_scalar', 'global_shift'],
                         ['alpha', 3.1, 0.0], ['0_0', '0_1'])),
        (cirq.Circuit(cirq.SWAP(q0, q1)),
         _build_op_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_op_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_op_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_op_proto("ISP", ['exponent', 'exponent_scalar', 'global_shift'],
                         ['alpha', 3.1, 0.0], ['0_0', '0_1'])),
        (cirq.Circuit(cirq.ISWAP(q0, q1)),
         _build_op_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_op_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_op_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_op_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_op_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_op_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_op_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_op_proto("XP", ['exponent', 'exponent_scalar', 'global_shift'],
                         [1.0, 1.0, -0.5], ['0_0'])),
        (cirq.Circuit(cirq.ry(np.pi)(q0)),
         _build_op_proto("YP", ['exponent', 'exponent_scalar', 'global_shift'],
                         [1.0, 1.0, -0.5], ['0_0'])),
        (cirq.Circuit(cirq.rz(np.pi)(q0)),
         _build_op_proto("ZP", ['exponent', 'exponent_scalar', 'global_shift'],
                         [1.0, 1.0, -0.5], ['0_0'])),

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

        # FSimGate
        (cirq.Circuit(cirq.FSimGate(theta=0.1, phi=0.2)(q0, q1)),
         _build_op_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_op_proto("FSIM", ['theta', 'theta_scalar', 'phi', 'phi_scalar'],
                         ['alpha', 2.1, 'beta', 1.3], ['0_0', '0_1'])),
    ]

    return pairs
Пример #6
0
 def generator(depth):
     if depth <= 0:
         yield cirq.CZ(q0, q1), cirq.Y(q0)
     else:
         yield cirq.X(q0), generator(depth - 1)
         yield cirq.Z(q0)
Пример #7
0
def test_pauli_sum_repr():
    q = cirq.LineQubit.range(2)
    pstr1 = cirq.X(q[0]) * cirq.X(q[1])
    pstr2 = cirq.Y(q[0]) * cirq.Y(q[1])
    psum = pstr1 + 2 * pstr2 + 1
    cirq.testing.assert_equivalent_repr(psum)
Пример #8
0
def test_ignore_non_composite():
    q0, q1 = cirq.LineQubit.range(2)
    circuit = cirq.Circuit()
    circuit.append([cirq.X(q0), cirq.Y(q1), cirq.CZ(q0, q1), cirq.Z(q0)])
    assert_optimizes(None, circuit.copy(), circuit)
Пример #9
0
import tensorflow_quantum as tfq

import cirq
import sympy
import numpy as np

#%matplotlib inline
import matplotlib

matplotlib.use('TkAgg')

import matplotlib.pyplot as plt
from cirq.contrib.svg import SVGCircuit

qubit = cirq.GridQubit(0, 0)
my_circuit = cirq.Circuit(cirq.Y(qubit)**sympy.Symbol('alpha'))
SVGCircuit(my_circuit)

pauli_x = cirq.X(qubit)
pauli_x


def my_expectation(op, alpha):
    """Compute ⟨Y(alpha)| `op` | Y(alpha)⟩"""
    params = {'alpha': alpha}
    sim = cirq.Simulator()
    final_state_vector = sim.simulate(my_circuit, params).final_state_vector
    return op.expectation_from_state_vector(final_state_vector, {
        qubit: 0
    }).real
Пример #10
0
def test_scaled_unitary_consistency():
    a, b = cirq.LineQubit.range(2)
    cirq.testing.assert_implements_consistent_protocols(2 * cirq.X(a) *
                                                        cirq.Y(b))
    cirq.testing.assert_implements_consistent_protocols(1j * cirq.X(a) *
                                                        cirq.Y(b))
Пример #11
0
def test_circuit_0():
    qusetta_circuit = [
        "H(0)", "H(1)", "CX(0, 1)", "CX(1, 0)", "CZ(2, 0)", "I(1)",
        "SWAP(0, 3)", "RY(PI)(1)", "X(2)", "S(0)", "Z(2)", "Y(3)",
        "RX(0.4*PI)(0)", "T(2)", "RZ(-0.3*PI)(2)", "CCX(0, 1, 2)"
    ]

    cirq_circuit = cirq.Circuit()
    q = [cirq.LineQubit(i) for i in range(4)]
    cirq_circuit.append(cirq.H(q[0]))
    cirq_circuit.append(cirq.H(q[1]))
    cirq_circuit.append(cirq.CX(q[0], q[1]))
    cirq_circuit.append(cirq.CX(q[1], q[0]))
    cirq_circuit.append(cirq.CZ(q[2], q[0]))
    cirq_circuit.append(cirq.I(q[1]))
    cirq_circuit.append(cirq.SWAP(q[0], q[3]))
    cirq_circuit.append(cirq.ry(pi)(q[1]))
    cirq_circuit.append(cirq.X(q[2]))
    cirq_circuit.append(cirq.S(q[0]))
    cirq_circuit.append(cirq.Z(q[2]))
    cirq_circuit.append(cirq.Y(q[3]))
    cirq_circuit.append(cirq.rx(.4 * pi)(q[0]))
    cirq_circuit.append(cirq.T(q[2]))
    cirq_circuit.append(cirq.rz(-.3 * pi)(q[2]))
    cirq_circuit.append(cirq.CCX(q[0], q[1], q[2]))

    # ibm is weird so we flip all of the qubits here
    qiskit_circuit = qiskit.QuantumCircuit(4)
    qiskit_circuit.h(3 - 0)
    qiskit_circuit.h(3 - 1)
    qiskit_circuit.cx(3 - 0, 3 - 1)
    qiskit_circuit.cx(3 - 1, 3 - 0)
    qiskit_circuit.cz(3 - 2, 3 - 0)
    qiskit_circuit.i(3 - 1)
    qiskit_circuit.swap(3 - 0, 3 - 3)
    qiskit_circuit.ry(pi, 3 - 1)
    qiskit_circuit.x(3 - 2)
    qiskit_circuit.s(3 - 0)
    qiskit_circuit.z(3 - 2)
    qiskit_circuit.y(3 - 3)
    qiskit_circuit.rx(.4 * pi, 3 - 0)
    qiskit_circuit.t(3 - 2)
    qiskit_circuit.rz(-.3 * pi, 3 - 2)
    qiskit_circuit.ccx(3 - 0, 3 - 1, 3 - 2)

    quasar_circuit = quasar.Circuit()
    quasar_circuit.H(0)
    quasar_circuit.H(1)
    quasar_circuit.CX(0, 1)
    quasar_circuit.CX(1, 0)
    quasar_circuit.CZ(2, 0)
    quasar_circuit.I(1)
    quasar_circuit.SWAP(0, 3)
    quasar_circuit.Ry(1, pi)
    quasar_circuit.X(2)
    quasar_circuit.S(0)
    quasar_circuit.Z(2)
    quasar_circuit.Y(3)
    quasar_circuit.Rx(0, .2 * pi)
    quasar_circuit.T(2)
    quasar_circuit.Rz(2, -.15 * pi)
    quasar_circuit.CCX(0, 1, 2)

    # tests
    all_tests(qusetta_circuit, cirq_circuit, qiskit_circuit, quasar_circuit)
Пример #12
0
    def test_get_gradient_circuits(self):
        """Test that the correct objects are returned."""

        # Minimal linear combination.
        input_weights = [1.0, -0.5]
        input_perturbations = [1.0, -1.5]
        diff = linear_combination.LinearCombination(input_weights,
                                                    input_perturbations)

        # Circuits to differentiate.
        symbols = [sympy.Symbol("s0"), sympy.Symbol("s1")]
        q0 = cirq.GridQubit(0, 0)
        q1 = cirq.GridQubit(1, 2)
        input_programs = util.convert_to_tensor([
            cirq.Circuit(cirq.X(q0)**symbols[0],
                         cirq.ry(symbols[1])(q1)),
            cirq.Circuit(cirq.rx(symbols[0])(q0),
                         cirq.Y(q1)**symbols[1]),
        ])
        input_symbol_names = tf.constant([str(s) for s in symbols])
        input_symbol_values = tf.constant([[1.5, -2.7], [-0.3, 0.9]])

        # For each program in the input batch: LinearCombination creates a copy
        # of that program for each symbol in the batch; then for each symbol,
        # the program is copied for each non-zero perturbation; finally, a
        # single copy is added for the zero perturbation (no zero pert here).
        expected_batch_programs = tf.stack([[input_programs[0]] * 4,
                                            [input_programs[1]] * 4])
        expected_new_symbol_names = input_symbol_names

        # For each program in the input batch: first, the input symbol_values
        # for the program are tiled to the number of copies in the output.
        tiled_symbol_values = tf.stack([[input_symbol_values[0]] * 4,
                                        [input_symbol_values[1]] * 4])
        # Then we create the tensor of perturbations to apply to these symbol
        # values: for each symbol we tile out the non-zero perturbations at that
        # symbol's index, keeping all the other symbol perturbations at zero.
        # Perturbations are the same for each program.
        single_program_perturbations = tf.stack([[input_perturbations[0], 0.0],
                                                 [input_perturbations[1], 0.0],
                                                 [0.0, input_perturbations[0]],
                                                 [0.0,
                                                  input_perturbations[1]]])
        tiled_perturbations = tf.stack(
            [single_program_perturbations, single_program_perturbations])
        # Finally we add the perturbations to the original symbol values.
        expected_batch_symbol_values = tiled_symbol_values + tiled_perturbations

        # The map for LinearCombination is the same for every program.
        individual_batch_mapper = tf.stack(
            [[input_weights[0], input_weights[1], 0.0, 0.0],
             [0.0, 0.0, input_weights[0], input_weights[1]]])
        expected_batch_mapper = tf.stack(
            [individual_batch_mapper, individual_batch_mapper])

        (test_batch_programs, test_new_symbol_names, test_batch_symbol_values,
         test_batch_mapper) = diff.get_gradient_circuits(
             input_programs, input_symbol_names, input_symbol_values)
        self.assertAllEqual(expected_batch_programs, test_batch_programs)
        self.assertAllEqual(expected_new_symbol_names, test_new_symbol_names)
        self.assertAllClose(expected_batch_symbol_values,
                            test_batch_symbol_values,
                            atol=1e-6)
        self.assertAllClose(expected_batch_mapper,
                            test_batch_mapper,
                            atol=1e-6)
def test_fixed_single_qubit_rotations():
    a, b, c, d = cirq.LineQubit.range(4)

    assert_url_to_circuit_returns(
        '{"cols":[["H","X","Y","Z"]]}', cirq.Circuit(cirq.H(a), cirq.X(b), cirq.Y(c), cirq.Z(d))
    )

    assert_url_to_circuit_returns(
        '{"cols":[["X^½","X^⅓","X^¼"],'
        '["X^⅛","X^⅟₁₆","X^⅟₃₂"],'
        '["X^-½","X^-⅓","X^-¼"],'
        '["X^-⅛","X^-⅟₁₆","X^-⅟₃₂"]]}',
        cirq.Circuit(
            cirq.X(a) ** (1 / 2),
            cirq.X(b) ** (1 / 3),
            cirq.X(c) ** (1 / 4),
            cirq.X(a) ** (1 / 8),
            cirq.X(b) ** (1 / 16),
            cirq.X(c) ** (1 / 32),
            cirq.X(a) ** (-1 / 2),
            cirq.X(b) ** (-1 / 3),
            cirq.X(c) ** (-1 / 4),
            cirq.X(a) ** (-1 / 8),
            cirq.X(b) ** (-1 / 16),
            cirq.X(c) ** (-1 / 32),
        ),
    )

    assert_url_to_circuit_returns(
        '{"cols":[["Y^½","Y^⅓","Y^¼"],'
        '["Y^⅛","Y^⅟₁₆","Y^⅟₃₂"],'
        '["Y^-½","Y^-⅓","Y^-¼"],'
        '["Y^-⅛","Y^-⅟₁₆","Y^-⅟₃₂"]]}',
        cirq.Circuit(
            cirq.Y(a) ** (1 / 2),
            cirq.Y(b) ** (1 / 3),
            cirq.Y(c) ** (1 / 4),
            cirq.Y(a) ** (1 / 8),
            cirq.Y(b) ** (1 / 16),
            cirq.Y(c) ** (1 / 32),
            cirq.Y(a) ** (-1 / 2),
            cirq.Y(b) ** (-1 / 3),
            cirq.Y(c) ** (-1 / 4),
            cirq.Y(a) ** (-1 / 8),
            cirq.Y(b) ** (-1 / 16),
            cirq.Y(c) ** (-1 / 32),
        ),
    )

    assert_url_to_circuit_returns(
        '{"cols":[["Z^½","Z^⅓","Z^¼"],'
        '["Z^⅛","Z^⅟₁₆","Z^⅟₃₂"],'
        '["Z^⅟₆₄","Z^⅟₁₂₈"],'
        '["Z^-½","Z^-⅓","Z^-¼"],'
        '["Z^-⅛","Z^-⅟₁₆"]]}',
        cirq.Circuit(
            cirq.Z(a) ** (1 / 2),
            cirq.Z(b) ** (1 / 3),
            cirq.Z(c) ** (1 / 4),
            cirq.Z(a) ** (1 / 8),
            cirq.Z(b) ** (1 / 16),
            cirq.Z(c) ** (1 / 32),
            cirq.Z(a) ** (1 / 64),
            cirq.Z(b) ** (1 / 128),
            cirq.Moment([cirq.Z(a) ** (-1 / 2), cirq.Z(b) ** (-1 / 3), cirq.Z(c) ** (-1 / 4)]),
            cirq.Z(a) ** (-1 / 8),
            cirq.Z(b) ** (-1 / 16),
        ),
    )
Пример #14
0
    def test_get_gradient_circuits(self):
        """Test that the correct objects are returned."""

        diff = parameter_shift.ParameterShift()

        # Circuits to differentiate.
        symbols = [sympy.Symbol("s0"), sympy.Symbol("s1")]
        q0 = cirq.GridQubit(0, 0)
        q1 = cirq.GridQubit(1, 2)
        input_programs = util.convert_to_tensor([
            cirq.Circuit(
                cirq.X(q0)**symbols[0],
                cirq.Y(q0)**symbols[0],
                cirq.ry(symbols[1])(q1)),
            cirq.Circuit(cirq.Y(q1)**symbols[1]),
        ])
        input_symbol_names = tf.constant([str(s) for s in symbols])
        input_symbol_values = tf.constant([[1.5, -2.7], [-0.3, 0.9]])

        # First, for each symbol `s`, check how many times `s` appears in each
        # program `p`, `n_ps`. Let `n_param_gates` be the maximum of `n_ps` over
        # all symbols and programs. Then, the shape of `batch_programs` will be
        # [n_programs, n_symbols * n_param_gates * n_shifts], where `n_shifts`
        # is 2 because we decompose into gates with 2 eigenvalues. For row index
        # `p` we have for column indices between `i * n_param_gates * n_shifts`
        # and `(i + 1) * n_param_gates * n_shifts`, the first `n_pi * 2`
        # programs are parameter shifted versions of `input_programs[p]` and the
        # remaining programs are empty.
        # Here, `n_param_gates` is 2.
        impurity_symbol_name = "_impurity_for_param_shift"
        impurity_symbol = sympy.Symbol(impurity_symbol_name)
        expected_batch_programs_0 = util.convert_to_tensor([
            cirq.Circuit(
                cirq.X(q0)**impurity_symbol,
                cirq.Y(q0)**symbols[0],
                cirq.ry(symbols[1])(q1)),
            cirq.Circuit(
                cirq.X(q0)**impurity_symbol,
                cirq.Y(q0)**symbols[0],
                cirq.ry(symbols[1])(q1)),
            cirq.Circuit(
                cirq.X(q0)**symbols[0],
                cirq.Y(q0)**impurity_symbol,
                cirq.ry(symbols[1])(q1)),
            cirq.Circuit(
                cirq.X(q0)**symbols[0],
                cirq.Y(q0)**impurity_symbol,
                cirq.ry(symbols[1])(q1)),
            cirq.Circuit(
                cirq.X(q0)**symbols[0],
                cirq.Y(q0)**symbols[0],
                cirq.ry(impurity_symbol)(q1)),
            cirq.Circuit(
                cirq.X(q0)**symbols[0],
                cirq.Y(q0)**symbols[0],
                cirq.ry(impurity_symbol)(q1)),
            cirq.Circuit(),
            cirq.Circuit()
        ])
        expected_batch_programs_1 = util.convert_to_tensor([
            cirq.Circuit(),
            cirq.Circuit(),
            cirq.Circuit(),
            cirq.Circuit(),
            cirq.Circuit(cirq.Y(q1)**impurity_symbol),
            cirq.Circuit(cirq.Y(q1)**impurity_symbol),
            cirq.Circuit(),
            cirq.Circuit()
        ])
        expected_batch_programs = tf.stack(
            [expected_batch_programs_0, expected_batch_programs_1])

        # The new symbols are the old ones, with an extra used for shifting.
        expected_new_symbol_names = tf.concat(
            [input_symbol_names,
             tf.constant([impurity_symbol_name])], 0)

        # The batch symbol values are the input symbol values, tiled and with
        # shifted values appended. Locations that have empty programs should
        # also have zero for the shift.
        # The shifted values are the original value plus 1/2 divided by the
        # `exponent_scalar` of the gate.
        expected_batch_symbol_values = tf.constant(
            [[[1.5, -2.7, 1.5 + 0.5], [1.5, -2.7, 1.5 - 0.5],
              [1.5, -2.7, 1.5 + 0.5], [1.5, -2.7, 1.5 - 0.5],
              [1.5, -2.7, -2.7 + np.pi / 2], [1.5, -2.7, -2.7 - np.pi / 2],
              [1.5, -2.7, -2.7], [1.5, -2.7, -2.7]],
             [[-0.3, 0.9, -0.3], [-0.3, 0.9, -0.3], [-0.3, 0.9, -0.3],
              [-0.3, 0.9, -0.3], [-0.3, 0.9, 0.9 + 0.5],
              [-0.3, 0.9, 0.9 - 0.5], [-0.3, 0.9, 0.9], [-0.3, 0.9, 0.9]]])

        # Empty program locations are given zero weight.
        expected_batch_weights = tf.constant(
            [[[np.pi / 2, -np.pi / 2, np.pi / 2, -np.pi / 2],
              [0.5, -0.5, 0.0, 0.0]],
             [[0.0, 0.0, 0.0, 0.0], [np.pi / 2, -np.pi / 2, 0.0, 0.0]]])

        expected_batch_mapper = tf.constant([[[0, 1, 2, 3], [4, 5, 6, 7]],
                                             [[0, 1, 2, 3], [4, 5, 6, 7]]])

        (test_batch_programs, test_new_symbol_names, test_batch_symbol_values,
         test_batch_weights, test_batch_mapper) = diff.get_gradient_circuits(
             input_programs, input_symbol_names, input_symbol_values)
        for i in range(tf.shape(input_programs)[0]):
            self.assertAllEqual(util.from_tensor(expected_batch_programs[i]),
                                util.from_tensor(test_batch_programs[i]))
        self.assertAllEqual(expected_new_symbol_names, test_new_symbol_names)
        self.assertAllClose(expected_batch_symbol_values,
                            test_batch_symbol_values,
                            atol=1e-5)
        self.assertAllClose(expected_batch_weights,
                            test_batch_weights,
                            atol=1e-5)
        self.assertAllEqual(expected_batch_mapper, test_batch_mapper)
Пример #15
0
def test_controls():
    a, b = cirq.LineQubit.range(2)

    assert_url_to_circuit_returns(
        '{"cols":[["•","X"]]}',
        cirq.Circuit(cirq.X(b).controlled_by(a), ),
    )
    assert_url_to_circuit_returns(
        '{"cols":[["◦","X"]]}',
        cirq.Circuit(
            cirq.X(a),
            cirq.X(b).controlled_by(a),
            cirq.X(a),
        ),
    )

    assert_url_to_circuit_returns(
        '{"cols":[["⊕","X"]]}',
        cirq.Circuit(
            cirq.Y(a)**0.5,
            cirq.X(b).controlled_by(a),
            cirq.Y(a)**-0.5,
        ),
        output_amplitudes_from_quirk=[
            {
                "r": 0.5,
                "i": 0
            },
            {
                "r": -0.5,
                "i": 0
            },
            {
                "r": 0.5,
                "i": 0
            },
            {
                "r": 0.5,
                "i": 0
            },
        ],
    )
    assert_url_to_circuit_returns(
        '{"cols":[["⊖","X"]]}',
        cirq.Circuit(
            cirq.Y(a)**-0.5,
            cirq.X(b).controlled_by(a),
            cirq.Y(a)**+0.5,
        ),
        output_amplitudes_from_quirk=[
            {
                "r": 0.5,
                "i": 0
            },
            {
                "r": 0.5,
                "i": 0
            },
            {
                "r": 0.5,
                "i": 0
            },
            {
                "r": -0.5,
                "i": 0
            },
        ],
    )

    assert_url_to_circuit_returns(
        '{"cols":[["⊗","X"]]}',
        cirq.Circuit(
            cirq.X(a)**-0.5,
            cirq.X(b).controlled_by(a),
            cirq.X(a)**+0.5,
        ),
        output_amplitudes_from_quirk=[
            {
                "r": 0.5,
                "i": 0
            },
            {
                "r": 0,
                "i": -0.5
            },
            {
                "r": 0.5,
                "i": 0
            },
            {
                "r": 0,
                "i": 0.5
            },
        ],
    )
    assert_url_to_circuit_returns(
        '{"cols":[["(/)","X"]]}',
        cirq.Circuit(
            cirq.X(a)**+0.5,
            cirq.X(b).controlled_by(a),
            cirq.X(a)**-0.5,
        ),
        output_amplitudes_from_quirk=[
            {
                "r": 0.5,
                "i": 0
            },
            {
                "r": 0,
                "i": 0.5
            },
            {
                "r": 0.5,
                "i": 0
            },
            {
                "r": 0,
                "i": -0.5
            },
        ],
    )

    qs = cirq.LineQubit.range(8)
    assert_url_to_circuit_returns(
        '{"cols":[["X","•","◦","⊕","⊖","⊗","(/)","Z"]]}',
        cirq.Circuit(
            cirq.X(qs[2]),
            cirq.Y(qs[3])**0.5,
            cirq.Y(qs[4])**-0.5,
            cirq.X(qs[5])**-0.5,
            cirq.X(qs[6])**0.5,
            cirq.X(qs[0]).controlled_by(*qs[1:7]),
            cirq.Z(qs[7]).controlled_by(*qs[1:7]),
            cirq.X(qs[6])**-0.5,
            cirq.X(qs[5])**0.5,
            cirq.Y(qs[4])**0.5,
            cirq.Y(qs[3])**-0.5,
            cirq.X(qs[2]),
        ),
    )
Пример #16
0
from google.protobuf.text_format import Merge

import cirq
import cirq_google
import cirq_google as cg
from cirq_google.api import v1, v2
from cirq_google.engine import util
from cirq_google.cloud import quantum
from cirq_google.engine.engine import EngineContext

_CIRCUIT = cirq.Circuit(
    cirq.X(cirq.GridQubit(5, 2))**0.5,
    cirq.measure(cirq.GridQubit(5, 2), key='result'))

_CIRCUIT2 = cirq.FrozenCircuit(
    cirq.Y(cirq.GridQubit(5, 2))**0.5,
    cirq.measure(cirq.GridQubit(5, 2), key='result'))


def _to_timestamp(json_string):
    timestamp_proto = timestamp_pb2.Timestamp()
    timestamp_proto.FromJsonString(json_string)
    return timestamp_proto


_A_RESULT = util.pack_any(
    Merge(
        """
sweep_results: [{
        repetitions: 1,
        measurement_keys: [{
Пример #17
0
def test_immutable_moment():
    with pytest.raises(AttributeError):
        q1, q2 = cirq.LineQubit.range(2)
        circuit = cirq.Circuit(cirq.X(q1))
        moment = circuit.moments[0]
        moment.operations += (cirq.Y(q2),)
Пример #18
0
 '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'),
     cirq.MeasurementGate(num_qubits=3,
                          key='z',
                          invert_mask=(True, False, True)),
     cirq.MeasurementGate(num_qubits=3,
                          key='z',
                          invert_mask=(True, False),
                          qid_shape=(1, 2, 3)),
 ],
 'Moment': [
     cirq.Moment(operations=[cirq.X(Q0), cirq.Y(Q1),
                             cirq.Z(Q2)]),
 ],
 'NO_NOISE':
 cirq.NO_NOISE,
 'NamedQubit':
 cirq.NamedQubit('hi mom'),
 'PauliString': [
     cirq.PauliString({
         Q0: cirq.X,
         Q1: cirq.Y,
         Q2: cirq.Z
     }),
     cirq.X(Q0) * cirq.Y(Q1) * 123
 ],
 'PhaseDampingChannel':
Пример #19
0
    for i, gate in enumerate(gates):
        a += gate
        b -= gate

        prefix = gates[:i + 1]
        expected_a = cirq.LinearCombinationOfGates(collections.Counter(prefix))
        expected_b = -expected_a

        assert_linear_combinations_are_equal(a, expected_a)
        assert_linear_combinations_are_equal(b, expected_b)


@pytest.mark.parametrize('op', (
    cirq.X(q0),
    cirq.Y(q1),
    cirq.XX(q0, q1),
    cirq.CZ(q0, q1),
    cirq.FREDKIN(q0, q1, q2),
    cirq.ControlledOperation((q0, q1), cirq.H(q2)),
    cirq.ParallelGateOperation(cirq.X, (q0, q1, q2)),
    cirq.PauliString({
        q0: cirq.X,
        q1: cirq.Y,
        q2: cirq.Z
    }),
))
def test_empty_linear_combination_of_operations_accepts_all_operations(op):
    combination = cirq.LinearCombinationOfOperations({})
    combination[op] = -0.5j
    assert len(combination) == 1
Пример #20
0
 def cirq_op(self, x):
     return cirq.Y(x)
Пример #21
0
def two_qubit_ops(
        target_qubits: List[cirq.GridQubit],
        matrix: np.ndarray) -> Tuple[cirq.OP_TREE, List[cirq.GridQubit]]:
    a = target_qubits[0]
    b = target_qubits[1]

    #return [cirq.CNOT(a,b)],[]

    circs = []
    circs2 = []
    #circs.append(  ([cirq.CNOT(a,b)],[])     )#For CNOT
    #circs.append(  ([  cirq.Z(a)**(1.5),cirq.X(b)**(0.5),cirq.Z(b)**(0.5),cirq.ISWAP(a,b)**0.5,cirq.ISWAP(a,b)**0.5,cirq.X(a)**(0.5),cirq.ISWAP(a,b)**0.5,cirq.ISWAP(a,b)**0.5,cirq.Z(b) **0.5 ] , [])   )
    circs2.append(([cirq.CNOT(a, b)], []))  #For CNOT
    circs.append(([cirq.CNOT(a, b)], []))  #For CNOT

    circs.append(([cirq.CNOT(b, a), cirq.X(b)], []))
    circs2.append(([cirq.CNOT(b, a), cirq.X(b)], []))

    circs.append(([cirq.google.SYC(a, b)], []))
    circs2.append(([cirq.google.SYC(a, b)], []))

    circs.append(([cirq.google.SYC(b, a)], []))
    circs2.append(([cirq.google.SYC(b, a)], []))

    circs.append(([cirq.X(a), cirq.X(b)], []))
    circs2.append(([cirq.X(a), cirq.X(b)], []))

    circs.append(([cirq.Y(a), cirq.Y(b)], []))
    circs2.append(([cirq.Y(a), cirq.Y(b)], []))

    circs.append(([cirq.Z(a), cirq.Z(b)], []))
    circs2.append(([cirq.Z(a), cirq.Z(b)], []))

    circs.append(([], []))
    circs2.append(([], []))

    first = True
    for i, circ in enumerate(circs):
        list, ancilla = circs2[i]
        unit = cirq.unitary(cirq.Circuit(list))
        if first:
            #print(matrix)
            first = False
        if np.allclose(matrix, unit, atol=0.00001):
            return circ
    #rint (np.array_str(matrix))
    '''
    for gate in [cirq.X,cirq.Y,cirq.Z]:
        if np.allclose(matrix, (cirq.unitary(gate)),atol=0.00001) :
            return [gate(a)],[]
    for gate in [cirq.H]:#,cirq.Y,cirq.Z]:
        if np.allclose(matrix, (cirq.unitary(gate)),atol=0.00001) :
            
            
            return [cirq.Z(a),cirq.Y(a)**0.5],[]
    for gate in [cirq.S]:#,cirq.Y,cirq.Z]:
        if np.allclose(matrix, (cirq.unitary(gate)),atol=0.00001) :
            
            
            return [cirq.Z(a)**0.5],[]
    for gate in [cirq.T]:#,cirq.Y,cirq.Z]:
        if np.allclose(matrix, (cirq.unitary(gate)),atol=0.00001) :
            
            
            return [cirq.Z(a)**0.25],[]    
    '''
    return [], []
Пример #22
0
def test_tagged_operation_forwards_protocols():
    """The results of all protocols applied to an operation with a tag should
    be equivalent to the result without tags.
    """
    q1 = cirq.GridQubit(1, 1)
    q2 = cirq.GridQubit(1, 2)
    h = cirq.H(q1)
    tag = 'tag1'
    tagged_h = cirq.H(q1).with_tags(tag)

    np.testing.assert_equal(cirq.unitary(tagged_h), cirq.unitary(h))
    assert cirq.has_unitary(tagged_h)
    assert cirq.decompose(tagged_h) == cirq.decompose(h)
    assert cirq.pauli_expansion(tagged_h) == cirq.pauli_expansion(h)
    assert cirq.equal_up_to_global_phase(h, tagged_h)
    assert np.isclose(cirq.kraus(h), cirq.kraus(tagged_h)).all()

    assert cirq.measurement_key(cirq.measure(
        q1, key='blah').with_tags(tag)) == 'blah'

    parameterized_op = cirq.XPowGate(
        exponent=sympy.Symbol('t'))(q1).with_tags(tag)
    assert cirq.is_parameterized(parameterized_op)
    resolver = cirq.study.ParamResolver({'t': 0.25})
    assert cirq.resolve_parameters(
        parameterized_op,
        resolver) == cirq.XPowGate(exponent=0.25)(q1).with_tags(tag)
    assert cirq.resolve_parameters_once(
        parameterized_op,
        resolver) == cirq.XPowGate(exponent=0.25)(q1).with_tags(tag)

    y = cirq.Y(q1)
    tagged_y = cirq.Y(q1).with_tags(tag)
    assert tagged_y**0.5 == cirq.YPowGate(exponent=0.5)(q1)
    assert tagged_y * 2 == (y * 2)
    assert 3 * tagged_y == (3 * y)
    assert cirq.phase_by(y, 0.125, 0) == cirq.phase_by(tagged_y, 0.125, 0)
    controlled_y = tagged_y.controlled_by(q2)
    assert controlled_y.qubits == (
        q2,
        q1,
    )
    assert isinstance(controlled_y, cirq.Operation)
    assert not isinstance(controlled_y, cirq.TaggedOperation)

    clifford_x = cirq.SingleQubitCliffordGate.X(q1)
    tagged_x = cirq.SingleQubitCliffordGate.X(q1).with_tags(tag)
    assert cirq.commutes(clifford_x, clifford_x)
    assert cirq.commutes(tagged_x, clifford_x)
    assert cirq.commutes(clifford_x, tagged_x)
    assert cirq.commutes(tagged_x, tagged_x)

    assert cirq.trace_distance_bound(y**0.001) == cirq.trace_distance_bound(
        (y**0.001).with_tags(tag))

    flip = cirq.bit_flip(0.5)(q1)
    tagged_flip = cirq.bit_flip(0.5)(q1).with_tags(tag)
    assert cirq.has_mixture(tagged_flip)
    assert cirq.has_kraus(tagged_flip)

    flip_mixture = cirq.mixture(flip)
    tagged_mixture = cirq.mixture(tagged_flip)
    assert len(tagged_mixture) == 2
    assert len(tagged_mixture[0]) == 2
    assert len(tagged_mixture[1]) == 2
    assert tagged_mixture[0][0] == flip_mixture[0][0]
    assert np.isclose(tagged_mixture[0][1], flip_mixture[0][1]).all()
    assert tagged_mixture[1][0] == flip_mixture[1][0]
    assert np.isclose(tagged_mixture[1][1], flip_mixture[1][1]).all()

    qubit_map = {q1: 'q1'}
    qasm_args = cirq.QasmArgs(qubit_id_map=qubit_map)
    assert cirq.qasm(h, args=qasm_args) == cirq.qasm(tagged_h, args=qasm_args)

    cirq.testing.assert_has_consistent_apply_unitary(tagged_h)
    )
    results = cirq.read_json(f'{tmpdir}/obs.json')
    (result, ) = results  # one group
    assert result.n_repetitions == 1_000
    assert result.means() == [1.0]


Q = cirq.NamedQubit('q')


@pytest.mark.parametrize(
    ['circuit', 'observable'],
    [
        (cirq.Circuit(cirq.X(Q)**0.2), cirq.Z(Q)),
        (cirq.Circuit(cirq.X(Q)**-0.5,
                      cirq.Z(Q)**0.2), cirq.Y(Q)),
        (cirq.Circuit(cirq.Y(Q)**0.5,
                      cirq.Z(Q)**0.2), cirq.X(Q)),
    ],
)
def test_XYZ_point8(circuit, observable):
    # each circuit, observable combination should result in the observable value of 0.8
    df = measure_observables_df(
        circuit,
        [observable],
        cirq.Simulator(seed=52),
        stopping_criteria=VarianceStoppingCriteria(1e-3**2),
    )
    assert len(df) == 1, 'one observable'
    mean = df.loc[0]['mean']
    np.testing.assert_allclose(0.8, mean, atol=1e-2)
 def default_decompose(self, qubits):
     yield cirq.X(qubits[0])
     yield cirq.Y(qubits[0])**0.5
Пример #25
0
 def _decompose_(self):
     yield cirq.X(cirq.LineQubit(0))
     yield cirq.Y(cirq.LineQubit(1))
Пример #26
0
 def _decompose_(self, qubits):
     q0, q1 = qubits
     yield cirq.X(q0)
     yield cirq.Y(q1)**0.5
     yield cirq.H(q0)
Пример #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.IdentityGate(4).on(q0, q1, q2, q3),
            ]),
            cirq.Moment([
                cirq.CCZPowGate(exponent=0.7, global_shift=0.3)(q2, q0, q1),
            ]),
            cirq.Moment([
                cirq.CCXPowGate(exponent=0.4, global_shift=0.6)(
                    q3, q1, q0).controlled_by(q2, control_values=[0]),
            ]),
            cirq.Moment([
                cirq.rx(0.3)(q0),
                cirq.ry(0.5)(q1),
                cirq.rz(0.7)(q2),
                cirq.rx(0.9)(q3),
            ]),
            cirq.Moment([
                cirq.TwoQubitDiagonalGate([0.1, 0.2, 0.3, 0.4])(q0, q1),
            ]),
            cirq.Moment([
                cirq.ThreeQubitDiagonalGate(
                    [0.5, 0.6, 0.7, 0.8, 0.9, 1, 1.2, 1.3])(q1, q2, q3),
            ]),
            cirq.Moment([
                cirq.CSwapGate()(q0, q3, q1),
            ]),
            cirq.Moment([
                cirq.rz(0.6)(q0),
                cirq.rx(0.7)(q1),
                cirq.ry(0.8)(q2),
                cirq.rz(0.9)(q3),
            ]),
            cirq.Moment([
                cirq.TOFFOLI(q3, q2, q0),
            ]),
            cirq.Moment([
                cirq.FREDKIN(q1, q3, q2),
            ]),
            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())
Пример #28
0
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import pytest

import cirq

from cirq.contrib.paulistring import converted_gate_set


@pytest.mark.parametrize(
    'op,expected_ops',
    (lambda q0, q1: (
        (cirq.X(q0), cirq.SingleQubitCliffordGate.X(q0)),
        (cirq.Y(q0), cirq.SingleQubitCliffordGate.Y(q0)),
        (cirq.Z(q0), cirq.SingleQubitCliffordGate.Z(q0)),
        (cirq.X(q0)**0.5, cirq.SingleQubitCliffordGate.X_sqrt(q0)),
        (cirq.Y(q0)**0.5, cirq.SingleQubitCliffordGate.Y_sqrt(q0)),
        (cirq.Z(q0)**0.5, cirq.SingleQubitCliffordGate.Z_sqrt(q0)),
        (cirq.X(q0)**-0.5, cirq.SingleQubitCliffordGate.X_nsqrt(q0)),
        (cirq.Y(q0)**-0.5, cirq.SingleQubitCliffordGate.Y_nsqrt(q0)),
        (cirq.Z(q0)**-0.5, cirq.SingleQubitCliffordGate.Z_nsqrt(q0)),
        (cirq.X(q0)**0.25,
         cirq.PauliStringPhasor(cirq.PauliString([cirq.X.on(q0)]))**0.25),
        (cirq.Y(q0)**0.25,
         cirq.PauliStringPhasor(cirq.PauliString([cirq.Y.on(q0)]))**0.25),
        (cirq.Z(q0)**0.25,
         cirq.PauliStringPhasor(cirq.PauliString([cirq.Z.on(q0)]))**0.25),
        (cirq.X(q0)**0, ()),
        (cirq.CZ(q0, q1), cirq.CZ(q0, q1)),
Пример #29
0
 def _decompose_(self, qubits):
     yield cirq.X(qubits[0])
     yield cirq.Y(qubits[0])**0.5
Пример #30
0
def _all_operations(q0, q1, q2, q3, q4, include_measurements=True):
    class DummyOperation(cirq.Operation):
        qubits = (q0,)
        with_qubits = NotImplemented

        def _qasm_(self, args: cirq.QasmArgs) -> str:
            return '// Dummy operation\n'

        def _decompose_(self):
            # Only used by test_output_unitary_same_as_qiskit
            return ()  # coverage: ignore

    class DummyCompositeOperation(cirq.Operation):
        qubits = (q0,)
        with_qubits = NotImplemented

        def _decompose_(self):
            return cirq.X(self.qubits[0])

        def __repr__(self):
            return 'DummyCompositeOperation()'

    return (
        cirq.Z(q0),
        cirq.Z(q0) ** 0.625,
        cirq.Y(q0),
        cirq.Y(q0) ** 0.375,
        cirq.X(q0),
        cirq.X(q0) ** 0.875,
        cirq.H(q1),
        cirq.CZ(q0, q1),
        cirq.CZ(q0, q1) ** 0.25,  # Requires 2-qubit decomposition
        cirq.CNOT(q0, q1),
        cirq.CNOT(q0, q1) ** 0.5,  # Requires 2-qubit decomposition
        cirq.SWAP(q0, q1),
        cirq.SWAP(q0, q1) ** 0.75,  # Requires 2-qubit decomposition
        cirq.CCZ(q0, q1, q2),
        cirq.CCX(q0, q1, q2),
        cirq.CCZ(q0, q1, q2) ** 0.5,
        cirq.CCX(q0, q1, q2) ** 0.5,
        cirq.CSWAP(q0, q1, q2),
        cirq.IdentityGate(1).on(q0),
        cirq.IdentityGate(3).on(q0, q1, q2),
        cirq.ISWAP(q2, q0),  # Requires 2-qubit decomposition
        cirq.PhasedXPowGate(phase_exponent=0.111, exponent=0.25).on(q1),
        cirq.PhasedXPowGate(phase_exponent=0.333, exponent=0.5).on(q1),
        cirq.PhasedXPowGate(phase_exponent=0.777, exponent=-0.5).on(q1),
        (
            cirq.measure(q0, key='xX'),
            cirq.measure(q2, key='x_a'),
            cirq.measure(q1, key='x?'),
            cirq.measure(q3, key='X'),
            cirq.measure(q4, key='_x'),
            cirq.measure(q2, key='x_a'),
            cirq.measure(q1, q2, q3, key='multi', invert_mask=(False, True)),
        )
        if include_measurements
        else (),
        DummyOperation(),
        DummyCompositeOperation(),
    )