Skip to content

Commit

Permalink
added test and clipping for final result
Browse files Browse the repository at this point in the history
  • Loading branch information
andrewellis55 committed Sep 15, 2024
1 parent 874e821 commit 230f92f
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
4 changes: 4 additions & 0 deletions pyoptsparse/pySLSQP/pySLSQP.py
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,10 @@ def slgrad(m, me, la, n, f, g, df, dg, x):
# fmt: on
optTime = time.time() - t0

# Clip final result to user bounds (this occurs during the optimization as well
# so this just makes the output consistent with what the optimizer sees)
xs = np.clip(xs, blx, bux)

# some entries of W include the lagrange multipliers
# for each constraint, there are two entries (lower, upper).
# if only one is active, look for the nonzero. If both are active, take the first one
Expand Down
47 changes: 47 additions & 0 deletions tests/test_slsqp.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
"""Test class for SLSQP specific tests"""

# First party modules
from pyoptsparse import Optimization, OPT

# Local modules
from testing_utils import OptTest


class TestSLSQP(OptTest):

def test_slsqp_strong_bound_enforcement(self):
"""
Test that SLSQP will never evaluate the function or gradient outside
the design variable bounds. Without strong bound enforcement, the
optimizer will step outside the bounds and a ValueError will be raised.
With strong bound enforement, this code will run without raising any
errors
"""

def objfunc(xdict):
x = xdict["xvars"]
funcs = {}
if x[0] < 0:
raise ValueError("Function cannot be evaluated below 0.")
funcs["obj"] = (x[0] - 1.0) ** 2
fail = False
return funcs, fail

def sens(xdict, funcs):
x = xdict["xvars"]
if x[0] < 0:
raise ValueError("Function cannot be evaluated below 0.")
funcsSens = {
"obj": {"xvars": [2 * (x[0] + 1.0)]},
}
fail = False
return funcsSens, fail

optProb = Optimization("Problem with Error Region", objfunc)
optProb.addVarGroup("xvars", 1, lower=[0], value=[2])
optProb.addObj("obj")
opt = OPT("SLSQP")
sol = opt(optProb, sens=sens)
self.assertEqual(sol.optInform["value"], 0)
self.assertGreaterEqual(sol.xStar["xvars"][0], 0)
self.assertAlmostEqual(sol.xStar["xvars"][0], 0, places=9)

0 comments on commit 230f92f

Please sign in to comment.