forked from douglasjacobsen/MPI-SCVT
-
Notifications
You must be signed in to change notification settings - Fork 0
/
scvt-mpi.cpp
3022 lines (2581 loc) · 82.6 KB
/
scvt-mpi.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
//**************************************************
// scvt-mpi.cpp
//
// Purpose:
//
// mpi-scvt.cpp is used to compute spherical centroidal Voronoi tessellations using a modified Lloyd's algorithm
// in parallel.
//
// Licensing:
//
// This code is distributed under the GNU LGPL license.
//
// Modified:
//
// 02 February 2012
//
// Author:
//
// Doug Jacobsen
// Geoff Womeldorff
//
//**************************************************
// Enable _DEBUG for output of routines. Useful for debugging any issues in mpi.
// All messages from turning this flag on are written to cerr
// #define _DEBUG
#include <stdlib.h>
#include <inttypes.h>
#include <iostream>
#include <fstream>
#include <tr1/unordered_set>
#include <vector>
#include <math.h>
#include <assert.h>
#ifdef USE_NETCDF
#include <netcdfcpp.h>
#endif
#include <boost/mpi.hpp>
#include <boost/serialization/vector.hpp>
#include "Triangle/triangle.h"
#include "Pugixml/pugixml.hpp"
#include "triangulation.h"
#define SEED 3729
// Uses boost mpi to make use of serialization routines for packing and unpacking of classes
namespace mpi = boost::mpi;
typedef boost::optional<mpi::status> optional;
// Uses namespaces std and tr1. tr1 is used for unordered_set which gives unique triangulation at the end.
using namespace std;
using namespace tr1;
class bpt {/*{{{*/
public:
struct bisect_hasher {/*{{{*/
size_t operator()(const pair<int,int> &p) const {
uint32_t hash;
size_t i, key[2] = { (size_t)p.first, (size_t)p.second};
for(hash = i = 0; i < sizeof(key); ++i) {
hash += ((uint8_t *)key)[i];
hash += (hash << 10);
hash ^= (hash >> 6);
}
hash += (hash << 3);
hash ^= (hash >> 11);
hash += (hash << 15);
return hash;
}
};/*}}}*/
};/*}}}*/
class region{/*{{{*/
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & center;
ar & radius;
ar & input_radius;
ar & triangles;
ar & neighbors;
ar & neighbors1;
ar & neighbors2;
ar & boundary_points;
ar & loop_start;
ar & loop_stop;
}
public:
pnt center;
double radius;
double input_radius;
vector<pnt> points;
vector<tri> triangles;
vector<int> neighbors; // First Level of Neighbors
vector<int> neighbors1; // First Level of Neighbors + Self
vector<int> neighbors2; // Second Level of Neighbors + First Level of Neighbors + Self
vector<pnt> boundary_points;
vector<int> loop_start; // beginning point in loop
vector<int> loop_stop; // ending point in loop
};/*}}}*/
struct int_hasher {/*{{{*/
size_t operator()(const int v) const { return v; }
};/*}}}*/
class mpi_timer{/*{{{*/
public:
mpi::timer my_timer;
double total_time;
int num_calls;
string name;
mpi_timer() : total_time(0), num_calls(0), name("Default") { };
mpi_timer(string in_name) : total_time(0), num_calls(0), name(in_name) { };
mpi_timer operator+(const mpi_timer &t) const {/*{{{*/
mpi_timer nt;
nt.init("Sum");
nt.num_calls = t.num_calls;
nt.total_time = t.total_time + total_time;
return nt;
}/*}}}*/
void init(string in_name){/*{{{*/
total_time = 0.0;
num_calls = 0;
name = in_name;
}/*}}}*/
void init(){/*{{{*/
total_time = 0;
num_calls = 0;
}/*}}}*/
void start(){/*{{{*/
my_timer.restart();
}/*}}}*/
void stop(){/*{{{*/
total_time += my_timer.elapsed();
num_calls++;
}/*}}}*/
};/*}}}*/
inline std::ostream & operator<<(std::ostream &os, const mpi_timer &t){/*{{{*/
if(t.num_calls > 0){
os << t.name << ": " << t.total_time*1e3 << " (ms), " << (t.total_time/t.num_calls)*1e3 << " (ms). Called " << t.num_calls << " times." << endl;
} else {
os << t.name << ": Never called. Time = 0.0 (ms)" << endl;
}
return os;
}/*}}}*/
// Triangles input flags
string flags_str = "QBPIOYYiz";
char * flags;
//Processor information and global communicator
const int master = 0;
int id, num_procs;
mpi::communicator world;
// Message tags for sending and receiving non-blocking messages
enum {msg_points, msg_tri_print , msg_restart, msg_ave, msg_max, msg_l1};
// Sort types
enum {sort_dot, sort_vor};
// Global constants
int points_begin = 0;
int num_pts = 162;
int num_bdry = 0;
int max_it = 100;
int max_it_no_proj = 100;
int max_it_scale_alpha = 0;
int div_levs = 1;
int num_bisections = 0;
int conv = 0;
int restart = 0;
int sort_method = sort_dot;
int use_barycenter = 0;
double min_bdry_angle = 1.0;
double eps = 1.0E-10;
double proj_alpha;
double max_resolution = 4.0;
double anneal_percent = 0.01;
int anneal_its = 0;
int anneal_limit = 0;
int anneal_on = 0;
int anneal_shape_control = 0;
//gw: restart mode type and variable (move to a header?)
enum restart_mode_type { RESTART_OVERWRITE, RESTART_RETAIN };
restart_mode_type restart_mode = RESTART_OVERWRITE;
enum fileio_mode_type { FILEIO_TXT, FILEIO_NETCDF, FILEIO_BOTH };
fileio_mode_type fileio_mode = FILEIO_TXT;
//Define variable for quadrature rules
int quad_rule = 2;
string quad_names[6] = {"Centroid Rule", "Vertex Rule", "Midpoint Rule", "7 Point Rule", "13 Point Rule", "19 Point Rule"};
double *wq, *q;
double wq7[7], q7[4];
double wq13[13], q13[8];
double wq19[19], q19[12];
//Define timers for performance studies
const int num_timers = 8;
const int num_global_timers = 4;
mpi_timer my_timers[num_timers];
mpi_timer global_timers[num_global_timers];
string names[num_timers] = {"Total", "Iteration", "Triangulation", "Integration", "Metrics", "Communication", "Convergence Check", "Sort"};
string global_names[num_global_timers] = {"Global Time", "Final Gather", "Final Triangulation", "Final Bisection"};
//Each processor has a copy of all points, and has a n_points (new points) vector for which points it should update.
vector<pnt> points;
vector<pnt> n_points;
vector<pnt>::iterator point_itr;
vector<pnt> boundary_points;
vector<pnt>::iterator boundary_itr;
vector<int> loop_start;
vector<int> loop_stop;
//Each processor has a list of all regions, as well as it's own regions (only one per processor currently)
vector<region> my_regions;
vector<region> regions;
vector<region>::iterator region_itr;
vector<tri> all_triangles;
//Region neighbors hold the connectivity of neighbors, for communication purposes.
vector<unordered_set<int, int_hasher> > region_neighbors;
unordered_set<int, int_hasher>::iterator region_neigh_itr;
//Iterators for neighbors and triangles.
vector<int>::iterator neighbor_itr;
vector<tri>::iterator tri_itr;
/* ***** Setup Routines *****{{{*/
void readParamsFile();
void buildRegions();
void printRegions();
void readBoundaries();
/*}}}*/
/* ***** Bisect Edges Routines *****{{{*/
void bisectEdges(int end);
void bisectTriangulation(int output);
/*}}}*/
/* ***** Point Init Routines ***** {{{*/
void readPoints();
void makeMCPoints(int n);
void makeGeneralizedSpiralPoints(int n);
void makeFibonacciGridPoints(int n);
/*}}}*/
/* ***** Integration Routines ***** {{{*/
void divideIntegrate(const int levs, const pnt &A, const pnt &B, const pnt &C, pnt &Top, double &bot);
void init_quadrature();
void quadrature(const pnt &A, const pnt &B, const pnt &C, pnt &top, double &bot);
void quadratureCR(const pnt &A, const pnt &B, const pnt &C, pnt &top, double &bot);
void quadratureVR(const pnt &A, const pnt &B, const pnt &C, pnt &top, double &bot);
void quadratureMP(const pnt &A, const pnt &B, const pnt &C, pnt &top, double &bot);
void quadrature7P(const pnt &A, const pnt &B, const pnt &C, pnt &top, double &bot);
void quadrature13P(const pnt &A, const pnt &B, const pnt &C, pnt &top, double &bot);
void quadrature19P(const pnt &A, const pnt &B, const pnt &C, pnt &top, double &bot);
/*}}}*/
/* ***** Generic Region Routines *****{{{ */
void sortPoints(int sort_type, vector<region> ®ion_vec);
void sortBoundaryPoints(vector<region> ®ion_vec);
void triangulateRegions(vector<region> ®ion_vec);
void integrateRegions(vector<region> ®ion_vec);
void computeMetrics(double &ave, double &max, double &l1);
void clearRegions(vector<region> ®ion_vec);
void makeFinalTriangulations(vector<region> ®ion_vec);
void projectToBoundary(vector<region> ®ion_vec);
void annealPoints(vector<region> ®ion_vec);
/*}}}*/
/* ***** Specific Region Routines ***** {{{ */
void printAllFinalTriangulation();
void printMyFinalTriangulation();
void storeMyFinalTriangulation();
/*}}}*/
/* ***** Communication Routines ***** {{{*/
void transferUpdatedPoints();
void gatherAllUpdatedPoints();
/*}}}*/
/* ***** Routines for Points *****{{{*/
void writePointsAsRestart(const int it, const restart_mode_type restart_mode, const fileio_mode_type fileio_mode);
#ifdef USE_NETCDF
int writeRestartFileOverwriteNC( const int it, const vector<pnt> &points );
int writeRestartFileRetainNC( const int it, const vector<pnt> &points );
#endif
int writeRestartFileOverwriteTXT( const int it );
int writeRestartFileRetainTXT( const int it );
double density(const pnt &p);
double pop_lowres_density(const pnt &p);
double pop_highres_density(const pnt &p);
double ellipse_density(const pnt &p, double lat_c, double lon_c, double lat_width, double lon_width);
/*}}}*/
int main(int argc, char **argv){
int bisection;
int it, i;
int stop, force_anneal, do_proj;
int ave_points, my_points;
mpi::request *ave_comms, *max_comms, *l1_comms;
double *my_ave, *my_max, *my_l1;
double glob_ave, glob_max, glob_l1;
double last_glob_ave, last_glob_max, last_glob_l1;
optional ave_opti, max_opti, l1_opti;
pnt p;
flags = new char[flags_str.size()+1];
strcpy(flags,flags_str.c_str());
for(i = 0; i < num_global_timers; i++){
global_timers[i] = mpi_timer(global_names[i]);
}
global_timers[0].start(); // Global Time Timer
mpi::environment env(argc, argv);
id = world.rank();
num_procs = world.size();
my_ave = new double[num_procs];
my_max = new double[num_procs];
my_l1 = new double[num_procs];
ave_comms = new mpi::request[num_procs];
max_comms = new mpi::request[num_procs];
l1_comms = new mpi::request[num_procs];
last_glob_ave = 1.0;
last_glob_max = 1.0;
last_glob_l1 = 1.0;
force_anneal = 0;
// Read in parameters and regions. Setup initial point set
if(id == master){
readParamsFile();
cout << "Using " << quad_names[quad_rule] << " for integration." << endl;
cout << "Writing restart files every " << restart << " steps." << endl;
if (points_begin == 0){
cout <<"Points being read in from SaveVertices." << endl;
readPoints();
} else if(points_begin == 1){
cout << "Points being created with Monte Carlo." << endl;
makeMCPoints(num_pts);
} else if(points_begin == 2){
cout << "Points being created with Generalized Spiral." << endl;
makeGeneralizedSpiralPoints(num_pts);
} else if(points_begin == 3){
cout << "Points being created with Fibonacci Grid." << endl;
makeFibonacciGridPoints(num_pts);
}
readBoundaries();
buildRegions();
ofstream pts_out("point_initial.dat");
for(point_itr = points.begin(); point_itr != points.end(); ++point_itr){
pts_out << (*point_itr) << endl;
}
pts_out.close();
}
// Each processor needs to setup the quadrature rules.
init_quadrature();
// Broadcast parameters, regions, and initial point set to each processor.
mpi::broadcast(world,num_pts,master);
mpi::broadcast(world,max_it,master);
mpi::broadcast(world,restart,master);
mpi::broadcast(world,sort_method,master);
mpi::broadcast(world,max_it_no_proj,master);
mpi::broadcast(world,max_it_scale_alpha,master);
mpi::broadcast(world,num_bisections,master);
mpi::broadcast(world,div_levs,master);
mpi::broadcast(world,conv,master);
mpi::broadcast(world,eps,master);
mpi::broadcast(world,quad_rule,master);
mpi::broadcast(world,use_barycenter,master);
mpi::broadcast(world,anneal_percent,master);
mpi::broadcast(world,anneal_its,master);
mpi::broadcast(world,anneal_limit,master);
mpi::broadcast(world,anneal_on,master);
mpi::broadcast(world,anneal_shape_control,master);
mpi::broadcast(world,regions,master);
mpi::broadcast(world,points,master);
mpi::broadcast(world,boundary_points,master);
//printRegions();
// Setup timers
for(i = 0; i < num_timers; i++){
my_timers[i] = mpi_timer(names[i]);
}
// Each processor clears my_regions (to make sure it's empty) and add it's own region into it's list.
// If there is only 1 processor, that processor takes all regions, which is a serial computation.
my_regions.clear();
if(num_procs > 1){
my_regions.push_back(regions.at(id));
if(num_procs != regions.size()){
cout << "Region error ---- Region size must equal number of processors." << endl;
cout << " Or you must only use 1 processor" << endl;
assert(num_procs == regions.size());
}
} else {
for(region_itr = regions.begin(); region_itr != regions.end(); ++region_itr){
my_regions.push_back((*region_itr));
}
}
sortBoundaryPoints(my_regions);
// Loop over bisections
for(bisection = 0; bisection <= num_bisections; bisection++){
// Clear loop timers
for(i = 0; i < num_timers; i++){
my_timers[i].init();
}
// Start loop timer
my_timers[0].start();
stop = 0;
do_proj = 1;
for(it = 0; it < max_it && !stop; it++){
glob_ave = 0.0;
glob_max = 0.0;
glob_l1 = 0.0;
for(i = 0; i < num_procs; i++){
my_ave[i] = 0.0;
my_max[i] = 0.0;
my_l1[i] = 0.0;
}
my_timers[1].start(); // Iteration Timer
clearRegions(my_regions);
my_timers[7].start(); // Sort Timer
sortPoints(sort_method, my_regions);
my_timers[7].stop(); // Sort Timer
if(anneal_limit > 0 && it < anneal_limit){
if(force_anneal || (anneal_its > 0 && it%anneal_its == 0)){
annealPoints(my_regions);
if(force_anneal) force_anneal = 0;
}
}
my_timers[2].start(); // Triangulation Timer
triangulateRegions(my_regions);
//makeFinalTriangulations(my_regions);
my_timers[2].stop();
my_timers[3].start(); // Integration Timer
integrateRegions(my_regions);
my_timers[3].stop();
if(it > max_it_no_proj){
proj_alpha = max((double)(it-max_it_no_proj), 0.0)/max((double)max_it_scale_alpha, 1.0);
projectToBoundary(my_regions);
}
my_timers[4].start(); // Metrics Timer
computeMetrics(my_ave[id],my_max[id], my_l1[id]);
// Start non-blocking sends and receives of metrics
if(id == master){
for(i = 1; i < num_procs; i++){
ave_comms[i] = world.irecv(i,msg_ave,my_ave[i]);
max_comms[i] = world.irecv(i,msg_max,my_max[i]);
l1_comms[i] = world.irecv(i,msg_l1,my_l1[i]);
}
} else {
ave_comms[id] = world.isend(master,msg_ave,my_ave[id]);
max_comms[id] = world.isend(master,msg_max,my_max[id]);
l1_comms[id] = world.isend(master,msg_l1,my_l1[id]);
}
my_timers[4].stop();
my_timers[5].start(); // Communication Timer
transferUpdatedPoints();
my_timers[5].stop();
my_timers[6].start();
// Finish metrics sends and receives, check for convergence and broadcast a stop request to all processors.
if(id == master){
glob_ave = my_ave[id];
glob_max = my_max[id];
glob_l1 = my_l1[id];
for(i = 1; i < num_procs; i++){
ave_opti = ave_comms[i].test();
max_opti = max_comms[i].test();
l1_opti = l1_comms[i].test();
if(!ave_opti) ave_comms[i].wait();
if(!max_opti) max_comms[i].wait();
if(!l1_opti) l1_comms[i].wait();
glob_ave += my_ave[i];
glob_max = std::max(glob_max, my_max[i]);
glob_l1 += my_l1[i];
}
glob_ave = sqrt(glob_ave)/points.size();
glob_l1 = glob_l1/points.size();
cout << it << " " << glob_ave << " " << glob_l1 << " " << glob_max << endl;
if(conv == 1 && glob_ave < eps){
cout << "Converged on average movement." << endl;
stop = 1;
} else if(conv == 2 && glob_max < eps){
cout << "Converged on maximum movement." << endl;
stop = 1;
}
if(anneal_on == 1 && fabs(glob_ave - last_glob_ave)/glob_ave < 1E-8) {
force_anneal = 1;
} else if(anneal_on == 2 && fabs(glob_max - last_glob_max)/glob_max < 1E-8) {
force_anneal = 1;
}
last_glob_ave = glob_ave;
last_glob_max = glob_max;
last_glob_l1 = glob_l1;
}
mpi::broadcast(world,stop,master);
mpi::broadcast(world,force_anneal,master);
my_timers[6].stop();
my_timers[1].stop();
if(restart > 0 && it > 0){
if(it%restart == 0){
writePointsAsRestart(it, restart_mode, fileio_mode);
}
}
}
// Finish loop timer
my_timers[0].stop();
// Bisect if needed
if(bisection < num_bisections){
bisectTriangulation(0);
} else {
if(id == master){
cout << "No more bisections for convergence" << endl;
}
}
//Print out loop timers
if(id == master){
cout << endl << endl;
for(i = 0; i < num_timers; i++){
cout << my_timers[i];
}
cout << endl;
}
}
global_timers[0].stop();
//Compute average points per region for diagnostics
ave_points = 0;
my_points = 0;
clearRegions(my_regions);
sortPoints(sort_method, my_regions);
for(region_itr = my_regions.begin(); region_itr != my_regions.end(); ++region_itr){
my_points += (*region_itr).points.size();
}
mpi::reduce(world, my_points, ave_points, std::plus<int>(), master);
ave_points = ave_points / regions.size();
if(id == master){
cout << endl;
cout << "Average points per region: " << ave_points << endl;
cout << endl;
}
//Gather all updated points onto master processor, for printing to end_points.dat
global_timers[1].start(); // Global Gather Timer
gatherAllUpdatedPoints();
global_timers[1].stop();
// Compute final triangulation by merging all triangulations from each processor into an
// unordered_set, and then ordering them ccw before printing them out.
// write triangles to triangles.dat
global_timers[2].start(); // Final Triangulation Timer
clearRegions(my_regions);
sortPoints(sort_vor, my_regions);
makeFinalTriangulations(my_regions);
global_timers[2].stop();
printMyFinalTriangulation();
if(id == master){
ofstream end_pts("end_points.dat");
ofstream pt_dens("point_density.dat");
ofstream bdry_pts("boundary_points.dat");
for(point_itr = points.begin(); point_itr != points.end(); ++point_itr){
end_pts << (*point_itr) << endl;
pt_dens << density((*point_itr)) << endl;
}
for(boundary_itr = boundary_points.begin(); boundary_itr != boundary_points.end(); boundary_itr++){
bdry_pts << (*boundary_itr) << endl;
}
end_pts.close();
pt_dens.close();
bdry_pts.close();
}
//Bisect all edges of all triangles to give an extra point set at the end, bisected_points.dat
global_timers[3].start(); // Final Bisection Timer
bisectTriangulation(1);
global_timers[3].stop();
//Print out final timers, for global times.
if(id == master){
cout << endl << " ---- Final Timers ---- " << endl;
for(i = 0; i < num_global_timers; i++){
cout << global_timers[i];
}
}
return 0;
}
/* ***** Setup Routines ***** {{{*/
void readParamsFile(){/*{{{*/
//Read in parameters from Params.
//If Params doesn't exist, write out Params with a default set of parameters
int temp_restart_mode;
int temp_fileio_mode;
pugi::xml_document config;
pugi::xml_parse_result result = config.load_file("config.xml");
cout << result.description() << endl;
points_begin = config.child("initial_point_set").attribute("value").as_int();
num_pts = config.child("number_of_generated_points").attribute("value").as_int();
max_it = config.child("maximum_iterations").attribute("value").as_int();
restart = config.child("iterations_per_restart").attribute("value").as_int();
max_it_no_proj = config.child("iterations_without_projection").attribute("value").as_int();
max_it_scale_alpha = config.child("iterations_with_variable_projection").attribute("value").as_int();
div_levs = std::max(1, config.child("triangle_divisions").attribute("value").as_int());
num_bisections = config.child("bisections").attribute("value").as_int();
conv = config.child("convergence_check").attribute("value").as_int();
eps = atof(config.child("convergence_criteria").attribute("value").value());
quad_rule = config.child("quadrature_rule").attribute("value").as_int();
use_barycenter = config.child("delaunay_triangle_center").attribute("value").as_int();
sort_method = config.child("sort_method").attribute("value").as_int();
max_resolution = atof(config.child("max_boundary_resolution").attribute("value").value());
temp_fileio_mode = config.child("file_io_mode").attribute("value").as_int();
temp_restart_mode = config.child("restart_file_handling").attribute("value").as_int();
anneal_percent = atof(config.child("max_annealing_percent").attribute("value").value());
anneal_its = config.child("annealing_frequency").attribute("value").as_int();
anneal_limit = config.child("max_annealing_iterations").attribute("value").as_int();
anneal_on = config.child("anneal_when_stagnant").attribute("value").as_int();
anneal_shape_control = config.child("anneal_only_non_hexagons").attribute("value").as_int();
switch (temp_fileio_mode) {
case 0:
fileio_mode = FILEIO_TXT;
break;
case 1:
fileio_mode = FILEIO_NETCDF;
break;
case 2:
fileio_mode = FILEIO_BOTH;
break;
default:
cout << "Restart file format has incorrect value in params file. Should be one of {0,1,2}.";
exit(1);
}
switch (temp_restart_mode) {
case 0:
restart_mode = RESTART_OVERWRITE;
break;
case 1:
restart_mode = RESTART_RETAIN;
break;
default:
cout << "Restart mode (overwrite/retain) has incorrect value in params file. Should be one of {0,1}";
exit(1);
}
}/*}}}*/
void readBoundaries(){/*{{{*/
int i, j, n_pts;
int count_count, bdry_count, fill_count, bdry_total;
int add_count;
int count_start, count_stop;
int cur_loop_start, cur_loop_length;
int p0_idx, p1_idx;
//pnt p;
//pnt p_b, p_e;
double bdry_lon, bdry_lat;
double dtr = M_PI/180.0;
double point_delta;
double add_spacing;
double denom;
double c0, c1;
double t, omega;
double r_earth = 6371.0; //avg radius in km
// gw: read boundary points file
bdry_count = 0;
ifstream bdry_in("SaveBoundaries");
if(!bdry_in)
return;
while(!bdry_in.eof()){
bdry_in >> bdry_lon >> bdry_lat;
bdry_in.ignore(10000,'\n');
if(bdry_in.good()){
bdry_lon *= dtr;
bdry_lat *= dtr;
pnt p = pntFromLatLon(bdry_lat, bdry_lon);
p.normalize();
p.idx = j;
p.isBdry = 0;
bdry_count++;
boundary_points.push_back(p);
} // end if input good
} // end while not eof
bdry_in.close();
// gw: read loop counts file
count_count = 0;
ifstream count_in("SaveLoopCounts");
if(!count_in)
return;
while(!count_in.eof()){
count_in >> count_start >> count_stop;
count_in.ignore(10000,'\n');
if(count_in.good()){
loop_start.push_back(count_start);
loop_stop.push_back(count_stop);
count_count++;
} // end if input good
} // end while not eof
count_in.close();
// gw: loop over loops
fill_count = 0;
for(int cur_loop = 0; cur_loop < count_count; cur_loop++){
cur_loop_start = loop_start.at(cur_loop) - 1;
cur_loop_length = loop_stop.at(cur_loop) - cur_loop_start;
// gw: loop over point pairs in current loop
for(int cur_pair = 0; cur_pair < cur_loop_length; cur_pair++){
p0_idx = cur_loop_start + cur_pair;
p1_idx = cur_loop_start + (cur_pair+1)%cur_loop_length;
pnt p0 = boundary_points.at(p0_idx);
pnt p1 = boundary_points.at(p1_idx);
point_delta = p1.dotForAngle(p0);
// gw: if distance between pair is greater than allowed amount
// then add some additional points
if ( (point_delta * r_earth) > max_resolution ) {
// gw: figure out how many points to added
add_count = (int)ceil( (point_delta * r_earth) ) / max_resolution;
add_spacing = 1.0 / ((double)add_count + 1);
denom = sin( point_delta );
bdry_lat = p1.getLat() - p0.getLat();
bdry_lon = p1.getLon() - p0.getLon();
// gw: loop for adding point(s)
for(int cur_add = 0; cur_add <= add_count; cur_add++){
/* Slerp - Doesn't work for constant lat, lon curves
// http://en.wikipedia.org/wiki/Slerp
t = add_spacing * ( (double)cur_add + 1 );
c0 = sin( (1.0 - t) * point_delta ) / denom;
c1 = sin( t * point_delta ) / denom;
pnt temp_point = c0 * p0 + c1 * p1; // */
// Linear interpolation, using Lat Lon.
pnt temp_point = pntFromLatLon( p0.getLat() + cur_add * add_spacing * bdry_lat,
p0.getLon() + cur_add * add_spacing * bdry_lon);
temp_point.normalize();
temp_point.idx = bdry_count + fill_count;
boundary_points.push_back(temp_point);
fill_count++;
}
} // end if need to add fill points
} // end loop over point pairs in current loop
} // end loop over loops
cout << "Read in " << bdry_count << " boundary points." << endl;
cout << "Made " << fill_count << " fill points." << endl;
cout << "There are " << boundary_points.size() << " boundary points total." << endl;
num_bdry = boundary_points.size();
}/*}}}*/
void buildRegions(){/*{{{*/
//Read in region centers, and connectivity (triangulation) from files
//RegionList, and RegionTriangulation
//From these, regions are setup to have a center and a radius.
ifstream region_list("RegionList");
ifstream region_connectivity("RegionTriangulation");
unordered_set<int, int_hasher> neighbors1, neighbors2;
unordered_set<int, int_hasher>::iterator neigh_itr;
vector<int>::iterator cur_neigh_itr;
region r;
pnt p;
double loc_radius, max_radius;
double alpha, beta;
int min_connectivity;
int t1, t2, t3;
int i;
alpha = 2.0/3.0;
beta = 4;
#ifdef _DEBUG
cerr << "Building regions " << id << endl;
#endif
if(!region_list){
cout << "Failed to open file RegionList." << endl;
exit(1);
}
// Read in region centers
i = 0;
while(!region_list.eof()){
region_list >> p;
p.idx = i;
i++;
p.normalize();
r.center = p;
r.radius = 0.0;
if(region_list.good()){
regions.push_back(r);
}
}
region_list.close();
region_neighbors.resize(regions.size());
if(!region_connectivity){
cout << "Failed to open file RegionTriangulation" << endl;
exit(1);
}
//Read in region triangulation, and insert into hash table to get unique connectivity.
min_connectivity = regions.size();
while(!region_connectivity.eof()){
region_connectivity >> t1 >> t2 >> t3;
if(t1 < min_connectivity)
min_connectivity = t1;
if(t2 < min_connectivity)
min_connectivity = t2;
if(t3 < min_connectivity)
min_connectivity = t3;
}
region_connectivity.close();
region_connectivity.open("RegionTriangulation");
while(!region_connectivity.eof()){
region_connectivity >> t1 >> t2 >> t3;
t1 = t1 - min_connectivity;
t2 = t2 - min_connectivity;
t3 = t3 - min_connectivity;
if(region_connectivity.good()){
region_neighbors[t1].insert(t2);
region_neighbors[t1].insert(t3);
region_neighbors[t2].insert(t1);
region_neighbors[t2].insert(t3);
region_neighbors[t3].insert(t1);
region_neighbors[t3].insert(t2);
}
}
region_connectivity.close();
//Compute region radii by dotting with each neighbor, and taking the max distance.
for(region_itr = regions.begin(); region_itr != regions.end(); ++region_itr){
max_radius = 0.0;
loc_radius = 0.0;
neighbors1.insert((*region_itr).center.idx);
for(region_neigh_itr = region_neighbors[(*region_itr).center.idx].begin();
region_neigh_itr != region_neighbors[(*region_itr).center.idx].end();
++region_neigh_itr){
loc_radius = (*region_itr).center.dotForAngle(regions[(*region_neigh_itr)].center);
if(loc_radius > max_radius){
max_radius = loc_radius;
}
(*region_itr).neighbors.push_back((*region_neigh_itr));
}
(*region_itr).radius = std::min(max_radius,M_PI);
(*region_itr).input_radius = std::min(max_radius,M_PI);
(*region_itr).points.clear();
(*region_itr).triangles.clear();
(*region_itr).boundary_points.clear();
}
// Build first and second levels of neighbors, for use in more complicated sort method.
for(region_itr = regions.begin(); region_itr != regions.end(); ++region_itr){
neighbors1.clear();
neighbors2.clear();
neighbors1.insert((*region_itr).center.idx);
neighbors2.insert((*region_itr).center.idx);
for(cur_neigh_itr = (*region_itr).neighbors.begin(); cur_neigh_itr != (*region_itr).neighbors.end(); ++cur_neigh_itr){
neighbors1.insert((*cur_neigh_itr));
neighbors2.insert((*cur_neigh_itr));
for(neighbor_itr = regions.at((*cur_neigh_itr)).neighbors.begin();
neighbor_itr != regions.at((*cur_neigh_itr)).neighbors.end(); ++neighbor_itr){
neighbors2.insert((*neighbor_itr));
}
}
for(neigh_itr = neighbors1.begin(); neigh_itr != neighbors1.end(); ++neigh_itr){
(*region_itr).neighbors1.push_back((*neigh_itr));
}
for(neigh_itr = neighbors2.begin(); neigh_itr != neighbors2.end(); ++neigh_itr){
(*region_itr).neighbors2.push_back((*neigh_itr));
}
}
region_neighbors.clear();
}/*}}}*/
void printRegions(){/*{{{*/
// This function is only for debugging purposes.
// It's used to print out the information associated with each region
// to verify the region information gets read correctly.
ofstream r_out("RegionCenters.dat");
ofstream rr_out("RegionRadii.dat");
ofstream rp_out("RegionProperties.dat");
double radius;
clearRegions(regions);
sortPoints(sort_method, regions);
for(region_itr = regions.begin(); region_itr != regions.end(); ++region_itr){
radius = (*region_itr).radius;
radius = acos(-radius + 1.0);
r_out << (*region_itr).center << endl;
rr_out << radius << endl;
rp_out << (*region_itr).points.size() << endl;
}
r_out.close();
rr_out.close();
rp_out.close();