-
Notifications
You must be signed in to change notification settings - Fork 24
/
kmercollection.cpp
433 lines (381 loc) · 13.4 KB
/
kmercollection.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
#include "kmercollection.h"
#include "util.h"
#include <sstream>
#include <string.h>
#include <memory.h>
#include "kmer.h"
const long HASH_LENGTH = (1L<<30);
KmerCollection::KmerCollection(string filename, Options* opt)
{
mOptions = opt;
mHashKCH = new uint32[HASH_LENGTH];
memset(mHashKCH, 0, sizeof(uint32)*HASH_LENGTH);
mFilename = filename;
mNumber = 0;
mIdBits = 0;
mIdMask = 0;
mCountMax = 0;
mStatDone = false;
mUniqueHashNum = 0;
mKCHits = NULL;
init();
}
KmerCollection::~KmerCollection()
{
if(mHashKCH) {
delete mHashKCH;
mHashKCH = NULL;
}
if(mKCHits) {
delete mKCHits;
mKCHits = NULL;
}
if (mZipped){
if (mZipFile){
gzclose(mZipFile);
mZipFile = NULL;
}
}
else {
if (mFile.is_open()){
mFile.close();
}
}
}
bool KmerCollection::getLine(char* line, int maxLine){
bool status = true;
if(mZipped)
status = gzgets(mZipFile, line, maxLine);
else {
mFile.getline(line, maxLine);
status = !mFile.fail();
}
// trim \n, \r or \r\n in the tail
int readed = strlen(line);
if(readed >=2 ){
if(line[readed-1] == '\n' || line[readed-1] == '\r'){
line[readed-1] = '\0';
if(line[readed-2] == '\r')
line[readed-2] = '\0';
}
}
return status;
}
bool descComp (int i,int j) { return (i>j); }
bool KCResultComp (KCResult i, KCResult j) {
if (i.mCoverage == j.mCoverage)
return i.mMedianHit > j.mMedianHit;
else
return i.mCoverage > j.mCoverage;
}
void KmerCollection::stat(){
vector<vector<int>> kmerHits(mNumber);
for(int i=0; i<mUniqueHashNum; i++) {
KCHit kch = mKCHits[i];
if(kch.mHit>0) {
mHits[kch.mID]+=kch.mHit;
kmerHits[kch.mID].push_back(kch.mHit);
}
}
for(int id=0; id<mNumber; id++){
if(mKmerCounts[id] == 0) {
mMedianHits[id]=0;
mMeanHits[id]=0.0;
mCoverage[id]=0.0;
} else{
int medianPos = (mKmerCounts[id]+1)/2;
if(medianPos >= kmerHits[id].size())
mMedianHits[id] = 0;
else {
nth_element(kmerHits[id].begin(), kmerHits[id].begin()+medianPos, kmerHits[id].end(), descComp);
mMedianHits[id] = kmerHits[id][medianPos];
}
mMeanHits[id] = (double)mHits[id]/(double)mKmerCounts[id];
mCoverage[id] = (double)kmerHits[id].size()/(double)mKmerCounts[id];
}
}
for(int id=0; id<mNumber; id++){
if(mCoverage[id] > mOptions->kcCoverageThreshold && mKmerCounts[id] > 10) {
KCResult kcr;
kcr.mName = mNames[id];
kcr.mHit = mHits[id];
kcr.mCoverage = mCoverage[id];
kcr.mMedianHit = mMedianHits[id];
kcr.mMeanHit = mMeanHits[id];
kcr.mKmerCount = mKmerCounts[id];
kcr.mUniqueReads = mGenomeReads[id];
mResults.push_back(kcr);
}
}
sort(mResults.begin(),mResults.end(),KCResultComp);
mStatDone = true;
}
uint32 KmerCollection::add(uint64 kmer64) {
uint64 kmerhash = makeHash(kmer64);
uint32 index = mHashKCH[kmerhash];
if(index != 0 && index != COLLISION_FLAG) {
if(mKCHits[index - 1].mKey64 == kmer64) {
mKCHits[index - 1].mHit++;
return mKCHits[index - 1].mID + 1;
} else
return 0;
} else
return 0;
}
void KmerCollection::addGenomeRead(uint32 genomeID) {
if(genomeID-1 < mGenomeReads.size())
mGenomeReads[genomeID-1]++;
}
void KmerCollection::init()
{
if(mOptions->verbose)
loginfo("Initializing k-mer collection: " + mFilename + "\n");
if (ends_with(mFilename, ".fasta.gz") || ends_with(mFilename, ".fa.gz")){
mZipFile = gzopen(mFilename.c_str(), "r");
mZipped = true;
}
else if(ends_with(mFilename, ".fasta") || ends_with(mFilename, ".fa")){
mFile.open(mFilename.c_str(), ifstream::in);
mZipped = false;
} else {
error_exit("Not a FASTA file: " + mFilename);
}
//unordered_map<uint64, KCHit> hashKmerMap;
const int maxLine = 1000;
char line[maxLine];
if (mZipped){
if (mZipFile == NULL)
return ;
}
vector<vector<uint64>> allKmer64;
int unique = 0;
int total = 0;
bool initialized = false;
while(true) {
if(eof())
break;
getLine(line, maxLine);
string linestr(line);
if(linestr.empty() || line[0]=='#') {
continue;
}
if(line[0]=='>') {
if(total > 0) {
//cerr << unique << "/" << total << endl;
mKmerCounts.push_back(unique);
total=0;
unique=0;
}
mNames.push_back(linestr.substr(1, linestr.length() - 1));
mHits.push_back(0);
allKmer64.push_back(vector<uint64>());
mMeanHits.push_back(0.0);
mCoverage.push_back(0.0);
mMedianHits.push_back(0);
mGenomeReads.push_back(0);
mNumber++;
//cerr<<mNumber<<": " << linestr << endl;
continue;
}
string& seq = linestr;
if(!initialized) {
initialized = true;
if(mOptions->kmerKeyLen == 0)
mOptions->kmerKeyLen = seq.length();
if(mOptions->kmerKeyLen > 32)
error_exit("k-mer key length cannot be >32: " + seq);
}
if(seq.length() != mOptions->kmerKeyLen) {
cerr << "k-mer length must be " << mOptions->kmerKeyLen << ", skipped " << seq << endl;
continue;
}
bool valid = true;
uint64 kmer64 = Kmer::seq2uint64(seq, 0, seq.length(), valid);
if(valid) {
total++;
uint64 kmerhash = makeHash(kmer64);
//unordered_map<uint64, KCHit>::iterator iter = hashKmerMap.find(kmerhash);
if(mHashKCH[kmerhash] == 0) {
unique++;
mHashKCH[kmerhash] = mNumber;
allKmer64[mNumber-1].push_back(kmer64);
} else if(mHashKCH[kmerhash] != COLLISION_FLAG) { // we use the mHits as a flag
if(mHashKCH[kmerhash] == mNumber)
unique--;
else {
int collID = mHashKCH[kmerhash]-1;
mKmerCounts[collID]--;
}
mHashKCH[kmerhash] = COLLISION_FLAG;
}
}
}
mKmerCounts.push_back(unique);
mUniqueHashNum = 0;
for(int i=0; i<mNumber; i++)
mUniqueHashNum += mKmerCounts[i];
mKCHits = new KCHit[mUniqueHashNum];
memset(mKCHits, 0, sizeof(KCHit)*mUniqueHashNum);
uint32 cur = 0;
for(int i=0; i<mNumber; i++) {
for(int j=0; j<allKmer64[i].size(); j++) {
uint64 kmer64 = allKmer64[i][j];
uint64 kmerhash = makeHash(kmer64);
uint32 index = mHashKCH[kmerhash];
// means unique
if(index == i+1) {
if(cur >= mUniqueHashNum)
error_exit("Uninque number incorrectly calculated in k-mer collection initialization.");
mHashKCH[kmerhash] = cur + 1; // 0 means no hit
mKCHits[cur].mID = i;
mKCHits[cur].mHit = 0;
mKCHits[cur].mKey64 = kmer64;
cur++;
}
}
}
//makeBitAndMask();
}
bool KmerCollection::eof() {
if (mZipped) {
return gzeof(mZipFile);
} else {
return mFile.eof();
}
}
uint64 KmerCollection::makeHash(uint64 key) {
return (1713137323 * key + (key>>12)*7341234131 + (key>>24)*371371377) & (HASH_LENGTH-1);
}
void KmerCollection::report() {
if(!mStatDone)
stat();
int highConfidenceNum = 0;
for(int i=0; i<mResults.size(); i++) {
KCResult kcr = mResults[i];
if(!isHighConfidence(kcr))
continue;
highConfidenceNum++ ;
cerr << highConfidenceNum << ", ";
cerr << kcr.mName << ",";
cerr << "coverage:" << kcr.mCoverage;
cerr << ",kmer_count:" << kcr.mKmerCount;
cerr << ",median_depth:" << kcr.mMedianHit;
cerr << ",mean_depth:" << kcr.mMeanHit;
cerr << ",unique_reads:" << kcr.mUniqueReads;
cerr << endl;
}
if(highConfidenceNum == 0)
cerr << "No high confidence k-mer coverage found." << endl;
}
void KmerCollection::reportJSON(ofstream& ofs) {
if(!mStatDone)
stat();
ofs << "\t" << "\"kmer_collection_scan_result\": {" << endl;
int first = true;
for(int i=0; i<mResults.size(); i++) {
KCResult kcr = mResults[i];
if(first) {
first = false;
} else
ofs << "," << endl;
string name = replace(kcr.mName, "\"", "'");
ofs << "\t\t\"" << name << "\":{";
ofs << "\"coverage\":" << kcr.mCoverage;
ofs << ",\"kmer_count\":" << kcr.mKmerCount;
ofs << ",\"kmer_hits\":" << kcr.mHit;
ofs << ",\"median_depth\":" << kcr.mMedianHit;
ofs << ",\"mean_depth\":" << kcr.mMeanHit;
ofs << ",\"unique_reads\":" << kcr.mUniqueReads;
ofs << "}";
}
ofs << endl << "\t}," << endl;
}
bool KmerCollection::isHighConfidence(KCResult kcr) {
if(kcr.mCoverage > mOptions->kcCoverageHighConfidence && kcr.mMedianHit > mOptions->kcMedianHitHighConfidence)
return true;
else
return false;
}
void KmerCollection::reportHTML(ofstream& ofs) {
ofs << "<table class='summary_table' style='width:100%'>\n";
ofs << "<tr style='background:#cccccc'> <td>Genome</td><td>K-mer hits</td><td>Unique reads</td><td>Coverage</td><td>Median depth</td><td>Mean depth</td><td>Remark</td> </tr>" << endl;
int highConfidence = 0;
for(int i=0; i<mResults.size(); i++) {
KCResult kcr = mResults[i];
if(!isHighConfidence(kcr))
continue;
highConfidence++;
string remark;
if(kcr.mName.find("phi-X174")!=string::npos)
remark = "Illumina PhiX control library";
else if(kcr.mName == "NC_045512.2 Wuhan seafood market pneumonia virus isolate Wuhan-Hu-1, complete genome")
remark = "SARS-CoV-2";
ofs << "<tr>";
ofs << "<td width=52%>" << kcr.mName << " (" << kcr.mKmerCount << " k-mer keys)</td>";
ofs << "<td width=8%>" << kcr.mHit << "</td>";
ofs << "<td width=8%>" << kcr.mUniqueReads << "</td>";
ofs << "<td width=10%>" << kcr.mCoverage * 100 << "%</td>";
ofs << "<td width=8%>" << kcr.mMedianHit << "</td>";
ofs << "<td width=8%>" << kcr.mMeanHit << "</td>";
ofs << "<td width=6%>" << remark << "</td>";
ofs << "</tr>" << endl;
}
if(highConfidence == 0)
ofs << "<tr> <td colspan=6 style='text-align:center;'>No high confidence k-mer coverage found. </td></tr>" << endl;
ofs << "</table>\n";
if(highConfidence != mResults.size()) {
ofs << "<div class='subsection_title' style='font-size:12px;font-weight:normal;color:#223399;' onclick=showOrHide('low_confidence_kcr')>+ Show " << mResults.size() - highConfidence;
ofs << " more with low confidence (coverage <= " << mOptions->kcCoverageHighConfidence * 100;
ofs << "% or median depth <= " << mOptions->kcMedianHitHighConfidence;
ofs << ") ▼ </div>\n";
ofs << "<table id='low_confidence_kcr' style='display:none;width:100%;' class='summary_table'>\n";
ofs << "<tr style='background:#cccccc'> <td>Genome</td><td>K-mer hits</td><td>Unique reads</td><td>Coverage</td><td>Median depth</td><td>Mean depth</td><td>Remark</td> </tr>" << endl;
int highConfidence = 0;
for(int i=0; i<mResults.size(); i++) {
KCResult kcr = mResults[i];
if(isHighConfidence(kcr))
continue;
string remark;
if(kcr.mName.find("phi-X174")!=string::npos)
remark = "Illumina PhiX control library";
else if(kcr.mName == "NC_045512.2 Wuhan seafood market pneumonia virus isolate Wuhan-Hu-1, complete genome")
remark = "SARS-CoV-2";
ofs << "<tr>";
ofs << "<td width=52%>" << kcr.mName << " (" << kcr.mKmerCount << " k-mer keys)</td>";
ofs << "<td width=8%>" << kcr.mHit << "</td>";
ofs << "<td width=8%>" << kcr.mUniqueReads << "</td>";
ofs << "<td width=10%>" << kcr.mCoverage * 100 << "%</td>";
ofs << "<td width=8%>" << kcr.mMedianHit << "</td>";
ofs << "<td width=8%>" << kcr.mMeanHit << "</td>";
ofs << "<td width=6%>" << remark << "</td>";
ofs << "</tr>" << endl;
}
ofs << "</table>\n";
}
}
void KmerCollection::makeBitAndMask() {
int bits=1;
uint32 mask =0x01;
while(true){
if(bits == 32) {
error_exit("Too many contigs in: " + mFilename);
}
if(mask > mNumber)
break;
bits++;
mask= (mask << 1) + 1;
}
mIdBits = bits;
mIdMask = mask;
mCountMax = (0xFFFFFFFFFFF >> mIdBits);
}
uint32 KmerCollection::packIdCount(uint32 id, uint32 count) {
uint32 data = 0;
data |= (count << mIdBits); // high bits: count
data |= id; // low bits: id
return data;
}
void KmerCollection::unpackIdCount(uint32 data, uint32& id, uint32& count) {
count = data >> mIdBits;
id = data & mIdMask;
}