-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathrunScript_FI.py
executable file
·288 lines (262 loc) · 9.56 KB
/
runScript_FI.py
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
#!/usr/bin/env python
# =============================================================================
# Imports
# =============================================================================
import argparse
import numpy as np
import json, copy
from mpi4py import MPI
import openmdao.api as om
from mphys.multipoint import Multipoint
from dafoam.mphys import DAFoamBuilder
from mphys.scenario_aerodynamic import ScenarioAerodynamic
parser = argparse.ArgumentParser()
# which optimizer to use. Options are: IPOPT (default), SLSQP, and SNOPT
parser.add_argument("-optimizer", help="optimizer to use", type=str, default="SNOPT")
# which task to run. Options are: opt (default), runPrimal, runAdjoint, checkTotals
parser.add_argument("-task", help="type of run to do", type=str, default="opt")
# which case to run
parser.add_argument("-index", help="which case index to run", type=int, default=0)
args = parser.parse_args()
# =============================================================================
# Input Parameters
# =============================================================================
idxI = args.index
cases = ["c1", "c2"]
U0s = [10.0, 20.0]
case = cases[idxI]
U0 = U0s[idxI]
nCells = 5000
np.random.seed(0)
with open("./probePointCoords.json") as f:
probePointCoords = json.load(f)
# Input parameters for DAFoam
daOptions = {
"solverName": "DASimpleFoam",
"primalMinResTol": 1.0e-8,
"primalMinResTolDiff": 1e3,
"primalBC": {
"U0": {"variable": "U", "patches": ["inlet"], "value": [U0, 0, 0]},
"useWallFunction": True,
},
"primalVarBounds": {"omegaMin": -1e16},
"regressionModel": {
"active": True,
"model": {
"modelType": "neuralNetwork",
"inputNames": ["PoD", "VoS", "PSoSS", "KoU2"],
# set a dummy output, so the regModel will not compute the augmented field
# it will just write the features to the disk
"outputName": "ADummyOutput",
"hiddenLayerNeurons": [20, 20],
"inputShift": [0.0, 0.0, 0.0, 0.0],
"inputScale": [1.0, 1.0, 1.0, 0.1],
"outputShift": 1.0,
"outputScale": 1.0,
"activationFunction": "tanh",
"printInputInfo": True,
"defaultOutputValue": 1.0,
"outputUpperBound": 1e1,
"outputLowerBound": -1e1,
"writeFeatures": True,
},
},
"objFunc": {
"VAR": {
"pVar": {
"type": "variance",
"source": "boxToCell",
"min": [-10.0, -10.0, -10.0],
"max": [10.0, 10.0, 10.0],
"scale": 1.0,
"mode": "surface",
"surfaceNames": ["bot"],
"varName": "p",
"varType": "scalar",
"timeDependentRefData": False,
"addToAdjoint": True,
},
# "UFieldVar": {
# "type": "variance",
# "source": "boxToCell",
# "min": [-10.0, -10.0, -10.0],
# "max": [10.0, 10.0, 10.0],
# "scale": 0.1,
# "mode": "field",
# "varName": "U",
# "varType": "vector",
# "components": [0, 1],
# "timeDependentRefData": False,
# "addToAdjoint": True,
# },
# "UProbeVar": {
# "type": "variance",
# "source": "boxToCell",
# "min": [-10.0, -10.0, -10.0],
# "max": [10.0, 10.0, 10.0],
# "scale": 1.0,
# "mode": "probePoint",
# "probePointCoords": probePointCoords["probePointCoords"],
# "varName": "U",
# "varType": "vector",
# "components": [0, 1],
# "timeDependentRefData": False,
# "addToAdjoint": True,
# "CDError": {
# "type": "force",
# "source": "patchToFace",
# "patches": ["bot"],
# "directionMode": "fixedDirection",
# "direction": [1.0, 0.0, 0.0],
# "scale": 1.0,
# "addToAdjoint": True,
# "calcRefVar": True,
# "ref": [0.0], # we will assign this later because each case has a different ref
# },
"betaVar": {
"type": "variance",
"source": "boxToCell",
"min": [-10.0, -10.0, -10.0],
"max": [10.0, 10.0, 10.0],
"scale": 1.0,
"mode": "field",
"varName": "betaFIOmega",
"varType": "scalar",
"timeOperator": "average",
"timeDependentRefData": False,
"addToAdjoint": True,
},
},
"CD": {
"part1": {
"type": "force",
"source": "patchToFace",
"patches": ["bot"],
"directionMode": "fixedDirection",
"direction": [1.0, 0.0, 0.0],
"scale": 1.0,
"addToAdjoint": False,
}
},
},
"adjStateOrdering": "cell",
"adjEqnOption": {
"gmresRelTol": 1.0e-6,
"pcFillLevel": 1,
"jacMatReOrdering": "natural",
},
"normalizeStates": {
"U": U0,
"p": U0 * U0 / 2.0,
"nuTilda": 1e-3,
"phi": 1.0,
},
"designVar": {
"beta": {"designVarType": "Field", "fieldName": "betaFIOmega", "fieldType": "scalar", "distributed": False},
},
}
def betaFunction(val, DASolver):
for idxI, v in enumerate(val):
DASolver.setFieldValue4GlobalCellI(b"betaFIOmega", v, idxI)
DASolver.updateBoundaryConditions(b"betaFIOmega", b"scalar")
# Top class to setup the optimization problem
class Top(Multipoint):
def setup(self):
# create the builder to initialize the DASolvers
dafoam_builder = DAFoamBuilder(options=daOptions, mesh_options=None, scenario="aerodynamic", run_directory=case)
dafoam_builder.initialize(self.comm)
# add the design variable component to keep the top level design variables
self.add_subsystem("dvs", om.IndepVarComp(), promotes=["*"])
# add a scenario (flow condition) for optimization, we pass the builder
# to the scenario to actually run the flow and adjoint
self.mphys_add_scenario("cruise", ScenarioAerodynamic(aero_builder=dafoam_builder))
def configure(self):
# configure and setup perform a similar function, i.e., initialize the optimization.
# But configure will be run after setup
# add the objective function to the cruise scenario
self.cruise.aero_post.mphys_add_funcs()
# pass this aoa function to the cruise group
self.cruise.coupling.solver.add_dv_func("beta", betaFunction)
self.cruise.aero_post.add_dv_func("beta", betaFunction)
# add the design variables to the dvs component's output
self.dvs.add_output("beta", val=np.ones(nCells), distributed=False)
self.connect("beta", "cruise.beta")
# define the design variables to the top level
self.add_design_var("beta", lower=-5.0, upper=10.0, scaler=1.0)
# add objective and constraints to the top level
self.add_objective("cruise.aero_post.VAR", scaler=1.0)
# OpenMDAO setup
prob = om.Problem()
prob.model = Top()
prob.setup(mode="rev")
om.n2(prob, show_browser=False, outfile="mphys.html")
# use pyoptsparse to setup optimization
prob.driver = om.pyOptSparseDriver()
prob.driver.options["optimizer"] = args.optimizer
# options for optimizers
if args.optimizer == "SNOPT":
prob.driver.opt_settings = {
"Major feasibility tolerance": 1.0e-6,
"Major optimality tolerance": 1.0e-6,
"Minor feasibility tolerance": 1.0e-6,
"Verify level": -1,
"Function precision": 1.0e-6,
"Major iterations limit": 50,
"Linesearch tolerance": 0.999,
"Hessian updates": 50,
"Nonderivative linesearch": None,
"Print file": "opt_SNOPT_print.txt",
"Summary file": "opt_SNOPT_summary.txt",
}
elif args.optimizer == "IPOPT":
prob.driver.opt_settings = {
"tol": 1.0e-5,
"constr_viol_tol": 1.0e-5,
"max_iter": 50,
"print_level": 5,
"output_file": "opt_IPOPT.txt",
"mu_strategy": "adaptive",
"limited_memory_max_history": 10,
"nlp_scaling_method": "none",
"alpha_for_y": "full",
"recalc_y": "yes",
}
elif args.optimizer == "SLSQP":
prob.driver.opt_settings = {
"ACC": 1.0e-5,
"MAXIT": 100,
"IFILE": "opt_SLSQP.txt",
}
else:
print("optimizer arg not valid!")
exit(1)
prob.driver.options["debug_print"] = ["nl_cons", "objs", "desvars"]
prob.driver.options["print_opt_prob"] = True
prob.driver.hist_file = "OptView.hst"
if args.task == "opt":
# run the optimization
prob.run_driver()
elif args.task == "runPrimal":
# just run the primal once
prob.run_model()
elif args.task == "runAdjoint":
# just run the primal and adjoint once
prob.run_model()
totals = prob.compute_totals()
if MPI.COMM_WORLD.rank == 0:
print(totals)
elif args.task == "checkTotals":
# verify the total derivatives against the finite-difference
prob.run_model()
prob.check_totals(
# of=["cruise.aero_post.CD", "cruise.aero_post.CL"],
# wrt=["shape", "aoa"],
compact_print=True,
step=1e-2,
form="central",
step_calc="abs",
show_progress=True,
)
else:
print("task arg not found!")
exit(1)