-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWingSolver_OuterLoop.FCMacro
More file actions
101 lines (85 loc) · 3.26 KB
/
Copy pathWingSolver_OuterLoop.FCMacro
File metadata and controls
101 lines (85 loc) · 3.26 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
# -*- coding: utf-8 -*-
import FreeCAD
import FreeCADGui
import WingSolver_dependencies.Macro_Dependencies as md
import os
from CfdOF.Mesh import CfdMeshTools
from CfdOF import CfdTools
import re
import math
import shutil
import time
from datetime import timedelta
start_time=time.time()
mydir = os.path.dirname(__file__)
prepareNextStepMacro=os.path.join(mydir, 'WingSolver_PrepareNextStep.FCMacro')
calcGradientMacro=os.path.join(mydir, 'WingSolver_CalcGradient.FCMacro')
plotResultMacro=os.path.join(mydir, 'WingSolver_PlotResult.FCMacro')
desc=FreeCAD.ActiveDocument.getObjectsByLabel("ParameterDescription")[0]
sstate=FreeCAD.ActiveDocument.getObjectsByLabel("SolverState")[0]
scontrol=FreeCAD.ActiveDocument.getObjectsByLabel("SolverControl")[0]
basedir=desc.cells["BaseDir"]
workingdirbase=os.path.join(basedir,"workingdir")
resultdirbase=os.path.join(basedir,"results")
paramnames=desc.cells[desc.cells["ParameterNames"]]
maxiterations=scontrol.cells["MaxIterations"]
finalcost=scontrol.cells["FinalCost"]
initialLR=scontrol.cells["InitialLearningRate"]
lrAlpha=scontrol.cells["LearningRateAlpha"]
keepgoing=True
while keepgoing:
#read numer of iterations formsstate spreadsheet
iterations=int(re.findall('\d+',sstate.getUsedRange()[1])[0])
try:
#read current cost
cost=float(sstate.cells["B1"][0])
except:
cost=-1.0
print("Solver outer loop, current iteration %d, max iterations %d, current cost %f, final cost %f"%(iterations,maxiterations,cost,finalcost))
if iterations>maxiterations:
print("Max iterations reached")
keepgoing=False
break
if cost!=-1.0:
if cost<finalcost:
print("Final cost reached")
keepgoing=False
break
#set new learningRate
newLR=initialLR*(lrAlpha**(iterations-1))
desc.set("LearningRate","%.8f"%newLR)
print("Preparing next step, learning rate %f"%newLR)
CfdTools.executeMacro(prepareNextStepMacro)
print("Calculating Gradients:")
CfdTools.executeMacro(calcGradientMacro)
print("Collecting results:")
outputfoldername=os.path.join(resultdirbase,str(iterations))
for p in ("0",)+paramnames:
subfolder=os.path.join(outputfoldername,p)
srcfolder=os.path.join(workingdirbase,p)
os.makedirs(subfolder,exist_ok=True)
for f in ("rawresult.csv","result.csv","parameters.csv","geometry.csv","mass.csv"):
srcfile=os.path.join(srcfolder,f)
dstfile=os.path.join(subfolder,f)
try:
shutil.copy(srcfile,dstfile)
except Exception as e:
print("Could not copy file %s, %s"%(srcfile,str(e)))
#also save the whole mesh case (meshCase = workingdir/<config>/meshCase)
#so the mesh can be analysed later - it is otherwise overwritten each iteration
srcmesh=os.path.join(srcfolder,"meshCase")
dstmesh=os.path.join(subfolder,"meshCase")
try:
shutil.copytree(srcmesh,dstmesh,dirs_exist_ok=True)
except Exception as e:
print("Could not copy mesh case %s, %s"%(srcmesh,str(e)))
print("Plotting Result:")
#CfdTools.executeMacro(plotResultMacro)
print("done")
md.spreadsheet_to_csv(sstate,os.path.join(resultdirbase,"sstate.csv"))
end_time=time.time()
# Calculate and format the total runtime
total_time = end_time - start_time
formatted_time = str(timedelta(seconds=total_time))
print(f"Total runtime: {formatted_time}")
print(f"Finished successfully after {formatted_time}. You can now save the data and start a new simulation.")