/
writer.py
1623 lines (1521 loc) · 67.2 KB
/
writer.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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# ***************************************************************************
# * Copyright (c) 2017 Markus Hovorka <m.hovorka@live.de> *
# * Copyright (c) 2020 Bernd Hahnebach <bernd@bimstatik.org> *
# * *
# * This file is part of the FreeCAD CAx development system. *
# * *
# * This program is free software; you can redistribute it and/or modify *
# * it under the terms of the GNU Lesser General Public License (LGPL) *
# * as published by the Free Software Foundation; either version 2 of *
# * the License, or (at your option) any later version. *
# * for detail see the LICENCE text file. *
# * *
# * 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 Library General Public License for more details. *
# * *
# * You should have received a copy of the GNU Library General Public *
# * License along with this program; if not, write to the Free Software *
# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
# * USA *
# * *
# ***************************************************************************
__title__ = "FreeCAD FEM solver Elmer writer"
__author__ = "Markus Hovorka"
__url__ = "https://www.freecadweb.org"
## \addtogroup FEM
# @{
import os
import os.path
import subprocess
import tempfile
from platform import system
from FreeCAD import Console
from FreeCAD import Units
from FreeCAD import ParamGet
import Fem
from . import sifio
from . import solver as solverClass
from .. import settings
from femmesh import gmshtools
from femtools import constants
from femtools import femutils
from femtools import membertools
from .equations import elasticity
from .equations import electricforce
from .equations import flow
from .equations import heat
_STARTINFO_NAME = "ELMERSOLVER_STARTINFO"
_SIF_NAME = "case.sif"
_ELMERGRID_IFORMAT = "8"
_ELMERGRID_OFORMAT = "2"
_SOLID_PREFIX = "Solid"
def _getAllSubObjects(obj):
s = ["Solid" + str(i + 1) for i in range(len(obj.Shape.Solids))]
s.extend(("Face" + str(i + 1) for i in range(len(obj.Shape.Faces))))
s.extend(("Edge" + str(i + 1) for i in range(len(obj.Shape.Edges))))
s.extend(("Vertex" + str(i + 1) for i in range(len(obj.Shape.Vertexes))))
return s
class Writer(object):
def __init__(self, solver, directory, testmode=False):
self.analysis = solver.getParentGroup()
self.solver = solver
self.directory = directory
Console.PrintMessage("Write elmer input files to: {}\n".format(self.directory))
self.testmode = testmode
self._usedVarNames = set()
self._builder = sifio.Builder()
self._handledObjects = set()
self._handleUnits()
self._handleConstants()
def getHandledConstraints(self):
return self._handledObjects
def write_solver_input(self):
self._handleRedifinedConstants()
self._handleSimulation()
self._handleHeat()
self._handleElasticity()
self._handleElectrostatic()
self._handleFlux()
self._handleElectricforce()
self._handleFlow()
self._addOutputSolver()
self._writeSif()
self._writeMesh()
self._writeStartinfo()
def _handleUnits(self):
# Elmer solver writer no longer uses FreeCAD unit system
# to retrieve units for writing the sif file
#
# ATM Elmer writer uses SI units only
#
# see forum topic: https://forum.freecadweb.org/viewtopic.php?f=18&t=70150
#
# TODO: adapt method and comment
# should be only one system for all solver and not in each solver
# https://forum.freecadweb.org/viewtopic.php?t=47895
# https://forum.freecadweb.org/viewtopic.php?t=48451
# https://forum.freecadweb.org/viewtopic.php?f=10&t=48642
# The FreeCAD unit schema is only used to determine the schema number
# all definition are done here ATM
# keep in mind a unit schema might not be consistent:
# Length could be mm and Area could be m2 and Volume could be cm3
# as long as only the seven base units are retrieved from a unit schema
# the units are consistent
# TODO retrieve the seven base units from FreeCAD unit schema
# instead of hard coding them here for a second once
self.unit_schema = Units.Scheme.SI1
self.unit_system = { # standard FreeCAD Base units = unit schema 0
"L": "m",
"M": "kg",
"T": "s",
"I": "A",
"O": "K",
"N": "mol",
"J": "cd",
}
param = ParamGet("User parameter:BaseApp/Preferences/Units")
self.unit_schema = param.GetInt("UserSchema", Units.Scheme.SI1)
if self.unit_schema == Units.Scheme.SI1:
Console.PrintMessage(
"The FreeCAD standard unit schema mm/kg/s is used. "
"Elmer sif-file writing is however done in SI units.\n"
)
elif self.unit_schema == Units.Scheme.SI2:
Console.PrintMessage(
"The SI unit schema m/kg/s is used. "
"Elmer sif-file writing is done in SI-units.\n"
)
self.unit_system = {
"L": "m",
"M": "kg",
"T": "s",
"I": "A",
"O": "K",
"N": "mol",
"J": "cd",
}
elif self.unit_schema == Units.Scheme.FemMilliMeterNewton:
# see also unit comment in calculix writer
Console.PrintMessage(
"The FEM unit schema mm/N/s is used. "
"Elmer sif-file writing is however done in SI units.\n"
)
self.unit_system = {
"L": "m",
"M": "kg",
"T": "s",
"I": "A",
"O": "K",
"N": "mol",
"J": "cd",
}
elif (
self.unit_schema > Units.Scheme.SI2
and self.unit_schema != Units.Scheme.FemMilliMeterNewton
):
Console.PrintMessage(
"Unit schema: {} not supported by Elmer writer. "
"The FreeCAD standard unit schema mm/kg/s is used. "
"Elmer sif-file writing is done in Standard FreeCAD units.\n"
.format(Units.listSchemas(self.unit_schema))
)
def _getFromUi(self, value, unit, outputDim):
quantity = Units.Quantity(str(value) + str(unit))
return self._convert(quantity, outputDim)
def _convert(self, quantityStr, unit):
quantity = Units.Quantity(quantityStr)
for key, setting in self.unit_system.items():
unit = unit.replace(key, setting)
return float(quantity.getValueAs(unit))
def _handleConstants(self):
self.constsdef = {
"Gravity": constants.gravity(),
"StefanBoltzmann": constants.stefan_boltzmann(),
"PermittivityOfVacuum": constants.vacuum_permittivity(),
"BoltzmannConstant": constants.boltzmann_constant(),
}
def _getConstant(self, name, unit_dimension):
# TODO without method directly use self.constsdef[name]
return self._convert(self.constsdef[name], unit_dimension)
def _setConstant(self, name, quantityStr):
# TODO without method directly use self.constsdef[name]
if name == "PermittivityOfVacuum":
theUnit = "s^4*A^2 / (m^3*kg)"
self.constsdef[name] = "{} {}".format(self._convert(quantityStr, theUnit), theUnit)
return True
def _writeMesh(self):
mesh = self._getSingleMember("Fem::FemMeshObject")
unvPath = os.path.join(self.directory, "mesh.unv")
groups = []
groups.extend(self._builder.getBodyNames())
groups.extend(self._builder.getBoundaryNames())
self._exportToUnv(groups, mesh, unvPath)
if self.testmode:
Console.PrintMessage(
"Solver Elmer testmode, ElmerGrid will not be used. "
"It might not be installed.\n"
)
else:
binary = settings.get_binary("ElmerGrid")
num_cores = settings.get_cores("ElmerGrid")
if binary is None:
raise WriteError("Could not find ElmerGrid binary.")
# for multithreading we first need a normal mesh creation run
# then a second to split the mesh into the number of used cores
argsBasic = [binary,
_ELMERGRID_IFORMAT,
_ELMERGRID_OFORMAT,
unvPath]
args = argsBasic
args.extend(["-out", self.directory])
if system() == "Windows":
subprocess.call(
args,
stdout=subprocess.DEVNULL,
startupinfo=femutils.startProgramInfo("hide")
)
else:
subprocess.call(args, stdout=subprocess.DEVNULL)
if int(num_cores) > 1:
args = argsBasic
args.extend(["-partdual", "-metiskway", num_cores,
"-out", self.directory])
if system() == "Windows":
subprocess.call(
args,
stdout=subprocess.DEVNULL,
startupinfo=femutils.startProgramInfo("hide")
)
else:
subprocess.call(args, stdout=subprocess.DEVNULL)
def _writeStartinfo(self):
path = os.path.join(self.directory, _STARTINFO_NAME)
with open(path, "w") as f:
f.write(_SIF_NAME)
def _exportToUnv(self, groups, mesh, meshPath):
unvGmshFd, unvGmshPath = tempfile.mkstemp(suffix=".unv")
brepFd, brepPath = tempfile.mkstemp(suffix=".brep")
geoFd, geoPath = tempfile.mkstemp(suffix=".geo")
os.close(brepFd)
os.close(geoFd)
os.close(unvGmshFd)
tools = gmshtools.GmshTools(mesh)
tools.group_elements = {g: [g] for g in groups}
tools.group_nodes_export = False
tools.ele_length_map = {}
tools.temp_file_geometry = brepPath
tools.temp_file_geo = geoPath
tools.temp_file_mesh = unvGmshPath
tools.get_dimension()
tools.get_region_data()
tools.get_boundary_layer_data()
tools.write_part_file()
tools.write_geo()
if self.testmode:
Console.PrintMessage(
"Solver Elmer testmode, Gmsh will not be used. "
"It might not be installed.\n"
)
import shutil
shutil.copyfile(geoPath, os.path.join(self.directory, "group_mesh.geo"))
else:
tools.get_gmsh_command()
tools.run_gmsh_with_geo()
ioMesh = Fem.FemMesh()
ioMesh.read(unvGmshPath)
ioMesh.write(meshPath)
os.remove(brepPath)
os.remove(geoPath)
os.remove(unvGmshPath)
def _handleRedifinedConstants(self):
"""
redefine constants in self.constsdef according constant redefine objects
"""
permittivity_objs = self._getMember("Fem::ConstantVacuumPermittivity")
if len(permittivity_objs) == 1:
Console.PrintLog("Constand permittivity overwriting.\n")
self._setConstant("PermittivityOfVacuum", permittivity_objs[0].VacuumPermittivity)
elif len(permittivity_objs) > 1:
Console.PrintError(
"More than one permittivity constant overwriting objects ({} objs). "
"The permittivity constant overwriting is ignored.\n"
.format(len(permittivity_objs))
)
def _handleSimulation(self):
# check if we need to update the equation
self._updateSimulation(self.solver)
# output the equation parameters
# first check what equations we have
hasHeat = False
for equation in self.solver.Group:
if femutils.is_of_type(equation, "Fem::EquationElmerHeat"):
hasHeat = True
if hasHeat:
self._simulation("BDF Order", self.solver.BDFOrder)
self._simulation("Coordinate System", "Cartesian 3D")
self._simulation("Coordinate Mapping", (1, 2, 3))
# Elmer uses SI base units, but our mesh is in mm, therefore we must tell
# the solver that we have another scale
self._simulation("Coordinate Scaling", 0.001)
self._simulation("Output Intervals", 1)
self._simulation("Simulation Type", self.solver.SimulationType)
if self.solver.SimulationType == "Steady State":
self._simulation(
"Steady State Max Iterations",
self.solver.SteadyStateMaxIterations
)
self._simulation(
"Steady State Min Iterations",
self.solver.SteadyStateMinIterations
)
if (
self.solver.SimulationType == "Scanning"
or self.solver.SimulationType == "Transient"
):
self._simulation("Timestep Intervals", self.solver.TimestepIntervals)
self._simulation("Timestep Sizes", self.solver.TimestepSizes)
# Output Intervals must be equal to Timestep Intervals
self._simulation("Output Intervals", self.solver.TimestepIntervals)
if hasHeat:
self._simulation("Timestepping Method", "BDF")
self._simulation("Use Mesh Names", True)
def _updateSimulation(self, solver):
# updates older simulations
if not hasattr(self.solver, "BDFOrder"):
solver.addProperty(
"App::PropertyIntegerConstraint",
"BDFOrder",
"Timestepping",
"Order of time stepping method 'BDF'"
)
solver.BDFOrder = (2, 1, 5, 1)
if not hasattr(self.solver, "SimulationType"):
solver.addProperty(
"App::PropertyEnumeration",
"SimulationType",
"Type",
""
)
solver.SimulationType = solverClass.SIMULATION_TYPE
solver.SimulationType = "Steady State"
if not hasattr(self.solver, "TimestepIntervals"):
solver.addProperty(
"App::PropertyIntegerList",
"TimestepIntervals",
"Timestepping",
(
"List of maximum optimization rounds if 'Simulation Type'\n"
"is either 'Scanning' or 'Transient'"
)
)
solver.TimestepIntervals = [100]
if not hasattr(self.solver, "TimestepSizes"):
solver.addProperty(
"App::PropertyFloatList",
"TimestepSizes",
"Timestepping",
(
"List of time steps of optimization if 'Simulation Type'\n"
"is either 'Scanning' or 'Transient'"
)
)
solver.TimestepSizes = [0.1]
def _handleHeat(self):
activeIn = []
for equation in self.solver.Group:
if femutils.is_of_type(equation, "Fem::EquationElmerHeat"):
if equation.References:
activeIn = equation.References[0][1]
else:
activeIn = self._getAllBodies()
solverSection = self._getHeatSolver(equation)
for body in activeIn:
self._addSolver(body, solverSection)
self._handleHeatEquation(activeIn, equation)
if activeIn:
self._handleHeatConstants()
self._handleHeatBndConditions()
self._handleHeatInitial(activeIn)
self._handleHeatBodyForces(activeIn)
self._handleHeatMaterial(activeIn)
def _getHeatSolver(self, equation):
# check if we need to update the equation
self._updateHeatSolver(equation)
# output the equation parameters
s = self._createNonlinearSolver(equation)
s["Equation"] = equation.Name
s["Procedure"] = sifio.FileAttr("HeatSolve/HeatSolver")
s["Bubbles"] = equation.Bubbles
s["Exec Solver"] = "Always"
s["Optimize Bandwidth"] = True
s["Stabilize"] = equation.Stabilize
s["Variable"] = self._getUniqueVarName("Temperature")
return s
def _handleHeatConstants(self):
self._constant(
"Stefan Boltzmann",
self._getConstant("StefanBoltzmann", "M/(O^4*T^3)"))
def _handleHeatEquation(self, bodies, equation):
for b in bodies:
if equation.Convection != "None":
self._equation(b, "Convection", equation.Convection)
if equation.PhaseChangeModel != "None":
self._equation(b, "Phase Change Model", equation.PhaseChangeModel)
def _updateHeatSolver(self, equation):
# updates older Heat equations
if not hasattr(equation, "Convection"):
equation.addProperty(
"App::PropertyEnumeration",
"Convection",
"Equation",
"Type of convection to be used"
)
equation.Convection = heat.CONVECTION_TYPE
equation.Convection = "None"
if not hasattr(equation, "PhaseChangeModel"):
equation.addProperty(
"App::PropertyEnumeration",
"PhaseChangeModel",
"Equation",
"Model for phase change"
)
equation.PhaseChangeModel = heat.PHASE_CHANGE_MODEL
equation.PhaseChangeModel = "None"
def _handleHeatBndConditions(self):
for obj in self._getMember("Fem::ConstraintTemperature"):
if obj.References:
for name in obj.References[0][1]:
if obj.ConstraintType == "Temperature":
temp = self._getFromUi(obj.Temperature, "K", "O")
self._boundary(name, "Temperature", temp)
elif obj.ConstraintType == "CFlux":
flux = self._getFromUi(obj.CFlux, "kg*mm^2*s^-3", "M*L^2*T^-3")
self._boundary(name, "Temperature Load", flux)
self._handled(obj)
for obj in self._getMember("Fem::ConstraintHeatflux"):
if obj.References:
for name in obj.References[0][1]:
if obj.ConstraintType == "Convection":
film = self._getFromUi(obj.FilmCoef, "W/(m^2*K)", "M/(T^3*O)")
temp = self._getFromUi(obj.AmbientTemp, "K", "O")
self._boundary(name, "Heat Transfer Coefficient", film)
self._boundary(name, "External Temperature", temp)
elif obj.ConstraintType == "DFlux":
flux = self._getFromUi(obj.DFlux, "W/m^2", "M*T^-3")
self._boundary(name, "Heat Flux BC", True)
self._boundary(name, "Heat Flux", flux)
self._handled(obj)
def _handleHeatInitial(self, bodies):
obj = self._getSingleMember("Fem::ConstraintInitialTemperature")
if obj is not None:
for name in bodies:
temp = self._getFromUi(obj.initialTemperature, "K", "O")
self._initial(name, "Temperature", temp)
self._handled(obj)
def _handleHeatBodyForces(self, bodies):
obj = self._getSingleMember("Fem::ConstraintBodyHeatSource")
if obj is not None:
for name in bodies:
heatSource = self._getFromUi(obj.HeatSource, "W/kg", "L^2*T^-3")
# according Elmer forum W/kg is correct
# http://www.elmerfem.org/forum/viewtopic.php?f=7&t=1765
# 1 watt = kg * m2 / s3 ... W/kg = m2 / s3
self._bodyForce(name, "Heat Source", heatSource)
self._handled(obj)
def _handleHeatMaterial(self, bodies):
tempObj = self._getSingleMember("Fem::ConstraintInitialTemperature")
if tempObj is not None:
refTemp = self._getFromUi(tempObj.initialTemperature, "K", "O")
for name in bodies:
self._material(name, "Reference Temperature", refTemp)
for obj in self._getMember("App::MaterialObject"):
m = obj.Material
refs = (
obj.References[0][1]
if obj.References
else self._getAllBodies())
for name in (n for n in refs if n in bodies):
if "Density" not in m:
raise WriteError(
"Used material does not specify the necessary 'Density'."
)
self._material(
name, "Density",
self._getDensity(m))
if "ThermalConductivity" not in m:
raise WriteError(
"Used material does not specify the necessary 'Thermal Conductivity'."
)
self._material(
name, "Heat Conductivity",
self._convert(m["ThermalConductivity"], "M*L/(T^3*O)"))
if "SpecificHeat" not in m:
raise WriteError(
"Used material does not specify the necessary 'Specific Heat'."
)
self._material(
name, "Heat Capacity",
self._convert(m["SpecificHeat"], "L^2/(T^2*O)"))
def _handleElectrostatic(self):
activeIn = []
for equation in self.solver.Group:
if femutils.is_of_type(equation, "Fem::EquationElmerElectrostatic"):
if equation.References:
activeIn = equation.References[0][1]
else:
activeIn = self._getAllBodies()
solverSection = self._getElectrostaticSolver(equation)
for body in activeIn:
self._addSolver(body, solverSection)
if activeIn:
self._handleElectrostaticConstants()
self._handleElectrostaticBndConditions()
# self._handleElectrostaticInitial(activeIn)
# self._handleElectrostaticBodyForces(activeIn)
self._handleElectrostaticMaterial(activeIn)
def _getElectrostaticSolver(self, equation):
# check if we need to update the equation
self._updateElectrostaticSolver(equation)
# output the equation parameters
s = self._createLinearSolver(equation)
s["Equation"] = "Stat Elec Solver" # equation.Name
s["Procedure"] = sifio.FileAttr("StatElecSolve/StatElecSolver")
s["Variable"] = self._getUniqueVarName("Potential")
s["Variable DOFs"] = 1
if equation.CalculateCapacitanceMatrix is True:
s["Calculate Capacitance Matrix"] = equation.CalculateCapacitanceMatrix
s["Capacitance Matrix Filename"] = equation.CapacitanceMatrixFilename
if equation.CalculateElectricEnergy is True:
s["Calculate Electric Energy"] = equation.CalculateElectricEnergy
if equation.CalculateElectricField is True:
s["Calculate Electric Field"] = equation.CalculateElectricField
if equation.CalculateElectricFlux is True:
s["Calculate Electric Flux"] = equation.CalculateElectricFlux
if equation.CalculateSurfaceCharge is True:
s["Calculate Surface Charge"] = equation.CalculateSurfaceCharge
if equation.ConstantWeights is True:
s["Constant Weights"] = equation.ConstantWeights
s["Exec Solver"] = "Always"
s["Optimize Bandwidth"] = True
if (
equation.CalculateCapacitanceMatrix is False
and (equation.PotentialDifference != 0.0)
):
s["Potential Difference"] = equation.PotentialDifference
s["Stabilize"] = equation.Stabilize
return s
def _updateElectrostaticSolver(self, equation):
# updates older Electrostatic equations
if not hasattr(equation, "CapacitanceMatrixFilename"):
equation.addProperty(
"App::PropertyFile",
"CapacitanceMatrixFilename",
"Electrostatic",
(
"File where capacitance matrix is being saved\n"
"Only used if 'CalculateCapacitanceMatrix' is true"
)
)
equation.CapacitanceMatrixFilename = "cmatrix.dat"
if not hasattr(equation, "ConstantWeights"):
equation.addProperty(
"App::PropertyBool",
"ConstantWeights",
"Electrostatic",
"Use constant weighting for results"
)
if not hasattr(equation, "PotentialDifference"):
equation.addProperty(
"App::PropertyFloat",
"PotentialDifference",
"Electrostatic",
(
"Potential difference in Volt for which capacitance is\n"
"calculated if 'CalculateCapacitanceMatrix' is false"
)
)
equation.PotentialDifference = 0.0
def _handleElectrostaticConstants(self):
self._constant(
"Permittivity Of Vacuum",
self._getConstant("PermittivityOfVacuum", "T^4*I^2/(L^3*M)")
)
# https://forum.freecadweb.org/viewtopic.php?f=18&p=400959#p400959
def _handleElectrostaticMaterial(self, bodies):
for obj in self._getMember("App::MaterialObject"):
m = obj.Material
refs = (
obj.References[0][1]
if obj.References
else self._getAllBodies())
for name in (n for n in refs if n in bodies):
if "RelativePermittivity" in m:
self._material(
name, "Relative Permittivity",
float(m["RelativePermittivity"])
)
def _handleElectrostaticBndConditions(self):
for obj in self._getMember("Fem::ConstraintElectrostaticPotential"):
if obj.References:
for name in obj.References[0][1]:
if obj.PotentialEnabled:
if hasattr(obj, "Potential"):
# Potential was once a float and scaled not fitting SI units
if isinstance(obj.Potential, float):
savePotential = obj.Potential
obj.removeProperty("Potential")
obj.addProperty(
"App::PropertyElectricPotential",
"Potential",
"Parameter",
"Electric Potential"
)
# scale to match SI units
obj.Potential = savePotential * 1e6
potential = float(obj.Potential.getValueAs("V"))
self._boundary(name, "Potential", potential)
if obj.PotentialConstant:
self._boundary(name, "Potential Constant", True)
if obj.ElectricInfinity:
self._boundary(name, "Electric Infinity BC", True)
if obj.ElectricForcecalculation:
self._boundary(name, "Calculate Electric Force", True)
if obj.CapacitanceBodyEnabled:
if hasattr(obj, "CapacitanceBody"):
self._boundary(name, "Capacitance Body", obj.CapacitanceBody)
self._handled(obj)
def _handleFlux(self):
activeIn = []
for equation in self.solver.Group:
if femutils.is_of_type(equation, "Fem::EquationElmerFlux"):
if equation.References:
activeIn = equation.References[0][1]
else:
activeIn = self._getAllBodies()
solverSection = self._getFluxSolver(equation)
for body in activeIn:
self._addSolver(body, solverSection)
def _getFluxSolver(self, equation):
s = self._createLinearSolver(equation)
# check if we need to update the equation
self._updateFluxSolver(equation)
# output the equation parameters
s["Equation"] = "Flux Solver" # equation.Name
s["Procedure"] = sifio.FileAttr("FluxSolver/FluxSolver")
if equation.AverageWithinMaterials is True:
s["Average Within Materials"] = equation.AverageWithinMaterials
s["Calculate Flux"] = equation.CalculateFlux
if equation.CalculateFluxAbs is True:
s["Calculate Flux Abs"] = equation.CalculateFluxAbs
if equation.CalculateFluxMagnitude is True:
s["Calculate Flux Magnitude"] = equation.CalculateFluxMagnitude
s["Calculate Grad"] = equation.CalculateGrad
if equation.CalculateGradAbs is True:
s["Calculate Grad Abs"] = equation.CalculateGradAbs
if equation.CalculateGradMagnitude is True:
s["Calculate Grad Magnitude"] = equation.CalculateGradMagnitude
if equation.DiscontinuousGalerkin is True:
s["Discontinuous Galerkin"] = equation.DiscontinuousGalerkin
if equation.EnforcePositiveMagnitude is True:
s["Enforce Positive Magnitude"] = equation.EnforcePositiveMagnitude
s["Flux Coefficient"] = equation.FluxCoefficient
s["Flux Variable"] = equation.FluxVariable
s["Stabilize"] = equation.Stabilize
return s
def _updateFluxSolver(self, equation):
# updates older Flux equations
if not hasattr(equation, "AverageWithinMaterials"):
equation.addProperty(
"App::PropertyBool",
"AverageWithinMaterials",
"Flux",
(
"Enforces continuity within the same material\n"
"in the 'Discontinuous Galerkin' discretization"
)
)
if hasattr(equation, "Bubbles"):
# Bubbles was removed because it is unused by Elmer for the flux solver
equation.removeProperty("Bubbles")
if not hasattr(equation, "CalculateFluxAbs"):
equation.addProperty(
"App::PropertyBool",
"CalculateFluxAbs",
"Flux",
"Computes absolute of flux vector"
)
if not hasattr(equation, "CalculateFluxMagnitude"):
equation.addProperty(
"App::PropertyBool",
"CalculateFluxMagnitude",
"Flux",
"Computes magnitude of flux vector field"
)
if not hasattr(equation, "CalculateGradAbs"):
equation.addProperty(
"App::PropertyBool",
"CalculateGradAbs",
"Flux",
"Computes absolute of gradient field"
)
if not hasattr(equation, "CalculateGradMagnitude"):
equation.addProperty(
"App::PropertyBool",
"CalculateGradMagnitude",
"Flux",
"Computes magnitude of gradient field"
)
if not hasattr(equation, "DiscontinuousGalerkin"):
equation.addProperty(
"App::PropertyBool",
"DiscontinuousGalerkin",
"Flux",
(
"Enable if standard Galerkin approximation leads to\n"
"unphysical results when there are discontinuities"
)
)
if not hasattr(equation, "EnforcePositiveMagnitude"):
equation.addProperty(
"App::PropertyBool",
"EnforcePositiveMagnitude",
"Flux",
(
"If true, negative values of computed magnitude fields\n"
"are a posteriori set to zero."
)
)
if not hasattr(equation, "FluxCoefficient"):
equation.addProperty(
"App::PropertyString",
"FluxCoefficient",
"Flux",
"Name of proportionality coefficient\nto compute the flux"
)
def _handleElectricforce(self):
activeIn = []
for equation in self.solver.Group:
if femutils.is_of_type(equation, "Fem::EquationElmerElectricforce"):
if equation.References:
activeIn = equation.References[0][1]
else:
activeIn = self._getAllBodies()
solverSection = self._getElectricforceSolver(equation)
for body in activeIn:
self._addSolver(body, solverSection)
def _getElectricforceSolver(self, equation):
# check if we need to update the equation
self._updateElectricforceSolver(equation)
# output the equation parameters
s = self._createEmptySolver()
s["Equation"] = "Electric Force" # equation.Name
s["Procedure"] = sifio.FileAttr("ElectricForce/StatElecForce")
s["Exec Solver"] = equation.ExecSolver
s["Stabilize"] = equation.Stabilize
return s
def _updateElectricforceSolver(self, equation):
# updates older Electricforce equations
if not hasattr(equation, "ExecSolver"):
equation.addProperty(
"App::PropertyEnumeration",
"ExecSolver",
"Electric Force",
(
"That solver is only executed after solution converged\n"
"To execute always, change to 'Always'"
)
)
equation.ExecSolver = electricforce.SOLVER_EXEC_METHODS
equation.ExecSolver = "After Timestep"
def _haveMaterialSolid(self):
for obj in self._getMember("App::MaterialObject"):
m = obj.Material
# fluid material always has KinematicViscosity defined
if not ("KinematicViscosity" in m):
return True
return False
def _handleElasticity(self):
activeIn = []
for equation in self.solver.Group:
if femutils.is_of_type(equation, "Fem::EquationElmerElasticity"):
if not self._haveMaterialSolid():
raise WriteError(
"The Elasticity equation requires at least one body with a solid material!"
)
if equation.References:
activeIn = equation.References[0][1]
else:
activeIn = self._getAllBodies()
solverSection = self._getElasticitySolver(equation)
for body in activeIn:
self._addSolver(body, solverSection)
self._handleElasticityEquation(activeIn, equation)
if activeIn:
self._handleElasticityConstants()
self._handleElasticityBndConditions()
self._handleElasticityInitial(activeIn)
self._handleElasticityBodyForces(activeIn)
self._handleElasticityMaterial(activeIn)
def _getElasticitySolver(self, equation):
s = self._createLinearSolver(equation)
# check if we need to update the equation
self._updateElasticitySolver(equation)
# output the equation parameters
s["Equation"] = "Stress Solver" # equation.Name
s["Procedure"] = sifio.FileAttr("StressSolve/StressSolver")
if equation.CalculateStrains is True:
s["Calculate Strains"] = equation.CalculateStrains
if equation.CalculateStresses is True:
s["Calculate Stresses"] = equation.CalculateStresses
if equation.CalculatePrincipal is True:
s["Calculate Principal"] = equation.CalculatePrincipal
if equation.CalculatePangle is True:
s["Calculate Pangle"] = equation.CalculatePangle
if equation.ConstantBulkSystem is True:
s["Constant Bulk System"] = equation.ConstantBulkSystem
s["Displace mesh"] = equation.DisplaceMesh
s["Eigen Analysis"] = equation.EigenAnalysis
if equation.EigenAnalysis is True:
s["Eigen System Convergence Tolerance"] = \
equation.EigenSystemTolerance
s["Eigen System Complex"] = equation.EigenSystemComplex
if equation.EigenSystemComputeResiduals is True:
s["Eigen System Compute Residuals"] = equation.EigenSystemComputeResiduals
s["Eigen System Damped"] = equation.EigenSystemDamped
s["Eigen System Max Iterations"] = equation.EigenSystemMaxIterations
s["Eigen System Select"] = equation.EigenSystemSelect
s["Eigen System Values"] = equation.EigenSystemValues
if equation.FixDisplacement is True:
s["Fix Displacement"] = equation.FixDisplacement
s["Geometric Stiffness"] = equation.GeometricStiffness
if equation.Incompressible is True:
s["Incompressible"] = equation.Incompressible
if equation.MaxwellMaterial is True:
s["Maxwell Material"] = equation.MaxwellMaterial
if equation.ModelLumping is True:
s["Model Lumping"] = equation.ModelLumping
if equation.ModelLumping is True:
s["Model Lumping Filename"] = equation.ModelLumpingFilename
s["Optimize Bandwidth"] = True
if equation.StabilityAnalysis is True:
s["Stability Analysis"] = equation.StabilityAnalysis
s["Stabilize"] = equation.Stabilize
if equation.UpdateTransientSystem is True:
s["Update Transient System"] = equation.UpdateTransientSystem
s["Variable"] = equation.Variable
s["Variable DOFs"] = 3
return s
def _handleElasticityEquation(self, bodies, equation):
for b in bodies:
if equation.PlaneStress:
self._equation(b, "Plane Stress", equation.PlaneStress)
def _updateElasticitySolver(self, equation):
# updates older Elasticity equations
if not hasattr(equation, "Variable"):
equation.addProperty(
"App::PropertyString",
"Variable",
"Elasticity",
(
"Only change this if 'Incompressible' is set to true\n"
"according to the Elmer manual."
)
)
equation.Variable = "Displacement"
if hasattr(equation, "Bubbles"):
# Bubbles was removed because it is unused by Elmer for the stress solver
equation.removeProperty("Bubbles")
if not hasattr(equation, "ConstantBulkSystem"):
equation.addProperty(
"App::PropertyBool",
"ConstantBulkSystem",
"Elasticity",
"See Elmer manual for info"
)
if not hasattr(equation, "DisplaceMesh"):
equation.addProperty(
"App::PropertyBool",
"DisplaceMesh",
"Elasticity",
(
"If mesh is deformed by displacement field.\n"
"Set to False for 'Eigen Analysis'."
)
)
# DisplaceMesh is true except if DoFrequencyAnalysis is true
equation.DisplaceMesh = True
if hasattr(equation, "DoFrequencyAnalysis"):
if equation.DoFrequencyAnalysis is True:
equation.DisplaceMesh = False
if not hasattr(equation, "EigenAnalysis"):
# DoFrequencyAnalysis was renamed to EigenAnalysis
# to follow the Elmer manual
equation.addProperty(
"App::PropertyBool",
"EigenAnalysis",
"Eigen Values",
"If true, modal analysis"
)
if hasattr(equation, "DoFrequencyAnalysis"):
equation.EigenAnalysis = equation.DoFrequencyAnalysis
equation.removeProperty("DoFrequencyAnalysis")
if not hasattr(equation, "EigenSystemComplex"):
equation.addProperty(
"App::PropertyBool",
"EigenSystemComplex",
"Eigen Values",
(
"Should be true if eigen system is complex\n"
"Must be false for a damped eigen value analysis."
)
)
equation.EigenSystemComplex = True
if not hasattr(equation, "EigenSystemComputeResiduals"):
equation.addProperty(
"App::PropertyBool",
"EigenSystemComputeResiduals",
"Eigen Values",
"Computes residuals of eigen value system"
)
if not hasattr(equation, "EigenSystemDamped"):
equation.addProperty(
"App::PropertyBool",
"EigenSystemDamped",
"Eigen Values",
(
"Set a damped eigen analysis. Can only be\n"
"used if 'Linear Solver Type' is 'Iterative'."
)
)
if not hasattr(equation, "EigenSystemMaxIterations"):
equation.addProperty(
"App::PropertyIntegerConstraint",
"EigenSystemMaxIterations",
"Eigen Values",
"Max iterations for iterative eigensystem solver"
)
equation.EigenSystemMaxIterations = (300, 1, int(1e8), 1)
if not hasattr(equation, "EigenSystemSelect"):
equation.addProperty(
"App::PropertyEnumeration",
"EigenSystemSelect",