-
Notifications
You must be signed in to change notification settings - Fork 2
/
EmbeddedBoundaryOperator.cpp
1923 lines (1548 loc) · 62.5 KB
/
EmbeddedBoundaryOperator.cpp
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 © 2020 The Multiphysics Modeling and Computation (M2C) Lab
* <kevin.wgy@gmail.com> <kevinw3@vt.edu>
************************************************************************/
#include<EmbeddedBoundaryOperator.h>
#include<Vector5D.h>
#include<CommunicationTools.h>
#include<GeoTools.h>
#include<trilinear_interpolation.h>
#include<gauss_quadratures.h>
#include<rbf_interp.hpp>
#include<deque>
#include<list>
#include<utility>
#include<memory.h> //unique_ptr
#include<dlfcn.h> //dlopen, dlclose
using std::string;
using std::map;
using std::vector;
using std::unique_ptr;
extern int INACTIVE_MATERIAL_ID;
extern int verbose;
//------------------------------------------------------------------------------------------------
EmbeddedBoundaryOperator::EmbeddedBoundaryOperator(MPI_Comm &comm_, IoData &iod_, bool surface_from_other_solver)
: comm(comm_), hasSurfFromOtherSolver(surface_from_other_solver),
dms_ptr(NULL), coordinates_ptr(NULL), ghost_nodes_inner_ptr(NULL),
ghost_nodes_outer_ptr(NULL), global_mesh_ptr(NULL),
cylindrical_symmetry(false)
{
// count surfaces from files
int counter = iod_.ebm.embed_surfaces.surfaces.dataMap.size();
// get the correct size of surfaces and F
surfaces.resize(counter);
F.resize(counter);
F_over_A.resize(counter);
Anodal.resize(counter);
surfaces_prev.resize(surfaces.size());
F_prev.resize(F.size());
F_over_A_prev.resize(F_over_A.size());
// set default boundary type to "None"
surface_type.assign(surfaces.size(), EmbeddedSurfaceData::None);
iod_embedded_surfaces.assign(surfaces.size(), NULL);
// read surfaces from files
int nConcurrent = 0;
for(auto it = iod_.ebm.embed_surfaces.surfaces.dataMap.begin();
it != iod_.ebm.embed_surfaces.surfaces.dataMap.end(); it++) {
int index = it->first;
if(index<0 || index>=counter) {
print_error("*** Error: Detected error in the indices of embedded surfaces (id = %d).", index);
exit_mpi();
}
iod_embedded_surfaces[index] = it->second;
if(index==0) {
if(surface_from_other_solver) {
if(it->second->provided_by_another_solver != EmbeddedSurfaceData::YES) {
print_error("*** Error: Conflict input in EmbeddedSurface[%d]. Should mesh be provided by another solver?",
index);
exit_mpi();
}
nConcurrent++;
continue; //no file to read
} else {
if(it->second->provided_by_another_solver != EmbeddedSurfaceData::NO) {
print_error("*** Error: Conflict input in EmbeddedSurface[%d]. Should mesh be provided by user?", index);
exit_mpi();
}
}
} else {
if(it->second->provided_by_another_solver != EmbeddedSurfaceData::NO) {
print_error("*** Error: Currently, only one embedded surface (with id 0) can be provided by another solver.");
exit_mpi();
}
}
surface_type[index] = it->second->type;
ReadMeshFile(it->second->filename, surfaces[index].X, surfaces[index].elems);
surfaces[index].X0 = surfaces[index].X;
// initialize the velocity vector (to 0)
surfaces[index].Udot.assign(surfaces[index].X.size(), 0.0);
surfaces[index].BuildConnectivities();
surfaces[index].CalculateNormalsAndAreas();
/*
bool orientation = surfaces[index].CheckSurfaceOrientation();
bool closed = surfaces[index].CheckSurfaceClosedness();
*/
}
print("- Activated the Embedded Boundary Method. Detected %d surface(s) (%d from concurrent program(s)).\n\n",
surfaces.size(), nConcurrent);
// set NULL to intersector pointers
intersector.assign(surfaces.size(), NULL);
// setup output
for(int i=0; i<(int)surfaces.size(); i++)
lagout.push_back(LagrangianOutput(comm, iod_embedded_surfaces[i]->output));
// setup dynamics_calculator
SetupUserDefinedDynamicsCalculator();
// set cylindrical_symmetry
cylindrical_symmetry = (iod_.mesh.type == MeshData::CYLINDRICAL);
// initialize 2d_to_3d to false
twoD_to_threeD.assign(counter, false);
}
//------------------------------------------------------------------------------------------------
// A constructor for tracking a single embedded surface provided using a mesh file
// The surface may contain multiple enclosures
EmbeddedBoundaryOperator::EmbeddedBoundaryOperator(MPI_Comm &comm_, EmbeddedSurfaceData &iod_surface)
: comm(comm_), hasSurfFromOtherSolver(false),
dms_ptr(NULL), coordinates_ptr(NULL), ghost_nodes_inner_ptr(NULL),
ghost_nodes_outer_ptr(NULL), global_mesh_ptr(NULL)
{
// get the correct size of surfaces and F
surfaces.resize(1);
F.resize(1);
F_over_A.resize(1);
Anodal.resize(1);
surfaces_prev.resize(1);
F_prev.resize(1);
F_over_A_prev.resize(1);
// set default boundary type to "None"
iod_embedded_surfaces.assign(1, &iod_surface);
surface_type.assign(1, iod_surface.type);
ReadMeshFile(iod_surface.filename, surfaces[0].X, surfaces[0].elems);
surfaces[0].X0 = surfaces[0].X;
surfaces[0].Udot.assign(surfaces[0].X.size(), 0.0);
surfaces[0].BuildConnectivities();
surfaces[0].CalculateNormalsAndAreas();
/*
bool orientation = surfaces[index].CheckSurfaceOrientation();
bool closed = surfaces[index].CheckSurfaceClosedness();
*/
print("- Activated the Embedded Boundary Method to track the surface provided in %s\n\n",
iod_surface.filename);
// set NULL to intersector pointers
intersector.assign(1, NULL);
// setup output
lagout.push_back(LagrangianOutput(comm, iod_embedded_surfaces[0]->output));
// setup dynamics_calculator
SetupUserDefinedDynamicsCalculator();
}
//------------------------------------------------------------------------------------------------
EmbeddedBoundaryOperator::~EmbeddedBoundaryOperator()
{
for(int i=0; i<(int)intersector.size(); i++)
if(intersector[i])
delete intersector[i];
for(auto it = dynamics_calculator.begin(); it != dynamics_calculator.end(); it++) {
if(std::get<0>(*it)) {
assert(std::get<2>(*it)); //this is the destruction function
(std::get<2>(*it))(std::get<0>(*it)); //use the destruction function to destroy the calculator
assert(std::get<1>(*it));
dlclose(std::get<1>(*it));
}
}
}
//------------------------------------------------------------------------------------------------
void
EmbeddedBoundaryOperator::Destroy()
{
for(int i=0; i<(int)intersector.size(); i++)
if(intersector[i])
intersector[i]->Destroy();
}
//------------------------------------------------------------------------------------------------
void
EmbeddedBoundaryOperator::SetCommAndMeshInfo(DataManagers3D &dms_, SpaceVariable3D &coordinates_,
vector<GhostPoint> &ghost_nodes_inner_, vector<GhostPoint> &ghost_nodes_outer_,
GlobalMeshInfo &global_mesh_)
{
dms_ptr = &dms_;
coordinates_ptr = &coordinates_;
ghost_nodes_inner_ptr = &ghost_nodes_inner_;
ghost_nodes_outer_ptr = &ghost_nodes_outer_;
global_mesh_ptr = &global_mesh_;
// determine twoD_to_threeD (in the constructor, it is set to false by default)
assert(global_mesh_ptr);
if(global_mesh_ptr->IsMesh2D()) {
bool involves_2D_3D_mapping = false;
for(int surf=0; surf<(int)twoD_to_threeD.size(); surf++) {
twoD_to_threeD[surf] = IsEmbeddedSurfaceIn3D(surf);
if(twoD_to_threeD[surf])
involves_2D_3D_mapping = true;
}
if(involves_2D_3D_mapping) {
print("- Detected embedded surface(s) in 3D, while M2C domain is in 2D.\n");
if(!global_mesh_ptr->two_dimensional_xy) {
print_error("*** Error: 2D Mesh must be in x-y plane (for 2D->3D mapping).\n");
exit_mpi();
}
else
print(" o Activated 2D->3D mapping in load calculation.\n");
}
}
}
//------------------------------------------------------------------------------------------------
bool
EmbeddedBoundaryOperator::IsEmbeddedSurfaceIn3D(int surf)
{
assert(surf<(int)surfaces.size());
vector<Vec3D> &X(surfaces[surf].X);
assert(X.size()>0);
std::set<double> xyz[3]; //using *set* to eliminate duplicates
for(auto&& x : X)
for(int d=0; d<3; d++)
xyz[d].insert(x[d]);
for(int d=0; d<3; d++) {
if(xyz[d].size()<3)
return false; //this dimension is not discretized. Cannot be 3D.
vector<double> coords(xyz[d].begin(), xyz[d].end()); //build a vector to store the coords
std::sort(coords.begin(), coords.end()); //increasing order
double hmax = 0.0;
for(int i=0; i<(int)coords.size()-1; i++)
hmax = std::max(hmax, coords[i+1]-coords[i]);
if(hmax>0.99*(coords.back() - coords.front())) //direction d has not been discretized
return false; //not 3D
}
return true;
}
//------------------------------------------------------------------------------------------------
void
EmbeddedBoundaryOperator::SetupIntersectors()
{
for(int i=0; i<(int)intersector.size(); i++) {
intersector[i] = new Intersector(comm, *dms_ptr, *iod_embedded_surfaces[i], surfaces[i],
*coordinates_ptr, *ghost_nodes_inner_ptr, *ghost_nodes_outer_ptr,
*global_mesh_ptr);
}
}
//------------------------------------------------------------------------------------------------
void
EmbeddedBoundaryOperator::FindSolidBodies(std::multimap<int, std::pair<int,int> > &id2closure)
{
// Part 1: Find inactive colors. Warning: When multiple surfaces have inactive regions that are close
// to each other or overlapping, the information collected here is invalid.
inactive_colors.clear();
for(int i=0; i<(int)surfaces.size(); i++) {
unique_ptr<EmbeddedBoundaryDataSet> EBDS = GetPointerToEmbeddedBoundaryData(i);
int nRegions = EBDS->nRegions; //this is the number of *closures*. Colors -1, -2, ...
for(int color = -1; color>=-nRegions; color--) {
bool found = false;
for(auto it = id2closure.begin(); it != id2closure.end(); it++) {
if(it->second.first == i && it->second.second == color) {
found = true;
break;
}
}
if(!found)
inactive_colors.insert(std::make_pair(i, color));
}
}
// Part 2: Find inactive_elem_status. Needed for force computation
inactive_elem_status.resize(surfaces.size());
for(int surf=0; surf<(int)surfaces.size(); surf++)
inactive_elem_status[surf].assign(surfaces[surf].elems.size(), 0);
vector<bool> touched(surfaces.size(), false);
for(auto it = inactive_colors.begin(); it != inactive_colors.end(); it++) {
int surf = it->first;
int this_color = it->second;
assert(intersector[surf]);
vector<int> &status(inactive_elem_status[surf]);
if(touched[surf]) { //be careful! Create a new vector for FindColorBoundary, then merge w/ existing one
vector<int> tmp;
intersector[surf]->FindColorBoundary(this_color, tmp);
assert(tmp.size() == status.size());
for(int i=0; i<(int)tmp.size(); i++) {
if(tmp[i]==1) {
if(status[i]==0)
status[i] = 1;
else if(status[i]==2)
status[i] = 3;
}
else if(tmp[i]==2) {
if(status[i]==0)
status[i] = 2;
else if(status[i]==1)
status[i] = 3;
}
else if(tmp[i]==3)
status[i] = 3;
}
}
else {
intersector[surf]->FindColorBoundary(this_color, status);
touched[surf] = true;
}
}
// output the wetted sides (i.e. active_elem_status)
int mpi_rank;
MPI_Comm_rank(comm, &mpi_rank);
for(int surf=0; surf<(int)surfaces.size(); surf++) {
if(mpi_rank != 0)
continue;
if(strcmp(iod_embedded_surfaces[surf]->output.wetting_output_filename,"")) {
char outname[512];
sprintf(outname, "%s%s", iod_embedded_surfaces[surf]->output.prefix,
iod_embedded_surfaces[surf]->output.wetting_output_filename);
std::fstream out(outname, std::fstream::out);
if(!out.is_open()) {
fprintf(stdout,"\033[0;31m*** Error: Cannot write file %s.\n\033[0m", outname);
exit(-1);
}
if(twoD_to_threeD[surf])
fprintf(stdout,"- Warning (Outputing wetted surface): Out-of-domain elements may not have "
"the correct status.\n");
vector<Vec3D>& Xs(surfaces[surf].X);
vector<Int3>& Es(surfaces[surf].elems);
vector<Vec3D>& Ns(surfaces[surf].elemNorm);
// find the median element "size" --> length of markers
vector<double> tmp = surfaces[surf].elemArea; //make a copy
auto mid = tmp.begin() + tmp.size()/2;
std::nth_element(tmp.begin(), mid, tmp.end()); //partial sort to find median
double midarea = tmp[tmp.size()/2];
assert(midarea>=0);
double amplification_factor = 2.0;
double marker_length = amplification_factor*sqrt(midarea*2.0);
vector<int> &status(inactive_elem_status[surf]);
// Write nodes
out << "Nodes WettedSurfacePoints" << std::endl;
Vec3D p,q;
for(int i=0; i<(int)Es.size(); i++) {
Int3 &nod(Es[i]);
switch (status[i]) {
case 0 : //both sides are wetted
p = (Xs[nod[0]]+Xs[nod[1]]+Xs[nod[2]])/3.0 - marker_length*Ns[i];
q = p + 2.0*marker_length*Ns[i];
break;
case 1 : //negative side is wetted
p = (Xs[nod[0]]+Xs[nod[1]]+Xs[nod[2]])/3.0;
q = p - marker_length*Ns[i];
break;
case 2 : //positive side is wetted
p = (Xs[nod[0]]+Xs[nod[1]]+Xs[nod[2]])/3.0;
q = p + marker_length*Ns[i];
break;
case 3 : //neither side is wetted
p = (Xs[nod[0]]+Xs[nod[1]]+Xs[nod[2]])/3.0;
q = p;
break;
}
out << std::setw(10) << 2*i+1
<< std::setw(14) << std::scientific << p[0]
<< std::setw(14) << std::scientific << p[1]
<< std::setw(14) << std::scientific << p[2] << "\n";
out << std::setw(10) << 2*i+2
<< std::setw(14) << std::scientific << q[0]
<< std::setw(14) << std::scientific << q[1]
<< std::setw(14) << std::scientific << q[2] << "\n";
}
// Write line segments / "markers"
out << "Elements Markers using WettedSurfacePoints" << std::endl;
for(int i=0; i<(int)Es.size(); i++) {
out << std::setw(10) << i+1 << " 1 " //"1" for line segment
<< std::setw(10) << 2*i+1
<< std::setw(10) << 2*i+2 << std::endl;
}
out.flush();
out.close();
}
}
MPI_Barrier(comm);
}
//------------------------------------------------------------------------------------------------
void
EmbeddedBoundaryOperator::ReadMeshFile(const char *filename, vector<Vec3D> &Xs, vector<Int3> &Es)
{
string fname(filename);
auto loc = fname.find_last_of(".");
if(loc>=fname.size()-1) {//assume the default format (top) if file extension not detected
ReadMeshFileInTopFormat(filename, Xs, Es);
return;
}
string ext = fname.substr(loc+1);
if(ext == "obj" || ext == "Obj" || ext == "OBJ")
ReadMeshFileInOBJFormat(filename, Xs, Es);
else if(ext == "stl" || ext == "Stl" || ext == "STL")
ReadMeshFileInSTLFormat(filename, Xs, Es);
else
ReadMeshFileInTopFormat(filename, Xs, Es);
}
//------------------------------------------------------------------------------------------------
void
EmbeddedBoundaryOperator::ReadMeshFileInTopFormat(const char *filename, vector<Vec3D> &Xs, vector<Int3> &Es)
{
// read data from the surface input file.
FILE *topFile;
topFile = fopen(filename, "r");
if(topFile == NULL) {
print_error("*** Error: Cannot open embedded surface mesh file (%s).\n", filename);
exit_mpi();
}
int MAXLINE = 500;
char line[MAXLINE], key1[MAXLINE], key2[MAXLINE]; //, copyForType[MAXLINE];
int num0 = 0;
int num1 = 0;
double x1, x2, x3;
int node1, node2, node3;
int type_reading = 0; //1 means reading node set; 2 means reading element set
std::deque<std::pair<int, Vec3D>> nodeList;
std::deque<std::array<int, 4>> elemList; // element ID + three node IDs
int maxNode = 0, maxElem = 0;
bool found_nodes = false;
bool found_elems = false;
// --------------------
// Read the file
// --------------------
while(fgets(line, MAXLINE, topFile) != 0) {
sscanf(line, "%s", key1);
string key1_string(key1);
if(key1[0] == '#') {
//Do nothing. This is user's comment
}
else if(same_strings_insensitive(key1_string,"Nodes")){
if(found_nodes) {//already found nodes... This is a conflict
print_error("*** Error: Found multiple sets of nodes (keyword 'Nodes') in %s.\n", filename);
exit_mpi();
}
sscanf(line, "%*s %s", key2);
type_reading = 1;
found_nodes = true;
}
else if(same_strings_insensitive(key1_string, "Elements")) {
if(found_elems) {//already found elements... This is a conflict
print_error("*** Error: Found multiple sets of elements (keyword 'Elements') in %s.\n", filename);
exit_mpi();
}
type_reading = 2;
found_elems = true;
}
else if(type_reading == 1) { //reading a node (following "Nodes Blabla")
int count = sscanf(line, "%d %lf %lf %lf", &num1, &x1, &x2, &x3);
if(count != 4) {
print_error("*** Error: Cannot interpret line %s (in %s). Expecting a node.\n", line, filename);
exit_mpi();
}
if(num1 < 1) {
print_error("*** Error: detected a node with index %d in embedded surface file %s.\n", num1, filename);
exit_mpi();
}
if(num1 > maxNode)
maxNode = num1;
nodeList.push_back({num1, {x1, x2, x3}});
}
else if(type_reading == 2) { // we are reading an element --- HAS TO BE A TRIANGLE!
int count = sscanf(line, "%d %d %d %d %d", &num0, &num1, &node1, &node2, &node3);
if(count != 5) {
print_error("*** Error: Cannot interpret line %s (in %s). Expecting a triangular element.\n", line, filename);
exit_mpi();
}
if(num0 < 1) {
print_error("*** Error: detected an element with index %d in embedded surface file %s.\n", num0, filename);
exit_mpi();
}
if(num0 > maxElem)
maxElem = num0;
elemList.push_back({num0, node1, node2, node3});
}
else { // found something I cannot understand...
print_error("*** Error: Unable to interpret line %s (in %s).\n", line, filename);
exit_mpi();
}
}
fclose(topFile);
if(!found_nodes) {
print_error("*** Error: Unable to find node set in %s.\n", filename);
exit_mpi();
}
if(!found_elems) {
print_error("*** Error: Unable to find element set in %s.\n", filename);
exit_mpi();
}
// ----------------------------
// Now, check and store nodes
// ----------------------------
int nNodes = nodeList.size();
map<int,int> old2new;
Xs.resize(nNodes);
int id(-1);
if(nNodes != maxNode) { // need to renumber nodes, i.e. create "old2new"
print_warning("Warning: The node indices of an embedded surface may have a gap: "
"max index = %d, number of nodes = %d. Renumbering nodes. (%s)\n",
maxNode, nNodes, filename);
// assert(nNodes < maxNode);
int current_id = 0;
vector<bool> nodecheck(maxNode+1, false);
for(auto it1 = nodeList.begin(); it1 != nodeList.end(); it1++) {
id = it1->first;
if(nodecheck[id]) {
print_error("*** Error: Found duplicate node (id: %d) in embedded surface file %s.\n", id, filename);
exit(-1);
}
nodecheck[id] = true;
Xs[current_id] = it1->second;
old2new[id] = current_id;
current_id++;
}
assert(current_id==(int)Xs.size());
}
else { //in good shape
vector<bool> nodecheck(nNodes, false);
for(auto it1 = nodeList.begin(); it1 != nodeList.end(); it1++) {
id = it1->first - 1;
if(nodecheck[id]) {
print_error("*** Error: Found duplicate node (id: %d) in embedded surface file %s.\n", id+1, filename);
exit(-1);
}
nodecheck[id] = true;
Xs[it1->first - 1] = it1->second;
}
}
// ------------------------------
// check nodes used by elements
// ------------------------------
for(auto it = elemList.begin(); it != elemList.end(); it++) {
id = (*it)[0];
node1 = (*it)[1];
node2 = (*it)[2];
node3 = (*it)[3];
if(old2new.empty()) {//node set is original order
if(node1<=0 || node1 > nNodes) {
print_error("*** Error: Detected unknown node number (%d) in element %d (%s).\n", node1, id, filename);
exit_mpi();
}
if(node2<=0 || node2 > nNodes) {
print_error("*** Error: Detected unknown node number (%d) in element %d (%s).\n", node2, id, filename);
exit_mpi();
}
if(node3<=0 || node3 > nNodes) {
print_error("*** Error: Detected unknown node number (%d) in element %d (%s).\n", node3, id, filename);
exit_mpi();
}
}
else {// nodes are renumbered
auto p1 = old2new.find(node1);
if(p1 == old2new.end()) {
print_error("*** Error: Detected unknown node number (%d) in element %d (%s).\n", node1, id, filename);
exit_mpi();
}
auto p2 = old2new.find(node2);
if(p2 == old2new.end()) {
print_error("*** Error: Detected unknown node number (%d) in element %d (%s).\n", node2, id, filename);
exit_mpi();
}
auto p3 = old2new.find(node3);
if(p3 == old2new.end()) {
print_error("*** Error: Detected unknown node number (%d) in element %d (%s).\n", node3, id, filename);
exit_mpi();
}
}
}
// ----------------------------
// check and store elements
// ----------------------------
int nElems = elemList.size();
Es.resize(nElems);
if(nElems != maxElem) { // need to renumber elements.
print_warning("Warning: The element indices of an embedded surface may have a gap: "
"max index = %d, number of elements = %d. Renumbering elements. (%s)\n",
maxElem, nElems, filename);
// assert(nElems < maxElem);
int current_id = 0;
vector<bool> elemcheck(maxElem+1, false);
for(auto it = elemList.begin(); it != elemList.end(); it++) {
id = (*it)[0];
if(elemcheck[id]) {
print_error("*** Error: Found duplicate element (id: %d) in embedded surface file %s.\n", id, filename);
exit_mpi();
}
elemcheck[id] = true;
node1 = (*it)[1];
node2 = (*it)[2];
node3 = (*it)[3];
if(old2new.empty()) //node set is original order
Es[current_id] = Int3(node1-1, node2-1, node3-1);
else {// nodes are renumbered
auto p1 = old2new.find(node1);
auto p2 = old2new.find(node2);
auto p3 = old2new.find(node3);
Es[current_id] = Int3(p1->second, p2->second, p3->second);
}
current_id++;
}
}
else { //element numbers in good shape
vector<bool> elemcheck(nElems, false);
for(auto it = elemList.begin(); it != elemList.end(); it++) {
id = (*it)[0] - 1;
if(elemcheck[id]) {
print_error("*** Error: Found duplicate element (id: %d) in embedded surface file %s.\n", id, filename);
exit_mpi();
}
elemcheck[id] = true;
node1 = (*it)[1];
node2 = (*it)[2];
node3 = (*it)[3];
if(old2new.empty()) //node set is original order
Es[id] = Int3(node1-1, node2-1, node3-1);
else {// nodes are renumbered
auto p1 = old2new.find(node1);
auto p2 = old2new.find(node2);
auto p3 = old2new.find(node3);
Es[id] = Int3(p1->second, p2->second, p3->second);
}
}
}
}
//------------------------------------------------------------------------------------------------
void
EmbeddedBoundaryOperator::ReadMeshFileInOBJFormat(const char *filename, vector<Vec3D> &Xs, vector<Int3> &Es)
{
// This function is adapted from toys::obj2top. But unlike the "toy", it does not separate different groups
Xs.clear();
Es.clear();
std::ifstream input(filename, std::ifstream::in);
if(input.fail()) {
print_error("*** Error: Cannot open embedded surface mesh file (%s).\n", filename);
exit_mpi();
}
string line, word;
double area_tol = 1e-12;
Vec3D xyz;
int nVerts, maxVerts = 1024, n1, n2, n3;
vector<int> ind(maxVerts); //should not have polygons with more than 1024 vertices!
vector<std::pair<string, vector<Int3> > > elem_groups;
vector<Int3> *elems = NULL;
std::set<string> ignored_keywords;
int line_number = 0;
while(getline(input, line)) {
line_number++;
auto first_nonspace_id = line.find_first_not_of(" ");
if((unsigned)first_nonspace_id<line.size() && line[first_nonspace_id] == '#')
continue; //this line is comment
std::stringstream linestream(line);
if(!(linestream >> word)) //the first word in the line
continue;
if(word == "v") { //vertex
linestream >> xyz[0] >> xyz[1] >> xyz[2]; //skipping vertex properties (if present)
Xs.push_back(xyz);
}
else if(word == "g") { //element group
string group_name;
linestream >> group_name; //the second word in the line -> group name
while(linestream >> word) //in stl, group name may have multiple words...
group_name = group_name + "_" + word;
bool found(false);
for(auto&& eg : elem_groups) {
if(eg.first == group_name) {
elems = &eg.second;
found = true;
break;
}
}
if(!found) {
elem_groups.push_back(std::make_pair(group_name, vector<Int3>()));
elems = &elem_groups.back().second;
}
}
else if(word == "f") { //face element
if(elem_groups.empty()) { //user did not specify group name
assert(elems==NULL);
elem_groups.push_back(std::make_pair("Default", vector<Int3>()));
elems = &elem_groups.back().second;
}
nVerts = 0;
while(linestream >> word) {
ind[nVerts++] = std::stoi(word.substr(0,word.find("/")));
if(nVerts>maxVerts) {
print_error("*** Error: Found a face element in %s with more than %d nodes.\n",
filename, maxVerts);
exit_mpi();
}
}
if(nVerts<3) {
print_error("*** Error: Found a face element in %s with only %d nodes.\n",
filename, nVerts);
exit_mpi();
}
for(int i=1; i<nVerts-1; i++)
elems->push_back(Int3(ind[0], ind[i], ind[i+1]));
}
else
ignored_keywords.insert(word);
}
for(auto&& key : ignored_keywords) {
if(!key.empty())
print_warning("Warning: Ignored lines in %s starting with %s.\n",
filename, key.c_str());
}
if(verbose>=1) {
print("- Found %d nodes in %s.\n", (int)Xs.size(), filename);
for(auto&& eg : elem_groups)
print("- Obtained %d triangular elements in group %s from %s.\n",
(int)eg.second.size(), eg.first.c_str(), filename);
if(elem_groups.size()>=2)
print_warning("Warning: Merging multiple (%d) groups into one.\n", (int)elem_groups.size());
}
for(auto&& eg : elem_groups) {
for(auto&& e : eg.second) {
n1 = e[0]; n2 = e[1]; n3 = e[2];
if(n1<=0 || n1>(int)Xs.size() || n2<=0 || n2>(int)Xs.size() ||
n3<=0 || n3>(int)Xs.size()) {
print_error("*** Error: Found element (%d %d %d) in %s with unknown node(s).\n",
n1, n2, n3, filename);
exit_mpi();
}
Vec3D cr = (Xs[n2-1] - Xs[n1-1])^(Xs[n3-1] - Xs[n1-1]);
if(cr.norm() < area_tol) {
print_warning("Warning: Detected a degenerate triangle with area %e --- dropped from the list.\n",
cr.norm());
continue;
}
Es.push_back(Int3(n1-1,n2-1,n3-1)); //node id starts at 0
}
}
input.close();
}
//------------------------------------------------------------------------------------------------
void
EmbeddedBoundaryOperator::ReadMeshFileInSTLFormat(const char *filename, vector<Vec3D> &Xs, vector<Int3> &Es)
{
// This function is adapted from toys::stl2top.
Xs.clear();
Es.clear();
std::ifstream input(filename, std::ifstream::in);
string line;
string word;
getline(input, line);
double area_tol = 1e-12;
int nodeid(0);
double x,y,z;
while(true) {
getline(input, line);
if(line.compare(0,8,"endsolid") == 0)
break;
getline(input, line);
input >> word >> x >> y >> z;
Vec3D X1(x,y,z);
input >> word >> x >> y >> z;
Vec3D X2(x,y,z);
input >> word >> x >> y >> z;
Vec3D X3(x,y,z);
Vec3D cr = (X2 - X1)^(X3 - X1);
getline(input, line); //get the end of line
getline(input, line);
getline(input, line);
if(cr.norm() < area_tol) {
print_warning("Warning: Detected a degenerate triangle with area %e --- dropped from the list.\n",
cr.norm());
continue;
}
Xs.push_back(X1);
Xs.push_back(X2);
Xs.push_back(X3);
Es.push_back(Int3(nodeid, nodeid+1, nodeid+2));
nodeid += 3;
}
if(verbose>=1)
print("Found %d triangular elements in %s.\n", (int)Es.size(), filename);
input.close();
}
//------------------------------------------------------------------------------------------------
void
EmbeddedBoundaryOperator::UpdateSurfacesPrevAndFPrev(bool partial_copy)
{
//partial_copy means only the nodal coordinates (not topology) gets copied to surfaces_prev
//
assert(partial_copy);
assert(F.size() == surfaces.size());
assert(surfaces.size() == F.size());
assert(F.size() == F_prev.size());
assert(F_over_A.size() == F_over_A_prev.size());
// loop through all the surfaces
for(int i = 0; i < (int)F.size(); i++) {
if(F_prev[i].size()>0) {//not the first time
assert(F[i].size() == F_prev[i].size());
assert(F_over_A[i].size() == F_over_A_prev[i].size());
} else {
F_prev[i].assign(F[i].size(),Vec3D(0.0));
F_over_A_prev[i].assign(F_over_A[i].size(),Vec3D(0.0));
}
// copy force & nodal area
for(int j=0; j<(int)F[i].size(); j++) {
F_prev[i][j] = F[i][j];
F_over_A_prev[i][j] = F_over_A[i][j];
}
if(surfaces_prev[i].X.size()>0) //not the first time
assert(surfaces[i].X.size() == surfaces_prev[i].X.size());
else
surfaces_prev[i].X.assign(surfaces[i].X.size(),Vec3D(0.0));
// copy nodal coords
for(int j=0; j<(int)surfaces[i].X.size(); j++)
surfaces_prev[i].X[j] = surfaces[i].X[j];
}
}
//------------------------------------------------------------------------------------------------
//----------------------------------------------------------------
// NOTE: ONLY PROC 0 HAS THE CORRECT FORCES FOR THE ENTIRE SURFACE
//----------------------------------------------------------------
void
EmbeddedBoundaryOperator::ComputeForces(SpaceVariable3D &V, SpaceVariable3D &ID)
{
/*
V.StoreMeshCoordinates(*coordinates_ptr);
V.WriteToVTRFile("V.vtr","sol");
ID.StoreMeshCoordinates(*coordinates_ptr);
ID.WriteToVTRFile("ID.vtr","ID");
*/
Vec5D*** v = (Vec5D***) V.GetDataPointer();
double*** id = ID.GetDataPointer();
// loop through all the embedded surfaces
for(int surf=0; surf<(int)surfaces.size(); surf++) {
// Get force vector
vector<Vec3D>& Fs(F[surf]); //Nodal loads (TO BE COMPUTED)
vector<Vec3D>& FAs(F_over_A[surf]); //Nodal loads divided by nodal area (TO BE COMPUTED)
// Get quadrature info
int np = 0; //number of Gauss points
switch (iod_embedded_surfaces[surf]->quadrature) {
case EmbeddedSurfaceData::NONE :
np = 0; //force is always 0 --> one-way coupling
break;
case EmbeddedSurfaceData::ONE_POINT :
np = 1;
break;
case EmbeddedSurfaceData::THREE_POINT :
np = 3;
break;
case EmbeddedSurfaceData::FOUR_POINT :
np = 4;
break;
case EmbeddedSurfaceData::SIX_POINT :
np = 6;