-
Notifications
You must be signed in to change notification settings - Fork 0
/
functionsALUMSS.cpp
1960 lines (1682 loc) · 67.8 KB
/
functionsALUMSS.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
/*
Implementation of all the functions required for the simulation and used in the
main program.
*/
#include "functionsALUMSS.h"
#include <boost/config.hpp>
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <numeric>
#include <utility>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/connected_components.hpp>
#include <math.h>
#include <stdio.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
using namespace std;
/*
1-Helper functions
2-Calculation of Ecosystem Service provision
3-Calculation of events' propensities
4-Initialization functions
5-ODEs and solver
*/
///////////////////////////////////////////////////////////////////////////////
// 1- Helper functions:
// - getNeighbourMatrix
// - getNeighbours
// - getNeighboursState
///////////////////////////////////////////////////////////////////////////////
void getNeighbourMatrix(vector<vector<unsigned int>> &neighbourMatrix, unsigned int nSide, double d)
{
/*fills a vector containing the neighbours indexes for each patch*/
unsigned int ix,jx,xi,yi,xj,yj,dx,dy,manhattanDist;
neighbourMatrix.clear();
neighbourMatrix.resize(nSide*nSide);
for (ix=0; ix<neighbourMatrix.size(); ++ix){
xi = (unsigned int)(ix%nSide);
yi = (unsigned int)(ix/nSide);
for (xj=0; xj<nSide; xj++){
dx=(unsigned int)abs((int)(xi-xj));
// calculating cyclic distances to account for periodic borders
if (dx>nSide/2){
dx=nSide-dx;
}
for (yj=0; yj<nSide; yj++){
dy=(unsigned int)abs((int)(yi-yj));
// calculating cyclic distances to account for periodic borders
if (dy>nSide/2){
dy=nSide-dy;
}
manhattanDist = dx+dy;
if (manhattanDist<=d and manhattanDist>0){
jx = xj + yj*nSide;
neighbourMatrix[ix].push_back(jx);
}
}
}
}
return;
}
void getNeighbours(vector<unsigned int> &neighboursList, const vector<vector<unsigned int>> &neighbourMatrix, unsigned int i)
{
neighboursList = neighbourMatrix[i];
return;
}
void getNeighboursState(vector<unsigned int> &neighboursState, const vector<vector<unsigned int>> &neighbourMatrix, const vector<unsigned int> &landscape, unsigned int i, unsigned int state)
{
/*
fills the vector neighboursState so that it contains the indexes of all the
closest neighbours of i in a given state. the landscape is passed as a constant
reference so that the vector cannot be modified by the function in main
*/
/*
getting the neighbours indexes in neighbour_list vector
*/
vector<unsigned int> neighboursList;
getNeighbours(neighboursList,neighbourMatrix,i);
/*
getting the index of neighbours in the wanted state
*/
unsigned long ix;
for (ix=0 ; ix<neighboursList.size() ; ++ix){
if (landscape[neighboursList[ix]] == state) {
neighboursState.push_back( neighboursList[ix] );
}
}
return;
}
void getNeighboursStateInf(vector<unsigned int> &neighboursState, const vector<vector<unsigned int>> &neighbourMatrix, const vector<unsigned int> &landscape, unsigned int i, unsigned int maxState)
{
/*
fills the vector neighboursState so that it contains the indexes of all the
closest neighbours of i in a state smaller than maxState.
the landscape is passed as a constant reference so that the vector cannot be
modified by the function in main
*/
/*
getting the neighbours indexes in neighbour_list vector
*/
vector<unsigned int> neighboursList;
getNeighbours(neighboursList,neighbourMatrix,i);
/*
getting the index of neighbours in the wanted state
*/
unsigned long ix;
for (ix=0 ; ix<neighboursList.size() ; ++ix){
if (landscape[neighboursList[ix]] < maxState) {
neighboursState.push_back( neighboursList[ix] );
}
}
return;
}
void getNeighboursStateSup(vector<unsigned int> &neighboursState, const vector<vector<unsigned int>> &neighbourMatrix, const vector<unsigned int> &landscape, unsigned int i, unsigned int minState)
{
/*
fills the vector neighboursState so that it contains the indexes of all the
closest neighbours of i in a state larger than minState.
the landscape is passed as a constant reference so that the vector cannot be
modified by the function in main
*/
/*
getting the neighbours indexes in neighbour_list vector
*/
vector<unsigned int> neighboursList;
getNeighbours(neighboursList,neighbourMatrix,i);
/*
getting the index of neighbours in the wanted state
*/
unsigned long ix;
for (ix=0 ; ix<neighboursList.size() ; ++ix){
if (landscape[neighboursList[ix]] > minState) {
neighboursState.push_back( neighboursList[ix] );
}
}
return;
}
////////////////////////////////////////////////////////////////////////////////
// 2- Calculation of Ecosystem Service provision:
// - getNaturalConnectedComponents
// - updateNCCadding
// - updateNCCremoving
// - getEcosystemServiceProvision
////////////////////////////////////////////////////////////////////////////////
void getNaturalConnectedComponents(vector<vector<int>> &naturalComponents, const vector<unsigned int> &landscape, double distanceConnection)
{
/*
fills a vector where each member is a vector containing the indexes of all the
natural patches belonging to the same cluster
*/
vector<unsigned int> naturalPatches;
unsigned int manhattanDist;
unsigned int i, j;
int xi, xj, yi, yj;
unsigned int dx, dy;
unsigned int n = (unsigned int) sqrt(landscape.size());
// clearing natural components vector for refilling
naturalComponents.clear();
/*
get the list of natural patches in the landscape
*/
for(i=0 ; i<landscape.size() ; ++i){
if (landscape[i]==0){
naturalPatches.push_back(i);
}
}
/*
create an undirected graph with the set of natural patches to calculate
the connected components. to estimate whether two patches are connected
we calculate the manhattan distance between them
*/
using namespace boost;
{
typedef adjacency_list< vecS, vecS, undirectedS > Graph;
Graph G;
for(i=0 ; i<naturalPatches.size() ; ++i){
add_edge(i,i,G);
// converting 1-D coordinates to 2-D
xi=naturalPatches[i]%n;
yi=(int)naturalPatches[i]/n;
for(j=0 ; j<i ; ++j){
// converting 1-D coordinates to 2-D
xj=naturalPatches[j]%n;
yj=(int)naturalPatches[j]/n;
// calculating manhattan distance between points
dx=abs(xi-xj);
dy=abs(yi-yj);
// calculating cyclic distances to account for periodic borders
if (dx>n/2){
dx=n-dx;
}
if (dy>n/2){
dy=n-dy;
}
//
manhattanDist=dx+dy;
if ( manhattanDist<distanceConnection ){
add_edge(i, j, G);
}
}
}
/*
initializing the vector containing the components and calculating components
*/
vector<int> component(num_vertices(G));
int num = connected_components(G, &component[0]);
/*
converting the nodes indexes into actual landscape coordinates
*/
naturalComponents.resize(num);
for (i=0 ; i<naturalComponents.size() ; ++i){
for (j=0; j<component.size(); j++){
if(component[j]==(int)i){
naturalComponents[i].push_back(naturalPatches[j]);
}
}
}
}
return;
}
void updateNCCadding(vector<vector<int>> &naturalComponents, const vector<vector<unsigned int>> &neighbourMatrix, const vector<unsigned int> &landscape, unsigned int i)
{
/*
note: updateNCCadding with non-local neighbourhood doesnt pose a problem as
long as there is a neighbourMatrix for natural cells that accounts for the
non-locality
*/
vector<unsigned int> neighboursNatural;
getNeighboursState(neighboursNatural,neighbourMatrix,landscape,i,0); // state 0 is natural
vector<int> newNaturalComponent, newNaturalComponent2;
newNaturalComponent.push_back(i);
if(neighboursNatural.size()==0){ //no natural neighbour: simplest case, just create a new component
naturalComponents.push_back(newNaturalComponent); // add it to the list
}
else{
vector<unsigned int>::iterator it1;
vector<vector<int>>::iterator it2;
vector<int>::iterator it3;
vector<vector<vector<int>>::iterator> toErase;
/*
first traversing the natural components and then the neighbours guarantees that
pointers to components are located in a sorted way. this is key to ensure
that the erasing process doesn't mess up with the memory.
*/
unsigned int neighboursFound = 0;
for(it2=naturalComponents.begin();it2!=naturalComponents.end();it2++){ // traverse all the components
for(it1=neighboursNatural.begin();it1!=neighboursNatural.end();it1++){ // traverse all the natural neigbhours of new natural cell
if( find( it2->begin(), it2->end(), *it1) != it2->end() ){ // found a neighbour in this component
neighboursFound+=1; // store the amount of natural neighbours found to stop search once all are
if ( find( toErase.begin(), toErase.end(), it2 ) == toErase.end() ){ // if the currently considered component hasn't been aded in the erase/merging list, then add it
toErase.push_back(it2);
}
}
}
if(neighboursFound==neighboursNatural.size()){ // end the search if all neighbours were located
break;
}
}
// if there is a single component in toErase just add i to that component, no need of merging
if (toErase.size()>0 && toErase.size()<2){
toErase[0]->push_back(i);
}
else if(toErase.size()>1){ // if there are more, erase them and push back the merged ones
// erasing components that are going to be merged
unsigned int ix;
for(ix=0;ix<toErase.size();ix++){
for(it3=toErase[ix]->begin();it3!=toErase[ix]->end();it3++){
newNaturalComponent.push_back(*it3);
}
}
/*now erase the components: traverse erase vector backwards to be sure of
addressing the correct bits of memory erasing first the furthest pointers*/
for(ix=toErase.size();ix>=1;--ix){
naturalComponents.erase(toErase[ix-1]);
}
/*now add the new natural component*/
naturalComponents.push_back(newNaturalComponent);
}
else{ // toErase is empty, in which case there is an error in the code
cout << "Error: toErase size is " << toErase.size() << " but toErase cannot be empty\n";
}
}
return;
}
void updateNCCremoving(vector<vector<int>> &naturalComponents, const vector<unsigned int> &landscape, int l, double distanceConnection)
{
/*
note: updateNCCremoving with non-local natural neighbourhoods requires only
having a parameter for the connection distance
*/
unsigned int n = (unsigned int) sqrt(landscape.size());
// find cluster of cell l
// these iterators are to traverse the naturalComponents
vector<vector<int>>::iterator it1;
vector<int>::iterator it2;
// iterating over natural components and checking to which natural component
// belonged the natural cell that needs to be removed.
//this iterator is to store the component to which the removed cell belonged
vector<vector<int>>::iterator itComp;
// iterate over components
for(it1=naturalComponents.begin();it1!=naturalComponents.end();it1++){
// find whether natural cell l is in this natural component
it2=find(it1->begin(), it1->end(),l);
// if it is then erase natural cell l and store the component
if(it2!=it1->end()){
it1->erase(it2);
itComp =it1;
break;
}
}
// get all the natural cells of the component where the removed cell belonged
// we need to know if the removal of the cell caused the fragmentation of the
// component in several pieces
vector<unsigned int> naturalPatches;
for (it2=itComp->begin();it2!=itComp->end();it2++){
naturalPatches.push_back(*it2);
}
// erase concerned cluster from naturalComponents, we will calculate the new
// component(s) and push them back. worst case scenario the component was not
// fragmentedand the following operation was useless computing time
naturalComponents.erase(itComp);
//get connected components from the naturalPatches
unsigned int manhattanDist;
unsigned int i, j;
int xi, xj, yi, yj;
unsigned int dx, dy;
/*
create an undirected graph with the set of natural patches to calculate
the connected components. to estimate whether two patches are connected
we calculate the manhattan distance between them, this uses the same method
than getNaturalConnectedComponents
*/
using namespace boost;
{
typedef adjacency_list< vecS, vecS, undirectedS > Graph;
Graph G;
for(i=0 ; i<naturalPatches.size() ; ++i){
add_edge(i,i,G);
// converting 1-D coordinates to 2-D
xi=naturalPatches[i]%n;
yi=(int)naturalPatches[i]/n;
for(j=0 ; j<i ; ++j){
// converting 1-D coordinates to 2-D
xj=naturalPatches[j]%n;
yj=(int)naturalPatches[j]/n;
// calculating manhattan distance between points
dx=abs(xi-xj);
dy=abs(yi-yj);
// calculating cyclic distances to account for periodic borders
if (dx>n/2){
dx=n-dx;
}
if (dy>n/2){
dy=n-dy;
}
//
manhattanDist=dx+dy;
if ( manhattanDist<2 ){
add_edge(i, j, G);
}
}
}
/*
initializing the vector containing the components and calculating components
*/
vector<int> component(num_vertices(G));
int num = connected_components(G, &component[0]);
// adding the new components to naturalComponents
vector<int> newComponent;
for(i=0; i<(unsigned int)num; i++){
for(j=0; j<component.size(); j++){
if((int)i==component[j]){
newComponent.push_back(naturalPatches[j]);
}
}
naturalComponents.push_back(newComponent);
newComponent.clear();
}
}
return;
}
void getEcosystemServiceProvision(vector<double> &ecosystemServices, const vector<vector<int>> &naturalComponents, const vector<vector<unsigned int>> &neighbourMatrix, const vector<unsigned int> &landscape, double z)
{
/*
returns the exposure to the wanted state of patch i. currently it is only used
for the exposure to nature. the exposure to nature scales with biodiversity
hence like a SAR, where the area is the total natural area in contact with
patch i
*/
double area;
double ecosystemServiceProvision;
vector<unsigned int> neighboursState;
unsigned long i,ix,jx;
unsigned int nNeighbours;
nNeighbours = neighbourMatrix[0].size();
for(i=0;i<landscape.size();i++){
ecosystemServiceProvision=0;
/*
getting the state neighbours indexes in neighboursState vector
*/
getNeighboursState(neighboursState,neighbourMatrix,landscape,i,0); // state 0 is natural
/*
calculate the area of each of the neighbour's component
*/
for (ix=0;ix<neighboursState.size();ix++){
// for each of the natural neighbours check their cluster membership
for (jx=0; jx<naturalComponents.size(); jx++){
// check if neighbour belongs to cluster jx
if (find( naturalComponents[jx].begin(),naturalComponents[jx].end(),neighboursState[ix]) != naturalComponents[jx].end()){
area=(double)naturalComponents[jx].size()/landscape.size();
ecosystemServiceProvision+=(double) pow(area,z)/nNeighbours;
break;
}
}
}
ecosystemServices[i]=ecosystemServiceProvision;
neighboursState.clear();
}
return;
}
////////////////////////////////////////////////////////////////////////////////
// 3- Calculation of events' propensities:
// - esSaturationFunction
// - getAgriculturalProduction
// - getResourceDeficit
// - getSpontaneousPropensities
// - getAgroPropensity
// - getAbandonmentPropensity
// - getPropensityVector
////////////////////////////////////////////////////////////////////////////////
void getAgriculturalProduction(vector<double> &agriculturalProduction, const vector<unsigned int> &landscape, const vector<double> &ecosystemServices, double ye)
{
/*
returns the total agricultural production for a given "landscape" and
minimum yield "y". the minimum yield is for a cropped patch with only
non natural neighbours. natural neighbours raise yield.
*/
// initialize the vector with production 0 everywhere
fill(agriculturalProduction.begin(),agriculturalProduction.end(),0.0);
unsigned int ix;
for (ix=0 ; ix<landscape.size() ; ++ix){
if(landscape[ix]==2){ // cropped patches
// putting baseline production 0.5 as a test...
agriculturalProduction[ix] = (1-ye) + ye*ecosystemServices[ix];
}
else if(landscape[ix]==3){ //intense
agriculturalProduction[ix] = 1 ;
}
}
return;
}
double getResourceDeficit(const vector<double> &agriculturalProduction, const vector<unsigned int> &population, double k0)
{
/*
Given a total production the function returns the resource deficit experienced
by the population. The resource deficit translates into demand for agricultural
expansion or intensification
*/
double totalAgriculturalProduction;
double resourceDeficit;
totalAgriculturalProduction=accumulate(agriculturalProduction.begin(),agriculturalProduction.end(),0.0,plus<double>());
if(population[0]>0){
resourceDeficit = (double) population[0]/k0 - totalAgriculturalProduction;
}
else{
resourceDeficit=0;
}
return resourceDeficit;
}
double getTotalManagementPropensity(const vector<unsigned int> &landscape, const vector<vector<unsigned int>> &farms, const vector<double> &farmSensitivity, double resourceDeficit)
{
double totalManagementPropensity=0;
unsigned int ix;
vector<unsigned int>::const_iterator it;
double maxSensitivity = 0;
if (resourceDeficit>0){
// if there is no natural land left, then there is no possible land conversion
if( find( landscape.begin(), landscape.end(), 0) != landscape.end() ){
// get the maximum sensitivity across the farms that still have room for conversion
for(ix=0;ix<farms.size();++ix){
for(it=farms[ix].begin();it!=farms[ix].end();++it){
if(landscape[*it]==0){ // i.e. there's a natural cell
if(farmSensitivity[ix]>maxSensitivity){
maxSensitivity = farmSensitivity[ix];
}
// move to the next farm
break;
}
}
}
totalManagementPropensity = resourceDeficit * maxSensitivity;
}
// else just return 0 since there cannot be any conversion
}
return totalManagementPropensity;
}
void getDemographicPropensities(vector<double> &demographicPropensities, const vector<double> &agriculturalProduction, vector<unsigned int> &population, double k0)
{
double totalAgriculturalProduction = accumulate(agriculturalProduction.begin(),agriculturalProduction.end(),0.0,plus<double>());
demographicPropensities[0] = 0;
demographicPropensities[1] = 0;
if(population[0]>0){
if (totalAgriculturalProduction > 0){
// this is to avoid a division by zero
demographicPropensities[0] = (double) population[0];
demographicPropensities[1] = (double) population[0]*population[0]/totalAgriculturalProduction/k0;
}
else{
// if there is no production just set population to zero, not the best solution but it is hard
// to do better with logistic growth
population[0]=0;
}
}
return;
}
void getSpontaneousPropensities(vector<double> &spontaneousPropensities, const vector<unsigned int> &landscape, const vector<double> &ecosystemServices, unsigned int nSide, double sR, double sD, double sFL)
{
/*
Calculate the propensities of recovery, degradation and fertility loss and store
them in a single vector in that order
*/
unsigned int ix,jx;
// initialize the spontaneous propensity with zeros
fill(spontaneousPropensities.begin(),spontaneousPropensities.end(),0.0);
// replace the non-null values
for (ix=0 ; ix<landscape.size() ; ++ix){
// first calculate the recovery propensity
if (landscape[ix]==1){
spontaneousPropensities[ix] = sR * ecosystemServices[ix];
}
//now calculate the degradation propensity
if (landscape[ix]==0){
jx = (unsigned int) (nSide*nSide + ix);
spontaneousPropensities[jx] = sD*(1-ecosystemServices[ix]);
}
// finally calculate the fertility loss propensity
if (landscape[ix]==2 || landscape[ix]==3){
jx = (unsigned int) (2*nSide*nSide + ix);
spontaneousPropensities[jx] = sFL*(1-ecosystemServices[ix]);
}
}
return;
}
void solveSSA(vector<unsigned int> &landscape, vector<vector<int>> &naturalComponents, vector<double> &ecosystemServices, vector<double> &agriculturalProduction, const vector<vector<unsigned int>> &farms, const vector<vector<unsigned int>> &neighbourMatrix, const vector<vector<unsigned int>> &neighbourMatrixES, vector<unsigned int> &population, const vector<double> &farmSensitivity, const vector<vector<double>> &farmStrategy, vector<double> &spontaneousPropensities, vector<double> &spontaneousCumulativePropensities, vector<double> &demographicPropensities, vector<double> &demographicCumulativePropensities, double totalManagementPropensity, double resourceDeficit, unsigned int nFarms, unsigned int nSide, double ye, double k0, double sR, double sD, double sFL, double z, double dES, gsl_rng *r, vector<unsigned int> &countTransitions)
{
vector<double> farmPropensity(nFarms,0);
vector<double> farmCumulativePropensity(nFarms);
vector<unsigned int> availableCells;
vector<unsigned int> agriculturalNeighbours;
vector<unsigned int> naturalNeighbours;
vector<double> conversionPropensity, conversionCumulativePropensity;
unsigned int ix,jx;
unsigned int transition,cell;
double conversionCumSum = 0;
double normFactor = 0;
vector<double>::iterator it0;
vector<unsigned int>::const_iterator it1;
vector<unsigned int>::iterator it2;
// random number to pick the transition and the cell
double xRand = gsl_rng_uniform(r)*(totalManagementPropensity + spontaneousCumulativePropensities.back() + demographicCumulativePropensities.back());
if(xRand < totalManagementPropensity){// if it is a management transition
// select the farm
ix=0;
for(ix=0;ix<farms.size();++ix){
// if there is no natural land in a farm then there is no conversion
for(it1 = farms[ix].begin(); it1!=farms[ix].end(); ++it1){
if(landscape[*it1]==0){
farmPropensity[ix]=farmSensitivity[ix];
normFactor += farmSensitivity[ix];
break;
}
}
}
for(it0=farmPropensity.begin();it0!=farmPropensity.end();++it0){
*it0 = *it0/normFactor*totalManagementPropensity;
}
partial_sum(farmPropensity.begin(),farmPropensity.end(),farmCumulativePropensity.begin());
ix=0;
while (xRand > farmCumulativePropensity[ix]){
ix++;
}
// now select the cell to transform
// iterate over the cells belonging to the selected farm
for(it1=farms[ix].begin();it1!=farms[ix].end();++it1){
// check if the cell is natural
if(landscape[*it1]==0){
// add the cell
availableCells.push_back(*it1);
}
}
// clear and resize the probability of conversion vector
conversionPropensity.resize(availableCells.size());
conversionCumulativePropensity.resize(availableCells.size());
// check the strategy of the farm
if(farmStrategy[ix][0]==0){ // if it is sharing
jx=0; // counter to fill probConversion
for (it2=availableCells.begin();it2!=availableCells.end();++it2){
// calculate the number of natural neighbours
naturalNeighbours.clear();
getNeighboursState(naturalNeighbours,neighbourMatrix,landscape,*it2,0);
conversionPropensity[jx]=pow( max(0.1 , (double)naturalNeighbours.size() ) , farmStrategy[ix][1] );
conversionCumSum += conversionPropensity[jx];
jx+=1;
}
for(jx=0;jx<conversionPropensity.size();++jx){
// creating the 0-1 weights accordign to clustering and multiplying by total farm cumulative sensitivity to get converion propensity
conversionPropensity[jx] = conversionPropensity[jx] * farmCumulativePropensity[ix] / conversionCumSum;
}
}
else{ // if there is clustering
jx=0; // counter to fill probConversion
for (it2=availableCells.begin();it2!=availableCells.end();++it2){
// calculate the number of agricultural neigbhours. In this occasion,
// lowInt and highInt are considered both with the same weighting into
// the calculation
agriculturalNeighbours.clear();
getNeighboursStateSup(agriculturalNeighbours,neighbourMatrix,landscape,*it2,1);
conversionPropensity[jx]=pow( max(0.1 , (double)agriculturalNeighbours.size() ) , farmStrategy[ix][1] );
conversionCumSum += conversionPropensity[jx];
jx+=1;
}
for(jx=0;jx<conversionPropensity.size();++jx){
// creating the 0-1 weights accordign to clustering and multiplying by total farm cumulative sensitivity to get converion propensity
conversionPropensity[jx] = conversionPropensity[jx] * farmCumulativePropensity[ix] / conversionCumSum;
}
}
jx=0;
it2=availableCells.begin();
partial_sum(conversionPropensity.begin(),conversionPropensity.end(),conversionCumulativePropensity.begin());
while (xRand > conversionCumulativePropensity[jx]){
jx++;
it2++;
}
// update the landscape according to the strategy: either natural to low-intense, or intense
if(farmStrategy[ix][0]==0){
landscape[*it2]=2;
countTransitions[4]+=1;
}
else if(farmStrategy[ix][0]==1){
landscape[*it2]=3;
countTransitions[5]+=1;
}
// update natural components
updateNCCremoving(naturalComponents,landscape,*it2,dES);
// update ecosystem service provision
getEcosystemServiceProvision(ecosystemServices,naturalComponents,neighbourMatrix,landscape,z); // update ES
// update the propensity of spontaneous transitions
getSpontaneousPropensities(spontaneousPropensities,landscape,ecosystemServices,nSide,sR,sD,sFL);
partial_sum(spontaneousPropensities.begin(),spontaneousPropensities.end(),spontaneousCumulativePropensities.begin());
// updating agricultural production after the management LUC transition
getAgriculturalProduction(agriculturalProduction, landscape, ecosystemServices, ye);
}
else if(xRand < totalManagementPropensity + spontaneousCumulativePropensities.back()){ // if it is a spontaneous transition
ix=0;
while(xRand > totalManagementPropensity + spontaneousCumulativePropensities[ix]){
ix++;
}
transition=(unsigned int) (ix/(nSide*nSide));
cell=(unsigned int) (ix%(nSide*nSide));
if (transition==0){ // land recovery
landscape[cell]=0; // update the landscape
countTransitions[0]+=1; // update the transitions' count
updateNCCadding(naturalComponents,neighbourMatrixES,landscape,cell); // update the NCC
getEcosystemServiceProvision(ecosystemServices,naturalComponents,neighbourMatrix,landscape,z); // update ES
// update the propensity of spontaneous transitions
getSpontaneousPropensities(spontaneousPropensities,landscape,ecosystemServices,nSide,sR,sD,sFL);
partial_sum(spontaneousPropensities.begin(),spontaneousPropensities.end(),spontaneousCumulativePropensities.begin());
}
else if(transition==1){ // land degradation
landscape[cell]=1;
countTransitions[1]+=1;
updateNCCremoving(naturalComponents,landscape,cell,dES);
getEcosystemServiceProvision(ecosystemServices,naturalComponents,neighbourMatrix,landscape,z);
// update the propensity of spontaneous transitions
getSpontaneousPropensities(spontaneousPropensities,landscape,ecosystemServices,nSide,sR,sD,sFL);
partial_sum(spontaneousPropensities.begin(),spontaneousPropensities.end(),spontaneousCumulativePropensities.begin());
}
else if(transition==2){ // fertility loss
if(landscape[cell]==2){ // if it was low-intense agriculture
landscape[cell] = 0;
countTransitions[2]+=1;
updateNCCadding(naturalComponents,neighbourMatrixES,landscape,cell);
getEcosystemServiceProvision(ecosystemServices,naturalComponents,neighbourMatrix,landscape,z);
// update the propensity of spontaneous transitions
getSpontaneousPropensities(spontaneousPropensities,landscape,ecosystemServices,nSide,sR,sD,sFL);
partial_sum(spontaneousPropensities.begin(),spontaneousPropensities.end(),spontaneousCumulativePropensities.begin());
}
else if(landscape[cell]==3){ // if it was high-intense agriculture
landscape[cell] = 1;
countTransitions[3]+=1;
// update the propensity of spontaneous transitions
spontaneousPropensities[ix]=0; // transition that just occurred has now null propensity
spontaneousPropensities[cell] = sR*ecosystemServices[cell]; // applying the recovery transition formula
partial_sum(spontaneousPropensities.begin(),spontaneousPropensities.end(),spontaneousCumulativePropensities.begin());
}
else{
cout << "Error: functionsALUMSS.cpp : solveSSA: fertility loss of non-agricultural cell. Land cover : "<< landscape[cell] <<"\n";
}
}
else{
cout << "Error: functionsALUMSS.cpp : solveSSA: spontaneous transition "<< transition << " does not exist.\n";
}
// updating agricultural production after the spontaneous LUC transition
getAgriculturalProduction(agriculturalProduction, landscape, ecosystemServices, ye);
}
else{
// it is a population event
if(xRand < totalManagementPropensity + spontaneousCumulativePropensities.back() + demographicCumulativePropensities[0]){
// it is a birth
population[0]+=1;
}
else{
// it is a death
population[0]-=1;
}
// demographic propensities are updated below
}
// updating demographic propensities after LUC transition or population event
getDemographicPropensities(demographicPropensities,agriculturalProduction,population,k0);
partial_sum(demographicPropensities.begin(),demographicPropensities.end(),demographicCumulativePropensities.begin());
return;
}
////////////////////////////////////////////////////////////////////////////////
// 4- Initialization functions:
// - initializeLandscape
// - initializePopulation
// - initializeSES
////////////////////////////////////////////////////////////////////////////////
void initializeVoronoiFarms( vector<vector<unsigned int>> &farms, const vector<vector<unsigned int>> &neighbourMatrix, unsigned int nSide, unsigned int nFarms, gsl_rng *r)
{
/*
This function initializes the political subdivisions representing each farm
managed by a different agent. The information is stored in vector<vector<unsigned int>> &farms
where each "line" correspond to a farm and the cells' indexes belonging to it
are stored in the columns. To create the subdivisions we do Voronoi tesselation
of the landscape. The process is as follows:
1- randomly place nFarms points with uniform probability in the landscape
2- each point is the "seed" of the voronoi cell. Perform radial growth process
from each seed until fronts of different farms collide.
*/
unsigned long ix,jx;
vector<double> voronoiSeedProbability(nSide*nSide,1.0);
vector<double> voronoiSeedCumulativeProbability;
voronoiSeedCumulativeProbability.resize(nSide*nSide);
vector<unsigned int> voronoiSeeds(nFarms);
vector<unsigned int>::iterator it;
double xRand;
// initialize shape of farms vector
farms.clear();
farms.resize(nFarms);
// iterate over the number of farms to randomly place each voronoi farm seed
// on the landscape
for(ix=0;ix<nFarms;++ix){
// calculate the cumulative sum of each cell's probability to be chosen
partial_sum(voronoiSeedProbability.begin(),voronoiSeedProbability.end(),voronoiSeedCumulativeProbability.begin(), plus<double>());
jx=0;
// draw a random number between [0,nSide*nSide[ to uniformly choose one of
// the cells as a seed
xRand = gsl_rng_uniform(r)*voronoiSeedCumulativeProbability.back();
while ( xRand > voronoiSeedCumulativeProbability[jx] ){
// as long as the condition isn't fulfill pass to the next cell by incrementing jx
jx++ ;
}
// once out of the loop, asociate a probability 0 to the cell that has already
// been attributed and store the cell index in the voronoiSeeds vector
voronoiSeedProbability[jx]=0.0;
voronoiSeeds[ix]=jx;
}
// perform a continuous time stochastic process for the radial growth departing
// from the seeds
// create the political landscape initializing the seeds
// the value nFarms indicate the cell hasn't been colonized
vector<unsigned int> politicalLandscape(nSide*nSide,nFarms);
// initializing farm count at 0 so that we reach nFarms-1 for the colonized
ix=0;
for(it = voronoiSeeds.begin(); it != voronoiSeeds.end(); ++it){
politicalLandscape[*it] = ix;
farms[ix].push_back(*it);
ix++;
}
vector<double> propensitiesRadialGrowth(nSide*nSide);
vector<double> cumulativePropensitiesRadialGrowth(nSide*nSide);
vector<unsigned int> neighbours;
vector<double> farmNeighboursPropensity(nFarms);
vector<double> farmNeighboursCumulativePropensity(nFarms);
unsigned int nColonized = nFarms;
unsigned int farmId;
// iterate until the whole landscape is colonized
while (nColonized<politicalLandscape.size()){
// initialize to 0 the propensity vector for the radial growth
fill(propensitiesRadialGrowth.begin(),propensitiesRadialGrowth.end(),0.0);
// calculate propensities
for(ix = 0; ix < politicalLandscape.size(); ix++){
// check if cell ix is non-colonized
if(politicalLandscape[ix]==nFarms){
// get all the colonized neighbours
getNeighboursStateInf(neighbours, neighbourMatrix, politicalLandscape, ix, nFarms);
// update the propensity = number of colonized neighbours
propensitiesRadialGrowth[ix]=neighbours.size();
neighbours.clear();
}
}
// get the cumulative propensity
partial_sum(propensitiesRadialGrowth.begin(),propensitiesRadialGrowth.end(),cumulativePropensitiesRadialGrowth.begin(), plus<double>());
ix=0;
// choose the cell at which the colonization happens
xRand = gsl_rng_uniform(r)*cumulativePropensitiesRadialGrowth.back();
while(xRand > cumulativePropensitiesRadialGrowth[ix]){
ix++;
}
// get neighbours of cell ix and choose which farmer colonized the cell
neighbours.clear();
getNeighboursStateInf(neighbours, neighbourMatrix, politicalLandscape, ix, nFarms);
fill(farmNeighboursPropensity.begin(),farmNeighboursPropensity.end(),0.0);
// iterate neighbours and identify potential farmer colonizers
for(it = neighbours.begin(); it != neighbours.end(); ++it){
// check to which farm belongs the neighbour
farmId = politicalLandscape[*it];
// increment the amount of neighbours from a given farm
farmNeighboursPropensity[farmId]+=1;
}
// select the colonizing farm
partial_sum(farmNeighboursPropensity.begin(),farmNeighboursPropensity.end(),farmNeighboursCumulativePropensity.begin(), plus<double>());
jx=0;
xRand = gsl_rng_uniform(r)*farmNeighboursCumulativePropensity.back();
while(xRand > farmNeighboursCumulativePropensity[jx]){
jx++;
}
// update newly-colonized cell
politicalLandscape[ix] = jx;
// update counter to control end of simulation
nColonized+=1;
// store the newly colonized cell in the farms vector
farms[jx].push_back(ix);
}
return;
}
void initializeFarmStrategy( vector<vector<double>> &farmStrategy, unsigned int nFarms, double a, gsl_rng *r)
{
/*
for instance we only consider the fraction of farms on each strategy and
not the spatial arrangement of the strategies (i.e. clustering of sharing farms)
hence strategies are attributed with uniform probability over space
this means we just attribute a strategy to each farm irrespective of the
voronoi tesselation
*/
unsigned int ix, jx, nSparing;
vector<double> probSparing(nFarms,1);
vector<double> cumProbSparing(nFarms);