diff --git a/qiskit/algorithms/gradients/lin_comb_sampler_gradient.py b/qiskit/algorithms/gradients/lin_comb_sampler_gradient.py index 0f4cf0631e97..8e5777f67fca 100644 --- a/qiskit/algorithms/gradients/lin_comb_sampler_gradient.py +++ b/qiskit/algorithms/gradients/lin_comb_sampler_gradient.py @@ -114,8 +114,14 @@ def _run( n = 2 ** circuits[i].num_qubits grad_dists = np.zeros((len(metadata_[i]["parameters"]), n)) for idx, coeff, dist in zip(result_indices_all[i], coeffs_all[i], result.quasi_dists): - grad_dists[idx][list(dist.keys())[:n]] += np.array(list(dist.values())[:n]) * coeff - grad_dists[idx][list(dist.keys())[:n]] -= np.array(list(dist.values())[n:]) * coeff + plus = {key: val for key, val in dist.items() if key < n} + minus = {key - n: val for key, val in dist.items() if key >= n} + grad_dists[idx][list(plus.keys())] += ( + np.fromiter(plus.values(), dtype=float) * coeff + ) + grad_dists[idx][list(minus.keys())] -= ( + np.fromiter(minus.values(), dtype=float) * coeff + ) gradient_ = [] for grad_dist in grad_dists: diff --git a/qiskit/algorithms/gradients/utils.py b/qiskit/algorithms/gradients/utils.py index 3d1e0b1907b4..4525836aa7b7 100644 --- a/qiskit/algorithms/gradients/utils.py +++ b/qiskit/algorithms/gradients/utils.py @@ -318,10 +318,10 @@ def _make_lin_comb_gradient_circuit( ] circuit2 = transpile(circuit, basis_gates=supported_gates, optimization_level=0) - qr_aux = QuantumRegister(1, "aux") - cr_aux = ClassicalRegister(1, "aux") + qr_aux = QuantumRegister(1, "qr_aux") + cr_aux = ClassicalRegister(1, "cr_aux") circuit2.add_register(qr_aux) - circuit2.add_bits(cr_aux) + circuit2.add_register(cr_aux) circuit2.h(qr_aux) circuit2.data.insert(0, circuit2.data.pop()) circuit2.sdg(qr_aux) diff --git a/releasenotes/notes/fix-libcomb-sampler-gradient-d759d6b0e2659abe.yaml b/releasenotes/notes/fix-libcomb-sampler-gradient-d759d6b0e2659abe.yaml new file mode 100644 index 000000000000..914be12875e7 --- /dev/null +++ b/releasenotes/notes/fix-libcomb-sampler-gradient-d759d6b0e2659abe.yaml @@ -0,0 +1,5 @@ +--- +fixes: + - | + Fixed an issue of :class:`~.LinCombSamplerGradient` that raises an error + with Aer Sampler.