Exemple #1
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)
Exemple #2
0
def test_parameterizable():
    a = sympy.Symbol('a')
    cy = cirq.ControlledGate(cirq.Y)
    cya = cirq.ControlledGate(cirq.YPowGate(exponent=a))
    scya = cirq.ControlledGate(cirq.YPowGate(exponent=a), [q])
    assert cirq.is_parameterized(cya)
    assert cirq.is_parameterized(scya)
    assert not cirq.is_parameterized(cy)
    assert cirq.resolve_parameters(cya, cirq.ParamResolver({'a': 1})) == cy
Exemple #3
0
def standard_gatenames_cirq_conversions():
    """
    A dictionary converting the gates with standard names to the cirq names for these gates.

    See :function:`standard_gatename_unitaries`.

    By default, an idle operation will not be converted to a gate.
    If you want an idle to be converted to a `cirq.WaitGate`, you will have
    to modify this dictionary.

    Note that throughout pyGSTi the standard gatenames (e.g., 'Gh' for Hadamard)
    are not enforced to correspond to the expected unitaries. So, if the user
    as, say, defined 'Gh' to be something other than the Hadamard gate this
    conversion dictionary will be incorrect.

    Currently there are some standard gate names with no conversion to cirq.

    TODO: add Clifford gates with
    https://cirq.readthedocs.io/en/latest/generated/cirq.SingleQubitCliffordGate.html

    Returns
    -------
    dict mapping strings to string
    """
    try:
        import cirq
    except ImportError:
        raise ImportError(
            "Cirq is required for this operation, and it does not appear to be installed."
        )

    std_gatenames_to_cirq = {}
    std_gatenames_to_cirq['Gi'] = None
    std_gatenames_to_cirq['Gxpi2'] = cirq.XPowGate(exponent=1 / 2)
    std_gatenames_to_cirq['Gxmpi2'] = cirq.XPowGate(exponent=-1 / 2)
    std_gatenames_to_cirq['Gxpi'] = cirq.X
    std_gatenames_to_cirq['Gzpi2'] = cirq.ZPowGate(exponent=1 / 2)
    std_gatenames_to_cirq['Gzmpi2'] = cirq.ZPowGate(exponent=-1 / 2)
    std_gatenames_to_cirq['Gzpi'] = cirq.Z
    std_gatenames_to_cirq['Gypi2'] = cirq.YPowGate(exponent=1 / 2)
    std_gatenames_to_cirq['Gympi2'] = cirq.YPowGate(exponent=-1 / 2)
    std_gatenames_to_cirq['Gypi'] = cirq.Y
    std_gatenames_to_cirq['Gp'] = std_gatenames_to_cirq['Gzpi2']
    std_gatenames_to_cirq['Gpdag'] = std_gatenames_to_cirq['Gzmpi2']
    std_gatenames_to_cirq['Gh'] = cirq.H
    std_gatenames_to_cirq['Gt'] = cirq.T
    std_gatenames_to_cirq['Gtdag'] = cirq.T**-1
    std_gatenames_to_cirq['Gcphase'] = cirq.CZ
    std_gatenames_to_cirq['Gcnot'] = cirq.CNOT
    std_gatenames_to_cirq['Gswap'] = cirq.SWAP

    return std_gatenames_to_cirq
Exemple #4
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 test_tf_gate_wrapper_tensor_inputs():
    # TODO
    init_t = np.pi / 2
    t = tf.Variable(init_t)
    inst = cirq.YPowGate(exponent=t)(q(0))
    wrapped = tf_gate_wrapper(inst)
    print(wrapped._tensor)
Exemple #6
0
def test_str():
    assert str(cirq.X) == 'X'
    assert str(cirq.X**0.5) == 'X**0.5'
    assert str(cirq.Rx(np.pi)) == 'Rx(π)'
    assert str(cirq.Rx(0.5 * np.pi)) == 'Rx(0.5π)'
    assert str(cirq.XPowGate(
        global_shift=-0.25)) == 'XPowGate(exponent=1.0, global_shift=-0.25)'

    assert str(cirq.Z) == 'Z'
    assert str(cirq.Z**0.5) == 'S'
    assert str(cirq.Z**0.125) == 'Z**0.125'
    assert str(cirq.Rz(np.pi)) == 'Rz(π)'
    assert str(cirq.Rz(1.4 * np.pi)) == 'Rz(1.4π)'
    assert str(cirq.ZPowGate(
        global_shift=0.25)) == 'ZPowGate(exponent=1.0, global_shift=0.25)'

    assert str(cirq.S) == 'S'
    assert str(cirq.S**-1) == 'S**-1'
    assert str(cirq.T) == 'T'
    assert str(cirq.T**-1) == 'T**-1'

    assert str(cirq.Y) == 'Y'
    assert str(cirq.Y**0.5) == 'Y**0.5'
    assert str(cirq.Ry(np.pi)) == 'Ry(π)'
    assert str(cirq.Ry(3.14 * np.pi)) == 'Ry(3.14π)'
    assert str(cirq.YPowGate(
        exponent=2,
        global_shift=-0.25)) == 'YPowGate(exponent=2, global_shift=-0.25)'

    assert str(cirq.CX) == 'CNOT'
    assert str(cirq.CNOT**0.5) == 'CNOT**0.5'
Exemple #7
0
def test_gateset_with_added_types():
    q = cirq.GridQubit(1, 1)
    x_gateset = cg.SerializableGateSet(
        gate_set_name='x', serializers=[X_SERIALIZER], deserializers=[X_DESERIALIZER]
    )
    xy_gateset = x_gateset.with_added_types(
        gate_set_name='xy', serializers=[Y_SERIALIZER], deserializers=[Y_DESERIALIZER]
    )
    assert x_gateset.name == 'x'
    assert x_gateset.is_supported_operation(cirq.X(q))
    assert not x_gateset.is_supported_operation(cirq.Y(q))
    assert xy_gateset.name == 'xy'
    assert xy_gateset.is_supported_operation(cirq.X(q))
    assert xy_gateset.is_supported_operation(cirq.Y(q))

    # test serialization and deserialization
    proto = op_proto(
        {
            'gate': {'id': 'y_pow'},
            'args': {'half_turns': {'arg_value': {'float_value': 0.125}}},
            'qubits': [{'id': '1_1'}],
        }
    )

    expected_gate = cirq.YPowGate(exponent=0.125)(cirq.GridQubit(1, 1))
    assert xy_gateset.serialize_op(expected_gate) == proto
    assert xy_gateset.deserialize_op(proto) == expected_gate
Exemple #8
0
def test_parameterizable():
    a = cirq.Symbol('a')
    cz = cirq.ControlledGate(cirq.Y)
    cza = cirq.ControlledGate(cirq.YPowGate(exponent=a))
    assert cirq.is_parameterized(cza)
    assert not cirq.is_parameterized(cz)
    assert cirq.resolve_parameters(cza, cirq.ParamResolver({'a': 1})) == cz
Exemple #9
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
Exemple #10
0
def test_arbitrary_xyz_repr():
    cirq.testing.assert_equivalent_repr(
        cirq.XPowGate(exponent=0.1, global_shift=0.2))
    cirq.testing.assert_equivalent_repr(
        cirq.YPowGate(exponent=0.1, global_shift=0.2))
    cirq.testing.assert_equivalent_repr(
        cirq.ZPowGate(exponent=0.1, global_shift=0.2))
Exemple #11
0
def test_tensor_state_vector_implicit_qubits():
    q = cirq.LineQubit.range(2)
    c = cirq.Circuit(cirq.YPowGate(exponent=0.25).on(q[0]))

    psi1 = cirq.final_state_vector(c, dtype=np.complex128)
    psi2 = ccq.tensor_state_vector(c)
    np.testing.assert_allclose(psi1, psi2, atol=1e-15)
def test_tensor_density_matrix_1():
    q = cirq.LineQubit.range(2)
    c = cirq.Circuit(cirq.YPowGate(exponent=0.25).on(q[0]))

    rho1 = cirq.final_density_matrix(c, qubit_order=q, dtype=np.complex128)
    rho2 = ccq.tensor_density_matrix(c, q)
    np.testing.assert_allclose(rho1, rho2, atol=1e-15)
 def _decompose_(self, qubits):
     a, b = qubits
     yield cirq.X(a)**0.5
     yield cirq.CNOT(a, b)
     yield cirq.XPowGate(exponent=self.exponent / 2,
                         global_shift=self._global_shift - 0.5).on(a)
     yield cirq.YPowGate(exponent=self.exponent / 2,
                         global_shift=self._global_shift - 0.5).on(b)
     yield cirq.CNOT(a, b)
     yield cirq.X(a)**-0.5
def test_parameterizable(resolve_fn):
    a = sympy.Symbol('a')
    cy = cirq.ControlledGate(cirq.Y)
    cya = cirq.ControlledGate(cirq.YPowGate(exponent=a))
    assert cirq.is_parameterized(cya)
    assert not cirq.is_parameterized(cy)
    assert resolve_fn(cya, cirq.ParamResolver({'a': 1})) == cy

    cchan = cirq.ControlledGate(
        cirq.RandomGateChannel(sub_gate=cirq.PhaseDampingChannel(0.1),
                               probability=a))
    with pytest.raises(ValueError, match='Cannot control channel'):
        resolve_fn(cchan, cirq.ParamResolver({'a': 0.1}))
def test_equivalent_circuit():
    qreg = cirq.LineQubit.range(4)
    oldc = cirq.Circuit()
    newc = cirq.Circuit()
    gates = [cirq.XPowGate() ** (1 / 2), cirq.YPowGate() ** (1 / 3), cirq.ZPowGate() ** -1]

    for gate in gates:
        for qubit in qreg:
            oldc.append(gate.on(qubit))
        newc.append(cirq.ops.ParallelGateOperation(gate, qreg))

    cirq.testing.assert_has_diagram(newc, oldc.to_text_diagram())
    cirq.testing.assert_circuits_with_terminal_measurements_are_equivalent(oldc, newc, atol=1e-6)
Exemple #16
0
    def create_circuit(self, train_Data):

        circuit_List = []
        for x in train_Data:
            qubits = cirq.GridQubit.rect(1, 2)
            circuit = cirq.Circuit()
            for i, val in enumerate(x):
                if i == 0:
                    circuit.append(cirq.XPowGate(exponent=val)(qubits[i]))
                if i == 1:
                    circuit.append(cirq.YPowGate(exponent=val)(qubits[i]))
            circuit_List.append(circuit)
        return circuit_List
Exemple #17
0
def test_runtime_types_of_rot_gates():
    for gate_type in [lambda p: cirq.CZPowGate(exponent=p),
                      lambda p: cirq.XPowGate(exponent=p),
                      lambda p: cirq.YPowGate(exponent=p),
                      lambda p: cirq.ZPowGate(exponent=p)]:
        p = gate_type(sympy.Symbol('a'))
        assert cirq.unitary(p, None) is None
        assert cirq.pow(p, 2, None) == gate_type(2 * sympy.Symbol('a'))
        assert cirq.inverse(p, None) == gate_type(-sympy.Symbol('a'))

        c = gate_type(0.5)
        assert cirq.unitary(c, None) is not None
        assert cirq.pow(c, 2) == gate_type(1)
        assert cirq.inverse(c) == gate_type(-0.5)
 def get_default_noise_dict(self) -> Dict[str, Any]:
     """Returns the current noise parameters"""
     default_noise_dict = {
         str(cirq.YPowGate()): cirq.depolarize(1e-2),
         str(cirq.ZPowGate()): cirq.depolarize(1e-2),
         str(cirq.XPowGate()): cirq.depolarize(1e-2),
         str(cirq.PhasedXPowGate(phase_exponent=0)): cirq.depolarize(1e-2),
         str(cirq.HPowGate(exponent=1)): cirq.depolarize(1e-2),
         str(cirq.CNotPowGate(exponent=1)): cirq.depolarize(3e-2),
         str(cirq.CZPowGate(exponent=1)): cirq.depolarize(3e-2),
         str(cirq.CCXPowGate(exponent=1)): cirq.depolarize(8e-2),
         str(cirq.CCZPowGate(exponent=1)): cirq.depolarize(8e-2),
     }
     return default_noise_dict
Exemple #19
0
    def test_simplify_circuit_merge_one_qubit_gates(self, qubits):

        q0 = qubits[0]
        c = cirq.Circuit()
        c.append([
            cirq.XPowGate(exponent=0.1)(q0),
            cirq.YPowGate(exponent=0.2)(q0),
            cirq.ZPowGate(exponent=0.3)(q0),
        ])
        new = simplify_circuit(c)

        # the one-qubit gates have been merged
        assert len(new) == 2
        assert isinstance(new[0].operations[0].gate, cirq.PhasedXPowGate)
        assert isinstance(new[1].operations[0].gate, cirq.ZPowGate)
Exemple #20
0
def test_ixyz_circuit_diagram():
    q = cirq.NamedQubit('q')
    ix = cirq.XPowGate(exponent=1, global_shift=0.5)
    iy = cirq.YPowGate(exponent=1, global_shift=0.5)
    iz = cirq.ZPowGate(exponent=1, global_shift=0.5)

    cirq.testing.assert_has_diagram(
        cirq.Circuit(
            ix(q),
            ix(q)**-1,
            ix(q)**-0.99999,
            ix(q)**-1.00001,
            ix(q)**3,
            ix(q)**4.5,
            ix(q)**4.500001,
        ),
        """
q: ───X───X───X───X───X───X^0.5───X^0.5───
        """,
    )

    cirq.testing.assert_has_diagram(
        cirq.Circuit(
            iy(q),
            iy(q)**-1,
            iy(q)**3,
            iy(q)**4.5,
            iy(q)**4.500001,
        ),
        """
q: ───Y───Y───Y───Y^0.5───Y^0.5───
    """,
    )

    cirq.testing.assert_has_diagram(
        cirq.Circuit(
            iz(q),
            iz(q)**-1,
            iz(q)**3,
            iz(q)**4.5,
            iz(q)**4.500001,
        ),
        """
q: ───Z───Z───Z───S───S───
    """,
    )
Exemple #21
0
def test_gateset_with_added_types():
    x_serializer = _x_serializer()
    x_deserializer = _x_deserializer()
    y_serializer = _y_serializer()
    y_deserializer = _y_deserializer()
    with cirq.testing.assert_deprecated('SerializableGateSet',
                                        deadline='v0.16',
                                        count=2):
        q = cirq.GridQubit(1, 1)
        x_gateset = cg.SerializableGateSet(gate_set_name='x',
                                           serializers=[x_serializer],
                                           deserializers=[x_deserializer])
        xy_gateset = x_gateset.with_added_types(gate_set_name='xy',
                                                serializers=[y_serializer],
                                                deserializers=[y_deserializer])
        assert x_gateset.name == 'x'
        assert x_gateset.is_supported_operation(cirq.X(q))
        assert not x_gateset.is_supported_operation(cirq.Y(q))
        assert xy_gateset.name == 'xy'
        assert xy_gateset.is_supported_operation(cirq.X(q))
        assert xy_gateset.is_supported_operation(cirq.Y(q))

        # test serialization and deserialization
        proto = op_proto({
            'gate': {
                'id': 'y_pow'
            },
            'args': {
                'half_turns': {
                    'arg_value': {
                        'float_value': 0.125
                    }
                }
            },
            'qubits': [{
                'id': '1_1'
            }],
        })

        expected_gate = cirq.YPowGate(exponent=0.125)(cirq.GridQubit(1, 1))
        assert xy_gateset.serialize_op(expected_gate) == proto
        assert xy_gateset.deserialize_op(proto) == expected_gate
Exemple #22
0
def test_exponentiate_single_value_as_exponent():
    q = cirq.LineQubit(0)

    assert cirq.approx_eq(math.e**(-0.25j * math.pi * cirq.X(q)),
                          cirq.Rx(0.25 * math.pi).on(q))

    assert cirq.approx_eq(math.e**(-0.25j * math.pi * cirq.Y(q)),
                          cirq.Ry(0.25 * math.pi).on(q))

    assert cirq.approx_eq(math.e**(-0.25j * math.pi * cirq.Z(q)),
                          cirq.Rz(0.25 * math.pi).on(q))

    assert cirq.approx_eq(np.exp(-0.3j * math.pi * cirq.X(q)),
                          cirq.Rx(0.3 * math.pi).on(q))

    assert cirq.approx_eq(cirq.X(q)**0.5, cirq.XPowGate(exponent=0.5).on(q))

    assert cirq.approx_eq(cirq.Y(q)**0.5, cirq.YPowGate(exponent=0.5).on(q))

    assert cirq.approx_eq(cirq.Z(q)**0.5, cirq.ZPowGate(exponent=0.5).on(q))
    def test_gateset_with_added_gates(self):
        """Test adding new gates to gateset."""
        q = cirq.GridQubit(1, 1)
        x_gateset = serializable_gate_set.SerializableGateSet(
            gate_set_name='x',
            serializers=[X_SERIALIZER],
            deserializers=[X_DESERIALIZER],
        )
        xy_gateset = x_gateset.with_added_gates(
            gate_set_name='xy',
            serializers=[Y_SERIALIZER],
            deserializers=[Y_DESERIALIZER],
        )
        self.assertEqual(x_gateset.gate_set_name, 'x')
        self.assertTrue(x_gateset.is_supported_operation(cirq.X(q)))
        self.assertFalse(x_gateset.is_supported_operation(cirq.Y(q)))
        self.assertEqual(xy_gateset.gate_set_name, 'xy')
        self.assertTrue(xy_gateset.is_supported_operation(cirq.X(q)))
        self.assertTrue(xy_gateset.is_supported_operation(cirq.Y(q)))

        # test serialization and deserialization
        proto = op_proto({
            'gate': {
                'id': 'y_pow'
            },
            'args': {
                'half_turns': {
                    'arg_value': {
                        'float_value': 0.125
                    }
                },
            },
            'qubits': [{
                'id': '1_1'
            }]
        })

        expected_gate = cirq.YPowGate(exponent=0.125)(cirq.GridQubit(1, 1))
        self.assertEqual(xy_gateset.serialize_op(expected_gate), proto)
        self.assertEqual(xy_gateset.deserialize_op(proto), expected_gate)
def test_serialize_sqrt_y_pow_gate():
    proto = op_proto({
        'gate': {
            'id': 'xy_half_pi'
        },
        'args': {
            'axis_half_turns': {
                'arg_value': {
                    'float_value': 0.5
                }
            }
        },
        'qubits': [{
            'id': '1_2'
        }],
    })
    q = cirq.GridQubit(1, 2)
    op = cirq.YPowGate(exponent=0.5)(q)
    assert HALF_PI_GATE_SET.serialize_op(op) == proto
    cirq.testing.assert_allclose_up_to_global_phase(cirq.unitary(
        HALF_PI_GATE_SET.deserialize_op(proto)),
                                                    cirq.unitary(op),
                                                    atol=1e-6)
    q = cirq.GridQubit(1, 2)
    op = cirq.YPowGate(exponent=0.5)(q)
    assert HALF_PI_GATE_SET.serialize_op(op) == proto
    cirq.testing.assert_allclose_up_to_global_phase(cirq.unitary(
        HALF_PI_GATE_SET.deserialize_op(proto)),
                                                    cirq.unitary(op),
                                                    atol=1e-6)


@pytest.mark.parametrize(
    ('gate', 'axis_half_turns', 'half_turns'),
    [
        (cirq.X**0.25, 0.0, 0.25),
        (cirq.Y**0.25, 0.5, 0.25),
        (cirq.XPowGate(exponent=0.125), 0.0, 0.125),
        (cirq.YPowGate(exponent=0.125), 0.5, 0.125),
        (cirq.PhasedXPowGate(exponent=0.125,
                             phase_exponent=0.25), 0.25, 0.125),
        (cirq.rx(0.125 * np.pi), 0.0, 0.125),
        (cirq.ry(0.25 * np.pi), 0.5, 0.25),
    ],
)
def test_serialize_deserialize_arbitrary_xy(gate, axis_half_turns, half_turns):
    op = gate.on(cirq.GridQubit(1, 2))
    expected = op_proto({
        'gate': {
            'id': 'xy'
        },
        'args': {
            'axis_half_turns': {
                'arg_value': {
Exemple #26
0
def test_equals():
    eq = cirq.testing.EqualsTester()
    eq.add_equality_group(cirq.X, cirq.ops.pauli_gates.X, cirq.XPowGate())
    eq.add_equality_group(cirq.Y, cirq.ops.pauli_gates.Y, cirq.YPowGate())
    eq.add_equality_group(cirq.Z, cirq.ops.pauli_gates.Z, cirq.ZPowGate())
Exemple #27
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
Exemple #28
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.channel(h), cirq.channel(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_channel(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)
Exemple #29
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())
Exemple #30
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())