Пример #1
0
    def create_calibration_program(
        self,
        layers: List['cirq.google.CalibrationLayer'],
        program_id: Optional[str] = None,
        gate_set: Optional[sgs.SerializableGateSet] = None,
        description: Optional[str] = None,
        labels: Optional[Dict[str, str]] = None,
    ) -> engine_program.EngineProgram:
        """Wraps a list of calibration layers into an Any for Quantum Engine.

        Args:
            layers: The calibration routines to execute.  All layers will be
                executed within the same API call in the order specified,
                though some layers may be interleaved together using
                hardware-specific batching.
            program_id: A user-provided identifier for the program. This must be
                unique within the Google Cloud project being used. If this
                parameter is not provided, a random id of the format
                'calibration-################YYMMDD' will be generated,
                where # is alphanumeric and YYMMDD is the current year, month,
                and day.
            gate_set: The gate set used to serialize the circuits in each
                layer.  The gate set must be supported by the processor.
            description: An optional description to set on the program.
            labels: Optional set of labels to set on the program.

        Returns:
            A EngineProgram for the newly created program.
        """
        if not gate_set:
            raise ValueError('Gate set must be specified.')
        if not program_id:
            program_id = _make_random_id('calibration-')

        calibration = v2.calibration_pb2.FocusedCalibration()
        for layer in layers:
            new_layer = calibration.layers.add()
            new_layer.calibration_type = layer.calibration_type
            for arg in layer.args:
                arg_to_proto(layer.args[arg], out=new_layer.args[arg])
            gate_set.serialize(layer.program, msg=new_layer.layer)

        new_program_id, new_program = self.context.client.create_program(
            self.project_id,
            program_id,
            code=self._pack_any(calibration),
            description=description,
            labels=labels,
        )

        return engine_program.EngineProgram(
            self.project_id,
            new_program_id,
            self.context,
            new_program,
            result_type=ResultType.Calibration,
        )
Пример #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 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)
Пример #5
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
Пример #6
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')