def create_experiment_data(self, iq_data: List[Any], single_shot: bool = False): """Populate avg_iq_data to use it for testing. Args: iq_data: A List of IQ data. single_shot: Indicates if the data is single-shot or not. """ results = [] if not single_shot: for circ_data in iq_data: res = ExperimentResult( success=True, meas_level=1, meas_return="avg", data=ExperimentResultData(memory=circ_data), header=self.header, shots=1024, ) results.append(res) else: for circ_data in iq_data: res = ExperimentResult( success=True, meas_level=1, meas_return="single", data=ExperimentResultData(memory=circ_data), header=self.header, shots=1024, ) results.append(res) # pylint: disable=attribute-defined-outside-init self.iq_experiment = ExperimentData(FakeExperiment()) self.iq_experiment.add_data(Result(results=results, **self.base_result_args))
def setUp(self): experiment_result_data = ExperimentResultData.from_dict( {'counts': { '0x0': 42 }}) experiment_result_data_2 = ExperimentResultData.from_dict( {'counts': { '0x1': 42 }}) header_1 = Obj.from_dict({'name': 'Test1'}) header_2 = Obj.from_dict({'name': 'Test2'}) self.experiment_result_dictionary_1 = { 'name': 'Test1', 'shots': 42, 'data': experiment_result_data, 'status': 'DONE', 'success': True, 'time_taken': 0.42, 'header': header_1 } self.experiment_result_dictionary_2 = { 'name': 'Test2', 'shots': 23, 'data': experiment_result_data_2, 'status': 'DONE', 'success': True, 'time_taken': 0.12, 'header': header_2 } self.experiment_result_1 = ExperimentResult( **self.experiment_result_dictionary_1) self.experiment_result_2 = ExperimentResult( **self.experiment_result_dictionary_2)
def setUp(self): """Here, single-shots average to points at plus/minus 1. The setting corresponds to four single-shots done on two qubits. """ super().setUp() circ_es = ExperimentResultData(memory=[[1.0, 1.0], [-1.0, 1.0]]) self._sig_gs = np.array([1.0, -1.0]) / np.sqrt(2.0) circ_gs = ExperimentResultData(memory=[[-1.0, -1.0], [1.0, -1.0]]) self._sig_es = np.array([-1.0, 1.0]) / np.sqrt(2.0) circ_x90p = ExperimentResultData(memory=[[0.0, 0.0], [0.0, 0.0]]) self._sig_x90 = np.array([0, 0]) circ_x45p = ExperimentResultData(memory=[[-0.5, -0.5], [0.5, -0.5]]) self._sig_x45 = np.array([0.5, -0.5]) / np.sqrt(2.0) res_es = ExperimentResult( shots=4, success=True, meas_level=1, meas_return="avg", data=circ_es, header=self.header, ) res_gs = ExperimentResult( shots=4, success=True, meas_level=1, meas_return="avg", data=circ_gs, header=self.header, ) res_x90p = ExperimentResult( shots=4, success=True, meas_level=1, meas_return="avg", data=circ_x90p, header=self.header, ) res_x45p = ExperimentResult( shots=4, success=True, meas_level=1, meas_return="avg", data=circ_x45p, header=self.header, ) self.data = ExperimentData(FakeExperiment()) self.data.add_data( Result(results=[res_es, res_gs, res_x90p, res_x45p], **self.base_result_args))
def _get_experiment_results(self, jobs: List[Dict[str, Any]]) -> List[ExperimentResult]: """ Get results from experiments from the Quantum Inspire platform for one or more jobs. :param jobs: A list of jobs :raises QiskitBackendError: If an error occurred while executing the job on the Quantum Inspire backend. :return: A list of experiment results; containing the data, execution time, status, etc. for the list of jobs. """ results = [self.__api.get_result_from_job(job['id']) for job in jobs] experiment_results = [] for result, job in zip(results, jobs): if not result.get('histogram', {}): raise QiskitBackendError( 'Result from backend contains no histogram data!\n{}'.format(result.get('raw_text'))) user_data = json.loads(str(job.get('user_data'))) measurements = user_data.pop('measurements') histogram_obj, memory_data = self.__convert_result_data(result, measurements) full_state_histogram_obj = self.__convert_histogram(result, measurements) calibration = self.__api.get_calibration_from_result(result['id']) experiment_result_data = ExperimentResultData(counts=histogram_obj, memory=memory_data, probabilities=full_state_histogram_obj, calibration=calibration) header = QobjExperimentHeader.from_dict(user_data) experiment_result_dictionary = {'name': job.get('name'), 'seed': 42, 'shots': job.get('number_of_shots'), 'data': experiment_result_data, 'status': 'DONE', 'success': True, 'time_taken': result.get('execution_time_in_seconds'), 'header': header} experiment_results.append(ExperimentResult(**experiment_result_dictionary)) return experiment_results
def get_experiment_results(self, qi_job: QIJob) -> List[ExperimentResult]: """ Get results from experiments from the Quantum-inspire platform. Args: qi_job: A job that has already been submitted and which execution is completed. Raises: QisKitBackendError: If an error occurred during execution by the backend. Returns: A list of experiment results; containing the data, execution time, status, etc. """ jobs = self.__api.get_jobs_from_project(int(qi_job.job_id())) results = [self.__api.get_result_from_job(job['id']) for job in jobs] experiment_results = [] for result, job in zip(results, jobs): if not result.get('histogram', {}): raise QisKitBackendError( 'Result from backend contains no histogram data!\n{}'.format(result.get('raw_text'))) user_data = json.loads(str(job.get('user_data'))) measurements = user_data.pop('measurements') histogram_obj, memory_data = self.__convert_result_data(result, measurements) full_state_histogram_obj = self.__convert_histogram(result, measurements) experiment_result_data = ExperimentResultData(counts=histogram_obj, probabilities=full_state_histogram_obj, memory=memory_data) header = Obj.from_dict(user_data) experiment_result_dictionary = {'name': job.get('name'), 'seed': 42, 'shots': job.get('number_of_shots'), 'data': experiment_result_data, 'status': 'DONE', 'success': True, 'time_taken': result.get('execution_time_in_seconds'), 'header': header} experiment_results.append(ExperimentResult(**experiment_result_dictionary)) return experiment_results
def result(self, **kwargs: KwargTypes) -> Result: if self._result is not None: return self._result result_list = [] for h, ex, fm in zip(self._handles, self._qobj.experiments, self._final_maps): tk_result = self._backend._backend.get_result(h) result_list.append( ExperimentResult( shots=self._qobj.config.shots, success=True, data=backendresult_to_qiskit_resultdata( tk_result, ex.header, fm), header=ex.header, )) self._backend._backend.pop_result(h) self._result = Result( backend_name=self._backend.name(), backend_version=self._backend.version(), qobj_id=self._qobj.qobj_id, job_id=self.job_id(), success=True, results=result_list, ) return self._result
def setUp(self): """Setup variables used for testing.""" super().setUp() mem1 = ExperimentResultData(memory=[ [[1103260.0, -11378508.0], [2959012.0, -16488753.0]], [[442170.0, -19283206.0], [-5279410.0, -15339630.0]], [[3016514.0, -14548009.0], [-3404756.0, -16743348.0]], ]) mem2 = ExperimentResultData(memory=[ [[5131962.0, -16630257.0], [4438870.0, -13752518.0]], [[3415985.0, -16031913.0], [2942458.0, -15840465.0]], [[5199964.0, -14955998.0], [4030843.0, -14538923.0]], ]) res1 = ExperimentResult(shots=3, success=True, meas_level=1, data=mem1, header=self.header) res2 = ExperimentResult(shots=3, success=True, meas_level=1, data=mem2, header=self.header) self.result_lvl1 = Result(results=[res1, res2], **self.base_result_args) raw_counts1 = {"0x0": 4, "0x2": 6} raw_counts2 = {"0x0": 2, "0x2": 8} data1 = ExperimentResultData(counts=dict(**raw_counts1)) data2 = ExperimentResultData(counts=dict(**raw_counts2)) res1 = ExperimentResult(shots=10, success=True, meas_level=2, data=data1, header=self.header) res2 = ExperimentResult(shots=10, success=True, meas_level=2, data=data2, header=self.header) self.exp_data_lvl2 = ExperimentData(FakeExperiment()) self.exp_data_lvl2.add_data( Result(results=[res1, res2], **self.base_result_args))
def setUp(self): """Setup some IQ data.""" super().setUp() mem_avg = ExperimentResultData( memory=[[-539698.0, -153030784.0], [5541283.0, -160369600.0]]) mem_single = ExperimentResultData(memory=[ [[-56470872.0, -136691568.0], [-53407256.0, -176278624.0]], [[-34623272.0, -151247824.0], [-36650644.0, -170559312.0]], [[42658720.0, -153054640.0], [29689970.0, -174671824.0]], [[-47387248.0, -177826640.0], [-62149124.0, -165909728.0]], [[-51465408.0, -148338000.0], [23157112.0, -165826736.0]], [[51426688.0, -142703104.0], [34330920.0, -185572592.0]], ]) res_single = ExperimentResult( shots=3, success=True, meas_level=1, meas_return="single", data=mem_single, header=self.header, ) res_avg = ExperimentResult(shots=6, success=True, meas_level=1, meas_return="avg", data=mem_avg, header=self.header) # result_single = Result(results=[res_single], **self.base_result_args) # result_avg = Result(results=[res_avg], **self.base_result_args) self.exp_data_single = ExperimentData(FakeExperiment()) self.exp_data_single.add_data( Result(results=[res_single], **self.base_result_args)) self.exp_data_avg = ExperimentData(FakeExperiment()) self.exp_data_avg.add_data( Result(results=[res_avg], **self.base_result_args))
def from_dict(dict): return FinishedExperiment( backend_name=dict.get('backend_name', ''), backend_version=dict.get('backend_version', None), date=dateutil.parser.parse(dict['date']) if 'date' in dict else None, qobj=Qobj.from_dict(dict.get('qobj', {})), job_id=dict.get('job_id', ''), status=JobStatus[dict['job_status']] if 'job_status' in dict else JobStatus.INITIALIZING, results=[ExperimentResult.from_dict(d) for d in dict.get('results', [])], noise_model=NoiseModel.from_dict(dict['noise_model']) if 'noise_model' in dict and dict['noise_model'] is not None else None, external_id=dict.get('external_id', None), theta=dict.get('theta', np.arange(0, 2*np.pi, 0.1)), # fixing a bug here.... argh! parameters=dict.get('parameters', []) )
def qiskit_experiment_result_from_quasar_probability_histogram( h: QuasarProbabilityHistogram, bit_map: Dict[int, int]) -> ExperimentResult: # it's possible for a null bit map if there are no measurement gates, in which # case the aer simulator returns {} for counts since nothing is measured qiskit_counts = remap_probability_histogram( h, bit_map) if len(bit_map) > 0 else {} experiment_data = ExperimentResultData(counts=qiskit_counts) experiment_result = ExperimentResult(shots=h.nmeasurement, success=True, data=experiment_data) # meas_level = MeasLevel.CLASSIFIED, meas_return = MeasLevel.AVERAGE ? # TODO must set jobj_id and job_id return experiment_result
def from_dict(cls, data): """Create a new ExperimentResultData object from a dictionary. Args: data (dict): A dictionary representing the Result to create. It will be in the same format as output by :meth:`to_dict`. Returns: Result: The ``Result`` object from the input dictionary. """ in_data = copy.copy(data) in_data["results"] = [ExperimentResult.from_dict(x) for x in in_data.pop("results")] if "header" in in_data: in_data["header"] = QobjHeader.from_dict(in_data.pop("header")) return cls(**in_data)
def _generate_experiment_result(qlm_result, metadata): """ Generates a Qiskit experiment result. Args: qlm_result: qat.core.wrappers.Result object which data is aggregated metadata: metadata of the circuit of the experiment Returns: An ExperimentResult structure. """ samples = [hex(s.state.state) for s in qlm_result.raw_data] counts = dict(Counter(samples)) data = ExperimentResultData.from_dict({"counts": counts}) return ExperimentResult( shots=len(qlm_result.raw_data), success=True, data=data, header=QobjExperimentHeader(**metadata), )
def result(self): experiment_results: List[ExperimentResult] = [] task: AwsQuantumTask qasm_experiment: QasmQobjExperiment for task, qasm_experiment in zip(self._tasks, self._qobj.experiments): result: GateModelQuantumTaskResult = task.result() counts: Dict[str, int] = map_measurements(result.measurement_counts, qasm_experiment) data = ExperimentResultData(counts=dict(counts)) experiment_result = ExperimentResult( shots=self.shots, success=task.state() == 'COMPLETED', header=qasm_experiment.header, status=task.state(), data=data) experiment_results.append(experiment_result) qiskit_result = Result(backend_name=self._backend.name(), backend_version=self._backend.version(), qobj_id=self._qobj.qobj_id, job_id=self._job_id, success=self.status(), results=experiment_results) return qiskit_result
def setUp(self): experiment_result_data_1 = ExperimentResultData.from_dict( {'counts': { '0x0': 42, '0x3': 58 }}) experiment_result_data_1.probabilities = {'0x0': 0.42, '0x3': 0.58} experiment_result_data_2 = ExperimentResultData.from_dict( {'counts': { '0x0': 24, '0x1': 25, '0x2': 23, '0x3': 28 }}) experiment_result_data_2.probabilities = { '0x0': 0.24, '0x1': 0.25, '0x2': 0.23, '0x3': 0.28 } experiment_result_data_3 = ExperimentResultData.from_dict( {'counts': { '0x0': 24, '0x1': 25, '0x2': 23, '0x3': 28 }}) header_1 = QobjHeader.from_dict({ 'name': 'Test1', 'memory_slots': 2, 'creg_sizes': [['c0', 2]] }) header_2 = QobjHeader.from_dict({ 'name': 'Test2', 'memory_slots': 3, 'creg_sizes': [['c0', 3]] }) header_3 = None self.experiment_result_dictionary_1 = { 'name': 'Test1', 'shots': 42, 'data': experiment_result_data_1, 'status': 'DONE', 'success': True, 'time_taken': 0.42, 'header': header_1 } self.experiment_result_dictionary_2 = { 'name': 'Test2', 'shots': 23, 'data': experiment_result_data_2, 'status': 'DONE', 'success': True, 'time_taken': 0.12, 'header': header_2 } self.experiment_result_dictionary_3 = { 'name': 'Test3', 'shots': 23, 'data': experiment_result_data_3, 'status': 'DONE', 'success': True, 'time_taken': 0.12, 'header': header_3 } self.experiment_result_1 = ExperimentResult( **self.experiment_result_dictionary_1) self.experiment_result_2 = ExperimentResult( **self.experiment_result_dictionary_2) self.experiment_result_3 = ExperimentResult( **self.experiment_result_dictionary_3)
def setUp(self): experiment_result_data_1 = ExperimentResultData.from_dict({ 'counts': { '0x0': 42, '0x3': 58 }, 'probabilities': { '0x0': 0.42, '0x3': 0.58 }, 'calibration': { 'fridge_temperature': 26.9, 'unit': 'mK' } }) experiment_result_data_2 = ExperimentResultData.from_dict({ 'counts': { '0x0': 24, '0x1': 25, '0x2': 23, '0x3': 28 }, 'probabilities': { '0x0': 0.24, '0x1': 0.25, '0x2': 0.23, '0x3': 0.28 }, 'calibration': { 'fridge_temperature': 25.0, 'unit': 'mK' } }) experiment_result_data_3 = ExperimentResultData.from_dict({ 'counts': { '0x0': 24, '0x1': 25, '0x2': 23, '0x3': 28 }, 'calibration': None }) experiment_result_data_4 = ExperimentResultData.from_dict( {'counts': { '0x0': 24, '0x1': 25, '0x2': 23, '0x3': 28 }}) header_1 = QobjHeader.from_dict({ 'name': 'Test1', 'memory_slots': 2, 'creg_sizes': [['c0', 2]] }) header_2 = QobjHeader.from_dict({ 'name': 'Test2', 'memory_slots': 3, 'creg_sizes': [['c0', 3]] }) header_3 = None header_4 = None self.experiment_result_dictionary_1 = { 'name': 'Test1', 'shots': 42, 'data': experiment_result_data_1, 'status': 'DONE', 'success': True, 'time_taken': 0.42, 'header': header_1 } self.experiment_result_dictionary_2 = { 'name': 'Test2', 'shots': 23, 'data': experiment_result_data_2, 'status': 'DONE', 'success': True, 'time_taken': 0.12, 'header': header_2 } self.experiment_result_dictionary_3 = { 'name': 'Test3', 'shots': 23, 'data': experiment_result_data_3, 'status': 'DONE', 'success': True, 'time_taken': 0.12, 'header': header_3 } self.experiment_result_dictionary_4 = { 'name': 'Test4', 'shots': 21, 'data': experiment_result_data_4, 'status': 'DONE', 'success': True, 'time_taken': 0.12, 'header': header_4 } self.experiment_result_1 = ExperimentResult( **self.experiment_result_dictionary_1) self.experiment_result_2 = ExperimentResult( **self.experiment_result_dictionary_2) self.experiment_result_3 = ExperimentResult( **self.experiment_result_dictionary_3) self.experiment_result_4 = ExperimentResult( **self.experiment_result_dictionary_4)
def setUp(self): """Setup variables used for testing.""" self.base_result_args = dict( backend_name="test_backend", backend_version="1.0.0", qobj_id="id-123", job_id="job-123", success=True, ) mem1 = ExperimentResultData(memory=[ [[1103260.0, -11378508.0], [2959012.0, -16488753.0]], [[442170.0, -19283206.0], [-5279410.0, -15339630.0]], [[3016514.0, -14548009.0], [-3404756.0, -16743348.0]], ]) mem2 = ExperimentResultData(memory=[ [[5131962.0, -16630257.0], [4438870.0, -13752518.0]], [[3415985.0, -16031913.0], [2942458.0, -15840465.0]], [[5199964.0, -14955998.0], [4030843.0, -14538923.0]], ]) header1 = QobjExperimentHeader( clbit_labels=[["meas", 0], ["meas", 1]], creg_sizes=[["meas", 2]], global_phase=0.0, memory_slots=2, metadata={ "experiment_type": "fake_test_experiment", "x_values": 0.0 }, ) header2 = QobjExperimentHeader( clbit_labels=[["meas", 0], ["meas", 1]], creg_sizes=[["meas", 2]], global_phase=0.0, memory_slots=2, metadata={ "experiment_type": "fake_test_experiment", "x_values": 1.0 }, ) res1 = ExperimentResult(shots=3, success=True, meas_level=1, data=mem1, header=header1) res2 = ExperimentResult(shots=3, success=True, meas_level=1, data=mem2, header=header2) self.result_lvl1 = Result(results=[res1, res2], **self.base_result_args) raw_counts = {"0x0": 4, "0x2": 6} data = ExperimentResultData(counts=dict(**raw_counts)) header = QobjExperimentHeader( metadata={"experiment_type": "fake_test_experiment"}, clbit_labels=[["c", 0], ["c", 1]], creg_sizes=[["c", 2]], n_qubits=2, memory_slots=2, ) res = ExperimentResult(shots=9, success=True, meas_level=2, data=data, header=header) self.exp_data_lvl2 = ExperimentData(FakeExperiment()) self.exp_data_lvl2.add_data( Result(results=[res], **self.base_result_args)) super().setUp()
def qiskit_experiment_result_from_statevector(sv) -> ExperimentResult: experiment_data = ExperimentResultData(statevector=sv) experiment_result = ExperimentResult(shots=1, success=True, data=experiment_data) return experiment_result
def run_experiment(self, experiment): """Run an experiment (circuit) and return a single experiment result. Args: experiment (QobjExperiment): experiment from qobj experiments list Returns: dict: A dictionary of results. dict: A result dictionary Raises: QCGPUSimulatorError: If the number of qubits is too large, or another error occurs during execution. """ self._number_of_qubits = experiment.header.n_qubits self._statevector = 0 start = time.time() try: sim = qcgpu.State(self._number_of_qubits) except OverflowError: raise QCGPUSimulatorError('too many qubits') for operation in experiment.instructions: name = operation.name qubits = operation.qubits params = [ float(param) for param in getattr(operation, 'params', []) ] if name == 'id': logger.info('Identity gates are ignored.') elif name == 'barrier': logger.info('Barrier gates are ignored.') elif name == 'u3': sim.u(qubits[0], *params) elif name == 'u2': sim.u2(qubits[0], *params) elif name == 'u1': sim.u1(qubits[0], *params) elif name == 'cx': sim.cx(*qubits) elif name == 'h': sim.h(qubits[0]) elif name == 'x': sim.x(qubits[0]) elif name == 'y': sim.y(qubits[0]) elif name == 'z': sim.z(qubits[0]) elif name == 's': sim.s(qubits[0]) elif name == 't': sim.t(qubits[0]) amps = [ complex(z) for z in sim.amplitudes().round(self._chop_threshold) ] end = time.time() # amps = np.stack((amps.real, amps.imag), axis=-1) return ExperimentResult(shots=1, success=True, data=ExperimentResultData(statevector=amps), time_taken=(end - start))