forked from millanek/Dsuite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Dsuite_utils.cpp
433 lines (384 loc) · 16 KB
/
Dsuite_utils.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
//
// Dsuite_utils.cpp
// Dsuite
//
// Created by Milan Malinsky on 02/04/2019.
// Copyright © 2019 Milan Malinsky. All rights reserved.
//
#include "Dsuite_utils.h"
double normalCDF(double x) // Phi(-∞, x) aka N(x)
{
return erfc(-x/std::sqrt(2))/2;
}
double Fd_Denom_perVariant(double p1, double p2, double p3, double pO) {
double Fd_Denom = 0;
if (p2 > p3) Fd_Denom = ((1-p1)*p2*p2*(1-pO)) - (p1*(1-p2)*p2*(1-pO));
else Fd_Denom = ((1-p1)*p3*p3*(1-pO)) - (p1*(1-p3)*p3*(1-pO));
return Fd_Denom;
}
double fG_Denom_perVariant(double p1, double p3a, double p3b, double pO) {
double fG_Denom = ((1-p1)*p3a*p3b*(1-pO)) - (p1*(1-p3a)*p3b*(1-pO));
return fG_Denom;
}
double FdM_Denom_perVariant(double p1, double p2, double p3, double pO) {
double FdM_Denom = 0;
if (p1 <= p2) {
if (p2 > p3) FdM_Denom = ((1-p1) * p2 * p2 * (1-pO)) - (p1 * (1-p2) * p2 * (1-pO));
else FdM_Denom = ((1-p1) * p3 * p3 * (1-pO)) - (p1 * (1-p3) * p3 * (1-pO));
} else {
if (p1 > p3) FdM_Denom = -(((1-p1)*p2*p1*(1-pO)) - (p1*(1-p2)*p1*(1-pO)));
else FdM_Denom = -(((1-p3)*p2*p3*(1-pO)) - (p3*(1-p2)*p3*(1-pO)));
}
return FdM_Denom;
}
// Works only on biallelic markers
void GeneralSetCounts::getSetVariantCounts(const std::vector<std::string>& genotypes, const std::map<size_t, string>& posToSpeciesMap) {
getBasicCounts(genotypes, posToSpeciesMap);
// If at least one of the outgroup individuals has non-missing data
// Find out what is the "ancestral allele" - i.e. the one more common in the outgroup
int AAint;
try {
if (setAlleleCounts.at("Outgroup") > 0) {
if ((double)setAltCounts.at("Outgroup")/setAlleleCounts.at("Outgroup") < 0.5) { AAint = 0; }
else { AAint = 1; }
}
} catch (std::out_of_range& e) { AAint = -1; }
// Now fill in the allele frequencies
for(std::map<string,int>::iterator it = setAltCounts.begin(); it != setAltCounts.end(); ++it) {
if (setAlleleCounts.at(it->first) > 0) {
setAAFs[it->first] = (double)setAltCounts.at(it->first)/setAlleleCounts.at(it->first);
if (AAint == 0) { // Ancestral allele seems to be the ref, so derived is alt
setDAFs[it->first] = (double)setAltCounts.at(it->first)/setAlleleCounts.at(it->first);
} else if (AAint == 1) { // Ancestral allele seems to be alt, so derived is ref
setDAFs[it->first] = 1 - ((double)setAltCounts.at(it->first)/setAlleleCounts.at(it->first));
}
}
}
}
// Works only on biallelic markers
void GeneralSetCounts::getSetVariantCountsSimple(const std::vector<std::string>& genotypes, const std::map<size_t, string>& posToSpeciesMap) {
// std::cerr << fields[0] << "\t" << fields[1] << std::endl;
getBasicCounts(genotypes, posToSpeciesMap);
// Now fill in the allele frequencies
for(std::map<string,int>::iterator it = setAltCounts.begin(); it != setAltCounts.end(); ++it) {
if (setAlleleCounts.at(it->first) > 0) {
setAAFs[it->first] = (double)setAltCounts.at(it->first)/setAlleleCounts.at(it->first);
}
}
}
void GeneralSetCounts::getBasicCounts(const std::vector<std::string>& genotypes, const std::map<size_t, string>& posToSpeciesMap) {
// Go through the genotypes - only biallelic markers are allowed
for (std::vector<std::string>::size_type i = 0; i != genotypes.size(); i++) {
bool speciesDefined = true;
std::string species; try { species = posToSpeciesMap.at(i); } catch (const std::out_of_range& oor) {
speciesDefined = false;
}
// The first allele in this individual
if (genotypes[i][0] == '1') { overall++; individualsWithVariant[i]++; }
if (genotypes[i][2] == '1') { overall++; individualsWithVariant[i]++; }
if (speciesDefined) {
if (genotypes[i][0] == '1') {
setAltCounts[species]++; setAlleleCounts[species]++;
} else if (genotypes[i][0] == '0') {
setAlleleCounts[species]++;
}
// The second allele in this individual
if (genotypes[i][2] == '1') {
setAltCounts[species]++; setAlleleCounts[species]++;
} else if (genotypes[i][2] == '0') {
setAlleleCounts[species]++;
}
}
}
}
void GeneralSetCountsWithSplits::getBasicCountsWithSplits(const std::vector<std::string>& genotypes, const std::map<size_t, string>& posToSpeciesMap) {
// Go through the genotypes - only biallelic markers are allowed
for (std::vector<std::string>::size_type i = 0; i != genotypes.size(); i++) {
double r = ((double) rand() / (RAND_MAX)); bool speciesDefined = true;
std::string species; try { species = posToSpeciesMap.at(i); } catch (const std::out_of_range& oor) {
speciesDefined = false;
}
// The first allele in this individual
if (genotypes[i][0] == '1') { overall++; individualsWithVariant[i]++; }
if (speciesDefined) {
if (genotypes[i][0] == '1') {
setAltCounts[species]++; setAlleleCounts[species]++;
if (r < 0.5) {
setAltCountsSplit1[species]++; setAlleleCountsSplit1[species]++;
} else {
setAltCountsSplit2[species]++; setAlleleCountsSplit2[species]++;
}
} else if (genotypes[i][0] == '0') {
setAlleleCounts[species]++;
if (r < 0.5) {
setAlleleCountsSplit1[species]++;
} else {
setAlleleCountsSplit2[species]++;
}
}
}
// The second allele in this individual
if (genotypes[i][2] == '1') { overall++; individualsWithVariant[i]++; }
if (speciesDefined) {
if (genotypes[i][2] == '1') {
setAltCounts[species]++; setAlleleCounts[species]++;
if (r < 0.5) {
setAltCountsSplit1[species]++; setAlleleCountsSplit1[species]++;
} else {
setAltCountsSplit2[species]++; setAlleleCountsSplit2[species]++;
}
} else if (genotypes[i][2] == '0') {
setAlleleCounts[species]++;
if (r < 0.5) {
setAlleleCountsSplit1[species]++;
} else {
setAlleleCountsSplit2[species]++;
}
}
}
}
}
void GeneralSetCountsWithSplits::getSplitCounts(const std::vector<std::string>& genotypes, const std::map<size_t, string>& posToSpeciesMap) {
getBasicCountsWithSplits(genotypes, posToSpeciesMap);
// If at least one of the outgroup individuals has non-missing data
// Find out what is the "ancestral allele" - i.e. the one more common in the outgroup
int AAint;
try {
if (setAlleleCounts.at("Outgroup") > 0) {
if ((double)setAltCounts.at("Outgroup")/setAlleleCounts.at("Outgroup") < 0.5) { AAint = 0; }
else { AAint = 1; }
}
} catch (std::out_of_range& e) { AAint = -1; }
// Now fill in the allele frequencies
for(std::map<string,int>::iterator it = setAltCounts.begin(); it != setAltCounts.end(); ++it) {
if (it->first == "") {
std::cerr << "it->first " << it->first << "\t" << it->second << std::endl;
}
if (setAlleleCounts.at(it->first) > 0) {
int nSplit1; int nSplit2;
setAAFs[it->first] = (double)setAltCounts.at(it->first)/setAlleleCounts.at(it->first);
nSplit1 = setAlleleCountsSplit1.at(it->first); nSplit2 = setAlleleCountsSplit2.at(it->first);
// std::cerr << "it->first " << it->first << std::endl;
try {
if (nSplit1 > 0)
setAAFsplit1[it->first] = (double)setAltCountsSplit1.at(it->first)/nSplit1;
if (nSplit2 > 0)
setAAFsplit2[it->first] = (double)setAltCountsSplit2.at(it->first)/nSplit2;
if (AAint == 0) { // Ancestral allele seems to be the ref, so derived is alt
setDAFs[it->first] = (double)setAltCounts.at(it->first)/setAlleleCounts.at(it->first);
if (nSplit1 > 0)
setDAFsplit1[it->first] = (double)setAltCountsSplit1.at(it->first)/nSplit1;
if (nSplit2 > 0)
setDAFsplit2[it->first] = (double)setAltCountsSplit2.at(it->first)/nSplit2;
} else if (AAint == 1) { // Ancestral allele seems to be alt, so derived is ref
setDAFs[it->first] = 1 - ((double)setAltCounts.at(it->first)/setAlleleCounts.at(it->first));
if (nSplit1 > 0)
setDAFsplit1[it->first] = 1 - ((double)setAltCountsSplit1.at(it->first)/nSplit1);
if (nSplit2 > 0)
setDAFsplit2[it->first] = 1 - ((double)setAltCountsSplit2.at(it->first)/nSplit2);
}
} catch (std::out_of_range& e) { std::cerr << "The trouble was here" << it->first << std::endl; }
}
}
}
double calculateOneDs(double ABBAtotal, double BABAtotal) {
// Get the D values
double Dnum1 = ABBAtotal - BABAtotal;
double Ddenom1 = ABBAtotal + BABAtotal;
double D = Dnum1/Ddenom1;
return D;
}
double* calculateThreeDs(double ABBAtotal, double BABAtotal, double BBAAtotal) {
// Get the D values
double Dnum1 = ABBAtotal - BABAtotal;
double Dnum2 = ABBAtotal - BBAAtotal;
double Dnum3 = BBAAtotal - BABAtotal;
double Ddenom1 = ABBAtotal + BABAtotal;
double Ddenom2 = ABBAtotal + BBAAtotal;
double Ddenom3 = BBAAtotal + BABAtotal;
static double Ds[3]; Ds[0] = Dnum1/Ddenom1; Ds[1] = Dnum2/Ddenom2; Ds[2] = Dnum3/Ddenom3;
return Ds;
}
double stringToDouble(std::string s) {
double d;
std::stringstream ss(s); //turn the string into a stream
ss >> d; //convert
return d;
}
// Remove a single file extension from the filename
std::string stripExtension(const std::string& filename)
{
size_t suffixPos = filename.find_last_of('.');
if(suffixPos == std::string::npos)
return filename; // no suffix
else
return filename.substr(0, suffixPos);
}
void split(const std::string &s, char delim, std::vector<std::string> &elems) {
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, delim)) {
elems.push_back(item);
}
}
std::vector<std::string> split(const std::string &s, char delim) {
std::vector<std::string> elems;
split(s, delim, elems);
return elems;
}
std::vector<std::string> split2(std::string s, string delim) {
std::vector<std::string> elems;
size_t pos = 0;
std::string token;
while ((pos = s.find(delim)) != std::string::npos) {
token = s.substr(0, pos);
elems.push_back(token);
s.erase(0, pos + delim.length());
}
elems.push_back(s);
return elems;
}
std::vector<size_t> locateSet(std::vector<std::string>& sample_names, const std::vector<std::string>& set) {
std::vector<size_t> setLocs;
for (std::vector<std::string>::size_type i = 0; i != set.size(); i++) {
std::vector<std::string>::iterator it = std::find(sample_names.begin(), sample_names.end(), set[i]);
if (it == sample_names.end()) {
std::cerr << "Did not find the sample: \"" << set[i] << "\"" << std::endl;
std::cerr << "Did not find the sample: \"" << sample_names[43] << "\"" << std::endl;
print_vector(sample_names, std::cerr,',');
} else {
size_t loc = std::distance(sample_names.begin(), it);
setLocs.push_back(loc);
}
}
return setLocs;
}
//
std::string suffix(const std::string& seq, size_t len)
{
assert(seq.length() >= len);
return seq.substr(seq.length() - len);
}
// Returns true if the filename has an extension indicating it is compressed
bool isGzip(const std::string& filename)
{
size_t suffix_length = sizeof(GZIP_EXT) - 1;
// Assume files without an extension are not compressed
if(filename.length() < suffix_length)
return false;
std::string extension = suffix(filename, suffix_length);
return extension == GZIP_EXT;
}
// Ensure a filehandle is open
void assertFileOpen(std::ifstream& fh, const std::string& fn)
{
if(!fh.is_open())
{
std::cerr << "Error: could not open " << fn << " for read\n";
exit(EXIT_FAILURE);
}
}
// Ensure a filehandle is open
void assertFileOpen(std::ofstream& fh, const std::string& fn)
{
if(!fh.is_open())
{
std::cerr << "Error: could not open " << fn << " for write\n";
exit(EXIT_FAILURE);
}
}
void assertGZOpen(gzstreambase& gh, const std::string& fn)
{
if(!gh.good())
{
std::cerr << "Error: could not open " << fn << std::endl;
exit(EXIT_FAILURE);
}
}
// Open a file that may or may not be gzipped for reading
// The caller is responsible for freeing the handle
std::istream* createReader(const std::string& filename, std::ios_base::openmode mode)
{
if(isGzip(filename))
{
igzstream* pGZ = new igzstream(filename.c_str(), mode);
assertGZOpen(*pGZ, filename);
return pGZ;
}
else
{
std::ifstream* pReader = new std::ifstream(filename.c_str(), mode);
assertFileOpen(*pReader, filename);
return pReader;
}
}
// Open a file that may or may not be gzipped for writing
// The caller is responsible for freeing the handle
std::ostream* createWriter(const std::string& filename,
std::ios_base::openmode mode)
{
if(isGzip(filename))
{
ogzstream* pGZ = new ogzstream(filename.c_str(), mode);
assertGZOpen(*pGZ, filename);
return pGZ;
}
else
{
std::ofstream* pWriter = new std::ofstream(filename.c_str(), mode);
assertFileOpen(*pWriter, filename);
return pWriter;
}
}
bool file_exists(const std::string& name) {
std::ifstream f(name.c_str());
return f.good();
}
void assignTreeLevelsAndLinkToTaxa(string& treeLine, std::map<string,std::vector<int>>& taxaToLoc, std::vector<int>& levels) {
// First take care of any branch lengths
std::regex branchLengths(":.*?(?=,|\\))");
treeLine = std::regex_replace(treeLine,branchLengths,"");
//std::cerr << line << std::endl;
// Now process the tree
levels.assign(treeLine.length(),0); int currentLevel = 0;
std::vector<string> treeTaxonNames;
string currentTaxonName = "";
int lastBegin = 0;
for (int i = 0; i < treeLine.length(); ++i) {
if (treeLine[i] == '(') {
currentLevel++; levels[i] = currentLevel;
} else if (treeLine[i] == ')') {
currentLevel--; levels[i] = currentLevel;
if (currentTaxonName != "") {
treeTaxonNames.push_back(currentTaxonName);
taxaToLoc[currentTaxonName].push_back(lastBegin);
taxaToLoc[currentTaxonName].push_back(i-1);
currentTaxonName = "";
}
} else if (treeLine[i] == ',') {
levels[i] = currentLevel;
if (currentTaxonName != "") {
treeTaxonNames.push_back(currentTaxonName);
taxaToLoc[currentTaxonName].push_back(lastBegin);
taxaToLoc[currentTaxonName].push_back(i-1);
currentTaxonName = "";
}
} else {
if (currentTaxonName == "")
lastBegin = i;
levels[i] = currentLevel;
currentTaxonName += treeLine[i];
}
}
//print_vector(treeTaxonNames, std::cout,'\n');
//print_vector(treeLevels, std::cout,' ');
//for (std::map<string,std::vector<int>>::iterator i = treeTaxonNamesToLoc.begin(); i != treeTaxonNamesToLoc.end(); i++) {
// std::cout << i->first << "\t" << i->second[0] << "\t" << i->second[1] << "\t" << treeLevels[i->second[0]] << "\t" << treeLevels[i->second[1]] << std::endl;
//}
}
void assignSplits01FromAlleleFrequency(const double p, double& splitA, double& splitB) {
double r = ((double) rand() / (RAND_MAX));
if (r <= p) { splitA = 1; }
double r2 = ((double) rand() / (RAND_MAX));
if (r2 <= p) { splitB = 1; }
}