ViewVC Help
View File | Revision Log | Show Annotations | View Changeset | Root Listing
root/gclib/fqtrim/fqtrim.cpp
(Generate patch)
# Line 2 | Line 2
2   #include "GStr.h"
3   #include "GHash.hh"
4   #include "GList.hh"
5 + #include <ctype.h>
6 + #include "GAlnExtend.h"
7  
8   #define USAGE "Usage:\n\
9 < fqtrim [-5 <5'adapter>] [-3 <3'adapter>] [-l <minlen>] [-C] [-D] [-Q] \\\n\
10 <    [-n <rename_prefix>] [-o <trimmed.fq>] [-r <discarded.lst>] <input.fq>\n\
9 > fqtrim [{-5 <5adapter> -3 <3adapter>|-f <adapters_file>}] [-a <min_matchlen>]\\\n\
10 >   [-q <minq> [-t <trim_max_len>]] [-p {64|33}] [-o <outsuffix>]\\\n\
11 >   [-l <minlen>] [-C] [-D] [-Q] [-n <rename_prefix>] [-r <discarded.lst>]\\\n\
12 >    <input.fq>[,<input_mates.fq>\n\
13   \n\
14 < Trim low quality bases at 3' end, optional adapter, filter for low complexity and\n\
15 < optionally collapse duplicates in the input fastq data.\n\
14 > Trim low quality bases at the 3' end and can trim adapter sequence(s), filter\n\
15 > for low complexity and collapse duplicate reads.\n\
16 > If read pairs should be trimmed and kept together (i.e. without discarding\n\
17 > one read in a pair), the two file names should be given delimited by a comma\n\
18 > or a colon character\n\
19   \n\
20   Options:\n\
21   -n  rename all the reads using the <prefix> followed by a read counter;\n\
22      if -C option was given, the suffix \"_x<N>\" is appended, with <N> being\n\
23      the read duplication count\n\
24 < -o  write the trimmed/filtered fastq into <trimmed.fq>(instead of stdout)\n\
24 > -o  unless this parameter is '-', write the trimmed/filtered reads to \n\
25 >    file(s) named <input>.<outsuffix> which will be created in the \n\
26 >    current (working) directory; (writes to stdout if -o- is given);\n\
27 >    a suffix ending with .gz, .gzip or .bz2 will enforce compression\n\
28 > -f  file with adapter sequences to trim, each line having this format:\n\
29 >    <5'-adapter-sequence> <3'-adapter-sequence>\n\
30   -5  trim the given adapter or primer sequence at the 5' end of each read\n\
31      (e.g. -5 CGACAGGTTCAGAGTTCTACAGTCCGACGATC)\n\
32   -3  trim the given adapter sequence at the 3' end of each read\n\
33      (e.g. -3 TCGTATGCCGTCTTCTGCTTG)\n\
34 < -l  minimum \"clean\" length at the high quality 5'end that a read must\n\
35 <    have in order to pass the filter (default: 16)\n\
34 > -A  disable polyA trimming (enabled by default)\n\
35 > -T  enable polyT trimming (disabled by default)\n\
36 > -y  minimum length of exact match to adaptor sequence at the proper end (6)\n\
37 > -q  trim bases with quality value lower than <minq> (starting at the 3' end)\n\
38 > -t  for -q option, maximum trimming at the 3' end is limited to <trim_max_len>\n\
39 > -m  maximum percentage of Ns allowed in a read after trimming (default 7)\n\
40 > -l  minimum \"clean\" length after trimming that a read must have\n\
41 >    in order to pass the filter (default: 16)\n\
42   -r  write a simple \"trash report\" file listing the discarded reads with a\n\
43      one letter code for the reason why they were trashed\n\
44 + -D  apply a low-complexity (dust) filter and discard any read that has over\n\
45 +    50% of its length detected as low complexity\n\
46   -C  collapse duplicate reads and add a prefix with their count to the read\n\
47 <    name\n\
48 < -D  apply a low-complexity (dust) filter and discard any read that has at\n\
49 <    least half of it masked by this\n\
50 < -Q  quality values in the input data are interpreted as phred64, convert\n\
31 <    them to phred33\n\
47 >    name (e.g. for microRNAs)\n\
48 > -p  input is phred64/phred33 (use -p64 or -p33)\n\
49 > -Q  convert quality values to the other Phred qv type\n\
50 > -V  verbose processing\n\
51   "
52 +
53 + //-z  for -o option, the output stream(s) will be first piped into the given\n
54 + //   <zcmd> command, which must output to stdout (e.g. -z 'bzip2 -9 -c')\n
55 +
56 +
57   // example 3' adapter for miRNAs: TCGTATGCCGTCTTCTGCTTG
58 < FILE* f_out=NULL; //stdout if not provided
59 < FILE* f_in=NULL; //input fastq (stdin if not provided)
58 >
59 > //For paired reads sequencing:
60 > //3' : ACACTCTTTCCCTACACGACGCTCTTCCGATCT
61 > //5' : GATCGGAAGAGCGGTTCAGCAGGAATGCCGAG
62 > //FILE* f_out=NULL; //stdout if not provided
63 > //FILE* f_out2=NULL; //for paired reads
64 > //FILE* f_in=NULL; //input fastq (stdin if not provided)
65 > //FILE* f_in2=NULL; //for paired reads
66   FILE* freport=NULL;
67 +
68   bool debug=false;
69 + bool verbose=false;
70   bool doCollapse=false;
71   bool doDust=false;
72 + bool fastaOutput=false;
73   bool trashReport=false;
74 < bool rawFormat=false;
74 > //bool rawFormat=false;
75   int min_read_len=16;
76 + double max_perc_N=7.0;
77   int dust_cutoff=16;
78   bool isfasta=false;
79 < bool phred64=false;
79 > bool convert_phred=false;
80 > GStr outsuffix; // -o
81   GStr prefix;
82 < GStr adapter3;
83 < GStr adapter5;
84 < int a3len=0;
85 < int a5len=0;
86 < // adaptor matching metrics -- for extendMatch() function
87 < static const int a_m_score=2; //match score
88 < static const int a_mis_score=-3; //mismatch
89 < static const int a_dropoff_score=7;
90 < static const int a_min_score=7;
82 > GStr zcmd;
83 > int num_trimmed5=0;
84 > int num_trimmed3=0;
85 > int num_trimmedN=0;
86 > int num_trimmedQ=0;
87 > int min_trimmed5=INT_MAX;
88 > int min_trimmed3=INT_MAX;
89 >
90 > int qvtrim_qmin=0;
91 > int qvtrim_max=0;  //for -q, do not trim at 3'-end more than this number of bases
92 > int qv_phredtype=0; // could be 64 or 33 (0 means undetermined yet)
93 > int qv_cvtadd=0; //could be -31 or +31
94 >
95 > // adaptor matching metrics -- for X-drop ungapped extension
96 > const int poly_m_score=2; //match score
97 > const int poly_mis_score=-3; //mismatch
98 > const int poly_dropoff_score=7;
99 > int poly_minScore=12; //i.e. an exact match of 6 bases at the proper ends WILL be trimmed
100 >
101 > const char *polyA_seed="AAAA";
102 > const char *polyT_seed="TTTT";
103 > /*
104 > struct CAdapters {
105 >    GStr a5;
106 >    GStr a3;
107 >    CAdapters(const char* s5=NULL, const char* s3=NULL):a5(s5),a3(s3) {
108 >      }
109 > };
110 > */
111 > GVec<GStr> adapters5;
112 > GVec<GStr> adapters3;
113  
114   // element in dhash:
115   class FqDupRec {
# Line 91 | Line 148
148    if (!s.is_empty()) {
149        if (s=='-') f=stdout;
150        else {
151 <       f=fopen(s,"w");
151 >       f=fopen(s.chars(),"w");
152         if (f==NULL) GError("Error creating file: %s\n", s.chars());
153         }
154       }
# Line 102 | Line 159
159  
160   GHash<FqDupRec> dhash; //hash to keep track of duplicates
161  
162 < bool ntrim(GStr& rseq, GStr &rqv, int &l5, int &l3); //returns true if any trimming occured
162 > int loadAdapters(const char* fname);
163 >
164 > void setupFiles(FILE*& f_in, FILE*& f_in2, FILE*& f_out, FILE*& f_out2,
165 >                       GStr& s, GStr& infname, GStr& infname2);
166 > // uses outsuffix to generate output file names and open file handles as needed
167  
168 + void writeRead(FILE* f_out, GStr& rname, GStr& rinfo, GStr& rseq, GStr& rqv, int& outcounter);
169 + void trash_report(char trashcode, GStr& rname, FILE* freport);
170 +
171 + bool getFastxRec(GLineReader& fq, GStr& rseq, GStr& rqv,
172 +          GStr& rname, GStr& rinfo, GStr& infname);
173 +
174 + char process_read(GStr& rname, GStr& rseq, GStr& rqv, int &l5, int &l3);
175 + //returns 0 if the read was untouched, 1 if it was trimmed and a trash code if it was trashed
176 +
177 + bool ntrim(GStr& rseq, int &l5, int &l3); //returns true if any trimming occured
178 + bool qtrim(GStr& qvs, int &l5, int &l3); //return true if any trimming occured
179   int dust(GStr& seq);
180 < bool trim_adapter3(GStr& seq, int &l5, int &l3); //returns true if any trimming occured
180 > bool trim_poly5(GStr &seq, int &l5, int &l3, const char* poly_seed); //returns true if any trimming occured
181 > bool trim_poly3(GStr &seq, int &l5, int &l3, const char* poly_seed);
182   bool trim_adapter5(GStr& seq, int &l5, int &l3); //returns true if any trimming occured
183 + bool trim_adapter3(GStr& seq, int &l5, int &l3);
184  
185 < void convertQ64(char* q, int len);
186 < void convertQ64(GStr& q);
185 > void convertPhred(char* q, int len);
186 > void convertPhred(GStr& q);
187  
188   int main(int argc, char * const argv[]) {
189 <  GArgs args(argc, argv, "QRDCl:d:3:5:n:r:o:");
189 >  GArgs args(argc, argv, "YQDCVl:d:3:5:m:n:r:p:q:f:t:o:z:a:");
190    int e;
117  int icounter=0; //counter for input reads
118  int outcounter=0; //counter for output reads
191    if ((e=args.isError())>0) {
192        GMessage("%s\nInvalid argument: %s\n", USAGE, argv[e]);
193        exit(224);
194        }
195 <  debug=(args.getOpt('D')!=NULL);
196 <  phred64=(args.getOpt('Q')!=NULL);
195 >  debug=(args.getOpt('Y')!=NULL);
196 >  verbose=(args.getOpt('V')!=NULL);
197 >  convert_phred=(args.getOpt('Q')!=NULL);
198    doCollapse=(args.getOpt('C')!=NULL);
199    doDust=(args.getOpt('D')!=NULL);
200 +  /*
201    rawFormat=(args.getOpt('R')!=NULL);
202    if (rawFormat) {
203      GError("Sorry, raw qseq format parsing is not implemented yet!\n");
204      }
205 +  */
206    prefix=args.getOpt('n');
207    GStr s=args.getOpt('l');
208    if (!s.is_empty())
209       min_read_len=s.asInt();
210 +  s=args.getOpt('m');
211 +  if (!s.is_empty())
212 +     max_perc_N=s.asDouble();
213    s=args.getOpt('d');
214    if (!s.is_empty()) {
215       dust_cutoff=s.asInt();
216       doDust=true;
217       }
218 <    
219 <  if (args.getOpt('3')!=NULL) {
220 <    adapter3=args.getOpt('3');
221 <    adapter3.upper();
222 <    a3len=adapter3.length();
223 <    }
224 <  if (args.getOpt('5')!=NULL) {
225 <    adapter5=args.getOpt('5');
226 <    adapter5.upper();
227 <    a5len=adapter5.length();
218 >  s=args.getOpt('q');
219 >  if (!s.is_empty()) {
220 >     qvtrim_qmin=s.asInt();
221 >     }
222 >  s=args.getOpt('t');
223 >  if (!s.is_empty()) {
224 >     qvtrim_max=s.asInt();
225 >     }
226 >  s=args.getOpt('p');
227 >  if (!s.is_empty()) {
228 >     int v=s.asInt();
229 >     if (v==33) {
230 >        qv_phredtype=33;
231 >        qv_cvtadd=31;
232 >        }
233 >      else if (v==64) {
234 >        qv_phredtype=64;
235 >        qv_cvtadd=-31;
236 >        }
237 >       else
238 >         GMessage("%s\nInvalid value for -p option (can only be 64 or 33)!\n",USAGE);
239 >     }
240 >  s=args.getOpt('f');
241 >  if (!s.is_empty()) {
242 >   loadAdapters(s.chars());
243 >   }
244 >  bool fileAdapters=adapters5.Count()+adapters3.Count();
245 >  s=args.getOpt('5');
246 >  if (!s.is_empty()) {
247 >    if (fileAdapters)
248 >      GError("Error: options -5 and -f cannot be used together!\n");
249 >    s.upper();
250 >    adapters5.Add(s);
251 >    }
252 >  s=args.getOpt('3');
253 >  if (!s.is_empty()) {
254 >    if (fileAdapters)
255 >      GError("Error: options -3 and -f cannot be used together!\n");
256 >      s.upper();
257 >      adapters3.Add(s);
258      }
259 +  s=args.getOpt('y');
260 +  if (!s.is_empty()) {
261 +     int minmatch=s.asInt();
262 +     poly_minScore=minmatch*poly_m_score;
263 +     }
264 +  
265 +  if (args.getOpt('o')!=NULL) outsuffix=args.getOpt('o');
266 +                         else outsuffix="-";
267    trashReport=  (args.getOpt('r')!=NULL);
268 <  if (args.startNonOpt()==0) {
268 >  int fcount=args.startNonOpt();
269 >  if (fcount==0) {
270      GMessage(USAGE);
271      exit(224);
272      }
273 <
274 <  openfw(f_out, args, 'o');
273 >   if (fcount>1 && doCollapse) {
274 >    GError("%s Sorry, the -C option only works with a single input.\n", USAGE);
275 >    }
276 >  //openfw(f_out, args, 'o');
277 >  //if (f_out==NULL) f_out=stdout;
278    if (trashReport)
279      openfw(freport, args, 'r');
280    char* infile=NULL;
281    while ((infile=args.nextNonOpt())!=NULL) {
282 <    GStr infname(infile);
283 <    if (strcmp(infile,"-")==0) {
284 <       f_in=stdin; infname="stdin"; }
285 <     else {
286 <        f_in=fopen(infile,"r");
287 <        if (f_in==NULL)
288 <            GError("Cannot open input file %s!\n",infile);
289 <        }
290 <     GLineReader fq(f_in);
291 <     char* l=NULL;
292 <     while ((l=fq.getLine())!=NULL) {
293 <        GStr rname; //current read name
294 <        GStr rseq;  //current read sequence
295 <        GStr rqv;   //current read quality values
296 <        GStr s;
297 <        if (rawFormat) {
298 <          //TODO: implement qseq parsing here
299 <          //if (raw type=N) then continue; //skip invalid/bad records
300 <          
301 <          } //raw qseq format
302 <         else { // FASTQ or FASTA
303 <          isfasta=(l[0]=='>');
304 <          if (!isfasta && l[0]!='@') GError("Error: fastq record marker not detected!\n");
305 <          s=l;
306 <          rname=&(l[1]);
307 <          icounter++;
308 <          //GMessage("readname=%s\n",rname.chars());
309 <          for (int i=0;i<rname.length();i++)
310 <            if (rname[i]<=' ') { rname.cut(i); break; }
311 <          //now get the sequence
312 <          if ((l=fq.getLine())==NULL)
313 <              GError("Error: unexpected EOF after header for %s\n",rname.chars());
314 <          rseq=l; //this must be the DNA line
315 <          if (isfasta) {
316 <            while ((l=fq.getLine())!=NULL) {
317 <              //fasta can have multiple sequence lines
318 <              if (l[0]=='>') {
319 <                   fq.pushBack();
320 <                   break; //
282 >    int incounter=0; //counter for input reads
283 >    int outcounter=0; //counter for output reads
284 >    int trash_s=0; //too short from the get go
285 >    int trash_Q=0;
286 >    int trash_N=0;
287 >    int trash_D=0;
288 >    int trash_A3=0;
289 >    int trash_A5=0;
290 >    s=infile;
291 >    GStr infname;
292 >    GStr infname2;
293 >    FILE* f_in=NULL;
294 >    FILE* f_in2=NULL;
295 >    FILE* f_out=NULL;
296 >    FILE* f_out2=NULL;
297 >    bool paired_reads=false;
298 >    setupFiles(f_in, f_in2, f_out, f_out2, s, infname, infname2);
299 >    GLineReader fq(f_in);
300 >    GLineReader* fq2=NULL;
301 >    if (f_in2!=NULL) {
302 >       fq2=new GLineReader(f_in2);
303 >       paired_reads=true;
304 >       }
305 >    GStr rseq, rqv, seqid, seqinfo;
306 >    GStr rseq2, rqv2, seqid2, seqinfo2;
307 >    while (getFastxRec(fq, rseq, rqv, seqid, seqinfo, infname)) {
308 >       incounter++;
309 >       int a5=0, a3=0, b5=0, b3=0;
310 >       char tcode=0, tcode2=0;
311 >       tcode=process_read(seqid, rseq, rqv, a5, a3);
312 >       //if (!doCollapse) {
313 >         if (fq2!=NULL) {
314 >            getFastxRec(*fq2, rseq2, rqv2, seqid2, seqinfo2, infname2);
315 >            if (seqid.substr(0,seqid.length()-1)!=seqid2.substr(0,seqid2.length()-1)) {
316 >               GError("Error: no paired match for read %s vs %s (%s,%s)\n",
317 >                  seqid.chars(), seqid2.chars(), infname.chars(), infname2.chars());
318 >               }
319 >            tcode2=process_read(seqid2, rseq2, rqv2, b5, b3);
320 >            //decide what to do with this pair and print rseq2 if the pair makes it
321 >            if (tcode>1 && tcode2<=1) {
322 >               //"untrash" rseq
323 >               if (a3-a5+1<min_read_len) {
324 >                   a5=1;
325 >                   if (a3<min_read_len) { a3= GMIN(rseq.length()-1, min_read_len+1); }
326                     }
327 <              rseq+=l;
328 <              }
329 <            } //multi-line fasta file
330 <          if (!isfasta) {
331 <            if ((l=fq.getLine())==NULL)
332 <                GError("Error: unexpected EOF after sequence for %s\n", rname.chars());
333 <            if (l[0]!='+') GError("Error: fastq qv header marker not detected!\n");
334 <            if ((l=fq.getLine())==NULL)
335 <                GError("Error: unexpected EOF after qv header for %s\n", rname.chars());
336 <            rqv=l;
337 <            if (rqv.length()!=rseq.length())
338 <                GError("Error: qv len != seq len for %s\n", rname.chars());
339 <            }
340 <        } //<-- FASTA or FASTQ
216 <        rseq.upper();
217 <        int l5=0;
218 <        int l3=rseq.length()-1;
219 <        if (l3-l5+1<min_read_len) {
220 <           if (trashReport) {
221 <                  fprintf(freport, "%s\ts\t%s\n",rname.chars(), rseq.chars());
222 <                  }
223 <           continue;
224 <           }
225 <        if (ntrim(rseq, rqv, l5, l3)) {
226 <           if (l3-l5+1<min_read_len) {
227 <             if (trashReport) {
228 <                    fprintf(freport, "%s\tN\t%s\n", rname.chars(), rseq.chars());
229 <                    }
230 <             continue; //invalid read
231 <             }
232 <            //-- keep only the l5..l3 range
233 <           rseq=rseq.substr(l5, l3-l5+1);
234 <           if (!rqv.is_empty())
235 <              rqv=rqv.substr(l5, l3-l5+1);
236 <           }
237 <          
238 <        if (a3len>0) {
239 <          if (trim_adapter3(rseq, l5, l3)) {
240 <             if (l3-l5+1<min_read_len) {
241 <                 if (trashReport) {
242 <                     fprintf(freport, "%s\tA3\t%s\n",rname.chars(), rseq.chars());
243 <                     }
244 <                 continue;
245 <                 }
246 <              //-- keep only the l5..l3 range
247 <              rseq=rseq.substr(l5, l3-l5+1);
248 <              if (!rqv.is_empty())
249 <                 rqv=rqv.substr(l5, l3-l5+1);
250 <              }//some adapter was trimmed
251 <           } //adapter trimming
252 <        if (a5len>0) {
253 <          if (trim_adapter5(rseq, l5, l3)) {
254 <             if (l3-l5+1<min_read_len) {
255 <                 if (trashReport) {
256 <                     fprintf(freport, "%s\tA5\t%s\n",rname.chars(), rseq.chars());
257 <                     }
258 <                 continue;
327 >               tcode=1;
328 >               }
329 >             else if (tcode<=1 && tcode2>1) {
330 >               //"untrash" rseq2
331 >               if (b3-b5+1<min_read_len) {
332 >                   b5=1;
333 >                   if (b3<min_read_len) { b3= GMIN((rseq2.length()-1),(min_read_len+1)); }
334 >                   }
335 >               tcode2=1;
336 >               }
337 >            if (tcode<=1) { //trimmed or left intact -- write it!
338 >               if (tcode>0) {
339 >                 rseq2=rseq2.substr(b5,b3-b5+1);
340 >                 if (!rqv2.is_empty()) rqv2=rqv2.substr(b5,b3-b5+1);
341                   }
342 <              //-- keep only the l5..l3 range
343 <              rseq=rseq.substr(l5, l3-l5+1);
344 <              if (!rqv.is_empty())
345 <                 rqv=rqv.substr(l5, l3-l5+1);
346 <              }//some adapter was trimmed
347 <           } //adapter trimming
348 <        if (doCollapse) {
349 <           //keep read for later
350 <           FqDupRec* dr=dhash.Find(rseq.chars());
351 <           if (dr==NULL) { //new entry
352 <                  //if (prefix.is_empty())
353 <                     dhash.Add(rseq.chars(),
354 <                          new FqDupRec(&rqv, rname.chars()));
355 <                  //else dhash.Add(rseq.chars(), new FqDupRec(rqv.chars(),rqv.length()));
342 >               int nocounter=0;
343 >               writeRead(f_out2, seqid2, seqinfo2, rseq2, rqv2, nocounter);
344 >               }
345 >            } //paired read
346 >       // }
347 >       if (tcode>1) { //trashed
348 >          if (tcode=='s') trash_s++;
349 >            else if (tcode=='Q') trash_Q++;
350 >              else if (tcode=='N') trash_N++;
351 >               else if (tcode=='D') trash_D++;
352 >                else if (tcode=='3') trash_A3++;
353 >                 else if (tcode=='5') trash_A5++;
354 >          if (trashReport) trash_report(tcode, seqid, freport);
355 >          }
356 >         else if (!doCollapse) { //write it
357 >          if (tcode>0) {
358 >            rseq=rseq.substr(a5,a3-a5+1);
359 >            if (!rqv.is_empty()) rqv=rqv.substr(a5,a3-a5+1);
360 >            }
361 >          writeRead(f_out, seqid, seqinfo, rseq, rqv, outcounter);
362 >          }
363 >       } //for each fastq record
364 >    delete fq2;
365 >    FRCLOSE(f_in);
366 >    FRCLOSE(f_in2);
367 >    if (doCollapse) {
368 >       outcounter=0;
369 >       int maxdup_count=1;
370 >       char* maxdup_seq=NULL;
371 >       dhash.startIterate();
372 >       FqDupRec* qd=NULL;
373 >       char* seq=NULL;
374 >       while ((qd=dhash.NextData(seq))!=NULL) {
375 >         GStr rseq(seq);
376 >         //do the dusting here
377 >         if (doDust) {
378 >            int dustbases=dust(rseq);
379 >            if (dustbases>(rseq.length()>>1)) {
380 >               if (trashReport && qd->firstname!=NULL) {
381 >                 fprintf(freport, "%s_x%d\tD\n",qd->firstname, qd->count);
382                   }
383 <              else    
384 <                 dr->add(rqv);
385 <           } //collapsing duplicates
386 <         else { //not collapsing duplicates
387 <           //do the dust filter now
388 <           if (doDust) {
389 <             int dustbases=dust(rseq);
390 <             if (dustbases>(rseq.length()>>1)) {
391 <                if (trashReport) {
392 <                  fprintf(freport, "%s\tD\t%s\n",rname.chars(),rseq.chars());
393 <                  }
394 <                continue;
395 <                }
288 <             }
289 <           //print this record here  
290 <           outcounter++;
291 <           if (isfasta) {
292 <            if (prefix.is_empty())
293 <               fprintf(f_out, ">%s\n%s\n", rname.chars(), rseq.chars());
294 <              else
295 <               fprintf(f_out, ">%s%08d\n%s\n", prefix.chars(), outcounter,
296 <                                  rseq.chars());
383 >               trash_D+=qd->count;
384 >               continue;
385 >               }
386 >            }
387 >         outcounter++;
388 >         if (qd->count>maxdup_count) {
389 >            maxdup_count=qd->count;
390 >            maxdup_seq=seq;
391 >            }
392 >         if (isfasta) {
393 >           if (prefix.is_empty()) {
394 >             fprintf(f_out, ">%s_x%d\n%s\n", qd->firstname, qd->count,
395 >                           rseq.chars());
396               }
397 <           else {  //fastq
398 <            if (phred64) convertQ64(rqv);
399 <            if (prefix.is_empty())
301 <               fprintf(f_out, "@%s\n%s\n+\n%s\n", rname.chars(), rseq.chars(),rqv.chars());
302 <              else
303 <               fprintf(f_out, "@%s_%08d\n%s\n+\n%s\n", prefix.chars(), outcounter,
304 <                                  rseq.chars(),rqv.chars() );
397 >           else { //use custom read name
398 >             fprintf(f_out, ">%s%08d_x%d\n%s\n", prefix.chars(), outcounter,
399 >                        qd->count, rseq.chars());
400               }
401 <           } //not collapsing duplicates
402 <        } //for each fastq record
403 <   } //while each input file
404 < FRCLOSE(f_in);
405 < if (doCollapse) {
406 <    outcounter=0;
312 <    int maxdup_count=1;
313 <    char* maxdup_seq=NULL;
314 <    dhash.startIterate();
315 <    FqDupRec* qd=NULL;
316 <    char* seq=NULL;
317 <    while ((qd=dhash.NextData(seq))!=NULL) {
318 <      GStr rseq(seq);
319 <      //do the dusting here
320 <      if (doDust) {
321 <         int dustbases=dust(rseq);
322 <         if (dustbases>(rseq.length()>>1)) {
323 <            if (trashReport && qd->firstname!=NULL) {
324 <              fprintf(freport, "%s_x%d\tD\t%s\n",qd->firstname, qd->count,seq);
325 <              }
326 <            continue;
401 >           }
402 >         else { //fastq format
403 >          if (convert_phred) convertPhred(qd->qv, qd->len);
404 >          if (prefix.is_empty()) {
405 >            fprintf(f_out, "@%s_x%d\n%s\n+\n%s\n", qd->firstname, qd->count,
406 >                           rseq.chars(), qd->qv);
407              }
408 +          else { //use custom read name
409 +            fprintf(f_out, "@%s%08d_x%d\n%s\n+\n%s\n", prefix.chars(), outcounter,
410 +                        qd->count, rseq.chars(), qd->qv);
411 +            }
412 +           }
413 +         }//for each element of dhash
414 +       if (maxdup_count>1) {
415 +         GMessage("Maximum read multiplicity: x %d (read: %s)\n",maxdup_count, maxdup_seq);
416           }
417 <      outcounter++;
418 <      if (qd->count>maxdup_count) {
419 <         maxdup_count=qd->count;
420 <         maxdup_seq=seq;
421 <         }
422 <      if (isfasta) {
423 <        if (prefix.is_empty()) {
424 <          fprintf(f_out, "@%s_x%d\n%s\n", qd->firstname, qd->count,
425 <                        rseq.chars());
426 <          }
427 <        else { //use custom read name
428 <          fprintf(f_out, "@%s%08d_x%d\n%s\n", prefix.chars(), outcounter,
429 <                     qd->count, rseq.chars());
417 >       } //collapse entries
418 >    if (verbose) {
419 >       if (paired_reads) {
420 >           GMessage(">Input files : %s , %s\n", infname.chars(), infname2.chars());
421 >           GMessage("Number of input pairs :%9d\n", incounter);
422 >           GMessage("         Output pairs :%9d\n", outcounter);
423 >           }
424 >         else {
425 >           GMessage(">Input file : %s\n", infname.chars());
426 >           GMessage("Number of input reads :%9d\n", incounter);
427 >           GMessage("         Output reads :%9d\n", outcounter);
428 >           }
429 >       GMessage("------------------------------------\n");
430 >       if (num_trimmed5)
431 >          GMessage("           5' trimmed :%9d  (min. trim: %d)\n", num_trimmed5, min_trimmed5);
432 >       if (num_trimmed3)
433 >          GMessage("           3' trimmed :%9d  (min. trim: %d)\n", num_trimmed3, min_trimmed3);
434 >       GMessage("------------------------------------\n");
435 >       if (trash_s>0)
436 >         GMessage("     Trashed by length:%9d\n", trash_s);
437 >       if (trash_N>0)
438 >         GMessage("         Trashed by N%%:%9d\n", trash_N);
439 >       if (trash_Q>0)
440 >         GMessage("Trashed by low quality:%9d\n", trash_Q);
441 >       if (trash_A5>0)
442 >         GMessage(" Trashed by 5' adapter:%9d\n", trash_A5);
443 >       if (trash_A3>0)
444 >         GMessage(" Trashed by 3' adapter:%9d\n", trash_A3);
445 >       }
446 >    if (trashReport) {
447 >          FWCLOSE(freport);
448            }
449 <        }
450 <      else { //fastq format
451 <       if (phred64) convertQ64(qd->qv, qd->len);
346 <       if (prefix.is_empty()) {
347 <         fprintf(f_out, "@%s_x%d\n%s\n+\n%s\n", qd->firstname, qd->count,
348 <                        rseq.chars(), qd->qv);
349 <         }
350 <       else { //use custom read name
351 <         fprintf(f_out, "@%s%08d_x%d\n%s\n+\n%s\n", prefix.chars(), outcounter,
352 <                     qd->count, rseq.chars(), qd->qv);
353 <         }
354 <        }
355 <      }//for each element of dhash
356 <    if (maxdup_count>1) {
357 <      GMessage("Maximum read multiplicity: x %d (read: %s)\n",maxdup_count, maxdup_seq);
358 <      }
359 <   } //report collapsed dhash entries
360 < GMessage("Number of input reads: %9d\n", icounter);
361 < GMessage("       Output records: %9d\n", outcounter);
362 < if (trashReport) {
363 <    FWCLOSE(freport);
364 <    }
449 >    FWCLOSE(f_out);
450 >    FWCLOSE(f_out2);
451 >   } //while each input file
452  
453 < FWCLOSE(f_out);
453 > //getc(stdin);
454   }
455  
456   class NData {
# Line 392 | Line 479
479       end5=1;
480       end3=seqlen;
481       for (int i=0;i<seqlen;i++)
482 <        if (rseq[i]=='N') {// if (!ichrInStr(rseq[i], "ACGT")
482 >        if (seq[i]=='N') {// if (!ichrInStr(rseq[i], "ACGT")
483             NPos[NCount]=i;
484             NCount++;
485             }
# Line 415 | Line 502
502   void N_analyze(int l5, int l3, int p5, int p3) {
503   /* assumes feat was filled properly */
504   int old_dif, t5,t3,v;
505 < if (l3-l5<min_read_len || p5>p3 ) {
505 > if (l3<l5+2 || p5>p3 ) {
506     feat.end5=l5+1;
507     feat.end3=l3+1;
508     return;
# Line 447 | Line 534
534   }
535  
536  
537 < bool ntrim(GStr& rseq, GStr &rqv, int &l5, int &l3) {
538 < //count Ns in the sequence
537 > bool qtrim(GStr& qvs, int &l5, int &l3) {
538 > if (qvtrim_qmin==0 || qvs.is_empty()) return false;
539 > if (qv_phredtype==0) {
540 >  //try to guess the Phred type
541 >  int vmin=256, vmax=0;
542 >  for (int i=0;i<qvs.length();i++) {
543 >     if (vmin>qvs[i]) vmin=qvs[i];
544 >     if (vmax<qvs[i]) vmax=qvs[i];
545 >     }
546 >  if (vmin<64) { qv_phredtype=33; qv_cvtadd=31; }
547 >  if (vmax>95) { qv_phredtype=64; qv_cvtadd=-31; }
548 >  if (qv_phredtype==0) {
549 >    GError("Error: couldn't determine Phred type, please use the -p33 or -p64 !\n");
550 >    }
551 >  if (verbose)
552 >    GMessage("Input reads have Phred-%d quality values.\n", (qv_phredtype==33 ? 33 : 64));
553 >  } //guessing Phred type
554 > for (l3=qvs.length()-1;l3>2;l3--) {
555 >  if (qvs[l3]-qv_phredtype>=qvtrim_qmin && qvs[l3-1]-qv_phredtype>=qvtrim_qmin) break;
556 >  }
557 > //just in case, check also the 5' the end (?)
558 > for (l5=0;l5<qvs.length()-3;l5++) {
559 >  if (qvs[l5]-qv_phredtype>=qvtrim_qmin && qvs[l5+1]-qv_phredtype>=qvtrim_qmin) break;
560 >  }
561 > if (qvtrim_max>0) {
562 >  if (qvs.length()-1-l3>qvtrim_max) l3=qvs.length()-1-qvtrim_max;
563 >  if (l5>qvtrim_max) l5=qvtrim_max;
564 >  }
565 > return (l5>0 || l3<qvs.length()-1);
566 > }
567 >
568 > bool ntrim(GStr& rseq, int &l5, int &l3) {
569 > //count Ns in the sequence, trim N-rich ends
570   feat.init(rseq);
571   l5=feat.end5-1;
572   l3=feat.end3-1;
573   N_analyze(feat.end5-1, feat.end3-1, 0, feat.NCount-1);
574 < if (l5==feat.end5-1 && l3==feat.end3-1)
575 <    return false; //nothing changed
574 > if (l5==feat.end5-1 && l3==feat.end3-1) {
575 >    if (feat.perc_N>max_perc_N) {
576 >           feat.valid=false;
577 >           l3=l5+1;
578 >           return true;
579 >           }
580 >      else {
581 >       return false; //nothing changed
582 >       }
583 >    }
584   l5=feat.end5-1;
585   l3=feat.end3-1;
586   if (l3-l5+1<min_read_len) {
# Line 462 | Line 588
588     return true;
589     }
590   feat.N_calc();
591 < if (feat.perc_N>6.2) { //not valid if more than 1 N per 16 bases
591 >
592 > if (feat.perc_N>max_perc_N) {
593        feat.valid=false;
594        l3=l5+1;
595        return true;
# Line 588 | Line 715
715   return ncount;
716   }
717  
718 < // ------------------ adapter matching - triplet matching
719 < //look for matching triplets amongst the first 9 nucleotides of the 3' adaptor
720 < // or the last 9 nucleotides for the 5' adapter
721 < //when a triplet match is found, simply try to extend the alignment using a drop-off scheme
722 < // check minimum score and
723 < // for 3' adapter trimming:
724 < //     require that the right end of the alignment for either the adaptor OR the read must be
725 < //     < 3 distance from its right end
726 < // for 5' adapter trimming:
727 < //     require that the left end of the alignment for either the adaptor OR the read must
728 < //     be at coordinate 0
602 <
603 < bool extendMatch(const char* a, int alen, int ai,
604 <                 const char* b, int blen, int bi, int mlen, int& l5, int& l3) {
605 < //so the alignment starts at ai in a, bi in b, with a perfect match of length mlen
606 < //GStr dbg(a);
607 < //GMessage(">> in %s\n\textending hit: %s at position %d\n", a, (dbg.substr(ai, mlen)).chars(), ai);
608 < int a_l=ai; //alignment coordinates on a
609 < int a_r=ai+mlen-1;
610 < int b_l=bi; //alignment coordinates on b
611 < int b_r=bi+mlen-1;
612 < int ai_maxscore=ai;
613 < int bi_maxscore=bi;
614 < int score=mlen*a_m_score;
615 < int maxscore=score;
616 < int mism5score=a_mis_score-2; //increase penalty for mismatches at 5' end
617 < //try to extend to the left first, if possible
618 < while (ai>0 && bi>0) {
619 <   ai--;
620 <   bi--;
621 <   score+= (a[ai]==b[bi])? a_m_score : mism5score;
622 <   if (score>maxscore) {
623 <       ai_maxscore=ai;
624 <       bi_maxscore=bi;
625 <       maxscore=score;
626 <       }
627 <     else if (maxscore-score>a_dropoff_score) break;
628 <   }
629 < a_l=ai_maxscore;
630 < b_l=bi_maxscore;
631 < //now extend to the right
632 < ai_maxscore=a_r;
633 < bi_maxscore=b_r;
634 < ai=a_r;
635 < bi=b_r;
636 < score=maxscore;
637 < //sometimes there are extra AAAAs at the end of the read, ignore those
638 < if (strcmp(&a[alen-4],"AAAA")==0) {
639 <    alen-=3;
640 <    while (a[alen-1]=='A' && alen>ai) alen--;
641 <    }
642 < while (ai<alen-1 && bi<blen-1) {
643 <   ai++;
644 <   bi++;
645 <   //score+= (a[ai]==b[bi])? a_m_score : a_mis_score;
646 <   if (a[ai]==b[bi]) { //match
647 <      score+=a_m_score;
648 <      if (ai>=alen-2) {
649 <           score+=a_m_score-(alen-ai-1);
650 <           }
651 <      }
652 <    else { //mismatch
653 <      score+=a_mis_score;
654 <      }  
655 <   if (score>maxscore) {
656 <       ai_maxscore=ai;
657 <       bi_maxscore=bi;
658 <       maxscore=score;
659 <       }
660 <     else if (maxscore-score>a_dropoff_score) break;
661 <   }
662 <  a_r=ai_maxscore;
663 <  b_r=bi_maxscore;
664 <  if (maxscore>=a_min_score && (alen-a_r<3 || blen-b_r<3 || a_l<2 || b_l<2)) {
665 <     if (a_l<alen-a_r-1) {
666 <        //adapter closer to the left end (typical for 5' adapter)
667 <        l5=a_r+1;
668 <        l3=alen-1;
669 <        }
670 <      else {
671 <        //adapter matching at the right end (typical for 3' adapter)
672 <        l5=0;
673 <        l3=a_l-1;
674 <        }
675 <     return true;
676 <     }
677 <  return false;
718 > int get3mer_value(const char* s) {
719 > return (s[0]<<16)+(s[1]<<8)+s[2];
720 > }
721 >
722 > int w3_match(int qv, const char* str, int slen, int start_index=0) {
723 > if (start_index>=slen || start_index<0) return -1;
724 > for (int i=start_index;i<slen-3;i++) {
725 >   int rv=get3mer_value(str+i);
726 >   if (rv==qv) return i;
727 >   }
728 > return -1;
729   }
730  
731 < bool trim_adapter3(GStr& seq, int&l5, int &l3) {
731 > int w3_rmatch(int qv, const char* str, int slen, int end_index=-1) {
732 > if (end_index>=slen) return -1;
733 > if (end_index<0) end_index=slen-1;
734 > for (int i=end_index-2;i>=0;i--) {
735 >   int rv=get3mer_value(str+i);
736 >   if (rv==qv) return i;
737 >   }
738 > return -1;
739 > }
740 >
741 > struct SLocScore {
742 >  int pos;
743 >  int score;
744 >  SLocScore(int p=0,int s=0) {
745 >    pos=p;
746 >    score=s;
747 >    }
748 >  void set(int p, int s) {
749 >    pos=p;
750 >    score=s;
751 >    }
752 >  void add(int p, int add) {
753 >    pos=p;
754 >    score+=add;
755 >    }
756 > };
757 >
758 > bool trim_poly3(GStr &seq, int &l5, int &l3, const char* poly_seed) {
759   int rlen=seq.length();
760   l5=0;
761   l3=rlen-1;
762 < //first try a full match, we might get lucky
763 < int fi=-1;
764 < if ((fi=seq.index(adapter3))>=0) {
765 <   if (fi<rlen-fi-a3len) {//match is closer to the right end
766 <      l5=fi+a3len;
767 <      l3=rlen-1;
762 > int32 seedVal=*(int32*)poly_seed;
763 > char polyChar=poly_seed[0];
764 > //assumes N trimming was already done
765 > //so a poly match should be very close to the end of the read
766 > // -- find the initial match (seed)
767 > int lmin=GMAX((rlen-12), 0);
768 > int li;
769 > for (li=rlen-4;li>lmin;li--) {
770 >   if (seedVal==*(int*)&(seq[li])) {
771 >      break;
772        }
691    else {
692      l5=0;
693      l3=fi-1;
694      }
695   return true;
773     }
774 < //also, for fast detection of other adapter-only reads that start past
775 < // the beginning of the adapter sequence, try to see if the first a3len-4
776 < // characters of the read are a substring of the adapter
777 < GStr rstart=seq.substr(0,a3len-4);
778 < if ((fi=adapter3.index(rstart))>=0) {
779 <   l3=rlen-1;
780 <   l5=a3len-4;
781 <   while (fi+l5<a3len && l5<l3 && adapter3[fi+l5]==seq[l5]) l5++;
782 <   return true;
774 > if (li<=lmin) return false;
775 > //seed found, try to extend it both ways
776 > //extend right
777 > int ri=li+3;
778 > SLocScore loc(ri, poly_m_score<<2);
779 > SLocScore maxloc(loc);
780 > //extend right
781 > while (ri<rlen-2) {
782 >   ri++;
783 >   if (seq[ri]==polyChar) {
784 >                loc.add(ri,poly_m_score);
785 >                }
786 >   else if (seq[ri]=='N') {
787 >                loc.add(ri,0);
788 >                }
789 >   else { //mismatch
790 >        loc.add(ri,poly_mis_score);
791 >        if (maxloc.score-loc.score>poly_dropoff_score) break;
792 >        }
793 >   if (maxloc.score<=loc.score) {
794 >      maxloc=loc;
795 >      }
796     }
797 <  
798 < //another easy case: first half of the adaptor matches
799 < int a3hlen=a3len>>1;
800 < GStr ahalf=adapter3.substr(0, a3hlen);
801 < if ((fi=seq.index(ahalf))>=0) {
802 <   extendMatch(seq.chars(), rlen, fi,
803 <                 adapter3.chars(), a3len, 0,  a3hlen, l5,l3);
804 <   return true;
797 > ri=maxloc.pos;
798 > if (ri<rlen-3) return false; //no trimming wanted, too far from 3' end
799 > //ri = right boundary for the poly match
800 > //extend left
801 > loc.set(li, maxloc.score);
802 > maxloc.pos=li;
803 > while (li>0) {
804 >    li--;
805 >    if (seq[li]==polyChar) {
806 >                 loc.add(li,poly_m_score);
807 >                 }
808 >    else if (seq[li]=='N') {
809 >                 loc.add(li,0);
810 >                 }
811 >    else { //mismatch
812 >         loc.add(li,poly_mis_score);
813 >         if (maxloc.score-loc.score>poly_dropoff_score) break;
814 >         }
815 >    if (maxloc.score<=loc.score) {
816 >       maxloc=loc;
817 >       }
818 >    }
819 > if (maxloc.score>poly_minScore && ri>=rlen-3) {
820 >    l5=li;
821 >    l3=ri;
822 >    return true;
823 >    }
824 > return false;
825 > }
826 >
827 >
828 > bool trim_poly5(GStr &seq, int &l5, int &l3, const char* poly_seed) {
829 > int rlen=seq.length();
830 > l5=0;
831 > l3=rlen-1;
832 > int32 seedVal=*(int32*)poly_seed;
833 > char polyChar=poly_seed[0];
834 > //assumes N trimming was already done
835 > //so a poly match should be very close to the end of the read
836 > // -- find the initial match (seed)
837 > int lmax=GMIN(8, rlen-4);//how far from 5' end to look for 4-mer seeds
838 > int li;
839 > for (li=0;li<=lmax;li++) {
840 >   if (seedVal==*(int*)&(seq[li])) {
841 >      break;
842 >      }
843     }
844 < //no easy cases, so let's do the word hashing
845 < for (int iw=0;iw<6;iw++) {
846 <   GStr aword=adapter3.substr(iw,3);
847 <   if ((fi=seq.index(aword))>=0  && rlen-fi>3) {
848 <      if (extendMatch(seq.chars(), rlen, fi, adapter3.chars(),
849 <                   a3len, iw, 3, l5,l3)) return true;
844 > if (li>lmax) return false;
845 > //seed found, try to extend it both ways
846 > //extend left
847 > int ri=li+3; //save rightmost base of the seed
848 > SLocScore loc(li, poly_m_score<<2);
849 > SLocScore maxloc(loc);
850 > while (li>0) {
851 >    li--;
852 >    if (seq[li]==polyChar) {
853 >                 loc.add(li,poly_m_score);
854 >                 }
855 >    else if (seq[li]=='N') {
856 >                 loc.add(li,0);
857 >                 }
858 >    else { //mismatch
859 >         loc.add(li,poly_mis_score);
860 >         if (maxloc.score-loc.score>poly_dropoff_score) break;
861 >         }
862 >    if (maxloc.score<=loc.score) {
863 >       maxloc=loc;
864 >       }
865 >    }
866 > li=maxloc.pos;
867 > if (li>3) return false; //no trimming wanted, too far from 5' end
868 > //li = right boundary for the poly match
869 >
870 > //extend right
871 > loc.set(ri, maxloc.score);
872 > maxloc.pos=ri;
873 > while (ri<rlen-2) {
874 >   ri++;
875 >   if (seq[ri]==polyChar) {
876 >                loc.add(ri,poly_m_score);
877 >                }
878 >   else if (seq[ri]=='N') {
879 >                loc.add(ri,0);
880 >                }
881 >   else { //mismatch
882 >        loc.add(ri,poly_mis_score);
883 >        if (maxloc.score-loc.score>poly_dropoff_score) break;
884 >        }
885 >   if (maxloc.score<=loc.score) {
886 >      maxloc=loc;
887        }
888     }
889 +
890 + if (maxloc.score>poly_minScore && li<=3) {
891 +    l5=li;
892 +    l3=ri;
893 +    return true;
894 +    }
895 + return false;
896 + }
897 +
898 + bool trim_adapter3(GStr& seq, int&l5, int &l3) {
899 + int rlen=seq.length();
900 + l5=0;
901 + l3=rlen-1;
902 +
903   return false; //no adapter parts found
904   }
905  
# Line 728 | Line 907
907   int rlen=seq.length();
908   l5=0;
909   l3=rlen-1;
910 < //try to see if adapter is fully included in the read
911 < int fi=-1;
912 < if ((fi=seq.index(adapter5))>=0) {
913 <   if (fi<rlen-fi-a5len) {//match is closer to the right end
914 <      l5=fi+a5len;
915 <      l3=rlen-1;
916 <      }
917 <    else {
918 <      l5=0;
919 <      l3=fi-1;
910 > bool trimmed=false;
911 > for (int ai=0;ai<adapters5.Count();ai++) {
912 >  if (adapters5[ai].is_empty()) continue;
913 >  int a5len=adapters5[ai].length();
914 >  GStr& adapter5=adapters5[ai];
915 >
916 >  }//for each 5' adapter
917 >  return trimmed;
918 > }
919 >
920 > //convert qvs to/from phred64 from/to phread33
921 > void convertPhred(GStr& q) {
922 > for (int i=0;i<q.length();i++) q[i]+=qv_cvtadd;
923 > }
924 >
925 > void convertPhred(char* q, int len) {
926 > for (int i=0;i<len;i++) q[i]+=qv_cvtadd;
927 > }
928 >
929 > bool getFastxRec(GLineReader& fq, GStr& rseq, GStr& rqv,
930 >          GStr& rname, GStr& rinfo, GStr& infname) {
931 > rseq="";
932 > rqv="";
933 > rname="";
934 > rinfo="";
935 > if (fq.eof()) return false;
936 > char* l=fq.getLine();
937 > while (l!=NULL && (l[0]==0 || isspace(l[0]))) l=fq.getLine(); //ignore empty lines
938 > if (l==NULL) return false;
939 > /* if (rawFormat) {
940 >      //TODO: implement raw qseq parsing here
941 >      //if (raw type=N) then continue; //skip invalid/bad records
942 >      } //raw qseq format
943 > else { // FASTQ or FASTA */
944 > isfasta=(l[0]=='>');
945 > if (!isfasta && l[0]!='@') GError("Error: fasta/fastq record marker not found(%s)\n%s\n",
946 >      infname.chars(), l);
947 > GStr s(l);
948 > rname=&(l[1]);
949 > for (int i=0;i<rname.length();i++)
950 >    if (rname[i]<=' ') {
951 >       if (i<rname.length()-2) rinfo=rname.substr(i+1);
952 >       rname.cut(i);
953 >       break;
954 >       }
955 >  //now get the sequence
956 > if ((l=fq.getLine())==NULL)
957 >      GError("Error: unexpected EOF after header for read %s (%s)\n",
958 >                   rname.chars(), infname.chars());
959 > rseq=l; //this must be the DNA line
960 > while ((l=fq.getLine())!=NULL) {
961 >      //seq can span multiple lines
962 >      if (l[0]=='>' || l[0]=='+') {
963 >           fq.pushBack();
964 >           break; //
965 >           }
966 >      rseq+=l;
967 >      } //check for multi-line seq
968 > if (!isfasta) { //reading fastq quality values, which can also be multi-line
969 >    if ((l=fq.getLine())==NULL)
970 >        GError("Error: unexpected EOF after sequence for %s\n", rname.chars());
971 >    if (l[0]!='+') GError("Error: fastq qv header marker not detected!\n");
972 >    if ((l=fq.getLine())==NULL)
973 >        GError("Error: unexpected EOF after qv header for %s\n", rname.chars());
974 >    rqv=l;
975 >    //if (rqv.length()!=rseq.length())
976 >    //  GError("Error: qv len != seq len for %s\n", rname.chars());
977 >    while (rqv.length()<rseq.length() && ((l=fq.getLine())!=NULL)) {
978 >      rqv+=l; //append to qv string
979        }
980 <   return true;
980 >    }// fastq
981 > // } //<-- FASTA or FASTQ
982 > rseq.upper();
983 > return true;
984 > }
985 >
986 > char process_read(GStr& rname, GStr& rseq, GStr& rqv, int &l5, int &l3) {
987 > //returns 0 if the read was untouched, 1 if it was just trimmed
988 > // and a trash code if it was trashed
989 > l5=0;
990 > l3=rseq.length()-1;
991 > if (l3-l5+1<min_read_len) {
992 >   return 's';
993     }
994 < //for fast detection of adapter-rich reads, check if the first 12
995 < //characters of the read are a substring of the adapter
996 < GStr rstart=seq.substr(1,12);
997 < if ((fi=adapter5.index(rstart))>=0) {
998 <   //l3=rlen-1;
999 <   //l5=a5len-4;
1000 <   //while (fi+l5<a5len && l5<l3 && adapter5[fi+l5]==seq[l5]) l5++;
1001 <   //return true;
1002 <   extendMatch(seq.chars(), rlen, 1,
1003 <                 adapter5.chars(), a5len, fi,  12, l5,l3);
1004 <   return true;
994 > GStr wseq(rseq.chars());
995 > GStr wqv(rqv.chars());
996 > int w5=l5;
997 > int w3=l3;
998 > //first do the q-based trimming
999 > if (qvtrim_qmin!=0 && !wqv.is_empty() && qtrim(wqv, w5, w3)) { // qv-threshold trimming
1000 >   if (w3-w5+1<min_read_len) {
1001 >     return 'Q'; //invalid read
1002 >     }
1003 >    //-- keep only the w5..w3 range
1004 >   l5=w5;
1005 >   l3=w3;
1006 >   wseq=wseq.substr(w5, w3-w5+1);
1007 >   if (!wqv.is_empty())
1008 >      wqv=wqv.substr(w5, w3-w5+1);
1009 >   } //qv trimming
1010 > // N-trimming on the remaining read seq
1011 > if (ntrim(wseq, w5, w3)) {
1012 >   //GMessage("before: %s\n",wseq.chars());
1013 >   //GMessage("after : %s (%d)\n",wseq.substr(w5,w3-w5+1).chars(),w3-w5+1);
1014 >   l5+=w5;
1015 >   l3-=(wseq.length()-1-w3);
1016 >   if (w3-w5+1<min_read_len) {
1017 >     return 'N'; //to be trashed
1018 >     }
1019 >    //-- keep only the w5..w3 range
1020 >   wseq=wseq.substr(w5, w3-w5+1);
1021 >   if (!wqv.is_empty())
1022 >      wqv=wqv.substr(w5, w3-w5+1);
1023 >   w5=0;
1024 >   w3=wseq.length()-1;
1025     }
1026 <  
1027 < //another easy case: last 12 characters of the adaptor found as a substring of the read
1028 < int aplen=12;
1029 < int apstart=a5len-aplen-2;
1030 < if (apstart<0) { apstart=0; aplen=a5len-1; }
1031 < GStr bstr=adapter5.substr(apstart, aplen);
1032 < if ((fi=seq.index(bstr))>=0) {
1033 <   extendMatch(seq.chars(), rlen, fi,
1034 <                 adapter5.chars(), a5len, apstart,  aplen, l5,l3);
1035 <   return true;
1026 > if (adapters3.Count()>0) {
1027 >  if (trim_adapter3(wseq, w5, w3)) {
1028 >     int trimlen=wseq.length()-(w3-w5+1);
1029 >     num_trimmed3++;
1030 >     if (trimlen<min_trimmed3)
1031 >         min_trimmed3=trimlen;
1032 >     l5+=w5;
1033 >     l3-=(wseq.length()-1-w3);
1034 >     if (w3-w5+1<min_read_len) {
1035 >         return '3';
1036 >         }
1037 >      //-- keep only the w5..w3 range
1038 >      wseq=wseq.substr(w5, w3-w5+1);
1039 >      if (!wqv.is_empty())
1040 >         wqv=wqv.substr(w5, w3-w5+1);
1041 >      }//some adapter was trimmed
1042 >   } //adapter trimming
1043 > if (adapters5.Count()>0) {
1044 >  if (trim_adapter5(wseq, w5, w3)) {
1045 >     int trimlen=wseq.length()-(w3-w5+1);
1046 >     num_trimmed5++;
1047 >     if (trimlen<min_trimmed5)
1048 >         min_trimmed5=trimlen;
1049 >     l5+=w5;
1050 >     l3-=(wseq.length()-1-w3);
1051 >     if (w3-w5+1<min_read_len) {
1052 >         return '5';
1053 >         }
1054 >      //-- keep only the w5..w3 range
1055 >      wseq=wseq.substr(w5, w3-w5+1);
1056 >      if (!wqv.is_empty())
1057 >         wqv=wqv.substr(w5, w3-w5+1);
1058 >      }//some adapter was trimmed
1059 >   } //adapter trimming
1060 > if (doCollapse) {
1061 >   //keep read for later
1062 >   FqDupRec* dr=dhash.Find(wseq.chars());
1063 >   if (dr==NULL) { //new entry
1064 >          //if (prefix.is_empty())
1065 >             dhash.Add(wseq.chars(),
1066 >                  new FqDupRec(&wqv, rname.chars()));
1067 >          //else dhash.Add(wseq.chars(), new FqDupRec(wqv.chars(),wqv.length()));
1068 >         }
1069 >      else
1070 >         dr->add(wqv);
1071 >   } //collapsing duplicates
1072 > else { //not collapsing duplicates
1073 >   //apply the dust filter now
1074 >   if (doDust) {
1075 >     int dustbases=dust(wseq);
1076 >     if (dustbases>(wseq.length()>>1)) {
1077 >        return 'D';
1078 >        }
1079 >     }
1080 >   } //not collapsing duplicates
1081 > return (l5>0 || l3<rseq.length()-1) ? 1 : 0;
1082 > }
1083 >
1084 > void printHeader(FILE* f_out, char recmarker, GStr& rname, GStr& rinfo) {
1085 > //GMessage("printing Header..%c%s\n",recmarker, rname.chars());
1086 > if (rinfo.is_empty()) fprintf(f_out, "%c%s\n",recmarker,rname.chars());
1087 >  else fprintf(f_out, "%c%s %s\n",recmarker, rname.chars(), rinfo.chars());
1088 > }
1089 >
1090 > void writeRead(FILE* f_out, GStr& rname, GStr& rinfo, GStr& rseq, GStr& rqv, int& outcounter) {
1091 >   outcounter++;
1092 >   bool asFasta=(rqv.is_empty() || fastaOutput);
1093 >   if (asFasta) {
1094 >    if (prefix.is_empty()) {
1095 >       printHeader(f_out, '>',rname,rinfo);
1096 >       fprintf(f_out, "%s\n", rseq.chars()); //plain one-line fasta for now
1097 >       }
1098 >      else {
1099 >       fprintf(f_out, ">%s%08d\n%s\n", prefix.chars(), outcounter,
1100 >                          rseq.chars());
1101 >       }
1102 >     }
1103 >   else {  //fastq
1104 >    if (convert_phred) convertPhred(rqv);
1105 >    if (prefix.is_empty()) {
1106 >       printHeader(f_out, '@', rname, rinfo);
1107 >       fprintf(f_out, "%s\n+\n%s\n", rseq.chars(), rqv.chars());
1108 >       }
1109 >      else
1110 >       fprintf(f_out, "@%s_%08d\n%s\n+\n%s\n", prefix.chars(), outcounter,
1111 >                          rseq.chars(),rqv.chars() );
1112 >     }
1113 > }
1114 >
1115 > void trash_report(char trashcode, GStr& rname, FILE* freport) {
1116 > if (freport==NULL || trashcode<=' ') return;
1117 > if (trashcode=='3' || trashcode=='5') {
1118 >   fprintf(freport, "%s\tA%c\n",rname.chars(),trashcode);
1119     }
1120 < //no easy cases, find a triplet match as a seed for alignment extension
1121 < //find triplets at the right end of the adapter
769 < for (int iw=0;iw<6;iw++) {
770 <   apstart=a5len-iw-4;
771 <   GStr aword=adapter5.substr(apstart,3);
772 <   if ((fi=seq.index(aword))>=0) {
773 <      if (extendMatch(seq.chars(), rlen, fi, adapter5.chars(),
774 <                   a5len, apstart, 3, l5,l3)) {
775 <                     return true;
776 <                     }
777 <      }
1120 > else {
1121 >   fprintf(freport, "%s\t%c\n",rname.chars(),trashcode);
1122     }
1123 < return false; //no adapter parts found
1123 > //tcounter++;
1124 > }
1125 >
1126 > GStr getFext(GStr& s, int* xpos=NULL) {
1127 > //s must be a filename without a path
1128 > GStr r("");
1129 > if (xpos!=NULL) *xpos=0;
1130 > if (s.is_empty() || s=="-") return r;
1131 > int p=s.rindex('.');
1132 > int d=s.rindex('/');
1133 > if (p<=0 || p>s.length()-2 || p<s.length()-7 || p<d) return r;
1134 > r=s.substr(p+1);
1135 > if (xpos!=NULL) *xpos=p+1;
1136 > r.lower();
1137 > return r;
1138   }
1139  
1140 < //conversion of phred64 to phread33
1141 < void convertQ64(GStr& q) {
1142 < for (int i=0;i<q.length();i++) q[i]-=31;
1140 > void baseFileName(GStr& fname) {
1141 > //remove all known extensions, like .txt,fq,fastq,fasta,fa)(.gz .gzip .bz2 .bzip2) .
1142 > int xpos=0;
1143 > GStr fext=getFext(fname, &xpos);
1144 > if (xpos<=1) return;
1145 > bool extdel=false;
1146 > GStr f2;
1147 > if (fext=="z" || fext=="zip") {
1148 >   extdel=true;
1149 >   }
1150 >  else if (fext.length()>=2) {
1151 >   f2=fext.substr(0,2);
1152 >   extdel=(f2=="gz" || f2=="bz");
1153 >   }
1154 > if (extdel) {
1155 >   fname.cut(xpos-1);
1156 >   fext=getFext(fname, &xpos);
1157 >   if (xpos<=1) return;
1158 >   }
1159 > extdel=false;
1160 > if (fext=="f" || fext=="fq" || fext=="txt" || fext=="seq" || fext=="sequence") {
1161 >   extdel=true;
1162 >   }
1163 >  else if (fext.length()>=2) {
1164 >   extdel=(fext.substr(0,2)=="fa");
1165 >   }
1166 > if (extdel) fname.cut(xpos-1);
1167 > GStr fncp(fname);
1168 > fncp.lower();
1169 > fncp.chomp("seq");
1170 > fncp.chomp("sequence");
1171 > fncp.trimR("_.");
1172 > if (fncp.length()<fname.length()) fname.cut(fncp.length());
1173 > }
1174 >
1175 > FILE* prepOutFile(GStr& infname, GStr& pocmd) {
1176 >  FILE* f_out=NULL;
1177 >  GStr fname(getFileName(infname.chars()));
1178 >  //eliminate known extensions
1179 >  baseFileName(fname);
1180 >  if (outsuffix.is_empty() || outsuffix=="-") { return stdout; }
1181 >    else if (pocmd.is_empty()) {
1182 >               GStr oname(fname);
1183 >               oname.append('.');
1184 >               oname.append(outsuffix);
1185 >               f_out=fopen(oname.chars(),"w");
1186 >               if (f_out==NULL) GError("Error: cannot create '%s'\n",oname.chars());
1187 >               }
1188 >            else {
1189 >              GStr oname(">");
1190 >              oname.append(fname);
1191 >              oname.append('.');
1192 >              oname.append(outsuffix);
1193 >              pocmd.append(oname);
1194 >              f_out=popen(pocmd.chars(), "w");
1195 >              if (f_out==NULL) GError("Error: cannot popen '%s'\n",pocmd.chars());
1196 >              }
1197 > return f_out;
1198   }
1199  
1200 < void convertQ64(char* q, int len) {
1201 < for (int i=0;i<len;i++) q[i]-=31;
1200 > void guess_unzip(GStr& fname, GStr& picmd) {
1201 > GStr fext=getFext(fname);
1202 > if (fext=="gz" || fext=="gzip" || fext=="z") {
1203 >    picmd="gzip -cd ";
1204 >    }
1205 >   else if (fext=="bz2" || fext=="bzip2" || fext=="bz" || fext=="bzip") {
1206 >    picmd="bzip2 -cd ";
1207 >    }
1208 > }
1209 >
1210 >
1211 > int loadAdapters(const char* fname) {
1212 >  GLineReader lr(fname);
1213 >  char* l;
1214 >  while ((l=lr.nextLine())!=NULL) {
1215 >   if (lr.length()<=3 || l[0]=='#') continue;
1216 >   if ( l[0]==' ' || l[0]=='\t' || l[0]==',' ||
1217 >        l[0]==';'|| l[0]==':' ) {
1218 >      int i=1;
1219 >      while (l[i]!=0 && isspace(l[i])) {
1220 >        i++;
1221 >        }
1222 >      if (l[i]!=0) {
1223 >        GStr s(&(l[i]));
1224 >        adapters3.Add(s);
1225 >        continue;
1226 >        }
1227 >      }
1228 >    else {
1229 >      GStr s(l);
1230 >      s.startTokenize("\t ;,:");
1231 >      GStr a5,a3;
1232 >      if (s.nextToken(a5))
1233 >         s.nextToken(a3);
1234 >      a5.upper();
1235 >      a3.upper();
1236 >      adapters5.Add(a5);
1237 >      adapters3.Add(a3);
1238 >      }
1239 >   }
1240 >   return adapters5.Count()+adapters3.Count();
1241   }
1242  
1243 + void setupFiles(FILE*& f_in, FILE*& f_in2, FILE*& f_out, FILE*& f_out2,
1244 +                       GStr& s, GStr& infname, GStr& infname2) {
1245 + // uses outsuffix to generate output file names and open file handles as needed
1246 + infname="";
1247 + infname2="";
1248 + f_in=NULL;
1249 + f_in2=NULL;
1250 + f_out=NULL;
1251 + f_out2=NULL;
1252 + //analyze outsuffix intent
1253 + GStr pocmd;
1254 + if (outsuffix=="-") {
1255 +    f_out=stdout;
1256 +    }
1257 +   else {
1258 +    GStr ox=getFext(outsuffix);
1259 +    if (ox.length()>2) ox=ox.substr(0,2);
1260 +    if (ox=="gz") pocmd="gzip -9 -c ";
1261 +        else if (ox=="bz") pocmd="bzip2 -9 -c ";
1262 +    }
1263 + if (s=="-") {
1264 +    f_in=stdin;
1265 +    infname="stdin";
1266 +    f_out=prepOutFile(infname, pocmd);
1267 +    return;
1268 +    } // streaming from stdin
1269 + s.startTokenize(",:");
1270 + s.nextToken(infname);
1271 + bool paired=s.nextToken(infname2);
1272 + if (fileExists(infname.chars())==0)
1273 +    GError("Error: cannot find file %s!\n",infname.chars());
1274 + GStr fname(getFileName(infname.chars()));
1275 + GStr picmd;
1276 + guess_unzip(fname, picmd);
1277 + if (picmd.is_empty()) {
1278 +   f_in=fopen(infname.chars(), "r");
1279 +   if (f_in==NULL) GError("Error opening file '%s'!\n",infname.chars());
1280 +   }
1281 +  else {
1282 +   picmd.append(infname);
1283 +   f_in=popen(picmd.chars(), "r");
1284 +   if (f_in==NULL) GError("Error at popen %s!\n", picmd.chars());
1285 +   }
1286 + if (f_out==stdout) {
1287 +   if (paired) GError("Error: output suffix required for paired reads\n");
1288 +   return;
1289 +   }
1290 + f_out=prepOutFile(infname, pocmd);
1291 + if (!paired) return;
1292 + if (doCollapse) GError("Error: sorry, -C option cannot be used with paired reads!\n");
1293 + // ---- paired reads:-------------
1294 + if (fileExists(infname2.chars())==0)
1295 +     GError("Error: cannot find file %s!\n",infname2.chars());
1296 + picmd="";
1297 + GStr fname2(getFileName(infname2.chars()));
1298 + guess_unzip(fname2, picmd);
1299 + if (picmd.is_empty()) {
1300 +   f_in2=fopen(infname2.chars(), "r");
1301 +   if (f_in2==NULL) GError("Error opening file '%s'!\n",infname2.chars());
1302 +   }
1303 +  else {
1304 +   picmd.append(infname2);
1305 +   f_in2=popen(picmd.chars(), "r");
1306 +   if (f_in2==NULL) GError("Error at popen %s!\n", picmd.chars());
1307 +   }
1308 + f_out2=prepOutFile(infname2, pocmd);
1309 + }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines