Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix the order bug in Estimator #1936

Merged
merged 3 commits into from
Sep 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 12 additions & 18 deletions qiskit_aer/primitives/estimator.py
Original file line number Diff line number Diff line change
Expand Up @@ -382,20 +382,16 @@ def _compute_with_approximation(
self._transpile_circuits(circuits)
experiment_manager = _ExperimentManager()
for i, j, value in zip(circuits, observables, parameter_values):
self._validate_parameter_length(value, i)
if (i, j) in experiment_manager.keys:
self._validate_parameter_length(value, i)
experiment_manager.append(
key=(i, j),
parameter_bind=dict(zip(self._parameters[i], value)),
)
key_index = experiment_manager.keys.index((i, j))
circuit = experiment_manager.experiment_circuits[key_index]
else:
self._validate_parameter_length(value, i)
circuit = (
self._circuits[i].copy()
if self._skip_transpilation
else self._transpiled_circuits[i].copy()
)

observable = self._observables[j]
if shots is None:
circuit.save_expectation_value(observable, self._layouts[i])
Expand All @@ -404,11 +400,11 @@ def _compute_with_approximation(
circuit.save_expectation_value(
pauli, self._layouts[i], label=str(term_ind)
)
experiment_manager.append(
key=(i, j),
parameter_bind=dict(zip(self._parameters[i], value)),
experiment_circuit=circuit,
)
experiment_manager.append(
key=(i, j),
parameter_bind=dict(zip(self._parameters[i], value)),
experiment_circuit=circuit,
)

self._cache[key] = experiment_manager
result = self._backend.run(
Expand Down Expand Up @@ -616,24 +612,22 @@ def __len__(self):
@property
def experiment_indices(self):
"""indices of experiments"""
return sum(self._input_indices, [])
return np.argsort(sum(self._input_indices, [])).tolist()

def append(
self,
key: tuple[int, int],
parameter_bind: dict[ParameterExpression, float],
experiment_circuit: QuantumCircuit | None = None,
experiment_circuit: QuantumCircuit,
):
"""append experiments"""
if experiment_circuit is not None:
self.experiment_circuits.append(experiment_circuit)

if key in self.keys:
if key in self.keys and parameter_bind:
key_index = self.keys.index(key)
for k, vs in self.parameter_binds[key_index].items():
vs.append(parameter_bind[k])
self._input_indices[key_index].append(self._num_experiment)
else:
self.experiment_circuits.append(experiment_circuit)
self.keys.append(key)
self.parameter_binds.append({k: [v] for k, v in parameter_bind.items()})
self._input_indices.append([self._num_experiment])
Expand Down
5 changes: 5 additions & 0 deletions releasenotes/notes/estimator-order-bug-a341d82075f47046.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
upgrade:
- |
Fixed a bug that caused results to be incorrectly ordered or errors in
:class:`~.Estimator` with ``approximation=True``.
17 changes: 16 additions & 1 deletion test/terra/primitives/test_estimator.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@

import numpy as np
from ddt import data, ddt
from qiskit.circuit import QuantumCircuit
from qiskit.circuit import Parameter, QuantumCircuit
from qiskit.circuit.library import RealAmplitudes
from qiskit.exceptions import QiskitError
from qiskit.opflow import PauliSumOp
Expand Down Expand Up @@ -308,6 +308,21 @@ def test_warn_shots_none_without_approximation(self):
np.testing.assert_allclose(result.values, [-1.313831587508902])
self.assertIsInstance(result.metadata[0]["variance"], float)

def test_result_order(self):
"""Test to validate the order."""
qc1 = QuantumCircuit(1)
qc1.measure_all()

param = Parameter("a")
qc2 = QuantumCircuit(1)
qc2.ry(np.pi / 2 * param, 0)
qc2.measure_all()

estimator = Estimator(approximation=True)
job = estimator.run([qc1, qc2, qc1, qc1, qc2], ["Z"] * 5, [[], [1], [], [], [1]])
result = job.result()
np.testing.assert_allclose(result.values, [1, 0, 1, 1, 0], atol=1e-10)


if __name__ == "__main__":
unittest.main()
Loading