-
Notifications
You must be signed in to change notification settings - Fork 54
/
NumericalSolution.py
2130 lines (1976 loc) · 123 KB
/
NumericalSolution.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
"""
A hierarchy of classes for managing complete numerical solution implementations
.. inheritance-diagram:: proteus.NumericalSolution
:parts: 1
"""
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
from builtins import zip
from builtins import str
from builtins import input
from builtins import range
from builtins import object
from past.utils import old_div
import os
import numpy
from subprocess import check_call
from . import LinearSolvers
from . import NonlinearSolvers
from . import MeshTools
from . import Profiling
from . import Transport
from . import SimTools
from . import Archiver
from . import Viewers
from .Archiver import ArchiveFlags
from . import Domain
from .Profiling import logEvent
# Global to control whether the kernel starting is active.
embed_ok = True
class NS_base(object): # (HasTraits):
r"""
The base class for managing the numerical solution of PDE's.
The constructor must build all the objects required by a numerical
method to approximate the solution over a sequence of time intervals.
calculateSolution(runName) carries out the numerical solution.
.. graphviz::
digraph NumericalSolutionHasA {
node [shape=record, fontname=Helvetica, fontsize=12];
NS [label="NumericalSolution" URL="\ref NumericalSolution", style="filled", fillcolor="gray"];
mList [label="MultilevelTranportModel [n]" URL="\ref proteus::Transport::MultilevelTransport"];
nsList [label="NonLinearSolver [n] " URL="\ref proteus::NonLinearSolver"];
lsList [label="LinearSolver [n] " URL="\ref proteus::LinearSolver"];
pList [label="Problem Specification [n]" URL="\ref proteus::default_p"];
nList [label="Numerics Specifiation [n]" URL="\ref proteus::default_n"];
sList [label="Output Specification [n]" URL="\ref proteus::SimTools"];
so [label="Coupling Specification " URL="\ref proteus::SO_base"];
ar [label="Archiver" URL="\ref proteus::AR_base"];
NS -> pList [arrowhead="normal", style="dashed", color="purple"];
NS -> nList [arrowhead="normal", style="dashed", color="purple"];
NS -> so [arrowhead="normal", style="dashed", color="purple"];
NS -> sList [arrowhead="normal", style="dashed", color="purple"];
NS -> mList [arrowhead="normal", style="dashed", color="purple"];
NS -> nsList [arrowhead="normal", style="dashed", color="purple"];
NS -> lsList [arrowhead="normal", style="dashed", color="purple"];
NS -> ar [arrowhead="normal", style="dashed", color="purple"];
}
"""
def __init__(self,so,pList,nList,sList,opts,simFlagsList=None):
from . import Comm
comm=Comm.get()
self.comm=comm
message = "Initializing NumericalSolution for "+so.name+"\n System includes: \n"
for p in pList:
message += p.name+"\n"
logEvent(message)
#: SplitOperator initialize file
self.so=so
#: List of physics initialize files
self.pList=pList
#: List of numerics initialize files
self.nList=nList
#: Dictionary of command line arguments
self.opts=opts
self.simFlagsList=simFlagsList
self.timeValues={}
Profiling.memory("Memory used before initializing"+so.name)
memBase = Profiling.memLast #save current memory usage for later
if not so.useOneMesh:
so.useOneArchive=False
logEvent("Setting Archiver(s)")
if so.useOneArchive:
self.femSpaceWritten={}
tmp = Archiver.XdmfArchive(opts.dataDir,so.name,useTextArchive=opts.useTextArchive,
gatherAtClose=opts.gatherArchive,hotStart=opts.hotStart,
useGlobalXMF=(not opts.subdomainArchives),
global_sync=opts.global_sync)
self.ar = dict([(i,tmp) for i in range(len(self.pList))])
elif len(self.pList) == 1:
self.ar = {0:Archiver.XdmfArchive(opts.dataDir,so.name,useTextArchive=opts.useTextArchive,
gatherAtClose=opts.gatherArchive,hotStart=opts.hotStart)} #reuse so.name if possible
else:
self.ar = dict([(i,Archiver.XdmfArchive(opts.dataDir,p.name,useTextArchive=opts.useTextArchive,
gatherAtClose=opts.gatherArchive,hotStart=opts.hotStart)) for i,p in enumerate(self.pList)])
#by default do not save quadrature point info
self.archive_q = dict([(i,False) for i in range(len(self.pList))]);
self.archive_ebq_global = dict([(i,False) for i in range(len(self.pList))]);
self.archive_ebqe = dict([(i,False) for i in range(len(self.pList))]);
self.archive_pod_residuals = dict([(i,False) for i in range(len(self.pList))]);
if simFlagsList is not None:
assert len(simFlagsList) == len(self.pList), "len(simFlagsList) = %s should be %s " % (len(simFlagsList),len(self.pList))
for index in range(len(self.pList)):
if 'storeQuantities' in simFlagsList[index]:
for quant in [a for a in simFlagsList[index]['storeQuantities'] if a is not None]:
recType = quant.split(':')
if len(recType) > 1 and recType[0] == 'q':
self.archive_q[index] = True
elif len(recType) > 1 and recType[0] == 'ebq_global':
self.archive_ebq_global[index] = True
elif len(recType) > 1 and recType[0] == 'ebqe':
self.archive_ebqe[index] = True
#
elif recType[0] == 'pod_residuals':
self.archive_pod_residuals[index]=True
else:
logEvent("Warning Numerical Solution storeQuantity = %s not recognized won't archive" % quant)
#
#
#
#
logEvent("Setting up MultilevelMesh")
mlMesh_nList = []
if so.useOneMesh:
logEvent("Building one multilevel mesh for all models")
nListForMeshGeneration=[nList[0]]
pListForMeshGeneration=[pList[0]]
else:
logEvent("Building seperate meshes for each model")
nListForMeshGeneration=nList
pListForMeshGeneration=pList
for p,n in zip(pListForMeshGeneration,nListForMeshGeneration):
if opts.hotStart:
p.genMesh = False
logEvent("Hotstarting, using existing mesh "+p.name)
else:
logEvent("Generating mesh for "+p.name)
#support for old-style domain input
if p.domain is None:
if p.nd == 1:
p.domain = Domain.RectangularDomain(L=p.L[:1],
x=p.x0[:1],
name=p.name)
elif p.nd == 2:
if p.polyfile is not None:
p.domain = Domain.PlanarStraightLineGraphDomain(fileprefix=p.polyfile,name=p.polyfile)
elif p.meshfile != None:
p.domain = Domain.Mesh2DMDomain(p.meshfile)
else:
p.domain = Domain.RectangularDomain(L=p.L[:2],
x=p.x0[:2],
name=p.name)
elif p.nd == 3:
if p.polyfile is not None:
p.domain = Domain.PiecewiseLinearComplexDomain(fileprefix=p.polyfile,name=p.polyfile)
elif p.meshfile is not None:
p.domain = Domain.Mesh3DMDomain(p.meshfile)
else:
p.domain = Domain.RectangularDomain(L=p.L[:3],
x=p.x0[:3],
name=p.name)
else:
raise RuntimeError("No support for domains in more than three dimensions")
#now generate meshes, could move to Domain and use polymorphism or MeshTools
if isinstance(p.domain,Domain.RectangularDomain):
if p.domain.nd == 1:
mlMesh = MeshTools.MultilevelEdgeMesh(n.nn, 1, 1,
p.domain.x[0], 0.0, 0.0,
p.domain.L[0], 1.0, 1.0,
refinementLevels=n.nLevels,
nLayersOfOverlap=n.nLayersOfOverlapForParallel,
parallelPartitioningType=n.parallelPartitioningType)
elif p.domain.nd == 2:
if (n.nnx == n.nny is None):
nnx = nny = n.nn
else:
nnx = n.nnx
nny = n.nny
logEvent("Building %i x %i rectangular mesh for %s" % (nnx,nny,p.name))
if not hasattr(n,'quad'):
n.quad = False
if (n.quad):
mlMesh = MeshTools.MultilevelQuadrilateralMesh(nnx,nny,1,
p.domain.x[0], p.domain.x[1], 0.0,
p.domain.L[0],p.domain.L[1],1,
refinementLevels=n.nLevels,
nLayersOfOverlap=n.nLayersOfOverlapForParallel,
parallelPartitioningType=n.parallelPartitioningType)
else:
if hasattr(n,'triangleFlag')==True:
triangleFlag=n.triangleFlag
else:
triangleFlag=0
mlMesh = MeshTools.MultilevelTriangularMesh(nnx,nny,1,
p.domain.x[0], p.domain.x[1], 0.0,
p.domain.L[0],p.domain.L[1],1,
refinementLevels=n.nLevels,
nLayersOfOverlap=n.nLayersOfOverlapForParallel,
parallelPartitioningType=n.parallelPartitioningType,
triangleFlag=triangleFlag)
elif p.domain.nd == 3:
if (n.nnx == n.nny == n.nnz is None):
nnx = nny = nnz = n.nn
else:
nnx = n.nnx
nny = n.nny
nnz = n.nnz
logEvent("Building %i x %i x %i rectangular mesh for %s" % (nnx,nny,nnz,p.name))
if not hasattr(n,'hex'):
n.hex = False
if not hasattr(n,'NURBS'):
n.NURBS = False
if (n.NURBS):
mlMesh = MeshTools.MultilevelNURBSMesh(nnx,nny,nnz,
n.px,n.py,n.pz,
p.domain.x[0], p.domain.x[1], p.domain.x[2],
p.domain.L[0], p.domain.L[1], p.domain.L[2],
refinementLevels=n.nLevels,
nLayersOfOverlap=n.nLayersOfOverlapForParallel,
parallelPartitioningType=n.parallelPartitioningType)
elif (n.hex):
if not hasattr(n,'px'):
n.px=0
n.py=0
n.pz=0
mlMesh = MeshTools.MultilevelHexahedralMesh(nnx, nny, nnz,
n.px,n.py,n.pz,
p.domain.x[0], p.domain.x[1], p.domain.x[2],
p.domain.L[0], p.domain.L[1], p.domain.L[2],
refinementLevels=n.nLevels,
nLayersOfOverlap=n.nLayersOfOverlapForParallel,
parallelPartitioningType=n.parallelPartitioningType)
else :
mlMesh = MeshTools.MultilevelTetrahedralMesh(nnx, nny, nnz,
p.domain.x[0], p.domain.x[1], p.domain.x[2],
p.L[0], p.L[1], p.L[2],
refinementLevels=n.nLevels,
nLayersOfOverlap=n.nLayersOfOverlapForParallel,
parallelPartitioningType=n.parallelPartitioningType)
elif isinstance(p.domain,Domain.PlanarStraightLineGraphDomain):
fileprefix = None
# run mesher
if p.domain.use_gmsh is True:
fileprefix = p.domain.geofile
if comm.isMaster() and (p.genMesh or not (os.path.exists(fileprefix+".ele") and
os.path.exists(fileprefix+".node") and
os.path.exists(fileprefix+".edge"))):
if p.genMesh or not os.path.exists(fileprefix+".msh"):
logEvent("Running gmsh to generate 2D mesh for "+p.name,level=1)
gmsh_cmd = "time gmsh {0:s} -v 10 -2 -o {1:s} -format msh2".format(fileprefix+".geo", fileprefix+".msh")
logEvent("Calling gmsh on rank 0 with command %s" % (gmsh_cmd,))
check_call(gmsh_cmd, shell=True)
logEvent("Done running gmsh; converting to triangle")
else:
logEvent("Using "+fileprefix+".msh to convert to triangle")
# convert gmsh to triangle format
MeshTools.msh2simplex(fileprefix=fileprefix, nd=2)
else:
fileprefix = p.domain.polyfile
if comm.isMaster() and p.genMesh:
logEvent("Calling Triangle to generate 2D mesh for "+p.name)
tricmd = "triangle -{0} -e {1}.poly".format(n.triangleOptions, fileprefix)
logEvent("Calling triangle on rank 0 with command %s" % (tricmd,))
check_call(tricmd, shell=True)
logEvent("Done running triangle")
check_call("mv {0:s}.1.ele {0:s}.ele".format(fileprefix), shell=True)
check_call("mv {0:s}.1.node {0:s}.node".format(fileprefix), shell=True)
check_call("mv {0:s}.1.edge {0:s}.edge".format(fileprefix), shell=True)
comm.barrier()
assert fileprefix is not None, 'did not find mesh file name'
# convert mesh to proteus format
mesh = MeshTools.TriangularMesh()
mesh.generateFromTriangleFiles(filebase=fileprefix,
base=1)
mlMesh = MeshTools.MultilevelTriangularMesh(0,0,0,skipInit=True,
nLayersOfOverlap=n.nLayersOfOverlapForParallel,
parallelPartitioningType=n.parallelPartitioningType)
logEvent("Generating %i-level mesh from coarse Triangle mesh" % (n.nLevels,))
mlMesh.generateFromExistingCoarseMesh(mesh,n.nLevels,
nLayersOfOverlap=n.nLayersOfOverlapForParallel,
parallelPartitioningType=n.parallelPartitioningType)
elif isinstance(p.domain,Domain.PiecewiseLinearComplexDomain):
from subprocess import call
import sys
if p.domain.use_gmsh is True:
fileprefix = p.domain.geofile
else:
fileprefix = p.domain.polyfile
if comm.rank() == 0 and (p.genMesh or not (os.path.exists(fileprefix+".ele") and
os.path.exists(fileprefix+".node") and
os.path.exists(fileprefix+".face"))):
if p.domain.use_gmsh is True:
if p.genMesh or not os.path.exists(fileprefix+".msh"):
logEvent("Running gmsh to generate 3D mesh for "+p.name,level=1)
gmsh_cmd = "time gmsh {0:s} -v 10 -3 -o {1:s} -format msh2".format(fileprefix+'.geo', p.domain.geofile+'.msh')
logEvent("Calling gmsh on rank 0 with command %s" % (gmsh_cmd,))
check_call(gmsh_cmd, shell=True)
logEvent("Done running gmsh; converting to tetgen")
else:
logEvent("Using "+p.domain.geofile+".msh to convert to tetgen")
MeshTools.msh2simplex(fileprefix=fileprefix, nd=3)
check_call("tetgen -Vfeen {0:s}.ele".format(fileprefix), shell=True)
else:
logEvent("Running tetgen to generate 3D mesh for "+p.name, level=1)
tetcmd = "tetgen -{0} {1}.poly".format(n.triangleOptions, fileprefix)
logEvent("Calling tetgen on rank 0 with command %s" % (tetcmd,))
check_call(tetcmd, shell=True)
logEvent("Done running tetgen")
check_call("mv {0:s}.1.ele {0:s}.ele".format(fileprefix), shell=True)
check_call("mv {0:s}.1.node {0:s}.node".format(fileprefix), shell=True)
check_call("mv {0:s}.1.face {0:s}.face".format(fileprefix), shell=True)
try:
check_call("mv {0:s}.1.neigh {0:s}.neigh".format(fileprefix), shell=True)
except:
logEvent("Warning: couldn't move {0:s}.1.neigh".format(fileprefix))
pass
try:
check_call("mv {0:s}.1.edge {0:s}.edge".format(fileprefix), shell=True)
except:
logEvent("Warning: couldn't move {0:s}.1.edge".format(fileprefix))
pass
comm.barrier()
logEvent("Initializing mesh and MultilevelMesh")
nbase = 1
mesh=MeshTools.TetrahedralMesh()
mlMesh = MeshTools.MultilevelTetrahedralMesh(0,0,0,skipInit=True,
nLayersOfOverlap=n.nLayersOfOverlapForParallel,
parallelPartitioningType=n.parallelPartitioningType)
if opts.generatePartitionedMeshFromFiles:
logEvent("Generating partitioned mesh from Tetgen files")
if("f" not in n.triangleOptions or "ee" not in n.triangleOptions):
sys.exit("ERROR: Remake the mesh with the `f` flag and `ee` flags in triangleOptions.")
mlMesh.generatePartitionedMeshFromTetgenFiles(fileprefix,nbase,mesh,n.nLevels,
nLayersOfOverlap=n.nLayersOfOverlapForParallel,
parallelPartitioningType=n.parallelPartitioningType)
else:
logEvent("Generating coarse global mesh from Tetgen files")
mesh.generateFromTetgenFiles(fileprefix,nbase,parallel = comm.size() > 1)
logEvent("Generating partitioned %i-level mesh from coarse global Tetgen mesh" % (n.nLevels,))
mlMesh.generateFromExistingCoarseMesh(mesh,n.nLevels,
nLayersOfOverlap=n.nLayersOfOverlapForParallel,
parallelPartitioningType=n.parallelPartitioningType)
elif isinstance(p.domain,Domain.PUMIDomain):
import sys
if(comm.size()>1 and p.domain.MeshOptions.parallelPartitioningType!=MeshTools.MeshParallelPartitioningTypes.element):
sys.exit("The mesh must be partitioned by elements and NOT nodes for adaptivity functionality. Do this with: `domain.MeshOptions.setParallelPartitioningType('element')'.")
if comm.size() > 1 and n.conservativeFlux != None:
sys.exit("ERROR: Element based partitions don't have a functioning conservative flux calculation. Set conservativeFlux to None in twp_navier_stokes")
#ibaned: PUMI conversion #1
if p.domain.nd == 3:
mesh = MeshTools.TetrahedralMesh()
else:
mesh = MeshTools.TriangularMesh()
logEvent("Converting PUMI mesh to Proteus")
mesh.convertFromPUMI(p.domain.PUMIMesh, p.domain.faceList,
p.domain.regList,
parallel = comm.size() > 1, dim = p.domain.nd)
if p.domain.nd == 3:
mlMesh = MeshTools.MultilevelTetrahedralMesh(
0,0,0,skipInit=True,
nLayersOfOverlap=n.nLayersOfOverlapForParallel,
parallelPartitioningType=n.parallelPartitioningType)
if p.domain.nd == 2:
mlMesh = MeshTools.MultilevelTriangularMesh(
0,0,0,skipInit=True,
nLayersOfOverlap=n.nLayersOfOverlapForParallel,
parallelPartitioningType=n.parallelPartitioningType)
logEvent("Generating %i-level mesh from PUMI mesh" % (n.nLevels,))
if comm.size()==1:
mlMesh.generateFromExistingCoarseMesh(
mesh,n.nLevels,
nLayersOfOverlap=n.nLayersOfOverlapForParallel,
parallelPartitioningType=n.parallelPartitioningType)
else:
mlMesh.generatePartitionedMeshFromPUMI(
mesh,n.nLevels,
nLayersOfOverlap=n.nLayersOfOverlapForParallel)
elif isinstance(p.domain,Domain.MeshTetgenDomain):
nbase = 1
mesh=MeshTools.TetrahedralMesh()
logEvent("Reading coarse mesh from tetgen file")
mlMesh = MeshTools.MultilevelTetrahedralMesh(0,0,0,skipInit=True,
nLayersOfOverlap=n.nLayersOfOverlapForParallel,
parallelPartitioningType=n.parallelPartitioningType)
if opts.generatePartitionedMeshFromFiles:
logEvent("Generating partitioned mesh from Tetgen files")
mlMesh.generatePartitionedMeshFromTetgenFiles(p.domain.meshfile,nbase,mesh,n.nLevels,
nLayersOfOverlap=n.nLayersOfOverlapForParallel,
parallelPartitioningType=n.parallelPartitioningType)
else:
logEvent("Generating coarse global mesh from Tetgen files")
mesh.generateFromTetgenFiles(p.domain.polyfile,nbase,parallel = comm.size() > 1)
logEvent("Generating partitioned %i-level mesh from coarse global Tetgen mesh" % (n.nLevels,))
mlMesh.generateFromExistingCoarseMesh(mesh,n.nLevels,
nLayersOfOverlap=n.nLayersOfOverlapForParallel,
parallelPartitioningType=n.parallelPartitioningType)
elif isinstance(p.domain,Domain.Mesh3DMDomain):
mesh=MeshTools.TetrahedralMesh()
logEvent("Reading coarse mesh from 3DM file")
mesh.generateFrom3DMFile(p.domain.meshfile)
mlMesh = MeshTools.MultilevelTetrahedralMesh(0,0,0,skipInit=True,
nLayersOfOverlap=n.nLayersOfOverlapForParallel,
parallelPartitioningType=n.parallelPartitioningType)
logEvent("Generating %i-level mesh from coarse 3DM mesh" % (n.nLevels,))
mlMesh.generateFromExistingCoarseMesh(mesh,n.nLevels,
nLayersOfOverlap=n.nLayersOfOverlapForParallel,
parallelPartitioningType=n.parallelPartitioningType)
elif isinstance(p.domain,Domain.Mesh2DMDomain):
mesh=MeshTools.TriangularMesh()
logEvent("Reading coarse mesh from 2DM file")
mesh.generateFrom2DMFile(p.domain.meshfile)
mlMesh = MeshTools.MultilevelTriangularMesh(0,0,0,skipInit=True,
nLayersOfOverlap=n.nLayersOfOverlapForParallel,
parallelPartitioningType=n.parallelPartitioningType)
logEvent("Generating %i-level mesh from coarse 2DM mesh" % (n.nLevels,))
mlMesh.generateFromExistingCoarseMesh(mesh,n.nLevels,
nLayersOfOverlap=n.nLayersOfOverlapForParallel,
parallelPartitioningType=n.parallelPartitioningType)
elif isinstance(p.domain,Domain.MeshHexDomain):
mesh=MeshTools.HexahedralMesh()
logEvent("Reading coarse mesh from file")
mesh.generateFromHexFile(p.domain.meshfile)
mlMesh = MeshTools.MultilevelHexahedralMesh(0,0,0,skipInit=True,
nLayersOfOverlap=n.nLayersOfOverlapForParallel,
parallelPartitioningType=n.parallelPartitioningType)
logEvent("Generating %i-level mesh from coarse mesh" % (n.nLevels,))
mlMesh.generateFromExistingCoarseMesh(mesh,n.nLevels,
nLayersOfOverlap=n.nLayersOfOverlapForParallel,
parallelPartitioningType=n.parallelPartitioningType)
elif isinstance(p.domain,Domain.GMSH_3D_Domain):
from subprocess import call
import sys
if comm.rank() == 0 and (p.genMesh or not (os.path.exists(p.domain.polyfile+".ele") and
os.path.exists(p.domain.polyfile+".node") and
os.path.exists(p.domain.polyfile+".face"))):
logEvent("Running gmsh to generate 3D mesh for "+p.name,level=1)
gmsh_cmd = "time gmsh {0:s} -v 10 -3 -o {1:s} -format mesh -clmax {2:f}".format(p.domain.geofile, p.domain.name+".mesh", 0.5*p.domain.he)
logEvent("Calling gmsh on rank 0 with command %s" % (gmsh_cmd,))
check_call(gmsh_cmd, shell=True)
logEvent("Done running gmsh; converting to tetgen")
gmsh2tetgen_cmd = "gmsh2tetgen {0} {1:f} {2:d} {3:d} {4:d}".format(
p.domain.name+".mesh",
p.domain.length_scale,
p.domain.permute_dims[0]+1,#switch to base 1 index...
p.domain.permute_dims[1]+1,
p.domain.permute_dims[2]+1)
check_call(gmsh2tetgen_cmd, shell=True)
check_call("tetgen -Vfeen %s.ele" % ("mesh",), shell=True)
check_call("mv %s.1.ele %s.ele" % ("mesh","mesh"), shell=True)
check_call("mv %s.1.node %s.node" % ("mesh","mesh"), shell=True)
check_call("mv %s.1.face %s.face" % ("mesh","mesh"), shell=True)
check_call("mv %s.1.neigh %s.neigh" % ("mesh","mesh"), shell=True)
check_call("mv %s.1.edge %s.edge" % ("mesh","mesh"), shell=True)
elefile = "mesh.ele"
nodefile = "mesh.node"
facefile = "mesh.face"
edgefile = "mesh.edge"
assert os.path.exists(elefile), "no mesh.ele"
tmp = "%s.ele" % p.domain.polyfile
os.rename(elefile,tmp)
assert os.path.exists(tmp), "no .ele"
assert os.path.exists(nodefile), "no mesh.node"
tmp = "%s.node" % p.domain.polyfile
os.rename(nodefile,tmp)
assert os.path.exists(tmp), "no .node"
if os.path.exists(facefile):
tmp = "%s.face" % p.domain.polyfile
os.rename(facefile,tmp)
assert os.path.exists(tmp), "no .face"
if os.path.exists(edgefile):
tmp = "%s.edge" % p.domain.polyfile
os.rename(edgefile,tmp)
assert os.path.exists(tmp), "no .edge"
comm.barrier()
logEvent("Initializing mesh and MultilevelMesh")
nbase = 1
mesh=MeshTools.TetrahedralMesh()
mlMesh = MeshTools.MultilevelTetrahedralMesh(0,0,0,skipInit=True,
nLayersOfOverlap=n.nLayersOfOverlapForParallel,
parallelPartitioningType=n.parallelPartitioningType)
if opts.generatePartitionedMeshFromFiles:
logEvent("Generating partitioned mesh from Tetgen files")
mlMesh.generatePartitionedMeshFromTetgenFiles(p.domain.polyfile,nbase,mesh,n.nLevels,
nLayersOfOverlap=n.nLayersOfOverlapForParallel,
parallelPartitioningType=n.parallelPartitioningType)
else:
logEvent("Generating coarse global mesh from Tetgen files")
mesh.generateFromTetgenFiles(p.domain.polyfile,nbase,parallel = comm.size() > 1)
logEvent("Generating partitioned %i-level mesh from coarse global Tetgen mesh" % (n.nLevels,))
mlMesh.generateFromExistingCoarseMesh(mesh,n.nLevels,
nLayersOfOverlap=n.nLayersOfOverlapForParallel,
parallelPartitioningType=n.parallelPartitioningType)
mlMesh_nList.append(mlMesh)
if opts.viewMesh:
logEvent("Attempting to visualize mesh")
try:
from proteusGraphical import vtkViewers
vtkViewers.ViewMesh(mlMesh.meshList[0],viewMaterialTypes=True)
vtkViewers.ViewBoundaryMesh(mlMesh.meshList[0],viewBoundaryMaterialTypes=True)
except:
logEvent("NumericalSolution ViewMesh failed for coarse mesh")
for l in range(n.nLevels):
try:
logEvent(mlMesh.meshList[l].meshInfo())
except:
logEvent("meshInfo() method not implemented for this mesh type")
if opts.viewMesh and opts.viewLevels and l > 0:
logEvent("Attempting to visualize mesh")
try:
from proteusGraphical import vtkViewers
vtkViewers.ViewMesh(mlMesh.meshList[l],title="mesh level %s " % l,
viewMaterialTypes=True)
vtkViewers.ViewBoundaryMesh(mlMesh.meshList[l],title="boundary mesh level %s " % l,
viewBoundaryMaterialTypes=True)
except:
logEvent("NumericalSolution ViewMesh failed for mesh level %s" % l)
theMesh = mlMesh.meshList[0].subdomainMesh
pCT = self.pList[0]#self.pList[0].ct
nCT = self.nList[0]#self.nList[0].ct
theDomain = pCT.domain
if hasattr(theDomain,"PUMIMesh") and not isinstance(theDomain,Domain.PUMIDomain) :
logEvent("Reconstruct based on Proteus, convert PUMI mesh to Proteus")
from scipy import spatial
meshVertexTree = spatial.cKDTree(theMesh.nodeArray)
meshVertex2Model= [0]*theMesh.nNodes_owned
for idx,vertex in enumerate(theDomain.vertices):
if(pCT.nd==2 and len(vertex) == 2): #there might be a smarter way to do this
vertex.append(0.0) #need to make a 3D coordinate
closestVertex = meshVertexTree.query(vertex)
meshVertex2Model[closestVertex[1]] = 1
isModelVert = numpy.asarray(meshVertex2Model).astype("i")
meshBoundaryConnectivity = numpy.zeros((theMesh.nExteriorElementBoundaries_global,2+pCT.nd),dtype=numpy.int32)
for elementBdyIdx in range(len(theMesh.exteriorElementBoundariesArray)):
exteriorIdx = theMesh.exteriorElementBoundariesArray[elementBdyIdx]
meshBoundaryConnectivity[elementBdyIdx][0] = theMesh.elementBoundaryMaterialTypes[exteriorIdx]
meshBoundaryConnectivity[elementBdyIdx][1] = theMesh.elementBoundaryElementsArray[exteriorIdx][0]
meshBoundaryConnectivity[elementBdyIdx][2] = theMesh.elementBoundaryNodesArray[exteriorIdx][0]
meshBoundaryConnectivity[elementBdyIdx][3] = theMesh.elementBoundaryNodesArray[exteriorIdx][1]
if(pCT.nd==3):
meshBoundaryConnectivity[elementBdyIdx][4] = theMesh.elementBoundaryNodesArray[exteriorIdx][2]
pCT.domain.PUMIMesh.reconstructFromProteus2(theMesh.cmesh,isModelVert,meshBoundaryConnectivity)
if so.useOneMesh:
for p in pList[1:]: mlMesh_nList.append(mlMesh)
try:
if (nList[0].MeshAdaptMesh.size_field_config() == 'isotropicProteus'):
mlMesh.meshList[0].subdomainMesh.size_field = numpy.ones((mlMesh.meshList[0].subdomainMesh.nNodes_global,1),'d')*1.0e-1
if (nList[0].MeshAdaptMesh.size_field_config() == 'anisotropicProteus'):
mlMesh.meshList[0].subdomainMesh.size_scale = numpy.ones((mlMesh.meshList[0].subdomainMesh.nNodes_global,3),'d')
mlMesh.meshList[0].subdomainMesh.size_frame = numpy.ones((mlMesh.meshList[0].subdomainMesh.nNodes_global,9),'d')
except:
pass
Profiling.memory("Mesh")
from collections import OrderedDict
self.modelSpinUp = OrderedDict()
for p in pList:
p.coefficients.opts = self.opts
if p.coefficients.sdInfo == {}:
for ci,ckDict in p.coefficients.diffusion.items():
for ck in list(ckDict.keys()):
if (ci,ck) not in p.coefficients.sdInfo:
p.coefficients.sdInfo[(ci,ck)] = (numpy.arange(start=0,stop=p.nd**2+1,step=p.nd,dtype='i'),
numpy.array([list(range(p.nd)) for row in range(p.nd)],dtype='i').flatten())
logEvent("Numerical Solution Sparse diffusion information key "+repr((ci,ck))+' = '+repr(p.coefficients.sdInfo[(ci,ck)]))
self.sList = sList
self.mlMesh_nList = mlMesh_nList
self.allocateModels()
#collect models to be used for spin up
for index in so.modelSpinUpList:
self.modelSpinUp[index] = self.modelList[index]
logEvent("Finished setting up models and solvers")
if self.opts.save_dof:
for m in self.modelList:
for lm in m.levelModelList:
for ci in range(lm.coefficients.nc):
lm.u[ci].dof_last = lm.u[ci].dof.copy()
self.archiveFlag= so.archiveFlag
logEvent("Setting up SimTools for "+p.name)
self.simOutputList = []
self.auxiliaryVariables = {}
if self.simFlagsList is not None:
for p,n,simFlags,model,index in zip(pList,nList,simFlagsList,self.modelList,list(range(len(pList)))):
self.simOutputList.append(SimTools.SimulationProcessor(flags=simFlags,nLevels=n.nLevels,
pFile=p,nFile=n,
analyticalSolution=p.analyticalSolution))
model.simTools = self.simOutputList[-1]
self.auxiliaryVariables[model.name]= [av.attachModel(model,self.ar[index]) for av in n.auxiliaryVariables]
else:
for p,n,s,model,index in zip(pList,nList,sList,self.modelList,list(range(len(pList)))):
self.simOutputList.append(SimTools.SimulationProcessor(pFile=p,nFile=n))
model.simTools = self.simOutputList[-1]
model.viewer = Viewers.V_base(p,n,s)
self.auxiliaryVariables[model.name]= [av.attachModel(model,self.ar[index]) for av in n.auxiliaryVariables]
for avList in list(self.auxiliaryVariables.values()):
for av in avList:
av.attachAuxiliaryVariables(self.auxiliaryVariables)
logEvent(Profiling.memory("NumericalSolution memory",className='NumericalSolution',memSaved=memBase))
if so.tnList is None:
logEvent("Building tnList from model = "+pList[0].name+" nDTout = "+repr(nList[0].nDTout))
self.tnList=[float(n)*nList[0].T/float(nList[0].nDTout)
for n in range(nList[0].nDTout+1)]
else:
logEvent("Using tnList from so = "+so.name)
self.tnList = so.tnList
logEvent("Time sequence"+repr(self.tnList))
logEvent("NAHeader Num Time Steps "+repr(len(self.tnList)-1))
logEvent("Setting "+so.name+" systemStepController to object of type "+str(so.systemStepControllerType))
self.systemStepController = so.systemStepControllerType(self.modelList,stepExact=so.systemStepExact)
self.systemStepController.setFromOptions(so)
logEvent("Finished NumericalSolution initialization")
def allocateModels(self):
self.modelList=[]
self.lsList=[]
self.nlsList=[]
for p,n,s,mlMesh,index \
in zip(self.pList,self.nList,self.sList,self.mlMesh_nList,list(range(len(self.pList)))):
if self.so.needEBQ_GLOBAL:
n.needEBQ_GLOBAL = True
if self.so.needEBQ:
n.needEBQ = True
## \todo clean up tolerances: use rtol_u,atol_u and rtol_res, atol_res; allow scaling by mesh diameter
## \todo pass in options = (p,n) instead of using monster ctor signature
tolList=[]
linTolList=[]
for l in range(n.nLevels):
#if mlMesh.meshList[l].hasGeometricInfo != True:
# mlMesh.meshList[l].computeGeometricInfo()
#fac = (mlMesh.meshList[l].h/mlMesh.meshList[0].h)**2
fac = 1.0
tolList.append(n.tolFac*fac)
linTolList.append(n.linTolFac*fac)
logEvent("Setting up MultilevelTransport for "+p.name)
model \
= Transport.MultilevelTransport(p,
n,
mlMesh,
OneLevelTransportType=p.LevelModelType)
self.modelList.append(model)
model.name = p.name
logEvent("Setting "+model.name+" stepController to "+str(n.stepController))
model.stepController = n.stepController(model,n)
Profiling.memory("MultilevelTransport for "+p.name)
logEvent("Setting up MultilevelLinearSolver for"+p.name)
#allow options database to set model specific parameters?
linear_solver_options_prefix = None
if 'linear_solver_options_prefix' in dir(n):
linear_solver_options_prefix = n.linear_solver_options_prefix
(multilevelLinearSolver,directSolverFlag) = LinearSolvers.multilevelLinearSolverChooser(
linearOperatorList = model.jacobianList,
par_linearOperatorList = model.par_jacobianList,
multilevelLinearSolverType = n.multilevelLinearSolver,
computeSolverRates=n.computeLinearSolverRates,
printSolverInfo=n.printLinearSolverInfo,
levelLinearSolverType = n.levelLinearSolver,
computeLevelSolverRates=n.computeLevelLinearSolverRates,
printLevelSolverInfo=n.printLevelLinearSolverInfo,
smootherType = n.linearSmoother,
computeSmootherRates=n.computeLinearSmootherRates,
printSmootherInfo=n.printLinearSmootherInfo,
prolongList = model.meshTransfers.prolongList,
restrictList = model.meshTransfers.restrictList,
connectivityListList = [model.levelModelList[l].sparsityInfo for l in range(n.nLevels)],
relativeToleranceList = linTolList,
absoluteTolerance = n.l_atol_res,
solverMaxIts = n.linearSolverMaxIts,
solverConvergenceTest=n.linearSolverConvergenceTest,
cycles=n.linearWCycles,
preSmooths=n.linearPreSmooths,
postSmooths=n.linearPostSmooths,
##\todo logic needs to handle element boundary partition too
parallelUsesFullOverlap=(n.nLayersOfOverlapForParallel > 0 or n.parallelPartitioningType == MeshTools.MeshParallelPartitioningTypes.node),
par_duList=model.par_duList,
solver_options_prefix=linear_solver_options_prefix,
computeEigenvalues = n.computeEigenvalues,
linearSmootherOptions = n.linearSmootherOptions)
self.lsList.append(multilevelLinearSolver)
Profiling.memory("MultilevelLinearSolver for "+p.name)
logEvent("Setting up MultilevelNonLinearSolver for "+p.name)
self.nlsList.append(NonlinearSolvers.multilevelNonlinearSolverChooser(
model.levelModelList,
model.jacobianList,
model.par_jacobianList,
duList=model.duList,
par_duList=model.par_duList,
multilevelNonlinearSolverType = n.multilevelNonlinearSolver,
computeSolverRates=n.computeNonlinearSolverRates,
solverConvergenceTest=n.nonlinearSolverConvergenceTest,
levelSolverConvergenceTest=n.levelNonlinearSolverConvergenceTest,
printSolverInfo=n.printNonlinearSolverInfo,
relativeToleranceList = tolList,
absoluteTolerance = n.nl_atol_res,
levelNonlinearSolverType=n.levelNonlinearSolver,
computeLevelSolverRates=n.computeNonlinearLevelSolverRates,
printLevelSolverInfo=n.printNonlinearLevelSolverInfo,
smootherType = n.nonlinearSmoother,
computeSmootherRates=n.computeNonlinearSmootherRates,
printSmootherInfo=n.printNonlinearSmootherInfo,
preSmooths=n.nonlinearPreSmooths,
postSmooths=n.nonlinearPostSmooths,
cycles=n.nonlinearWCycles,
maxSolverIts=n.maxNonlinearIts,
prolong_bcList = model.meshTransfers.prolong_bcListDict,
restrict_bcList = model.meshTransfers.restrict_bcListDict,
restrict_bcSumList = model.meshTransfers.restrict_bcSumListDict,
prolongList = model.meshTransfers.prolongList,
restrictList = model.meshTransfers.restrictList,
restrictionRowSumList = model.meshTransfers.restrictSumList,
connectionListList=[model.levelModelList[l].sparsityInfo for l in range(n.nLevels)],
linearSolverList=multilevelLinearSolver.solverList,
linearDirectSolverFlag=directSolverFlag,
solverFullNewtonFlag=n.fullNewtonFlag,
levelSolverFullNewtonFlag=n.fullNewtonFlag,
smootherFullNewtonFlag=n.fullNewtonFlag,
EWtol=n.useEisenstatWalker,
maxLSits=n.maxLineSearches,
#\todo need to add logic in multilevel NL solver chooser to account for numerical method's stencil as well
parallelUsesFullOverlap=(n.nLayersOfOverlapForParallel > 0 or n.parallelPartitioningType == MeshTools.MeshParallelPartitioningTypes.node),
nonlinearSolverNorm = n.nonlinearSolverNorm))
model.solver=self.nlsList[-1]
model.viewer = Viewers.V_base(p,n,s)
Profiling.memory("MultilevelNonlinearSolver for"+p.name)
def PUMI2Proteus(self,mesh):
#p0 = self.pList[0] #This can probably be cleaned up somehow
#n0 = self.nList[0]
p0 = self.pList[0].ct
n0 = self.nList[0].ct
logEvent("Generating %i-level mesh from PUMI mesh" % (n0.nLevels,))
if p0.domain.nd == 3:
mlMesh = MeshTools.MultilevelTetrahedralMesh(
0,0,0,skipInit=True,
nLayersOfOverlap=n0.nLayersOfOverlapForParallel,
parallelPartitioningType=n0.parallelPartitioningType)
if p0.domain.nd == 2:
mlMesh = MeshTools.MultilevelTriangularMesh(
0,0,0,skipInit=True,
nLayersOfOverlap=n0.nLayersOfOverlapForParallel,
parallelPartitioningType=n0.parallelPartitioningType)
if self.comm.size()==1:
mlMesh.generateFromExistingCoarseMesh(
mesh,n0.nLevels,
nLayersOfOverlap=n0.nLayersOfOverlapForParallel,
parallelPartitioningType=n0.parallelPartitioningType)
else:
mlMesh.generatePartitionedMeshFromPUMI(
mesh,n0.nLevels,
nLayersOfOverlap=n0.nLayersOfOverlapForParallel)
self.mlMesh_nList=[]
for p in self.pList:
self.mlMesh_nList.append(mlMesh)
if (p0.domain.PUMIMesh.size_field_config() == "isotropicProteus"):
mlMesh.meshList[0].subdomainMesh.size_field = numpy.ones((mlMesh.meshList[0].subdomainMesh.nNodes_global,1),'d')*1.0e-1
if (p0.domain.PUMIMesh.size_field_config() == 'anisotropicProteus'):
mlMesh.meshList[0].subdomainMesh.size_scale = numpy.ones((mlMesh.meshList[0].subdomainMesh.nNodes_global,3),'d')
mlMesh.meshList[0].subdomainMesh.size_frame = numpy.ones((mlMesh.meshList[0].subdomainMesh.nNodes_global,9),'d')
#may want to trigger garbage collection here
modelListOld = self.modelList
logEvent("Allocating models on new mesh")
self.allocateModels()
logEvent("Attach auxiliary variables to new models")
#(cut and pasted from init, need to cleanup)
self.simOutputList = []
self.auxiliaryVariables = {}
self.newAuxiliaryVariables = {}
if self.simFlagsList is not None:
for p, n, simFlags, model, index in zip(
self.pList,
self.nList,
self.simFlagsList,
self.modelList,
list(range(len(self.pList)))):
self.simOutputList.append(
SimTools.SimulationProcessor(
flags=simFlags,
nLevels=n.nLevels,
pFile=p,
nFile=n,
analyticalSolution=p.analyticalSolution))
model.simTools = self.simOutputList[-1]
#Code to refresh attached gauges. The goal is to first purge
#existing point gauge node associations as that may have changed
#If there is a line gauge, then all the points must be deleted
#and remade.
from collections import OrderedDict
for av in n.auxiliaryVariables:
if hasattr(av,'adapted'):
av.adapted=True
for point, l_d in av.points.items():
if 'nearest_node' in l_d:
l_d.pop('nearest_node')
if(av.isLineGauge or av.isLineIntegralGauge): #if line gauges, need to remove all points
av.points = OrderedDict()
if(av.isGaugeOwner):
if(self.comm.rank()==0 and not av.file.closed):
av.file.close()
for item in av.pointGaugeVecs:
item.destroy()
for item in av.pointGaugeMats:
item.destroy()
for item in av.dofsVecs:
item.destroy()
av.pointGaugeVecs = []
av.pointGaugeMats = []
av.dofsVecs = []
av.field_ids=[]
av.isGaugeOwner=False
##reinitialize auxiliaryVariables
self.auxiliaryVariables[model.name]= [av.attachModel(model,self.ar[index]) for av in n.auxiliaryVariables]
else:
for p,n,s,model,index in zip(
self.pList,
self.nList,
self.sList,
self.modelList,
list(range(len(self.pList)))):
self.simOutputList.append(SimTools.SimulationProcessor(pFile=p,nFile=n))
model.simTools = self.simOutputList[-1]
model.viewer = Viewers.V_base(p,n,s)
self.auxiliaryVariables[model.name]= [av.attachModel(model,self.ar[index]) for av in n.auxiliaryVariables]
for avList in list(self.auxiliaryVariables.values()):
for av in avList:
av.attachAuxiliaryVariables(self.auxiliaryVariables)
logEvent("Transfering fields from PUMI to Proteus")
for m in self.modelList:
for lm in m.levelModelList:
coef = lm.coefficients
if coef.vectorComponents is not None:
vector=numpy.zeros((lm.mesh.nNodes_global,3),'d')
p0.domain.PUMIMesh.transferFieldToProteus(
coef.vectorName, vector)
for vci in range(len(coef.vectorComponents)):
lm.u[coef.vectorComponents[vci]].dof[:] = vector[:,vci]
p0.domain.PUMIMesh.transferFieldToProteus(
coef.vectorName+"_old", vector)
for vci in range(len(coef.vectorComponents)):
lm.u[coef.vectorComponents[vci]].dof_last[:] = vector[:,vci]
del vector
for ci in range(coef.nc):
if coef.vectorComponents is None or \
ci not in coef.vectorComponents:
scalar=numpy.zeros((lm.mesh.nNodes_global,1),'d')
p0.domain.PUMIMesh.transferFieldToProteus(
coef.variableNames[ci], scalar)
lm.u[ci].dof[:] = scalar[:,0]
p0.domain.PUMIMesh.transferFieldToProteus(
coef.variableNames[ci]+"_old", scalar)
lm.u[ci].dof_last[:] = scalar[:,0]
del scalar
logEvent("Attaching models on new mesh to each other")
for m,ptmp,mOld in zip(self.modelList, self.pList, modelListOld):
for lm, lu, lr, lmOld in zip(m.levelModelList, m.uList, m.rList,mOld.levelModelList):
#save_dof=[]
#for ci in range(lm.coefficients.nc):
# save_dof.append( lm.u[ci].dof.copy())
# lm.u[ci].dof_last = lm.u[ci].dof.copy()
lm.setFreeDOF(lu)
#for ci in range(lm.coefficients.nc):
# assert((save_dof[ci] == lm.u[ci].dof).all())
lm.calculateSolutionAtQuadrature()
lm.timeIntegration.tLast = lmOld.timeIntegration.tLast
lm.timeIntegration.t = lmOld.timeIntegration.t
lm.timeIntegration.dt = lmOld.timeIntegration.dt
assert(lmOld.timeIntegration.tLast == lm.timeIntegration.tLast)
assert(lmOld.timeIntegration.t == lm.timeIntegration.t)
assert(lmOld.timeIntegration.dt == lm.timeIntegration.dt)
m.stepController.dt_model = mOld.stepController.dt_model
m.stepController.t_model = mOld.stepController.t_model
m.stepController.t_model_last = mOld.stepController.t_model_last
m.stepController.substeps = mOld.stepController.substeps
#Attach models and do sample residual calculation. The results are usually irrelevant.
#What's important right now is to re-establish the relationships between data structures.
#The necessary values will be written in later.
for m,ptmp,mOld in zip(self.modelList, self.pList, modelListOld):
logEvent("Attaching models to model "+ptmp.name)
m.attachModels(self.modelList)
logEvent("Evaluating residuals and time integration")
for m,ptmp,mOld in zip(self.modelList, self.pList, modelListOld):
for lm, lu, lr, lmOld in zip(m.levelModelList, m.uList, m.rList, mOld.levelModelList):
lm.timeTerm=True
lm.getResidual(lu,lr)
lm.timeIntegration.initializeTimeHistory(resetFromDOF=True)
lm.initializeTimeHistory()
lm.timeIntegration.initializeSpaceHistory()
lm.getResidual(lu,lr)
#lm.estimate_mt() #function is empty in all models
assert(m.stepController.dt_model == mOld.stepController.dt_model)
assert(m.stepController.t_model == mOld.stepController.t_model)
assert(m.stepController.t_model_last == mOld.stepController.t_model_last)
logEvent("Initializing time history for model step controller")
m.stepController.initializeTimeHistory()
p0.domain.initFlag=True #For next step to take initial conditions from solution, only used on restarts
self.systemStepController.modelList = self.modelList
self.systemStepController.exitModelStep = {}
self.systemStepController.controllerList = []
for model in self.modelList:
self.systemStepController.exitModelStep[model] = False
if model.levelModelList[-1].timeIntegration.isAdaptive:
self.systemStepController.controllerList.append(model)
self.systemStepController.maxFailures = model.stepController.maxSolverFailures
self.systemStepController.choose_dt_system()
##This section is to correct any differences in the quadrature point field from the old model
#Shock capturing lagging needs to be matched
import copy
#This sections gets beta bdf right
#import pdb; pdb.set_trace()
#self.modelList[1].levelModelList[0].u_store = copy.deepcopy(self.modelList[1].levelModelList[0].u)
#self.modelList[1].levelModelList[0].u[0].dof[:] = self.modelList[1].levelModelList[0].u[0].dof_last
#self.modelList[1].levelModelList[0].calculateElementResidual()
#self.modelList[1].levelModelList[0].q[('m_last',0)][:] = self.modelList[1].levelModelList[0].q[('m_tmp',0)]
##this section gets numDiff right
#self.modelList[1].levelModelList[0].u[0].dof[:] = self.modelList[1].levelModelList[0].u_store[0].dof
#self.modelList[1].levelModelList[0].u[0].dof_last[:] = self.modelList[1].levelModelList[0].u_store[0].dof_last
#self.modelList[1].levelModelList[0].calculateElementResidual()
#self.modelList[1].levelModelList[0].q[('m_last',0)][:] = self.modelList[1].levelModelList[0].q[('m_tmp',0)]
#if(modelListOld[1].levelModelList[0].shockCapturing.nStepsToDelay is not None and modelListOld[1].levelModelList[0].shockCapturing.nSteps > modelListOld[1].levelModelList[0].shockCapturing.nStepsToDelay):
# self.modelList[1].levelModelList[0].shockCapturing.nSteps=self.modelList[1].levelModelList[0].shockCapturing.nStepsToDelay
# self.modelList[1].levelModelList[0].shockCapturing.updateShockCapturingHistory()
###Details for solution transfer
#To get shock capturing lagging correct, the numDiff array needs to be computed correctly with the u^{n} solution.
#numDiff depends on the PDE residual and can depend on the subgrid error (SGE)
#the PDE residual depends on the alpha and beta_bdf terms which depend on m_tmp from u^{n-1} as well as VOF or LS fields.
#getResidual() is used to populate m_tmp, numDiff.
#The goal is therefore to populate the nodal fields with the old solution, get m_tmp properly and lagged sge properly.
#Mimic the solver stagger with a new loop to repopulate the nodal fields with u^{n} solution. This is necessary because NS relies on the u^{n-1} field for VOF/LS
###This loop stores the current solution (u^n) and loads in the previous timestep solution (u^{n-1})
for m,mOld in zip(self.modelList, modelListOld):
for lm, lu, lr, lmOld in zip(m.levelModelList, m.uList, m.rList, mOld.levelModelList):
#lm.coefficients.postAdaptStep() #MCorr needs this at the moment
#lm.u_store = copy.copy(lm.u)
lm.u_store = {}
lm.u_store_last = {}
for ci in range(0,lm.coefficients.nc):
lm.u_store[ci] = copy.deepcopy(lm.u[ci].dof)
lm.u_store_last[ci] = copy.deepcopy(lm.u[ci].dof_last)
lm.dt_store = copy.copy(lm.timeIntegration.dt)
for ci in range(0,lm.coefficients.nc):
lm.u[ci].dof[:] = lm.u[ci].dof_last
lm.setFreeDOF(lu)
#All solution fields are now in state u^{n-1}
for m,mOld in zip(self.modelList, modelListOld):