Skip to content

Commit

Permalink
Fix LinCombSamplerGradient to leverage AerSampler (#9258)
Browse files Browse the repository at this point in the history
* fix LinCombSamplerGradient

* fix lib_comb circuit

* add reno

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
  • Loading branch information
t-imamichi and mergify[bot] authored Dec 8, 2022
1 parent 840f44a commit 45db5ec
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 5 deletions.
10 changes: 8 additions & 2 deletions qiskit/algorithms/gradients/lin_comb_sampler_gradient.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
6 changes: 3 additions & 3 deletions qiskit/algorithms/gradients/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
fixes:
- |
Fixed an issue of :class:`~.LinCombSamplerGradient` that raises an error
with Aer Sampler.

0 comments on commit 45db5ec

Please sign in to comment.