-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdld_sim.cc
2363 lines (2102 loc) · 72.7 KB
/
dld_sim.cc
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
#include "dld_sim.hh"
typedef std::complex<double> Comp;
dld_sim::dld_sim():
n_part(0), n_dissd(0), max_swp_thr(5), mrsq(1.), mr(1.),abmr(1.),
co(NULL), mem(NULL), wlpos(NULL),
rando(NULL), buf(NULL), shape(NULL), ba(NULL)
{}
/* #################### Constructor and Setup functions ################### */
/** Constructs a dld_sim class, allocating a block structure to store the
* particles positions and opening a diagnostic output file.
* Good for all geometry, parameters controlled by the sim_params object.
* \param[in] spars the pointer to a sim_params object that controls the type of simulation to initialize. */
dld_sim::dld_sim(sim_params *spars_p_):
n_part(0), n_dissd(0), max_swp_thr(5), mrsq(1.), mr(1.),abmr(1.),
rando(gsl_rng_alloc(gsl_rng_taus)), buf(new char[256]), spars_p(spars_p_)
{
get_sim_params();
co=new int[mn];
mem=new int[mn];
ba=new particle*[mn];
for(int i=0;i<mn;i++) {
co[i]=0;
if(!(spars_p->aggre)){
ba[i]=new particle[init_region_memory];
mem[i]=init_region_memory;
}
else{
ba[i] = NULL;
mem[i]=0;
}
}
dspcell = double (nocell)/dx;
int min[] = {0,0};
int max[] = {128,128};
wlpos = new int[nocell*nocell+1];
wl_gen my_list(min, max, max_swp_thr, nocell);
wl=my_list.worklist;
// Store the starting points of each worklist in wlpos[]
wl_pos();
//hard coded threshold value, change this later
/*
Grid g=extract_grid();
mytree=KDTree(g);
thr.push_back(1);
thr.push_back(2);
thr.push_back(4);
thr.push_back(8);
thr.push_back(10);
thr.push_back(13);
thr.push_back(18);
*/
}
/** Extracts paramters from spars object and call set_rnd() and set_blc_size(...).
* For flat geometry, it also sets some parameters in sim_params object, such as f_rate, target, burnin, etc.*/
void dld_sim::get_sim_params(){
sim_params &spars = *spars_p;
tot_nr = spars.nr;
seed = spars.randseed;
nocell = spars.nocell;
rad = spars.rad;
redge = rad;
height = 0;
tot_nrsp = 1.0 / (double) tot_nr;
cell_normalizer = 1/double (nocell*nocell);
filename = spars.sim_dir;
set_rnd(seed);
// adld stuff
if(spars.simtype == spars.ADLD){
if(!spars.adld_set) fatal_error("Initialization", PARAM_NOT_SET);
set_blc_size(spars.params, spars.terms, spars.length, rad, spars.dtheta);
}
else if(spars.simtype == spars.CIRCLE){
shape = new Comp[1];
set_blc_size();
}
else if(spars.simtype == spars.FLAT1){
if(!spars.aflat_set) fatal_error("Initialization", PARAM_NOT_SET);
rad /= 2;
redge = rad;
height = spars.height;
ul = height;
cftol = spars.cftol;
mr = -rad;
abmr = 5.0;
shape = new Comp[1];
set_blc_size(spars.tilt);
spars.set_output_params(twidth, nv, dx, true_tilt);
}
else if(spars.simtype == spars.FLAT2){
if(!spars.nflat_set) fatal_error("Initialization", PARAM_NOT_SET);
rad /= 2;
redge = rad;
height = spars.height;
ul = height;
mr = -rad;
abmr = 5.0;
shape = new Comp[1];
set_blc_size(spars.siden);
spars.set_output_params(twidth, nv, dx, true_tilt);
}
}
/** Set vital parameters in the simulation: dx, nv, nh, epsilon, xsp. For circles.*/
void dld_sim::set_blc_size(){
double tmp_r = rad;
int i=0;
while (tmp_r>min_blc_size){
tmp_r /= 2.;
i++;
}
nh = std::pow(2,i+1);
if (height!=0) nv = int(ceil(height/tmp_r));
else nv = nh;
mn = nv*nh;
dx = tmp_r;
epsilon = 0.0001;
xsp = 1/tmp_r;
twidth = rad+redge;
is_flat = false;
}
/** Set vital parameters in the simulation: dx, nv, nh, epsilon, xsp. For adlds.
* \param[in] params the array of coefficients for Laurent series that defines the shape.
* \param[in] terms the array of powers in the Laurent series.
* \param[in] length the first dimension of params array.
* \param[in] ur the size of the cluster.
* \param[in] dtheta sampling rate around the unit circle. */
void dld_sim::set_blc_size(double ** params, int* terms, int length, double ur, double dtheta){
int i=0;
adld_len = int(2*pi/dtheta);
//printf("adld_len = %d\n", length);
shape = new Comp[adld_len];
for(i=0;i<adld_len;i++) shape[i] = Comp(0,0);
adld_outline(shape, params, terms, length, ur, dtheta);
double rmax = -(rad*rad*10000);
for(i=0; i<adld_len; i++){
double shape_rsq = real(shape[i])*real(shape[i]) + imag(shape[i])* imag(shape[i]);
if(shape_rsq > rmax) rmax = shape_rsq;
}
rad= std::ceil(sqrt(rmax));
double tmp_r = rad;
i=0;
while (tmp_r>min_blc_size){
tmp_r /= 2.;
i++;
}
//i+1 because x-length is double the radius
nh = std::pow(2,i+1);
if (height!=0) nv = int(ceil(height/tmp_r));
else nv = nh;
mn = nv*nh;
dx = tmp_r;
epsilon = 0.0001;
xsp = 1/tmp_r;
twidth = rad+redge;
is_flat = false;
}
/** Set vital parameters in the simulation: par_lim, dx, nv, nh, epsilon, xsp
* true_tilt, redge, height, blclow, ylow.
* For flat geometry, with vertical number of particle specified.
* \param[in] n user provided particle numerator (in tan(theta) calculation).*/
void dld_sim::set_blc_size(int n){
int d = int (sqrt(rad*rad*4 - n*n));
ul = sqrt(d*d+n*n);
redge = ( (int) (rad*2/ul)) * ul - rad;
height = int (std::ceil(height/ul)) *ul;
if(height==0) height=ul;
true_tilt = atan2(double(n), double(d));
par_n = n;
par_d = d;
// Set block size
double tmp_r = rad + redge;
int i=0;
while (tmp_r>min_blc_size){
tmp_r /= 2.;
i++;
}
//i because x-length is the radius
nh = std::pow(2,i);
// nv is multiplied by two to allow shifting the whole array of particle up when it's dissolved away partially.
if (height!=0) nv = 2*int(ceil(height/tmp_r));
else nv = nh;
mn = nv*nh;
dx = tmp_r;
xsp = 1/tmp_r;
epsilon =0.0001;
// This puts ylow just outside of the maximum height, such at ylow-Y_DIS is at the max height
blclow=nv-1;
// This might lead to survey(dh, nelem) breaking, since mr is bounding the block of particles, and ylow is bounding the simulation domain
// mr - ylow, which should give the total high difference, would be negative before any particle was dissolved
ylow=nv*dx-rad +sfac*sqrt(2)*cos(pi/4- true_tilt); // this is the highest possible y (accounting the particle size)
yref= round(nv*dx - rad + 0.5);
twidth = rad+redge;
is_flat = true;
}
/** Set vital parameters in the simulation: par_lim, dx, nv, nh, epsilon, xsp
* true_tilt, redge, height, blclow, ylow.
* For flat geometry, with tilting angle specified.
* \param[in] tilt user provided tilting angle.*/
void dld_sim::set_blc_size(double tilt){
int d=1, n=0, par_lim=20;
bool success = 0;
if (tilt !=0){
success = cont_frac(tilt, n, d, par_lim);
while(!success){
par_lim +=10;
success = cont_frac(tilt, n, d, par_lim);
}
ul = sqrt(d*d+n*n);
par_n = n;
par_d = d;
redge = ( (int) (rad*2/ul)) * ul - rad;
height = int (std::ceil(height/ul)) *ul;
if(height==0) height=ul;
if(redge<= -rad) {
sprintf(buf,"Width is too small to accomodate tilt = %.0f estimate tolerance (%f) and unitlength %f\n", tilt, cftol, ul);
fatal_error("set_blc_size()", buf);
}
true_tilt = atan2(double(n), double(d));
}
else{
true_tilt = 0;
ul = rad;
}
// Set block size
double tmp_r = rad + redge;
int i=0;
while (tmp_r>min_blc_size){
tmp_r /= 2.;
i++;
}
//i because x-length is the radius
nh = std::pow(2,i);
// nv is multiplied by two to allow shifting the whole array of particle up when it's dissolved away partially.
if (height!=0) nv = 2*int(ceil(height/tmp_r));
else nv = nh;
mn = nv*nh;
dx = tmp_r;
xsp = 1/tmp_r;
epsilon =0.0001;
// This puts ylow just outside of the maximum height, such at ylow-Y_DIS is at the max height
blclow=nv-1;
// This might lead to survey(dh, nelem) breaking, since mr is bounding the block of particles, and ylow is bounding the simulation domain
// mr - ylow, which should give the total high difference, would be negative before any particle was dissolved
ylow=nv*dx-rad +sfac*sqrt(2)*cos(pi/4- true_tilt);
yref= round(nv*dx - rad + 0.5);
twidth = rad+redge;
is_flat = true;
}
/** The class destructor closes the diagnostic file and frees the dynamically allocated memory. */
dld_sim::~dld_sim() {
if(wlpos!=NULL) delete [] wlpos;
if(ba!=NULL){
for(int i=mn-1;i>=0;i--) delete [] ba[i];
delete [] ba;
}
if(mem!=NULL) delete [] mem;
if(co!=NULL) delete [] co;
if(shape!=NULL) delete [] shape;
if(buf!=NULL) delete [] buf;
if(rando!=NULL) gsl_rng_free(rando);
}
/* #################### House Keeping ####################*/
/** Reset all the counters, and the storage array.
* Used when multiple simulations are using the same dld_sim object.
* \param[in] dla a flat to tell how much initial region memory to allocate
* if true then initial memory is zero. Default value is false. */
void dld_sim::clean(bool dla){
n_part=0;
n_dissd=0;
yref= round(nv*dx - rad + 0.5);
// Reinitialize the simulation blocks
for(int i=0; i<mn;i++){
co[i]=0;
if(!dla){
mem[i]=init_region_memory;
particle* nba=new particle[init_region_memory];
delete [] ba[i];
ba[i]=nba;
}
else{
mem[i]=0;
if(ba[i]!=NULL) delete [] ba[i];
ba[i] = NULL;
}
}
mrsq=1.0;
if (is_flat) mr = -rad;
else mr = 1;
}
/** Checks if there are duplicate particles in the system */
void dld_sim::check_dup(){
for (int i=0; i<mn;i++){
for (int j =0;j<co[i]; j++){
particle * dummy = &ba[i][j];
for (int k=0; k<co[i]; k++){
if (k!=j){
if(ba[i][k].x<dummy->x+epsilon && ba[i][k].x>dummy->x - epsilon && ba[i][k].y <dummy->y+epsilon && ba[i][k].y>dummy->y- epsilon) {
sprintf(buf, "Found duplication particles at block %d, (%f %f)", i, ba[i][k].x, ba[i][k].y);
fatal_error("check_dup()", buf);
}
}
}
}
}
}
/** Take a particle from the simulation.
* \param[in] doom the pointer to the particle to be taken. */
void dld_sim::take(particle* doom) {
double x=doom->x;
double y=doom->y;
double ax = (-1)*rad, ay = (-1)*rad;
// Compute which block the particle is within
int nx=int((x-ax)*xsp);if(nx<0) nx=0;if(nx>=nh) nx=nh-1;
int ny=int((y-ay)*xsp);if(ny<0) ny=0;if(ny>=nv) ny=nv-1;
int s=nx+nh*ny;
*doom = ba[s][--co[s]];
n_part --;
}
/** Adds a particle to the simulation.
* \param[in] x the x coordinate of the particle.
* \param[in] y the y coordinate of the particle. */
particle * dld_sim::put(double x,double y) {
double ax = (-1)*rad, ay = (-1)*rad;
// Compute which block the particle is within
int nx=int((x-ax)*xsp);if(nx<0) nx=0;if(nx>=nh) nx=nh-1;
int ny=int((y-ay)*xsp);if(ny<0) ny=0;if(ny>=nv) ny=nv-1;
int s=nx+nh*ny;
//printf("put: nh = %d, nv=%d, nx=%d, ny=%d\n", nh, nv, nx, ny);
if (s>=mn) {
sprintf(buf,"Putting particle at x=%.2f, y=%.2f, nx=%d, ny=%d, s=%d.\nBlock index out of bound. Probably from shiftup().\n", x, y, nx, ny, s);
fatal_error("put():", buf);
}
// Check there's enough memory for the particle,
// and if not, extend the memory
if(co[s]==mem[s]) add_region_memory(s);
ba[s][co[s]++]=particle(x,y);
n_part++;
if(!is_flat){
double rsq=sqrt(x*x+y*y)+1;
// Update the maximum radius of the cluster
if(rsq>mr) {
mr=rsq;
mrsq=mr*mr;
}
}
else{
double R = y+abmr;
if (R>mr){
mr = R;
// hypotenuse squared
mrsq = mr*mr + 4*rad*rad;
}
}
return ba[s]+co[s]-1;
}
/** Initialize the cluster from file, return if the file was read successfully
* \param[in] init_filename the full path and name to the file for initialization */
bool dld_sim::init_from_file(char* init_filename){
std::fstream fn(init_filename, std::ios_base::in);
double a,x=0,y=0;
int counter=0;
while(fn>>a){
if(counter%2==0) x=a;
else {
y=a;
put(x,y);
}
counter++;
}
return counter;
}
/** Consider a walker at (x,y)=(r,0). This samples the angle at which the walker first
* touches the unit circle.
* \param[in] r the x position of the walker. */
double dld_sim::bias_angle(double r) {
return 2*std::atan((r+1)/(r-1)*std::tan((rnd()-0.5)*pi));
}
/** Consider a walker at (x,y). This maps the walker to the line y=mr
* the x position is determined by uniform sampling from 0 to 2PI, then conformal map to real line
* \param[in,out] x the x position of the walker.
* \param[in,out] y the y position of the walker. */
void dld_sim::pbcremap(double &x, double &y){
if(y>(mr+abmr)){
double b = y-mr;
double theta = 2*pi*rnd();
Comp z_denom = Comp(1.0+cos(theta), sin(theta));
Comp z_num = Comp(b*sin(theta), b*(1.0-cos(theta)));
Comp w= z_num / z_denom;
double new_x = real(w)+x;
//printf("pbcremap(): (%f, %f)\n", new_x, new_y);
y = mr;
if(new_x< -rad) new_x=fmod(new_x+rad, twidth)+redge;
else if(new_x >=redge) new_x=fmod(new_x-redge, twidth) -rad;
x=new_x;
}
}
/** Calculates the total number of particles in the simulation. */
int dld_sim::total_particles() {
int tot=*co;
for(int i=1;i<mn;i++) tot+=co[i];
return tot;
}
/** Check whether north, south, east, west neighbors exist
* 0, 1 = north, south, 2, 3 = west, east.
* \param[in] x x-coordinate of the current particle.
* \param[in] y y-coordinate of the current particle.
* \param[in] dir a integer representation of the inquired neighbor.*/
bool dld_sim::ex_neighbor(double x, double y, short dir){
double sintheta = sin(true_tilt);
double costheta = cos(true_tilt);
double tol = 0.1, ngx, ngy;
//north
if(dir==0){
ngx = x-sintheta;
ngy = y+costheta;
if(is_flat && ngx<-rad) ngx +=twidth;
}
//south
else if (dir==1){
ngx = x+sintheta;
ngy = y-costheta;
if(is_flat && ngx>=redge) ngx -=twidth;
}
//west
else if (dir==2){
ngx = x-costheta;
ngy = y-sintheta;
if(is_flat && ngx<-rad) ngx +=twidth;
}
//east
else if (dir ==3){
ngx = x+costheta;
ngy = y+sintheta;
if(is_flat && ngx>=redge) ngx -=twidth;
}
else fatal_error("ex_neighbor()", "dir must be 0, 1, 2, 3 for north, south, east, west");
bool exist = 0;
// highest possible is nv*dx -rad since the particles can be shifted up
if (ngy>(-1)*rad && ngy<(nv*dx-rad)){
double ax = (-1)*rad;
double ay = ax;
int nx=int((ngx-ax)*xsp);if(nx<0) nx=0;if(nx>=nh) nx=nh-1;
int ny=int((ngy-ay)*xsp);if(ny<0) ny=0;if(ny>=nv) ny=nv-1;
int s = nx+nh*ny;
for (int i =0; i<co[s]; i++){
double px = ba[s][i].x;
double py = ba[s][i].y;
if (px<ngx+tol && px>ngx-tol && py <ngy+tol && py>ngy-tol){
exist=1;
break;
}
}
}
return exist;
}
/** Sets the lowest y coordinate in the system and the corresponding lowest block.
* \param[in] pp the pointer to the particle that is just dissolved. */
void dld_sim::set_lowest(particle *pp){
double ay = (-1)*rad;
double y = pp->y, x =pp->x;
int ny=int((y-ay)*xsp);if(ny<0) ny=0;if(ny>=nv) ny=nv-1;
if (ny<blclow) {
blclow = ny;
}
if (y<ylow){
ylow=y;
xlow=x;
}
}
/** Determines whether the cluster has dissolved enough to be shifted up by a unit height. */
bool dld_sim::diss_enough(){
if(blclow>1) return false;
else{
double ay = (-1)*rad;
double y;
int ny;
for(int i=mn-1;i>=0;i--){
for (int j=0; j<co[i]; j++){
y = ba[i][j].y;
ny=int((y-ay)*xsp);if(ny<0) ny=0;if(ny>=nv) ny=nv-1;
if((ny+1) > (int) nv/2) {
return false;
}
}
}
return true;
}
}
/** Shifts the entire cluster up by member data, height, a unit length determined by cont_frac().
* \param[in] dupcheck a switch to check if there are duplicate particles.
* \param[in] verbose a switch to turn on self-identifying and debug info. */
void dld_sim::shiftup(bool dupcheck, bool verbose){
bool enough = diss_enough();
if (!enough) {
if(verbose) msg("shiftup()", "Have not dissolved enough.");
return;
}
else{
if (blclow < 1 ) fatal_error("shiftup()", "Might have dissolved too much, or blclow artifially set too low.");
for (int i=mn-1; i>=0; i--){
for (int j=0; j<co[i]; j++){
double xx = ba[i][j].x;
double yy = ba[i][j].y;
put(xx, yy+height);
}
if (co[i]!=0){
n_part -= co[i];
mem[i] = init_region_memory;
co[i] = 0;
}
}
ylow += height;
yref += height;
int ny = (int) ((ylow+rad)*xsp); if(ny<0) ny=0; if(ny>=nv) ny= nv-1;
blclow=ny;
flat(verbose);
if(dupcheck) check_dup();
}
}
/** Doubles the memory allocation in a simulation block.
* \param[in] s the block to double. */
void dld_sim::add_region_memory(int s) {
if(mem[s]==0) mem[s]=1;
else mem[s]<<=1;
if(mem[s]>=max_region_memory) {
sprintf(buf, "Memory allocation exceeded in region %d, number of particles %d. But not fatal.\n",s, co[s]);
msg("add_region_memory():",buf);
}
particle* nba=new particle[mem[s]];
if (ba[s]!=NULL) {
for(int i=0;i<co[s];i++) nba[i]=ba[s][i];
delete [] ba[s];
}
ba[s]=nba;
}
/** Halves the memory allocation in a simulation block.
* \param[in] s the block to halve. */
void dld_sim::halve_region_memory(int s) {
// >1 because we want non-zero memory, since add_region_memory
// does bit shifting, shifting zero still gives zero.
if(mem[s]>1){
mem[s]>>=1;
particle* nba=new particle[mem[s]];
for(int i=0;i<co[s];i++) nba[i]=ba[s][i];
delete [] ba[s];
ba[s]=nba;
}
}
/** Use sim_params info to initialize a cluster, gives back the total number of particles;
* cleans up all the particles afterward. This is used in output filename of active zone files.*/
void dld_sim::calculate_cluster_size(){
sim_params &spars = *spars_p;
bool hexa = spars.hexa, adld = (spars.simtype==1);
if(hexa) printf("Nothing has been done. Hexagonal grid not implemented.\n");
if(!adld) square(rad);
else adld_cluster();
int tb = total_particles();
spars.set_output_params(tb);
clean();
}
/** Saves the particle positions as a text file containing integer IDs,
* positions, lengths, and rotations.
* \param[in] suffix the string suffix to add to the filename. */
void dld_sim::write(const char* k) {
// create the output filename and open the output file
sprintf(buf,"%s/f.%s",filename,k);
FILE *fp=safe_fopen(buf,"w");
//output the particle positions to the file
for(int s=0;s<mn;s++) {
for(int q=0;q<co[s];q++) {
particle &b=ba[s][q];
fprintf(fp,"%g %g\n",b.x,b.y);
}
}
// close the file
fclose(fp);
}
/** Saves the particle positions as a text file containing integer IDs,
* positions, lengths, and rotations.
* \param[in] k the integer suffix to add to the filename. */
void dld_sim::write(int k) {
// create the output filename and open the output file
sprintf(buf,"%s/f.%d",filename,k);
FILE *fp=safe_fopen(buf,"w");
//output the particle positions to the file
for(int s=0;s<mn;s++) {
for(int q=0;q<co[s];q++) {
particle &b=ba[s][q];
fprintf(fp,"%g %g\n",b.x,b.y);
}
}
// close the file
fclose(fp);
}
/** Scans all the blocks and give the location of the last particle. */
particle dld_sim::last() {
if(total_particles()==1){
particle loner;
for(int i=0; i<mn; i++){
if(co[i]==1) {
loner=ba[i][0];
// take away the particle
co[i]--;
break;
}
}
return loner;
}
else {
fatal_error("last()", "More than just one particle left, but other parts of the code claim only 1 particle left. Check your code.");
exit(0);
}
}
/** Scan all the blocks and shrink the max radius if applicable. */
void dld_sim::shrink_r() {
double rsq=0;
if(is_flat) {
rsq = -rad;
bool update = false;
for(int i=0;i<mn;i++){
for(int j=0;j<co[i];j++){
double y = ba[i][j].y;
if(y>=rsq) {
rsq = y;
update = true;
}
}
}
if(update==true){
mr = rsq+abmr;
mrsq = mr*mr + 4*rad*rad;
}
}
else{
for(int i=0;i<mn;i++){
// This bit frees up unused memory.
if(mem[i]>1){
int gold_fish=mem[i];
while(co[i]<=(gold_fish>>=1)){
halve_region_memory(i);
if(gold_fish == 1) break;
}
}
// This bit shrinks down the radius.
for(int j=0;j<co[i];j++){
double my_rsq;
my_rsq=ba[i][j].x*ba[i][j].x+ba[i][j].y*ba[i][j].y;
if(my_rsq>=rsq) rsq=my_rsq;
}
}
mr=sqrt(rsq)+2.*sfac;
mrsq=mr*mr;
}
}
/* #################### Creating the grids ################### */
/** Create a circular cluster of radius r on hexagonal grid. Particle radius = 0.5.
* \param[in] r cluster radius. */
void dld_sim::hex(double r){
int rmax = (int) r +1;
// The side of the hexagonal cells is 1
// h is the height from the center of the cell to the side
double h=sqrt(3)*0.5;
// Radius of the cluster in the units of h.
int rh= (int)(r/h)+1;
// j is the index of the rows
for(int j=(-1)*rmax; j<=rmax; j++){
// i is the index of the columns.
// In this particular hexagonal lattice, all the points line up vertically,
// spaced by h. While horizontally, spacing alternates.
for(int i=(-1)*rh; i<=rh; i++){
if(i%2==0){
double x=(double) (i*h);
double y=(double) j;
if(x*x+y*y<=r*r) put(x,y);
}
else{
double x=(double) (i*h);
double y=(double) (j+0.5);
if(x*x+y*y<=r*r) put(x,y);
}
}
}
}
/** Create a circular cluster of radius r, on cartesian grid. Particle radius=0.5.
* \param[in] r the radius of the cluster. */
void dld_sim::square(double r) {
// Start a circular cluster by putting a seed at (0,0)
int rmax = (int) r+1;
for(int i=(-1)*rmax; i<=rmax;i++){
for (int j=(-1)*rmax; j<=rmax;j++){
double x = (double) i;
double y = (double)j;
if (x*x+y*y<=r*r) put(x, y);
}
}
}
/** Generates the outline of shapes in ADLD.
* \param[out] result the complex number that represent the outline of the shape.
* \param[in] params a 2D double pointers array specifying the conformal mapping coefficient of the shape.
* \param[in] terms the pointer to an array specifying the powers in the Laurent series of the shape.
* \param[in] length length of the 2D double points, row wise, i.e. number of terms in Laurent series.
* \param[in] ur the size of the cluster.
* \param[in] dtheta sampling rate around the unit circle. */
void dld_sim::adld_outline(Comp *&result, double ** params, int * terms, int length, double ur, double dtheta){
Comp *mypars = new Comp[length];
for(int i =0; i<length; i++){
mypars[i] = Comp(params[i][0], params[i][1]);
//printf("%f %f\n", real(mypars[i]), imag(mypars[i]));
}
int domain = int (2*pi/dtheta);
for (int i =0; i<domain; i++){
double theta = i*dtheta;
Comp z = Comp(cos(theta), sin(theta));
for (int j= 0; j<length; j++){
result[i] += ur*mypars[j]* pow(z, terms[j]);
}
}
delete [] mypars;
}
/** Creates cluster according to ADLD shape outline. */
void dld_sim::adld_cluster(){
Comp * outline = shape;
int outline_len = adld_len;
// grad the x and y coordinate in 2D
double * xcoord = new double[outline_len];
double * ycoord = new double[outline_len];
// find xmax and xmin
double xlargest = -rad;
double xsmallest = rad;
double ylargest = xlargest, ysmallest = xsmallest;
for (int i=0; i<outline_len; i++){
xcoord[i] = real(outline[i]);
ycoord[i] = imag(outline[i]);
if(xcoord[i]>xlargest) {
xlargest = xcoord[i];
}
if(xcoord[i]<xsmallest){
xsmallest = xcoord[i];
}
if(ycoord[i]>ylargest) {
ylargest = ycoord[i];
}
if(ycoord[i]<ysmallest){
ysmallest = ycoord[i];
}
// check whether xcoord[i], ycoord[i] are integers, to be continued here
}
int xmax = int(std::ceil(xlargest));
int xmin = int(std::floor(xsmallest));
int ymax = int(std::ceil(ylargest));
int ymin = int(std::floor(ysmallest));
// create a vector to get store pair of verteces where ray crosses the segment
std::vector<vertex_pair> crosses;
// value of side =1 if vertex is to the left of ray; otherwise 0
bool side = 0;
// side value for next vertex
bool next_side = 0;
// true if current vertex is on the ray
bool on_vertex = 0;
// true if next vertex is on the ray
bool next_on_vertex = 0;
for (int x=xmax; x>=xmin; x--){
//printf("x =%d\n", x);
int vp_co = 0;
// compare first point on the polygon to last point
if(xcoord[0]<x) {
side=1;
on_vertex = 0;
} // if to the left of the ray
else if (xcoord[0]>x) {
side = 0;
on_vertex = 0;
} // if to the right
else {
vertex_pair single_vp(xcoord[0], ycoord[0]);
on_vertex =1 ;
// check whether the ray is grazing this single vertex
bool graze_check1 = 0;
bool graze_check2 = 0;
if (xcoord[1] < xcoord[0]) graze_check1 = 1;
else if (xcoord[1] > xcoord[0]) graze_check1 =0;
else fatal_error("adld_cluste()", "Encounters vertical lines\n");
if (xcoord[outline_len-1] < xcoord[0]) graze_check2=1;
else if( xcoord[outline_len-1]>xcoord[0]) graze_check2=0;
else fatal_error("adld_cluster()", "Encounters vertical lines\n");
// if two neighbors are on the same side, then the ray grazes current vertex
if(graze_check1 == graze_check2) {
single_vp.graze=1;
}
// if it doesn't graze it, then add it to the ylim list
else{ vp_co++ ; }
crosses.push_back(single_vp);
} // if neither, ray go through vertex
// since while loop only look at current vertex starting from 1, compared to the one before,
// the loop will miss 0 comparing to the one before
// here we test vertex 0 and vertex -1 (end)
if(xcoord[outline_len-1] < x) {
next_side=1;
next_on_vertex =0 ;
}
else if (xcoord[outline_len -1] > x) {
next_side =0;
next_on_vertex = 0;
}
else {
//crosses.push_back( vertex_pair(xcoord[outline_len-1], ycoord[outline_len-1]) );
next_on_vertex = 1;
}
// on the in the case of neither point is on the ray, one is left and one is right
if(side!=next_side && !(on_vertex | next_on_vertex) ){
crosses.push_back( vertex_pair( xcoord[0], ycoord[0], xcoord[outline_len-1], ycoord[outline_len-1] ));
vp_co++;
}
// starting at second vertex, compare to the one before
int j = 1;
while(j < outline_len){
if (xcoord[j] < x ) {
next_side = 1;
next_on_vertex = 0;
}
else if (xcoord[j] > x) {
next_side =0;
next_on_vertex = 0;
}
else {
next_on_vertex = 1;
vertex_pair single_vp(xcoord[j], ycoord[j]);
// check whether the ray is grazing this single vertex
bool graze_check1 = 0;
bool graze_check2 = 0;
if (xcoord[j+1] < xcoord[j]) graze_check1 = 1;
else if (xcoord[j+1] > xcoord[j]) graze_check1 =0;
else fatal_error("adld_cluste()", "Encounters vertical lines");
if (xcoord[j-1] < xcoord[j]) graze_check2=1;
else if( xcoord[j-1]>xcoord[j]) graze_check2=0;
else fatal_error("adld_cluste()", "Encounters vertical lines");
// if two neighbors are on the same side, then the ray grazes current vertex
if(graze_check1 == graze_check2) {
single_vp.graze=1;
}
else{
vp_co++;
}
crosses.push_back(single_vp);
}
if(next_side!=side && !(on_vertex | next_on_vertex)) {
crosses.push_back( vertex_pair(xcoord[j], ycoord[j], xcoord[j-1], ycoord[j-1]) );
vp_co++;
}
// set the current vertex
side = next_side;
on_vertex = next_on_vertex;
j++;
// if on the same side don't do anything
}
std::vector<vertex_pair>::iterator it;
// if there are crossings
if (vp_co!=0) {
double * ylim = new double[vp_co];
int dummy_index = 0;
double dummy_y;
for (it=crosses.begin(); it!=crosses.end(); it++){
if ( (!(*it).single && !(*it).graze) || ((*it).single && !(*it).graze) ) {
double lx1 = (*it).v1[0], ly1= (*it).v1[1], lx2= (*it).v2[0], ly2=(*it).v2[1];
if ((*it).single) {
dummy_y = ly1;
}
else{
double t = (double(x) - lx1)/(lx2 - lx1);
dummy_y = ly1*(1-t)+ly2*t;
}
ylim[dummy_index] = dummy_y;
dummy_index++;
}
else if ( (*it).single && (*it).graze ){ put( (*it).v1[0], (*it).v1[1] ); }
else fatal_error("adld_cluste()", "A situation with a pair of verteces grazing the ray hasn't been considered, but detected anyway.");
}
// Gotta sort the ylim first!
if (dummy_index >2 ){
for (int p = 0; p<dummy_index; p++){
double lips = ylim[p];
int lips_pos = p;
for (int q = p+1; q<dummy_index; q++){
if(ylim[q] < lips){
lips = ylim[q];
lips_pos = q;
}
}
if(lips_pos!=p){
double lips_tmp = ylim[p];
ylim[p] = ylim[lips_pos];
ylim[lips_pos] = lips_tmp;
}
}
//for(int p=0; p<dummy_index; p++) printf("ylim[%d]= %f\n", p, ylim[p]);
}
dummy_index = 0;
while(dummy_index<vp_co/2){
double y_hi = ylim[dummy_index*2];
double y_low = ylim[dummy_index*2+1];
if(y_hi<y_low){
double tmp = y_low;
y_low = y_hi;
y_hi = tmp;
}
//printf("yhi=%f, ylow=%f\n", yhi, ylow);
double y = double(ymax);
while( y>=ymin ){
if( y>=y_low && y<= y_hi) put(double(x), y);
y-=1.0;
}
dummy_index++;
}