-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNeutralTrait.cpp
More file actions
341 lines (292 loc) · 14.2 KB
/
NeutralTrait.cpp
File metadata and controls
341 lines (292 loc) · 14.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
/*----------------------------------------------------------------------------
*
* 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/>.
*
* File Created by Roslyn Henry March 2023. Code adapted from NEMO (https://nemo2.sourceforge.io/)
--------------------------------------------------------------------------*/
#include "NeutralTrait.h"
// ----------------------------------------------------------------------------------------
// Initialisation constructor
// Called when initialising community
// Sets up initial values, and immutable attributes (distributions and parameters)
// that are defined at the species-level
// ----------------------------------------------------------------------------------------
NeutralTrait::NeutralTrait(SpeciesTrait* P)
{
pSpeciesTrait = P;
DistributionType mutationDistribution = pSpeciesTrait->getMutationDistribution();
map<GenParamType, float> mutationParameters = pSpeciesTrait->getMutationParameters();
// Set default value to user-specified max
wildType = (int)mutationParameters.find(MAX)->second;
if (wildType > NeutralValUpperBound)
throw logic_error("max number of alleles cannot exceed " + to_string(NeutralValUpperBound) + ".\n");
_inherit_func_ptr = (pSpeciesTrait->getPloidy() == 1) ? &NeutralTrait::inheritHaploid : &NeutralTrait::inheritDiploid; //this could be changed if we wanted some alternative form of inheritance
if (mutationDistribution == SSM)
_mutate_func_ptr = &NeutralTrait::mutate_SSM;
if (mutationDistribution == KAM)
_mutate_func_ptr = &NeutralTrait::mutate_KAM;
if (mutationDistribution != SSM && mutationDistribution != KAM)
throw logic_error("wrong mutation distribution for neutral markers, must be KAM or SSM \n");
if (mutationParameters.count(MAX) != 1)
throw logic_error("KAM or SSM mutation distribution parameter must contain max value (e.g. max= ), max cannot exceed 256 \n");
DistributionType initialDistribution = pSpeciesTrait->getInitialDistribution();
map<GenParamType, float> initialParameters = pSpeciesTrait->getInitialParameters();
if (mutationDistribution == SSM && initialDistribution != UNIFORM)
throw logic_error("If using SSM mutation model for neutral trait, must use uniform initial distribution.\n");
switch (initialDistribution) {
case UNIFORM:
{
if (initialParameters.count(MAX) != 1)
throw logic_error("initial distribution parameter must contain one max value if set to UNIFORM (e.g. max= ), max cannot exceed " + to_string(NeutralValUpperBound) + "\n");
float maxNeutralVal = initialParameters.find(MAX)->second;
if (maxNeutralVal > NeutralValUpperBound) {
throw logic_error("initial distribution parameter max cannot exceed " + to_string(NeutralValUpperBound) + ", resetting to " + to_string(NeutralValUpperBound) + "\n");
maxNeutralVal = NeutralValUpperBound; //reserve 255 for wildtype
}
initialiseUniform(maxNeutralVal);
break;
}
default:
{
throw logic_error("wrong parameter value for parameter \"initialisation of neutral trait\", must be left uniform \n");
break; //should return false
}
}
}
// ----------------------------------------------------------------------------------------
// Inheritance constructor
// Copies immutable features from a parent trait
// Only called via clone()
// ----------------------------------------------------------------------------------------
NeutralTrait::NeutralTrait(const NeutralTrait& T) :
pSpeciesTrait(T.pSpeciesTrait), _mutate_func_ptr(T._mutate_func_ptr), _inherit_func_ptr(T._inherit_func_ptr) {
}
// ----------------------------------------------------------------------------------------
// mutate options
// ----------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------
// Draw and apply mutations according to a KAM process
//
// Mutations drawn only for existing positions,
// that is no new genes are created during simulation
// KAM = randomly drawn value in 0-MAX, differs from previous value
// ----------------------------------------------------------------------------------------
void NeutralTrait::mutate_KAM()
{
const int positionsSize = pSpeciesTrait->getPositionsSize();
const auto& genePositions = pSpeciesTrait->getGenePositions();
const short ploidy = pSpeciesTrait->getPloidy();
const float mutationRate = pSpeciesTrait->getMutationRate();
auto rng = pRandom->getRNG();
unsigned char mut;
map<GenParamType, float> mutationParameters = pSpeciesTrait->getMutationParameters();
int maxNeutralVal = (int)mutationParameters.find(MAX)->second;
if (maxNeutralVal > NeutralValUpperBound) maxNeutralVal = NeutralValUpperBound; //reserve max value for wildtype
for (int whichChromosome = 0; whichChromosome < ploidy; whichChromosome++) {
unsigned int NbMut = pRandom->Binomial(positionsSize, mutationRate);
if (NbMut > 0) {
vector<int> mutationPositions;
sample(genePositions.begin(), genePositions.end(), std::back_inserter(mutationPositions),
NbMut, rng); // without replacement
for (int m : mutationPositions) {
mut = (unsigned char)pRandom->IRandom(0, maxNeutralVal); // draw new mutation, could draw wildtype
auto it = genes.find(m);
if (it == genes.end())
throw runtime_error("Locus selected for mutation doesn't exist.");
auto currentChar = it->second[whichChromosome]; // current allele
if (maxNeutralVal > 0) { // dodge the infinite loop
do {
mut = (unsigned char)pRandom->IRandom(0, maxNeutralVal);
} while (mut == currentChar); // new allele value is different
}
else mut = 0;
it->second[whichChromosome] = mut; //overwrite with new value
}
}
}
}
// ----------------------------------------------------------------------------------------
// Draw and apply single-step mutations (SSM)
//
// Mutations drawn only for existing positions,
// that is no new genes are created during simulation
// Increment previous value by 1 or -1,
// unless already 0 (then always +1) or MAX (then always -1)
// ----------------------------------------------------------------------------------------
void NeutralTrait::mutate_SSM()
{
const int positionsSize = pSpeciesTrait->getPositionsSize();
const auto& genePositions = pSpeciesTrait->getGenePositions();
const short ploidy = pSpeciesTrait->getPloidy();
const float mutationRate = pSpeciesTrait->getMutationRate();
auto rng = pRandom->getRNG();
map<GenParamType, float> mutationParameters = pSpeciesTrait->getMutationParameters();
int maxNeutralVal = (int)mutationParameters.find(MAX)->second;
if (maxNeutralVal > NeutralValUpperBound) maxNeutralVal = NeutralValUpperBound; //reserved max value for wildtype
for (int whichChromosome = 0; whichChromosome < ploidy; whichChromosome++) {
unsigned int NbMut = pRandom->Binomial(positionsSize, mutationRate);
if (NbMut > 0) {
vector<int> mutationPositions;
sample(genePositions.begin(), genePositions.end(), std::back_inserter(mutationPositions),
NbMut, rng);
for (int m : mutationPositions) {
int mutateUp = pRandom->Bernoulli(0.5);
auto it = genes.find(m);
if (it == genes.end())
throw runtime_error("Locus selected for mutation doesn't exist.");
auto currentAllele = it->second[whichChromosome];
if (mutateUp == 1 && currentAllele < maxNeutralVal)
it->second[whichChromosome] += 1; // one step up
else if (currentAllele > 0) // step down or already max
it->second[whichChromosome] -= 1; // one step down
else // current allele is 0, step up
it->second[whichChromosome] += 1;
}
}
}
}
// ----------------------------------------------------------------------------------------
// Wrapper to inheritance function
// ----------------------------------------------------------------------------------------
void NeutralTrait::inheritGenes(const bool& fromMother, QuantitativeTrait* parent, set<unsigned int> const& recomPositions, int startingChromosome)
{
auto parentCast = dynamic_cast<NeutralTrait*> (parent); // must convert QuantitativeTrait to NeutralTrait
const auto& parent_seq = parentCast->getGenes();
(this->*_inherit_func_ptr) (fromMother, parent_seq, recomPositions, startingChromosome);
}
// ----------------------------------------------------------------------------------------
// Inheritance for diploid, sexual species
// Called once for each parent. Given a list of recombinant sites,
// populates offspring genes with appropriate parent alleles
// Assumes mother genes are inherited first
// ----------------------------------------------------------------------------------------
void NeutralTrait::inheritDiploid(const bool& fromMother, map<int, vector<unsigned char>> const& parentGenes, set<unsigned int> const& recomPositions, int parentChromosome) {
const int lastPosition = parentGenes.rbegin()->first;
auto recomIt = recomPositions.lower_bound(parentGenes.begin()->first);
// If no recombination sites, only breakpoint is last position
// i.e., no recombination occurs
int nextBreakpoint = recomIt == recomPositions.end() ? lastPosition : *recomIt;
// Is the first parent gene position already recombinant?
auto distance = std::distance(recomPositions.begin(), recomIt);
if (distance % 2 != 0)
parentChromosome = 1 - parentChromosome; //switch chromosome
for (auto const& [locus, allelePair] : parentGenes) {
// Switch chromosome if locus is past recombination site
while (locus > nextBreakpoint) {
parentChromosome = 1 - parentChromosome;
std::advance(recomIt, 1); // go to next recombination site
nextBreakpoint = recomIt == recomPositions.end() ? lastPosition : *recomIt;
}
if (locus <= nextBreakpoint) {
unsigned char parentAllele = allelePair[parentChromosome];
auto it = genes.find(locus);
if (it == genes.end()) {
// locus does not exist yet, create and initialise it
if (!fromMother) throw runtime_error("Father-inherited locus does not exist.");
vector<unsigned char> newAllelePair(2, wildType);
newAllelePair[sex_t::FEM] = parentAllele;
genes.insert(make_pair(locus, newAllelePair));
}
else { // father, locus already exists
if (fromMother) throw runtime_error("Mother-inherited locus already exists.");
it->second[sex_t::MAL] = parentAllele;
}
}
}
}
// ----------------------------------------------------------------------------------------
// Inheritance for haploid, asexual species
// Simply pass down parent genes
// Arguments are still needed to match overloaded function in base class
// ----------------------------------------------------------------------------------------
void NeutralTrait::inheritHaploid(const bool& fromMother, map<int, vector<unsigned char>> const& parentGenes, set<unsigned int> const& recomPositions, int parentChromosome)
{
genes = parentGenes;
}
// ----------------------------------------------------------------------------------------
// Initialise neutral loci
// ----------------------------------------------------------------------------------------
void NeutralTrait::initialiseUniform(int maxAlleleVal)
{
const auto& genePositions = pSpeciesTrait->getGenePositions();
const auto& initPositions = pSpeciesTrait->getInitPositions();
short ploidy = pSpeciesTrait->getPloidy();
for (auto position : genePositions) {
vector<unsigned char> allelePair;
for (int i = 0; i < ploidy; i++) {
unsigned char alleleVal = char(0);
if (initPositions.contains(position)) {
// allele values span 0 - max inclusive, max is wildtype
alleleVal = (unsigned char)pRandom->IRandom(0, maxAlleleVal);
}
allelePair.emplace_back(alleleVal);
}
genes.insert(make_pair(position, allelePair));
}
}
// ----------------------------------------------------------------------------------------
// Check if particular loci is heterozygote
// ----------------------------------------------------------------------------------------
bool NeutralTrait::isHeterozygoteAtLocus(int locus) const {
// assumes diploidy
auto it = genes.find(locus);
if (it == genes.end())
throw runtime_error("Neutral gene queried for heterozygosity does not exist.");
else
return(it->second[0] != it->second[1]);
}
// ----------------------------------------------------------------------------------------
// Count heterozygote loci in genome
// ----------------------------------------------------------------------------------------
int NeutralTrait::countHeterozygoteLoci() const {
// assumes diploidy
int count = 0;
for (auto const& [locus, allelePair] : genes) {
count += (allelePair[0] != allelePair[1]);
}
return count;
}
// ----------------------------------------------------------------------------------------
// Get allele value at loci
// ----------------------------------------------------------------------------------------
float NeutralTrait::getAlleleValueAtLocus(short whichChromosome, int position) const {
auto it = genes.find(position);
if (it == genes.end()) //no mutations there
throw runtime_error("The neutral locus queried for its allele value does not exist.");
return it->second[whichChromosome];
}
#ifdef UNIT_TESTS // Testing only
// Create a default set of neutral alleles for testing
//
// Shorthand function to manually set genotypes for neutral
// traits, instead of having to manipulate mutations.
map<int, vector<unsigned char>> createTestNeutralGenotype(
const int genomeSz, const bool isDiploid,
const unsigned char valAlleleA,
const unsigned char valAlleleB
) {
vector<unsigned char> gene(isDiploid ? 2 : 1);
gene[0] = valAlleleA;
if (isDiploid) gene[1] = valAlleleB;
map<int, vector<unsigned char>> genotype;
for (int i = 0; i < genomeSz; i++) {
genotype.emplace(i, gene);
}
return genotype;
}
#endif // UNIT_TESTS