-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPopulation.cpp
More file actions
1817 lines (1665 loc) · 57.7 KB
/
Population.cpp
File metadata and controls
1817 lines (1665 loc) · 57.7 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 "Population.h"
#include <algorithm>
//---------------------------------------------------------------------------
ofstream outPop;
ofstream outInds;
//---------------------------------------------------------------------------
Population::Population(void) {
nSexes = nStages = 0;
pPatch = NULL;
pSpecies = NULL;
return;
}
Population::Population(Species* pSp, Patch* pPch, int ninds, int resol)
{
// constructor for a Population of a specified size
int n, nindivs, age = 0, minage, maxage, nAges = 0;
int cumtotal = 0;
float probmale;
double ageprob, ageprobsum;
std::vector <double> ageProb; // for quasi-equilibrium initial age distribution
Cell* pCell;
if (ninds > 0) {
inds.reserve(ninds);
juvs.reserve(ninds);
}
pSpecies = pSp;
pPatch = pPch;
// record the new population in the patch
patchPopn pp;
pp.pSp = pSpecies; pp.pPop = this;
pPatch->addPopn(pp);
demogrParams dem = pSpecies->getDemogrParams();
stageParams sstruct = pSpecies->getStageParams();
emigRules emig = pSpecies->getEmigRules();
transferRules trfr = pSpecies->getTransferRules();
settleType sett = pSpecies->getSettle();
initParams init = paramsInit->getInit();
// determine no. of stages and sexes of species to initialise
if (dem.stageStruct) {
nStages = sstruct.nStages;
}
else // non-structured population has 2 stages, but user only ever sees stage 1
nStages = 2;
if (dem.repType == 0) { nSexes = 1; probmale = 0.0; }
else { nSexes = 2; probmale = dem.propMales; }
// set up population sub-totals
for (int stg = 0; stg < gMaxNbStages; stg++) {
for (int sex = 0; sex < gMaxNbSexes; sex++) {
nInds[stg][sex] = 0;
}
}
// set up local copy of minimum age table
short minAge[gMaxNbStages][gMaxNbSexes];
for (int stg = 0; stg < nStages; stg++) {
for (int sex = 0; sex < nSexes; sex++) {
if (dem.stageStruct) {
if (dem.repType == 1) { // simple sexual model
// both sexes use minimum ages recorded for females
minAge[stg][sex] = pSpecies->getMinAge(stg, 0);
}
else {
minAge[stg][sex] = pSpecies->getMinAge(stg, sex);
}
}
else { // non-structured population
minAge[stg][sex] = 0;
}
}
}
// individuals of new population must be >= stage 1
for (int stg = 1; stg < nStages; stg++) {
if (dem.stageStruct) { // allocate to stages according to initialisation conditions
// final stage is treated separately to ensure that correct total
// no. of individuals is created
if (stg == nStages - 1) {
n = ninds - cumtotal;
}
else {
n = (int)(ninds * paramsInit->getProp(stg) + 0.5);
cumtotal += n;
}
}
else { // non-structured - all individuals go into stage 1
n = ninds;
}
// establish initial age distribution
minage = maxage = stg;
if (dem.stageStruct) {
// allow for stage-dependent minimum ages (use whichever sex is greater)
if (minAge[stg][0] > 0 && minage < minAge[stg][0]) minage = minAge[stg][0];
if (nSexes == 2 && minAge[stg][1] > 0 && minage < minAge[stg][1]) minage = minAge[stg][1];
// allow for specified age distribution
if (init.initAge != 0) { // not lowest age
if (stg == nStages - 1) maxage = sstruct.maxAge; // final stage
else { // all other stages - use female max age, as sex of individuals is not predetermined
maxage = minAge[stg + 1][0] - 1;
}
if (maxage < minage) maxage = minage;
nAges = maxage - minage + 1;
if (init.initAge == 2) { // quasi-equilibrium distribution
double psurv = (double)pSpecies->getSurv(stg, 0); // use female survival for the stage
ageProb.clear();
ageprobsum = 0.0;
ageprob = 1.0;
for (int i = 0; i < nAges; i++) {
ageProb.push_back(ageprob); ageprobsum += ageprob; ageprob *= psurv;
}
for (int i = 0; i < nAges; i++) {
ageProb[i] /= ageprobsum;
if (i > 0) ageProb[i] += ageProb[i - 1]; // to give cumulative probability
}
}
}
}
// create individuals
int sex;
nindivs = (int)inds.size();
for (int i = 0; i < n; i++) {
pCell = pPatch->getRandomCell();
if (dem.stageStruct) {
switch (init.initAge) {
case 0: // lowest possible age
age = minage;
break;
case 1: // randomised
if (maxage > minage) age = pRandom->IRandom(minage, maxage);
else age = minage;
break;
case 2: // quasi-equilibrium
if (nAges > 1) {
double rrr = pRandom->Random();
int ageclass = 0;
while (rrr > ageProb[ageclass]) ageclass++;
age = minage + ageclass;
}
else age = minage;
break;
}
}
else age = stg;
Individual* newInd = new Individual(pSpecies, pCell, pPatch, stg, age, sstruct.repInterval,
probmale, trfr.usesMovtProc, trfr.moveType);
if (pSpecies->getNTraits() > 0) {
newInd->setUpGenes(pSpecies, resol);
}
inds.push_back(newInd);
nInds[stg][newInd->getSex()]++;
}
}
}
Population::~Population(void) {
int ninds = (int)inds.size();
for (int i = 0; i < ninds; i++) {
if (inds[i] != NULL) delete inds[i];
}
inds.clear();
int njuvs = (int)juvs.size();
for (int i = 0; i < njuvs; i++) {
if (juvs[i] != NULL) delete juvs[i];
}
juvs.clear();
int nsampledInds = (int)sampledInds.size();
for (int i = 0; i < nsampledInds; i++) {
if (sampledInds[i] != NULL) sampledInds[i]=NULL;
}
sampledInds.clear();
}
traitsums Population::getIndTraitsSums(Species* pSpecies) {
traitsums ts = traitsums();
for (int sex = 0; sex < gMaxNbSexes; sex++) {
ts.ninds[sex] = 0;
ts.sumD0[sex] = ts.ssqD0[sex] = 0.0;
ts.sumAlpha[sex] = ts.ssqAlpha[sex] = 0.0;
ts.sumBeta[sex] = ts.ssqBeta[sex] = 0.0;
ts.sumDist1[sex] = ts.ssqDist1[sex] = 0.0;
ts.sumDist2[sex] = ts.ssqDist2[sex] = 0.0;
ts.sumProp1[sex] = ts.ssqProp1[sex] = 0.0;
ts.sumDP[sex] = ts.ssqDP[sex] = 0.0;
ts.sumGB[sex] = ts.ssqGB[sex] = 0.0;
ts.sumAlphaDB[sex] = ts.ssqAlphaDB[sex] = 0.0;
ts.sumBetaDB[sex] = ts.ssqBetaDB[sex] = 0.0;
ts.sumStepL[sex] = ts.ssqStepL[sex] = 0.0;
ts.sumRho[sex] = ts.ssqRho[sex] = 0.0;
ts.sumS0[sex] = ts.ssqS0[sex] = 0.0;
ts.sumAlphaS[sex] = ts.ssqAlphaS[sex] = 0.0;
ts.sumBetaS[sex] = ts.ssqBetaS[sex] = 0.0;
ts.sumGeneticFitness[sex] = ts.ssqGeneticFitness[sex] = 0.0;
}
emigRules emig = pSpecies->getEmigRules();
transferRules trfr = pSpecies->getTransferRules();
settleType sett = pSpecies->getSettle();
for (auto& ind : inds) {
int sex = ind->getSex();
ts.ninds[sex] += 1;
// emigration traits
emigTraits e = ind->getIndEmigTraits();
ts.sumD0[sex] += e.d0;
ts.ssqD0[sex] += e.d0 * e.d0;
ts.sumAlpha[sex] += e.alpha;
ts.ssqAlpha[sex] += e.alpha * e.alpha;
ts.sumBeta[sex] += e.beta;
ts.ssqBeta[sex] += e.beta * e.beta;
// transfer traits
if (trfr.usesMovtProc) {
switch (trfr.moveType) {
case 1: { // SMS
trfrSMSTraits sms = ind->getIndSMSTraits();
ts.sumDP[sex] += sms.dp;
ts.ssqDP[sex] += sms.dp * sms.dp;
ts.sumGB[sex] += sms.gb;
ts.ssqGB[sex] += sms.gb * sms.gb;
ts.sumAlphaDB[sex] += sms.alphaDB;
ts.ssqAlphaDB[sex] += sms.alphaDB * sms.alphaDB;
ts.sumBetaDB[sex] += sms.betaDB;
ts.ssqBetaDB[sex] += sms.betaDB * sms.betaDB;
break;
}
case 2: {
trfrCRWTraits c = ind->getIndCRWTraits();
ts.sumStepL[sex] += c.stepLength;
ts.ssqStepL[sex] += c.stepLength * c.stepLength;
ts.sumRho[sex] += c.rho;
ts.ssqRho[sex] += c.rho * c.rho;
break;
}
default:
throw runtime_error("usesMoveProcess is ON but moveType is neither 1 (SMS) or 2 (CRW).");
break;
}
}
else {
trfrKernelParams k = ind->getIndKernTraits();
ts.sumDist1[sex] += k.meanDist1;
ts.ssqDist1[sex] += k.meanDist1 * k.meanDist1;
ts.sumDist2[sex] += k.meanDist2;
ts.ssqDist2[sex] += k.meanDist2 * k.meanDist2;
ts.sumProp1[sex] += k.probKern1;
ts.ssqProp1[sex] += k.probKern1 * k.probKern1;
}
// settlement traits
settleTraits s = ind->getIndSettTraits();
ts.sumS0[sex] += s.s0;
ts.ssqS0[sex] += s.s0 * s.s0;
ts.sumAlphaS[sex] += s.alpha;
ts.ssqAlphaS[sex] += s.alpha * s.alpha;
ts.sumBetaS[sex] += s.beta;
ts.ssqBetaS[sex] += s.beta * s.beta;
double fitness = ind->getGeneticFitness();
ts.sumGeneticFitness[sex] += fitness;
ts.ssqGeneticFitness[sex] += fitness * fitness;
}
return ts;
}
//int Population::getNInds() { return static_cast<int>(inds.size()); }
// ----------------------------------------------------------------------------------------
// reset allele table
// ----------------------------------------------------------------------------------------
void Population::resetPopNeutralTables() {
for (auto& entry : popNeutralCountTables) {
entry.reset();
}
}
// ----------------------------------------------------------------------------------------
// Populate population-level NEUTRAL count tables
// Update allele occurrence and heterozygosity counts, and allele frequencies
// ----------------------------------------------------------------------------------------
void Population::updatePopNeutralTables() {
const int nLoci = pSpecies->getNPositionsForTrait(NEUTRAL);
const int nAlleles = pSpecies->getSpTrait(NEUTRAL)->getNbNeutralAlleles();
const auto& positions = pSpecies->getSpTrait(NEUTRAL)->getGenePositions();
const int ploidy = pSpecies->isDiploid() ? 2 : 1;
// Create /reset empty tables
if (popNeutralCountTables.size() != 0)
resetPopNeutralTables();
else {
popNeutralCountTables.reserve(nLoci);
for (int l = 0; l < nLoci; l++) {
popNeutralCountTables.push_back(NeutralCountsTable(nAlleles));
}
}
// Fill tallies for each locus
for (Individual* individual : sampledInds) {
const auto trait = individual->getTrait(NEUTRAL);
int whichLocus = 0;
for (auto position : positions) {
int alleleOnChromA = (int)trait->getAlleleValueAtLocus(0, position);
popNeutralCountTables[whichLocus].incrementTally(alleleOnChromA);
if (ploidy == 2) { // second allele and heterozygosity
int alleleOnChromB = (int)trait->getAlleleValueAtLocus(1, position);
popNeutralCountTables[whichLocus].incrementTally(alleleOnChromB);
bool isHetero = alleleOnChromA != alleleOnChromB;
if (isHetero) {
popNeutralCountTables[whichLocus].incrementHeteroTally(alleleOnChromA);
popNeutralCountTables[whichLocus].incrementHeteroTally(alleleOnChromB);
}
}
whichLocus++;
}
}
// Fill frequencies
if (sampledInds.size() > 0) {
std::for_each(
popNeutralCountTables.begin(),
popNeutralCountTables.end(),
[&](NeutralCountsTable& thisLocus) -> void {
thisLocus.setFrequencies(static_cast<int>(sampledInds.size()) * ploidy);
});
}
}
double Population::getAlleleFrequency(int thisLocus, int whichAllele) {
return popNeutralCountTables[thisLocus].getFrequency(whichAllele);
}
int Population::getAlleleTally(int thisLocus, int whichAllele) {
return popNeutralCountTables[thisLocus].getTally(whichAllele);
}
int Population::getHeteroTally(int thisLocus, int whichAllele) {
return popNeutralCountTables[thisLocus].getHeteroTally(whichAllele);
}
// ----------------------------------------------------------------------------------------
// Count number of heterozygotes loci in sampled individuals
// ----------------------------------------------------------------------------------------
int Population::countHeterozygoteLoci() {
int nbHetero = 0;
if (pSpecies->isDiploid()) {
for (Individual* ind : sampledInds) {
const NeutralTrait* trait = (NeutralTrait*)(ind->getTrait(NEUTRAL));
nbHetero += trait->countHeterozygoteLoci();
}
}
return nbHetero;
}
// ----------------------------------------------------------------------------------------
// Count number of heterozygotes among sampled individuals for each locus
// ----------------------------------------------------------------------------------------
vector<int> Population::countNbHeterozygotesEachLocus() {
const auto& positions = pSpecies->getSpTrait(NEUTRAL)->getGenePositions();
vector<int> hetero(positions.size(), 0);
if (pSpecies->isDiploid()) {
for (Individual* ind : sampledInds) {
const NeutralTrait* trait = (NeutralTrait*)ind->getTrait(NEUTRAL);
int counter = 0;
for (auto position : positions) {
hetero[counter] += trait->isHeterozygoteAtLocus(position);
counter++;
}
}
}
return hetero;
}
// ----------------------------------------------------------------------------------------
// Compute the expected heterozygosity for population
// ----------------------------------------------------------------------------------------
double Population::computeHs() {
int nLoci = pSpecies->getNPositionsForTrait(NEUTRAL);
int nAlleles = pSpecies->getSpTrait(NEUTRAL)->getNbNeutralAlleles();
double hs = 0;
double freq;
vector<double> locihet(nLoci, 1);
if (sampledInds.size() > 0) {
for (int thisLocus = 0; thisLocus < nLoci; ++thisLocus) {
for (int allele = 0; allele < nAlleles; ++allele) {
freq = getAlleleFrequency(thisLocus, allele);
freq *= freq; //squared frequencies (expected _homozygosity)
locihet[thisLocus] -= freq; // 1 - sum of p2 = expected heterozygosity
}
hs += locihet[thisLocus];
}
}
return hs;
}
popStats Population::getStats(std::vector <float> localDemoScaling)
{
popStats p = popStats();
int ninds;
float fec;
bool breeders[2] = { false, false };
demogrParams dem = pSpecies->getDemogrParams();
p.pSpecies = pSpecies;
p.pPatch = pPatch;
p.spNum = pSpecies->getSpNum();
p.nInds = (int)inds.size();
p.nNonJuvs = p.nAdults = 0;
p.breeding = false;
for (int stg = 1; stg < nStages; stg++) {
for (int sex = 0; sex < nSexes; sex++) {
ninds = nInds[stg][sex];
p.nNonJuvs += ninds;
if (ninds > 0) {
if (pSpecies->stageStructured()) {
if (dem.repType == 2) {
if (pSpecies->getFecSpatial() && pSpecies->getFecLayer(stg,sex)>=0){
fec = pSpecies->getFec(stg,sex)*localDemoScaling[pSpecies->getFecLayer(stg,sex)];
}
else fec = pSpecies->getFec(stg,sex);
}
else {
if (pSpecies->getFecSpatial() && pSpecies->getFecLayer(stg,0)>=0){
fec = pSpecies->getFec(stg,0)*localDemoScaling[pSpecies->getFecLayer(stg,0)];
}
else fec = pSpecies->getFec(stg, 0);
}
if (fec > 0.0) { breeders[sex] = true; p.nAdults += ninds; }
}
else breeders[sex] = true;
}
}
}
// is there a breeding population present?
if (nSexes == 1) {
p.breeding = breeders[0];
}
else {
if (breeders[0] && breeders[1]) p.breeding = true;
}
return p;
}
Species* Population::getSpecies(void) { return pSpecies; }
int Population::getNbInds() const {
return inds.size();
}
int Population::getNbInds(int stg) const {
int t = 0;
if (stg < 0 || stg >= nStages) throw runtime_error("Attempt to get nb individuals for stage " + to_string(stg) + ", no such stage.");
for (int sex = 0; sex < nSexes; sex++) {
t += nInds[stg][sex];
}
return t;
}
int Population::getNbInds(int stg, int sex) const {
if (stg < 0 || stg >= nStages) throw runtime_error("Attempt to get nb individuals for stage " + to_string(stg) + ", no such stage.");
return nInds[stg][sex];
}
//---------------------------------------------------------------------------
// Remove all Individuals
void Population::extirpate(void) {
int ninds = (int)inds.size();
for (int i = 0; i < ninds; i++) {
if (inds[i] != NULL) delete inds[i];
}
inds.clear();
int njuvs = (int)juvs.size();
for (int i = 0; i < njuvs; i++) {
if (juvs[i] != NULL) delete juvs[i];
}
juvs.clear();
for (int sex = 0; sex < nSexes; sex++) {
for (int stg = 0; stg < nStages; stg++) {
nInds[stg][sex] = 0;
}
}
}
//---------------------------------------------------------------------------
// Produce juveniles and hold them in the juvs vector
void Population::reproduction(const float localK, const float envval, const int resol, std::vector <float> localDemoScaling)
{
// get population size at start of reproduction
int ninds = (int)inds.size();
if (ninds == 0) return;
int nsexes, stage, sex, njuvs, nj, nmales, nfemales;
Cell* pCell;
indStats ind;
double expected;
bool skipbreeding;
envStochParams env = paramsStoch->getStoch();
demogrParams dem = pSpecies->getDemogrParams();
stageParams sstruct = pSpecies->getStageParams();
emigRules emig = pSpecies->getEmigRules();
transferRules trfr = pSpecies->getTransferRules();
settleType sett = pSpecies->getSettle();
if (dem.repType == 0)
nsexes = 1;
else nsexes = 2;
// set up local copy of species fecundity table
float fec[gMaxNbStages][gMaxNbSexes];
for (int stg = 0; stg < sstruct.nStages; stg++) {
for (int sex = 0; sex < nsexes; sex++) {
if (dem.stageStruct) {
if (dem.repType == 1) { // simple sexual model
// both sexes use fecundity recorded for females
if (pSpecies->getFecSpatial() && pSpecies->getFecLayer(stg,0)>=0){
fec[stg][sex] = pSpecies->getFec(stg,0)*localDemoScaling[pSpecies->getFecLayer(stg,0)];
}
else fec[stg][sex] = pSpecies->getFec(stg,0);
}
else {
if (pSpecies->getFecSpatial() && pSpecies->getFecLayer(stg,sex)>=0){
fec[stg][sex] = pSpecies->getFec(stg,sex)*localDemoScaling[pSpecies->getFecLayer(stg,sex)];
}
else fec[stg][sex] = pSpecies->getFec(stg, sex);
}
}
else { // non-structured population
if (stg == 1) fec[stg][sex] = dem.lambda; // adults
else fec[stg][sex] = 0.0; // juveniles
}
}
}
if (dem.stageStruct) {
// apply environmental effects and density dependence
// to all non-zero female non-juvenile stages
for (int stg = 1; stg < nStages; stg++) {
if (fec[stg][0] > 0.0) {
// apply any effect of environmental gradient and/or stochasticty
fec[stg][0] *= envval;
if (env.stoch && !env.inK) {
// fecundity (at low density) is constrained to lie between limits specified
// for the species
float limit;
limit = pSpecies->getMinMax(0);
if (fec[stg][0] < limit) fec[stg][0] = limit;
limit = pSpecies->getMinMax(1);
if (fec[stg][0] > limit) fec[stg][0] = limit;
}
if (sstruct.fecDens) { // apply density dependence
float effect = 0.0;
if (sstruct.fecStageDens) { // stage-specific density dependence
// NOTE: matrix entries represent effect of ROW on COLUMN
// AND males precede females
float weight = 0.0;
for (int effstg = 0; effstg < nStages; effstg++) {
for (int effsex = 0; effsex < nSexes; effsex++) {
if (dem.repType == 2) {
if (effsex == 0) weight = pSpecies->getDDwtFec(2 * stg + 1, 2 * effstg + 1);
else weight = pSpecies->getDDwtFec(2 * stg + 1, 2 * effstg);
}
else {
weight = pSpecies->getDDwtFec(stg, effstg);
}
effect += (float)nInds[effstg][effsex] * weight;
}
}
}
else // not stage-specific
effect = (float)getNbInds();
if (localK > 0.0) fec[stg][0] *= exp(-effect / localK);
}
}
}
}
else { // non-structured - set fecundity for adult females only
// apply any effect of environmental gradient and/or stochasticty
fec[1][0] *= envval;
if (env.stoch && !env.inK) {
// fecundity (at low density) is constrained to lie between limits specified
// for the species
float limit;
limit = pSpecies->getMinMax(0);
if (fec[1][0] < limit) fec[1][0] = limit;
limit = pSpecies->getMinMax(1);
if (fec[1][0] > limit) fec[1][0] = limit;
}
// apply density dependence
if (localK > 0.0) {
if (dem.repType == 1 || dem.repType == 2) { // sexual model
// apply factor of 2 (as in manual, eqn. 6)
fec[1][0] *= 2.0;
}
fec[1][0] /= (1.0f + fabs(dem.lambda - 1.0f) * pow(((float)ninds / localK), dem.bc));
}
}
double propBreed;
Individual* father = nullptr;
std::vector <Individual*> fathers;
switch (dem.repType) {
case 0: // asexual model
for (int i = 0; i < ninds; i++) {
stage = inds[i]->breedingFem();
if (stage > 0) { // female of breeding age
if (dem.stageStruct) {
// determine whether she must miss current breeding attempt
ind = inds[i]->getStats();
if (ind.fallow >= sstruct.repInterval) {
if (pRandom->Bernoulli(sstruct.probRep)) skipbreeding = false;
else skipbreeding = true;
}
else skipbreeding = true; // cannot breed this time
}
else skipbreeding = false; // not structured - always breed
if (skipbreeding) {
inds[i]->incFallow();
}
else { // attempt to breed
inds[i]->resetFallow();
expected = fec[stage][0];
if (expected <= 0.0) njuvs = 0;
else njuvs = pRandom->Poisson(expected);
nj = (int)juvs.size();
pCell = pPatch->getRandomCell();
for (int j = 0; j < njuvs; j++) {
Individual* newJuv;
newJuv = new Individual(pSpecies, pCell, pPatch, 0, 0, 0, dem.propMales, trfr.usesMovtProc, trfr.moveType);
if (pSpecies->getNTraits() > 0) {
newJuv->inheritTraits(pSpecies, inds[i], resol);
}
if (!newJuv->isViable()) {
delete newJuv;
}
else {
juvs.push_back(newJuv);
nInds[0][0]++;
}
}
}
}
}
break;
case 1: // simple sexual model
case 2: // complex sexual model
// count breeding females and males
// add breeding males to list of potential fathers
nfemales = nmales = 0;
for (int i = 0; i < ninds; i++) {
ind = inds[i]->getStats();
if (ind.sex == 0 && fec[ind.stage][0] > 0.0) nfemales++;
if (ind.sex == 1 && fec[ind.stage][1] > 0.0) {
fathers.push_back(inds[i]);
nmales++;
}
}
if (nfemales > 0 && nmales > 0)
{ // population can breed
if (dem.repType == 2) { // complex sexual model
// calculate proportion of eligible females which breed
propBreed = (2.0 * dem.harem * nmales) / (nfemales + dem.harem * nmales);
if (propBreed > 1.0) propBreed = 1.0;
}
else propBreed = 1.0;
for (int i = 0; i < ninds; i++) {
stage = inds[i]->breedingFem();
if (stage > 0 && fec[stage][0] > 0.0) { // (potential) breeding female
if (dem.stageStruct) {
// determine whether she must miss current breeding attempt
ind = inds[i]->getStats();
if (ind.fallow >= sstruct.repInterval) {
if (pRandom->Bernoulli(sstruct.probRep)) skipbreeding = false;
else skipbreeding = true;
}
else skipbreeding = true; // cannot breed this time
}
else skipbreeding = false; // not structured - always breed
if (skipbreeding) {
inds[i]->incFallow();
}
else { // attempt to breed
inds[i]->resetFallow();
// NOTE: FOR COMPLEX SEXUAL MODEL, NO. OF FEMALES *ACTUALLY* BREEDING DOES NOT
// NECESSARILY EQUAL THE EXPECTED NO. FROM EQN. 7 IN THE MANUAL...
if (pRandom->Bernoulli(propBreed)) {
expected = fec[stage][0]; // breeds
}
else expected = 0.0; // fails to breed
if (expected <= 0.0) njuvs = 0;
else njuvs = pRandom->Poisson(expected);
if (njuvs > 0)
{
nj = (int)juvs.size();
// select father at random from breeding males ...
int rrr = 0;
if (nmales > 1) rrr = pRandom->IRandom(0, nmales - 1);
father = fathers[rrr];
pCell = pPatch->getRandomCell();
for (int j = 0; j < njuvs; j++) {
Individual* newJuv;
newJuv = new Individual(pSpecies, pCell, pPatch, 0, 0, 0, dem.propMales, trfr.usesMovtProc, trfr.moveType);
if (pSpecies->getNTraits() > 0) {
newJuv->inheritTraits(pSpecies, inds[i], father, resol);
}
if (!newJuv->isViable()) {
delete newJuv;
}
else {
juvs.push_back(newJuv);
sex = newJuv->getSex();
nInds[0][sex]++;
}
}
}
}
}
}
}
fathers.clear();
break;
} // end of switch (dem.repType)
// THIS MAY NOT BE CORRECT FOR MULTIPLE SPECIES IF THERE IS SOME FORM OF
// CROSS-SPECIES DENSITY-DEPENDENT FECUNDITY
}
// Following reproduction of ALL species, add juveniles to the population prior to dispersal
void Population::fledge(void)
{
demogrParams dem = pSpecies->getDemogrParams();
if (dem.stageStruct) { // juveniles are added to the individuals vector
inds.insert(inds.end(), juvs.begin(), juvs.end());
}
else { // all adults die and juveniles replace adults
int ninds = (int)inds.size();
for (int i = 0; i < ninds; i++) {
delete inds[i];
}
inds.clear();
for (int sex = 0; sex < nSexes; sex++) {
nInds[1][sex] = 0; // set count of adults to zero
}
inds = std::move(juvs);
}
juvs.clear();
}
Individual* Population::sampleInd() const {
int index = pRandom->IRandom(0, static_cast<int>(inds.size() - 1));
return inds[index];
}
void Population::sampleIndsWithoutReplacement(string strNbToSample, const set<int>& sampleStages) {
if (sampledInds.size() > 0) {
sampledInds.clear();
}
auto rng = pRandom->getRNG();
vector<Individual*> stagedInds;
// Stage individuals in eligible stages
for (int stage : sampleStages) {
vector<Individual*> toAdd = getIndividualsInStage(stage);
stagedInds.insert(stagedInds.begin(), toAdd.begin(), toAdd.end());
}
if (strNbToSample == "all") {
// Sample all individuals in selected stages
sampledInds = stagedInds;
}
else { // random
int nbToSample = stoi(strNbToSample);
if (stagedInds.size() <= nbToSample) {
// Sample all individuals in selected stages
sampledInds = stagedInds;
}
else {
// Sample n individuals across selected stages
sample(stagedInds.begin(), stagedInds.end(), std::back_inserter(sampledInds), nbToSample, rng);
}
}
}
int Population::sampleSize() const {
return static_cast<int>(sampledInds.size());
}
vector<Individual*> Population::getIndividualsInStage(int stage) {
vector<Individual*> indsInStage;
for (auto ind : inds) {
if (ind->getStats().stage == stage)
indsInStage.push_back(ind);
}
return indsInStage;
}
// Determine which individuals will disperse
void Population::emigration(float localK)
{
int nsexes;
double disp, pbDisp, NK;
demogrParams dem = pSpecies->getDemogrParams();
stageParams sstruct = pSpecies->getStageParams();
emigRules emig = pSpecies->getEmigRules();
emigTraits eparams;
transferRules trfr = pSpecies->getTransferRules();
indStats ind;
// to avoid division by zero, assume carrying capacity is at least one individual
// localK can be zero if there is a moving gradient or stochasticity in K
if (localK < 1.0) localK = 1.0;
NK = static_cast<float>(getNbInds()) / localK;
int ninds = static_cast<int>(inds.size());
// set up local copy of emigration probability table
// used when there is no individual variability
// NB - IT IS DOUBTFUL THIS CONTRIBUTES ANY SUBSTANTIAL TIME SAVING
if (dem.repType == 0) nsexes = 1;
else nsexes = 2;
double pbEmig[gMaxNbStages][gMaxNbSexes];
for (int stg = 0; stg < sstruct.nStages; stg++) {
for (int sex = 0; sex < nsexes; sex++) {
if (emig.indVar) pbEmig[stg][sex] = 0.0;
else {
if (emig.densDep) {
if (emig.sexDep) {
if (emig.stgDep) {
eparams = pSpecies->getSpEmigTraits(stg, sex);
}
else {
eparams = pSpecies->getSpEmigTraits(0, sex);
}
}
else { // !emig.sexDep
if (emig.stgDep) {
eparams = pSpecies->getSpEmigTraits(stg, 0);
}
else {
eparams = pSpecies->getSpEmigTraits(0, 0);
}
}
pbEmig[stg][sex] = eparams.d0 / (1.0 + exp(-(NK - eparams.beta) * eparams.alpha));
}
else { // density-independent
if (emig.sexDep) {
if (emig.stgDep) {
pbEmig[stg][sex] = pSpecies->getSpEmigD0(stg, sex);
}
else { // !emig.stgDep
pbEmig[stg][sex] = pSpecies->getSpEmigD0(0, sex);
}
}
else { // !emig.sexDep
if (emig.stgDep) {
pbEmig[stg][sex] = pSpecies->getSpEmigD0(stg, 0);
}
else { // !emig.stgDep
pbEmig[stg][sex] = pSpecies->getSpEmigD0(0, 0);
}
}
}
} // end of !emig.indVar
}
}
for (int i = 0; i < ninds; i++) {
ind = inds[i]->getStats();
if (ind.status < 1) // ToDo: Maybe allow dispersal after translocation? If so, we need to update the pPrevCell and pCurrCell variables of the translocated individuals!
{
if (emig.indVar) { // individual variability in emigration
if (dem.stageStruct && ind.stage != emig.emigStage) {
// emigration may not occur
pbDisp = 0.0;
}
else { // non-structured or individual is in emigration stage
eparams = inds[i]->getIndEmigTraits();
if (emig.densDep) { // density-dependent
NK = (float)getNbInds() / localK;
pbDisp = eparams.d0 / (1.0 + exp(-(NK - eparams.beta) * eparams.alpha));
}
else { // density-independent
if (emig.sexDep) {
pbDisp = pbEmig[0][ind.sex] + eparams.d0;
}
else {
pbDisp = pbEmig[0][0] + eparams.d0;
}
}
}
} // end of individual variability
else { // no individual variability
if (emig.densDep) {
if (emig.sexDep) {
if (emig.stgDep) {
pbDisp = pbEmig[ind.stage][ind.sex];
}
else {
pbDisp = pbEmig[0][ind.sex];
}
}
else { // !emig.sexDep
if (emig.stgDep) {
pbDisp = pbEmig[ind.stage][0];
}
else {
pbDisp = pbEmig[0][0];
}
}
}
else { // density-independent
if (emig.sexDep) {
if (emig.stgDep) {
pbDisp = pbEmig[ind.stage][ind.sex];
}
else { // !emig.stgDep
pbDisp = pbEmig[0][ind.sex];
}
}
else { // !emig.sexDep
if (emig.stgDep) {
pbDisp = pbEmig[ind.stage][0];
}
else { // !emig.stgDep
pbDisp = pbEmig[0][0];
}
}
}
} // end of no individual variability
disp = pRandom->Bernoulli(pbDisp);
if (disp == 1) { // emigrant
inds[i]->setStatus(1);
}
} // end of if (ind.status < 1) condition
} // end of for loop
}
// All individuals emigrate after patch destruction