-
Notifications
You must be signed in to change notification settings - Fork 122
Expand file tree
/
Copy pathtest_hs015.py
More file actions
297 lines (257 loc) · 9.73 KB
/
test_hs015.py
File metadata and controls
297 lines (257 loc) · 9.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
"""Test solution of problem HS15 from the Hock & Schittkowski collection"""
# Standard Python modules
import os
import unittest
# External modules
from baseclasses.utils import readPickle, writePickle
import numpy as np
from parameterized import parameterized
# First party modules
from pyoptsparse import OPT, History, Optimization
# Local modules
from testing_utils import OptTest
class TestHS15(OptTest):
## Solve test problem HS15 from the Hock & Schittkowski collection.
#
# min 100 (x2 - x1^2)^2 + (1 - x1)^2
# s.t. x1 x2 >= 1
# x1 + x2^2 >= 0
# x1 <= 0.5
#
# The standard start point (-2, 1) usually converges to the standard
# minimum at (0.5, 2.0), with final objective = 306.5.
# Sometimes the solver converges to another local minimum
# at (-0.79212, -1.26243), with final objective = 360.4.
##
name = "HS015"
DVs = {"xvars"}
cons = {"con"}
objs = {"obj"}
extras = {"extra1", "extra2"}
fStar = [
306.5,
360.379767,
]
xStar = [
{"xvars": (0.5, 2.0)},
{"xvars": (-0.79212322, -1.26242985)},
]
tol = {
"SLSQP": 1e-5,
"NLPQLP": 1e-12,
"IPOPT": 1e-4,
"ParOpt": 1e-6,
"CONMIN": 1e-10,
"PSQP": 5e-12,
}
optOptions = {}
def objfunc(self, xdict):
self.nf += 1
x = xdict["xvars"]
funcs = {}
funcs["obj"] = [100 * (x[1] - x[0] ** 2) ** 2 + (1 - x[0]) ** 2]
conval = np.zeros(2, "D")
conval[0] = x[0] * x[1]
conval[1] = x[0] + x[1] ** 2
funcs["con"] = conval
# extra keys
funcs["extra1"] = 0.0
funcs["extra2"] = 1.0
fail = False
return funcs, fail
def sens(self, xdict, funcs):
self.ng += 1
x = xdict["xvars"]
funcsSens = {}
funcsSens["obj"] = {
"xvars": [2 * 100 * (x[1] - x[0] ** 2) * (-2 * x[0]) - 2 * (1 - x[0]), 2 * 100 * (x[1] - x[0] ** 2)]
}
funcsSens["con"] = {"xvars": [[x[1], x[0]], [1, 2 * x[1]]]}
fail = False
return funcsSens, fail
def setup_optProb(self):
# Optimization Object
self.optProb = Optimization("HS15 Constraint Problem", self.objfunc)
# Design Variables
lower = [-5.0, -5.0]
upper = [0.5, 5.0]
value = [-2, 1.0]
self.optProb.addVarGroup("xvars", 2, lower=lower, upper=upper, value=value)
# Constraints
lower = [1.0, 0.0]
upper = [None, None]
self.optProb.addConGroup("con", 2, lower=lower, upper=upper)
# Objective
self.optProb.addObj("obj")
def test_snopt(self):
self.optName = "SNOPT"
self.setup_optProb()
store_vars = ["Hessian", "slack", "lambda", "penalty_vector", "nS", "BSwap", "maxVi"]
optOptions = {"Save major iteration variables": store_vars}
self.optimize_with_hotstart(1e-12, optOptions=optOptions)
hist = History(self.histFileName, flag="r")
data = hist.getValues(callCounters=["last"])
keys = hist.getIterKeys()
self.assertIn("isMajor", keys)
self.assertEqual(7, data["nMajor"])
for var in store_vars:
self.assertIn(var, data.keys())
self.assertEqual(data["Hessian"].shape, (1, 2, 2))
self.assertEqual(data["feasibility"].shape, (1, 1))
self.assertEqual(data["slack"].shape, (1, 2))
self.assertEqual(data["lambda"].shape, (1, 2))
# dv = sol.getDVs()
# sol_xvars = [sol.variables["xvars"][i].value for i in range(2)]
# assert_allclose(sol_xvars, dv["xvars"], atol=tol, rtol=tol)
@parameterized.expand(["SLSQP", "PSQP", "CONMIN", "NLPQLP", "ParOpt"])
def test_optimization(self, optName):
self.optName = optName
self.setup_optProb()
optOptions = self.optOptions.pop(optName, None)
sol = self.optimize(optOptions=optOptions)
# Check Solution
self.assert_solution_allclose(sol, self.tol[optName])
# Check informs
self.assert_inform_equal(sol)
def test_ipopt(self):
self.optName = "IPOPT"
self.setup_optProb()
optOptions = self.optOptions.pop(self.optName, None)
sol = self.optimize(optOptions=optOptions, storeHistory=True)
# Check Solution
self.assert_solution_allclose(sol, self.tol[self.optName])
# Check informs
self.assert_inform_equal(sol)
# Check iteration counters
hist = History(self.histFileName, flag="r")
data_init = hist.read(0)
self.assertEqual(0, data_init["iter"])
data_last = hist.read(hist.read("last"))
self.assertEqual(11, data_last["iter"]) # took 12 function evaluations (see test_ipopt.out)
# Make sure there is no duplication in objective history
data = hist.getValues(names=["obj"])
objhis_len = data["obj"].shape[0]
self.assertEqual(12, objhis_len)
for i in range(objhis_len - 1):
self.assertNotEqual(data["obj"][i], data["obj"][i + 1])
def test_snopt_hotstart(self):
self.optName = "SNOPT"
self.setup_optProb()
sol, restartDict = self.optimize(optOptions={"Return work arrays": True})
# Check Solution
self.assert_solution_allclose(sol, 1e-12)
# Check informs
self.assert_inform_equal(sol)
# Check restartDict
self.assertEqual({"cw", "iw", "rw", "xs", "hs", "pi"}, set(restartDict.keys()))
# Now optimize again, but using the hotstart
self.setup_optProb()
self.nf = 0
self.ng = 0
opt = OPT(self.optName, options={"Start": "Hot", "Verify level": -1})
sol = opt(self.optProb, sens=self.sens, restartDict=restartDict)
# Check Solution
self.assert_solution_allclose(sol, 1e-12)
# Should only take one major iteration
self.assertEqual(self.nf, 1)
self.assertEqual(self.ng, 1)
@staticmethod
def my_snstop(iterDict):
"""manually terminate SNOPT after 1 major iteration"""
if iterDict["nMajor"] == 1:
return 1
return 0
def test_snopt_snstop(self):
self.optName = "SNOPT"
self.setup_optProb()
optOptions = {
"snSTOP function handle": self.my_snstop,
}
sol = self.optimize(optOptions=optOptions, storeHistory=True)
# Check informs
# we should get 70/74
self.assert_inform_equal(sol, optInform=74)
@staticmethod
def my_snstop_restart(iterDict, restartDict):
# Save the restart dictionary
writePickle("restart.pickle", restartDict)
# Exit after 5 major iterations
if iterDict["nMajor"] == 5:
return 1
return 0
def test_snopt_snstop_restart(self):
# Run the optimization for 5 major iterations
self.optName = "SNOPT"
self.setup_optProb()
optOptions = {
"snSTOP function handle": self.my_snstop_restart,
"snSTOP arguments": ["restartDict"],
}
sol = self.optimize(optOptions=optOptions, storeHistory=True)
# Read the restart dictionary pickle file saved by snstop
pickleFile = "restart.pickle"
restartDict = readPickle(pickleFile)
# Now optimize again but using the restart dictionary
self.setup_optProb()
opt = OPT(
self.optName,
options={
"Start": "Hot",
"Verify level": -1,
"snSTOP function handle": self.my_snstop_restart,
"snSTOP arguments": ["restartDict"],
},
)
histFile = "restart.hst"
sol = opt(self.optProb, sens=self.sens, storeHistory=histFile, restartDict=restartDict)
# Check that the optimization converged in fewer than 5 more major iterations
self.assert_solution_allclose(sol, 1e-12)
self.assert_inform_equal(sol, optInform=1)
# Delete the pickle and history files
os.remove(pickleFile)
os.remove(histFile)
def test_snopt_work_arrays_save(self):
# Run the optimization for 5 major iterations
self.optName = "SNOPT"
self.setup_optProb()
pickleFile = "work_arrays_save.pickle"
optOptions = {
"snSTOP function handle": self.my_snstop,
"Work arrays save file": pickleFile,
}
sol = self.optimize(optOptions=optOptions, storeHistory=True)
# Read the restart dictionary pickle file saved by snstop
restartDict = readPickle(pickleFile)
# Now optimize again but using the restart dictionary
self.setup_optProb()
opt = OPT(
self.optName,
options={
"Start": "Hot",
"Verify level": -1,
},
)
histFile = "work_arrays_save.hst"
sol = opt(self.optProb, sens=self.sens, storeHistory=histFile, restartDict=restartDict)
# Check that the optimization converged in fewer than 5 more major iterations
self.assert_solution_allclose(sol, 1e-12)
self.assert_inform_equal(sol, optInform=1)
# Delete the pickle and history files
os.remove(pickleFile)
os.remove(histFile)
def test_snopt_failed_initial(self):
def failed_fun(x_dict):
funcs = {"obj": 0.0, "con": [np.nan, np.nan]}
fail = True
return funcs, fail
self.optName = "SNOPT"
self.setup_optProb()
# swap obj to report NaN
self.optProb.objFun = failed_fun
sol = self.optimize(optOptions={}, storeHistory=True)
self.assert_inform_equal(sol, optInform=61)
# make sure empty history does not error out
hist = History(self.histFileName, flag="r")
hist.getValues()
if __name__ == "__main__":
unittest.main()