Beispiel #1
0
    def test_counts_no_header(self):
        """Test that counts are extracted properly without header."""
        raw_counts = {'0x0': 4, '0x2': 10}
        no_header_processed_counts = {
            bin(int(bs[2:], 16))[2:]: counts
            for (bs, counts) in raw_counts.items()
        }
        data = models.ExperimentResultData(counts=base.Obj(**raw_counts))
        exp_result = models.ExperimentResult(shots=14,
                                             success=True,
                                             meas_level=2,
                                             data=data)
        result = Result(results=[exp_result], **self.base_result_args)

        self.assertEqual(result.get_counts(0), no_header_processed_counts)
Beispiel #2
0
    def test_memory_counts_no_header(self):
        """Test that memory bitstrings are extracted properly without header."""
        raw_memory = ['0x0', '0x0', '0x2', '0x2', '0x2', '0x2', '0x2']
        no_header_processed_memory = [
            bin(int(bs[2:], 16))[2:] for bs in raw_memory
        ]
        data = models.ExperimentResultData(memory=raw_memory)
        exp_result = models.ExperimentResult(shots=14,
                                             success=True,
                                             meas_level=2,
                                             memory=True,
                                             data=data)
        result = Result(results=[exp_result], **self.base_result_args)

        self.assertEqual(result.get_memory(0), no_header_processed_memory)
Beispiel #3
0
    def test_memory_int_out(self):
        """Test that memory bitstrings are extracted properly without header."""
        raw_memory = ["0x0", "0x0", "0x2", "0x2", "0x2", "0x2", "0x2"]
        data = models.ExperimentResultData(memory=raw_memory)
        exp_result = models.ExperimentResult(shots=14,
                                             success=True,
                                             meas_level=2,
                                             memory=True,
                                             data=data)
        result = Result(results=[exp_result], **self.base_result_args)

        with self.assertRaises(Exception) as context:
            result.get_memory(99)
        self.assertEqual('Result for experiment "99" could not be found.',
                         context.exception.message)
Beispiel #4
0
    def _compute_phases(
            self, num_unitary_qubits: int, circuit_result: Result
    ) -> Union[numpy.ndarray, qiskit.result.Counts]:
        """Compute frequencies/counts of phases from the result of running the QPE circuit.

        How the frequencies are computed depends on whether the backend computes amplitude or
        samples outcomes.

        1) If the backend is a statevector simulator, then the reduced density matrix of the
        phase-reading register is computed from the combined phase-reading- and input-state
        registers. The elements of the diagonal :math:`(i, i)` give the probability to measure the
        each of the states `i`. The index `i` expressed as a binary integer with the LSB rightmost
        gives the state of the phase-reading register with the LSB leftmost when interpreted as a
        phase. In order to maintain the compact representation, the phases are maintained as decimal
        integers.  They may be converted to other forms via the results object,
        `PhaseEstimationResult` or `HamiltonianPhaseEstimationResult`.

         2) If the backend samples bitstrings, then the counts are first retrieved as a dict.  The
        binary strings (the keys) are then reversed so that the LSB is rightmost and the counts are
        converted to frequencies. Then the keys are sorted according to increasing phase, so that
        they can be easily understood when displaying or plotting a histogram.

        Args:
            num_unitary_qubits: The number of qubits in the unitary.
            circuit_result: the result object returned by the backend that ran the QPE circuit.

        Returns:
            Either a dict or numpy.ndarray representing the frequencies of the phases.

        """
        if self._quantum_instance.is_statevector:
            state_vec = circuit_result.get_statevector()
            evaluation_density_matrix = qiskit.quantum_info.partial_trace(
                state_vec,
                range(self._num_evaluation_qubits,
                      self._num_evaluation_qubits + num_unitary_qubits))
            phases = evaluation_density_matrix.probabilities()
        else:
            # return counts with keys sorted numerically
            num_shots = circuit_result.results[0].shots
            counts = circuit_result.get_counts()
            phases = {k[::-1]: counts[k] / num_shots for k in counts.keys()}
            phases = _sort_phases(phases)
            phases = qiskit.result.Counts(phases,
                                          memory_slots=counts.memory_slots,
                                          creg_sizes=counts.creg_sizes)

        return phases
Beispiel #5
0
    def _set_result(self, raw_data: Optional[Dict]) -> None:
        """Set the job result.

        Args:
            raw_data: Raw result data.

        Raises:
            IBMQJobInvalidStateError: If result is in an unsupported format.
            IBMQJobApiError: If an unexpected error occurred when communicating
                with the server.
        """
        if raw_data is None:
            self._result = None
            return
        raw_data['client_version'] = self.client_version
        decode_result(raw_data)
        try:
            self._result = Result.from_dict(raw_data)
        except (KeyError, TypeError) as err:
            if not self._kind:
                raise IBMQJobInvalidStateError(
                    'Unable to retrieve result for job {}. Job result '
                    'is in an unsupported format.'.format(
                        self.job_id())) from err
            raise IBMQJobApiError('Unable to retrieve result for '
                                  'job {}: {}'.format(self.job_id(),
                                                      str(err))) from err
Beispiel #6
0
    def result(self,
               timeout: Optional[float] = None,
               wait: float = 0.5) -> Result:
        """

        Args:
            timeout: Timeout in seconds.
            wait: Wait time between queries to the quantum-inspire platform.

        Returns:
            Result object containing results from the experiments.

        Raises:
            JobTimeoutError: If timeout is reached.
            QisKitBackendError: If an error occurs during simulation.
        """
        start_time = time.time()
        while self.status() != JobStatus.DONE:
            elapsed_time = time.time() - start_time
            if timeout is not None and elapsed_time > timeout:
                raise JobTimeoutError(
                    'Failed getting result: timeout reached.')
            time.sleep(wait)
        experiment_results = self._backend.get_experiment_results(self)
        return Result(backend_name=self._backend.backend_name,
                      backend_version=quantum_inspire_version,
                      job_id=self.job_id(),
                      qobj_id=self.job_id(),
                      success=True,
                      results=experiment_results)
Beispiel #7
0
    def _run_job(self, job_id, qobj):
        """Run experiments in qobj.

        Args:
            job_id (str): unique id for the job.
            qobj (Qobj): job description

        Returns:
            Result: Result object
        """
        self._validate(qobj)
        result_list = []
        start = time.time()
        for experiment in qobj.experiments:
            result_list.append(self.run_experiment(experiment))
        end = time.time()
        result = {
            "backend_name": self.name(),
            "backend_version": self._configuration.backend_version,
            "qobj_id": qobj.qobj_id,
            "job_id": job_id,
            "results": result_list,
            "status": "COMPLETED",
            "success": True,
            "time_taken": (end - start),
            "header": qobj.header.to_dict(),
        }

        return Result.from_dict(result)
Beispiel #8
0
    def test_zz_fitter(self):
        """
        Test ZZ fitter in Ignis characterization

        This test relies on static data stored in the file zz_data.json.
        To generate zz_data.json, run 'python generate_data.py zz'.
        """

        with open(os.path.join(os.path.dirname(__file__), 'zz_data.json'),
                  'r') as handle:
            data = json.load(handle)

        fit = ZZFitter(Result.from_dict(data['backend_result']),
                       data['xdata'],
                       data['qubits'],
                       data['spectators'],
                       fit_p0=[0.5, data['omega'], 0, 0.5],
                       fit_bounds=([-0.5, 0, -np.pi, -0.5],
                                   [1.5, 2 * data['omega'], np.pi, 1.5]))

        self.assertEqual(fit.series, ['0', '1'])
        self.assertEqual(sorted(list(fit.params.keys())), ['0', '1'])

        num_of_qubits = len(data['qubits'])
        self.assertEqual(len(fit.params['0']), num_of_qubits)
        self.assertEqual(len(fit.params_err['0']), num_of_qubits)

        self.assertTrue(
            np.isclose(fit.ZZ_rate(), data['zz'], rtol=0.3, atol=0.1))
Beispiel #9
0
    def _run_job(self, job_id, run_input, data, qobj_id, qobj_header,
                 **options):
        """Run experiments in run_input
        Args:
            job_id (str): unique id for the job.
            run_input (QuantumCircuit or Schedule or list): job description
        Returns:
            Result: Result object
        """
        start = time.time()

        self._data = data

        experiments = run_input.experiments if hasattr(run_input,
                                                       'config') else run_input
        if isinstance(experiments, QuantumCircuit):
            experiments = [experiments]
        results = []

        for experiment in experiments:
            results.append(self.run_experiment(experiment, **options))

        return Result(backend_name=self.name(),
                      backend_version=self._configuration.backend_version,
                      qobj_id=qobj_id,
                      job_id=job_id,
                      success=True,
                      results=results,
                      date=datetime.now(),
                      status='COMPLETED',
                      header=qobj_header,
                      time_taken=(time.time() - start))
Beispiel #10
0
    def test_marginal_counts_result_format(self):
        """Test that marginal_counts with format_marginal true properly formats output."""
        raw_counts_1 = {'0x0': 4, '0x1': 7, '0x2': 10, '0x6': 5, '0x9': 11, '0xD': 9, '0x12': 8}
        data_1 = models.ExperimentResultData(counts=dict(**raw_counts_1))
        exp_result_header_1 = QobjExperimentHeader(creg_sizes=[['c0', 2], ['c1', 3]],
                                                   memory_slots=5)
        exp_result_1 = models.ExperimentResult(shots=54, success=True, data=data_1,
                                               header=exp_result_header_1)

        result = Result(results=[exp_result_1], **self.base_result_args)

        expected_marginal_counts_1 = {'0_0 _0': 14, '0_0 _1': 18,
                                      '0_1 _0': 5, '0_1 _1': 9, '1_0 _0': 8}
        marginal_counts_result = marginal_counts(result.get_counts(), [0, 2, 4],
                                                 format_marginal=True)
        self.assertEqual(marginal_counts_result, expected_marginal_counts_1)
Beispiel #11
0
    def run_job(self, job_id, qobj):
        """Main dummy run loop"""
        del qobj  # unused
        time.sleep(self.time_alive)

        return Result.from_dict(
            {'job_id': job_id, 'result': [], 'status': 'COMPLETED'})
    def run(self, run_input, **options):
        """
        Run the Tphi backend
        """
        self.options.update_options(**options)
        shots = 1000
        t1_circuits = []
        t2ramsey_circuits = []
        for circ in run_input:
            if circ.metadata["composite_metadata"][0]["experiment_type"] == "T1":
                t1_circuits.append(circ)
            elif circ.metadata["composite_metadata"][0]["experiment_type"] == "T2Ramsey":
                t2ramsey_circuits.append(circ)
            else:
                raise ValueError("Illegal name for circuit in Tphi")

        job_t1 = self._internal_backends["T1"].run(run_input=t1_circuits, shots=shots)
        job_t2ramsey = self._internal_backends["T2*"].run(run_input=t2ramsey_circuits, shots=shots)
        final_results = job_t1.result().results + job_t2ramsey.result().results
        result_for_fake = Result(
            backend_name="Tphi backend",
            backend_version="0",
            qobj_id="0",
            job_id="0",
            success=True,
            results=final_results,
            status="JobStatus.DONE",
        )
        return FakeJob(self, result_for_fake)
Beispiel #13
0
    def _run(self, qobj, job_id=''):
        """Run a job"""
        # Start timer
        start = time.time()

        # Run simulation
        output = self._execute(qobj)

        # Validate output
        if not isinstance(output, dict):
            logger.error("%s: simulation failed.", self.name())
            if output:
                logger.error('Output: %s', output)
            raise AerError(
                "simulation terminated without returning valid output.")

        # Format results
        output["job_id"] = job_id
        output["date"] = datetime.datetime.now().isoformat()
        output["backend_name"] = self.name()
        output["backend_version"] = self.configuration().backend_version

        # Add execution time
        output["time_taken"] = time.time() - start

        # Display warning if simulation failed
        if not output.get("success", False):
            msg = "Simulation failed"
            if "status" in output:
                msg += f" and returned the following error message:\n{output['status']}"
            logger.warning(msg)

        return Result.from_dict(output)
Beispiel #14
0
    def _set_result(self, raw_data: Optional[Dict]) -> None:
        """Set the job result.

        Args:
            raw_data: Raw result data.

        Raises:
            IBMQJobInvalidStateError: If result is in an unsupported format.
            IBMQJobApiError: If an unexpected error occurred when communicating
                with the server.
        """
        if raw_data is None:
            self._result = None
            return
        raw_data['client_version'] = self.client_version
        # TODO Stop checking Terra version when it's released.
        from qiskit.version import __version__ as terra_version
        if terra_version >= '0.15.0':
            decode_result(raw_data)
        # if 'date' in raw_data:
        #     raw_data['date'] = utc_to_local(raw_data['date'])
        try:
            self._result = Result.from_dict(raw_data)
            if hasattr(self._result, 'date'):
                self._result.date = utc_to_local(self._result.date)
        except (KeyError, TypeError) as err:
            if not self._kind:
                raise IBMQJobInvalidStateError(
                    'Unable to retrieve result for job {}. Job result '
                    'is in an unsupported format.'.format(
                        self.job_id())) from err
            raise IBMQJobApiError('Unable to retrieve result for '
                                  'job {}: {}'.format(self.job_id(),
                                                      str(err))) from err
 def test_circuit_unitary_repr_decimal(self):
     """Test postprocessing of unitary giving decimals arg."""
     raw_unitary = np.array(
         [[0.70710678 + 0.00000000e+00j, 0.70710678 - 8.65956056e-17j],
          [0.70710678 + 0.00000000e+00j, -0.70710678 + 8.65956056e-17j]],
         dtype=np.complex_)
     processed_unitary = np.array(
         [[0.707 + 0.j, 0.707 - 0.j], [0.707 + 0.j, -0.707 + 0.j]],
         dtype=np.complex_)
     data = models.ExperimentResultData(unitary=raw_unitary)
     exp_result = models.ExperimentResult(shots=1, success=True, data=data)
     result = Result(results=[exp_result], **self.base_result_args)
     unitary = result.get_unitary(decimals=3)
     self.assertEqual(unitary.shape, (2, 2))
     self.assertEqual(unitary.dtype, np.complex_)
     np.testing.assert_almost_equal(unitary, processed_unitary)
Beispiel #16
0
    def test_meas_level_0_avg(self):
        """Test measurement level 0 average result."""
        # 3 qubits
        raw_memory = [[[0., 1.], [0., 1.], [0., 1.]],
                      [[1., 0.], [1., 0.], [1., 0.]]]
        processed_memory = np.array([[1.j, 1.j, 1.j],
                                     [1., 1., 1.]], dtype=np.complex_)
        data = models.ExperimentResultData(memory=raw_memory)
        exp_result = models.ExperimentResult(shots=2, success=True, meas_level=0,
                                             meas_return='avg', data=data)
        result = Result(results=[exp_result], **self.base_result_args)
        memory = result.get_memory(0)

        self.assertEqual(memory.shape, (2, 3))
        self.assertEqual(memory.dtype, np.complex_)
        np.testing.assert_almost_equal(memory, processed_memory)
Beispiel #17
0
    def _get_job_result(self, circ_count, has_metadata=False):
        """Return a job result with random counts."""
        job_result = {
            "backend_name": self.backend.name(),
            "backend_version": "1.1.1",
            "qobj_id": "1234",
            "job_id": "some_job_id",
            "success": True,
            "results": [],
        }
        circ_result_template = {"shots": 1024, "success": True, "data": {}}

        for _ in range(circ_count):
            counts = randrange(1024)
            circ_result = copy.copy(circ_result_template)
            circ_result["data"] = {
                "counts": {
                    "0x0": counts,
                    "0x3": 1024 - counts
                }
            }
            if has_metadata:
                circ_result["header"] = {"metadata": {"meas_basis": "pauli"}}
            job_result["results"].append(circ_result)

        return Result.from_dict(job_result)
Beispiel #18
0
 def test_circuit_statevector_repr_decimal(self):
     """Test postprocessing of statevector giving decimals arg."""
     raw_statevector = np.array(
         [0.35355339 + 0.j, 0.35355339 + 0.j, 0.35355339 + 0.j, 0.35355339 + 0.j,
          0.35355339 + 0.j, 0.35355339 + 0.j, 0.35355339 + 0.j, 0.35355339 + 0.j],
         dtype=np.complex_)
     processed_sv = np.array(
         [0.354 + 0.j, 0.354 + 0.j, 0.354 + 0.j, 0.354 + 0.j, 0.354 + 0.j, 0.354 + 0.j,
          0.354 + 0.j, 0.354 + 0.j], dtype=np.complex_)
     data = models.ExperimentResultData(statevector=raw_statevector)
     exp_result = models.ExperimentResult(shots=1, success=True, data=data)
     result = Result(results=[exp_result], **self.base_result_args)
     statevector = result.get_statevector(decimals=3)
     self.assertEqual(statevector.shape, (8,))
     self.assertEqual(statevector.dtype, np.complex_)
     np.testing.assert_almost_equal(statevector, processed_sv)
    def _process_results(self):
        """Convert Honeywell job result to qiskit.Result"""
        results = []
        self._status = JobStatus.DONE
        for i, res_resp in enumerate(self._experiment_results):
            status = res_resp.get('status', 'failed')
            if status == 'failed':
                self._status = JobStatus.ERROR
            res = res_resp['results']
            counts = dict(Counter(hex(int("".join(r), 2)) for r in [*zip(*list(res.values()))]))

            experiment_result = {
                'shots': self._qobj_payload.get('config', {}).get('shots', 1),
                'success': ApiJobStatus(status) is ApiJobStatus.COMPLETED,
                'data': {'counts': counts},
                'header': self._qobj_payload[
                    'experiments'][i]['header'] if self._qobj_payload else {},
                'job_id': self._job_ids[i]
            }
            results.append(experiment_result)

        result = {
            'success': self._status is JobStatus.DONE,
            'job_id': self._job_id,
            'results': results,
            'backend_name': self._backend.name(),
            'backend_version': self._backend.status().backend_version,
            'qobj_id': self._job_id
        }
        return Result.from_dict(result)
Beispiel #20
0
def _qlm_to_qiskit_result(backend_name, backend_version, qobj_id, job_id,
                          success, qlm_results, metadata, qobj_header):
    """
    Tranform a QLM result into a Qiskit result structure.

    Args:
        backend_name:
        backend_version:
        qobj_id:
        job_id:
        success:
        qlm_results: List of qat.core.wrappers.Result objects
        metadata: List of the circuit's metadata
        qobj_header: user input that will be in the Result

    Returns:
        A qiskit Result structure.
    """
    return Result(
        backend_name=backend_name,
        backend_version=backend_version,
        qobj_id=qobj_id,
        job_id=job_id,
        success=success,
        results=[
            _generate_experiment_result(result, md)
            for result, md in zip(qlm_results, metadata)
        ],
        header=qobj_header,
    )
Beispiel #21
0
    def result(self):
        result = self._wait_for_result()
        results = [{
            'success': True,
            'shots': len(result['samples']),
            'data': {
                'counts': self._format_counts(result['samples'])
            },
            'header': {
                'memory_slots': self.qobj.config.memory_slots,
                'name': self.qobj.experiments[0].header.name
            }
        }]

        return Result.from_dict({
            'results':
            results,
            'backend_name':
            self._backend._configuration.backend_name,
            'backend_version':
            self._backend._configuration.backend_version,
            'qobj_id':
            self.qobj.qobj_id,
            'success':
            True,
            'job_id':
            self._job_id,
        })
Beispiel #22
0
    def test_t2star_fitter(self):
        """
        Test T2* fitter in Ignis characterization

        This test relies on static data stored in the file t2star_data.json.
        To generate t2star_data.json, run 'python generate_data.py t2star'.
        """

        with open(os.path.join(os.path.dirname(__file__), 't2star_data.json'),
                  'r') as handle:
            data = json.load(handle)

        fit = T2StarFitter(
            Result.from_dict(data['backend_result']),
            data['xdata'],
            data['qubits'],
            fit_p0=[0.5, data['t2'], data['omega'], 0, 0.5],
            fit_bounds=([-0.5, 0, data['omega'] - 0.02, -np.pi, -0.5], [
                1.5, data['t2'] * 1.2, data['omega'] + 0.02, np.pi, 1.5
            ]))

        self.assertEqual(fit.series, ['0'])
        self.assertEqual(list(fit.params.keys()), ['0'])

        num_of_qubits = len(data['qubits'])
        self.assertEqual(len(fit.params['0']), num_of_qubits)
        self.assertEqual(len(fit.params_err['0']), num_of_qubits)

        for qubit in range(num_of_qubits):
            self.assertTrue(
                np.allclose(fit.params['0'][qubit],
                            [0.5, data['t2'], data['omega'], 0, 0.5],
                            rtol=0.3,
                            atol=0.1))
Beispiel #23
0
def calibration_data(
        result: Result,
        metadata: List[Dict[str,
                            any]]) -> Tuple[Dict[int, Dict[int, int]], int]:
    """Return FullMeasureErrorMitigator from result data.

    Args:
        result: Qiskit result object.
        metadata: mitigation generator metadata.

    Returns:
        Calibration data dictionary {label: Counts} and number of qubits.
    """
    # Filter mitigation calibration data
    cal_data = {}
    num_qubits = None
    method = None
    for i, meta in enumerate(metadata):
        if meta.get('experiment') == 'meas_mit':
            if num_qubits is None:
                num_qubits = len(meta['cal'])
            if method is None:
                method = meta.get('method', None)
            key = int(meta['cal'], 2)
            counts = result.get_counts(i).int_outcomes()
            if key not in cal_data:
                cal_data[key] = counts
            else:
                cal_data[key] = combine_counts(cal_data[key], counts)
    return cal_data, num_qubits, method
Beispiel #24
0
    def object_hook(self, obj: Any) -> Any:
        """Called to decode object."""
        if '__type__' in obj:
            obj_type = obj['__type__']
            obj_val = obj['__value__']

            if obj_type == 'complex':
                return obj_val[0] + 1j * obj_val[1]
            if obj_type == 'ndarray':
                return _decode_and_deserialize(obj_val, np.load)
            if obj_type == 'set':
                return set(obj_val)
            if obj_type == 'QuantumCircuit':
                return _decode_and_deserialize(obj_val,
                                               qpy_serialization.load)[0]
            if obj_type == 'ParameterExpression':
                return _decode_and_deserialize(
                    obj_val, qpy_serialization._read_parameter_expression,
                    False)
            if obj_type == 'Instruction':
                return _decode_and_deserialize(
                    obj_val, qpy_serialization._read_instruction, False)
            if obj_type == 'settings':
                return deserialize_from_settings(mod_name=obj['__module__'],
                                                 class_name=obj['__class__'],
                                                 settings=obj_val)
            if obj_type == 'Result':
                return Result.from_dict(obj_val)
            if obj_type == 'spmatrix':
                return _decode_and_deserialize(obj_val, scipy.sparse.load_npz,
                                               False)
            if obj_type == 'to_json':
                return obj_val
        return obj
Beispiel #25
0
    def __init__(
            self,
            backend: 'ibmqbackend.IBMQBackend',
            api: AccountClient,
            job_id: str,
            creation_date: str,
            status: str,
            kind: Optional[str] = None,
            name: Optional[str] = None,
            time_per_step: Optional[dict] = None,
            result: Optional[dict] = None,
            qobj: Optional[Union[dict, QasmQobj, PulseQobj]] = None,
            error: Optional[dict] = None,
            tags: Optional[List[str]] = None,
            run_mode: Optional[str] = None,
            **kwargs: Any
    ) -> None:
        """IBMQJob constructor.

        Args:
            backend: The backend instance used to run this job.
            api: Object for connecting to the server.
            job_id: Job ID.
            creation_date: Job creation date.
            status: Job status returned by the server.
            kind: Job type.
            name: Job name.
            time_per_step: Time spent for each processing step.
            result: Job result.
            qobj: Qobj for this job.
            error: Job error.
            tags: Job tags.
            run_mode: Scheduling mode the job runs in.
            kwargs: Additional job attributes.
        """
        self._backend = backend
        self._api = api
        self._job_id = job_id
        self._creation_date = dateutil.parser.isoparse(creation_date)
        self._api_status = status
        self._kind = ApiJobKind(kind) if kind else None
        self._name = name
        self._time_per_step = time_per_step
        self._result = Result.from_dict(result) if result else None
        if isinstance(qobj, dict):
            qobj = dict_to_qobj(qobj)
        self._qobj = qobj
        self._error = error
        self._tags = tags or []
        self._run_mode = run_mode
        self._status, self._queue_info = \
            self._get_status_position(status, kwargs.pop('info_queue', None))
        self._use_object_storage = (self._kind == ApiJobKind.QOBJECT_STORAGE)

        SimpleNamespace.__init__(self, **kwargs)
        BaseJob.__init__(self, self.backend(), self.job_id())

        # Properties used for caching.
        self._cancelled = False
        self._job_error_msg = None  # type: Optional[str]
    def test_marginal_counts_result_creg_sizes(self):
        """Test that marginal_counts with Result input properly changes creg_sizes."""
        raw_counts = {
            "0x0": 4,
            "0x1": 7,
            "0x2": 10,
            "0x6": 5,
            "0x9": 11,
            "0xD": 9,
            "0xE": 8
        }
        data = models.ExperimentResultData(counts=dict(**raw_counts))
        exp_result_header = QobjExperimentHeader(creg_sizes=[["c0", 1],
                                                             ["c1", 3]],
                                                 memory_slots=4)
        exp_result = models.ExperimentResult(shots=54,
                                             success=True,
                                             data=data,
                                             header=exp_result_header)

        result = Result(results=[exp_result], **self.base_result_args)

        expected_marginal_counts = {"0 0": 14, "0 1": 18, "1 0": 13, "1 1": 9}
        expected_creg_sizes = [["c0", 1], ["c1", 1]]
        expected_memory_slots = 2
        marginal_counts_result = marginal_counts(result, [0, 2])
        self.assertEqual(marginal_counts_result.results[0].header.creg_sizes,
                         expected_creg_sizes)
        self.assertEqual(marginal_counts_result.results[0].header.memory_slots,
                         expected_memory_slots)
        self.assertEqual(marginal_counts_result.get_counts(0),
                         expected_marginal_counts)
Beispiel #27
0
    def test_coder(self):
        """Test runtime encoder and decoder."""
        result = Result(backend_name='ibmqx2',
                        backend_version='1.1',
                        qobj_id='12345',
                        job_id='67890',
                        success=False,
                        results=[])

        data = {
            "string": "foo",
            "float": 1.5,
            "complex": 2 + 3j,
            "array": np.array([[1, 2, 3], [4, 5, 6]]),
            "result": result,
            "sclass": SerializableClass("foo"),
        }
        encoded = json.dumps(data, cls=RuntimeEncoder)
        decoded = json.loads(encoded, cls=RuntimeDecoder)
        decoded["sclass"] = SerializableClass.from_json(decoded['sclass'])

        decoded_result = decoded.pop('result')
        data.pop('result')

        decoded_array = decoded.pop('array')
        orig_array = data.pop('array')

        self.assertEqual(decoded, data)
        self.assertIsInstance(decoded_result, Result)
        self.assertTrue((decoded_array == orig_array).all())
    def test_marginal_counts_no_cregs(self):
        """Test that marginal_counts without cregs See qiskit-terra/6430."""
        raw_counts_1 = {
            "0x0": 4,
            "0x1": 7,
            "0x2": 10,
            "0x6": 5,
            "0x9": 11,
            "0xD": 9,
            "0x12": 8
        }
        data_1 = models.ExperimentResultData(counts=dict(**raw_counts_1))
        exp_result_header_1 = QobjExperimentHeader(memory_slots=5)
        exp_result_1 = models.ExperimentResult(shots=54,
                                               success=True,
                                               data=data_1,
                                               header=exp_result_header_1)

        result = Result(results=[exp_result_1], **self.base_result_args)

        _ = marginal_counts(result, indices=[0])
        marginal_counts_result = marginal_counts(result, indices=[0])
        self.assertEqual(marginal_counts_result.get_counts(), {
            "0": 27,
            "1": 27
        })
    def _run_job(self, job_id, qobj):
        """Run experiments in qobj.

        Args:
            job_id (str): unique id for the job.
            qobj (Qobj): job description

        Returns:
            Result: Result object
        """
        self._validate(qobj)
        result_list = []
        start = time.time()
        for experiment in qobj.experiments:
            result_list.append(self.run_experiment(experiment))
        end = time.time()
        result = {'backend_name': self.name(),
                  'backend_version': self._configuration.backend_version,
                  'qobj_id': qobj.qobj_id,
                  'job_id': job_id,
                  'results': result_list,
                  'status': 'COMPLETED',
                  'success': True,
                  'time_taken': (end - start),
                  'header': qobj.header.to_dict()}

        return Result.from_dict(result)
Beispiel #30
0
def _qlm_to_qiskit_result(
        backend_name,
        backend_version,
        qobj_id,
        job_id,
        success,
        qlm_results,
        headers
        ):
    """
    Tranform a QLM result into a Qiskit result structure.

    Args:
        backend_name:
        backend_version:
        qobj_id:
        job_id:
        success:
        qlm_results: List of qat.core.wrappers.Result objects
        headers: List of the experiments' headers

    Returns:
        A qiskit Result structure.
    """
    return Result(
        backend_name=backend_name,
        backend_version=backend_version,
        qobj_id=qobj_id,
        job_id=job_id,
        success=success,
        results=[
            _generate_experiment_result(result, head)
            for result, head in zip(qlm_results, headers)
        ],
    )