Skip to content

Commit

Permalink
Lint
Browse files Browse the repository at this point in the history
  • Loading branch information
wshanks committed Oct 14, 2024
1 parent 79758e4 commit 2e3ab73
Show file tree
Hide file tree
Showing 6 changed files with 42 additions and 29 deletions.
12 changes: 8 additions & 4 deletions qiskit_experiments/framework/experiment_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -319,9 +319,13 @@ def completion_times(self) -> Dict[str, datetime]:
if job is not None:
if hasattr(job, "time_per_step") and "COMPLETED" in job.time_per_step():
job_times[job_id] = job.time_per_step().get("COMPLETED")
elif (execution := job.result().metadata.get("execution")) and "execution_spans" in execution:
elif (
execution := job.result().metadata.get("execution")
) and "execution_spans" in execution:
job_times[job_id] = execution["execution_spans"].stop
elif (client := getattr(job, "_api_client", None)) and hasattr(client, "job_metadata"):
elif (client := getattr(job, "_api_client", None)) and hasattr(
client, "job_metadata"
):
metadata = client.job_metadata(job.job_id())
finished = metadata.get("timestamps", {}).get("finished", {})
if finished:
Expand Down Expand Up @@ -1095,8 +1099,8 @@ def _add_result_data(self, result: Result, job_id: Optional[str] = None) -> None
# to put it back from the circuits themselves.
if "circuit_metadata" in testres.metadata:
data["metadata"] = testres.metadata["circuit_metadata"]
else:
corresponding_pub = job.inputs["pubs"][i]
elif self._jobs[job_id] is not None:
corresponding_pub = self._jobs[job_id].inputs["pubs"][i]
circuit = corresponding_pub[0]
data["metadata"] = circuit.metadata

Expand Down
3 changes: 2 additions & 1 deletion qiskit_experiments/test/fake_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,8 @@ def _default_options(cls):
def target(self) -> Target:
return self._target

def run(self, run_input, shots=100, **options):
def run(self, run_input, **options):
shots = options.get("shots", 100)
if not isinstance(run_input, list):
run_input = [run_input]
results = [
Expand Down
4 changes: 1 addition & 3 deletions qiskit_experiments/test/mock_iq_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -459,9 +459,7 @@ def _generate_data(
run_result["counts"] = counts
if meas_return == "single" or self.options.get("memory"):
run_result["memory"] = [
format(result, "x")
for result, num in enumerate(results)
for _ in range(num)
format(result, "x") for result, num in enumerate(results) for _ in range(num)
]
else:
# Phase has meaning only for IQ shot, so we calculate it here
Expand Down
44 changes: 25 additions & 19 deletions test/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,25 @@
from qiskit.utils.deprecation import deprecate_func
import qiskit_aer.backends.aerbackend

from qiskit_experiments.framework import (
ExperimentDecoder,
ExperimentEncoder,
ExperimentData,
)
from qiskit_experiments.framework.experiment_data import ExperimentStatus
from .extended_equality import is_equivalent

# The imports from here to the next blank line are just for the monkey-patching
# at the end of the file.
# pylint: disable=wrong-import-order,ungrouped-imports
import copy
import math
from dataclasses import dataclass
from typing import Literal
import numpy as np
import qiskit.primitives.backend_sampler_v2
from qiskit.circuit import QuantumCircuit
from qiskit.exceptions import QiskitError
from qiskit.primitives import (
BackendEstimatorV2,
BackendSamplerV2,
Expand All @@ -52,13 +62,7 @@
from qiskit.result import Result
from qiskit_ibm_runtime.fake_provider.local_service import QiskitRuntimeLocalService

from qiskit_experiments.framework import (
ExperimentDecoder,
ExperimentEncoder,
ExperimentData,
)
from qiskit_experiments.framework.experiment_data import ExperimentStatus
from .extended_equality import is_equivalent
# pylint: enable=wrong-import-order,ungrouped-imports


# Workaround until https://github.com/Qiskit/qiskit-aer/pull/2142 is released
Expand Down Expand Up @@ -167,7 +171,6 @@ def setUpClass(cls):
category=UserWarning,
)


# Some functionality may be deprecated in Qiskit Experiments. If
# the deprecation warnings aren't filtered, the tests will fail as
# ``QiskitTestCase`` sets all warnings to be treated as an error by
Expand Down Expand Up @@ -404,7 +407,7 @@ def _patched_run_circuits(


def _patched_run_backend_primitive_v2(
self,
self, # pylint: disable=unused-argument
backend: BackendV1 | BackendV2,
primitive: Literal["sampler", "estimator"],
options: dict,
Expand Down Expand Up @@ -503,15 +506,17 @@ def _patched_run_pubs(self, pubs: list[SamplerPub], shots: int) -> list[SamplerP
memory=True,
shots=shots,
seed_simulator=self._options.seed_simulator,
**run_opts
**run_opts,
)
result_memory = qiskit.primitives.backend_sampler_v2._prepare_memory(results)

# pack memory to an ndarray of uint8
results = []
start = 0
for pub, bound in zip(pubs, bound_circuits):
meas_info, max_num_bytes = qiskit.primitives.backend_sampler_v2._analyze_circuit(pub.circuit)
meas_info, max_num_bytes = qiskit.primitives.backend_sampler_v2._analyze_circuit(
pub.circuit
)
end = start + bound.size
results.append(
self._postprocess_pub(
Expand All @@ -522,35 +527,38 @@ def _patched_run_pubs(self, pubs: list[SamplerPub], shots: int) -> list[SamplerP
max_num_bytes,
pub.circuit.metadata,
meas_level=self._options.meas_level,
meas_return=self._options.meas_return,
)
)
start = end

return results


def _patched_postprocess_pub(
self,
self, # pylint: disable=unused-argument
result_memory: list[list[str]],
shots: int,
shape: tuple[int, ...],
meas_info: list[qiskit.primitives.backend_sampler_v2._MeasureInfo],
max_num_bytes: int,
circuit_metadata: dict,
meas_level: int | None = None,
meas_return: str | None = None,
) -> SamplerPubResult:
"""Converts the memory data into an array of bit arrays with the shape of the pub."""
if meas_level == 2 or meas_level is None:
arrays = {
item.creg_name: np.zeros(shape + (shots, item.num_bytes), dtype=np.uint8)
for item in meas_info
}
memory_array = qiskit.primitives.backend_sampler_v2._memory_array(result_memory, max_num_bytes)
memory_array = qiskit.primitives.backend_sampler_v2._memory_array(
result_memory, max_num_bytes
)

for samples, index in zip(memory_array, np.ndindex(*shape)):
for item in meas_info:
ary = qiskit.primitives.backend_sampler_v2._samples_to_packed_array(samples, item.num_bits, item.start)
ary = qiskit.primitives.backend_sampler_v2._samples_to_packed_array(
samples, item.num_bits, item.start
)
arrays[item.creg_name][index] = ary

meas = {
Expand All @@ -560,9 +568,7 @@ def _patched_postprocess_pub(
raw = np.array(result_memory)
cplx = raw[..., 0] + 1j * raw[..., 1]
cplx = np.reshape(cplx, (*shape, *cplx.shape[1:]))
meas = {
item.creg_name: cplx for item in meas_info
}
meas = {item.creg_name: cplx for item in meas_info}
else:
raise QiskitError(f"Unsupported meas_level: {meas_level}")
return SamplerPubResult(
Expand Down
6 changes: 5 additions & 1 deletion test/framework/test_composite.py
Original file line number Diff line number Diff line change
Expand Up @@ -530,7 +530,11 @@ def run(self, run_input, **options):
"header": {"metadata": circ.metadata},
"data": {
"counts": cnt,
"memory": [format(int(f"0b{s}", 2), "x") for s, n in cnt.items() for _ in range(n)]
"memory": [
format(int(f"0b{s}", 2), "x")
for s, n in cnt.items()
for _ in range(n)
],
},
}
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ def test_integration(self, ix, iy, iz, zx, zy, zz):

dt = 0.222e-9
sigma = 64
shots=2000
shots = 2000

backend = AerSimulator(seed_simulator=123, shots=shots)
backend._configuration.dt = dt
Expand Down

0 comments on commit 2e3ab73

Please sign in to comment.