-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWingSolver_CalcGradient.FCMacro
More file actions
311 lines (268 loc) · 9.6 KB
/
Copy pathWingSolver_CalcGradient.FCMacro
File metadata and controls
311 lines (268 loc) · 9.6 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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
# -*- coding: utf-8 -*-
import FreeCAD
import FreeCADGui
from os import path
from CfdOF.Mesh import CfdMeshTools
from CfdOF import CfdTools
from CfdOF.Solve import CfdCaseWriterFoam
import copy
import WingSolver_dependencies.WingSolver_Dependencies as wng
mydir = path.dirname(__file__)
failcount=0
meshsize=0
analyseCSVMacro=path.join(mydir, 'WingSolver_AnalyseResult.FCMacro')
optimizeVelocityMacro=path.join(mydir, "WingSolver_OptimizeVelocity.FCMacro")
#load spreadsheets
desc=FreeCAD.ActiveDocument.getObjectsByLabel("ParameterDescription")[0]
rdesc=FreeCAD.ActiveDocument.getObjectsByLabel("ResultDescription")[0]
current=FreeCAD.ActiveDocument.getObjectsByLabel("CurrentParameter")[0]
geometry=FreeCAD.ActiveDocument.getObjectsByLabel("WingGeometry")[0]
analysis=FreeCAD.ActiveDocument.getObjectsByLabel("CfdAnalysis")[0]
raw=FreeCAD.ActiveDocument.getObjectsByLabel("RawResultData")[0]
res=FreeCAD.ActiveDocument.getObjectsByLabel("ResultData")[0]
sstate=FreeCAD.ActiveDocument.getObjectsByLabel("SolverState")[0]
mass=FreeCAD.ActiveDocument.getObjectsByLabel("ComputedValues")[0]
#get workingdir
basedir=desc.cells["BaseDir"]
workingdirbase=path.join(basedir,"workingdir")
#reset workingdir
wng.empty_directory(workingdirbase)
meshsizes=desc.cells["MeshSizes"]
#get parameter data
paramnames=desc.cells[desc.cells["ParameterNames"]]
paramdefaults=desc.cells[desc.cells["DefaultValues"]]
parammins=desc.cells[desc.cells["MinValue"]]
parammaxs=desc.cells[desc.cells["MaxValue"]]
paramsteps=desc.cells[desc.cells["SensibleStepWidth"]]
#get learning rate
lr=desc.cells["LearningRate"]
params={}
#Create Dictionary with important data of each parameter
for i in range(len(paramnames)):
params[paramnames[i]]={"name":paramnames[i],"default":paramdefaults[i],"min":parammins[i],"max":parammaxs[i],"step":paramsteps[i], "current":current.cells[paramnames[i]]}
#Create dictionary of result data (with name and reference variable/parameter)
rparamnames=rdesc.cells[rdesc.cells["ParameterNames"]]
rparamref=rdesc.cells[rdesc.cells["Ref"]]
rparams={}
for i in range(len(rparamnames)):
if rparamref[i] in rparamnames:
rparams[rparamnames[i]]={"name":rparamnames[i],"ref":rparamref[i]}
#create dict for gardienttest:
#0: Initial position. For each parameter (e.g. aspect ratio) the current value is changed according to the sensible step size)
gradienttests={0:params}
for pn in params:
ps=copy.deepcopy(params)
ps[pn]["current"]=params[pn]["current"]+(params[pn]["step"]*lr)
gradienttests[pn]=ps
casepaths={}
basepaths={}
meshpaths={}
#generate meshcases and cases
def _set_params(tn):
#sets the current paramters of the model (Wing Geometry) to one(tn) of the test cases
#Input: name of the testcase tn
test=gradienttests[tn]
for pn in test:
if (tn==pn):
print("Setting %s to %s"%(pn,"%E"%test[pn]["current"]))
current.set(pn,"%E"%test[pn]["current"])
current.recompute() #recomputes the spreadsheet for the parameters
geometry.recompute() #recomputes the spreadsheet for the wing geometry
for obj in FreeCAD.ActiveDocument.Objects:
obj.touch()
FreeCAD.ActiveDocument.recompute() # dimensions just changed all over the place - recompute needed
def _export_mesh(tn):
global casepaths,meshpaths,basepaths,meshsizes,meshsize
#set basepath (workingdir/name)
workingdir=path.join(workingdirbase,str(tn))
current.set("WorkingDir",workingdir)
basepaths[tn]=workingdir
#set parameters for testcase tn
_set_params(tn)
# generate mesh
meshobject=FreeCAD.ActiveDocument.Cylinder_Mesh
meshobject.CharacteristicLengthMax=meshsizes[meshsize]
FreeCAD.ActiveDocument.recompute()
cart_mesh = CfdMeshTools.CfdMeshTools(meshobject)
FreeCAD.ActiveDocument.Cylinder_Mesh.Proxy.cart_mesh = cart_mesh
cart_mesh.writeMesh()
FreeCAD.ActiveDocument.recompute()
#generate case
FreeCAD.ActiveDocument.CfdSolver.Proxy.case_writer = CfdCaseWriterFoam.CfdCaseWriterFoam(analysis)
writer = FreeCAD.ActiveDocument.CfdSolver.Proxy.case_writer
writer.writeCase()
FreeCAD.ActiveDocument.recompute()
fullworkingdir=CfdTools.getOutputPath(analysis)
casepaths[tn]=path.join(fullworkingdir,"case")
meshpaths[tn]=path.join(fullworkingdir,"meshCase")
def _reset_base():
#reset path to the workingdir
current.set("WorkingDir",workingdirbase)
#reset parameters to basecase
_set_params(0)
while failcount>=0:
for tn in gradienttests:
_export_mesh(tn)
# reset to old values
_reset_base()
print("running mesher")
#generate meshcases and cases
command="echo \""
for tn in gradienttests:
#break
command+="cd "+meshpaths[tn]+"; ./Allmesh\n"
command+= '" | xargs -d "\\n" -n 1 -P 0 bash -c >/dev/null'
#command+= '" | xargs -d "\\n" -n 1 -P 0 echo'
print(command)
print("parallel computation - waiting for completion, pease wait")
try:
FreeCADGui.updateGui( )
except:
pass
try:
CfdTools.runFoamCommand(command)
failcount=-1
except:
print("mesher failed")
failcount+=1
if failcount<len(meshsizes):
meshsize=failcount
print("setting meshmaxsize to %i"%meshsizes[meshsize])
else:
raise Exception("parallel mesher call failed for all meshsizes - please rerun on commandline and check for errors")
print("meshing succeeded")
# note meshsize is NOT reset to ensure all gradient tests during iteration run with the same meshsize
failcount=0
print("running solvers")
for tn in gradienttests:
#break
command="cp "+path.join(basedir,"U")+" "+path.join(casepaths[tn],"0")+"; cp "+path.join(basedir,"pvScript.py")+" "+casepaths[tn]+"; cd "+casepaths[tn]+"; ./Allrun >/dev/null"
print("running solver:")
print(command)
try:
FreeCADGui.updateGui( )
except:
pass
while failcount<5:
try:
CfdTools.runFoamCommand(command)
failcount=0
break
except:
failcount+=1
print("solver failed %i times - retrying"%failcount)
_export_mesh(tn)
_reset_base()
print("rerunning mesher for %s"%tn)
subcommand="cd "+meshpaths[tn]+"; ./Allmesh"
try:
CfdTools.runFoamCommand(subcommand)
except:
print("mesher rerun for %s failed - aborting"%tn)
raise Exception("mesher rerun failed - aborting")
pass
if (failcount>0):
print("failed - aborting")
raise Exception("solver call failed - please rerun on commandline and check for errors")
print("all solvers succeeded")
print("doing analysis")
command="echo \""
for tn in gradienttests:
#break
command+="cd "+casepaths[tn]+"; "+desc.cells["pvBatchPath"]+" pvScript.py\n"
command+= '" | xargs -d "\\n" -n 1 -P 0 bash -c'
#command+= '" | xargs -d "\\n" -n 1 -P 0 echo'
print(command)
print("parallel computation - waiting for completion, pease wait")
try:
FreeCADGui.updateGui( )
except:
pass
try:
CfdTools.runFoamCommand(command)
except:
print(gradienttests)
print("failed - aborting")
raise Exception("parallel paraview call failed - please rerun on commandline and check for errors")
print("analysis succeeded")
print("calculating cost and gradients")
costs={}
gradients={}
state={}
deviationcorelation={}
costcorelation={}
cost2corelation={}
params[0]={"current":0.0}
for tn in gradienttests:
print("importing CSV for %s"%tn)
raw.importFile(path.join(casepaths[tn],"mycsv.csv"),",")
raw.recompute()
FreeCAD.ActiveDocument.recompute()
try:
FreeCADGui.updateGui( )
except:
pass
CfdTools.executeMacro(analyseCSVMacro) #run the analysis macro - calculates cost
costs[tn]=res.cells["TotalCost"]
print("Total Cost: %f"%costs[tn])
print("saving detailed results")
#save parameters and results for debugging
raw.exportFile(path.join(basepaths[tn],"rawresult.csv"),",")
res.exportFile(path.join(basepaths[tn],"result.csv"),",")
current.exportFile(path.join(basepaths[tn],"parameters.csv"),",")
geometry.exportFile(path.join(basepaths[tn],"geometry.csv"),",")
mass.exportFile(path.join(basepaths[tn],"mass.csv"),",")
gradients[tn]=costs[tn]-costs[0]
state[tn]=params[tn]["current"]
deviationcorelation2=[]
costcorelation2=[]
cost2corelation2=[]
for pn in rparams:
#go through different lines in spreadsheet and save values for sstate
for suffix in ("Absolute","Slope","Center"):
deviationcorelation2.append(res.cells[pn+suffix+"Deviation"])
costcorelation2.append(res.cells[pn+suffix+"Cost"])
cost2corelation2.append(res.cells[pn+suffix+"Deviation"])
deviationcorelation[tn]="tuple"+str(tuple(deviationcorelation2))
costcorelation[tn]="tuple"+str(tuple(costcorelation2))
cost2corelation[tn]="tuple"+str(tuple(cost2corelation2))
print("State:"+str(state))
print("Cost:"+str(costs))
print("Gradient (normalized to stepsize):"+str(gradients))
sstate.insertRows("1",1)
sstate.recompute()
sstate.set("A1","=tuple"+str(tuple(state.values())))
sstate.set("B1","=tuple"+str(tuple(costs.values())))
sstate.set("C1","=tuple"+str(tuple(gradients.values())))
sstate.set("D1","=tuple("+'; '.join((i for i in deviationcorelation.values()))+")")
sstate.set("E1","=tuple("+'; '.join((i for i in costcorelation.values()))+")")
sstate.set("F1","=tuple("+'; '.join((i for i in cost2corelation.values()))+")")
sstate.set("G1",str(meshsizes[meshsize]))
sstate.recompute()
FreeCAD.ActiveDocument.recompute()
try:
FreeCADGui.updateGui( )
except:
pass
print("setting CSV back to main result")
#set cvs back to the values of configuration 0
raw.importFile(path.join(casepaths[0],"mycsv.csv"),",")
raw.recompute()
FreeCAD.ActiveDocument.recompute()
try:
FreeCADGui.updateGui( )
except:
pass
CfdTools.executeMacro(analyseCSVMacro) #run the analysis macro - calculates cost
#now all costs have bee n calculated, we can change the velocity to the optimal velocity (we are in the "0" configuration)
print("optimizing velocity")
CfdTools.executeMacro(optimizeVelocityMacro)
print("saving main documents")
FreeCAD.ActiveDocument.save()
#print("closing main window")
#try:
# FreeCADGui.getMainWindow().close()
#except:
# pass
#
print("done")