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))
Exemplo n.º 2
0
    def setUp(self):
        """
        Setup internal variables and a fake simulation. Aer is used to get the
        structure of the qiskit.Result. The IQ data is generated using gaussian
        random number generators.
        """
        self.shots = 52
        self.qubits = [0, 1]

        meas_cal, _ = circuits.tensored_meas_cal([[0], [1]])

        backend = Aer.get_backend('qasm_simulator')
        job = qiskit.execute(meas_cal,
                             backend=backend,
                             shots=self.shots,
                             meas_level=1)

        self.cal_results = job.result()

        i0, q0, i1, q1 = 0., -1., 0., 1.
        ground = utils.create_shots(i0, q0, 0.1, 0.1, self.shots, self.qubits)
        excited = utils.create_shots(i1, q1, 0.1, 0.1, self.shots, self.qubits)

        self.cal_results.results[0].meas_level = 1
        self.cal_results.results[1].meas_level = 1
        self.cal_results.results[0].data = ExperimentResultData(memory=ground)
        self.cal_results.results[1].data = ExperimentResultData(memory=excited)
Exemplo n.º 3
0
 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)
Exemplo n.º 4
0
    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))
Exemplo n.º 5
0
    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
Exemplo n.º 6
0
    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 backendresult_to_qiskit_resultdata(
    res: BackendResult,
    header: "QobjExperimentHeader",
    final_map: Optional[Dict[UnitID, UnitID]],
) -> ExperimentResultData:
    data: Dict[str, Any] = dict()
    if res.contains_state_results:
        qbits = (
            _gen_uids(header.qreg_sizes, Qubit) if hasattr(header, "qreg_sizes") else []
        )
        if final_map:
            qbits = [final_map[q] for q in qbits]
        stored_res = res.get_result(qbits)
        if stored_res.state is not None:
            data["statevector"] = stored_res.state
        if stored_res.unitary is not None:
            data["unitary"] = stored_res.unitary
    if res.contains_measured_results:
        cbits = (
            _gen_uids(header.creg_sizes, Bit) if hasattr(header, "creg_sizes") else []
        )
        if final_map:
            cbits = [final_map[c] for c in cbits]
        stored_res = res.get_result(cbits)
        if stored_res.shots is not None:
            data["memory"] = [hex(i) for i in stored_res.shots.to_intlist()]
            data["counts"] = dict(Counter(data["memory"]))
        elif stored_res.counts is not None:
            data["counts"] = {
                hex(i.to_intlist()[0]): f for i, f in stored_res.counts.items()
            }
    return ExperimentResultData(**data)
Exemplo n.º 8
0
    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))
Exemplo n.º 9
0
    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))
Exemplo n.º 10
0
    def test_apply(self):
        """
        Set-up a discriminator based on simulated data, train it and then
        discriminate the calibration data.
        """
        meas_cal, _ = circuits.tensored_meas_cal([[0], [1]])

        backend = Aer.get_backend('qasm_simulator')
        job = qiskit.execute(meas_cal,
                             backend=backend,
                             shots=self.shots,
                             meas_level=1)

        cal_results = job.result()

        i0, q0, i1, q1 = 0., -1., 0., 1.
        ground = utils.create_shots(i0, q0, 0.1, 0.1, self.shots, self.qubits)
        excited = utils.create_shots(i1, q1, 0.1, 0.1, self.shots, self.qubits)

        cal_results.results[0].meas_level = 1
        cal_results.results[1].meas_level = 1
        cal_results.results[0].data = ExperimentResultData(memory=ground)
        cal_results.results[1].data = ExperimentResultData(memory=excited)

        discriminator = LinearIQDiscriminator(cal_results, self.qubits,
                                              ['00', '11'])

        d_filter = DiscriminationFilter(discriminator)

        self.assertEqual(cal_results.results[0].meas_level, 1)
        new_results = d_filter.apply(cal_results)

        self.assertEqual(new_results.results[0].meas_level, 2)

        counts_00 = new_results.results[0].data.counts.to_dict()['0x0']
        counts_11 = new_results.results[1].data.counts.to_dict()['0x3']

        self.assertEqual(counts_00, self.shots)
        self.assertEqual(counts_11, self.shots)
Exemplo n.º 11
0
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
Exemplo n.º 12
0
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),
    )
Exemplo n.º 13
0
    def apply(self, raw_data: Result) -> Result:
        """
        Create a new result from the raw_data by converting level 1 data to
        level 2 data.

        Args:
            raw_data: list of qiskit.Result or qiskit.Result.

        Returns:
            A list of qiskit.Result or qiskit.Result.
        """
        new_results = deepcopy(raw_data)

        to_be_discriminated = []

        # Extract all the meas level 1 data from the Result.
        shots_per_experiment_result = []
        for result in new_results.results:
            if result.meas_level == 1:
                shots_per_experiment_result.append(result.shots)
                to_be_discriminated.append(result)

        new_results.results = to_be_discriminated

        x_data = self.discriminator.get_xdata(new_results, 2)
        y_data = self.discriminator.discriminate(x_data)

        start = 0
        for idx, n_shots in enumerate(shots_per_experiment_result):
            memory = y_data[start:(start + n_shots)]
            counts = Obj.from_dict(self.count(memory))
            new_results.results[idx].data = ExperimentResultData(counts=counts,
                                                                 memory=memory)
            start += n_shots

        for result in new_results.results:
            result.meas_level = 2

        return new_results
 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
Exemplo n.º 15
0
    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)
Exemplo n.º 16
0
    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 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))
Exemplo n.º 18
0
    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()
Exemplo n.º 19
0
    def _process_job_result(self, job_result:Result, batch:Batch) -> Dict[str, Result]:
        """Post-process the job result corresponding to a batch. Recreate the single results by adding up the shots of multiple executions

        Args:
            job_result (Result)
            batch (Batch): corresponding batch to the job_result

        Returns:
            Dict[str, Result]: Maps the keys of the initial QuantumExecutionJobs to their Results
        """
        results = {}
        exp_number = 0
        # get the Result as dict and delete the results 
        result_dict = job_result.to_dict()

        index = batch.batch_number
        backend_name = batch.backend_name
        try:
            previous_key = self._previous_key[backend_name]
            previous_memory = self._previous_memory[backend_name]
            previous_counts = self._previous_counts[backend_name]
        except KeyError:
            previous_key = None
            previous_memory = None
            previous_counts = None
        
        self._log.info(f"Process result of job {index}")

        for exp in batch.experiments:
            key = exp["key"]
            circ = exp["circuit"]
            reps = exp["reps"]
            shots = exp["shots"]
            total_shots = exp["total_shots"]
            memory = []
            counts = {}
            result_data = None

            

            if previous_memory:
                # there is data from the previous job
                assert(previous_key==key)
                memory.extend(previous_memory)
                counts.update(previous_counts)
                shots += len(previous_memory)
                total_shots += len(previous_memory)
                previous_memory = None
                previous_counts = None
                previous_key = None
            
            # get ExperimentResult as dict
            job_exp_result_dict = job_result._get_experiment(exp_number).to_dict() 

            if not (shots == total_shots and reps == 1 and len(memory) == 0):
                # do not run this block if it is only one experiment (shots == total_shots) with one repetition and no previous data is available
                for exp_index in range(exp_number, exp_number+reps):
                    mem = job_result.data(exp_index)['memory']
                    memory.extend(mem)
                    cnts = job_result.data(exp_index)['counts']
                    
                    if exp_index == exp_number+reps-1 and shots == total_shots:
                        # last experiment for this circuit
                        if len(memory) > total_shots:
                            # trim memory and counts w.r.t. number of shots
                            too_much = len(memory) - total_shots
                            memory = memory[:total_shots]
                            mem = mem[:-too_much]
                            cnts = dict(Counter(mem))

                    counts = self._add_dicts(counts, cnts)
                
                if shots < total_shots:
                    previous_memory = copy.deepcopy(memory)
                    previous_counts = copy.deepcopy(counts)
                    previous_key = key
                    continue
                if self._memory:
                    result_data = ExperimentResultData(counts=counts, memory=memory).to_dict()
                else:
                    result_data = ExperimentResultData(counts=counts).to_dict()

                # overwrite the data and the shots
                job_exp_result_dict["data"] = result_data
                job_exp_result_dict["shots"] = total_shots

            else:
                if not self._memory:
                    counts = job_result.data(exp_number)['counts']
                    result_data = ExperimentResultData(counts=counts).to_dict()
                    job_exp_result_dict["data"] = result_data

            # overwrite the results with the computed result
            result_dict["results"] = [job_exp_result_dict]
            results[key] = Result.from_dict(result_dict)
            exp_number += reps
        self._previous_key[backend_name] = previous_key
        self._previous_memory[backend_name] = previous_memory
        self._previous_counts[backend_name] = previous_counts
        return results
Exemplo n.º 20
0
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