Ejemplo n.º 1
0
    def _serialize_program(
        self,
        program: 'cirq.Circuit',
        gate_set: serializable_gate_set.SerializableGateSet = None
    ) -> Dict[str, Any]:
        gate_set = gate_set or gate_sets.XMON

        if self.proto_version == ProtoVersion.V1:
            if isinstance(program, circuits.Circuit):
                program.device.validate_circuit(program)
            else:
                raise TypeError(f'Unrecognized program type: {type(program)}')
            program_descriptor = v1.program_pb2.Program.DESCRIPTOR
            program_dict = {}  # type: Dict[str, Any]
            program_dict['@type'] = TYPE_PREFIX + program_descriptor.full_name
            program_dict['operations'] = [
                op for op in v1.circuit_as_schedule_to_proto_dicts(program)
            ]
            return program_dict
        elif self.proto_version == ProtoVersion.V2:
            program = gate_set.serialize(program)
            return _any_dict_from_msg(program)
        else:
            raise ValueError('invalid program proto version: {}'.format(
                self.proto_version))
Ejemplo n.º 2
0
Archivo: engine.py Proyecto: yy8yy/Cirq
    def _serialize_program(
        self,
        program: TProgram,
        gate_set: serializable_gate_set.SerializableGateSet = None
    ) -> Dict[str, Any]:
        gate_set = gate_set or gate_sets.XMON

        if self.proto_version == ProtoVersion.V1:
            schedule = self.program_as_schedule(program)
            schedule.device.validate_schedule(schedule)

            program_descriptor = v1.program_pb2.Program.DESCRIPTOR
            program_dict = {}  # type: Dict[str, Any]
            program_dict['@type'] = TYPE_PREFIX + program_descriptor.full_name
            program_dict['operations'] = [
                op for op in api_v1.schedule_to_proto_dicts(schedule)
            ]
            return program_dict
        elif self.proto_version == ProtoVersion.V2:
            if isinstance(program, schedules.Schedule):
                program.device.validate_schedule(program)
            program = gate_set.serialize(program)
            return _any_dict_from_msg(program)
        else:
            raise ValueError('invalid program proto version: {}'.format(
                self.proto_version))
Ejemplo n.º 3
0
    def from_proto(
        cls, proto: v2.device_pb2.DeviceSpecification,
        gate_set: serializable_gate_set.SerializableGateSet
    ) -> 'SerializableDevice':
        """

        Args:
            proto: A proto describing the qubits on the device, as well as the
                supported gates and timing information.
            gate_set: A SerializableGateSet that can translate the gate_ids
                into cirq Gates.
        """

        # Store target sets, since they are refered to by name later
        allowed_targets: Dict[str, Set[Tuple['cirq.Qid', ...]]] = {}
        permutation_ids: Set[str] = set()
        for ts in proto.valid_targets:
            allowed_targets[ts.name] = cls._create_target_set(ts)
            if ts.target_ordering == v2.device_pb2.TargetSet.SUBSET_PERMUTATION:
                permutation_ids.add(ts.name)

        # Store gate definitions from proto
        gate_definitions: Dict[str, _GateDefinition] = {}
        for gs in proto.valid_gate_sets:
            for gate_def in gs.valid_gates:
                # Combine all valid targets in the gate's listed target sets
                gate_target_set = set([
                    target for ts_name in gate_def.valid_targets
                    for target in allowed_targets[ts_name]
                ])
                which_are_permutations = [
                    t in permutation_ids for t in gate_def.valid_targets
                ]
                is_permutation = any(which_are_permutations)
                if is_permutation:
                    if not all(which_are_permutations):
                        msg = f'Id {gate_def.id} in {gate_set.gate_set_name} ' \
                            ' mixes SUBSET_PERMUTATION with other types which' \
                            ' is not currently allowed.'
                        raise NotImplementedError(msg)
                gate_definitions[gate_def.id] = _GateDefinition(
                    duration=Duration(picos=gate_def.gate_duration_picos),
                    target_set=gate_target_set,
                    is_permutation=is_permutation,
                    number_of_qubits=gate_def.number_of_qubits)

        # Loop through serializers and map gate_definitions to type
        gates_by_type: Dict[Type['cirq.Gate'], _GateDefinition] = {}
        for gate_type in gate_set.supported_gate_types():
            for serializer in gate_set.serializers[gate_type]:
                gate_id = serializer.serialized_gate_id
                if gate_id not in gate_definitions:
                    raise ValueError(f'Serializer has {gate_id} which is not '
                                     'supported by the device specification')
                gates_by_type[gate_type] = gate_definitions[gate_id]

        return SerializableDevice(
            qubits=SerializableDevice._qubits_from_ids(proto.valid_qubits),
            gate_definitions=gates_by_type,
        )
Ejemplo n.º 4
0
    def _serialize_program(self, program: 'cirq.Circuit',
                           gate_set: sgs.SerializableGateSet) -> any_pb2.Any:
        if not isinstance(program, circuits.Circuit):
            raise TypeError(f'Unrecognized program type: {type(program)}')
        program.device.validate_circuit(program)

        if self.context.proto_version == ProtoVersion.V2:
            program = gate_set.serialize(program)
            return self._pack_any(program)
        else:
            raise ValueError('invalid program proto version: {}'.format(
                self.context.proto_version))
Ejemplo n.º 5
0
def test_sample_with_gate_set():
    gate_set = SerializableGateSet('test', SINGLE_QUBIT_SERIALIZERS,
                                   SINGLE_QUBIT_DESERIALIZERS)
    sampler = cirq.ZerosSampler(gate_set=gate_set)
    a, b = cirq.LineQubit.range(2)
    circuit1 = cirq.Circuit([cirq.X(a)])
    circuit2 = cirq.Circuit([cirq.CX(a, b)])

    sampler.sample(circuit1)

    with pytest.raises(AssertionError, match='Unsupported operation'):
        sampler.sample(circuit2)
Ejemplo n.º 6
0
Archivo: engine.py Proyecto: wabei/Cirq
    def _serialize_program_v2(
        self, program: Program, sweeps: List[Sweep], repetitions: int,
        gate_set: SerializableGateSet
    ) -> Tuple[Dict[str, Any], Dict[str, Any]]:
        if isinstance(program, Schedule):
            program.device.validate_schedule(program)

        program = gate_set.serialize(program)

        run_context = v2.run_context_pb2.RunContext()
        for sweep in sweeps:
            sweep_proto = run_context.parameter_sweeps.add()
            sweep_proto.repetitions = repetitions
            api_v2.sweep_to_proto(sweep, out=sweep_proto.sweep)

        def any_dict(message: gp.message.Message) -> Dict[str, Any]:
            any_message = any_pb2.Any()
            any_message.Pack(message)
            return gp.json_format.MessageToDict(any_message)

        return any_dict(program), any_dict(run_context)
Ejemplo n.º 7
0
    def _serialize_program(
        self,
        program: 'cirq.Circuit',
        gate_set: serializable_gate_set.SerializableGateSet = None
    ) -> qtypes.any_pb2.Any:
        gate_set = gate_set or gate_sets.XMON
        code = qtypes.any_pb2.Any()

        if not isinstance(program, circuits.Circuit):
            raise TypeError(f'Unrecognized program type: {type(program)}')
        program.device.validate_circuit(program)

        if self.context.proto_version == ProtoVersion.V1:
            code.Pack(
                v1.program_pb2.Program(operations=[
                    op for op in v1.circuit_as_schedule_to_protos(program)
                ]))
        elif self.context.proto_version == ProtoVersion.V2:
            program = gate_set.serialize(program)
            code.Pack(program)
        else:
            raise ValueError('invalid program proto version: {}'.format(
                self.context.proto_version))
        return code