forked from jaheyns/CfdOF
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TestCfdOF.py
482 lines (386 loc) · 19.1 KB
/
TestCfdOF.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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
# ***************************************************************************
# * *
# * Copyright (c) 2015 - Przemo Firszt <przemo@firszt.eu> *
# * Copyright (c) 2017 Johan Heyns (CSIR) <jheyns@csir.co.za> *
# * Copyright (c) 2017 Oliver Oxtoby (CSIR) <ooxtoby@csir.co.za> *
# * Copyright (c) 2017 Alfred Bogaers (CSIR) <abogaers@csir.co.za> *
# * Copyright (c) 2021-2022 Oliver Oxtoby <oliveroxtoby@gmail.com> *
# * Copyright (c) 2022 Jonathan Bergh <bergh.jonathan@gmail.com> *
# * *
# * This program is free software: you can redistribute it and/or modify *
# * it under the terms of the GNU Lesser General Public License as *
# * published by the Free Software Foundation, either version 3 of the *
# * License, or (at your option) any later version. *
# * *
# * This program is distributed in the hope that it will be useful, *
# * but WITHOUT ANY WARRANTY; without even the implied warranty of *
# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
# * GNU Lesser General Public License for more details. *
# * *
# * You should have received a copy of the GNU Lesser General Public *
# * License along with this program. If not, *
# * see <https://www.gnu.org/licenses/>. *
# * *
# ***************************************************************************
import FreeCAD
import FreeCADGui
from CfdOF import CfdAnalysis as CfdAnalysis
from CfdOF.Solve import CfdSolverFoam
from CfdOF.Solve import CfdPhysicsSelection
from CfdOF.Solve import CfdInitialiseFlowField
from CfdOF.Solve import CfdFluidMaterial
from CfdOF.Mesh import CfdMesh
from CfdOF.Solve import CfdFluidBoundary
from CfdOF import CfdTools
from CfdOF.Solve import CfdCaseWriterFoam
from CfdOF.Mesh import CfdMeshTools
from CfdOF.Solve import CfdRunnableFoam
import tempfile
import unittest
import os
import shutil
# ***************************************************************************
# *
# CFD WB unit tests *
# *
# To run: *
# * From command line: FreeCAD -t TestCfdOF *
# * From GUI: 'Test framework' Workbench -> Self-test -> 'TestCfdOF' *
# *
# ***************************************************************************
home_path = CfdTools.getModulePath()
temp_dir = tempfile.gettempdir()
test_file_dir = os.path.join(home_path, 'Data', 'TestFiles')
def fccPrint(message):
FreeCAD.Console.PrintMessage('{} \n'.format(message))
class BlockTest(unittest.TestCase):
__doc_name = 'block'
__part_name = 'Box'
def setUp(self):
""" Load document with part. """
print (test_file_dir)
part_file = os.path.join(test_file_dir, 'parts', self.__class__.__doc_name + '.fcstd')
FreeCAD.open(part_file)
FreeCAD.setActiveDocument(self.__class__.__doc_name)
self.active_doc = FreeCAD.ActiveDocument
self.active_doc.recompute()
def createNewAnalysis(self):
self.analysis = CfdAnalysis.makeCfdAnalysis('CfdAnalysis')
CfdTools.setActiveAnalysis(self.analysis)
self.active_doc.recompute()
def createNewSolver(self):
self.solver_object = CfdSolverFoam.makeCfdSolverFoam()
self.analysis.addObject(self.solver_object)
self.solver_object.EndTime = 100
self.solver_object.ConvergenceTol = 0.001
self.solver_object.Parallel = False
self.active_doc.recompute()
def createNewPhysics(self):
self.physics_object = CfdPhysicsSelection.makeCfdPhysicsSelection()
self.analysis.addObject(self.physics_object)
phys = self.physics_object
phys.Time = 'Steady'
phys.Flow = 'Isothermal'
phys.Turbulence = 'Laminar'
self.active_doc.recompute()
def createNewInitialise(self):
self.initialise_object = CfdInitialiseFlowField.makeCfdInitialFlowField()
self.analysis.addObject(self.initialise_object)
init_var = self.initialise_object
init_var.PotentialFlowP = True
init_var.UseOutletPValue = False
self.active_doc.recompute()
def createNewFluidProperty(self):
self.material_object = CfdFluidMaterial.makeCfdFluidMaterial('FluidProperties')
self.analysis.addObject(self.material_object)
mat = self.material_object.Material
mat['Name'] = 'None'
mat['Density'] = '1.20 kg/m^3'
mat['DynamicViscosity'] = '0.000018 kg/m/s'
self.active_doc.recompute()
def createNewMesh(self, mesh_name):
self.mesh_object = CfdMesh.makeCfdMesh(mesh_name)
self.analysis.addObject(self.mesh_object)
doc = FreeCAD.getDocument(self.__class__.__doc_name)
obj = doc.getObject(mesh_name)
obj.Part = doc.getObject(self.__class__.__part_name)
if obj.isDerivedFrom("Fem::FemMeshObject"):
obj.ViewObject.show()
obj.CharacteristicLengthMax = "80 mm"
obj.MeshUtility = "gmsh"
obj.ElementDimension = "3D"
def createInletBoundary(self):
self.inlet_boundary = CfdFluidBoundary.makeCfdFluidBoundary('inlet')
self.analysis.addObject(self.inlet_boundary)
bc_set = self.inlet_boundary
bc_set.BoundaryType = 'inlet'
bc_set.BoundarySubType = 'uniformVelocityInlet'
bc_set.Ux = 1
bc_set.Uy = 0
bc_set.Uz = 0
# Test addSelection and rebuild_list_references
doc = FreeCAD.getDocument(self.__class__.__doc_name)
obj = doc.getObject('inlet')
vobj = obj.ViewObject
from CfdOF.Solve import TaskPanelCfdFluidBoundary
physics_model = CfdTools.getPhysicsModel(self.analysis)
material_objs = CfdTools.getMaterials(self.analysis)
taskd = TaskPanelCfdFluidBoundary.TaskPanelCfdFluidBoundary(obj, physics_model, material_objs)
taskd.selecting_references = True
taskd.faceSelector.addSelection(doc.Name, self.__class__.__part_name, 'Face1')
# Give scheduled recompute a chance to happen
FreeCADGui.updateGui()
taskd.accept()
def createOutletBoundary(self):
self.outlet_boundary = CfdFluidBoundary.makeCfdFluidBoundary('outlet')
self.analysis.addObject(self.outlet_boundary)
bc_set = self.outlet_boundary
bc_set.BoundaryType = 'outlet'
bc_set.BoundarySubType = 'staticPressureOutlet'
bc_set.Pressure = 0.0
doc = FreeCAD.getDocument(self.__class__.__doc_name)
obj = doc.getObject('Box')
self.outlet_boundary.ShapeRefs = [(obj, ('Face4'))]
FreeCADGui.doCommand("FreeCAD.getDocument('"+self.__class__.__doc_name+"').recompute()")
def createWallBoundary(self):
self.wall_boundary = CfdFluidBoundary.makeCfdFluidBoundary('wall')
self.analysis.addObject(self.wall_boundary)
bc_set = self.wall_boundary
bc_set.BoundaryType = 'wall'
bc_set.BoundarySubType = 'fixedWall'
doc = FreeCAD.getDocument(self.__class__.__doc_name)
obj = doc.getObject('Box')
self.wall_boundary.ShapeRefs = [(obj, ('Face2', 'Face3'))]
FreeCADGui.doCommand("FreeCAD.getDocument('"+self.__class__.__doc_name+"').recompute()")
def createSlipBoundary(self):
self.slip_boundary = CfdFluidBoundary.makeCfdFluidBoundary('slip')
self.analysis.addObject(self.slip_boundary)
bc_set = self.slip_boundary
bc_set.BoundaryType = 'wall'
bc_set.BoundarySubType = 'slipWall'
doc = FreeCAD.getDocument(self.__class__.__doc_name)
obj = doc.getObject('Box')
self.slip_boundary.ShapeRefs = [(obj, ('Face5', 'Face6'))]
FreeCADGui.doCommand("FreeCAD.getDocument('"+self.__class__.__doc_name+"').recompute()")
def writeCaseFiles(self):
print ('Write mesh files ...')
from CfdOF.Mesh import TaskPanelCfdMesh
taskd = TaskPanelCfdMesh.TaskPanelCfdMesh(self.mesh_object)
taskd.obj = self.mesh_object.ViewObject
taskd.writeMesh()
taskd.closed()
print ('Write case files ...')
from CfdOF.Solve import TaskPanelCfdSolverControl
solver_runner = CfdRunnableFoam.CfdRunnableFoam(self.analysis, self.solver_object)
taskd = TaskPanelCfdSolverControl.TaskPanelCfdSolverControl(solver_runner)
taskd.obj = self.solver_object.ViewObject
taskd.write_input_file_handler()
taskd.closing()
def test_new_analysis(self):
fccPrint('--------------- Start of CFD tests ---------------')
fccPrint('Checking CFD {} analysis ...'.format(self.__class__.__doc_name))
self.createNewAnalysis()
self.assertTrue(self.analysis, "CfdTest of analysis failed")
fccPrint('Checking CFD {} physics object ...'.format(self.__class__.__doc_name))
self.createNewPhysics()
self.assertTrue(self.physics_object, "CfdTest of physics object failed")
self.analysis.addObject(self.physics_object)
fccPrint('Checking CFD {} initialise ...'.format(self.__class__.__doc_name))
self.createNewInitialise()
self.assertTrue(self.initialise_object, "CfdTest of initialise failed")
self.analysis.addObject(self.initialise_object)
fccPrint('Checking CFD {} fluid property ...'.format(self.__class__.__doc_name))
self.createNewFluidProperty()
self.assertTrue(self.material_object, "CfdTest of fluid property failed")
self.analysis.addObject(self.material_object)
fccPrint('Checking Cfd {} velocity inlet boundary ...'.format(self.__class__.__doc_name))
self.createInletBoundary()
self.assertTrue(self.inlet_boundary, "CfdTest of inlet boundary failed")
self.analysis.addObject(self.inlet_boundary)
fccPrint('Checking Cfd {} velocity outlet boundary ...'.format(self.__class__.__doc_name))
self.createOutletBoundary()
self.assertTrue(self.outlet_boundary, "CfdTest of outlet boundary failed")
self.analysis.addObject(self.outlet_boundary)
fccPrint('Checking Cfd {} wall boundary ...'.format(self.__class__.__doc_name))
self.createWallBoundary()
self.assertTrue(self.wall_boundary, "CfdTest of wall boundary failed")
self.analysis.addObject(self.wall_boundary)
fccPrint('Checking Cfd {} slip boundary ...'.format(self.__class__.__doc_name))
self.createSlipBoundary()
self.assertTrue(self.slip_boundary, "CfdTest of slip boundary failed")
self.analysis.addObject(self.slip_boundary)
fccPrint('Checking CFD {} mesh ...'.format(self.__class__.__doc_name))
self.createNewMesh('mesh')
self.assertTrue(self.mesh_object, "CfdTest of mesh failed")
self.analysis.addObject(self.mesh_object)
fccPrint('Checking CFD {} solver ...'.format(self.__class__.__doc_name))
self.createNewSolver()
self.assertTrue(self.solver_object, self.__class__.__doc_name + " of solver failed")
self.analysis.addObject(self.solver_object)
fccPrint('Writing {} case files ...'.format(self.__class__.__doc_name))
self.analysis.OutputPath = temp_dir
self.solver_object.InputCaseName = "case" + self.__class__.__doc_name
self.mesh_object.CaseName = "meshCase" + self.__class__.__doc_name
self.writeCaseFiles()
mesh_ref_dir = os.path.join(test_file_dir, "cases", self.__class__.__doc_name, "meshCase")
mesh_case_dir = os.path.join(CfdTools.getOutputPath(self.analysis), self.mesh_object.CaseName)
ref_dir = os.path.join(test_file_dir, "cases", self.__class__.__doc_name, "case")
case_dir = os.path.join(CfdTools.getOutputPath(self.analysis), self.solver_object.InputCaseName)
comparePaths(mesh_ref_dir, mesh_case_dir, self)
comparePaths(ref_dir, case_dir, self)
#shutil.rmtree(mesh_case_dir)
#shutil.rmtree(case_dir)
fccPrint('--------------- End of CFD tests ---------------')
def tearDown(self):
FreeCAD.closeDocument(self.__class__.__doc_name)
pass
class MacroTest:
""" Base class for macro-based regression tests below """
def __init__(self, var):
self.child_instance = None
def setUp(self):
pass
def writeCaseFiles(self):
analysis = CfdTools.getActiveAnalysis()
self.meshwriter = CfdMeshTools.CfdMeshTools(CfdTools.getMeshObject(analysis))
self.meshwriter.writeMesh()
self.writer = CfdCaseWriterFoam.CfdCaseWriterFoam(FreeCAD.ActiveDocument.CfdAnalysis)
self.writer.writeCase()
def runTest(self, dir_name, macro_names):
fccPrint('--------------- Start of CFD tests ---------------')
for m in macro_names:
macro_name = os.path.join(home_path, "Demos", dir_name, m)
fccPrint('Running {} macro {} ...'.format(dir_name, macro_name))
CfdTools.executeMacro(macro_name)
fccPrint('Writing {} case files ...'.format(dir_name))
analysis = CfdTools.getActiveAnalysis()
analysis.OutputPath = temp_dir
CfdTools.getSolver(analysis).InputCaseName = "case" + dir_name
CfdTools.getMeshObject(analysis).CaseName = "meshCase" + dir_name
self.writeCaseFiles()
self.child_instance.assertTrue(self.writer, "CfdTest of writer failed")
mesh_ref_dir = os.path.join(test_file_dir, "cases", dir_name, "meshCase")
mesh_case_dir = self.meshwriter.meshCaseDir
comparePaths(mesh_ref_dir, mesh_case_dir, self.child_instance)
ref_dir = os.path.join(test_file_dir, "cases", dir_name, "case")
case_dir = self.writer.case_folder
comparePaths(ref_dir, case_dir, self.child_instance)
#shutil.rmtree(mesh_case_dir)
#shutil.rmtree(case_dir)
fccPrint('--------------- End of CFD tests ---------------')
def closeDoc(self):
FreeCAD.closeDocument(FreeCAD.ActiveDocument.Name)
class ElbowTest(unittest.TestCase, MacroTest):
__dir_name = 'Elbow'
__macros = ['elbow.FCMacro']
def __init__(self, var):
super().__init__(var)
MacroTest.child_instance = self
def test_run(self):
self.runTest(self.__class__.__dir_name, self.__class__.__macros)
def tearDown(self):
self.closeDoc()
class DuctTest(unittest.TestCase, MacroTest):
__dir_name = 'Duct'
__macros = ['01-geom.FCMacro', '02-mesh.FCMacro', '03-porous.FCMacro', '04-screen.FCMacro']
def __init__(self, var):
super().__init__(var)
MacroTest.child_instance = self
def test_run(self):
self.runTest(self.__class__.__dir_name, self.__class__.__macros)
def tearDown(self):
self.closeDoc()
class ViscousTubeBundleTest(unittest.TestCase, MacroTest):
__dir_name = 'ViscousTubeBundle'
__macros = ['viscousTubeBundle.FCMacro']
def __init__(self, var):
super().__init__(var)
MacroTest.child_instance = self
def test_run(self):
self.runTest(self.__class__.__dir_name, self.__class__.__macros)
def tearDown(self):
self.closeDoc()
class UAVTest(unittest.TestCase, MacroTest):
__dir_name = 'UAV'
__macros = ['01-partDesign.FCMacro', '02-firstAnalysis.FCMacro', '03-refineMesh.FCMacro']
def __init__(self, var):
super().__init__(var)
MacroTest.child_instance = self
def test_run(self):
self.runTest(self.__class__.__dir_name, self.__class__.__macros)
def tearDown(self):
self.closeDoc()
class ProjectileTest(unittest.TestCase, MacroTest):
__dir_name = 'Projectile'
__macros = ['01-geometry.FCMacro', '02-mesh.FCMacro', '03-boundaries.FCMacro', '04-forceCoeffs.FCMacro']
def __init__(self, var):
super().__init__(var)
MacroTest.child_instance = self
def test_run(self):
self.runTest(self.__class__.__dir_name, self.__class__.__macros)
def tearDown(self):
self.closeDoc()
class LESStepTest(unittest.TestCase, MacroTest):
__dir_name = 'LESStep'
__macros = ['backwardStep.FCMacro']
def __init__(self, var):
super().__init__(var)
MacroTest.child_instance = self
def test_run(self):
self.runTest(self.__class__.__dir_name, self.__class__.__macros)
def tearDown(self):
self.closeDoc()
class DamBreak3DTest(unittest.TestCase, MacroTest):
__dir_name = 'DamBreak3D'
__macros = ['01-geom.FCMacro', '02-analysis.FCMacro', '03-probes.FCMacro','04-adaptiveMesh.FCMacro']
def __init__(self, var):
super().__init__(var)
MacroTest.child_instance = self
def test_run(self):
self.runTest(self.__class__.__dir_name, self.__class__.__macros)
def tearDown(self):
self.closeDoc()
def compareInpFiles(file_name1, file_name2):
file1 = open(file_name1, 'r')
f1 = file1.readlines()
file1.close()
lf1 = [l for l in f1 if not l.startswith("FOAMDIR=") and not l.startswith("GMSH_EXE=")
and not l.startswith("set FOAMDIR") and not l.startswith("call %FOAMDIR%") and not l.startswith("$GMSH_EXE")]
lf1 = forceUnixLineEnds(lf1)
file2 = open(file_name2, 'r')
f2 = file2.readlines()
file2.close()
lf2 = [l for l in f2 if not l.startswith("FOAMDIR=") and not l.startswith("GMSH_EXE=")
and not l.startswith("set FOAMDIR") and not l.startswith("call %FOAMDIR%") and not l.startswith("$GMSH_EXE")]
lf2 = forceUnixLineEnds(lf2)
import difflib
diff = difflib.unified_diff(lf1, lf2, n=0)
result = ''
for l in diff:
result += l
if result:
result = "Comparing {} to {} failed!\n".format(file_name1, file_name2) + result
return result
def forceUnixLineEnds(line_list):
new_line_list = []
for l in line_list:
if l.endswith("\r\n"):
l = l[:-2] + '\n'
new_line_list.append(l)
return new_line_list
def comparePaths(ref_dir, case_dir, unit_test):
""" Compares every file in ref_dir to corresponding one in case_dir """
fccPrint("Comparing files in {} to those in {}".format(case_dir, ref_dir))
unit_test.assertTrue(os.path.exists(ref_dir))
for path, directories, files in os.walk(ref_dir):
for file in files:
ref_file = os.path.join(path, file)
case_file = os.path.join(case_dir, os.path.relpath(path, ref_dir), file)
fccPrint('Comparing {} to {}'.format(ref_file, case_file))
ret = compareInpFiles(ref_file, case_file)
unit_test.assertFalse(ret, "File \'{}\' test failed.\n{}".format(file, ret))
def runCfdUnitTests():
suite = unittest.TestSuite()
suite.addTest(unittest.defaultTestLoader.loadTestsFromName("TestCfdOF"))
r = unittest.TextTestRunner()
r.run(suite)