Skip to content
Open
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
5 changes: 3 additions & 2 deletions pyqpanda-algorithm/pyqpanda_alg/QAOA/spsa.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@


def _check_bounds(d, bounds):
"""Check if the given bounds fits the variables."""
"""Check if the given bounds fits the variables. Returns d (min, max) pairs, or None."""
bounds = np.array(bounds)
bn = len(bounds)
if bn == 0:
Expand All @@ -29,8 +29,9 @@ def _check_bounds(d, bounds):
elif bn > 1:
if d != bn:
raise IndexError('Dimension of ``bounds`` does not match the dimension of variable ``x``.')
return bounds
elif bn == 1:
return bounds * d
return np.tile(bounds, (d, 1))


def _jail_inside(x, bounds):
Expand Down
49 changes: 48 additions & 1 deletion test/QAOA/Test_spsa_minimize.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,5 +54,52 @@ def test_spsa_basic_functionality(self, noise_function):
# 验证回调函数被调用
assert len(noise_function.history) > 0
assert noise_function.eval_count > 0


def test_spsa_bounds_respected(self, simple_function):
"""Result stays inside per-variable bounds."""
np.random.seed(0)
x0 = np.array([5.0, 5.0])
bounds = [(1.0, 2.0), (1.0, 2.0)]

result = spsa.spsa_minimize(simple_function, x0, bounds=bounds, maxiter=100)

assert (result >= 1.0).all()
assert (result <= 2.0).all()

def test_spsa_single_pair_bounds_respected(self, simple_function):
"""A single (min, max) pair applies to every variable."""
np.random.seed(0)
x0 = np.array([5.0, 5.0, 5.0])

result = spsa.spsa_minimize(simple_function, x0, bounds=[(1.0, 2.0)], maxiter=100)

assert result.shape == x0.shape
assert (result >= 1.0).all()
assert (result <= 2.0).all()

def test_check_bounds_per_variable(self):
"""One pair per variable is returned as given."""
bounds = [(0.0, 1.0), (-2.0, 2.0), (3.0, 4.0)]

checked = spsa._check_bounds(3, bounds)

assert checked is not None
assert np.array_equal(checked, np.array(bounds))

def test_check_bounds_single_pair_tiled(self):
"""A single pair is tiled, not multiplied."""
checked = spsa._check_bounds(3, [(0, 1)])

assert np.array_equal(checked, np.array([[0, 1], [0, 1], [0, 1]]))

def test_check_bounds_validation(self):
"""Invalid bounds still raise, empty bounds still mean no bounds."""
with pytest.raises(ValueError):
spsa._check_bounds(2, [(2, 1), (0, 1)])

with pytest.raises(IndexError):
spsa._check_bounds(3, [(0, 1), (0, 1)])

assert spsa._check_bounds(2, []) is None