def test_multiple_serializers():
    serializer1 = cg.GateOpSerializer(
        gate_type=cirq.XPowGate,
        serialized_gate_id='x_pow',
        args=[
            cg.SerializingArg(serialized_name='half_turns',
                              serialized_type=float,
                              op_getter='exponent')
        ],
        can_serialize_predicate=lambda x: x.gate.exponent != 1,
    )
    serializer2 = cg.GateOpSerializer(
        gate_type=cirq.XPowGate,
        serialized_gate_id='x',
        args=[
            cg.SerializingArg(serialized_name='half_turns',
                              serialized_type=float,
                              op_getter='exponent')
        ],
        can_serialize_predicate=lambda x: x.gate.exponent == 1,
    )
    gate_set = cg.SerializableGateSet(gate_set_name='my_gate_set',
                                      serializers=[serializer1, serializer2],
                                      deserializers=[])
    q0 = cirq.GridQubit(1, 1)
    assert gate_set.serialize_op(cirq.X(q0)).gate.id == 'x'
    assert gate_set.serialize_op(cirq.X(q0)**0.5).gate.id == 'x_pow'
Example #2
0
def test_multiple_serializers():
    # Deprecations: cirq_google.SerializableGateSet, cirq_google.GateOpSerializer, and
    # cirq_google.SerializingArg
    with cirq.testing.assert_deprecated('SerializableGateSet',
                                        'CircuitSerializer',
                                        deadline='v0.16',
                                        count=5):
        serializer1 = cg.GateOpSerializer(
            gate_type=cirq.XPowGate,
            serialized_gate_id='x_pow',
            args=[
                cg.SerializingArg(serialized_name='half_turns',
                                  serialized_type=float,
                                  op_getter='exponent')
            ],
            can_serialize_predicate=lambda x: x.gate.exponent != 1,
        )
        serializer2 = cg.GateOpSerializer(
            gate_type=cirq.XPowGate,
            serialized_gate_id='x',
            args=[
                cg.SerializingArg(serialized_name='half_turns',
                                  serialized_type=float,
                                  op_getter='exponent')
            ],
            can_serialize_predicate=lambda x: x.gate.exponent == 1,
        )
        gate_set = cg.SerializableGateSet(
            gate_set_name='my_gate_set',
            serializers=[serializer1, serializer2],
            deserializers=[])
        q0 = cirq.GridQubit(1, 1)
        assert gate_set.serialize_op(cirq.X(q0)).gate.id == 'x'
        assert gate_set.serialize_op(cirq.X(q0)**0.5).gate.id == 'x_pow'
Example #3
0
def test_to_proto_callable(val_type, val, arg_value):
    serializer = cg.GateOpSerializer(
        gate_type=GateWithMethod,
        serialized_gate_id='my_gate',
        args=[
            cg.SerializingArg(serialized_name='my_val',
                              serialized_type=val_type,
                              op_getter=get_val)
        ],
    )
    q = cirq.GridQubit(1, 2)
    result = serializer.to_proto(GateWithMethod(val)(q),
                                 arg_function_language='linear')
    expected = op_proto({
        'gate': {
            'id': 'my_gate'
        },
        'args': {
            'my_val': arg_value
        },
        'qubits': [{
            'id': '1_2'
        }]
    })
    assert result == expected
Example #4
0
def test_is_supported_operation_can_serialize_predicate():
    x_deserializer = _x_deserializer()
    # Deprecations: cirq_google.SerializableGateSet, cirq_google.GateOpSerializer, and
    # cirq_google.SerializingArg
    with cirq.testing.assert_deprecated('SerializableGateSet',
                                        'CircuitSerializer',
                                        deadline='v0.16',
                                        count=3):
        q = cirq.GridQubit(1, 2)
        serializer = cg.GateOpSerializer(
            gate_type=cirq.XPowGate,
            serialized_gate_id='x_pow',
            args=[
                cg.SerializingArg(serialized_name='half_turns',
                                  serialized_type=float,
                                  op_getter='exponent')
            ],
            can_serialize_predicate=lambda x: x.gate.exponent == 1.0,
        )
        gate_set = cg.SerializableGateSet(gate_set_name='my_gate_set',
                                          serializers=[serializer],
                                          deserializers=[x_deserializer])
        assert gate_set.is_supported_operation(cirq.XPowGate()(q))
        assert not gate_set.is_supported_operation(cirq.XPowGate()(q)**0.5)
        assert gate_set.is_supported_operation(cirq.X(q))
Example #5
0
def test_to_proto_not_required_ok():
    serializer = cg.GateOpSerializer(
        gate_type=GateWithProperty,
        serialized_gate_id='my_gate',
        args=[
            cg.SerializingArg(serialized_name='my_val',
                              serialized_type=float,
                              op_getter='val'),
            cg.SerializingArg(
                serialized_name='not_req',
                serialized_type=float,
                op_getter='not_req',
                required=False,
            ),
        ],
    )
    expected = op_proto({
        'gate': {
            'id': 'my_gate'
        },
        'args': {
            'my_val': {
                'arg_value': {
                    'float_value': 0.125
                }
            }
        },
        'qubits': [{
            'id': '1_2'
        }],
    })

    q = cirq.GridQubit(1, 2)
    assert serializer.to_proto(GateWithProperty(0.125)(q)) == expected
Example #6
0
def test_token_serialization():
    serializer = cg.GateOpSerializer(
        gate_type=GateWithAttribute,
        serialized_gate_id='my_gate',
        args=[
            cg.SerializingArg(serialized_name='my_val',
                              serialized_type=float,
                              op_getter='val')
        ],
    )
    q = cirq.GridQubit(1, 2)
    tag = cg.CalibrationTag('my_token')
    expected = op_proto({
        'gate': {
            'id': 'my_gate'
        },
        'args': {
            'my_val': {
                'arg_value': {
                    'float_value': 0.125
                }
            }
        },
        'qubits': [{
            'id': '1_2'
        }],
        'token_value': 'my_token',
    })
    assert expected == serializer.to_proto(
        GateWithAttribute(0.125)(q).with_tags(tag))
Example #7
0
def test_to_proto_line_qubit_supported():
    serializer = cg.GateOpSerializer(
        gate_type=GateWithProperty,
        serialized_gate_id='my_gate',
        args=[
            cg.SerializingArg(serialized_name='my_val',
                              serialized_type=float,
                              op_getter='val')
        ],
    )
    q = cirq.LineQubit('10')
    arg_value = 1.0
    result = serializer.to_proto(GateWithProperty(arg_value)(q))

    expected = op_proto({
        'gate': {
            'id': 'my_gate'
        },
        'args': {
            'my_val': {
                'arg_value': {
                    'float_value': arg_value
                }
            }
        },
        'qubits': [{
            'id': '10'
        }],
    })
    assert result == expected
Example #8
0
def test_token_serialization_with_constant_reference(constants, expected_index,
                                                     expected_constants):
    serializer = cg.GateOpSerializer(
        gate_type=GateWithAttribute,
        serialized_gate_id='my_gate',
        args=[
            cg.SerializingArg(serialized_name='my_val',
                              serialized_type=float,
                              op_getter='val')
        ],
    )
    # Make a local copy since we are modifying the array in-place.
    constants = copy.copy(constants)
    q = cirq.GridQubit(1, 2)
    tag = cg.CalibrationTag('my_token')
    expected = op_proto({
        'gate': {
            'id': 'my_gate'
        },
        'args': {
            'my_val': {
                'arg_value': {
                    'float_value': 0.125
                }
            }
        },
        'qubits': [{
            'id': '1_2'
        }],
        'token_constant_index': expected_index,
    })
    assert expected == serializer.to_proto(
        GateWithAttribute(0.125)(q).with_tags(tag), constants=constants)
    assert constants == expected_constants
Example #9
0
def test_to_proto_gate_mismatch():
    serializer = cg.GateOpSerializer(
        gate_type=GateWithProperty,
        serialized_gate_id='my_gate',
        args=[cg.SerializingArg(serialized_name='my_val', serialized_type=float, op_getter='val')],
    )
    q = cirq.GridQubit(1, 2)
    with pytest.raises(ValueError, match='GateWithAttribute.*GateWithProperty'):
        serializer.to_proto(GateWithAttribute(1.0)(q))
Example #10
0
def test_to_proto_no_getattr():
    serializer = cg.GateOpSerializer(
        gate_type=GateWithProperty,
        serialized_gate_id='my_gate',
        args=[cg.SerializingArg(serialized_name='my_val', serialized_type=float, op_getter='nope')],
    )
    q = cirq.GridQubit(1, 2)
    with pytest.raises(ValueError, match='does not have'):
        serializer.to_proto(GateWithProperty(1.0)(q))
Example #11
0
def test_to_proto_unsupported_type():
    serializer = cg.GateOpSerializer(
        gate_type=GateWithProperty,
        serialized_gate_id='my_gate',
        args=[cg.SerializingArg(serialized_name='my_val', serialized_type=bytes, op_getter='val')],
    )
    q = cirq.GridQubit(1, 2)
    with pytest.raises(ValueError, match='bytes'):
        serializer.to_proto(GateWithProperty(b's')(q))
Example #12
0
def test_can_serialize_operation_subclass():
    serializer = cg.GateOpSerializer(
        gate_type=GateWithAttribute,
        serialized_gate_id='my_gate',
        args=[cg.SerializingArg(serialized_name='my_val', serialized_type=float, op_getter='val')],
        can_serialize_predicate=lambda x: x.gate.val == 1,
    )
    q = cirq.GridQubit(1, 1)
    assert serializer.can_serialize_operation(SubclassGate(1)(q))
    assert not serializer.can_serialize_operation(SubclassGate(0)(q))
Example #13
0
def test_deprecated_fields():
    serializer = cg.GateOpSerializer(
        gate_type=GateWithAttribute,
        serialized_gate_id='my_gate',
        args=[],
    )
    with assert_deprecated('Use serialized_id', deadline='v0.13'):
        assert serializer.serialized_gate_id == serializer.serialized_id

    with assert_deprecated('Use internal_type', deadline='v0.13'):
        assert serializer.gate_type == serializer.internal_type
Example #14
0
def test_to_proto_type_mismatch(val_type, val):
    serializer = cg.GateOpSerializer(
        gate_type=GateWithProperty,
        serialized_gate_id='my_gate',
        args=[
            cg.SerializingArg(serialized_name='my_val', serialized_type=val_type, op_getter='val')
        ],
    )
    q = cirq.GridQubit(1, 2)
    with pytest.raises(ValueError, match=str(type(val))):
        serializer.to_proto(GateWithProperty(val)(q))
Example #15
0
def _y_serializer():
    with cirq.testing.assert_deprecated('CircuitSerializer',
                                        deadline='v0.16',
                                        count=None):
        return cg.GateOpSerializer(
            gate_type=cirq.YPowGate,
            serialized_gate_id='y_pow',
            args=[
                cg.SerializingArg(serialized_name='half_turns',
                                  serialized_type=float,
                                  op_getter='exponent')
            ],
        )
Example #16
0
def test_to_proto_required_but_not_present():
    serializer = cg.GateOpSerializer(
        gate_type=GateWithProperty,
        serialized_gate_id='my_gate',
        args=[
            cg.SerializingArg(serialized_name='my_val',
                              serialized_type=float,
                              op_getter=lambda x: None)
        ],
    )
    q = cirq.GridQubit(1, 2)
    with pytest.raises(ValueError, match='required'):
        serializer.to_proto(GateWithProperty(1.0)(q))
Example #17
0
def test_get_engine_device(get_processor):
    device_spec = _to_any(
        Merge(
            """
valid_gate_sets: [{
    name: 'test_set',
    valid_gates: [{
        id: 'x',
        number_of_qubits: 1,
        gate_duration_picos: 1000,
        valid_targets: ['1q_targets']
    }]
}],
valid_qubits: ['0_0', '1_1'],
valid_targets: [{
    name: '1q_targets',
    target_ordering: SYMMETRIC,
    targets: [{
        ids: ['0_0']
    }]
}]
""",
            v2.device_pb2.DeviceSpecification(),
        ))

    gate_set = cg.SerializableGateSet(
        gate_set_name='x_gate_set',
        serializers=[
            cg.GateOpSerializer(gate_type=cirq.XPowGate,
                                serialized_gate_id='x',
                                args=[])
        ],
        deserializers=[
            cg.GateOpDeserializer(serialized_gate_id='x',
                                  gate_constructor=cirq.XPowGate,
                                  args=[])
        ],
    )

    get_processor.return_value = qtypes.QuantumProcessor(
        device_spec=device_spec)
    device = cirq_google.get_engine_device('rainbow',
                                           'project',
                                           gatesets=[gate_set])
    assert set(device.qubits) == {cirq.GridQubit(0, 0), cirq.GridQubit(1, 1)}
    device.validate_operation(cirq.X(cirq.GridQubit(0, 0)))
    with pytest.raises(ValueError):
        device.validate_operation(cirq.X(cirq.GridQubit(1, 2)))
    with pytest.raises(ValueError):
        device.validate_operation(cirq.Y(cirq.GridQubit(0, 0)))
Example #18
0
def _create_gate_op_serializer(
    *,
    gate_type,
    serialized_gate_id,
    args,
    can_serialize_predicate=lambda x: True,
    serialize_tokens=True,
):
    with cirq.testing.assert_deprecated('CircuitSerializer',
                                        deadline='v0.16',
                                        count=1):
        return cg.GateOpSerializer(
            gate_type=gate_type,
            serialized_gate_id=serialized_gate_id,
            args=args,
            can_serialize_predicate=can_serialize_predicate,
            serialize_tokens=serialize_tokens,
        )
Example #19
0
def test_is_supported_operation_can_serialize_predicate():
    q = cirq.GridQubit(1, 2)
    serializer = cg.GateOpSerializer(
        gate_type=cirq.XPowGate,
        serialized_gate_id='x_pow',
        args=[
            cg.SerializingArg(
                serialized_name='half_turns', serialized_type=float, op_getter='exponent'
            )
        ],
        can_serialize_predicate=lambda x: x.gate.exponent == 1.0,
    )
    gate_set = cg.SerializableGateSet(
        gate_set_name='my_gate_set', serializers=[serializer], deserializers=[X_DESERIALIZER]
    )
    assert gate_set.is_supported_operation(cirq.XPowGate()(q))
    assert not gate_set.is_supported_operation(cirq.XPowGate()(q) ** 0.5)
    assert gate_set.is_supported_operation(cirq.X(q))
def _just_meas():
    # Deprecations: cirq_google.SerializableGateSet, cirq_google.GateOpSerializer, and
    # cirq_google.GateOpDeserializer
    with cirq.testing.assert_deprecated('SerializableGateSet',
                                        'CircuitSerializer',
                                        deadline='v0.16',
                                        count=None):
        return cg.SerializableGateSet(
            gate_set_name='meas_gate_set',
            serializers=[
                cg.GateOpSerializer(gate_type=cirq.MeasurementGate,
                                    serialized_gate_id='meas',
                                    args=[])
            ],
            deserializers=[
                cg.GateOpDeserializer(serialized_gate_id='meas',
                                      gate_constructor=cirq.MeasurementGate,
                                      args=[])
            ],
        )
Example #21
0
def test_defaults_not_serialized():
    serializer = cg.GateOpSerializer(
        gate_type=GateWithAttribute,
        serialized_gate_id='my_gate',
        args=[
            cg.SerializingArg(
                serialized_name='my_val', serialized_type=float, default=1.0, op_getter='val'
            )
        ],
    )
    q = cirq.GridQubit(1, 2)
    no_default = op_proto(
        {
            'gate': {'id': 'my_gate'},
            'args': {'my_val': {'arg_value': {'float_value': 0.125}}},
            'qubits': [{'id': '1_2'}],
        }
    )
    assert no_default == serializer.to_proto(GateWithAttribute(0.125)(q))
    with_default = op_proto({'gate': {'id': 'my_gate'}, 'qubits': [{'id': '1_2'}]})
    assert with_default == serializer.to_proto(GateWithAttribute(1.0)(q))
valid_targets: [{
    name: '1q_targets',
    target_ordering: SYMMETRIC,
    targets: [{
        ids: ['0_0']
    }]
}]
""",
        v2.device_pb2.DeviceSpecification(),
    ))

_GATE_SET = cg.SerializableGateSet(
    gate_set_name='x_gate_set',
    serializers=[
        cg.GateOpSerializer(gate_type=cirq.XPowGate,
                            serialized_gate_id='x',
                            args=[])
    ],
    deserializers=[
        cg.GateOpDeserializer(serialized_gate_id='x',
                              gate_constructor=cirq.XPowGate,
                              args=[])
    ],
)

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

_RESULTS_V2 = v2.result_pb2.Result(sweep_results=[
    v2.result_pb2.SweepResult(
from typing import Dict
import pytest
import sympy
from google.protobuf import json_format

import cirq
from cirq.testing import assert_deprecated
import cirq_google as cg
from cirq_google.api import v2

X_SERIALIZER = cg.GateOpSerializer(
    gate_type=cirq.XPowGate,
    serialized_gate_id='x_pow',
    args=[
        cg.SerializingArg(
            serialized_name='half_turns',
            serialized_type=float,
            op_getter='exponent',
        )
    ],
)

X_DESERIALIZER = cg.GateOpDeserializer(
    serialized_gate_id='x_pow',
    gate_constructor=cirq.XPowGate,
    args=[
        cg.DeserializingArg(
            serialized_name='half_turns',
            constructor_arg_name='exponent',
        )
    ],
Example #24
0
import pytest

import cirq
import cirq_google
import cirq_google as cg
import cirq_google.api.v2 as v2
import cirq_google.api.v2.device_pb2 as device_pb2
import cirq_google.devices.known_devices as cgdk
import cirq_google.serialization.common_serializers as cgc

_JUST_CZ = cg.SerializableGateSet(
    gate_set_name='cz_gate_set',
    serializers=[
        cg.GateOpSerializer(gate_type=cirq.CZPowGate,
                            serialized_gate_id='cz',
                            args=[])
    ],
    deserializers=[
        cg.GateOpDeserializer(serialized_gate_id='cz',
                              gate_constructor=cirq.CZPowGate,
                              args=[])
    ],
)

_JUST_MEAS = cg.SerializableGateSet(
    gate_set_name='meas_gate_set',
    serializers=[
        cg.GateOpSerializer(gate_type=cirq.MeasurementGate,
                            serialized_gate_id='meas',
                            args=[])