Ejemplo n.º 1
0
    def _serialize_run_context(
            self,
            sweeps: List[study.Sweep],
            repetitions: int,
    ) -> qtypes.any_pb2.Any:
        import cirq.google.engine.engine as engine_base
        context = qtypes.any_pb2.Any()
        proto_version = self.context.proto_version
        if proto_version == engine_base.ProtoVersion.V1:
            context.Pack(
                v1.program_pb2.RunContext(parameter_sweeps=[
                    v1.sweep_to_proto(sweep, repetitions) for sweep in sweeps
                ]))
        elif proto_version == engine_base.ProtoVersion.V2:
            run_context = v2.run_context_pb2.RunContext()
            for sweep in sweeps:
                sweep_proto = run_context.parameter_sweeps.add()
                sweep_proto.repetitions = repetitions
                v2.sweep_to_proto(sweep, out=sweep_proto.sweep)

            context.Pack(run_context)
        else:
            raise ValueError(
                'invalid run context proto version: {}'.format(proto_version))
        return context
Ejemplo n.º 2
0
    def _serialize_run_context(
        self,
        sweeps: List[study.Sweep],
        repetitions: int,
    ) -> Dict[str, Any]:
        proto_version = self.proto_version
        if proto_version == ProtoVersion.V1:
            context_descriptor = v1.program_pb2.RunContext.DESCRIPTOR
            context_dict = {}  # type: Dict[str, Any]
            context_dict['@type'] = TYPE_PREFIX + context_descriptor.full_name
            context_dict['parameter_sweeps'] = [
                v1.sweep_to_proto_dict(sweep, repetitions) for sweep in sweeps
            ]
            return context_dict
        elif proto_version == ProtoVersion.V2:
            run_context = v2.run_context_pb2.RunContext()
            for sweep in sweeps:
                sweep_proto = run_context.parameter_sweeps.add()
                sweep_proto.repetitions = repetitions
                v2.sweep_to_proto(sweep, out=sweep_proto.sweep)

            return _any_dict_from_msg(run_context)
        else:
            raise ValueError(
                'invalid run context proto version: {}'.format(proto_version))
Ejemplo n.º 3
0
def test_sweep_to_proto_points():
    proto = v2.sweep_to_proto(cirq.Points('foo', [-1, 0, 1, 1.5]))
    assert isinstance(proto, run_context_pb2.Sweep)
    assert proto.HasField('single_sweep')
    assert proto.single_sweep.parameter_key == 'foo'
    assert proto.single_sweep.WhichOneof('sweep') == 'points'
    assert list(proto.single_sweep.points.points) == [-1, 0, 1, 1.5]
Ejemplo n.º 4
0
def test_sweep_to_proto_linspace():
    proto = v2.sweep_to_proto(cirq.Linspace('foo', 0, 1, 20))
    assert isinstance(proto, run_context_pb2.Sweep)
    assert proto.HasField('single_sweep')
    assert proto.single_sweep.parameter_key == 'foo'
    assert proto.single_sweep.WhichOneof('sweep') == 'linspace'
    assert proto.single_sweep.linspace.first_point == 0
    assert proto.single_sweep.linspace.last_point == 1
    assert proto.single_sweep.linspace.num_points == 20
Ejemplo n.º 5
0
def test_sweep_with_flattened_sweep():
    q = cirq.GridQubit(0, 0)
    circuit = cirq.Circuit.from_ops(
        cirq.PhasedXPowGate(exponent=sympy.Symbol('t') / 4 + 0.5,
                            phase_exponent=sympy.Symbol('t') / 2 + 0.1,
                            global_shift=0.0)(q), cirq.measure(q, key='m'))
    param_sweep1 = cirq.Linspace('t', start=0, stop=1, length=20)
    (_, param_sweep2) = cirq.flatten_with_sweep(circuit, param_sweep1)
    assert v2.sweep_to_proto(param_sweep2) is not None
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 test_sweep_with_list_sweep():
    ls = cirq.study.to_sweep([{'a': 1, 'b': 2}, {'a': 3, 'b': 4}])
    proto = v2.sweep_to_proto(ls)
    expected = v2.run_context_pb2.Sweep()
    expected.sweep_function.function_type = v2.run_context_pb2.SweepFunction.ZIP
    p1 = expected.sweep_function.sweeps.add()
    p1.single_sweep.parameter_key = 'a'
    p1.single_sweep.points.points.extend([1, 3])
    p2 = expected.sweep_function.sweeps.add()
    p2.single_sweep.parameter_key = 'b'
    p2.single_sweep.points.points.extend([2, 4])
    assert proto == expected
Ejemplo n.º 8
0
    def run_batch(
        self,
        job_id: Optional[str] = None,
        params_list: List[study.Sweepable] = None,
        repetitions: int = 1,
        processor_ids: Sequence[str] = (),
        description: Optional[str] = None,
        labels: Optional[Dict[str, str]] = None,
    ) -> engine_job.EngineJob:
        """Runs a batch of circuits on the QuantumEngine.

        This method should only be used if the Program object was created
        with a BatchProgram.  The number of parameter sweeps should match
        the number of circuits within that BatchProgram.

        This method does not block until a result is returned.  However,
        no results will be available until the entire batch is complete.

        Args:
            job_id: Optional job id to use. If this is not provided, a random id
                of the format 'job-################YYMMDD' will be generated,
                where # is alphanumeric and YYMMDD is the current year, month,
                and day.
            params_list: Parameter sweeps to run with the program.  There must
                be one Sweepable object for each circuit in the batch. If this
                is None, it is assumed that the circuits are not parameterized
                and do not require sweeps.
            repetitions: The number of circuit repetitions to run.
            processor_ids: The engine processors that should be candidates
                to run the program. Only one of these will be scheduled for
                execution.
            description: An optional description to set on the job.
            labels: Optional set of labels to set on the job.

        Returns:
            An EngineJob. If this is iterated over it returns a list of
            TrialResults. All TrialResults for the first circuit are listed
            first, then the TrialResults for the second, etc. The TrialResults
            for a circuit are listed in the order imposed by the associated
            parameter sweep.

        Raises:
            ValueError: if the program was not a batch program or no processors
                were supplied.
        """
        import cirq.google.engine.engine as engine_base

        if self.result_type != ResultType.Batch:
            raise ValueError('Can only use run_batch() in batch mode.')
        if params_list is None:
            params_list = [None] * self.batch_size()
        if not job_id:
            job_id = engine_base._make_random_id('job-')
        if not processor_ids:
            raise ValueError('No processors specified')

        # Pack the run contexts into batches
        batch = v2.batch_pb2.BatchRunContext()
        for param in params_list:
            sweeps = study.to_sweeps(param)
            current_context = batch.run_contexts.add()
            for sweep in sweeps:
                sweep_proto = current_context.parameter_sweeps.add()
                sweep_proto.repetitions = repetitions
                v2.sweep_to_proto(sweep, out=sweep_proto.sweep)
        batch_context = qtypes.any_pb2.Any()
        batch_context.Pack(batch)

        created_job_id, job = self.context.client.create_job(
            project_id=self.project_id,
            program_id=self.program_id,
            job_id=job_id,
            processor_ids=processor_ids,
            run_context=batch_context,
            description=description,
            labels=labels,
        )
        return engine_job.EngineJob(
            self.project_id,
            self.program_id,
            created_job_id,
            self.context,
            job,
            result_type=ResultType.Batch,
        )
Ejemplo n.º 9
0
def test_sweep_from_proto_unknown_sweep_type():
    with pytest.raises(ValueError, match='cannot convert to v2 Sweep proto'):
        v2.sweep_to_proto(UnknownSweep('foo'))
Ejemplo n.º 10
0
def test_sweep_to_proto_unit():
    proto = v2.sweep_to_proto(cirq.UnitSweep)
    assert isinstance(proto, run_context_pb2.Sweep)
    assert not proto.HasField('single_sweep')
    assert not proto.HasField('sweep_function')
Ejemplo n.º 11
0
def test_sweep_to_proto_roundtrip(sweep):
    msg = v2.sweep_to_proto(sweep)
    deserialized = v2.sweep_from_proto(msg)
    assert deserialized == sweep