-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfqtrim.cpp
More file actions
2445 lines (2318 loc) · 70.6 KB
/
Copy pathfqtrim.cpp
File metadata and controls
2445 lines (2318 loc) · 70.6 KB
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
#define VERSION "0.9.7"
#include "GArgs.h"
#include "GStr.h"
#include "GHash.hh"
#include "GList.hh"
#include <ctype.h>
#include "GAlnExtend.h"
#ifndef NOTHREADS
#include "GThreads.h"
#endif
#include "time.h"
#include "sys/time.h"
//DEBUG ONLY: uncomment this to show trimming progress
//#define TRIMDEBUG 1
#define USAGE "fqtrim v" VERSION ". Usage:\n\
fqtrim [{-5 <5adapter> -3 <3adapter>|-f <adapters_file>}] [-a <min_match>]\\\n\
[-R] [-q <minq> [-t <trim_max_len>]] [-p <numcpus>] [-P {64|33}] \\\n\
[-m <max_percN>] [--ntrimdist=<max_Ntrim_dist>] [-l <minlen>] [-C]\\\n\
[-o <outsuffix> [--outdir <outdir>]] [-D][-Q][-O] [-n <rename_prefix>]\\\n\
[-r <trim_report.txt>] [-y <min_poly>] [-A|-B] <input.fq>[,<input_mates.fq>\\\n\
\n\
Trim low quality bases at the 3' end and can trim adapter sequence(s), filter\n\
for low complexity and collapse duplicate reads.\n\
If read pairs should be trimmed and kept together (i.e. never discarding\n\
only one read in a pair), the two file names should be given delimited by a comma\n\
or a colon character.\n\
\n\
Options:\n\
-n rename the reads using the <prefix> followed by a read counter;\n\
if -C option was also provided, the suffix \"_x<N>\" is appended\n\
(where <N> is the read duplication count)\n\
-o write the trimmed/filtered reads to file(s) named <input>.<outsuffix>\n\
which will be created in the current (working) directory (unless --outdir\n\
is used); this suffix should include the file extension; if this extension\n\
is .gz, .gzip or .bz2 then the output will be compressed accordingly.\n\
NOTE: if the input file is '-' (stdin) then this is the full name of the\n\
output file, not just the suffix.\n\
--outdir for -o option, write the output file(s) to <outdir> directory instead\n\
-f file with adapter sequences to trim, each line having this format:\n\
[<5_adapter_sequence>][ <3_adapter_sequence>]\n\
-5 trim the given adapter or primer sequence at the 5' end of each read\n\
(e.g. -5 CGACAGGTTCAGAGTTCTACAGTCCGACGATC)\n\
-3 trim the given adapter sequence at the 3' end of each read\n\
(e.g. -3 TCGTATGCCGTCTTCTGCTTG)\n\
-A disable polyA/T trimming (enabled by default)\n\
-B trim polyA/T at both ends (default: only poly-A at 3' end, poly-T at 5')\n\
-O output only reads affected by trimming (discard clean reads!)\n\
-y minimum length of poly-A/T run to remove (6)\n\
-q trim read ends where the quality value drops below <minq>\n\
-w for -q, sliding window size for calculating avg. quality (default 6)\n\
-t for -q, limit maximum trimming at either end to <trim_max_len>\n\
-m maximum percentage of Ns allowed in a read after trimming (default 5)\n\
-l minimum read length after trimming (if the remaining sequence is shorter\n\
than this, the read will be discarded (trashed)(default: 16)\n\
-r write a \"trimming report\" file listing the affected reads with a list\n\
of trimming operations\n\
-s1/-s2: for paired reads, one of the reads (1 or 2) is not being processed\n\
(no attempt to trim it) but the pair is discarded if the other read is\n\
trashed by the trimming process\n\
--aidx option can only be given with -r and -f options and it makes all the \n\
vector/adapter trimming operations encoded as a,b,c,.. instead of V,\n\
corresponding to the order of adapter sequences in the -f file\n\
-T write the number of bases trimmed at 5' and 3' ends after the read names\n\
in the FASTA/FASTQ output file(s)\n\
-D pass reads through a low-complexity (dust) filter and discard any read\n\
that has over 50% of its length masked as low complexity\n\
--dmask option is the same with -D but fqtrim will actually mask the low \n\
complexity regions with Ns in the output sequence\n\
-C collapse duplicate reads and append a _x<N>count suffix to the read\n\
name (where <N> is the duplication count)\n\
-p use <numcpus> CPUs (threads) on the local machine\n\
-P input is phred64/phred33 (use -P64 or -P33)\n\
-Q convert quality values to the other Phred qv type\n\
-M disable read name consistency check for paired reads\n\
-V show verbose trimming summary\n\
Advanced adapter/primer match options (for -f or -5 , -3 options):\n\
-a minimum length of exact suffix-prefix match with adapter sequence that\n\
can be trimmed at either end of the read (default: 6)\n\
--pid5 minimum percent identity for adapter match at 5' end (default 96.0)\n\
--pid3 minimum percent identity for adapter match at 3' end (default 94.0)\n\
--mism mismatch penalty for scoring the adapter alignment (default 3)\n\
--match match reward for scoring the adapter alignment (default 1)\n\
-R also look for terminal alignments with the reverse complement\n\
of the adapter sequence(s)\n\
"
/*
--mdist maximum distance from the ends of the read for an adapter\n\
alignment to be considered for trimming; can be given as\n\
a percentage of read length if followed by '%' (default: \n\
*/
// example 3' adapter for miRNAs: TCGTATGCCGTCTTCTGCTTG
//For paired reads sequencing:
//3' : ACACTCTTTCCCTACACGACGCTCTTCCGATCT
//5' : GATCGGAAGAGCGGTTCAGCAGGAATGCCGAG
//FILE* f_out=NULL; //stdout if not provided
//FILE* f_out2=NULL; //for paired reads
//FILE* f_in=NULL; //input fastq (stdin if not provided)
//FILE* f_in2=NULL; //for paired reads
FILE* freport=NULL;
bool debug=false;
bool verbose=false;
bool doCollapse=false;
bool doDust=false;
bool doPolyTrim=true;
bool fastaOutput=false;
bool trimReport=false; //create a trim/trash report file
bool showAdapterIdx=false;
bool trimInfo=false; //trim info added to the output reads
bool polyBothEnds=false; //attempt poly-A/T trimming at both ends
bool onlyTrimmed=false; //report only trimmed reads
bool show_Trim=false;
bool dustMask=false;
bool pairedOutput=false;
bool revCompl=false; //also reverse complement adapter sequences
bool disableMateNameCheck=false;
int adapter_idx=0;
int min_read_len=16;
int num_cpus=1; // -p option
int readBufSize=200; //how many reads to fetch at a time (useful for multi-threading)
int shieldMate=0; //-s option, shield a mate from trimming but discard the pair
//if the other mate gets trashed
double max_perc_N=5.0;
double perc_lenN=12.0; // incremental distance from ends, in percentage of read length
// where N-trimming is allowed (default:12 %) (autolimited to 20)
int dist_lenN=0; // incremental distance from either end (in bp)
// where N-trimming is allowed (default: none, perc_lenN controls it)
int dust_cutoff=16;
bool isfasta=false;
bool convert_phred=false;
GStr outdir(".");
GStr outsuffix; // -o
GStr prefix;
GStr zcmd;
char isACGT[256];
uint inCounter=0;
uint outCounter=0;
int gtrash_s=0;
int gtrash_poly=0;
int gtrash_Q=0;
int gtrash_N=0;
int gtrash_D=0;
int gtrash_V=0;
int gtrash_X=0;
uint gnum_trimN=0; //reads trimmed by N%
uint gnum_trimQ=0; //reads trimmed by qv threshold
uint gnum_trimV=0; //reads trimmed by adapter match
uint gnum_trimA=0; //reads trimmed by polyA
uint gnum_trimT=0; //reads trimmed by polyT
uint gnum_trim5=0; //number of reads trimmed at 5' end
uint gnum_trim3=0; //number of reads trimmed at 3' end
uint64 gb_totalIn=0; //total number of input bases
uint64 gb_totalN=0; //total number of undetermined bases found in input bases
uint64 gb_trimN=0; //total number of bases trimmed due to N-trim
uint64 gb_trimQ=0; //number of bases trimmed due to qv threshold
uint64 gb_trimV=0; //total number of bases trimmed due to adapter matches
uint64 gb_trimA=0; //number of bases trimmed due to poly-A tails
uint64 gb_trimT=0; //number of bases trimmed due to poly-T tails
uint64 gb_trim5=0; //total bases trimmed on the 5' side
uint64 gb_trim3=0; //total bases trimmed on the 3' side
//int min_trimmed5=INT_MAX;
//int min_trimmed3=INT_MAX;
int qvtrim_qmin=0;
int qvtrim_max=0; //(-t) for -q, do not trim the 3'-end more than this number of bases
int qvtrim_win=6; //(-w) for -q, sliding window length for avg qual calculation
int qv_phredtype=0; // could be 64 or 33 (0 means undetermined yet)
int qv_cvtadd=0; //could be -31 or +31
// adapter matching metrics -- for X-drop ungapped extension
//const int match_reward=2;
//const int mismatch_penalty=3;
int match_reward=1;
int mismatch_penalty=3;
int Xdrop=8;
int minEndAdapter=6;
//adapter matching percent identiy thresholds:
double min_pid3=94.0; //min % identity for primer/adapter match at 3' end
double min_pid5=96.0; //min % identity for primer/adapter match at 5' end
const int poly_m_score=2; //match score for poly-A/T extension
const int poly_mis_score=-3; //mismatch for poly-A/T extension
const int poly_dropoff_score=7;
int poly_minScore=12; //i.e. an exact match of 6 bases at the proper ends WILL be trimmed
const char *polyA_seed="AAAA";
const char *polyT_seed="TTTT";
#ifndef NOTHREADS
GFastMutex readMutex; //reading input
GFastMutex writeMutex; //writing the output reads
GFastMutex reportMutex; //trim report writing
GFastMutex statsMutex; //for updating global stats
void workerThread(GThreadData& td); // Thread function
#endif
struct STrimOp {
byte tend; //5 or 3
char tcode; //'N','A','T','V' or 'a'..'z'
short tlen; //trim length
STrimOp(byte e=0, char c=0, short l=0) {
assign(e,c,l);
}
void assign(byte e,char c, short l) {
tend=e;
tcode=c;
tlen=l;
}
};
struct RData {
GStr seq;
GStr qv;
GStr rid;
GStr rinfo;
GVec<STrimOp> trimhist;
int trim5;
int trim3;
char trashcode;
int l3() { return seq.length()-trim3-1; }
RData():seq(),qv(),rid(),rinfo(), trimhist(), trim5(0), trim3(0), trashcode(0) {}
GStr getTrimSeq() {
if (trim5 || trim3)
return seq.substr(trim5, seq.length()-trim5-trim3);
else return seq;
}
GStr getTrimQv() {
if (trim5 || trim3)
return qv.substr(trim5, qv.length()-trim5-trim3);
else return qv;
}
void clear() { seq="";qv="";rid="";rinfo=""; trimhist.Clear();
trim5=0; trim3=0; trashcode=0; }
};
struct RInfo {
GLineReader* fq;
GLineReader* fq2;
FILE* f_out;
FILE* f_out2;
GStr infname;
GStr infname2;
RInfo(FILE* fo=NULL, FILE* fo2=NULL, GLineReader* fl=NULL,
GLineReader* fl2=NULL): fq(fl), fq2(fl2),
f_out(fo), f_out2(fo2), infname(), infname2() { }
};
struct CASeqData {
//positional data for every possible hexamer in an adapter
GVec<uint16>* pz[4096]; //0-based coordinates of all possible hexamers in the adapter sequence
GVec<uint16>* pzr[4096]; //0-based coordinates of all possible hexamers for the reverse complement of the adapter sequence
GStr seq; //actual adapter sequence data
GStr seqr; //reverse complement sequence
int fidx; //index of adapter in the file (order they are given)
int amlen; //fraction of adapter length matching that's enough to consider the alignment
GAlnTrimType trim_type;
bool use_reverse;
CASeqData(bool rev=false, int aidx=0):seq(),seqr(),
fidx(aidx), amlen(0), use_reverse(rev) {
trim_type=galn_None; //should be updated later!
for (int i=0;i<4096;i++) {
pz[i]=NULL;
pzr[i]=NULL;
}
}
void update(const char* s) {
seq=s;
table6mers(seq.chars(), seq.length(), pz);
amlen=calc_safelen(seq.length());
if (!use_reverse) return;
//reverse complement
seqr=s;
int slen=seq.length();
for (int i=0;i<slen;i++)
seqr[i]=ntComplement(seq[slen-i-1]);
table6mers(seqr.chars(), seqr.length(), pzr);
}
void freePosData() {
for (int i=0;i<4096;i++) {
delete pz[i];
delete pzr[i];
}
}
~CASeqData() { freePosData(); }
};
GPVec<CASeqData> adapters5(false);
GPVec<CASeqData> adapters3(false);
GPVec<CASeqData> all_adapters(true);
// element in dhash:
class FqDupRec {
public:
int count; //how many of these reads are the same
int len; //length of qv
char* firstname; //optional, only if we want to keep the original read names
char* qv;
FqDupRec(GStr* qstr=NULL, const char* rname=NULL) {
len=0;
qv=NULL;
firstname=NULL;
count=0;
if (qstr!=NULL) {
qv=Gstrdup(qstr->chars());
len=qstr->length();
count++;
}
if (rname!=NULL) firstname=Gstrdup(rname);
}
~FqDupRec() {
GFREE(qv);
GFREE(firstname);
}
void add(GStr& d) { //collapse another record into this one
if (d.length()!=len)
GError("Error at FqDupRec::add(): cannot collapse reads with different length!\n");
count++;
for (int i=0;i<len;i++)
qv[i]+=(d[i]-qv[i])/count; //the mean is calculated incrementally
}
};
struct CTrimHandler {
CGreedyAlignData* gxmem_l;
CGreedyAlignData* gxmem_r;
GVec<RData> rbuf; //read buffer
int rbuf_p; //index of next read unprocessed from the reading buffer
GVec<RData> rbuf2; //mate read buffer
int rbuf2_p;
RInfo* rinfo;
int incounter;
int outcounter;
int trash_s;
int trash_poly;
int trash_Q;
int trash_N;
int trash_D;
int trash_V;
int trash_X;
uint num_trimN, num_trimQ, num_trimV,
num_trimA, num_trimT, num_trim5, num_trim3;
uint64 b_totalIn, b_totalN, b_trimN, b_trimQ,
b_trimV, b_trimA, b_trimT, b_trim5, b_trim3;
CTrimHandler(RInfo* ri=NULL): gxmem_l(NULL), gxmem_r(NULL), rbuf(readBufSize), rbuf_p(-1),
rbuf2(0),rbuf2_p(-1), rinfo(ri), incounter(0), outcounter(0),trash_s(0), trash_poly(0),
trash_Q(0), trash_N(0), trash_D(0), trash_V(0),
trash_X(0),
num_trimN(0), num_trimQ(0), num_trimV(0), num_trimA(0), num_trimT(0), num_trim5(0), num_trim3(0),
b_totalIn(0), b_totalN(0), b_trimN(0), b_trimQ(0), b_trimV(0),
b_trimA(0), b_trimT(0), b_trim5(0), b_trim3(0) {
if (adapters5.Count()>0)
gxmem_l=new CGreedyAlignData(match_reward, mismatch_penalty, Xdrop);
if (adapters3.Count()>0)
gxmem_r=new CGreedyAlignData(match_reward, mismatch_penalty, Xdrop);
if (ri && ri->fq2) {
rbuf2.setCapacity(readBufSize);
}
}
void updateTrashCounts(RData& rd);
void Clear() {
rbuf_p=0; rbuf2_p=0;
incounter=0; outcounter=0;
rbuf.Clear(); rbuf2.Clear();
trash_s=0; trash_poly=0;
trash_Q=0; trash_N=0;
trash_X=0;
trash_D=0; num_trimV=0;
num_trimN=0;num_trimQ=0;
num_trimA=0;num_trimT=0;
num_trim5=0;num_trim3=0;
b_totalIn=0;b_totalN=0;
b_trimN=0;b_trimQ=0;
b_trimV=0;b_trimA=0;b_trimT=0;
b_trim5=0;b_trim3=0;
}
void updateCounts() {
#ifndef NOTHREADS
GLockGuard<GFastMutex> guard(statsMutex);
#endif
inCounter+=incounter;
outCounter+=outcounter;
gtrash_s+=trash_s;
gtrash_poly+=trash_poly;
gtrash_Q+=trash_Q;
gtrash_N+=trash_N;
gtrash_D+=trash_D;
gtrash_V+=trash_V;
gtrash_X+=trash_X;
gnum_trimN+=num_trimN;
gnum_trimQ+=num_trimQ;
gnum_trimV+=num_trimV;
gnum_trimA+=num_trimA;
gnum_trimT+=num_trimT;
gnum_trim5+=num_trim5;
gnum_trim3+=num_trim3;
gb_totalIn+=b_totalIn;
gb_totalN+=b_totalN;
gb_trimN+=b_trimN;
gb_trimQ+=b_trimQ;
gb_trimV+=b_trimV;
gb_trimA+=b_trimA;
gb_trimT+=b_trimT;
gb_trim5+=b_trim5;
gb_trim3+=b_trim3;
}
~CTrimHandler() {
delete gxmem_l;
delete gxmem_r;
}
void processAll();
bool fetchReads();
void flushReads();
void writeRead(RData& rd, RData* rd2);
//writes the output read/pair after processing
//also implements pair survival decision logic
bool nextRead(RData* & rdata, RData* & rdata2);
bool processRead();
char process_read(RData& r);
//returns 0 if the read was untouched, 1 if it was trimmed and a trash code if it was trashed
//void trim_report(char trashcode, GStr& rname, GVec<STrimOp>& t_hist, FILE* freport);
void trim_report(RData& rd, int mate=0);
bool ntrim(GStr& rseq, int &l5, int &l3, double& pN); //returns true if any trimming occured
bool qtrim(GStr& qvs, int &l5, int &l3); //return true if any trimming occured
bool trim_poly5(GStr &seq, int &l5, int &l3, const char* poly_seed); //returns true if any trimming occured
bool trim_poly3(GStr &seq, int &l5, int &l3, const char* poly_seed);
bool trim_adapter5(GStr& seq, int &l5, int &l3, int &aidx); //returns true if any trimming occured
bool trim_adapter3(GStr& seq, int &l5, int &l3, int &aidx);
};
//bool getBufRead(GVec<RData>& rbuf, int& rbuf_p, GLineReader* fq, GStr& infname, RData& rdata);
int dust(GStr& seq);
void openfw(FILE* &f, GArgs& args, char opt) {
GStr s=args.getOpt(opt);
if (!s.is_empty()) {
if (s=='-') f=stdout;
else {
f=fopen(s.chars(),"w");
if (f==NULL) GError("Error creating file: %s\n", s.chars());
}
}
}
#define FWCLOSE(fh) if (fh!=NULL && fh!=stdout) fclose(fh)
#define FRCLOSE(fh) if (fh!=NULL && fh!=stdin) fclose(fh)
GHash<FqDupRec> dhash; //hash to keep track of duplicates
void addAdapter(GPVec<CASeqData>& adapters, GStr& seq, GAlnTrimType trim_type);
int loadAdapters(const char* fname);
void setupFiles(FILE*& f_in, FILE*& f_in2, FILE*& f_out, FILE*& f_out2,
GStr& s, GStr& infname, GStr& infname2);
// uses outsuffix to generate output file names and open file handles as needed
void convertPhred(char* q, int len);
void convertPhred(GStr& q);
int main(int argc, char* argv[]) {
GArgs args(argc, argv, "pid5=pid3=mism=ntrimdist=match=XDROP=outdir=dmask;aidx;showtrim;YQDCRVABOTMl:d:3:5:m:n:r:p:s:P:q:f:w:t:o:z:a:y:");
int e;
if ((e=args.isError())>0) {
GMessage("%s\nInvalid argument: %s\n", USAGE, argv[e]);
exit(224);
}
debug=(args.getOpt('Y')!=NULL);
verbose=(args.getOpt('V')!=NULL);
convert_phred=(args.getOpt('Q')!=NULL);
doCollapse=(args.getOpt('C')!=NULL);
doDust=(args.getOpt('D')!=NULL);
revCompl=(args.getOpt('R')!=NULL);
polyBothEnds=(args.getOpt('B')!=NULL);
onlyTrimmed=(args.getOpt('O')!=NULL);
show_Trim=(args.getOpt("showtrim")!=NULL);
dustMask=(args.getOpt("dmask")!=NULL);
if (dustMask) doDust=true;
disableMateNameCheck=(args.getOpt('M')!=NULL);
if (args.getOpt('A')) doPolyTrim=false;
/*
rawFormat=(args.getOpt('R')!=NULL);
if (rawFormat) {
GError("Sorry, raw qseq format parsing is not implemented yet!\n");
}
*/
prefix=args.getOpt('n');
GStr s=args.getOpt('l');
if (!s.is_empty())
min_read_len=s.asInt();
s=args.getOpt('m');
if (!s.is_empty())
max_perc_N=s.asDouble();
s=args.getOpt('d');
if (!s.is_empty()) {
dust_cutoff=s.asInt();
doDust=true;
}
s=args.getOpt('q');
if (!s.is_empty()) {
qvtrim_qmin=s.asInt();
}
s=args.getOpt('w');
if (!s.is_empty()) {
qvtrim_win=s.asInt(); //must be >0 !
if (qvtrim_win<1) qvtrim_win=1;
}
s=args.getOpt('t');
if (!s.is_empty()) {
qvtrim_max=s.asInt();
}
s=args.getOpt('s');
if (!s.is_empty()) {
shieldMate=s.asInt();
if (shieldMate<=0 or shieldMate>2) {
GError("Error: -s option can only have value 1 or 2\n");
}
}
s=args.getOpt("match");
if (!s.is_empty())
match_reward=s.asInt();
s=args.getOpt("ntrimdist");
if (!s.is_empty()) {
dist_lenN=s.asInt();
if (dist_lenN<=0) GError("Error: invalid --ntrimdist value, must be >0\n");
}
s=args.getOpt("mism");
if (!s.is_empty()) {
mismatch_penalty=s.asInt();
if (mismatch_penalty<0)
mismatch_penalty=-mismatch_penalty;
}
s=args.getOpt("pid5");
if (!s.is_empty()) {
min_pid5=s.asReal();
//if (min_pid5<50 || min_pid5>100.0) GError();
}
s=args.getOpt("pid3");
if (!s.is_empty()) {
min_pid3=s.asReal();
}
s=args.getOpt("XDROP");
if (!s.is_empty())
Xdrop=s.asInt();
s=args.getOpt('p');
if (!s.is_empty()) {
num_cpus=s.asInt();
if (doCollapse) {
GMessage("Warning: -p option ignored (not supported with -C).\n");
num_cpus=1;
} else
if (num_cpus<1) {
GMessage("Warning: invalid number of threads specified (-p option).\n");
num_cpus=1;
}
}
s=args.getOpt('P');
if (!s.is_empty()) {
int v=s.asInt();
if (v==33) {
qv_phredtype=33;
qv_cvtadd=31;
}
else if (v==64) {
qv_phredtype=64;
qv_cvtadd=-31;
}
else
GMessage("%s\nInvalid value for -P option (can only be 64 or 33)!\n",USAGE);
}
memset((void*)isACGT, 0, 256);
isACGT['A']=isACGT['a']=isACGT['C']=isACGT['c']=1;
isACGT['G']=isACGT['g']=isACGT['T']=isACGT['t']=1;
s=args.getOpt('f');
if (!s.is_empty()) {
loadAdapters(s.chars());
}
bool fileAdapters=adapters5.Count()+adapters3.Count();
s=args.getOpt('5');
if (!s.is_empty()) {
if (fileAdapters)
GError("Error: options -5 and -f cannot be used together!\n");
s.upper();
addAdapter(adapters5, s, galn_TrimLeft);
}
s=args.getOpt('3');
if (!s.is_empty()) {
if (fileAdapters)
GError("Error: options -3 and -f cannot be used together!\n");
s.upper();
addAdapter(adapters3, s, galn_TrimRight);
}
s=args.getOpt('y');
if (!s.is_empty()) {
int minmatch=s.asInt();
if (minmatch>2)
poly_minScore=minmatch*poly_m_score;
else GMessage("Warning: invalid -y option, ignored.\n");
}
s=args.getOpt('a');
if (!s.is_empty()) {
int minmatch=s.asInt();
if (minmatch>2)
minEndAdapter=minmatch;
else GMessage("Warning: invalid -a option, ignored.\n");
}
if (args.getOpt('o')!=NULL) outsuffix=args.getOpt('o');
else outsuffix="-";
if (args.getOpt("outdir")!=NULL) {
outdir=args.getOpt("outdir");
if (outdir.length()==0) outdir=".";
outdir.chomp("/");
}
trimReport = (args.getOpt('r')!=NULL);
trimInfo = (args.getOpt('T')!=NULL);
if (args.getOpt("aidx")!=NULL) {
if (!trimReport || !fileAdapters)
GError("Error: option --aidx requires -f and -r options.\n");
showAdapterIdx=true;
}
int fcount=args.startNonOpt();
if (fcount==0) {
GMessage(USAGE);
exit(224);
}
if (fcount>1 && doCollapse) {
GError("%s Sorry, the -C option only works with a single input file.\n", USAGE);
}
if (verbose) args.printCmdLine(stderr);
if (trimReport)
openfw(freport, args, 'r');
char* infile=NULL;
while ((infile=args.nextNonOpt())!=NULL) {
//for each input file
inCounter=0; //counter for input reads
outCounter=0; //counter for output reads
gtrash_s=0; //too short from the get go
gtrash_Q=0;
gtrash_N=0;
gtrash_D=0;
gtrash_poly=0;
gtrash_V=0;
gtrash_X=0;
gnum_trimN=0;
gnum_trimQ=0;
gnum_trimV=0;
gnum_trimA=0;
gnum_trimT=0;
gnum_trim5=0;
gnum_trim3=0;
gb_totalIn=0;
gb_totalN=0;
gb_trimN=0;
gb_trimQ=0;
gb_trimV=0;
gb_trimA=0;
gb_trimT=0;
gb_trim5=0;
gb_trim3=0;
s=infile;
GStr infname;
GStr infname2;
FILE* f_in=NULL;
FILE* f_in2=NULL;
FILE* f_out=NULL;
FILE* f_out2=NULL;
bool paired_reads=false;
setupFiles(f_in, f_in2, f_out, f_out2, s, infname, infname2);
GLineReader fq(f_in);
GLineReader* fq2=NULL;
if (f_in2!=NULL) {
fq2=new GLineReader(f_in2);
paired_reads=true;
}
RInfo rinfo(f_out, f_out2, &fq, fq2);
rinfo.infname=infname;
rinfo.infname2=infname2;
#ifndef NOTHREADS
GThread *threads=new GThread[num_cpus];
for (int t=0;t<num_cpus;t++) {
threads[t].kickStart(workerThread, &rinfo);
}
#else
CTrimHandler* trimmer=new CTrimHandler(&rinfo);
trimmer->processAll();
delete trimmer;
#endif
#ifndef NOTHREADS
for (int i=0;i<num_cpus;i++)
threads[i].join();
delete[] threads;
#endif
delete fq2;
FRCLOSE(f_in);
FRCLOSE(f_in2);
if (doCollapse) {
outCounter=0;
int maxdup_count=1;
char* maxdup_seq=NULL;
dhash.startIterate();
FqDupRec* qd=NULL;
char* seq=NULL;
while ((qd=dhash.NextData(seq))!=NULL) {
GStr rseq(seq);
//do the dusting here
if (doDust) {
int dustbases=dust(rseq);
if (dustbases>(rseq.length()>>1)) {
if (trimReport && qd->firstname!=NULL) {
fprintf(freport, "%s_x%d\tD\n",qd->firstname, qd->count);
}
gtrash_D+=qd->count;
continue;
}
}
outCounter++;
if (qd->count>maxdup_count) {
maxdup_count=qd->count;
maxdup_seq=seq;
}
if (isfasta) {
if (prefix.is_empty()) {
fprintf(f_out, ">%s_x%d\n%s\n", qd->firstname, qd->count,
rseq.chars());
}
else { //use custom read name
fprintf(f_out, ">%s%08d_x%d\n%s\n", prefix.chars(), outCounter,
qd->count, rseq.chars());
}
}
else { //fastq format
if (convert_phred) convertPhred(qd->qv, qd->len);
if (prefix.is_empty()) {
fprintf(f_out, "@%s_x%d\n%s\n+\n%s\n", qd->firstname, qd->count,
rseq.chars(), qd->qv);
}
else { //use custom read name
fprintf(f_out, "@%s%08d_x%d\n%s\n+\n%s\n", prefix.chars(), outCounter,
qd->count, rseq.chars(), qd->qv);
}
}
}//for each element of dhash
if (maxdup_count>1) {
GMessage("Maximum read multiplicity: x %d (read: %s)\n",maxdup_count, maxdup_seq);
}
} //collapse entries
if (verbose) {
if (paired_reads) {
GMessage(">Input files : %s , %s\n", infname.chars(), infname2.chars());
GMessage("Number of input pairs :%9u\n", inCounter);
if (onlyTrimmed)
GMessage(" Output pairs :%9u\t(trimmed only)\n", outCounter);
else
GMessage(" Output pairs :%9u\t(%u discarded)\n", outCounter, inCounter-outCounter);
}
else {
GMessage(">Input file : %s\n", infname.chars());
GMessage("Number of input reads :%9d\n", inCounter);
GMessage(" Output reads :%9d (%u discarded)\n", outCounter, inCounter-outCounter);
}
GMessage("\n-------------- Read trimming: --------------\n");
if (gnum_trim5)
GMessage(" 5' trimmed :%9u\n", gnum_trim5);
if (gnum_trim3)
GMessage(" 3' trimmed :%9u\n", gnum_trim3);
if (gnum_trimQ)
GMessage(" q.v. trimmed :%9u\n", gnum_trimQ);
if (gnum_trimN)
GMessage(" N trimmed :%9u\n", gnum_trimN);
if (gnum_trimT)
GMessage(" poly-T trimmed :%9u\n", gnum_trimT);
if (gnum_trimA)
GMessage(" poly-A trimmed :%9u\n", gnum_trimA);
if (gnum_trimV)
GMessage(" Adapter trimmed :%9u\n", gnum_trimV);
GMessage("--------------------------------------------\n");
if (gtrash_s>0)
GMessage("Trashed by initial len:%9d\n", gtrash_s);
if (gtrash_N>0)
GMessage(" Trashed by N%%:%9d\n", gtrash_N);
if (gtrash_Q>0)
GMessage("Trashed by low quality:%9d\n", gtrash_Q);
if (gtrash_poly>0)
GMessage(" Trashed by poly-A/T:%9d\n", gtrash_poly);
if (gtrash_V>0)
GMessage(" Trashed by adapter:%9d\n", gtrash_V);
if (gtrash_X>0)
GMessage(" Trashed by X :%9d\n", gtrash_X);
GMessage("\n-------------- Base counts: ----------------\n");
GMessage(" Input bases :%12llu\n", gb_totalIn);
double percN=100.0* ((double)gb_totalN/(double)gb_totalIn);
GMessage(" N bases :%12llu (%4.2f%%)\n", gb_totalN, percN);
GMessage(" trimmed from 5':%12llu\n", gb_trim5);
GMessage(" trimmed from 3':%12llu\n", gb_trim3);
GMessage("\n");
if (gb_trimQ)
GMessage(" q.v. trimmed :%12llu\n", gb_trimQ);
if (gb_trimN)
GMessage(" N trimmed :%12llu\n", gb_trimN);
if (gb_trimT)
GMessage(" poly-T trimmed :%12llu\n", gb_trimT);
if (gb_trimA)
GMessage(" poly-A trimmed :%12llu\n", gb_trimA);
if (gb_trimV)
GMessage(" Adapter trimmed :%12llu\n", gb_trimV);
}
FWCLOSE(f_out);
FWCLOSE(f_out2);
} //while each input file
if (trimReport) {
FWCLOSE(freport);
}
//getc(stdin);
}
class NData {
public:
GVec<int> NPos; //there should be no reads longer than 1K ?
//int NCount;
int end5;
int end3;
int n5; //left side N position (index in NPos)
int n3; //right side N position (index in NPos)
int seqlen;
double perc_N; //percentage of Ns in end5..end3 range only!
const char* seq;
bool valid;
NData():NPos(),end5(0),end3(0),n5(0),n3(-1),seqlen(0),
perc_N(0),seq(NULL),valid(true) { }
NData(GStr& rseq):NPos(rseq.length()), end5(0),end3(rseq.length()-1),n5(0),n3(-1),
seqlen(rseq.length()), perc_N(0),seq(rseq.chars()),valid(true) {
//init(rseq);
for (int i=0;i<seqlen;i++)
if (seq[i]=='N') {// if (!ichrInStr(rseq[i], "ACGT")
NPos.Add(i);
}
n3=NPos.Count()-1; // -1 if no Ns
N_calc();
}
void N_trim(); //former N_analyze();
double N_calc() { //only in the end5-end3 region
if (n5<=n3) {
perc_N=((n3-n5+1)*100.0)/(end3-end5+1);
}
else perc_N=0;
return perc_N;
}
};
void NData::N_trim() { //N_analyze(NData& feat, int l5, int l3, int p5, int p3) {
/* assumes feat was filled properly */
int old_dif, t5,t3,v;
int l3=end3;
int l5=end5;
while (l3>=l5+2 && n5<=n3) {
t5=NPos[n5]-l5; //left side possible trimming
t3=l3-NPos[n3]; //right side potential trimming
old_dif=n3-n5;
if (dist_lenN) {
v=dist_lenN;
}
else {
v=iround(perc_lenN*(l3-l5+1)/100);
if (v>20) v=20; // enforce N-search limit for very long reads
else if (v<1) v=1;
}
if (t5 <= v ) {
l5=NPos[n5]+1;
n5++; //we can trim at 5' end up to after leftmost N
}
if (t3 <= v) {
l3=NPos[n3]-1;
n3--; //we can trim at 3' before leftmost N;
}
// restNs=p3-p5; number of Ns in the new CLR
if (n3-n5==old_dif) { // no change, return
break;
}
}
end5=l5;
end3=l3;
N_calc();
return;
/*
if (l3<l5+2 || p5>p3 ) {
feat.end5=l5+1;
feat.end3=l3+1;
return;
}
t5=feat.NPos[p5]-l5; //left side possible trimming
t3=l3-feat.NPos[p3]; //right side potential trimming
old_dif=p3-p5;
v=(int)((((double)(l3-l5))*perc_lenN)/100);
if (v>20) v=20; // enforce N-search limit for very long reads
else if (v<1) v=1;
if (t5 < v ) {
l5=feat.NPos[p5]+1;
p5++; //we can trim at 5' end up to after leftmost N
}
if (t3 < v) {
l3=feat.NPos[p3]-1;
p3--; //we can trim at 3' before leftmost N;
}
// restNs=p3-p5; number of Ns in the new CLR
if (p3-p5==old_dif) { // no change, return
feat.end5=l5+1;
feat.end3=l3+1;
return;
}
else
N_analyze(feat, l5,l3, p5,p3);
*/
}
bool CTrimHandler::qtrim(GStr& qvs, int &l5, int &l3) {
if (qvtrim_qmin==0 || qvs.is_empty()) return false;
l5=0;
l3=qvs.length()-1;
if (qv_phredtype==0) {
//try to guess the Phred type
int vmin=256, vmax=0;
for (int i=0;i<qvs.length();i++) {
if (vmin>qvs[i]) vmin=qvs[i];
if (vmax<qvs[i]) vmax=qvs[i];
}
if (vmin<64) { qv_phredtype=33; qv_cvtadd=31; }
if (vmax>95) { qv_phredtype=64; qv_cvtadd=-31; }
if (qv_phredtype==0) {
GError("Error: couldn't determine Phred type, please use the -p33 or -p64 !\n");
}
if (verbose)
GMessage("Input reads have Phred-%d quality values.\n", (qv_phredtype==33 ? 33 : 64));
} //guessing Phred type
int winlen=GMIN(qvtrim_win, qvs.length()/4);
if (winlen<3) {
//no sliding window
//scan from the ends and look for two consecutive bases above the threshold
for (;l3>2;l3--) {
if (qvs[l3]-qv_phredtype>=qvtrim_qmin && qvs[l3-1]-qv_phredtype>=qvtrim_qmin) break;
}
// qtrim 5' end
for (l5=0;l5<qvs.length()-3;l5++) {
if (qvs[l5]-qv_phredtype>=qvtrim_qmin && qvs[l5+1]-qv_phredtype>=qvtrim_qmin) break;
}
}
else {
// trim 3'
//sliding window from the 5' end until avg qual drops below the threshold
//init sum
int qsum=0;
/*
int qilow=-1; //first base index where qv drops below qmin