Skip to content

Commit

Permalink
Bug fix on QNSPSA (Qiskit#9483)
Browse files Browse the repository at this point in the history
* Bug fix

Old syntax was giving type error when dividing int by float

* Bug fix

* Convert to float to avoid type error

* Add unit test

* Add release note

* Update releasenotes/notes/qnspsa-float-bug-fix-4035f7e1eb61dec2.yaml

Co-authored-by: Julien Gacon <[email protected]>

* Ran black

* Make unused argument explicitly ignored

* Change to np array syntax

* Pylint disable invalid name

The name of variable "_y" must have this form because the argument is unused

* Make black

---------

Co-authored-by: Julien Gacon <[email protected]>
Co-authored-by: ElePT <[email protected]>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
  • Loading branch information
4 people authored and pranay1990 committed Feb 9, 2023
1 parent c2c1c9a commit 60c610d
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 2 deletions.
5 changes: 3 additions & 2 deletions qiskit/algorithms/optimizers/qnspsa.py
Original file line number Diff line number Diff line change
Expand Up @@ -228,9 +228,10 @@ def _point_sample(self, loss, x, eps, delta1, delta2):
gradient_estimate = (loss_values[0] - loss_values[1]) / (2 * eps) * delta1

# compute the preconditioner point estimate
fidelity_values = np.asarray(fidelity_values, dtype=float)
diff = fidelity_values[2] - fidelity_values[0]
diff -= fidelity_values[3] - fidelity_values[1]
diff /= 2 * eps**2
diff = diff - (fidelity_values[3] - fidelity_values[1])
diff = diff / (2 * eps**2)

rank_one = np.outer(delta1, delta2)
# -0.5 factor comes from the fact that we need -0.5 * fidelity
Expand Down
5 changes: 5 additions & 0 deletions releasenotes/notes/qnspsa-float-bug-fix-4035f7e1eb61dec2.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
fixes:
- |
Fixed bug in :class:`.QNSPSA` which raised a type error when the computed fidelities
happened to be integers but the perturbation was of type float.
25 changes: 25 additions & 0 deletions test/python/algorithms/optimizers/test_spsa.py
Original file line number Diff line number Diff line change
Expand Up @@ -255,3 +255,28 @@ def objective(x):
with self.subTest("check number of function calls"):
expected_nfev = 8 # 7 * maxiter + 1
self.assertEqual(result.nfev, expected_nfev)

def test_point_sample(self):
"""Test point sample function in QNSPSA"""
# pylint: disable=invalid-name

def fidelity(x, _y):
x = np.asarray(x)
return np.ones_like(x, dtype=float) # some float

def objective(x):
return x

def get_perturbation():
def perturbation():
while True:
yield 1

return perturbation

qnspsa = QNSPSA(fidelity, maxiter=1, learning_rate=0.1, perturbation=get_perturbation())
initial_point = 1.0
result = qnspsa.minimize(objective, initial_point)

expected_nfev = 8 # 7 * maxiter + 1
self.assertEqual(result.nfev, expected_nfev)

0 comments on commit 60c610d

Please sign in to comment.