-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathInputStream.cpp
3282 lines (2920 loc) · 91.5 KB
/
InputStream.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
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
/* sdm: simple demultiplexer
Copyright (C) 2013 Falk Hildebrand
email: [email protected]
This program 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.
This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*/
#define _CRT_SECURE_NO_DEPRECATE
#include <mutex>
#include <thread>
#include "InputStream.h"
#include "FastxReader.h"
#include <iostream>
#include <vector>
#include <functional>
#include <chrono>
#include <string>
#ifdef _gzipread
#include "include/gzstream.h"
//#include <include/zstr.h>
#endif
string spaceX(uint k){
string ret = "";
for (uint i = 0; i < k; i++){
ret += " ";
}
return ret;
}
int digitsInt(int x){
int length = 1;
while (x /= 10)
length++;
return length;
}
int digitsFlt(float x){
std::stringstream s;
s << x;
return (int)s.str().length();
}
string intwithcommas(int value) {
string numWithCommas = std::to_string((long long)value);
int insertPosition = (int)numWithCommas.length() - 3;
while (insertPosition > 0) {
numWithCommas.insert(insertPosition, ",");
insertPosition -= 3;
}
return (numWithCommas);
}
std::string itos(int number) {
std::stringstream ss;
ss << number;
return ss.str();
}
std::string ftos(float number,int digits) {
std::stringstream ss;
ss << std::setprecision(digits)<< number;
return ss.str();
}
bool isGZfile(const string fi) {
string subst = fi.substr(fi.length() - 3);
if (subst == ".gz") {
return true;
}
return false;
}
std::istream& safeGetline(std::istream& is, std::string& t) {
t.clear();
//from http://stackoverflow.com/questions/6089231/getting-std-ifstream-to-handle-lf-cr-and-crlf
// The characters in the stream are read one-by-one using a std::streambuf.
// That is faster than reading them one-by-one using the std::istream.
// Code that uses streambuf this way must be guarded by a sentry object.
// The sentry object performs various tasks,
// such as thread synchronization and updating the stream state.
std::istream::sentry se(is, true);
std::streambuf* sb = is.rdbuf();
for (;;) {
int c = sb->sbumpc();
switch (c) {
case '\n':
return is;
case '\r':
if (sb->sgetc() == '\n')
sb->sbumpc();
return is;
case EOF:
// Also handle the case when the last line has no line ending
if (t.empty())
is.setstate(std::ios::eofbit);
return is;
default:
t += (char)c;
}
}
}
/*
void rtrim(std::string& s) {
//s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
//return s;
s.erase(std::find_if(s.rbegin(), s.rend(), [](unsigned char ch) {
return !std::isspace(ch);
}).base(), s.end());
}
*/
int parseInt(const char** p1) {//,int& pos){//, const char ** curPos) {
//from http://stackoverflow.com/questions/5830868/c-stringstream-is-too-slow-how-to-speed-up
//size_t nxtPos = input.find_first_of(' ', curPos);
//const char *p = input.substr(curPos,nxtPos).c_str();
//if (!*p || *p == '?') return 0;
//int s = 1;
//p = (const char*)curPos;
const char* p = *p1;
while (*p == ' ') p++;
int acc = 0;
while (*p >= '0' && *p <= '9')
acc = acc * 10 + *p++ - '0';
*p1 = p;
//curPos = (size_t) p;
return acc;
}
//MOCAT
std::vector<std::string> header_string_split(const std::string str, const std::string sep) {
std::vector<std::string> tokens;
tokens.reserve(13);
size_t start = 0;
size_t pos = 0;
while ((pos = str.find_first_of(sep, start)) != std::string::npos) {
tokens.push_back(str.substr(start, pos - start));
start = pos + 1;
}
if (start < str.length()) {
tokens.push_back(str.substr(start));
} else if (start == str.length()) {
tokens.push_back("0");
}
return tokens;
}
void remove_paired_info(string &s, short RP) {
size_t f1 = s.find(" ");
if (f1 != string::npos) {
s = s.substr(0, f1);
f1 = string::npos;
}
size_t tarPos = s.size() - 2;
/*if (RP == 0) {
f1 = s.rfind("/1");
if (f1 == string::npos) {
f1 = s.rfind(".1");
}
}
else if (RP == 1) {
f1 = s.rfind("/2");
if (f1 == string::npos) {
f1 = s.rfind(".2");
}
}
else {*/
f1 = s.rfind("/1");
if (f1 == string::npos || f1 != tarPos) { f1 = s.rfind("/2"); }
if (f1 == string::npos || f1 != tarPos) { f1 = s.rfind(".1"); }
if (f1 == string::npos || f1 != tarPos) { f1 = s.rfind(".2"); }
//}
if (f1 != string::npos && f1 == tarPos) {
s = s.substr(0, f1);
}
}
std::string header_stem(string& header) {
const size_t slash = header.find('/');
if (slash != std::string::npos) {
return header.substr(0, slash);
}
std::vector<std::string> tokens = header_string_split(header, ": ");
if (tokens.size() == 11) {
//if (tokens[8] == "Y") seq.clear();
return tokens[0] + ":" + tokens[3] + ":" + tokens[4]
+ ":" + tokens[5] + ":" + tokens[6];// +"#" + tokens[10];
} else if (tokens.size() == 6 || tokens.size() == 7) {
return tokens[0] + ":" + tokens[2] + ":" + tokens[3]
+ ":" + tokens[4] + ":" + tokens[5];// + "#0";
} else {
cerr << "fastq header format error\n"; exit(98);
}
//throw std::runtime_error("fastq header format error\n" + header); }
}
void reverseTS(string & Seq) {
int qs = (int)Seq.length() - 1;
string S2 = Seq.c_str();
for (int i = qs; i >= 0; i--) {
Seq[i] = DNA_trans[(int)S2[qs - i]];
}
}
string reverseTS2(const string & Seq) {
int qs = (int)Seq.length() - 1;
string S2 = Seq.c_str();
for (int i = qs; i >= 0; i--) {
S2[i] = DNA_trans[(int)Seq[qs - i]];
}
return S2;
}
bool any_lowered(const string& is) {
for (uint i = 0; i < is.length(); i++) {
char c = is[i];
if (islower(c)) { return true; }
}
return false;
}
std::ptrdiff_t len_common_prefix_base(char const a[], char const b[])
{
if (std::strlen(b) > std::strlen(a)) {
return std::distance(a, std::mismatch(a, a + std::strlen(a), b).first);
}
return std::distance(b, std::mismatch(b, b + std::strlen(b), a).first);
}
string applyFileIT(string x, int it,const string xtr){
size_t pos = x.find_last_of(".");
if (pos != string::npos && isGZfile(x)) {
pos = x.find_last_of(".", pos-1);
}
if (it == 0) {
if (pos == string::npos) {
return x + xtr;
}
return x.substr(0, pos) + xtr + x.substr(pos);
}
ostringstream ss;
ss << it;
if (pos == string::npos) {
return x + "." + ss.str() + xtr ;
}
return x.substr(0,pos) + "."+ss.str() + xtr + x.substr(pos);
}
bool fileExists(const std::string& name, int i, bool extiffail) {
if (name == "") { return true; }
if (FILE *file = fopen(name.c_str(), "r")) {
fclose(file); return true;
} else {
if (extiffail) {
cerr << "ERROR: Could not find file " << name << endl;
if (i >= 0) {
cerr << "on mapping file line " << i << endl;
}
exit(92);
}
return false;
}
}
string detectSeqFmt(const string inF) {
vector<string> tfasP = splitByCommas(inF, ';');
for (size_t i = 0; i < tfasP.size(); i++) {
vector<string> tfas = splitByCommas(tfasP[i]);
string fileS = tfas[0];
istream* fnax(NULL);
string file_type = "test file";
string tmp("");
string ret = "";
if (fileS != "") {
// auto detect gzip
#ifdef _gzipread
fnax = DBG_NEW zstr::ifstream(fileS.c_str(), ios::in);
#else
fnax = DBG_NEW ifstream(fileS.c_str(), ios::in);
#endif
if (!*(fnax)) { cerr << "\nCouldn't find " << file_type << " file \"" << fileS << "\"!\n Aborting..\n"; exit(4); }
//char Buffer[RDBUFFER];
//fasta_istreams[0]->rdbuf()->pubsetbuf(Buffer, RDBUFFER);
while (safeGetline(*fnax, tmp)) {
if (tmp[0] == '>') {
ret = "-i_fna"; break;
}
else if (tmp[0] == '@') {
ret = "-i_fastq"; break;
}
else if (tmp.length() == 0) {//do nothing
;
}
else {
cerr << " Could not auto detect input format. First non-empty line of your file looked like:\n" << tmp << endl;
exit(888);
}
}
}
delete fnax;
if (ret == "") {
cerr << "Empty input file detected:\n" << fileS << endl;
} else {
return ret;
}
}
return "empty";
}
//compares two DNA entries, decides which one has overall better stats
bool whoIsBetter(shared_ptr<DNA> d1, shared_ptr<DNA> d2, shared_ptr<DNA> dM,
shared_ptr<DNA> r1, shared_ptr<DNA> r2, shared_ptr<DNA> rM,
float& ever_best, bool forSeed) {
//if (forSeed) { return false; }
//check if two primers present
if (d2 == nullptr) {//hard reason .. only for PacBio etc reads
if (d1->has2PrimersDetected() && !r1->has2PrimersDetected()) { return true; }
if (!d1->has2PrimersDetected() && r1->has2PrimersDetected()) { return false; }
} else {
if (d2->getRevPrimCut() && !r1->getFwdPrimCut() && !r2->getRevPrimCut()) { return true;}
}
//check if at least 1 primers present
if (d1->getFwdPrimCut() && !r1->getFwdPrimCut()) { return true; }//hard reason
if (!d1->getFwdPrimCut() && r1->getFwdPrimCut()) { return false; }
double d1pid(1.), refpid(1.);
if (ever_best >=0) {
d1pid = (double) d1->getTempFloat(); refpid = (double)r1->getTempFloat();
if (d1pid > ever_best) {
ever_best = (float) d1pid;
}
//everbest is likely 100.f (ref OTUs)
if (d1pid < (refpid - 0.3f) || d1pid < (ever_best - 0.4f ) ) { return false; }
}
bool dMerge(true), rMerg(true);
double curL = (double)d1->getMergeLength();
if (curL < 0) {
curL = (double) d1->length();
//if (d2 != NULL) { curL += (double) d2->length(); }
dMerge = false;
}
double refL = (double)r1->getMergeLength();
if (refL < 0) {
refL = (double) r1->length();
//if (r2 != NULL) { refL += (double) r2->length(); }
rMerg = false;
}
//first check if d1 has merged, but ref did not.. clearly go for d, hard filter
//if (d1->getMergeLength() != -1 && r1->getMergeLength() == -1) { return true; }
//hard check on length ratios.. too drastically small , don't use d1
if ((curL) / (refL) < BestLengthRatio ) { return false; }
//at least 90% length of "good" hit
//if (r1->getMergeErrors() < 0) {//no merge, can look at read1 only
// if (d1->length() / r1->length() < RefLengthRatio) { return false; }
//}
float dmergErrSco = 0.f; float refMergErrSco = 0.f;
//only check further if both comparisons did merge
if (r1->getMergeLength() >=0 && d1->getMergeLength() >=0) {
if (d1->getMergeErrors() > 0) {
dmergErrSco = (float)d1->getMergeErrors();// *log10((maxQErr - (float)d1->getMergeErrorsQual()));
dmergErrSco += d1->getMergeErrorsQual()/30;
}
if (r1->getMergeErrors() > 0) {
refMergErrSco = (float)r1->getMergeErrors() + r1->getMergeErrorsQual() / 30;// *log10((maxQErr - (float)r1->getMergeErrorsQual()));
}
//scale to 1
float maxMerr = max(refMergErrSco, dmergErrSco);
dmergErrSco /= maxMerr; refMergErrSco /= maxMerr;
dmergErrSco = 1.f - dmergErrSco; refMergErrSco = 1.f - refMergErrSco;
}
//choose merged DNA if possible; d2 no longer needed then
shared_ptr<DNA> dx, rx;
bool allowMergeGuide = false;
if (allowMergeGuide && dM != nullptr) { dx = dM; d2 = nullptr; } else { dx = d1; }
if (allowMergeGuide && rM != nullptr) { rx = rM; r2 = nullptr;}else { rx = r1; }
float thScore = dx->getAvgQual(); //*(d1pid / 100)* log((float)curL);
float rScore = rx->getAvgQual();// *(refpid / 100)* log((float)refL);//r1->length()
//if (thScore > rScore) {
//also check for stable lowest score
// if (d1->minQual() > r1->minQual() - MinQualDiff) { return true; }
//}
float maxScore = max(thScore, rScore);
thScore /= maxScore; rScore /= maxScore;
//checks if the new DNA has a better overall quality
double dAcSc = dx->getAccumError(); double dLen = dx->mem_length();
double tAcSc = rx->getAccumError(); double tLen = rx->mem_length();
if (d2 != nullptr) { dAcSc += d2->getAccumError(); dLen += d2->mem_length(); }
if (r2 != nullptr) { tAcSc += r2->getAccumError(); tLen += r2->mem_length(); }
dAcSc /= dLen; tAcSc /= tLen;
//calculate ratios to compare more easily among metrics
double ratAccErr = log(dAcSc)/log(tAcSc); //smaller better, log changes terms around
double ratLength = double(curL) / (double)refL; //higher better
double ratId = d1pid / refpid * 10 - 9.; //higher better //10-fold weighting
if ((ratAccErr * ratLength * ratId) > 1.) {
return true;
}
//normalize and invert
//normalize to gene length, and invert to convert to positive score system
/*maxScore = max(dAcSc, tAcSc);
dAcSc /= maxScore; tAcSc /= maxScore;
dAcSc = 1.f - dAcSc; tAcSc = 1.f - tAcSc;
//norm to 1, to compare to other terms
double maxEr = max(dAcSc, tAcSc);
dAcSc /= maxEr; tAcSc /= maxEr;
//dmergErrSco refMergErrSco dAcSc + tAcSc + thScore rScore
if ( (dAcSc) *(d1pid / 100) * log((float)curL)
> (tAcSc) *(refpid / 100) * log((float)refL )) {
if (dx->minQual() > rx->minQual() - MinQualDiff) { return true; }
// return true;
}
*/
return false;
}
void DNA::fixQ0(void) {
return;//still depends on sequencer what is actually returned..
for (uint i = 0; i < qual_.size(); i++) {
if (qual_[i] <= 0) {
sequence_.replace(i, 1, "N");
}
}
}
bool DNA::seal(bool isFasta) {//DN = sequence_.c_str();
size_t QSi = qual_.size();
if (QSi == 0 && isFasta) {
return true;//nothing to be done, just empty DNA
} else if (QSi == 0 && sequence_ == "" ) {
this->setPassed(false);
return true;
} else if (QSi != sequence_.length()) {
cerr << "Unequal length of seq and quality for name " << this->getId() << "\n";
this->setPassed(false);
return false;
}
//uppercase DNA
std::transform(sequence_.begin(), sequence_.end(), sequence_.begin(), ::toupper);
sequence_length_ = sequence_.length();
this->fixQ0();
return true;
}
DNA::DNA(vector<string> fas):DNA() {
// Abort if input stream is at the end
if (fas[0].length() == 0 ) {
return;
}
if (fas[0][0] != '>') {
cerr << "ERROR: Line 1 in fasta file does not start with \">\" :\n"<<fas[0]<<endl;
exit(23);
}
// Storage objects
string tqual;
this->setHeader(fas[0].substr(1));
this->setSequence( fas[1]);
uint lsize = fas[1].length();
vector<qual_score> Iqual(lsize, 11);
if (fas[2].length() > 0) {
tqual = fas[2];
rtrim(tqual);
const char* lQ = tqual.c_str();
uint ii(0);
qual_score nn(0);
for (; ii < lsize; ii++) {
nn = (qual_score)parseInt(&lQ);// , posStr);
Iqual[ii] = nn;
if (*lQ == '\0') {
break;
}
//issQ >> Iqual[ii];
}
if (Iqual.size() != fas[1].length()) {
cerr << "Unequal fasta (" << fas[1].length() << ")/qual (" << fas[2].length() << ") length:\n";
cerr << fas[0] << endl << fas[1] << endl << fas[2] << endl;
exit(923);
}
}
this->setQual(move(Iqual));
}
DNA::DNA(vector<string> fq, qual_score fastQver):DNA(){
//string line;
if (fq.size() != 4 || fq[0].length() == 0) { delself(); return; }
while (fq[0][0] != '@') {
cerr<< "ERROR on line " + fq[0] + ": Could not find \'@\' when expected (file likely corrupt, trying to recover):\n" ;// << endl;
delself();
return;
}
this->setHeader(fq[0].substr(1));
sequence_ = fq[1];
sequence_length_ = sequence_.size();
if (fq[2][0] != '+') {
cerr<<"Error input line " + fq[2] + ": Could not find \'+\' when expected (file likely corrupt, aborting):\n" + fq[0];// << endl;
delself();
return;
//if (!safeGetline(fna, line)) { delete tdn; return NULL; }
}
//qual_ score
string& line = fq[3];
if (line.length() != this->mem_length()) {
string sizdif = "More";
if (line.length() > this->mem_length()) {
sizdif = "Less";
}
//check that quality gets not more length than DNA
delself();
cerr << "Error input line " + fq[3] + "'\n" + fq[1] + "'\n: "+ sizdif+" quality positions than nucleotides detected for sequence\n " +
fq[0];// << endl;
return;
}
uint qcnt(0); uint lline = (uint)this->mem_length();// line.length();
vector<qual_score> Iqual(this->mem_length(), 0);
for (; qcnt < lline; qcnt++) {
qual_score q = (qual_score)line[qcnt] - fastQver;
Iqual[qcnt] = q;// minmaxQscore();
}
this->setQual(move(Iqual));
}
/*
DNA::DNA(FastxRecord* FR, qual_score & minQScore, qual_score & maxQScore, qual_score fastQver) :DNA(){
id_ = FR->header.substr(1);
sequence_=FR->sequence;
qual_.resize(FR->quality.length(), 0);
uint qcnt(0); uint lline = (uint)FR->quality.length();
for (; qcnt < lline; qcnt++) {
qual_score t((qual_score)FR->quality[qcnt] - fastQver);
if (minQScore > t) {
minQScore = t;
if (minQScore < 0) {
}
}
else if (maxQScore < t) {
maxQScore = t;
}
qual_[qcnt] = t;
}
}
*/
string DNA::getPositionFreeId() { // remove /1 /2 #1:0 etc
string s = this->getShortId();
remove_paired_info(s, read_position_);
return s;
}
int DNA::numNonCanonicalDNA(bool all) {
int DNAch = 0;
size_t DNAl = length();
if (all) {
DNAl=sequence_.size();
}
for (size_t i = 0; i < DNAl; i++) {
DNAch += DNA_amb[sequence_[i]];
}
return DNAch;
}
int DNA::numACGT(){
int DNAch = 0;
uint maxL = length();
for (unsigned int i = 0; i < length(); i++){
DNAch += DNA_amb[(int) sequence_[i]];
}
return DNAch;
}
void DNA::stripLeadEndN() {
int i = 0;
while (DNA_amb[(int)sequence_[i]]) {
i++;
}
if (i) {
this->cutSeq(0, i);
}
//cut at end N's
i = (int)sequence_.length();
while (DNA_amb[(int)sequence_[i]]) {
i--;
}
if (i != (int)sequence_.length()) {
this->cutSeq(i+1, (int)sequence_.length());
}
}
void DNA::appendQuality(const vector<qual_score> &q)
{
qual_.insert(qual_.end(), q.begin(), q.end());
avg_qual_ = -1.f;
}
float DNA::getAvgQual(){
if (avg_qual_ < 0.f){
if (quality_sum_ == 0){
for (unsigned int i = 0; i < this->length(); i++){
quality_sum_ += qual_[i];
}
}
avg_qual_ = static_cast<float> (quality_sum_) / static_cast<float> (this->length());
}
return avg_qual_;
}
int DNA::getMedianQual() {
/*vector<qual_score> meq = qual_;
sort(meq.begin(), meq.end());
return calc_median2(meq, 0.5);*/
return median(qual_);
}
/*float DNA::qualWinfloat_hybr(int W, float T, int W2, float T2, int& reason){//not used
//if (T==0.f){return true;}
int AQS=0, AQL;
int TotQ = 0;
int upTs = static_cast<int>(T * W);
int upTl = static_cast<int>(T2 * W2);
int QS = int (qual_.size());
if (W>=QS){W = QS;} // too short
int smallerW = W, largerW = W2;
bool W1IsSmall = true;
if (smallerW > W2){ largerW=W; smallerW = W2; W1IsSmall=false;
std::swap(upTl,upTs); }
for (unsigned int i=0; i<(unsigned int) smallerW; i++){
AQS += qual_[i];
}
AQL = AQS;
//hybrid schleife
for (unsigned int i=smallerW; i<(unsigned int) largerW; i++){
AQL += qual_[i];
AQS += qual_[i]; AQS -= qual_[i-smallerW];
if (AQS < upTs){
if (W1IsSmall){ reason=0; return 0.f;
} else {reason=1; this->cutSeq(i/2,this->length()); return float(AQL)/float(QS);}
}
}
TotQ = AQL;
for (unsigned int i=W; i<(unsigned int) QS; i++){
AQS += qual_[i]; AQL += qual_[i];
TotQ += qual_[i];
AQS -= qual_[i-W];AQL -= qual_[i-W];
if (AQS < upTs || AQL < upTl){
if (W1IsSmall){ reason=0; return 0.f;
} else {reason=1; this->cutSeq(i/2,this->length()); return float(AQL)/float(QS);}
}
}
//if (averageQ > static_cast<float> (TotQ) /static_cast<float> ( qual_.size())){return false;}
return static_cast<float> (TotQ) /static_cast<float> ( QS);
}
*/
// modified from https://github.com/fpusan/moira/blob/master/moira/bernoullimodule.c
float DNA::interpolate(int errors1, float prob1, int errors2, float prob2, float alpha)
{
float result = errors1 + ((errors2 - errors1) * ((1 - alpha) - prob1) / (prob2 - prob1));
if (result < 0) //Happens only for very-short high qual_ sequences in which the probability of having 0 errors is higher than 1 - alpha.
{
result = 0;
}
return result;
}
float DNA::prob_j_errors(float p, float j, float n) //Where p is the error probability, j is the number of errors and n the number of observations.
{
float per_position_accum_probs;
if (j > n) {
return 0.0f; //The formula below would also return 0.
}
per_position_accum_probs = pow((1 - p), n); //For j == 0.
float i(1);
for (; i <= j; i += 1.f) {//For j > 0.
per_position_accum_probs = ((n - i + 1.f) / (1.0f*i)) * (p / (1.f - p)) * per_position_accum_probs;
}
return per_position_accum_probs;
}
float DNA::sum_of_binomials(const float j, int k, float n, int qual_length, const vector<float>& error_probs, const vector< vector<float>> & per_position_accum_probs)
//#Where j is the number of errors and k is the position in the sequence.
{
float probability = 0;
float i(0); int k1 = (int) k - 1;
for (; i <= j; i+=1.f)
{
probability += DNA::prob_j_errors(error_probs[k], i, n) * per_position_accum_probs[int(j - i)][k1];
//Where error_probs[k] is the error probability of the k-th position.
//Where per_position_accum_probs[j-i][k-1] is the probability that all the bases from position 0 to k-1 had a total of j-i errors.
}
return probability;
}
float DNA::binomialFilter(int maxErr, float alpha){
if (alpha == -1.f|| this->length()<3){ return 0.f; }//deactivated
if (maxErr > 1e5) {return 0.f; } // impossibly large..
///Initialize some variables.
int SeqLengthI = (int)sequence_length_;
int n = 1; //Since we have a Bernoulli distribution.
float n_f = (float)n;
float alpha1 = 1.f - alpha;
///Translate quality scores into error probabilities.
vector<float> error_probs (sequence_length_, 1.f);
for (size_t i = 0; i < sequence_length_; i++){
if (qual_[i]<0 || qual_[i]>maxSAqualP) { continue; }
error_probs[i] = (float)SAqualP[qual_[i]];//pow(10, (contig_quals[i] / -10.0)); //Since we want a continuous list of non-N error_probs.
}
///Actually get the job done.
int max_expected_errors = maxErr + 3;// (int)sequence_length_ + 1;
int expected_errors = 0;
float probability;
vector<float> accumulated_probs (max_expected_errors,0.f);
//int j;
int k;
vector<float> empty(sequence_length_, 0.f);
vector< vector<float>> per_position_accum_probs(max_expected_errors, empty);
while (1)
{
float expected_errors_f = (float)expected_errors;
//vector<float > per_position_accum_probs(sequence_length_, 0.f);
for (k = 0; k < (int)sequence_length_; k++) {
if (k == 0) {
per_position_accum_probs[expected_errors][k] = DNA::prob_j_errors(error_probs[k], expected_errors_f, n_f);
} else {
per_position_accum_probs[expected_errors][k] = DNA::sum_of_binomials((float)expected_errors, k, n_f, SeqLengthI, error_probs, per_position_accum_probs);
}
}
probability = per_position_accum_probs[expected_errors][SeqLengthI - 1];
if (expected_errors == 0){
accumulated_probs[expected_errors] = probability;
}else{
accumulated_probs[expected_errors] = accumulated_probs[expected_errors - 1] + probability;
}
if (accumulated_probs[expected_errors] > (alpha1) || expected_errors >= (max_expected_errors-1)){
break;
}else{
expected_errors++;
}
}
if (expected_errors == 0){
return 0.f;
}
float EXE = interpolate(expected_errors - 1, accumulated_probs[expected_errors - 1], expected_errors, accumulated_probs[expected_errors], alpha);
return EXE;
}
float DNA::qualWinfloat(uint W, float T, int& reason){
//if (T==0.f){return true;}
int AQS=0;
int TotQ = 0;
int upTs = int(T) * int(W);
uint QS = this->length();//static_cast<unsigned int> (qual_.size());
if (W>=QS){W = QS;} // too short
//1st loop to ini window
for (size_t i = 0; i < size_t (W); i++) {
AQS += qual_[i];
}
TotQ = AQS;
for (size_t i=W; i<(size_t) QS; i++){
AQS += qual_[i] - qual_[i - W];
TotQ += qual_[i];
if (AQS < upTs ){
reason=1; return 0.f;
}
}
//if (averageQ > static_cast<float> (TotQ) /static_cast<float> ( qual_.size())){return false;}
return float(TotQ) /float( QS);
}
int DNA::qualAccumulate(double d){
unsigned int i(0);double accErr(0.0);
for (; i<this->length(); i++) {
accErr+=SAqualP[qual_[i]];
if (accErr >= d){break;}
}
this->accumulated_error_ = accErr;
return i;
}
/*std::mutex qsc_mutex;
std::mutex ntcnt_mutex;
std::vector<std::mutex> qsc_mutexes;
std::vector<std::mutex> ntcnt_mutexes;*/
void DNA::ntSpecQualScores(vector<long>& qsc, vector<long>& ntcnt) {
size_t sql = sequence_.length();
if (qsc.size() < sql) {
qsc.resize(sql,0);
}
if (ntcnt.size() < sql) {
ntcnt.resize(sql,0);
}
for (uint i = 0; i < sql; i++ ) {
short p = NT_POS[(int) sequence_[i]];
qsc[p] += qual_[i];
ntcnt[p]++;
}
}
void DNA::ntSpecQualScoresMT(vector<long>& qsc, vector<long>& ntcnt) {
size_t sql = sequence_.length();
if (qsc.size() < sql) {
qsc.resize(sql,0);
}
if (ntcnt.size() < sql) {
ntcnt.resize(sql,0);
}
for (uint i = 0; i < sql; i++ ) {
short p = NT_POS[(int) sequence_[i]];
qsc[p] += qual_[i];
ntcnt[p]++;
}
}
bool DNA::qualAccumTrim(double d){
if (d == -1.) {
return true;
}
unsigned int i(qualAccumulate(d));
if (i != this->length()){
//cut 3' end
this->cutSeqPseudo(i);
this->QualCtrl.AccErrTrimmed = true;
return false;
}
//did not cut this sequence:
return true;
}
bool DNA::qualWinPos(unsigned int W, float T){
if (T==0.f){return true;}
int AQ=0;
int unT = static_cast<int>((float)W*T);
unsigned int QS = this->length();// (unsigned int)qual_.size();
unsigned int QSh = QS >> 2;
QSh = max(QSh,W);
if (W>=QS){return true;} // too short
vector<float> WQ((int) W);
//TODO: check that the right num of nucs is taken..
int cnt=0;
if (QS < W) {return true;}
for (unsigned int i=QS-1; i> QS-(unsigned int) W-1; i--){
AQ += qual_[i];
cnt++;
}
if (AQ > unT){return true;}
int curW = QS-(unsigned int) W;
for (uint i=QS-(unsigned int) W-1; i > QSh; i--){
AQ += qual_[i];
AQ -= qual_[i + W];
if (AQ < unT){ //min Window qual_ was broken.. kick seq
curW = i;
} else {
break;
}
}
//partial seq removal
int pos = curW - (W>>1);
if (pos < 0) {pos = 0;}
this->cutSeqPseudo(pos);
this->QualCtrl.QWinTrimmed = true;
return false;
}
shared_ptr<DNA> DNA::getDNAsubseq(int start, int end, string id) {
shared_ptr<DNA> rdn = make_shared<DNA>();
rdn->setSequence(this->getSequence().substr(start,(end-start)) );
vector<qual_score> tq = this->getQual(start, end) ;
rdn->setQual(tq);
rdn->setHeader(id);
if (this->getBCnumber() >= 0) {
rdn->setBCnumber(this->getBCnumber(),0);
if (getBarcodeCut()) {
rdn->setBarcodeCut();
}
rdn->setBarcodeDetected(getBarcodeDetected());
}
return rdn;
}
//removes part of seq and qual_ indexes between start & stop
//set stop to -2 if cut till end in pseudo == true mode
bool DNA::cutSeq(int start, int stop, bool pseudo){
if (stop == -1) {
if (start >= (int) sequence_length_ || start < 0) { return false; }
} else if (start >= stop || start >= (int)qual_.size()) {
return false;
}
if (stop > (int)qual_.size()) {
stop = (int)qual_.size();
}
//pseudo deactivates cutting of 3'
if (pseudo) {
if (stop == -1 ){//|| stop <= (int) sequence_length_) {
sequence_length_ = start;
return true;
}
}
// this is to account for any already maybe incurred pseudo cuttings
int seqLDiff = int(sequence_.length() - sequence_length_);
string se = sequence_;
if (stop == -1) {
stop = (int)sequence_.length();
}
if (start == 0) {
sequence_ = se.substr(stop);
} else {
sequence_ = se.substr(0, start) + se.substr(stop);
}
//DN = sequence_.c_str();
//Quali
qual_.erase(qual_.begin() + start, qual_.begin() + stop);
sequence_length_ = sequence_.length() - seqLDiff;
return true;
}
int DNA::matchSeq(std::string PrSt,int Err,int searchSpace, int startPos,bool exhaustive){
//const char* DN = sequence_.c_str();
//const char* Pr = PrSt.c_str();
int PrL = (int) PrSt.length();
int mthL = this->length() - PrL;
//int wantSc = PrL - Err;
int endPos(-1),pos(startPos), Prp(0), c_err(0),Prp2(0), c_points(0), point_aim(1);
point_aim = max(1, int(PrL / 2));
//bool res(false);
vector<int> potentialMatches(0);