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

Bug fix on QNSPSA #9483

Merged
merged 13 commits into from
Feb 2, 2023
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)