diff --git a/qiskit/primitives/backend_sampler.py b/qiskit/primitives/backend_sampler.py index 73be4200510e..60d45f3af5cd 100644 --- a/qiskit/primitives/backend_sampler.py +++ b/qiskit/primitives/backend_sampler.py @@ -72,7 +72,7 @@ def __init__( self._transpile_options = Options() self._bound_pass_manager = bound_pass_manager self._preprocessed_circuits: list[QuantumCircuit] | None = None - self._transpiled_circuits: list[QuantumCircuit] | None = None + self._transpiled_circuits: list[QuantumCircuit] = [] self._skip_transpilation = skip_transpilation def __new__( # pylint: disable=signature-differs @@ -108,8 +108,8 @@ def transpiled_circuits(self) -> list[QuantumCircuit]: """ if self._skip_transpilation: self._transpiled_circuits = list(self._circuits) - elif self._transpiled_circuits is None: - # Only transpile if have not done so yet + elif len(self._transpiled_circuits) < len(self._circuits): + # transpile only circuits that are not transpiled yet self._transpile() return self._transpiled_circuits @@ -174,10 +174,10 @@ def _postprocessing(self, result: Result, circuits: list[QuantumCircuit]) -> Sam def _transpile(self): from qiskit.compiler import transpile - self._transpiled_circuits = cast( - "list[QuantumCircuit]", + start = len(self._transpiled_circuits) + self._transpiled_circuits.extend( transpile( - self.preprocessed_circuits, + self.preprocessed_circuits[start:], self.backend, **self.transpile_options.__dict__, ), diff --git a/releasenotes/notes/fix-backend-sampler-890cbcf913667b08.yaml b/releasenotes/notes/fix-backend-sampler-890cbcf913667b08.yaml new file mode 100644 index 000000000000..42637b41562f --- /dev/null +++ b/releasenotes/notes/fix-backend-sampler-890cbcf913667b08.yaml @@ -0,0 +1,5 @@ +--- +fixes: + - | + Fixed a bug of :class:`~.BackendSampler` that raises an error + if :meth:`~.BackendSampler.run` method is called two times sequentially. diff --git a/test/python/primitives/test_backend_sampler.py b/test/python/primitives/test_backend_sampler.py index ccf420afbbbd..46ca9b935eea 100644 --- a/test/python/primitives/test_backend_sampler.py +++ b/test/python/primitives/test_backend_sampler.py @@ -319,6 +319,22 @@ def test_primitive_job_size_limit_backend_v1(self): self.assertDictAlmostEqual(result.quasi_dists[0], {0: 1}, 0.1) self.assertDictAlmostEqual(result.quasi_dists[1], {1: 1}, 0.1) + def test_sequential_run(self): + """Test sequential run.""" + qc = QuantumCircuit(1) + qc.measure_all() + qc2 = QuantumCircuit(1) + qc2.x(0) + qc2.measure_all() + sampler = BackendSampler(backend=FakeNairobi()) + result = sampler.run([qc]).result() + self.assertDictAlmostEqual(result.quasi_dists[0], {0: 1}, 0.1) + result2 = sampler.run([qc2]).result() + self.assertDictAlmostEqual(result2.quasi_dists[0], {1: 1}, 0.1) + result3 = sampler.run([qc, qc2]).result() + self.assertDictAlmostEqual(result3.quasi_dists[0], {0: 1}, 0.1) + self.assertDictAlmostEqual(result3.quasi_dists[1], {1: 1}, 0.1) + if __name__ == "__main__": unittest.main()