-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcluster_dynamics.cpp
More file actions
1646 lines (1130 loc) · 60.3 KB
/
cluster_dynamics.cpp
File metadata and controls
1646 lines (1130 loc) · 60.3 KB
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 "cluster_dynamics.h"
//---------------------Some Primitives -------------------------------------------//
double random_real(double initial, double last) {
std::uniform_real_distribution<double> distribution(initial, last);
return distribution(rng); // Use rng as a generator
}
int random_int(int initial, int last) {
std::uniform_int_distribution<int> distribution(initial, last);
return distribution(rng); // Use rng as a generator
}
float mean_of_array(float array[],int size){
float sum = 0.0;
for (int i =0; i<size; ++i){
sum += array[i];
}
return sum/(float)size;
}
float standard_deviation_of_array(float array[],int size){
float mean = mean_of_array(array,size);
float sum = 0.0;
for (int i = 0; i < size; ++i){
sum += (array[i]-mean)*(array[i]-mean);
}
float variance = sum/(float)size;
return sqrt(variance);
}
float mean_of_vector(vector<float> array,int size){
float sum = 0.0;
for (int i =0; i<size; ++i){
sum += array[i];
}
return sum/(float)size;
}
void random_frame(int frame[], int grid_size) {
for (int i = 0; i < grid_size; ++i) {
for (int j = 0; j < grid_size; ++j) {
frame[i*grid_size + j] = random_int(0, 1);
}
}
}
void random_frame_of_density(float density, int frame[], int grid_size) {
for (int i = 0; i < grid_size; ++i) {
for (int j = 0; j < grid_size; ++j) {
if (random_real(0,1)<=density){
frame[i*grid_size + j] = 1;
}
else{
frame[i*grid_size + j] = 0;
}
}
}
}
void zeros(int frame[], int grid_size) {
for (int i = 0; i < grid_size; ++i) {
for (int j = 0; j < grid_size; ++j) {
frame[i*grid_size + j] = 0;
}
}
}
float calculate_density(int frame[], int grid_size){
float occupancy = 0;
for (int i = 0; i < grid_size; ++i) {
for (int j = 0; j < grid_size; ++j) {
occupancy += frame[i*grid_size + j];
}
}
float density = occupancy/(grid_size*grid_size);
return density;
}
void increase_stack_limit(int stack_size){
//Source: https://stackoverflow.com/questions/2279052/increase-stack-size-in-linux-with-setrlimit
//Credit: https://stackoverflow.com/users/253056/paul-r
//Used with modification
// This becomes necessary for recursive depth first search when finding clusters.
const rlim_t kStackSize = 64 * 1024 * 1024; // min stack size = 16 MB
struct rlimit rl;
int result;
result = getrlimit(RLIMIT_STACK, &rl);
if (result == 0)
{
if (rl.rlim_cur < kStackSize)
{
rl.rlim_cur = kStackSize;
result = setrlimit(RLIMIT_STACK, &rl);
if (result != 0)
{
fprintf(stderr, "setrlimit returned result = %d\n", result);
}
}
}
}
int disjoint_vectors(vector<int> vec_1, vector<int> vec_2){
//https://www.faceprep.in/c/check-if-the-given-arrays-are-disjoint-in-c-c-java-and-python-faceprep/
// returns 1 if the two arrays have a common element, 0 otherwise
int size_vec_1 = vec_1.size();
int size_vec_2 = vec_2.size();
for(int i = 0;i<size_vec_1;i++)
{
for(int j=0;j<size_vec_2;j++)
{
if(vec_1[i] == vec_2[j])
return 1;
}
}
return 0;
}
vector<int> common_elements(vector<int> vec_1, vector<int> vec_2){
//Credits: https://www.faceprep.in/c/check-if-the-given-arrays-are-disjoint-in-c-c-java-and-python-faceprep/
//returns the unique common elements of two vectors
vector<int> common_elements;
int size_vec_1 = vec_1.size();
int size_vec_2 = vec_2.size();
for(int i = 0;i<size_vec_1;i++)
{
for(int j=0;j<size_vec_2;j++)
{
if(vec_1[i] == vec_2[j])
common_elements.push_back(vec_1[i]);
}
}
sort( common_elements.begin(), common_elements.end() );
common_elements.erase( unique( common_elements.begin(), common_elements.end() ), common_elements.end() );
return common_elements;
}
template<typename T>std::vector<double> linspace(T start_in, T end_in, int num_in){
//Source: https://stackoverflow.com/questions/27028226/python-linspace-in-c/27030598#27030598
//Credits: https://stackoverflow.com/users/1078084/akavall
//Equivalent of numpy's linspace method.
std::vector<double> linspaced;
double start = static_cast<double>(start_in);
double end = static_cast<double>(end_in);
double num = static_cast<double>(num_in);
if (num == 0) { return linspaced; }
if (num == 1)
{
linspaced.push_back(start);
return linspaced;
}
double delta = (end - start) / (num - 1);
for(int i=0; i < num-1; ++i)
{
linspaced.push_back(start + delta * i);
}
linspaced.push_back(end);
return linspaced;
}
void print_vector(std::vector<double> vec){
std::cout << "size: " << vec.size() << std::endl;
for (double d : vec)
std::cout << d << " ";
std::cout << std::endl;
}
// -------------------------------Percolation Models---------------------------------------//
coordinates select_neighbor_of_site(coordinates site, int grid_size){
// Selects at random one of the four neighbours in von-neumann radius of 1 with periodic boundary conditions
int x = site.x;
int y = site.y;
coordinates neighbours[4];
neighbours[0].x = (x-1)%grid_size, neighbours[0].y = y; //left
neighbours[1].x = (x+1)%grid_size, neighbours[1].y = y; //right
neighbours[2].x = x, neighbours[2].y = (y-1)%grid_size; //bottom
neighbours[3].x = x, neighbours[3].y = (y+1)%grid_size; //top
int who = random_int(0,3);
coordinates neighbour = neighbours[who];
if (neighbour.x < 0){
neighbour.x = grid_size-1; //correction if selected site is the left of first column
}
if (neighbour.y < 0){
neighbour.y = grid_size-1; //correction if selected site is the top of first row
}
return neighbour;
}
coordinates select_neighbor_of_pair(coordinates site, coordinates neighbour, int grid_size){
// Selects at random one of the six neighbours of a pair of sites. Here too we have periodic boundary conditions.
int diff_x = site.x - neighbour.x;
int diff_y = site.y - neighbour.y;
coordinates neighbours_of_pair[6];
if ((diff_x ==1||diff_x==-(grid_size-1)) && diff_y ==0){ // neighbour is to the left of focal site
neighbours_of_pair[0].x = (site.x+1)%grid_size, neighbours_of_pair[0].y = site.y;
neighbours_of_pair[1].x = (neighbour.x-1)%grid_size, neighbours_of_pair[1].y = site.y;
neighbours_of_pair[2].x = site.x, neighbours_of_pair[2].y = (site.y+1)%grid_size;
neighbours_of_pair[3].x = site.x, neighbours_of_pair[3].y = (site.y-1)%grid_size;
neighbours_of_pair[4].x = neighbour.x, neighbours_of_pair[4].y = (neighbour.y+1)%grid_size;
neighbours_of_pair[5].x = neighbour.x, neighbours_of_pair[5].y = (neighbour.y-1)%grid_size;
}
if ((diff_x ==-1 ||diff_x==(grid_size-1)) && diff_y ==0){ // neighbour is to the right of focal site
neighbours_of_pair[0].x = (site.x-1)%grid_size, neighbours_of_pair[0].y = site.y;
neighbours_of_pair[1].x = (neighbour.x+1)%grid_size, neighbours_of_pair[1].y = site.y;
neighbours_of_pair[2].x = site.x, neighbours_of_pair[2].y = (site.y+1)%grid_size;
neighbours_of_pair[3].x = site.x, neighbours_of_pair[3].y = (site.y-1)%grid_size;
neighbours_of_pair[4].x = neighbour.x, neighbours_of_pair[4].y = (neighbour.y+1)%grid_size;
neighbours_of_pair[5].x = neighbour.x, neighbours_of_pair[5].y = (neighbour.y-1)%grid_size;
}
if (diff_x ==0 && (diff_y ==1 ||diff_y==-(grid_size-1))){ // neighbour is below the focal site
neighbours_of_pair[0].x = site.x, neighbours_of_pair[0].y = (site.y+1)%grid_size;
neighbours_of_pair[1].x = neighbour.x, neighbours_of_pair[1].y = (neighbour.y-1)%grid_size;
neighbours_of_pair[2].x = (site.x+1)%grid_size, neighbours_of_pair[2].y = site.y;
neighbours_of_pair[3].x = (site.x-1)%grid_size, neighbours_of_pair[3].y = site.y;
neighbours_of_pair[4].x = (neighbour.x+1)%grid_size, neighbours_of_pair[4].y = neighbour.y;
neighbours_of_pair[5].x = (neighbour.x-1)%grid_size, neighbours_of_pair[5].y = neighbour.y;
}
if (diff_x ==0 && (diff_y ==-1 ||diff_y==(grid_size-1))){ // neighbour is above the focal site
neighbours_of_pair[0].x = site.x, neighbours_of_pair[0].y = (site.y-1)%grid_size;
neighbours_of_pair[1].x = neighbour.x, neighbours_of_pair[1].y = (neighbour.y+1)%grid_size;
neighbours_of_pair[2].x = (site.x+1)%grid_size, neighbours_of_pair[2].y = site.y;
neighbours_of_pair[3].x = (site.x-1)%grid_size, neighbours_of_pair[3].y = site.y;
neighbours_of_pair[4].x = (neighbour.x+1)%grid_size, neighbours_of_pair[4].y = neighbour.y;
neighbours_of_pair[5].x = (neighbour.x-1)%grid_size, neighbours_of_pair[5].y = neighbour.y;
}
int who = random_int(0,5);
coordinates neighbour_of_pair = neighbours_of_pair[who];
if (neighbour_of_pair.x < 0){
neighbour_of_pair.x = grid_size-1; //correction if selected site is the left of first column
}
if (neighbour_of_pair.y < 0){
neighbour_of_pair.y = grid_size-1; //correction if selected site is the top of first row
}
return neighbour_of_pair;
}
void np_update(int frame[], int grid_size, float birth_probability){
// performs single asynchronous update for P at a randomly selected site on the lattice
int x = random_int(0, grid_size-1);
int y = random_int(0, grid_size-1);
double chance = random_real(0, 1);
if (frame[x*grid_size+y]==0){ // selected site is occupied
if (chance < birth_probability){
frame[x*grid_size+y]=1; // birth at empty focal site with probability p
}
}
else {
if (chance < 1-birth_probability){
frame[x*grid_size+y]=0; // death at occupied focal site with probability (1-p)
}
}
}
void dp_update(int frame[], int grid_size, float birth_probability){
// performs single asynchronous update for DP at a randomly selected site on the lattice
int x = random_int(0, grid_size-1);
int y = random_int(0, grid_size-1);
coordinates site;
site.x = x;
site.y = y;
if (frame[x*grid_size+y]==1){ // selected site is occupied
coordinates neighbour = select_neighbor_of_site(site,grid_size);
double chance = random_real(0, 1);
if (chance<birth_probability){
frame[neighbour.x*grid_size+neighbour.y] = 1; //birth at neighbour of occupied focal site with probability p
}
else {
frame[x*grid_size+y]=0; //death at focal site with probability (1-p_)
}
}
}
void tp_update(int frame[], int grid_size, float birth_probability, float feedback_strength){
// performs single asynchronous update for TP at a randomly selected site on the lattice
int x = random_int(0, grid_size-1);
int y = random_int(0, grid_size-1);
coordinates site;
site.x = x;
site.y = y;
if (frame[x*grid_size+y]==1){ // selected site is occupied
coordinates neighbour = select_neighbor_of_site(site,grid_size);
if (frame[neighbour.x*grid_size+neighbour.y]==0) { // neighbour of focal site is empty. DP like updates in this case
double chance = random_real(0, 1);
if (chance < birth_probability){
frame[neighbour.x*grid_size+neighbour.y] = 1; //birth at neighbour of occupied focal site with probability p
}
else {
frame[x*grid_size+y]=0; //death at focal site with probability (1-p_)
}
}
else { // neighbour of focal site is occupied. Facilitation taken into account
double chance = random_real(0, 1);
double another_chance = random_real(0, 1);
if (chance < feedback_strength){
coordinates neighbour_of_pair = select_neighbor_of_pair(site,neighbour,grid_size);
frame[neighbour_of_pair.x*grid_size+neighbour_of_pair.y] = 1; // birth at neighbour of pair with enhanced probability q
}
else if (another_chance < 1-birth_probability){
frame[x*grid_size+y]=0; // death at focal site with diminished death probability (1-q)(1-p)
}
}
}
}
void simulate_np(int frame[], int grid_size, float birth_probability, int updates_per_site){
// Takes a frame and simulates P for the specified number of updates per site with the specified birth probability
while (updates_per_site > 0) {
for (int i = 0; i < grid_size*grid_size; i++){ // loop performs on average a single update per site
np_update(frame, grid_size, birth_probability);
}
updates_per_site -= 1;
}
}
void simulate_dp(int frame[], int grid_size, float birth_probability, int updates_per_site){
// Takes a frame and simulates DP for the specified number of updates per site with the specified birth probability
while (updates_per_site > 0) {
for (int i = 0; i < grid_size*grid_size; i++){ // loop performs on average a single update per site
dp_update(frame, grid_size, birth_probability);
}
updates_per_site -= 1;
}
}
void simulate_tp(int frame[], int grid_size, float birth_probability, float feedback_strength, int updates_per_site){
// Takes a frame and simulates TP for the specified number of updates per site with the specified birth probability
while (updates_per_site > 0) {
for (int i = 0; i < grid_size*grid_size; i++){ // loop performs on average a single update per site
tp_update(frame, grid_size, birth_probability, feedback_strength);
}
updates_per_site -= 1;
}
}
float equilibrium_density_dp(int grid_size, float birth_probability, int number_of_census, int lag, int updates_per_site, int collect_frames){
// Simulates DP with specified parameters and prints the mean and standard deviation of vegetation cover to the terminal. The frames from
// which vegetation cover is calculated can also be captured. Finally it returns the mean vegetation cover.
float densities[number_of_census];
int frame[grid_size*grid_size];
random_frame(frame, grid_size);
simulate_dp(frame,grid_size,birth_probability,updates_per_site);
for (int i=0; i<number_of_census; i++) {
simulate_dp(frame,grid_size,birth_probability,lag);
densities[i] = calculate_density(frame,grid_size);
if (collect_frames ==1){ // conditional for collecting frames
ofstream outdata;
stringstream p, census, Lag;
p << setprecision(3) << birth_probability;
census << i;
Lag << lag;
outdata.open("dump/dp_frame_"+std::to_string(grid_size)+"_"+p.str()+"_"+Lag.str()+'_'+census.str()+".txt");
if( !outdata ) {
cerr << "File error, try again." << endl;
exit(1);
}
for (int i = 0; i < grid_size; ++i) {
for (int j = 0; j < grid_size; ++j) {
outdata << frame[i*grid_size + j];
}
outdata << '\n';
}
outdata.close();
}
}
float mean_density = mean_of_array(densities,number_of_census);
float standard_deviation_density = standard_deviation_of_array(densities,number_of_census);
cout << endl;
cout << "p: " << setprecision(4) << birth_probability << " Mean: " << setprecision(2) << mean_density << " Standard Deviation: " << setprecision(4) << standard_deviation_density << endl;
return mean_density;
}
float equilibrium_density_tp(int grid_size, float birth_probability, float feedback_strength, int number_of_census, int lag, int updates_per_site, int collect_frames){
// Simulates TP with specified parameters and prints the mean and standard deviation of vegetation cover to the terminal. The frames from
// which vegetation cover is calculated can also be captured. Finally it returns the mean vegetation cover.
float densities[number_of_census];
int frame[grid_size*grid_size];
random_frame(frame, grid_size);
simulate_tp(frame,grid_size,birth_probability,feedback_strength, updates_per_site);
for (int i=0; i<number_of_census; i++) {
simulate_tp(frame, grid_size, birth_probability, feedback_strength, lag);
densities[i] = calculate_density(frame,grid_size);
if (collect_frames ==1){
ofstream outdata;
stringstream p, q, census, Lag;
p << setprecision(3) << birth_probability;
q << setprecision(2) << feedback_strength;
census << i;
Lag << lag;
outdata.open("dump/tp_frame_"+std::to_string(grid_size)+"_"+q.str()+'_'+p.str()+"_"+Lag.str()+"_"+census.str()+".txt");
if( !outdata ) {
cerr << "File error, try again." << endl;
exit(1);
}
for (int i = 0; i < grid_size; ++i) {
for (int j = 0; j < grid_size; ++j) {
outdata << frame[i*grid_size + j];
}
outdata << '\n';
}
outdata.close();
}
}
float mean_density = mean_of_array(densities,number_of_census);
float standard_deviation_density = standard_deviation_of_array(densities,number_of_census);
cout << endl;
cout << "p: " << setprecision(4) << birth_probability << " q: " << feedback_strength <<" Mean: " << setprecision(2) << mean_density << " Standard Deviation: " << setprecision(2) << standard_deviation_density << endl;
return mean_density;
}
// -----------------------------------Cluster Statics -----------------------------------------//
vector<int> spanning_cluster_label(int frame[], int grid_size){
// Takes a frame, labels it, checks if a spanning cluster is present and returns its label.
vector<int> up; // empty vector to store upper border
vector<int> down; // empty vector to store lower border
vector <int> left; // empty vector to store left border
vector <int> right; // empty vector to store right border
int labels[grid_size*grid_size] = {0}; // initialize all sites of label lattice to 0
vector<int> spanning_cluster_label;
vector<cluster> clusters; // See cluster_dynamics.h for the data structure cluster. It has two attributes: label and coords.
find_clusters_free_boundary(frame, labels, clusters, grid_size);
// Segregates clusters, populates labels lattice and accumulates clusters with free boundary conditions
for (int i = 0; i<grid_size; i++){ // loop to populate up, down, left and right.
if (labels[i] != 0){
up.push_back(labels[i]);
}
if (labels[grid_size*(grid_size-1)+i] != 0){
down.push_back(labels[grid_size*(grid_size-1)+i]);
}
if (labels[grid_size*i] != 0){
left.push_back(labels[grid_size*i]);
}
if (labels[grid_size*(i+1)-1] != 0){
right.push_back(labels[grid_size*(i+1)-1]);
}
}
if (is_spanning_horizontal(frame,grid_size)){ // conditional to check if the frame has a cluster that spans the lattice horizontally
spanning_cluster_label = common_elements(left, right); // label of the horizontally spanning cluster which must be present in both left and right
}
else if (is_spanning_vertical(frame,grid_size)){ // conditional to check if the frame has a cluster that spans the lattice vertically
spanning_cluster_label = common_elements(up, down); // label of the vertically spanning cluster which must be present in both up and down
}
else{ // the frame does not have a spanning cluster
spanning_cluster_label.push_back(-1); // Unique identification of absence of spanning cluster since label must be non-negative integer
}
return spanning_cluster_label;
}
void find_clusters_without_spanning(int frame[], int labels[],vector<cluster>& clusters, int grid_size){
// Accumulates all the finite clusters from the frame
int id = 1;
vector <int> spanning_label = spanning_cluster_label(frame, grid_size); // find the label of spanning cluster if present
for(int i=0; i<grid_size;i++){
for (int j=0; j<grid_size; j++){ //traverse every site on the lattice once
coordinates site;
site.x = i;
site.y = j;
if((frame[i*grid_size+j]==1) && labels[i*grid_size+j]==0){ // if the site is occupied but unlabelled.
std::vector<int> sites; //to accumulate all sites that are part of the cluster to which the focal site belongs
depth_first_search_free_boundary(site,sites,frame,labels,id++,grid_size); //recursive depth first search to find the cluster's sites
cluster this_cluster; // declaring a cluster structure
this_cluster.label = labels[i*grid_size+j]; // storing the label of the cluster
this_cluster.coords = sites; // storing the coordinates of the cluster
if (this_cluster.label != spanning_label[0]){ // accumulate finite clusters only
clusters.push_back(this_cluster);
}
}
}
}
}
void find_patch_sizes_dp(vector<int>& cluster_sizes,int grid_size, float birth_probability, int number_of_census, int lag, int updates_per_site, int collect_frames){
// Accumulates the cluster sizes from the specified number of frames with the specified parameters
int frame[grid_size*grid_size];
random_frame(frame, grid_size);
simulate_dp(frame,grid_size,birth_probability,updates_per_site);
for (int i=0; i<number_of_census; i++) {
simulate_dp(frame,grid_size,birth_probability,lag);
int labels[grid_size*grid_size] = {0}; // initialize all sites of label lattice to 0
vector<cluster> clusters;
find_clusters_without_spanning(frame, labels, clusters, grid_size); //accumulate all finite clusters from the current frame
for (int i=0; i<clusters.size(); i++){
cluster_sizes.push_back(clusters[i].coords.size()); // append the clusters from the current frame to the main cluster sizes vector
}
if (collect_frames ==1){ // conditional to collect frames
ofstream outdata;
stringstream p, census, Lag;
p << setprecision(3) << birth_probability;
census << i;
Lag << lag;
outdata.open("dump/dp_frame_"+std::to_string(grid_size)+"_"+p.str()+"_"+Lag.str()+'_'+census.str()+".txt");
if( !outdata ) {
cerr << "File error, try again." << endl;
exit(1);
}
for (int i = 0; i < grid_size; ++i) {
for (int j = 0; j < grid_size; ++j) {
outdata << frame[i*grid_size + j];
}
outdata << '\n';
}
outdata.close();
}
}
}
void find_patch_sizes_np(vector<int>& cluster_sizes,int grid_size, float birth_probability, int number_of_census, int lag, int updates_per_site, int collect_frames){
// Accumulates the cluster sizes from the specified number of frames with the specified parameters
int frame[grid_size*grid_size];
random_frame(frame, grid_size);
simulate_np(frame,grid_size,birth_probability,updates_per_site);
for (int i=0; i<number_of_census; i++) {
simulate_np(frame,grid_size,birth_probability,lag);
int labels[grid_size*grid_size]; // initialize all sites of label lattice to 0
for (int i=0; i<grid_size; i++){
for (int j=0; j<grid_size; j++){
labels[grid_size*i+j] = 0;
}
}
vector<cluster> clusters;
find_clusters_without_spanning(frame, labels, clusters, grid_size); //accumulate all finite clusters from the current frame
for (int i=0; i<clusters.size(); i++){
cluster_sizes.push_back(clusters[i].coords.size()); // append the clusters from the current frame to the main cluster sizes vector
}
if (collect_frames ==1){ // conditional to collect frames
ofstream outdata;
stringstream p, census, Lag;
p << setprecision(3) << birth_probability;
census << i;
Lag << lag;
outdata.open("dump/np_frame_"+std::to_string(grid_size)+"_"+p.str()+"_"+Lag.str()+'_'+census.str()+".txt");
if( !outdata ) {
cerr << "File error, try again." << endl;
exit(1);
}
for (int i = 0; i < grid_size; ++i) {
for (int j = 0; j < grid_size; ++j) {
outdata << frame[i*grid_size + j];
}
outdata << '\n';
}
outdata.close();
}
}
}
//------------------------------------Cluster Dynamics----------------------------------------//
void find_neighbours_of_site(coordinates neighbours[4], coordinates site, int grid_size){
// returns all the four neighbours in the von Newmann neighbourhood of the focal site as an array of coordinates. See cluster_dynamics.h for the structure coordinates
int x = site.x;
int y = site.y;
neighbours[0].x = (x-1)%grid_size, neighbours[0].y = y; // left neighbour
neighbours[1].x = (x+1)%grid_size, neighbours[1].y = y; // right neighbour
neighbours[2].x = x, neighbours[2].y = (y-1)%grid_size; // bottom neighbour
neighbours[3].x = x, neighbours[3].y = (y+1)%grid_size; // top neighbour
for(int i=0; i<4; i++){
if (neighbours[i].x < 0){
neighbours[i].x = grid_size-1; //correction if selected site is the left of first column
}
if (neighbours[i].y < 0){
neighbours[i].y = grid_size-1; //correction if selected site is the top of first row
}
}
}
void depth_first_search(coordinates site, vector<int>& sites, int frame[], int labels[], int id, int grid_size){
//Source: https://stackoverflow.com/questions/22051069/how-do-i-find-the-connected-components-in-a-binary-image
//Credits: https://stackoverflow.com/users/2185825/shole
//Used with modification
// Recursively labels a cluster and accumulates its sites
labels[grid_size*site.x+site.y] = id; // Label the focal site on the labels lattice
sites.push_back(grid_size*site.x+site.y); // Add the focal site to the sites vector
coordinates neighbours[4];
find_neighbours_of_site(neighbours, site, grid_size); // find the neighbours of the focal site with periodic boundary conditions
for(int i=0; i<4;i++){ // iterate through the neighbours of the focal site
if((frame[grid_size*neighbours[i].x + neighbours[i].y]==1) && (labels[grid_size*neighbours[i].x+neighbours[i].y]==0)){
//conditional entered if the neighbour is occupied but unlaballed
depth_first_search(neighbours[i],sites,frame,labels,id,grid_size);
// recursively call depth first search so that the neighbour becomes the focal site
}
}
}
void find_clusters(int frame[], int labels[],vector<cluster>& clusters, int grid_size){
// Find all the clusters (labels and coordinates) in the frame
int id = 1;
for(int i=0; i<grid_size;i++){
for (int j=0; j<grid_size; j++){ //traverse the lattice
coordinates site;
site.x = i;
site.y = j;
if((frame[i*grid_size+j]==1) && labels[i*grid_size+j]==0){ // if the site is occupied but unlabelled
std::vector<int> sites;
depth_first_search(site,sites,frame,labels,id++,grid_size); //label the cluster to which the current site belongs and accumulate its coordinates
cluster this_cluster;
this_cluster.label = labels[i*grid_size+j]; // label of the cluster to which the current site belongs
this_cluster.coords = sites; // coordinates of the cluster to which the current site belongs
clusters.push_back(this_cluster);
}
}
}
}
int check_presence(std::vector<int> vec,int element){
// Returns 1 if the element is present, 0 otherwise
std::vector<int>::iterator it = std::find(vec.begin(), vec.end(), element);
if (it != vec.end()){
return 1;
}
else {
return 0;
}
}
void find_transformations_single_shot(vector<transformation>& transformations,
int previous_frame[], int previous_frame_labels[],vector<cluster>& previous_frame_clusters,
int current_frame[], int current_frame_labels[], vector<cluster>& current_frame_clusters, int grid_size){
// takes two consecutive frames with the difference of a single update and finds the size of the cluster before and after the update.
// The change in size is the difference of these two cluster sizes.
int diff[grid_size*grid_size];
std::vector<int> changes;
for (int i=0; i<grid_size*grid_size; i++){ // scan the lattice to find the change
diff[i] = current_frame[i] - previous_frame[i];
if (diff[i] != 0){
changes.push_back(i); // collect the site at which the change has occured
}
}
if (changes.size()==0 || changes.size() >1){ // exit function if no change or more than one change has occured
return;
}
else{
std::vector<int> finished_labels_current_frame;
std::vector<int> finished_labels_previous_frame;
if (diff[changes[0]]>0){ // the change was a birth
// it may have: a) created a cluster of size 1 b) caused a cluster of size n to become a cluster of size n+1 c) caused two or clusters to merge
if (!check_presence(finished_labels_current_frame,current_frame_labels[changes[0]])){
// conditional is entered if the label of the site which appeared in the current frame is not present in finished labels of the current frame
finished_labels_current_frame.push_back(current_frame_labels[changes[0]]); // add the label to finished labels of current frame
cluster focal_cluster = current_frame_clusters[current_frame_labels[changes[0]]-1]; // get the cluster to which the newly appeared site belongs
std::vector<int> comparison_clusters;
std::vector<int> finished_labels_comparison_clusters;
for (int j=0; j<focal_cluster.coords.size(); j++){ // loop through the sites of the focal cluster
if ((previous_frame_labels[focal_cluster.coords[j]] != 0)&&
(!check_presence(finished_labels_comparison_clusters,previous_frame_labels[focal_cluster.coords[j]]))){
// conditional is entered if the label of the cluster in the previous frame at the site
// corresponding to the current site of the focal cluster (from the current frame)
// is absent in finished_labels_comparison_clusters
finished_labels_comparison_clusters.push_back(previous_frame_labels[focal_cluster.coords[j]]);
//add the label from the previous frame to finished_labels_comparison_clusters
comparison_clusters.push_back(previous_frame_clusters[previous_frame_labels[focal_cluster.coords[j]]-1].coords.size());
// add the cluster from the previous frame to comparison_clusters
}
}
transformation transformation_merge; // See cluster_dynamics.h for the definition of the transformation structure
if (comparison_clusters.size() == 0){ //This means the a cluster of size 1 has appeared.
transformation_merge.before = 0;
transformation_merge.after = focal_cluster.coords.size();
transformations.push_back(transformation_merge);
}
else { // This means that either a cluster has grown by size 1 or two or more clusters have merged.
// If two or more clusters have merged we only consider the largest of the comparison clusters from the previous frame
// as the cluster which has transformed to the single cluster in the current frame
transformation_merge.before = *max_element(comparison_clusters.begin(), comparison_clusters.end()); //finds the largest among the comparison clusters
transformation_merge.after = focal_cluster.coords.size();
transformations.push_back(transformation_merge);
}
}
}
else { // the change was a death
// it may have: a) removed a cluster of size 1 b) caused a cluster of size n to become a cluster of size n-1 c) caused two or clusters to split
if (!check_presence(finished_labels_previous_frame,previous_frame_labels[changes[0]])){
// conditional is entered if the label of the site which disappeared in the current frame is not present in finished labels of the previous frame
finished_labels_previous_frame.push_back(previous_frame_labels[changes[0]]); // add the label to finished labels of previous frame
cluster focal_cluster = previous_frame_clusters[previous_frame_labels[changes[0]]-1]; // get the cluster in the previous frame from which a site has disappeared
std::vector<int> comparison_clusters;
std::vector<int> finished_labels_comparison_clusters;
for (int j=0; j<focal_cluster.coords.size(); j++){ // loop through the sites of the focal cluster
if ((current_frame_labels[focal_cluster.coords[j]] != 0)&&
(!check_presence(finished_labels_comparison_clusters,current_frame_labels[focal_cluster.coords[j]]))){
// conditional is entered if the label of the cluster in the current frame at the site
// corresponding to the current site of the focal cluster (from the previous frame)
// is absent in finished_labels_comparison_clusters
finished_labels_comparison_clusters.push_back(current_frame_labels[focal_cluster.coords[j]]);
//add the label from the current frame to finished_labels_comparison_clusters
comparison_clusters.push_back(current_frame_clusters[current_frame_labels[focal_cluster.coords[j]]-1].coords.size());
// add the cluster from the current frame to comparison_clusters
}
}
transformation transformation_primary_split; // See cluster_dynamics.h for the definition of the transformation structure
if (comparison_clusters.size() == 0){ //This means the a cluster of size 1 has disappeared.
transformation_primary_split.before = focal_cluster.coords.size();
transformation_primary_split.after = 0;
transformations.push_back(transformation_primary_split);
}
else { // This means that either a cluster has shrunk by size 1 or a cluster has split into two or more clusters
// If a cluster has split into two or more clusters we only consider the largest of the comparison clusters
//from the curernt frame as the cluster to which the single cluster from the previous frame has transformed.
transformation_primary_split.before = focal_cluster.coords.size();
transformation_primary_split.after = *max_element(comparison_clusters.begin(), comparison_clusters.end()); //finds the largest among the comparison clusters
transformations.push_back(transformation_primary_split);
}
}
}
}
}
void find_equilibrium_single_shot_transformations_np(int grid_size, float birth_probability, int time_to_equilibrium,
int how_many, vector<transformation>& transformations){
// Simulates P for the specified parameters and collects the specified number of transformations from the steady state
int seed = std::random_device{}();
rng.seed(seed);
int previous_frame[grid_size*grid_size];
int previous_frame_labels[grid_size*grid_size];
vector<cluster> previous_frame_clusters;
int current_frame[grid_size*grid_size];
int current_frame_labels[grid_size*grid_size];
vector<cluster> current_frame_clusters;
random_frame(current_frame, grid_size); // initialize the current frame
zeros(current_frame_labels,grid_size); // initialize labels for the current frame
simulate_np(current_frame, grid_size, birth_probability, time_to_equilibrium); // simulate P to reach steady state
auto start = high_resolution_clock::now();
find_clusters(current_frame,current_frame_labels,current_frame_clusters,grid_size); // find clusters from the current frame
while (transformations.size() < how_many){ // loop till we have the specified number of transformations
for (int i=0; i<grid_size; i++){
for (int j=0; j<grid_size; j++){ // scan the current frame and duplicate it into the previous frame
previous_frame[grid_size*i+j] = current_frame[grid_size*i+j];
previous_frame_labels[grid_size*i+j] = current_frame_labels[grid_size*i+j];
}
}
previous_frame_clusters = current_frame_clusters; // duplicate the clusters too
np_update(current_frame, grid_size, birth_probability); // make a single update to the current frame
current_frame_clusters.clear(); // wash the stale clusters of the current frame (since it has been updated now)
zeros(current_frame_labels,grid_size); // wash the labels too