def to_proto(
        self,
        op: 'cirq.Operation',
        msg: Optional[v2.program_pb2.Operation] = None,
        *,
        arg_function_language: Optional[str] = '',
    ) -> Optional[v2.program_pb2.Operation]:
        """Returns the cirq.google.api.v2.Operation message as a proto dict."""

        gate = op.gate
        if not isinstance(gate, self.gate_type):
            raise ValueError(
                'Gate of type {} but serializer expected type {}'.format(
                    type(gate), self.gate_type))

        if not self.can_serialize_predicate(op):
            return None

        if msg is None:
            msg = v2.program_pb2.Operation()

        msg.gate.id = self.serialized_gate_id
        for qubit in op.qubits:
            msg.qubits.add().id = v2.qubit_to_proto_id(qubit)
        for arg in self.args:
            value = self._value_from_gate(op, arg)
            if value is not None:
                _arg_to_proto(value,
                              out=msg.args[arg.serialized_name],
                              arg_function_language=arg_function_language)
        return msg
示例#2
0
    def to_proto(
        self,
        op: 'cirq.Operation',
        msg: Optional[v2.program_pb2.Operation] = None,
        *,
        arg_function_language: Optional[str] = '',
        constants: List[v2.program_pb2.Constant] = None
    ) -> Optional[v2.program_pb2.Operation]:
        """Returns the cirq.google.api.v2.Operation message as a proto dict.

        Note that this function may modify the constant list if it adds
        tokens to the circuit's constant table.
        """

        gate = op.gate
        if not isinstance(gate, self.gate_type):
            raise ValueError(
                'Gate of type {} but serializer expected type {}'.format(
                    type(gate), self.gate_type))

        if not self.can_serialize_predicate(op):
            return None

        if msg is None:
            msg = v2.program_pb2.Operation()

        msg.gate.id = self.serialized_gate_id
        for qubit in op.qubits:
            msg.qubits.add().id = v2.qubit_to_proto_id(qubit)
        for arg in self.args:
            value = self._value_from_gate(op, arg)
            if value is not None and (not arg.default or value != arg.default):
                _arg_to_proto(value,
                              out=msg.args[arg.serialized_name],
                              arg_function_language=arg_function_language)
        if self.serialize_tokens:
            for tag in op.tags:
                if isinstance(tag, CalibrationTag):
                    if constants is not None:
                        constant = v2.program_pb2.Constant()
                        constant.string_value = tag.token
                        try:
                            msg.token_constant_index = constants.index(
                                constant)
                        except ValueError:
                            # Token not found, add it to the list
                            msg.token_constant_index = len(constants)
                            constants.append(constant)
                    else:
                        msg.token_value = tag.token
        return msg
示例#3
0
def test_serialize_conversion(value: ARG_LIKE, proto: v2.program_pb2.Arg):
    msg = v2.program_pb2.Arg()
    json_format.ParseDict(proto, msg)
    packed = json_format.MessageToDict(_arg_to_proto(value,
                                                     arg_function_language=''),
                                       including_default_value_fields=True,
                                       preserving_proto_field_name=True,
                                       use_integers_for_enums=True)
    assert packed == proto
示例#4
0
def test_serialize_sympy_constants():
    proto = _arg_to_proto(sympy.pi, arg_function_language='')
    packed = json_format.MessageToDict(proto,
                                       including_default_value_fields=True,
                                       preserving_proto_field_name=True,
                                       use_integers_for_enums=True)
    assert packed == {
        'arg_value': {
            'float_value': float(np.float32(sympy.pi))
        }
    }
示例#5
0
def test_serialize_sympy_constants():
    proto = _arg_to_proto(sympy.pi, arg_function_language='')
    packed = json_format.MessageToDict(proto,
                                       including_default_value_fields=True,
                                       preserving_proto_field_name=True,
                                       use_integers_for_enums=True)
    assert len(packed) == 1
    assert len(packed['arg_value']) == 1
    # protobuf 3.12+ truncates floats to 4 bytes
    assert np.isclose(packed['arg_value']['float_value'],
                      np.float32(sympy.pi),
                      atol=1e-7)
示例#6
0
def test_correspondence(min_lang: str, value: ARG_LIKE,
                        proto: v2.program_pb2.Arg):
    msg = v2.program_pb2.Arg()
    json_format.ParseDict(proto, msg)
    min_i = LANGUAGE_ORDER.index(min_lang)
    for i, lang in enumerate(LANGUAGE_ORDER):
        if i < min_i:
            with pytest.raises(ValueError,
                               match='not supported by arg_function_language'):
                _ = _arg_to_proto(value, arg_function_language=lang)
            with pytest.raises(ValueError, match='Unrecognized function type'):
                _ = _arg_from_proto(msg, arg_function_language=lang)
        else:
            parsed = _arg_from_proto(msg, arg_function_language=lang)
            packed = json_format.MessageToDict(
                _arg_to_proto(value, arg_function_language=lang),
                including_default_value_fields=True,
                preserving_proto_field_name=True,
                use_integers_for_enums=True)

            assert parsed == value
            assert packed == proto
示例#7
0
def test_unsupported_function_language():
    with pytest.raises(ValueError, match='Unrecognized arg_function_language'):
        _ = _arg_to_proto(1, arg_function_language='NEVER GONNAH APPEN')
    with pytest.raises(ValueError, match='Unrecognized arg_function_language'):
        _ = _arg_from_proto(None, arg_function_language='NEVER GONNAH APPEN')