def run_sweep( self, job_id: Optional[str] = None, params: study.Sweepable = None, repetitions: int = 1, processor_ids: Sequence[str] = ('xmonsim',), description: Optional[str] = None, labels: Optional[Dict[str, str]] = None, ) -> engine_job.EngineJob: """Runs the program on the QuantumEngine. In contrast to run, this runs across multiple parameter sweeps, and does not block until a result is returned. 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: Parameters to run with the program. 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, one for each parameter sweep. """ import cirq.google.engine.engine as engine_base if self.result_type != ResultType.Program: raise ValueError('Please use run_batch() for batch mode.') if not job_id: job_id = engine_base._make_random_id('job-') sweeps = study.to_sweeps(params or study.ParamResolver({})) run_context = self._serialize_run_context(sweeps, repetitions) 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=run_context, description=description, labels=labels, ) return engine_job.EngineJob( self.project_id, self.program_id, created_job_id, self.context, job )
def create_job( self, *, # Force keyword args. program_name: str, job_config: Optional[JobConfig] = None, params: study.Sweepable = None, repetitions: int = 1, priority: int = 500, processor_ids: Sequence[str] = ('xmonsim', ), gate_set: serializable_gate_set.SerializableGateSet = None ) -> engine_job.EngineJob: gate_set = gate_set or gate_sets.XMON # Check program to run and program parameters. if not 0 <= priority < 1000: raise ValueError('priority must be between 0 and 1000') job_config = self.implied_job_config(job_config) sweeps = study.to_sweeps(params or study.ParamResolver({})) run_context = self._serialize_run_context(sweeps, repetitions) # Create job. request = { 'name': '%s/jobs/%s' % (program_name, job_config.job_id), 'output_config': { 'gcs_results_location': { 'uri': job_config.gcs_results } }, 'scheduling_config': { 'priority': priority, 'processor_selector': { 'processor_names': [ 'projects/%s/processors/%s' % (self.project_id, processor_id) for processor_id in processor_ids ] } }, 'run_context': run_context } response = self._make_request( self.service.projects().programs().jobs().create( parent=program_name, body=request)) return engine_job.EngineJob(job_config, response, self)
def create_job( self, *, # Force keyword args. program_name: str, job_config: Optional[JobConfig] = None, params: study.Sweepable = None, repetitions: int = 1, priority: int = 500, processor_ids: Sequence[str] = ('xmonsim',), gate_set: serializable_gate_set.SerializableGateSet = None ) -> engine_job.EngineJob: gate_set = gate_set or gate_sets.XMON # Check program to run and program parameters. if not 0 <= priority < 1000: raise ValueError('priority must be between 0 and 1000') job_config = self.implied_job_config(job_config) sweeps = study.to_sweeps(params or study.ParamResolver({})) run_context = self._serialize_run_context(sweeps, repetitions) # Create job. request = qtypes.QuantumJob( name='%s/jobs/%s' % (program_name, job_config.job_id), scheduling_config=qtypes.SchedulingConfig( priority=priority, processor_selector=qtypes.SchedulingConfig.ProcessorSelector( processor_names=[ 'projects/%s/processors/%s' % (self.project_id, processor_id) for processor_id in processor_ids ])), run_context=run_context) response = self._make_request(lambda: self.client.create_quantum_job( program_name, request, False)) return engine_job.EngineJob(job_config, response, self)
def sample( self, program: 'cirq.Circuit', *, repetitions: int = 1, params: 'cirq.Sweepable' = None, ) -> 'pd.DataFrame': """Samples the given Circuit, producing a pandas data frame. Args: program: The circuit to sample from. repetitions: The number of times to sample the program, for each parameter mapping. params: Maps symbols to one or more values. This argument can be a dictionary, a list of dictionaries, a `cirq.Sweep`, a list of `cirq.Sweep`, etc. The program will be sampled `repetition` times for each mapping. Defaults to a single empty mapping. Returns: A `pandas.DataFrame` with a row for each sample, and a column for each measurement result as well as a column for each symbolic parameter. There is an also index column containing the repetition number, for each parameter assignment. Examples: >>> a, b, c = cirq.LineQubit.range(3) >>> sampler = cirq.Simulator() >>> circuit = cirq.Circuit(cirq.X(a), ... cirq.measure(a, key='out')) >>> print(sampler.sample(circuit, repetitions=4)) out 0 1 1 1 2 1 3 1 >>> circuit = cirq.Circuit(cirq.X(a), ... cirq.CNOT(a, b), ... cirq.measure(a, b, c, key='out')) >>> print(sampler.sample(circuit, repetitions=4)) out 0 6 1 6 2 6 3 6 >>> circuit = cirq.Circuit(cirq.X(a)**sympy.Symbol('t'), ... cirq.measure(a, key='out')) >>> print(sampler.sample( ... circuit, ... repetitions=3, ... params=[{'t': 0}, {'t': 1}])) t out 0 0 0 1 0 0 2 0 0 0 1 1 1 1 1 2 1 1 """ sweeps_list = study.to_sweeps(params) keys = sorted(sweeps_list[0].keys) if sweeps_list else [] for sweep in sweeps_list: if sweep and set(sweep.keys) != set(keys): raise ValueError( 'Inconsistent sweep parameters. ' f'One sweep had {repr(keys)} ' f'while another had {repr(sorted(sweep.keys))}.') results = [] for sweep in sweeps_list: sweep_results = self.run_sweep(program, params=sweep, repetitions=repetitions) for resolver, result in zip(sweep, sweep_results): param_values_once = [resolver.value_of(key) for key in keys] param_table = pd.DataFrame(data=[param_values_once] * repetitions, columns=keys) results.append(pd.concat([param_table, result.data], axis=1)) return pd.concat(results)
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, )
def run_sweep( self, *, # Force keyword args. program: Program, job_config: Optional[JobConfig] = None, params: Sweepable = None, repetitions: int = 1, priority: int = 500, processor_ids: Sequence[str] = ('xmonsim', ), gate_set: SerializableGateSet = gate_sets.XMON) -> 'EngineJob': """Runs the supplied Circuit or Schedule via Quantum Engine. In contrast to run, this runs across multiple parameter sweeps, and does not block until a result is returned. Args: program: The Circuit or Schedule to execute. If a circuit is provided, a moment by moment schedule will be used. job_config: Configures the names of programs and jobs. params: Parameters to run with the program. repetitions: The number of circuit repetitions to run. priority: The priority to run at, 0-100. processor_ids: The engine processors to run against. gate_set: The gate set used to serialize the circuit. The gate set must be supported by the selected processor Returns: An EngineJob. If this is iterated over it returns a list of TrialResults, one for each parameter sweep. """ job_config = self.implied_job_config(job_config) # Check program to run and program parameters. if not 0 <= priority < 1000: raise ValueError('priority must be between 0 and 1000') sweeps = study.to_sweeps(params or ParamResolver({})) if self.proto_version == ProtoVersion.V1: code, run_context = self._serialize_program_v1( program, sweeps, repetitions) elif self.proto_version == ProtoVersion.V2: code, run_context = self._serialize_program_v2( program, sweeps, repetitions, gate_set) else: raise ValueError('invalid proto version: {}'.format( self.proto_version)) # Create program. request = { 'name': 'projects/%s/programs/%s' % ( self.project_id, job_config.program_id, ), 'gcs_code_location': { 'uri': job_config.gcs_program }, 'code': code, } response = self.service.projects().programs().create( parent='projects/%s' % self.project_id, body=request).execute() # Create job. request = { 'name': '%s/jobs/%s' % (response['name'], job_config.job_id), 'output_config': { 'gcs_results_location': { 'uri': job_config.gcs_results } }, 'scheduling_config': { 'priority': priority, 'processor_selector': { 'processor_names': [ 'projects/%s/processors/%s' % (self.project_id, processor_id) for processor_id in processor_ids ] } }, 'run_context': run_context } response = self.service.projects().programs().jobs().create( parent=response['name'], body=request).execute() return EngineJob(job_config, response, self)