-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIndividual.cpp
More file actions
1748 lines (1541 loc) · 53.2 KB
/
Individual.cpp
File metadata and controls
1748 lines (1541 loc) · 53.2 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 "Individual.h"
#ifdef _OPENMP
#include <mutex>
#endif
//---------------------------------------------------------------------------
template <typename T>
MemoryQueue<T>::MemoryQueue(std::size_t size):
space(size),
data(new T[size]),
begin_idx(0),
nb_elts(0)
{ }
template <typename T>
T &MemoryQueue<T>::front() {
return data[begin_idx];
}
template <typename T>
T const &MemoryQueue<T>::front() const {
return data[begin_idx];
}
template <typename T>
T &MemoryQueue<T>::back() {
return data[(begin_idx + nb_elts - 1) % space];
}
template <typename T>
T const &MemoryQueue<T>::back() const {
return data[(begin_idx + nb_elts - 1) % space];
}
template <typename T>
void MemoryQueue<T>::push(const T& value) {
size_t end_idx = (begin_idx + nb_elts) % space;
data[end_idx] = value;
nb_elts++;
}
template <typename T>
void MemoryQueue<T>::push(T&& value) {
size_t end_idx = (begin_idx + nb_elts) % space;
data[end_idx] = std::move(value);
nb_elts++;
}
template <typename T>
void MemoryQueue<T>::pop() {
begin_idx++;
begin_idx %= space;
nb_elts--;
}
template <typename T>
std::size_t MemoryQueue<T>::size() const {
return nb_elts;
}
template <typename T>
bool MemoryQueue<T>::empty() const {
return nb_elts == 0;
}
template <typename T>
bool MemoryQueue<T>::full() const {
return nb_elts == space;
}
//---------------------------------------------------------------------------
#ifdef _OPENMP
std::atomic<int> Individual::indCounter = 0;
#else // _OPENMP
int Individual::indCounter = 0;
#endif // _OPENMP
TraitFactory Individual::traitFactory = TraitFactory();
//---------------------------------------------------------------------------
// Individual constructor
Individual::Individual(Species* pSpecies, Cell* pCell, Patch* pPatch, short stg, short a, short repInt,
float probmale, bool movt, short moveType):
memory(pSpecies->getSpSMSTraits().memSize)
{
indId = indCounter; indCounter++; // unique identifier for each individual
geneticFitness = 1.0;
stage = stg;
if (probmale <= 0.0) sex = FEM;
else sex = pRandom->Bernoulli(probmale) ? MAL : FEM;
age = a;
status = 0;
if (sex == 0 && repInt > 0) { // set no. of fallow seasons for female
fallow = pRandom->IRandom(0, repInt);
}
else fallow = 9999;
isDeveloping = false;
pPrevCell = pCurrCell = pCell;
pNatalPatch = pPatch;
pTrfrData = nullptr; //set to null as default
if (movt) {
locn loc = pCell->getLocn();
path = new pathData;
path->year = 0; path->total = 0; path->out = 0;
path->pSettPatch = 0; path->settleStatus = 0;
#if RS_RCPP
path->pathoutput = 1;
#endif
if (moveType == 1) { // SMS
// set up location data for SMS
pTrfrData = make_unique<smsData>(loc, loc);
}
if (moveType == 2) { // CRW
// set up continuous co-ordinates etc. for CRW movement
float xc = ((float)pRandom->Random() * 0.999f) + (float)loc.x;
float yc = (float)(pRandom->Random() * 0.999f) + (float)loc.y;
float prevdrn = (float)(pRandom->Random() * 2.0 * PI);
pTrfrData = make_unique<crwData>(prevdrn, xc, yc);
}
}
else {
path = 0;
pTrfrData = make_unique<kernelData>(0.0, 0.0, 0.0);
}
}
Individual::~Individual(void) {
if (path != 0) delete path;
}
void Individual::setEmigTraits(const emigTraits& emig) {
pEmigTraits = make_unique<emigTraits>(emig);
}
void Individual::setSettleTraits(const settleTraits& settle) {
pSettleTraits = make_unique<settleTraits>(settle);
}
QuantitativeTrait* Individual::getTrait(TraitType trait) const {
auto p = this->spTraitTable.find(trait);
if (p == spTraitTable.end())
throw runtime_error("Trait does not exist in trait table.");
else return p->second.get();
}
set<TraitType> Individual::getTraitTypes() {
auto kv = std::views::keys(this->spTraitTable);
set< TraitType > keys{ kv.begin(), kv.end() };
return keys;
}
//---------------------------------------------------------------------------
// Inheritance for diploid, sexual species
//---------------------------------------------------------------------------
void Individual::inherit(Species* pSpecies, const Individual* mother, const Individual* father) {
int events = 0;
const set<int> chromosomeEnds = pSpecies->getChromosomeEnds();
const int genomeSize = pSpecies->getGenomeSize();
int maternalStartingChromosome = pRandom->Bernoulli(0.5);
int paternalStartingChromosome = pRandom->Bernoulli(0.5);
set<unsigned int> maternalRecomPositions;
set<unsigned int> paternalRecomPositions;
// Determine which parental chromosomes are inherited
for (int pos : chromosomeEnds) {
if (pRandom->Bernoulli(0.5)) // switch strand for next chromosome
maternalRecomPositions.insert(pos);
if (pRandom->Bernoulli(0.5))
paternalRecomPositions.insert(pos);
}
// Draw recombination events for maternal genome
if (pSpecies->getRecombinationRate() > 0.0)
events = pRandom->Binomial(genomeSize, pSpecies->getRecombinationRate());
// if poisson exceeds genomeSize, bound to genomeSize
int nbrCrossOvers = events + maternalRecomPositions.size();
if (nbrCrossOvers > genomeSize) {
nbrCrossOvers = genomeSize;
}
while (maternalRecomPositions.size() < nbrCrossOvers) {
// Sample recombination sites
maternalRecomPositions.insert(pRandom->IRandom(0, genomeSize));
}
// Draw recombination events for paternal genome
if (pSpecies->getRecombinationRate() > 0.0)
events = pRandom->Binomial(genomeSize, pSpecies->getRecombinationRate());
nbrCrossOvers = events + paternalRecomPositions.size();
if (nbrCrossOvers > genomeSize) {
nbrCrossOvers = genomeSize;
}
while (paternalRecomPositions.size() < nbrCrossOvers) {
paternalRecomPositions.insert(pRandom->IRandom(0, genomeSize));
}
// Inherit genes for each trait
const auto& spTraits = pSpecies->getTraitTypes();
for (auto const& trait : spTraits)
{
const auto motherTrait = mother->getTrait(trait);
const auto fatherTrait = father->getTrait(trait);
auto newTrait = motherTrait->clone(); // shallow copy pointer to species-level attributes
// Inherit from mother first
newTrait->inheritGenes(true, motherTrait, maternalRecomPositions, maternalStartingChromosome);
if (newTrait->isInherited()) {
// Inherit father trait values
newTrait->inheritGenes(false, fatherTrait, paternalRecomPositions, paternalStartingChromosome);
if (newTrait->getMutationRate() > 0 && pSpecies->areMutationsOn())
newTrait->mutate();
}
if (trait == GENETIC_LOAD1 || trait == GENETIC_LOAD2 || trait == GENETIC_LOAD3 || trait == GENETIC_LOAD4 || trait == GENETIC_LOAD5)
geneticFitness *= newTrait->express();
// Add the inherited trait and genes to the newborn's list
spTraitTable.insert(make_pair(trait, move(newTrait)));
}
}
//---------------------------------------------------------------------------
// Inheritance for haploid, asexual species
//---------------------------------------------------------------------------
void Individual::inherit(Species* pSpecies, const Individual* mother) {
set<unsigned int> recomPositions; //not used here cos haploid but need it for inherit function, not ideal
int startingChromosome = 0;
const auto& spTraits = pSpecies->getTraitTypes();
for (auto const& trait : spTraits)
{
const auto motherTrait = mother->getTrait(trait);
auto newTrait = motherTrait->clone(); // shallow copy, pointer to species trait initialised and empty sequence
newTrait->inheritGenes(true, motherTrait, recomPositions, startingChromosome);
if (newTrait->isInherited()) {
if (newTrait->getMutationRate() > 0 && pSpecies->areMutationsOn())
newTrait->mutate();
}
if (trait == GENETIC_LOAD1 || trait == GENETIC_LOAD2 || trait == GENETIC_LOAD3 || trait == GENETIC_LOAD4 || trait == GENETIC_LOAD5)
geneticFitness *= newTrait->express();
// Add the inherited trait and genes to the newborn's list
spTraitTable.insert(make_pair(trait, move(newTrait)));
}
}
// Initialise individual trait genes from species-level traits
void Individual::setUpGenes(Species* pSpecies, int resol) {
// this way to keep spp trait table immutable i.e. not able to call getTraitTable,
// could pass it back by value (copy) instead but could be heavy if large map
const auto& traitTypes = pSpecies->getTraitTypes();
for (auto const& traitType : traitTypes)
{
const auto spTrait = pSpecies->getSpTrait(traitType);
this->spTraitTable.emplace(traitType, traitFactory.Create(traitType, spTrait));
}
expressDispersalPhenotypes(pSpecies, resol);
expressGeneticLoad(pSpecies);
}
void Individual::expressDispersalPhenotypes(Species* pSpecies, int resol) {
const emigRules emig = pSpecies->getEmigRules();
const transferRules trfr = pSpecies->getTransferRules();
const settleType sett = pSpecies->getSettle();
const settleRules settRules = pSpecies->getSettRules(stage, sex);
// record phenotypic traits
if (emig.indVar) setEmigTraits(pSpecies, emig.sexDep, emig.densDep);
if (trfr.indVar) setTransferTraits(pSpecies, trfr, resol);
if (sett.indVar) setSettlementTraits(pSpecies, sett.sexDep, settRules.densDep);
}
// Set the fitness attribute of individuals
// Only called at initialisation, otherwise probably faster to compute directly during inheritance
void Individual::expressGeneticLoad(Species* pSpecies) {
const int nbGenLoadTraits = pSpecies->getNbGenLoadTraits();
const vector<TraitType> whichTrait = { GENETIC_LOAD1 , GENETIC_LOAD2, GENETIC_LOAD3, GENETIC_LOAD4, GENETIC_LOAD5 };
for (int i = 0; i < nbGenLoadTraits; i++) {
if (spTraitTable.contains(whichTrait[i]))
geneticFitness *= getTrait(whichTrait[i])->express();
}
}
void Individual::setTransferTraits(Species* pSpecies, transferRules trfr, int resol) {
if (trfr.usesMovtProc) {
if (trfr.moveType == 1) {
setIndSMSTraits(pSpecies);
}
else setIndCRWTraits(pSpecies);
}
else setIndKernelTraits(pSpecies, trfr.sexDep, trfr.twinKern, resol);
}
void Individual::setSettlementTraits(Species* pSpecies, bool sexDep, bool densDep) {
settleTraits s; s.s0 = s.alpha = s.beta = 0.0;
if (sexDep) {
if (this->getSex() == MAL) {
s.s0 = getTrait(S_S0_M)->express();
if (densDep) {
s.alpha = getTrait(S_ALPHA_M)->express();
s.beta = getTrait(S_BETA_M)->express();
}
}
else if (this->getSex() == FEM) {
s.s0 = getTrait(S_S0_F)->express();
if (densDep) {
s.alpha = getTrait(S_ALPHA_F)->express();
s.beta = getTrait(S_BETA_F)->express();
}
}
else {
throw runtime_error("Attempt to express invalid emigration trait sex.");
}
}
else {
s.s0 = getTrait(S_S0)->express();
if (densDep) {
s.alpha = getTrait(S_ALPHA)->express();
s.beta = getTrait(S_BETA)->express();
}
}
pSettleTraits = make_unique<settleTraits>();
pSettleTraits->s0 = (float)(s.s0);
pSettleTraits->alpha = (float)(s.alpha);
pSettleTraits->beta = (float)(s.beta);
if (pSettleTraits->s0 < 0.0) pSettleTraits->s0 = 0.0;
if (pSettleTraits->s0 > 1.0) pSettleTraits->s0 = 1.0;
return;
}
// Inherit genome from parent(s), diploid
void Individual::inheritTraits(Species* pSpecies, Individual* mother, Individual* father, int resol)
{
inherit(pSpecies, mother, father);
expressDispersalPhenotypes(pSpecies, resol);
}
// Inherit genome from mother, haploid
void Individual::inheritTraits(Species* pSpecies, Individual* mother, int resol)
{
inherit(pSpecies, mother);
expressDispersalPhenotypes(pSpecies, resol);
}
//---------------------------------------------------------------------------
// Identify whether an individual is a potentially breeding female -
// if so, return her stage, otherwise return 0
int Individual::breedingFem(void) {
if (sex == FEM) {
if (status == 0 || status == 4 || status == 5 || status == 10) return stage;
else return 0;
}
else return 0;
}
int Individual::getId(void) { return indId; }
sex_t Individual::getSex(void) { return sex; }
int Individual::getStatus(void) { return status; }
float Individual::getGeneticFitness(void) { return geneticFitness; }
bool Individual::isViable() const {
float probViability = geneticFitness > 1.0 ? 1.0 : geneticFitness;
return probViability >= pRandom->Random();
}
indStats Individual::getStats(void) {
indStats s;
s.stage = stage; s.sex = sex; s.age = age; s.status = status; s.fallow = fallow;
s.isDeveloping = isDeveloping;
return s;
}
Cell* Individual::getPrevCell() {
return pPrevCell;
}
Cell* Individual::getCurrCell() {
return pCurrCell;
}
Patch* Individual::getNatalPatch(void) { return pNatalPatch; }
void Individual::setYearSteps(int t) {
if (path != 0 && t >= 0) {
if (t >= 0) path->year = t;
else path->year = 666;
}
}
pathSteps Individual::getSteps(void) {
pathSteps s;
if (path == 0) {
s.year = 0; s.total = 0; s.out = 0;
}
else {
s.year = path->year; s.total = path->total; s.out = path->out;
}
return s;
}
settlePatch Individual::getSettPatch(void) {
settlePatch s;
if (path == 0) {
s.pSettPatch = 0; s.settleStatus = 0;
}
else {
s.pSettPatch = path->pSettPatch; s.settleStatus = path->settleStatus;
}
return s;
}
void Individual::setSettPatch(const settlePatch s) {
if (path == 0) {
path = new pathData;
path->year = 0; path->total = 0; path->out = 0; path->settleStatus = 0;
#if RS_RCPP
path->pathoutput = 1;
#endif
}
if (s.settleStatus >= 0 && s.settleStatus <= 2) path->settleStatus = s.settleStatus;
path->pSettPatch = s.pSettPatch;
}
void Individual::setEmigTraits(Species* pSpecies, bool sexDep, bool densityDep) {
emigTraits e;
e.d0 = e.alpha = e.beta = 0.0;
if (sexDep) {
if (this->getSex() == MAL) {
e.d0 = this->getTrait(E_D0_M)->express();
if (densityDep) {
e.alpha = getTrait(E_ALPHA_M)->express();
e.beta = getTrait(E_BETA_M)->express();
}
}
else if (this->getSex() == FEM) {
e.d0 = this->getTrait(E_D0_F)->express();
if (densityDep) {
e.alpha = getTrait(E_ALPHA_F)->express();
e.beta = getTrait(E_BETA_F)->express();
}
}
else {
throw runtime_error("Attempt to express invalid emigration trait sex.");
}
}
else {
e.d0 = this->getTrait(E_D0)->express();
if (densityDep) {
e.alpha = getTrait(E_ALPHA)->express();
e.beta = getTrait(E_BETA)->express();
}
}
pEmigTraits = make_unique<emigTraits>();
pEmigTraits->d0 = e.d0;
pEmigTraits->alpha = e.alpha;
pEmigTraits->beta = e.beta;
// Below must never trigger, phenotype is bounded in express()
if (pEmigTraits->d0 < 0.0) throw runtime_error("d0 value has become negative.");
if (pEmigTraits->d0 > 1.0) throw runtime_error("d0 value has exceeded 1.");
return;
}
// Get phenotypic emigration traits
emigTraits Individual::getIndEmigTraits(void) {
emigTraits e;
e.d0 = e.alpha = e.beta = 0.0;
if (pEmigTraits != 0) {
e.d0 = pEmigTraits->d0;
e.alpha = pEmigTraits->alpha;
e.beta = pEmigTraits->beta;
}
return e;
}
// Set phenotypic transfer by kernel traits
void Individual::setIndKernelTraits(Species* pSpecies, bool sexDep, bool twinKernel, int resol) {
trfrKernelParams k;
k.meanDist1 = k.meanDist2 = k.probKern1 = 0.0;
if (sexDep) {
if (this->sex == MAL) {
k.meanDist1 = getTrait(KERNEL_MEANDIST_1_M)->express();
if (twinKernel) { // twin kernel
k.meanDist2 = getTrait(KERNEL_MEANDIST_2_M)->express();
k.probKern1 = getTrait(KERNEL_PROBABILITY_M)->express();
}
}
else if (this->sex == FEM) {
k.meanDist1 = getTrait(KERNEL_MEANDIST_1_F)->express();
if (twinKernel) { // twin kernel
k.meanDist2 = getTrait(KERNEL_MEANDIST_2_F)->express();
k.probKern1 = getTrait(KERNEL_PROBABILITY_F)->express();
}
}
else {
throw runtime_error("Attempt to express invalid kernel transfer trait sex.");
}
}
else {
k.meanDist1 = getTrait(KERNEL_MEANDIST_1)->express();
if (twinKernel) { // twin kernel
k.meanDist2 = getTrait(KERNEL_MEANDIST_2)->express();
k.probKern1 = getTrait(KERNEL_PROBABILITY)->express();
}
}
float meanDist1 = (float)(k.meanDist1);
float meanDist2 = (float)(k.meanDist2);
float probKern1 = (float)(k.probKern1);
if (!pSpecies->useFullKernel()) {
// kernel mean(s) may not be less than landscape resolution
if (meanDist1 < resol) meanDist1 = (float)resol;
if (meanDist2 < resol) meanDist2 = (float)resol;
}
if (probKern1 < 0.0) probKern1 = 0.0;
if (probKern1 > 1.0) probKern1 = 1.0;
auto& pKernel = dynamic_cast<kernelData&>(*pTrfrData);
pKernel.meanDist1 = meanDist1;
pKernel.meanDist2 = meanDist2;
pKernel.probKern1 = probKern1;
return;
}
// Get phenotypic emigration traits
trfrKernelParams Individual::getIndKernTraits(void) {
trfrKernelParams k; k.meanDist1 = k.meanDist2 = k.probKern1 = 0.0;
if (pTrfrData != 0) {
auto& pKernel = dynamic_cast<const kernelData&>(*pTrfrData);
k.meanDist1 = pKernel.meanDist1;
k.meanDist2 = pKernel.meanDist2;
k.probKern1 = pKernel.probKern1;
}
return k;
}
void Individual::setIndSMSTraits(Species* pSpecies) {
trfrSMSTraits s = pSpecies->getSpSMSTraits();
double dp, gb, alphaDB, betaDB;
dp = gb = alphaDB = betaDB = 0.0;
dp = getTrait(SMS_DP)->express();
if (s.goalType == 2) {
gb = getTrait(SMS_GB)->express();
alphaDB = getTrait(SMS_ALPHADB)->express();
betaDB = getTrait(SMS_BETADB)->express();
}
auto& pSMS = dynamic_cast<smsData&>(*pTrfrData);
pSMS.dp = (float)(dp);
pSMS.gb = (float)(gb);
if (s.goalType == 2) {
pSMS.alphaDB = (float)(alphaDB);
pSMS.betaDB = (int)(betaDB);
}
else {
pSMS.alphaDB = s.alphaDB;
pSMS.betaDB = s.betaDB;
}
if (pSMS.dp < 1.0) pSMS.dp = 1.0;
if (pSMS.gb < 1.0) pSMS.gb = 1.0;
if (pSMS.alphaDB <= 0.0) pSMS.alphaDB = 0.000001f;
if (pSMS.betaDB < 1) pSMS.betaDB = 1;
return;
}
trfrData* Individual::getTrfrData(void) {
return pTrfrData.get();
}
// Get phenotypic transfer by SMS traits
trfrSMSTraits Individual::getIndSMSTraits(void) {
trfrSMSTraits s; s.dp = s.gb = s.alphaDB = 1.0; s.betaDB = 1;
if (pTrfrData != 0) {
auto& pSMS = dynamic_cast<const smsData&>(*pTrfrData);
s.dp = pSMS.dp; s.gb = pSMS.gb;
s.alphaDB = pSMS.alphaDB; s.betaDB = pSMS.betaDB;
}
return s;
}
// Set phenotypic transfer by CRW traits
void Individual::setIndCRWTraits(Species* pSpecies) {
trfrCRWTraits c; c.stepLength = c.rho = 0.0;
c.stepLength = getTrait(CRW_STEPLENGTH)->express();
c.rho = getTrait(CRW_STEPCORRELATION)->express();
auto& pCRW = dynamic_cast<crwData&>(*pTrfrData);
pCRW.stepLength = (float)(c.stepLength);
pCRW.rho = (float)(c.rho);
if (pCRW.stepLength < 1.0) pCRW.stepLength = 1.0;
if (pCRW.rho < 0.0) pCRW.rho = 0.0;
if (pCRW.rho > 0.999) pCRW.rho = 0.999f;
return;
}
// Get phenotypic transfer by CRW traits
trfrCRWTraits Individual::getIndCRWTraits(void) {
trfrCRWTraits c;
c.stepLength = c.rho = 0.0;
if (pTrfrData != 0) {
auto& pCRW = dynamic_cast<const crwData&>(*pTrfrData);
c.stepLength = pCRW.stepLength;
c.rho = pCRW.rho;
}
return c;
}
// Get phenotypic settlement traits
settleTraits Individual::getIndSettTraits(void) {
settleTraits s; s.s0 = s.alpha = s.beta = 0.0;
if (pSettleTraits != 0) {
s.s0 = pSettleTraits->s0;
s.alpha = pSettleTraits->alpha;
s.beta = pSettleTraits->beta;
}
return s;
}
void Individual::setStatus(short s) {
if (s >= 0 && s <= 10) status = s;
status = s;
}
void Individual::setToDevelop(void) {
isDeveloping = true;
}
void Individual::develop(void) {
stage++; isDeveloping = false;
}
void Individual::ageIncrement(short maxage) {
if (status < 6 || status == 10) { // alive
age++;
if (age > maxage) status = 9; // exceeds max. age - dies
else {
if (path != 0) path->year = 0; // reset annual step count for movement models
if (status == 3) // waiting to continue dispersal
status = 1;
}
}
}
void Individual::incFallow(void) { fallow++; }
void Individual::resetFallow(void) { fallow = 0; }
//---------------------------------------------------------------------------
// Move to a specified neighbouring cell
void Individual::moveto(Cell* newCell) {
// check that location is indeed a neighbour of the current cell
locn currloc = pCurrCell->getLocn();
locn newloc = newCell->getLocn();
double d = sqrt(((double)currloc.x - (double)newloc.x) * ((double)currloc.x - (double)newloc.x)
+ ((double)currloc.y - (double)newloc.y) * ((double)currloc.y - (double)newloc.y));
if (d >= 1.0 && d < 1.5) { // ok
pCurrCell = newCell; status = 5;
}
}
//---------------------------------------------------------------------------
// Move to a new cell by sampling a dispersal distance from a single or double
// negative exponential kernel
// Returns 1 if still dispersing (including having found a potential patch), otherwise 0
int Individual::moveKernel(Landscape* pLandscape, Species* pSpecies, const bool absorbing)
{
int patchNum = 0;
int newX = 0, newY = 0;
int dispersing = 1;
double xrand, yrand, meandist, dist, r1, rndangle, nx, ny;
float localK;
trfrKernelParams kern;
Cell* pCell;
Patch* pPatch;
locn loc = pCurrCell->getLocn();
landData land = pLandscape->getLandData();
bool usefullkernel = pSpecies->useFullKernel();
transferRules trfr = pSpecies->getTransferRules();
settleRules sett = pSpecies->getSettRules(stage, sex);
pCell = NULL;
pPatch = NULL;
if (trfr.indVar) { // get individual's kernel parameters
kern.meanDist1 = kern.meanDist2 = kern.probKern1 = 0.0;
auto& pKernel = dynamic_cast<const kernelData&>(*pTrfrData);
kern.meanDist1 = pKernel.meanDist1;
if (trfr.twinKern)
{
kern.meanDist2 = pKernel.meanDist2;
kern.probKern1 = pKernel.probKern1;
}
}
else { // get kernel parameters for the species
if (trfr.sexDep) {
if (trfr.stgDep) {
kern = pSpecies->getSpKernTraits(stage, sex);
}
else {
kern = pSpecies->getSpKernTraits(0, sex);
}
}
else {
if (trfr.stgDep) {
kern = pSpecies->getSpKernTraits(stage, 0);
}
else {
kern = pSpecies->getSpKernTraits(0, 0);
}
}
}
// scale the appropriate kernel mean to the cell size
if (trfr.twinKern)
{
if (pRandom->Bernoulli(kern.probKern1))
meandist = kern.meanDist1 / (float)land.resol;
else
meandist = kern.meanDist2 / (float)land.resol;
}
else
meandist = kern.meanDist1 / (float)land.resol;
// scaled mean may not be less than 1 unless emigration derives from the kernel
// (i.e. the 'use full kernel' option is applied)
# ifdef NDEBUG // bypass this requirement for tests
if (!usefullkernel && meandist < 1.0) meandist = 1.0;
# endif
int loopsteps = 0; // new counter to prevent infinite loop added 14/8/15
do {
do {
do {
// randomise the cell within the patch, provided that the individual is still in
// its natal cell (i.e. not waiting in the matrix)
// this is because, if the patch is very large, the individual is near the centre
// and the (single) kernel mean is (not much more than) the cell size, an infinite
// loop could otherwise result, as the individual never reaches the patch edge
// (in a cell-based model, this has no effect, other than as a processing overhead)
if (status == 1) {
pCell = pNatalPatch->getRandomCell();
if (pCell != 0) {
loc = pCell->getLocn();
}
}
// randomise the position of the individual inside the cell
// so x and y are a corner of the cell?
xrand = (double)loc.x + pRandom->Random() * 0.999;
yrand = (double)loc.y + pRandom->Random() * 0.999;
// draw factor r1 0 < r1 <= 1
r1 = 0.0000001 + pRandom->Random() * (1.0 - 0.0000001);
dist = (-1.0 * meandist) * log(r1);
rndangle = pRandom->Random() * 2.0 * PI;
nx = xrand + dist * sin(rndangle);
ny = yrand + dist * cos(rndangle);
if (nx < 0.0) newX = -1; else newX = (int)nx;
if (ny < 0.0) newY = -1; else newY = (int)ny;
#ifndef NDEBUG
if (path != 0) (path->year)++;
#endif
loopsteps++;
} while (loopsteps < 1000 &&
// keep drawing if out of bounds of landscape or same cell
((!absorbing
&& (newX < land.minX || newX > land.maxX || newY < land.minY || newY > land.maxY))
|| (!usefullkernel && newX == loc.x && newY == loc.y))
);
if (loopsteps < 1000) {
if (newX < land.minX || newX > land.maxX
|| newY < land.minY || newY > land.maxY) { // beyond absorbing boundary
// this cannot be reached if not absorbing?
pCell = 0;
pPatch = nullptr;
patchNum = -1;
}
else {
pCell = pLandscape->findCell(newX, newY);
if (pCell == 0) { // no-data cell
pPatch = nullptr;
patchNum = -1;
}
else {
pPatch = pCell->getPatch();
if (pPatch == nullptr) { // matrix
patchNum = 0;
}
else {
patchNum = pPatch->getPatchNum();
}
}
}
}
else { // exceeded 1000 attempts
pPatch = nullptr;
patchNum = -1;
}
} while (!absorbing && patchNum < 0 && loopsteps < 1000); // in a no-data region
} while (!usefullkernel && pPatch == pNatalPatch && loopsteps < 1000); // still in the original (natal) patch
if (loopsteps < 1000) {
if (pCell == 0) { // beyond absorbing boundary or in no-data cell
// only if absorbing=true and out of bounddaries
pCurrCell = 0;
status = 6;
dispersing = 0;
}
else {
pCurrCell = pCell;
if (pPatch == 0) localK = 0.0; // matrix
else localK = pPatch->getK();
if (patchNum > 0 && localK > 0.0) { // found a new patch
status = 2; // record as potential settler
}
else {
// unsuitable patch
dispersing = 0;
// can wait in matrix if population is stage structured ...
if (pSpecies->stageStructured()) {
// ... and wait option is applied ...
if (sett.wait) { // ... it is
status = 3; // waiting
}
else // ... it is not
status = 6; // dies (unless there is a suitable neighbouring cell)
}
else status = 6; // dies (unless there is a suitable neighbouring cell)
}
}
}
else { // exceeded 1000 attempts
status = 6;
dispersing = 0;
}
// apply dispersal-related mortality, which may be distance-dependent
dist *= (float)land.resol; // re-scale distance moved to landscape scale
if (status < 7 || status == 10) {
double dispmort;
trfrMortParams mort = pSpecies->getMortParams();
if (trfr.distMort) {
dispmort = 1.0 / (1.0 + exp(-(dist - mort.mortBeta) * mort.mortAlpha));
}
else {
dispmort = mort.fixedMort;
}
if (pRandom->Bernoulli(dispmort)) {
status = 7; // dies
dispersing = 0;
}
}
return dispersing;
}
//---------------------------------------------------------------------------
// Make a single movement step according to a mechanistic movement model
// Returns 1 if still dispersing (including having found a potential patch), otherwise 0
int Individual::moveStep(Landscape* pLandscape, Species* pSpecies,
const short landIx, const bool absorbing)
{
if (status != 1) return 0; // not currently dispersing
int patchNum;
int newX, newY;
locn loc;
int dispersing = 1;
double xcnew, ycnew;
double angle;
double mortprob, rho, steplen;
movedata move;
Patch* pPatch = nullptr;
bool absorbed = false;
//int popsize;
landData land = pLandscape->getLandData();
simParams sim = paramsSim->getSim();
transferRules trfr = pSpecies->getTransferRules();
trfrCRWTraits movt = pSpecies->getSpCRWTraits();
settleSteps settsteps = pSpecies->getSteps(stage, sex);
pPatch = pCurrCell->getPatch();
if (pPatch == nullptr) { // matrix
patchNum = 0;
}
else {
patchNum = pPatch->getPatchNum();
}
// apply step-dependent mortality risk ...
if (trfr.habMort)
{ // habitat-dependent
int h = pCurrCell->getHabIndex(landIx);
if (h < 0) { // no-data cell - should not occur, but if it does, individual dies
mortprob = 1.0;
}
else mortprob = pSpecies->getHabMort(h);
}
else mortprob = movt.stepMort;
// ... unless individual has not yet left natal patch in emigration year
if (pPatch == pNatalPatch && path->out == 0 && path->year == path->total) {
mortprob = 0.0;
}
if (pRandom->Bernoulli(mortprob)) { // individual dies
status = 7;
dispersing = 0;
}
else { // take a step
(path->year)++;
(path->total)++;
if (pPatch == nullptr || patchNum == 0) { // not in a patch
if (path != 0) path->settleStatus = 0; // reset path settlement status
(path->out)++;
}
loc = pCurrCell->getLocn();
newX = loc.x; newY = loc.y;
switch (trfr.moveType) {
case 1: // SMS
move = smsMove(pLandscape, pSpecies, landIx, pPatch == pNatalPatch, trfr.indVar, absorbing);
if (move.dist < 0.0) {
// either INTERNAL ERROR CONDITION - INDIVIDUAL IS IN NO-DATA SQUARE
// or individual has crossed absorbing boundary ...
// ... individual dies
status = 6;
dispersing = 0;
}