/
Util.cpp
444 lines (392 loc) · 11.3 KB
/
Util.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
434
435
436
437
438
439
440
441
442
443
//-----------------------------------------------
// Copyright 2009 Wellcome Trust Sanger Institute
// Written by Jared Simpson (js18@sanger.ac.uk)
// Released under the GPL
//-----------------------------------------------
//
// Util - Common data structures and functions
//
#include <iostream>
#include <math.h>
#include <map>
#include "Util.h"
//
// Sequence operations
//
// Reverse complement a sequence
std::string reverseComplement(const std::string& seq)
{
std::string out(seq.length(), 'A');
size_t last_pos = seq.length() - 1;
for(int i = last_pos; i >= 0; --i)
{
out[last_pos - i] = complement(seq[i]);
}
return out;
}
// Reverse complement a sequence using the full iupac alphabet
std::string reverseComplementIUPAC(const std::string& seq)
{
std::string out(seq.length(), 'A');
size_t last_pos = seq.length() - 1;
for(int i = last_pos; i >= 0; --i)
{
out[last_pos - i] = complementIUPAC(seq[i]);
}
return out;
}
// Reverse a sequence
std::string reverse(const std::string& seq)
{
return std::string(seq.rbegin(), seq.rend());
}
// Complement a sequence
std::string complement(const std::string& seq)
{
std::string out(seq.length(), 'A');
size_t l = seq.length();
for(size_t i = 0; i < l; ++i)
out[i] = complement(seq[i]);
return out;
}
// Complement a sequence over the IUPAC alphabet
std::string complementIUPAC(const std::string& seq)
{
std::string out(seq.length(), 'A');
size_t l = seq.length();
for(size_t i = 0; i < l; ++i)
out[i] = complementIUPAC(seq[i]);
return out;
}
//
std::string prefix(const std::string& seq, const unsigned int len)
{
assert(seq.length() >= len);
return seq.substr(0, len);
}
//
std::string suffix(const std::string& seq, const unsigned int len)
{
assert(seq.length() >= len);
return seq.substr(seq.length() - len);
}
//
// Dust scoring scheme as given by:
// Morgulis A. "A fast and symmetric DUST implementation to Mask
// Low-Complexity DNA Sequences". J Comp Bio.
double calculateDustScore(const std::string& seq)
{
std::map<std::string, int> scoreMap;
// Cannot calculate dust scores on very short reads
if(seq.size() < 3)
return 0.0f;
// Slide a 3-mer window over the sequence and insert the sequences into the map
for(size_t i = 0; i < seq.size() - 3; ++i)
{
std::string triMer = seq.substr(i, 3);
scoreMap[triMer]++;
}
// Calculate the score by summing the square of every element in the map
double sum = 0;
std::map<std::string, int>::iterator iter = scoreMap.begin();
for(; iter != scoreMap.end(); ++iter)
{
int tc = iter->second;
double score = (double)(tc * (tc - 1)) / 2.0f;
sum += score;
}
return sum / (seq.size() - 2);
}
// Returns the window over seq with the highest dust score
double maxDustWindow(const std::string& seq, size_t windowSize, size_t minWindow)
{
double maxScore = 0.0f;
for(size_t i = 0; i < seq.size(); i += 1)
{
size_t r = seq.size() - i;
size_t w = r < windowSize ? r : windowSize;
if(w >= minWindow) // don't calculate score for small windows
{
double s = calculateDustScore(seq.substr(i, w));
if(s > maxScore)
maxScore = s;
}
}
return maxScore;
}
// count the differences between s1 and s2 over the first n bases
int countDifferences(const std::string& s1, const std::string& s2, size_t n)
{
int numDiff = 0;
for(size_t i = 0; i < n; ++i)
{
if(s1[i] != s2[i])
numDiff++;
}
return numDiff;
}
// count the differences between s1 and s2 over the first n bases
std::string getDiffString(const std::string& s1, const std::string& s2)
{
std::string out;
size_t stop = std::min(s1.size(), s2.size());
for(size_t i = 0; i < stop; ++i)
out.push_back(s1[i] == s2[i] ? '.' : s1[i]);
return out;
}
//
char randomBase()
{
int i = rand() % 4;
switch(i)
{
case 0:
return 'A';
case 1:
return 'C';
case 2:
return 'G';
case 3:
return 'T';
default:
assert(false);
}
return 'A';
}
// Strip the leading directories and
// the last trailling suffix from a filename
std::string stripFilename(const std::string& filename)
{
std::string out = stripDirectories(filename);
// Remove the gzip extension if necessary
if(isGzip(out))
out = stripExtension(out);
return stripExtension(out);
}
// 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);
}
// Remove an extension from a filename, including the .gz extension
// file.fastq will return file
// file.fastq.gz will return file
std::string stripGzippedExtension(const std::string& filename)
{
if(isGzip(filename))
return stripExtension(stripExtension(filename));
else
return stripExtension(filename);
}
// Strip the leadering directories from a filename
std::string stripDirectories(const std::string& filename)
{
size_t lastDirPos = filename.find_last_of('/');
if(lastDirPos == std::string::npos)
return filename; // no directories
else
return filename.substr(lastDirPos + 1);
}
// Return the file extension
std::string getFileExtension(const std::string& filename)
{
size_t suffixPos = filename.find_last_of('.');
if(suffixPos == std::string::npos)
return "";
else
return filename.substr(suffixPos + 1);
}
// Write out a fasta record
void writeFastaRecord(std::ostream* pWriter, const std::string& id, const std::string& seq, size_t maxLineLength)
{
*pWriter << ">" << id << " " << seq.length() << "\n";
for(size_t i = 0; i < seq.size(); i += maxLineLength)
{
size_t span = std::min(seq.size() - i, maxLineLength);
*pWriter << seq.substr(i, span) << "\n";
}
}
// 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;
}
// Returns true if the filename has an extension indicating it is fastq
bool isFastq(const std::string& filename)
{
return filename.find(".fastq") != std::string::npos || filename.find(".fq") != std::string::npos;
}
// Returns the size of the file. Code from stackoverflow.
std::ifstream::pos_type getFilesize(const std::string& filename)
{
std::ifstream in(filename.c_str(), std::ifstream::in | std::ifstream::binary);
in.seekg(0, std::ifstream::end);
return in.tellg();
}
// 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;
}
}
// 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);
}
}
// Split a string into parts based on the delimiter
StringVector split(std::string in, char delimiter)
{
StringVector out;
size_t lastPos = 0;
size_t pos = in.find_first_of(delimiter);
while(pos != std::string::npos)
{
out.push_back(in.substr(lastPos, pos - lastPos));
lastPos = pos + 1;
pos = in.find_first_of(delimiter, lastPos);
}
out.push_back(in.substr(lastPos));
return out;
}
// Split a key-value pair
void splitKeyValue(std::string in, std::string& key, std::string& value)
{
StringVector parts = split(in, CAF_SEP);
if(parts.size() != 2)
{
std::cerr << "Invalid key-value pair " << in << std::endl;
assert(false);
}
key = parts[0];
value = parts[1];
assert(key.size() > 0 && value.size() > 0 && "Invalid key-value pair");
}
// Get the shared component of a read pair name
// This is the part of the name preceding the "/"
std::string getPairBasename(const std::string& id)
{
assert(!id.empty());
size_t pos = id.find_last_of('/');
if(pos == std::string::npos)
return id;
else
return id.substr(0, pos);
}
// Get the ID of the pair of a given read
std::string getPairID(const std::string& id)
{
assert(!id.empty());
std::string pid(id);
size_t li = id.length() - 1;
char last = id[li];
if(last == 'A')
pid[li] = 'B';
else if(last == 'B')
pid[li] = 'A';
else if(last == '1')
pid[li] = '2';
else if(last == '2')
pid[li] = '1';
else if(last == 'f')
pid[li] = 'r';
else if(last == 'r')
pid[li] = 'f';
else
pid = "";
return pid;
}
// Return 0 if the id indicates the first read of a pair, 1 otherwise
int getPairIndex(const std::string& id)
{
size_t li = id.length() - 1;
char last = id[li];
if(last == 'A' || last == '1' || last == 'f')
return 0;
else if(last == 'B' || last == '2' || last == 'r')
return 1;
else
{
std::cerr << "Unrecognized pair format: " << id << "\n";
exit(EXIT_FAILURE);
}
}
// Debug function to parse the distance between two reads
// based on their names
// This assumes is that the read names are just the positions the reads
// were sampled from
size_t debug_getReadDistFromNames(const std::string& name1, const std::string& name2)
{
std::string id;
std::string pos;
StringVector parts = split(name1, ':');
if(parts.size() != 2)
return 0;
int p1 = atoi(parts[1].c_str());
parts = split(name2, ':');
if(parts.size() != 2)
return 0;
int p2 = atoi(parts[1].c_str());
int dist = int(abs(p1 - p2));
return dist;
}