-
Notifications
You must be signed in to change notification settings - Fork 5
/
InputStream.h
1436 lines (1239 loc) · 40.4 KB
/
InputStream.h
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
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/>.
*/
#ifndef _InputStr_h
#define _InputStr_h
//input through combined getDNApairs
#define togRe//ad
//input through getDNAlines
#define IOsep
#define _CRT_SECURE_NO_DEPRECATE
#include "DNAconsts.h"
//#include "include/iowrap.h"
//#include "FastxReader.h"
#include <functional>
#include <cctype>
#include <locale>
#include <climits>
//#include "ThreadPool.h"
#include <fstream>
#include <shared_mutex>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <future>
#ifdef _isa1gzip
#include "include/GZipStr.h"
#endif
#ifdef _izlib
#include "include/izlib.h"
#else
#ifdef _gzipread
#include "include/gzstream.h"
#include "include/zstr.h"
#endif
/*typedef struct {
FILE* fp;char* mode;int is_plain;
// struct isal_gzip_header* gzip_header;
// struct inflate_state* state;
// struct isal_zstream* zstream;
uint8_t* buf_in;size_t buf_in_size;uint8_t* buf_out;size_t buf_out_size;
} gzFile_t;
int gzeof(gzFile_t* fp) { return 0; }
typedef gzFile_t* gzFile;
*/
#endif
extern char DNA_trans[256];
extern short DNA_amb[256];
extern short NT_POS[256];
extern short DNA_IUPAC[256 * 256];
typedef double matrixUnit;
typedef robin_hood::unordered_flat_map<int, long> read_occ;
string spaceX(uint k);
int digitsInt(int x);
int digitsFlt(float x);
string intwithcommas(int value);
std::string itos(int number);
std::string ftos(float number, int digits=4);
bool isGZfile(const string fileS);//test if file is gzipped input
static 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());
}
inline int parseInt(const char** p1);
static void cdbg(const string& x) {
#ifdef DEBUG
cerr << x;
#endif
}
//MOCAT header fix
std::vector<std::string> header_string_split(const std::string str, const std::string sep);
void remove_paired_info(string&, short = -1);
//MOCAT header fix
std::string header_stem(string& header);
std::istream& safeGetline(std::istream& is, std::string& t);
string reverseTS2(const std::string & Seq);
void reverseTS(std::string & Seq);
bool any_lowered(const string& is);
//this function changes input string (file location) to have consistent file names
string applyFileIT(string x, int it, const string xtr = "");
bool fileExists(const std::string& name, int i=-1,bool extiffail=true);
//vector<int> orderOfVec(vector<int>&);
struct filesStr {//used in separateByFile
vector<string> FastaF;
vector<string> QualF;
vector<string> FastqF;
vector<string> MIDfq;
vector<string> fastXtar;
// Indicates if FASTQ files were submitted
bool isFastq = true;
//input path
string path = "";
//set up some log structures
string deLog = "";//dereplication main log
string logF = "";// (*cmdArgs)["-log"];
string logFA = "";// (*cmdArgs)["-log"].substr(0, (*cmdArgs)["-log"].length() - 3) + "add.log";
// Unique Fas initialized with first element of tar (can be b_derep_as_fasta_ and fastq)
// Contains all unique b_derep_as_fasta_ or fastq files from the mapping file
unordered_map<string, int> uniqueFastxFiles;
// idx content: [ [0] ]
// idx contains one row (vector) for each unique string in tar
// This vector then contains the indices at which this string occurs in tar
vector < vector<int> > idx = vector<vector<int>>(0);
//rewrite uniqueFastxFiles to get it sorted after seqRun..
vector<pair<string, int>> uniqFxFls;
};
struct multi_tmp_lines {
multi_tmp_lines() :tmp(0) {}
multi_tmp_lines(int s) :tmp(0)
{
string empty(""); empty.reserve(151); vector<string>tmpLines2(4, empty);
vector<vector<string>> tmpLines(3, tmpLines2);
tmp.resize(s, tmpLines);
}
size_t size() { return tmp.size(); }
void setSize(size_t X) { tmp.resize(X); }
vector< vector< vector< string>>> tmp;
bool lastInFile = false;
};
//static mutex input_mtx;
class ifbufstream {//: private std::streambuf, public std::ostream {
public:
ifbufstream(const string& inF, size_t buf1=20000,bool isMC=false,bool test=false) :
file(inF),modeIO(ios::in),at(0),isGZ(false), atEnd(false), hasKickoff(false),
doMC(isMC), bufS(buf1), bufSW(buf1), primary(nullptr) //,primaryG(nullptr)
{
if (bufS < 10) {
cerr << "Buffer size chosen too small: " << bufS << endl << "class ifbufstream\n";
exit(236);
}
iniBufStrm();
if (isGZfile(file)) { //write a gzip out??
isGZ = true;
#if !defined(_gzipread) && !defined(_isa1gzip)
cerr << "ifbufstream::gzip input not supported in your sdm build\n" << file << endl;
exit(51);
#endif
}
openFstream();
if (!primary ){//} && !gzeof(primaryG)){
atEnd = true;
return;
}
if (test) {
return;
}
/*primary.seekg(0, primary.end);
int length = primary.tellg();
primary.seekg(0, is.beg);*/
//first round read..
input_mtx.lock();
//cerr << "ReadX";
#ifdef _izlib
if (isGZ) {
int rd = gzread(primaryG, keeper, bufS);
if (!gzeof(primaryG)) { bufSW = (size_t)rd + 1; }
if (!gzeof(primaryG) || bufS > rd) {
bufS = (size_t)rd + 1; atEnd = true;
delete[] keeperW; keeperW = nullptr;
}else { kickOff(); }
}
else {
primary->read(keeper, bufS);
if (!(*primary) || bufS > primary->gcount()) {
bufS = (size_t)primary->gcount() + 1; atEnd = true;
delete[] keeperW; keeperW = nullptr;
}else { kickOff(); }
}
#else
primary->read(keeper, bufS);
if (!(*primary) || bufS > primary->gcount()) {
bufS = (size_t)primary->gcount() + 1; atEnd = true;
delete[] keeperW; keeperW = nullptr;
} else { kickOff(); }
#endif
//cerr << keeper << endl;
//cerr << "Y";
input_mtx.unlock();
}
~ifbufstream() {
cdbg("destroy ibufstream ");
input_mtx.lock();
if (hasKickoff) { readKickoff.get(); hasKickoff = false;}
delete[] keeper; keeper = nullptr;
delete[] keeperW; keeperW = nullptr;
delete primary;
input_mtx.unlock();
}
void reset() {
input_mtx.lock();
if (hasKickoff) { readKickoff.get(); hasKickoff = false; }
at = 0;
primary->clear();
delete primary;
openFstream();
delete[] keeper; keeper = nullptr;
delete[] keeperW; keeperW = nullptr;
iniBufStrm();
primary->read(keeper, bufS);
if (!(*primary) || bufS > primary->gcount()) {
bufS = (size_t)primary->gcount() + 1; atEnd = true;
delete[] keeperW; keeperW = nullptr;
}else { kickOff(); }
input_mtx.unlock();
}
void setMC(bool b) { doMC = b; }
bool eof() {
return atEnd && at >= bufS;
}
bool operator! (void) {
return !atEnd;
}
void jumpLines(int x=1) {
string mpt;
for (int y = 0; y < x; y++) {
this->getline(mpt);
}
}
bool getlines(string& ret,int & linesRead, bool nwlRspace=false) {
ret.clear();
if (atEnd && at >= bufS) {
return false;
}
for (;;) {
if (at >= bufS && !readChunk()) {
return false;// read next chunk already
}
char c = keeper[at];
at++;
switch (c) {
case '\n':
if (at >= bufS && !readChunk()) {
return false;// read next chunk already
}
linesRead++;
if (nwlRspace) {
ret += ' ';
}
if (keeper[at] == '>') {
return true;
}
break;
case '\r':
if (at >= bufS && !readChunk()) {
return false;// read next chunk already
}
if (keeper[at] == '\n') {
linesRead++;
if (nwlRspace) {
ret += ' ';
}
at += 1;
if (at >= bufS && !readChunk()) {
return false;// read next chunk already
}
if (at < bufS && keeper[at] == '>') {
return true;
}
break;
}
case EOF:
// Also handle the case when the last line has no line ending
atEnd = true;
//primary->setstate(std::ios::eofbit);
return false;
default:
ret += c;
}
}
if (atEnd && at >= bufS) {
return false;
}
return true;
}
//specific function that gets fasta line looking for pattern '\n>'
bool get4lines(vector<string>& in) {
bool ret(false);
ret = this->getline(in[0]);
ret = this->getline(in[1]);
ret = this->getline(in[2]);
ret = this->getline(in[3]);
//cerr << in[0] << endl << in[1] << endl << in[2] << endl << in[3] << endl;exit(2);
return ret;
}
bool getline(string& ret) {
if (atEnd && at >= bufS) {
return false;
}
ret.clear(); locBuffer.clear();
size_t inStrPos = 0;
for (;;) {
char c = keeper[at];
at++;
if (at >= bufS ) {
if (!readChunk()) {
return false;// read next chunk already
}
}
switch (c) {
case '\n':
//ret = locBuffer;
return true;
case '\r':
if (keeper[at] == '\n') {
at+=1;
ret = locBuffer;
return true;
}
case EOF:
// Also handle the case when the last line has no line ending
atEnd = true;
//primary->setstate(std::ios::eofbit);
//ret = locBuffer;
return false;
default:
ret += c;
//locBuffer+=c;
//inStrPos++;
}
}
//ret = locBuffer;
if (atEnd && at >= bufS) {
return false;
}
return true;
}
string getInFile() { return file; }
private:
bool internalReadChunk() {
if (!*(primary)) {
if (keeperW != nullptr) { delete[] keeperW; }
keeperW = nullptr;
atEnd = true;
//bufS = primary->gcount()+1;
//keeperW[XX] = char_traits<char>::eof();
return false;
}
#ifdef _izlib
if (isGZ) {
int rd = gzread(primaryG, keeperW, bufS);
if (!gzeof(primaryG)) { bufSW = (size_t)rd + 1; }
} else {
primary->read(keeperW, bufS);
if (!*(primary)) { bufSW = (size_t)primary->gcount() + 1; }
}
#else
primary->read(keeperW, bufS);
if (!*(primary)) {bufSW = (size_t)primary->gcount() + 1;}
#endif
return true;
}
void openFstream() {
if (isGZ) {
#ifdef _isa1gzip
primary = new GzipIfstream(file.c_str(), 48* 1024*1024);
#elif defined(_izlib)
primaryG = gzopen(file.c_str(), "r");
#elif defined(_gzipread)
primary = new zstr::ifstream(file.c_str());
//primary = new igzstream(file.c_str());
#else
cerr << "gzip not supported in your sdm build\n (ifbufstream) " << file; exit(50);
#endif
}
else {
primary = new ifstream(file, modeIO);
}
/*
if (isGZ) {
#ifdef _isa1gzip
primary = std::make_unique<IsalGzipReader>(file);
#elif _gzipread && ! _isa1gzip
primary = std::make_unique<GzipReader>(file);
#else
cerr << "gzip not supported in your sdm build\n (ifbufstream) " << file; exit(50);
#endif
}
else {
primary = new UncompressedReader(file);
}
*/
}
bool kickOff() {
if (doMC) {//do MC?
if (!atEnd) {
assert(!hasKickoff);
//
hasKickoff = true;
readKickoff = async(std::launch::async, &ifbufstream::internalReadChunk,
this);
return true;
} else {
return false;
}
}
else {
// Without multithreading
return internalReadChunk();
}
}
bool readChunk() {
localMTX.lock();
if (hasKickoff) { hasKickoff = false; readKickoff.get(); }
if (atEnd && keeperW == nullptr) {
localMTX.unlock();
return false;
}
//do a swap, no memcpy needed
//input_mtx.lock(); // not needed here, is already in input lock from calling routine..
char* tmp = keeper;
keeper = keeperW;
keeperW = tmp;
bufS=bufSW;//replace length of read string
at = 0;
//input_mtx.unlock();
//memcpy(keeper, keeperW, bufS);
kickOff();
localMTX.unlock();
//primary->read(keeperW, bufS);
return true;
}
void iniBufStrm(){
cdbg("Ini ibufstream");
keeper = DBG_NEW char[bufS];
keeperW = DBG_NEW char[bufS];
for (uint x = 0; x < bufS; x++) {
keeper[x] = EOF; keeperW[x] = EOF;
}
}
string file;
char* keeper; char* keeperW;
string locBuffer;
ios_base::openmode modeIO;
size_t at;
bool isGZ, atEnd, hasKickoff, doMC;
istream* primary;
//gzFile primaryG;
//Reader* primary;
future<bool> readKickoff;
size_t bufS, bufSW ;
mutex localMTX;// , input_mtx2;
shared_mutex input_mtx;
};
std::ptrdiff_t len_common_prefix_base(char const a[], char const b[]);
//static mutex output_mtx;
class ofbufstream {//: private std::streambuf, public std::ostream {
public:
ofbufstream(size_t bufferS):file("T"), keeper(0), keeperW(0), modeIO(ios::app), used(0), usedW(0),
coutW(true), isGZ(false), doMC(false), bufS(0),hasKickoff(false){
int x = 0;
}
ofbufstream(const string IF, int mif, bool isMC = false, size_t bufferS = 20000);
~ofbufstream();
void finishWrites();
bool operator! (void);
void operator<< (const string& X);
void emptyStream();
void activate();
void deactivate();
// end
private:
mutex append_mtx_;
mutex output_mtx;
bool internalWrite(bool closeThis){
//output_mtx.lock();
primary->write(keeperW, usedW);
//output_mtx.unlock();
//delete[] keeperW;//clean up
if (closeThis) {
deactivate();
}
return true;
}
void write(std::string s, std::string file) {
{
// Lock the input area
//std::lock_guard<std::mutex> guard(output_mtx);
ofstream of(file.c_str(), ios::app);
of.write(s.c_str(), s.size());
of.close();
}
}
void writeStream(bool doKickoff = true);
//functions
string file;
char* keeper;
char* keeperW;
int modeIO;
size_t used, usedW;
//write to cout? gzip input? do multicore?
bool coutW, isGZ, doMC;
ostream* primary;
size_t bufS;
// Multithreading throw threadpool
//ThreadPool *pool = nullptr;//currently just used to check if MC or not
// end
future<bool> writeKickoff;
bool hasKickoff=false;
};
class dualOfBufStream {
public:
dualOfBufStream(void);
~dualOfBufStream(void);
void write(const string& in, int stream) {
assert(stream < bufs.size());
dualMtx.lock();
bufs[stream] += in;
dualMtx.unlock();
emptyStreams(false);
}
void write2(const string& in, const string& in2 ) {
// assert(opened[0]);
// if (!active) { activate(); }
dualMtx.lock();
//bufs[0] += in;bufs[1] += in2;
(*ostr[1]) << in2; (*ostr[0]) << in;
dualMtx.unlock();
// emptyStreams(false);
}
bool open(const string IF, int mif, int pair, bool isMC = false, size_t bufferS = 20000) {
assert(!opened[pair]);
ostr[pair] = DBG_NEW ofbufstream(IF, mif, isMC, bufferS);
opened[pair] = true;
FileNames[pair] = IF;
if (!ostr[pair]) { return false; }
return true;
}
bool activate() {
if (active) {return true;}
for (size_t i = 0; i < ostr.size(); i++) { if (ostr[i] != nullptr) { ostr[i]->activate(); } }
active = true;
cerr << "Activating dual ostreams: " << FileNames[0] << "," << FileNames[1] << endl;
return true;
}
bool deactivate() {
for (size_t i = 0; i < ostr.size(); i++) { if (ostr[i] != nullptr) { ostr[i]->deactivate(); } }
active = false;
return true;
}
void emptyStreams(bool force) {
if (force || bufs[1].size() >= buf2S) {
dualMtx.lock();
(*ostr[1]) << bufs[1];
bufs[1].clear();
dualMtx.unlock();
}
if (force || bufs[0].size() >= buf1S) {
dualMtx.lock();
(*ostr[0]) << bufs[0];
bufs[0].clear();
dualMtx.unlock();
}
}
private:
size_t buf1S, buf2S;
vector<string> bufs;
vector<string> FileNames;
vector<ofbufstream*> ostr;
vector<bool> opened;
bool active;
mutex dualMtx;
};
inline vector<string> splitByComma(const string& fileS,bool requireTwo, char SrchStr=','){
string::size_type pos = fileS.find(SrchStr);
if (pos == string::npos){
if (requireTwo){
cerr<<fileS<<endl;
cerr << "Could not find \"" << SrchStr<<"\" in input file (required for paired end sequences, as these are two files separated by \",\")\n";
exit(14);
}else {
return vector<string> (1,fileS);
}
}
vector<string> tfas(2,"");
tfas[0] = fileS.substr(0,pos);
tfas[1] = fileS.substr(pos+1);
return tfas;
}
inline vector<string> splitByCommas(const string& fileS, char SrchStr = ',') {
if (fileS.find(SrchStr) == string::npos) { return vector<string>(1, fileS); }
vector<string> res = splitByComma(fileS, true, SrchStr);
vector<string> ret(0); ret.push_back(res[0]);
while (res[1].find(SrchStr) != string::npos) {
res = splitByComma(res[1], true, SrchStr);
ret.push_back(res[0]);
}
ret.push_back(res[1]);
return ret;
}
//requires sorted vector with the entries being actual datapoints
template<class TYPE>
TYPE calc_median2(vector<TYPE>& in, float perc){
size_t sum = in.size() - 1;
if (sum < 0) { return 0; }
size_t tar = (size_t)(((float)sum) * perc);
return in[tar];
}
template<class TYPE>
TYPE median(vector<TYPE>& v)
{
size_t n = v.size() / 2;
nth_element(v.begin(), v.begin() + n, v.end());
return v[n];
}
//returns "i_fna" or "i_fastq"
string detectSeqFmt(const string);
class Filters;
class DNA: public std::enable_shared_from_this<DNA> {
friend class DNAunique;
public:
DNA(string seq, string names) : sequence_(seq), sequence_length_(sequence_.length()),
id_(names), new_id_(names),
qual_(0), qual_traf_(""), sample_id_(-1), avg_qual_(-1.f),
quality_sum_(0), accumulated_error_(0.),
failed_(false),good_quality_(false), mid_quality_(false),
reversed_(false),
read_position_(-1),
FtsDetected(),
id_fixed_(false), tempFloat(0.f),merge_offset_(-1){}
DNA(): sequence_(""), sequence_length_(0), id_(""), new_id_(""), qual_(0), qual_traf_(""),
sample_id_(-1), avg_qual_(-1.f),
quality_sum_(0), accumulated_error_(0.),
failed_(false),good_quality_(false), mid_quality_(false),
reversed_(false),
read_position_(-1),
FtsDetected(),
id_fixed_(false), tempFloat(0.f), merge_offset_(-1) {
sequence_.reserve(151);//set to resonable expectation
}
//starts with fastx record
//DNA(FastxRecord*, qual_score & minQScore, qual_score & maxQScore, qual_score fastQver);
//works directly with 4 lines in fastq format
DNA(vector<string> fq, qual_score fastQver);//fastq input
DNA(vector<string> fas);//this is for fasta only..
~DNA() {
//cout << "destruct" << endl;
}
bool operator==(DNA i) {
if (i.getSeqPseudo() == this->getSeqPseudo()) {
return true;
} else {
return false;
}
}
bool operator==(shared_ptr<DNA> i) {
if (i->getSeqPseudo() == this->getSeqPseudo()) {
return true;
} else {
return false;
}
}
//something wrong with DNA object, just del all info
void delself() {
sequence_ = ""; sequence_length_ = 0; id_ = ""; new_id_ = ""; qual_.resize(0);
good_quality_ = false; mid_quality_ = false; failed_ = true;
}
//~DNA(){}
void appendSequence(const string &s) { sequence_ += s; sequence_length_ = sequence_.length(); }
void appendQuality(const vector<qual_score> &q);
void fixQ0(void);
void setSequence(string & s) {
sequence_ = s;
sequence_length_ = sequence_.length();
} void setSequence(string && s) {
sequence_ = s;
sequence_length_ = sequence_.length();
}
string &getSequence() { return sequence_; }
const vector<qual_score>& getQual() const {
return qual_;
}
const vector<qual_score> getQual(int sta , int end ) const {
if (sta == 0 && end == 0) {
return qual_;
}
vector<qual_score>::const_iterator first = qual_.begin() + sta;
vector<qual_score>::const_iterator last = qual_.begin() + end;
vector<qual_score> newVec(first, last);
return newVec;
}
string getSeqPseudo() {
return sequence_.substr(0, sequence_length_);
}
void setQual(vector<qual_score> Q) { qual_ = move(Q); avg_qual_ = -1.f; }
//void setQual(vector<qual_score>&& Q) { qual_ = Q; avg_qual_ = -1.f; }
void setAllQual(qual_score q) { for (size_t i = 0; i < qual_.size(); i++) { qual_[i] = q; } avg_qual_ = -1.f;}
const string& getId() {
if (id_fixed_) {
return new_id_;
}
return id_;
}
shared_ptr<DNA> getDNAsubseq(int start, int end, string id);
string getPositionFreeId(); // remove /1 /2 #1:0 etc
const string& getOldId() { return id_; }
string getShortId() { return id_.substr(0, getShorterHeadPos(id_)); }
string getNewIDshort() { return new_id_.substr(0, getShorterHeadPos(new_id_)); }
bool seal(bool isFasta=false);
bool isEmpty() {
if (id_.empty() && sequence_.empty()) {
this->setPassed(false);
return true;
}
return false;
}
int numACGT();
void stripLeadEndN();
int numNonCanonicalDNA(bool);
float getAvgQual();
int getMedianQual();
unsigned int getQsum(){return quality_sum_;}
float qualWinfloat(uint,float,int&);
float binomialFilter(int, float);
//float qualWinfloat_hybr(int,float,int,float,int&);
bool qualWinPos(unsigned int,float);
bool qualAccumTrim(double d);
int qualAccumulate(double d);
double getAccumError(){
if (accumulated_error_ == 0.f) {
for (uint i = 0; i < qual_.size(); i++) {
if (qual_[i] >= 0) {
accumulated_error_ += SAqualP[qual_[i]];
}
}
}
if (std::isinf((double) accumulated_error_)) {
accumulated_error_ = 5.f;
}
return accumulated_error_;
}
int minQual(){int mq=50; for (uint i=0; i < qual_.size(); i++){if (qual_[i] < mq){ mq=qual_[i];}}return mq;}
void ntSpecQualScores(vector<long>&, vector<long>&);
void ntSpecQualScoresMT(vector<long>&, vector<long>&);
//returns qual filtered length
inline uint length() { return (uint) sequence_length_; }
//returns original length
inline uint mem_length() { return (uint) sequence_.length(); }
bool cutSeq(int start, int stop=-1, bool = false);
bool cutSeqPseudo(int start) { return cutSeq(start, -1, true); }
bool HomoNTRuns(int);
int matchSeq(string, int Err, int searchSpace, int startPos,bool exhaustive=false);
void reverse_compliment(bool reset=true);
int matchSeqRev(const string&, int Err, int searchSpace, int start=0,bool=false);
int matchSeq_tot(const string&, int, int, int&);
void writeSeq(ostream&, bool singleLine = false);
string writeSeq(bool singleLine = false);
void writeSeq(string& seq, bool singleLine = false);
void writeQual(ostream&, bool singleLine = false);
string writeQual(bool singleLine = false);
void writeQual(string&, bool singleLine = false);
void writeFastQ(ostream&, bool = true);
string writeFastQ(bool = true);
void writeFastQ(string&, bool = true);
//void writeFastQ(ofbufstream&, bool = true);
void writeFastQEmpty(ostream&);
void setNewID(string x) { new_id_ = x; }
void setHeader(string x){ new_id_=x;id_=x;}
void changeHeadPver(int ver);
void setTA_cut(bool x) { FtsDetected.TA_cut = x; }
bool getTA_cut() { return FtsDetected.TA_cut; }
void setBarcodeCut() { FtsDetected.barcode_cut = true; FtsDetected.barcode_detected = true; }
bool getBarcodeCut() { return FtsDetected.barcode_cut; }
void setBarcodeDetected(bool x){ FtsDetected.barcode_detected = x; }
bool getBarcodeDetected() { return FtsDetected.barcode_detected; }
bool isMIDseq() { if (read_position_ == 3) { return true; } return false; }
void setMIDseq(bool b){ if (b){ read_position_ = 3; } }
void setpairFWD(){ read_position_ = 0; }
void setpairREV(){ read_position_ = 1; }
int getReadMatePos() { return (int) read_position_; }
bool sameHeadPosFree(shared_ptr<DNA>);
bool sameHead(const string&);
//inline void reverseTranscribe();
void setTempFloat(float i){tempFloat = i;}
float getTempFloat(){return tempFloat;}
//void adaptHead(shared_ptr<DNA>,const int,const int);
void failed() { good_quality_ = false; mid_quality_ = false; failed_ = true; }
bool control(){ if (qual_.size() == 0){return false;}return true;}
void setBCnumber(int i, int BCoff) {
if (i < 0) {
sample_id_ = i ;
FtsDetected.barcode_detected = false;
} else {
sample_id_ = i + BCoff;
FtsDetected.barcode_detected = true;
}
}
//always return BC tag IDX global (no local filter idx accounted for, use getBCoffset() to correct)
int getBCnumber() const {
return sample_id_;
}
void prepareWrite(int fastQver);
void reset();
void resetTruncation() { sequence_length_ = sequence_.length(); }
void setPassed(bool b);
void setYellowQual(bool b) {
mid_quality_ = b; failed_ = false;
}
bool isFailed() {
return failed_;
}
bool isGreenQual(void) {
if (mid_quality_) { return false; }
return good_quality_;
}
bool isYellowQual(void) {
if (good_quality_) { return false; }
return mid_quality_;
}
bool isGreenYellowQual(void) {
return (mid_quality_ || good_quality_);
}
string getSubSeq(int sta, int sto){return sequence_.substr(sta, sto);}
void resetQualOffset(int off, bool solexaFmt);
//control & check what happened to any primers (if)
bool has2PrimersDetected() { return (FtsDetected.reverse && FtsDetected.forward); }
bool getRevPrimCut() { return FtsDetected.reverse; }
bool getFwdPrimCut() { return FtsDetected.forward; }
void setRevPrimCut() { FtsDetected.reverse = true; }
void setFwdPrimCut() { FtsDetected.forward = true; }
void setDereplicated() { FtsDetected.dereplicated = true; }
bool isDereplicated() { return FtsDetected.dereplicated ; }
void constellationPairRev(bool b) { FtsDetected.revPairConstellation = b; }
bool isConstellationPairRev() { return FtsDetected.revPairConstellation ; }
int getMergeLength() { return FtsDetected.mergeLength; }
//only used in pre best seed step
//float getSeedScore() { return tempFloat; }
//void setSeedScore(float i) { tempFloat = (float)i; }
struct QualStats {
bool maxL; bool PrimerFwdFail; bool AvgQual; //sAvgQual
bool HomoNT; bool PrimerRevFail; bool minL;
bool minLqualTrim; //<-sMinQTrim trimmed due to quality
bool TagFail; bool MaxAmb; bool QualWin;//sQualWin
bool AccErrTrimmed; bool QWinTrimmed; // either of these makes bool Trimmed;
bool fail_correct_BC; bool suc_correct_BC; bool
failedDNAread;
//bool adapterRem; -> setTA_cut
bool RevPrimFound;
bool BinomialErr; bool dblTagFail;
QualStats() :
maxL(false), PrimerFwdFail(false), AvgQual(false), HomoNT(false),
PrimerRevFail(false), minL(false), minLqualTrim(false),
TagFail(false), MaxAmb(false), QualWin(false),
AccErrTrimmed(false), QWinTrimmed(false),
fail_correct_BC(false), suc_correct_BC(false),
failedDNAread(false), RevPrimFound(false),
BinomialErr(false),
dblTagFail(false)
{}
} QualCtrl;
protected:
size_t getShorterHeadPos(const string & x, int fastQheadVer = -1);
//mainly used to mark if rev/Fwd primer was detected
string xtraHdStr();
size_t getSpaceHeadPos(const string & x);
//binomial accumulated error calc
inline float interpolate(int errors1, float prob1, int errors2, float prob2, float alpha);
float 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);
inline float prob_j_errors(float p, float j, float n);
inline bool matchDNA(char,char);
std::string sequence_;
size_t sequence_length_;
string id_, new_id_; //original and newly constructed id_
vector<qual_score> qual_;
public: