-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathModel.cpp
More file actions
1932 lines (1787 loc) · 63.4 KB
/
Model.cpp
File metadata and controls
1932 lines (1787 loc) · 63.4 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
/*----------------------------------------------------------------------------
*
* Copyright (C) 2026 Greta Bocedi, Stephen C.F. Palmer, Justin M.J. Travis, Anne-Kathleen Malchow, Roslyn Henry, Théo Pannetier, Jette Wolff, Damaris Zurell
*
* This file is part of RangeShifter.
*
* RangeShifter is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* RangeShifter is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with RangeShifter. If not, see <https://www.gnu.org/licenses/>.
*
--------------------------------------------------------------------------*/
//---------------------------------------------------------------------------
#include "Model.h"
ofstream outPar;
using namespace std::chrono;
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
#if RS_RCPP && !R_CMD
Rcpp::List RunModel(Landscape* pLandscape, int seqsim, Rcpp::S4 ParMaster) //Rcpp::S4 ParMaster new for all variants
#else
int RunModel(Landscape* pLandscape, int seqsim)
#endif
{
int yr, totalInds;
bool filesOK;
landParams ppLand = pLandscape->getLandParams();
envGradParams grad = paramsGrad->getGradient();
envStochParams env = paramsStoch->getStoch();
demogrParams dem = pSpecies->getDemogrParams();
stageParams sstruct = pSpecies->getStageParams();
transferRules trfr = pSpecies->getTransferRules();
managementParams manage = pManagement->getManagementParams();
translocationParams transloc = pManagement->getTranslocationParams();
initParams init = paramsInit->getInit();
simParams sim = paramsSim->getSim();
if (!ppLand.generated) {
if (!ppLand.patchModel) { // cell-based landscape
// create patches for suitable cells, adding unsuitable cells to the matrix
// NB this is an overhead here, but is necessary in case the identity of
// suitable habitats has been changed from one simulation to another (GUI or batch)
// substantial time savings may result during simulation in certain landscapes
// if using neutral markers, set up patches to sample from
pLandscape->allocatePatches(pSpecies);
}
pComm = new Community(pLandscape); // set up community
// set up a sub-community associated with each patch (incl. the matrix)
pLandscape->updateCarryingCapacity(pSpecies, 0, 0);
//if SPATIALDEMOG
if (ppLand.rasterType == 2 && ppLand.spatialdemog)
pLandscape->updateDemoScalings(0); // TODO -> is this needed independent of whether it is on or off?
// endif SPATIALDEMOG
patchData ppp;
int npatches = pLandscape->patchCount();
for (int i = 0; i < npatches; i++) {
ppp = pLandscape->getPatchData(i);
pComm->addSubComm(ppp.pPatch, ppp.patchNum); // SET UP ALL SUB-COMMUNITIES
}
if (init.seedType == 0 && init.freeType < 2 && init.initFrzYr > 0) {
// restrict available landscape to initialised region
pLandscape->setLandLimits(init.minSeedX, init.minSeedY,
init.maxSeedX, init.maxSeedY);
}
else {
pLandscape->resetLandLimits();
}
// Random patches are sampled once per landscape
if (sim.patchSamplingOption == "random") {
int nbToSample = pSpecies->getNbPatchesToSample();
auto patchesToSample = pLandscape->samplePatches(sim.patchSamplingOption, nbToSample, pSpecies);
pSpecies->setSamplePatchList(patchesToSample);
}
}
#if RS_RCPP && !R_CMD
Rcpp::List list_outPop;
#endif
// Loop through replicates
for (int rep = 0; rep < sim.reps; rep++) {
cout << "Running replicate " << rep + 1 << " / " << sim.reps << endl;
if (sim.saveVisits && !ppLand.generated) {
pLandscape->resetVisits();
}
if (sim.fixReplicateSeed) {
pRandom->fixNewSeed(rep);
}
patchChange patchchange;
costChange costchange;
int npatchchanges = pLandscape->numPatchChanges();
int ncostchanges = pLandscape->numCostChanges();
int ixpchchg = 0;
int ixcostchg = 0;
if (ppLand.generated) {
// delete previous community (if any)
// Note: this must be BEFORE the landscape is reset (as a sub-community accesses
// its corresponding patch upon deletion)
if (pComm != 0) delete pComm;
// generate new cell-based landscape
pLandscape->resetLand();
pLandscape->generatePatches();
pComm = new Community(pLandscape); // set up community
// set up a sub-community associated with each patch (incl. the matrix)
pLandscape->updateCarryingCapacity(pSpecies, 0, 0);
patchData ppp;
int npatches = pLandscape->patchCount();
for (int i = 0; i < npatches; i++) {
ppp = pLandscape->getPatchData(i);
pComm->addSubComm(ppp.pPatch, ppp.patchNum); // SET UP ALL SUB-COMMUNITIES
}
if (sim.patchSamplingOption == "random") {
// Then patches must be resampled for new landscape
int nbToSample = pSpecies->getNbPatchesToSample();
auto patchesToSample = pLandscape->samplePatches(sim.patchSamplingOption, nbToSample, pSpecies);
pSpecies->setSamplePatchList(patchesToSample);
}
}
if (init.seedType == 0 && init.freeType < 2 && init.initFrzYr > 0) {
// restrict available landscape to initialised region
pLandscape->setLandLimits(init.minSeedX, init.minSeedY,
init.maxSeedX, init.maxSeedY);
}
else {
pLandscape->resetLandLimits();
}
filesOK = true;
#if RS_RCPP
if(init.seedType==2 && init.indsFile=="NULL"){ // initialisation from InitInds list of dataframes
if(rep > 0){
int error_init = 0;
Rcpp::S4 InitParamsR("InitialisationParams");
InitParamsR = Rcpp::as<Rcpp::S4>(ParMaster.slot("init"));
Rcpp::List InitIndsList = Rcpp::as<Rcpp::List>(InitParamsR.slot("InitIndsList"));
error_init = ReadInitIndsFileR(0, pLandscape, Rcpp::as<Rcpp::DataFrame>(InitIndsList[rep]));
if(error_init>0) {
filesOK = false;
}
}
}
#endif
if (rep == 0) {
// open output files
if (sim.outRange) { // open Range file
if (!pComm->outRangeStartLandscape(pSpecies, ppLand.landNum)) {
filesOK = false;
}
}
if (sim.outOccup && sim.reps > 1)
if (!pComm->outOccupancyStartLandscape()) {
filesOK = false;
}
#if RS_RCPP
if (sim.outPop && sim.CreatePopFile) {
#else
if (sim.outPop) {
#endif
// open Population file
if (!pComm->outPopStartLandscape(pSpecies)) {
filesOK = false;
}
}
if (sim.outTraitsCells)
if (!pComm->outTraitsStartLandscape(pSpecies, ppLand.landNum)) {
filesOK = false;
}
if (sim.outTraitsRows)
if (!pComm->outTraitsRowsStartLandscape(pSpecies, ppLand.landNum)) {
filesOK = false;
}
if (sim.outConnect && ppLand.patchModel) // open Connectivity file
if (!pLandscape->outConnectStartLandscape()) {
filesOK = false;
}
if (sim.outputGlobalFst) { // open neutral genetics file
if (!pComm->openNeutralOutputFile(pSpecies, ppLand.landNum)) {
filesOK = false;
}
}
}
if (!filesOK) {
// close any files which may be open
if (sim.outRange) {
pComm->outRangeFinishLandscape();
}
if (sim.outOccup && sim.reps > 1)
pComm->outOccupancyFinishLandscape();
if (sim.outPop) {
pComm->outPopFinishLandscape();
}
if (sim.outTraitsCells)
pComm->outTraitsFinishLandscape();
if (sim.outTraitsRows)
pComm->outTraitsRowsFinishLandscape();
if (sim.outConnect && ppLand.patchModel)
pLandscape->outConnectFinishLandscape();
if (sim.outputGlobalFst) {
pComm->openNeutralOutputFile(pSpecies, -999);
}
#if RS_RCPP && !R_CMD
return Rcpp::List::create(Rcpp::Named("Errors") = 666);
#else
return 666;
#endif
}
if (env.stoch && !env.local) {
// create time series in case of global environmental stochasticity
pLandscape->setGlobalStoch(sim.years + 1);
}
if (grad.gradient) { // set up environmental gradient
pLandscape->setEnvGradient(pSpecies, true);
}
if (sim.outConnect && ppLand.patchModel)
pLandscape->createConnectMatrix();
// variables to control dynamic landscape
landChange landChg; landChg.chgNb = 0; landChg.chgYear = 999999;
if (!ppLand.generated && ppLand.dynamic) {
landChg = pLandscape->getLandChange(0); // get first change year
}
// set up populations in the community
pLandscape->updateCarryingCapacity(pSpecies, 0, 0);
if (ppLand.rasterType == 2 && ppLand.spatialdemog)
pLandscape->updateDemoScalings(0);
// if (init.seedType != 2) {
pComm->initialise(pSpecies, -1);
bool updateland = false;
int landIx = 0; // landscape change index
#if BATCH && RS_RCPP && !R_CMD
Rcpp::Rcout << "RunModel(): completed initialisation " << endl;
#endif
// open a new individuals file for each replicate
if (sim.outInds)
pComm->outIndsStartReplicate(rep, ppLand.landNum);
// open a new genetics file for each replicate
if (sim.outputGenes) {
bool geneOutFileHasOpened = pComm->openOutGenesFile(pSpecies->isDiploid(), ppLand.landNum, rep);
if (!geneOutFileHasOpened) throw logic_error("Output gene value file could not be initialised.");
}
// open a new genetics file for each replicate for per locus and pairwise stats
if (sim.outputPerLocusFst) {
pComm->openPerLocusFstFile(pSpecies, pLandscape, ppLand.landNum, rep);
}
if (sim.outPairwiseFst) {
pComm->openPairwiseFstFile(pSpecies, pLandscape, ppLand.landNum, rep);
}
#if RS_RCPP
// open a new movement paths file for each replicate
if (sim.outPaths)
pLandscape->outPathsStartReplicate(rep);
#endif
// years loop
for (yr = 0; yr < sim.years; yr++) {
#if RS_RCPP && !R_CMD
Rcpp::checkUserInterrupt();
#endif
bool updateCC = false;
if (yr < 4
|| (yr < 31 && yr % 10 == 0)
|| (yr < 301 && yr % 100 == 0)
|| (yr < 3001 && yr % 1000 == 0)
|| (yr < 30001 && yr % 10000 == 0)
|| (yr < 300001 && yr % 100000 == 0)
|| (yr < 3000001 && yr % 1000000 == 0)
) {
#if RS_RCPP && !R_CMD
Rcpp::Rcout << "Starting year " << yr << "..." << endl;
#else
cout << "Starting year " << yr << endl;
#endif
}
if (init.seedType == 0 && init.freeType < 2) {
// apply any range restrictions
if (yr == init.initFrzYr) {
// release initial frozen range - reset landscape to its full extent
pLandscape->resetLandLimits();
updateCC = true;
}
if (init.restrictRange) {
if (yr > init.initFrzYr && yr < init.finalFrzYr) {
if ((yr - init.initFrzYr) % init.restrictFreq == 0) {
// apply dynamic range restriction
commStats s = pComm->getStats();
int minY = s.maxY - init.restrictRows;
if (minY < 0) minY = 0;
pLandscape->setLandLimits(ppLand.minX, minY, ppLand.maxX, ppLand.maxY);
updateCC = true;
}
}
if (yr == init.finalFrzYr) {
// apply final range restriction
commStats s = pComm->getStats();
pLandscape->setLandLimits(ppLand.minX, s.minY, ppLand.maxX, s.maxY);
updateCC = true;
}
}
}
// environmental gradient, stochasticity & local extinction
// or dynamic landscape
updateland = false;
if (env.stoch || grad.gradient || ppLand.dynamic) {
if (grad.shifting && yr > grad.shift_begin && yr < grad.shift_stop) {
paramsGrad->incrOptY();
pLandscape->setEnvGradient(pSpecies, false);
updateCC = true;
}
if (env.stoch) {
if (env.local) pLandscape->updateLocalStoch();
updateCC = true;
}
if (ppLand.dynamic) {
if (yr == landChg.chgYear) { // apply landscape change
landIx = landChg.chgNb;
updateland = updateCC = true;
if (ppLand.patchModel) { // apply any patch changes
Patch* pPatch;
Cell* pCell;
patchchange = pLandscape->getPatchChange(ixpchchg++);
while (patchchange.chgnum <= landIx && ixpchchg <= npatchchanges) {
// move cell from original patch to new patch
pCell = pLandscape->findCell(patchchange.x, patchchange.y);
if (patchchange.oldpatch != 0) { // not matrix
pPatch = pLandscape->findPatch(patchchange.oldpatch);
pPatch->removeCell(pCell);
}
if (patchchange.newpatch == 0) { // matrix
pPatch = 0;
}
else {
pPatch = pLandscape->findPatch(patchchange.newpatch);
pPatch->addCell(pCell, patchchange.x, patchchange.y);
}
pCell->setPatch(pPatch);
// get next patch change
patchchange = pLandscape->getPatchChange(ixpchchg++);
}
ixpchchg--;
pLandscape->resetPatches(); // reset patch limits
}
if (landChg.pathCostFile != "NULL") { // apply any SMS cost changes
Cell* pCell;
costchange = pLandscape->getCostChange(ixcostchg++);
while (costchange.chgnum <= landIx && ixcostchg <= ncostchanges) {
pCell = pLandscape->findCell(costchange.x, costchange.y);
if (pCell != 0) {
pCell->setCost(costchange.newcost);
}
costchange = pLandscape->getCostChange(ixcostchg++);
}
ixcostchg--;
pLandscape->resetEffCosts();
}
if (landIx < pLandscape->numLandChanges()) { // get next change
landChg = pLandscape->getLandChange(landIx);
}
else {
landChg.chgYear = 9999999;
}
}
}
} // end of environmental gradient, etc.
if (updateCC) {
pLandscape->updateCarryingCapacity(pSpecies, yr, landIx);
if (ppLand.rasterType == 2 && ppLand.spatialdemog) //ppLand.spatialdemog false by default
pLandscape->updateDemoScalings((short)landIx);
}
if (sim.outConnect && ppLand.patchModel)
pLandscape->resetConnectMatrix();
if (ppLand.dynamic && updateland) {
if (trfr.usesMovtProc && trfr.moveType == 1) { // SMS
if (!trfr.costMap) pLandscape->resetCosts(); // in case habitats have changed
}
// apply effects of landscape change to species present in changed patches
pComm->patchChanges();
#if RS_RCPP
pComm->dispersal(landIx, yr);
#else
pComm->dispersal(landIx);
#endif // RS_RCPP
}
if (init.restrictRange) {
// remove any population from region removed from restricted range
if (yr > init.initFrzYr && yr < init.finalFrzYr) {
if ((yr - init.initFrzYr) % init.restrictFreq == 0) {
pComm->patchChanges();
}
}
}
if (init.seedType == 2) {
// add any new initial individuals for the current year
pComm->initialise(pSpecies, yr);
}
for (int gen = 0; gen < dem.repSeasons; gen++) // generation loop
{
// TODO move translocation before dispersal?
if (manage.translocation && std::find(transloc.translocation_years.begin(), transloc.translocation_years.end(), yr) != transloc.translocation_years.end()) {
pManagement->translocate(yr
, pLandscape
, pSpecies
);
}
// Output and pop. visualisation before reproduction
if (sim.outOccup || sim.outTraitsCells || sim.outTraitsRows)
PreReproductionOutput(pLandscape, pComm, rep, yr, gen);
// for non-structured population, also produce range and population output now
if (!dem.stageStruct && (sim.outRange || sim.outPop))
RangePopOutput(pComm, rep, yr, gen);
#if RS_RCPP && !R_CMD
if ((sim.ReturnPopMatrix || sim.ReturnPopDataFrame) && sim.outPop && yr >= sim.outStartPop && yr % sim.outIntPop == 0) {
// if ReturnPopMatrix
if(sim.ReturnPopMatrix) {
// total abundance
list_outPop.push_back(
pComm->addYearToPopList(rep, yr, PopOutType::NInd, -1),
"rep" + std::to_string(rep) + "_year" + std::to_string(yr) + "_NInd"
);
// also output single stages
if(sim.ReturnStages.length() > 1){
bool ReturnStage;
for(int i = 1; i < sim.ReturnStages.length(); i++) {
ReturnStage = sim.ReturnStages[i] == 1;
if(ReturnStage) {
list_outPop.push_back(
pComm->addYearToPopList(rep, yr, PopOutType::Stage, i),
"rep" + std::to_string(rep) +
"_year" + std::to_string(yr) +
"_NInd_stage" + std::to_string(i)
);
}
}
//
//
ReturnStage = sim.ReturnStages[0] == 1;
if (ReturnStage) {
//Rcpp::Rcout << "Return Juveniles" << endl;
list_outPop.push_back(
pComm->addYearToPopList(rep, yr, PopOutType::Juvs, -1),
"rep" + std::to_string(rep) + "_year" + std::to_string(yr) + "_NJuv"
);
}
}
}
if(sim.ReturnPopDataFrame){
// in contrast to ReturnMatrix, this function produces a list of data frames, one per rep and year, holding all (stage-specific) abundances for all patches,
// instead of a single matrix for each population size metric (total abundance, stage-specific abundance, juvenile abundance) and each year and replicate
list_outPop.push_back(
pComm->addYearToPopListPatchBased(rep, yr, sim.ReturnStages),
"rep" + std::to_string(rep) + "_year" + std::to_string(yr)
);
}
// list_outPop.push_back(pComm->addYearToPopList(rep, yr), "rep" + std::to_string(rep) + "_year" + std::to_string(yr));
}
#endif
// apply local extinction for generation 0 only
// CHANGED TO *BEFORE* RANGE & POPN OUTPUT PRODUCTION IN v1.1,
// SO THAT NOS. OF JUVENILES BORN CAN BE REPORTED
if (!ppLand.patchModel && gen == 0) {
if (env.localExt) pComm->localExtinction(0);
if (grad.gradient && grad.gradType == 3) pComm->localExtinction(1);
}
// reproduction
pComm->reproduction(yr);
if (dem.stageStruct) {
if (sstruct.survival == 0) { // at reproduction
pComm->survival0(2, 1); // survival of all non-juvenile stages
}
}
// Output and pop. visualisation AFTER reproduction
if (dem.stageStruct && (sim.outRange || sim.outPop))
RangePopOutput(pComm, rep, yr, gen);
// Dispersal
pComm->emigration();
#if RS_RCPP
pComm->dispersal(landIx, yr);
#else
pComm->dispersal(landIx);
#endif // RS_RCPP
// survival part 0
if (dem.stageStruct) {
if (sstruct.survival == 0) { // at reproduction
pComm->survival0(0, 1); // survival of juveniles only
}
if (sstruct.survival == 1) { // between reproduction events
pComm->survival0(1, 1); // survival of all stages
}
if (sstruct.survival == 2) { // annually
pComm->survival0(1, 0); // development only of all stages
}
}
else { // non-structured population
pComm->survival0(1, 1);
}
// output Individuals
if (sim.outInds && yr >= sim.outStartInd && yr % sim.outIntInd == 0)
pComm->outIndividuals(rep, yr, gen);
bool doGenes =
sim.outputGenes &&
yr >= sim.outputGenesStart &&
sim.outputGenesInterval > 0 &&
yr % sim.outputGenesInterval == 0;
bool doGlobalFst =
sim.outputGlobalFst &&
yr >= sim.outputGlobalFstStart &&
sim.outputGlobalFstInterval > 0 &&
yr % sim.outputGlobalFstInterval == 0;
bool doPairwiseFst =
sim.outPairwiseFst &&
yr >= sim.outputPairwiseFstStart &&
sim.outputPairwiseFstInterval > 0 &&
yr % sim.outputPairwiseFstInterval == 0;
if (doGenes || doGlobalFst || doPairwiseFst) {
if (sim.patchSamplingOption != "list" &&
sim.patchSamplingOption != "random") {
int nbToSample = pSpecies->getNbPatchesToSample();
auto patchesToSample =
pLandscape->samplePatches(sim.patchSamplingOption, nbToSample, pSpecies);
pSpecies->setSamplePatchList(patchesToSample);
}
pComm->sampleIndividuals(pSpecies);
if (doGenes) {
pComm->outputGeneValues(yr, gen, pSpecies);
}
if (doGlobalFst || doPairwiseFst) {
pComm->calculateNeutralGenetics(
pSpecies, rep, yr, gen,
doPairwiseFst, sim.outputPairwiseFstStart, sim.outputPairwiseFstInterval,
doGlobalFst, sim.outputGlobalFstStart, sim.outputGlobalFstInterval,
sim.outputPerLocusFst);
}
}
// Resolve survival and devlpt
pComm->survival1();
} // end of the generation loop
totalInds = pComm->totalInds();
if (totalInds <= 0) {
cout << "All populations went extinct." << endl;
yr++;
break;
}
// Connectivity Matrix
if (sim.outConnect && ppLand.patchModel
&& yr >= sim.outStartConn && yr % sim.outIntConn == 0)
pLandscape->outConnect(rep, yr);
if (dem.stageStruct && sstruct.survival == 2) { // annual survival - all stages
pComm->survival0(1, 2);
pComm->survival1();
}
if (dem.stageStruct) {
pComm->ageIncrement(); // increment age of all individuals
if (sim.outInds && yr >= sim.outStartInd && yr % sim.outIntInd == 0)
pComm->outIndividuals(rep, yr, -1); // list any individuals dying having reached maximum age
pComm->survival1(); // delete any such individuals
totalInds = pComm->totalInds();
if (totalInds <= 0) {
cout << "All populations went extinct." << endl;
yr++;
break;
}
}
} // end of the years loop
// Final output
// produce final summary output
if (sim.outOccup || sim.outTraitsCells || sim.outTraitsRows)
PreReproductionOutput(pLandscape, pComm, rep, yr, 0);
if (sim.outRange || sim.outPop)
RangePopOutput(pComm, rep, yr, 0);
pComm->resetPopns();
//Reset the gradient optimum
if (grad.gradient) paramsGrad->resetOptY();
pLandscape->resetLandLimits();
if (ppLand.patchModel && ppLand.dynamic && ixpchchg > 0) {
// apply any patch changes to reset landscape to original configuration
// (provided that at least one has already occurred)
patchChange patchchange;
Patch* pPatch;
Cell* pCell;
patchchange = pLandscape->getPatchChange(ixpchchg++);
while (patchchange.chgnum <= 666666 && ixpchchg <= npatchchanges) {
// move cell from original patch to new patch
pCell = pLandscape->findCell(patchchange.x, patchchange.y);
if (patchchange.oldpatch != 0) { // not matrix
pPatch = pLandscape->findPatch(patchchange.oldpatch);
pPatch->removeCell(pCell);
}
if (patchchange.newpatch == 0) { // matrix
pPatch = 0;
}
else {
pPatch = pLandscape->findPatch(patchchange.newpatch);
pPatch->addCell(pCell, patchchange.x, patchchange.y);
}
pCell->setPatch(pPatch);
// get next patch change
patchchange = pLandscape->getPatchChange(ixpchchg++);
}
ixpchchg--;
pLandscape->resetPatches();
}
if (ppLand.dynamic) {
transferRules trfr = pSpecies->getTransferRules();
if (trfr.usesMovtProc && trfr.moveType == 1) { // SMS
if (ixcostchg > 0) {
// apply any cost changes to reset landscape to original configuration
// (provided that at least one has already occurred)
Cell* pCell;
costchange = pLandscape->getCostChange(ixcostchg++);
while (costchange.chgnum <= 666666 && ixcostchg <= ncostchanges) {
pCell = pLandscape->findCell(costchange.x, costchange.y);
if (pCell != 0) {
pCell->setCost(costchange.newcost);
}
costchange = pLandscape->getCostChange(ixcostchg++);
}
ixcostchg--;
pLandscape->resetEffCosts();
}
if (!trfr.costMap) pLandscape->resetCosts(); // in case habitats have changed
}
}
if (sim.outConnect && ppLand.patchModel)
pLandscape->resetConnectMatrix(); // set connectivity matrix to zeroes
if (sim.outInds) // close Individuals output file
pComm->outIndsFinishReplicate();
if (sim.outputGenes) { // close genetic values output file
pComm->openOutGenesFile(false, -999, rep);
}
//if (sim.outputGlobalFst) //close per locus file
// pComm->openNeutralOutputFile(pSpecies, -999);
if (sim.outputPerLocusFst) //close per locus file
pComm->openPerLocusFstFile(pSpecies, pLandscape, -999, rep);
if (sim.outPairwiseFst) //close per locus file
pComm->openPairwiseFstFile(pSpecies, pLandscape, -999, rep);
if (sim.saveVisits) {
pLandscape->outVisits(rep, ppLand.landNum);
pLandscape->resetVisits();
}
#if RS_RCPP
if (sim.outPaths)
pLandscape->outPathsFinishReplicate();
#endif
} // end of the replicates loop
if (sim.outConnect && ppLand.patchModel) {
pLandscape->deleteConnectMatrix();
pLandscape->outConnectFinishLandscape(); // close Connectivity Matrix file
}
// Occupancy outputs
if (sim.outOccup && sim.reps > 1) {
pComm->outOccupancy();
pComm->outOccSuit();
pComm->deleteOccupancy((sim.years / sim.outIntOcc) + 1);
pComm->outOccupancyFinishLandscape();
}
if (sim.outRange) {
pComm->outRangeFinishLandscape(); // close Range file
}
#if RS_RCPP
if (sim.outPop && sim.CreatePopFile) {
#else
if (sim.outPop) {
#endif
pComm->outPopFinishLandscape(); // close Population file
}
if (sim.outTraitsCells)
pComm->outTraitsFinishLandscape(); // close Traits file
if (sim.outTraitsRows)
pComm->outTraitsRowsFinishLandscape(); // close Traits rows file
// close Individuals & Genetics output files if open
// they can still be open if the simulation was stopped by the user
if (sim.outInds) pComm->outIndsFinishReplicate();
if (sim.outputGenes) pComm->openOutGenesFile(0, -999, 0);
if (sim.outputGlobalFst) {
pComm->openNeutralOutputFile(pSpecies, -999);
}
if (sim.outputPerLocusFst) {
pComm->openPerLocusFstFile(pSpecies, pLandscape, -999, 0);
}
if (sim.outPairwiseFst) pComm->openPairwiseFstFile(pSpecies, pLandscape, -999, 0);
delete pComm;
pComm = 0;
#if RS_RCPP && !R_CMD
return list_outPop;
#else
return 0;
#endif
}
#if LINUX_CLUSTER || RS_RCPP
// Check whether a specified directory path exists
bool is_directory(const char* pathname) {
struct stat info;
if (stat(pathname, &info) != 0) return false; // path does not exist
if (S_ISDIR(info.st_mode)) return true;
return false;
}
#endif
//---------------------------------------------------------------------------
bool CheckDirectory(const string& pathToProjDir)
{
bool errorfolder = false;
string subfolder;
subfolder = pathToProjDir + "Inputs";
const char* inputs = subfolder.c_str();
if (!is_directory(inputs)) errorfolder = true;
subfolder = pathToProjDir + "Outputs";
const char* outputs = subfolder.c_str();
if (!is_directory(outputs)) errorfolder = true;
subfolder = pathToProjDir + "Output_Maps";
const char* outputmaps = subfolder.c_str();
if (!is_directory(outputmaps)) errorfolder = true;
if (errorfolder) {
cout << endl << "***** Invalid working directory: " << pathToProjDir
<< endl << endl;
cout << "***** Working directory must contain Inputs, Outputs and Output_Maps folders"
<< endl << endl;
cout << "*****" << endl;
cout << "***** Simulation ABORTED" << endl;
cout << "*****" << endl;
return false;
}
else return true;
}
//---------------------------------------------------------------------------
//For outputs and population visualisations pre-reproduction
void PreReproductionOutput(Landscape* pLand, Community* pComm, int rep, int yr, int gen)
{
simParams sim = paramsSim->getSim();
// trait outputs and visualisation
if ((sim.outTraitsCells && yr >= sim.outStartTraitCell && yr % sim.outIntTraitCell == 0)
|| (sim.outTraitsRows && yr >= sim.outStartTraitRow && yr % sim.outIntTraitRow == 0))
{
pComm->outTraits(pSpecies, rep, yr, gen);
}
if (sim.outOccup && yr % sim.outIntOcc == 0 && gen == 0)
pComm->updateOccupancy(yr / sim.outIntOcc, rep);
}
//For outputs and population visualisations pre-reproduction
void RangePopOutput(Community* pComm, int rep, int yr, int gen)
{
simParams sim = paramsSim->getSim();
if (sim.outRange && (yr % sim.outIntRange == 0 || pComm->totalInds() <= 0))
pComm->outRange(pSpecies, rep, yr, gen);
#if RS_RCPP
if (sim.outPop && sim.CreatePopFile && yr >= sim.outStartPop && yr%sim.outIntPop == 0)
#else
if (sim.outPop && yr >= sim.outStartPop && yr % sim.outIntPop == 0)
#endif
pComm->outPop(rep, yr, gen);
}
//---------------------------------------------------------------------------
void OutParameters(Landscape* pLandscape)
{
double k;
//int nrows,ncols,nsexes,nstages;
int nsexes, nstages;
landParams ppLand = pLandscape->getLandParams();
genLandParams ppGenLand = pLandscape->getGenLandParams();
envGradParams grad = paramsGrad->getGradient();
envStochParams env = paramsStoch->getStoch();
demogrParams dem = pSpecies->getDemogrParams();
stageParams sstruct = pSpecies->getStageParams();
emigRules emig = pSpecies->getEmigRules();
transferRules trfr = pSpecies->getTransferRules();
settleType sett = pSpecies->getSettle();
settleRules srules;
settleSteps ssteps;
settleTraits settleDD;
simParams sim = paramsSim->getSim();
string name;
if (sim.batchMode)
name = paramsSim->getDir(2)
+ "Batch" + to_string(sim.batchNum) + "_"
+ "Sim" + to_string(sim.simulation)
+ "_Land" + to_string(ppLand.landNum) + "_Parameters.txt";
else
name = paramsSim->getDir(2) + "Sim" + to_string(sim.simulation) + "_Parameters.txt";
outPar.open(name.c_str());
outPar << "RangeShifter 3.0 ";
outPar << endl;
outPar << "================ ";
outPar << " =====================";
outPar << endl << endl;
outPar << "BATCH MODE \t";
if (sim.batchMode) outPar << "yes" << endl;
else outPar << "no" << endl;
outPar << "SEED \t" << pRandom->getSeed() << endl;
outPar << "REPLICATES \t" << sim.reps << endl;
outPar << "YEARS \t" << sim.years << endl;
outPar << "REPRODUCTIVE SEASONS / YEAR\t" << dem.repSeasons << endl;
if (ppLand.patchModel) {
outPar << "PATCH-BASED MODEL" << endl;
outPar << "No. PATCHES \t" << pLandscape->patchCount() - 1 << endl;
}
else
outPar << "CELL-BASED MODEL" << endl;
outPar << "BOUNDARIES \t";
if (sim.absorbing) outPar << "absorbing" << endl;
else outPar << "reflective" << endl;
outPar << endl;
outPar << "LANDSCAPE:\t";
if (ppLand.generated) {
outPar << "artificially generated map" << endl;
outPar << "TYPE: \t";
if (ppGenLand.continuous) outPar << "continuous \t";
else outPar << "discrete \t";
if (ppGenLand.fractal) outPar << "fractal";
else outPar << "random";
outPar << endl << "PROPORTION OF SUITABLE HABITAT (p)\t" << ppGenLand.propSuit << endl;
if (ppGenLand.fractal) outPar << "HURST EXPONENT\t" << ppGenLand.hurst << endl;
}
else {
outPar << "imported map" << endl;
outPar << "TYPE: \t";
switch (ppLand.rasterType) {
case 0:
outPar << "habitat codes" << endl;
break;
case 1:
outPar << "habitat % cover" << endl;
break;
case 2:
outPar << "habitat quality" << endl;
break;
}
outPar << "FILE NAME: ";
#if RS_RCPP
if (ppLand.dynamic) {
outPar << name_landscape << endl;
}
else {
outPar << name_landscape << endl;
}
if (ppLand.patchModel) {
outPar << "PATCH FILE: " << name_patch << endl;
}
if (trfr.costMap) {
outPar << "COSTS FILE: " << name_costfile << endl;
}
#else
if (sim.batchMode) outPar << " (see batch file) " << landFile << endl;
#endif
outPar << "No. HABITATS:\t" << ppLand.nHab << endl;
}
outPar << "RESOLUTION (m): \t" << ppLand.resol << endl;
outPar << "DIMENSIONS: X " << ppLand.dimX << " Y " << ppLand.dimY << endl;
outPar << "AVAILABLE: min.X " << ppLand.minX << " min.Y " << ppLand.minY
<< " max.X " << ppLand.maxX << " max.Y " << ppLand.maxY << endl;
if (!ppLand.generated && ppLand.dynamic) {
landChange chg;
outPar << "DYNAMIC LANDSCAPE: " << endl;
int nchanges = pLandscape->numLandChanges();
for (int i = 0; i < nchanges; i++) {
chg = pLandscape->getLandChange(i);
outPar << "Change no. " << chg.chgNb << " in year " << chg.chgYear << endl;
outPar << "Landscape: " << chg.pathHabFile << endl;
if (ppLand.patchModel) {
outPar << "Patches : " << chg.pathPatchFile << endl;
}
if (chg.pathCostFile != "none" && chg.pathCostFile != "NULL") {
outPar << "Costs : " << chg.pathCostFile << endl;
}
}
}
outPar << endl << "SPECIES DISTRIBUTION LOADED: \t";
if (ppLand.spDist)
{
outPar << "yes" << endl;
outPar << "RESOLUTION (m)\t" << ppLand.spResol << endl;
outPar << "FILE NAME: ";
#if !RS_RCPP
if (sim.batchMode) outPar << " (see batch file) " << landFile << endl;
#else
outPar << name_sp_dist << endl;
#endif
}
else outPar << "no" << endl;
outPar << endl << "ENVIRONMENTAL GRADIENT:\t ";
if (grad.gradient)
{
switch (grad.gradType) {
case 1:
if (dem.stageStruct) outPar << "Density dependence strength (1/b)" << endl;
else outPar << "Carrying capacity (K)" << endl;
break;
case 2:
if (dem.stageStruct) outPar << "Fecundity" << endl;
else outPar << "Intrinsic growth rate (r)" << endl;
break;
case 3:
outPar << "Local extinction probability" << endl;
break;
default:
outPar << "ERROR ERROR ERROR" << endl;
;