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  
7   #define USAGE "Usage:\n\
8 < fqtrim [-5 <5'adapter>] [-3 <3'adapter>] [-l <minlen>] [-q <minqv>] [-C] [-D]\\\n\
9 <   [-p {64|33}] [-n <rename_prefix>] [-o <trimmed.fq>] [-r <discarded.lst>]\\\n\
10 <   [-Q] <input.fq>\n\
8 > fqtrim [{-5 <5adapter> -3 <3adapter>|-f <adapters_file>}] [-a <min_matchlen>]\\\n\
9 >   [-q <minq> [-t <trim_max_len>]] [-p {64|33}] [-o <outsuffix>]\\\n\
10 >   [-l <minlen>] [-C] [-D] [-Q] [-n <rename_prefix>] [-r <discarded.lst>]\\\n\
11 >    <input.fq>[,<input_mates.fq>\n\
12   \n\
13 < Trim low quality bases at 3' end, optionally trim adapter sequence, filter\n\
14 < for low complexity and collapse duplicate reads\n\
13 > Trim low quality bases at the 3' end and can trim adapter sequence(s), filter\n\
14 > for low complexity and collapse duplicate reads.\n\
15 > If read pairs should be trimmed and kept together (i.e. without discarding\n\
16 > one read in a pair), the two file names should be given delimited by a comma\n\
17 > or a colon character\n\
18   \n\
19   Options:\n\
20   -n  rename all the reads using the <prefix> followed by a read counter;\n\
21      if -C option was given, the suffix \"_x<N>\" is appended, with <N> being\n\
22      the read duplication count\n\
23 < -o  write the trimmed/filtered fastq into <trimmed.fq>(instead of stdout)\n\
23 > -o  unless this parameter is '-', write the trimmed/filtered reads to \n\
24 >    file(s) named <input>.<outsuffix> which will be created in the \n\
25 >    current (working) directory; (writes to stdout if -o- is given);\n\
26 >    a suffix ending with .gz, .gzip or .bz2 will enforce compression\n\
27 > -f  file with adapter sequences to trim, each line having this format:\n\
28 >    <5'-adapter-sequence> <3'-adapter-sequence>\n\
29   -5  trim the given adapter or primer sequence at the 5' end of each read\n\
30      (e.g. -5 CGACAGGTTCAGAGTTCTACAGTCCGACGATC)\n\
31   -3  trim the given adapter sequence at the 3' end of each read\n\
32      (e.g. -3 TCGTATGCCGTCTTCTGCTTG)\n\
33 < -q  trim bases with quality value lower than <minq> (starting the 3' end)\n\
33 > -a  minimum length of exact match to adaptor sequence at the proper end (6)\n\
34 > -q  trim bases with quality value lower than <minq> (starting at the 3' end)\n\
35 > -t  for -q option, maximum trimming at the 3' end is limited to <trim_max_len>\n\
36   -m  maximum percentage of Ns allowed in a read after trimming (default 7)\n\
37   -l  minimum \"clean\" length after trimming that a read must have\n\
38      in order to pass the filter (default: 16)\n\
# Line 34 | Line 46
46   -Q  convert quality values to the other Phred qv type\n\
47   -V  verbose processing\n\
48   "
49 +
50 + //-z  for -o option, the output stream(s) will be first piped into the given\n
51 + //   <zcmd> command, which must output to stdout (e.g. -z 'bzip2 -9 -c')\n
52 +
53 +
54   // example 3' adapter for miRNAs: TCGTATGCCGTCTTCTGCTTG
55  
56 < //For pair ends sequencing:
56 > //For paired reads sequencing:
57   //3' : ACACTCTTTCCCTACACGACGCTCTTCCGATCT
58   //5' : GATCGGAAGAGCGGTTCAGCAGGAATGCCGAG
59 < FILE* f_out=NULL; //stdout if not provided
60 < FILE* f_in=NULL; //input fastq (stdin if not provided)
59 > //FILE* f_out=NULL; //stdout if not provided
60 > //FILE* f_out2=NULL; //for paired reads
61 > //FILE* f_in=NULL; //input fastq (stdin if not provided)
62 > //FILE* f_in2=NULL; //for paired reads
63   FILE* freport=NULL;
64 +
65   bool debug=false;
66   bool verbose=false;
67   bool doCollapse=false;
68   bool doDust=false;
69 + bool fastaOutput=false;
70   bool trashReport=false;
71   //bool rawFormat=false;
72   int min_read_len=16;
# Line 53 | Line 74
74   int dust_cutoff=16;
75   bool isfasta=false;
76   bool convert_phred=false;
77 + GStr outsuffix; // -o
78 + //GStr adapter3;
79 + //GStr adapter5;
80   GStr prefix;
81 < GStr adapter3;
82 < GStr adapter5;
83 <
84 < int qvtrim_min=0;
81 > GStr zcmd;
82 > int num_trimmed5=0;
83 > int num_trimmed3=0;
84 > int num_trimmedN=0;
85 > int num_trimmedQ=0;
86 > int min_trimmed5=INT_MAX;
87 > int min_trimmed3=INT_MAX;
88  
89 + int qvtrim_qmin=0;
90 + int qvtrim_max=0;  //for -q, do not trim at 3'-end more than this number of bases
91   int qv_phredtype=0; // could be 64 or 33 (0 means undetermined yet)
92   int qv_cvtadd=0; //could be -31 or +31
93  
94   int a3len=0;
95   int a5len=0;
96   // adaptor matching metrics -- for extendMatch() function
97 + const int match_score=2; //match score
98 + const int mismatch_score=-3; //mismatch
99 +
100   const int a_m_score=2; //match score
101   const int a_mis_score=-3; //mismatch
102   const int a_dropoff_score=7;
103 < const int a_min_score=8; //an exact match of 4 bases at the proper ends WILL be trimmed
103 > const int poly_dropoff_score=7;
104 > int a_min_score=12; //an exact match of 6 bases at the proper ends WILL be trimmed
105   const int a_min_chain_score=15; //for gapped alignments
106  
107   class CSegChain;
# Line 273 | Line 306
306    if (!s.is_empty()) {
307        if (s=='-') f=stdout;
308        else {
309 <       f=fopen(s,"w");
309 >       f=fopen(s.chars(),"w");
310         if (f==NULL) GError("Error creating file: %s\n", s.chars());
311         }
312       }
# Line 284 | Line 317
317  
318   GHash<FqDupRec> dhash; //hash to keep track of duplicates
319  
320 + void setupFiles(FILE*& f_in, FILE*& f_in2, FILE*& f_out, FILE*& f_out2,
321 +                       GStr& s, GStr& infname, GStr& infname2);
322 + // uses outsuffix to generate output file names and open file handles as needed
323 +
324 + void writeRead(FILE* f_out, GStr& rname, GStr& rinfo, GStr& rseq, GStr& rqv, int& outcounter);
325 + void trash_report(char trashcode, GStr& rname, FILE* freport);
326 +
327 + bool getFastxRec(GLineReader& fq, GStr& rseq, GStr& rqv,
328 +          GStr& rname, GStr& rinfo, GStr& infname);
329 +
330 + char process_read(GStr& rname, GStr& rseq, GStr& rqv, int &l5, int &l3);
331 + //returns 0 if the read was untouched, 1 if it was trimmed and a trash code if it was trashed
332 +
333   bool ntrim(GStr& rseq, int &l5, int &l3); //returns true if any trimming occured
334 + bool polytrim(GStr& rseq, int &l5, int &l3); //returns true if any trimming occured
335   bool qtrim(GStr& qvs, int &l5, int &l3); //return true if any trimming occured
336   int dust(GStr& seq);
337   bool trim_adapter3(GStr& seq, int &l5, int &l3); //returns true if any trimming occured
# Line 294 | Line 341
341   void convertPhred(GStr& q);
342  
343   int main(int argc, char * const argv[]) {
344 <  GArgs args(argc, argv, "YQDCVl:d:3:5:m:n:r:p:q:o:");
344 >  GArgs args(argc, argv, "YQDCVl:d:3:5:m:n:r:p:q:f:t:o:z:a:");
345    int e;
299  int icounter=0; //counter for input reads
300  int outcounter=0; //counter for output reads
346    if ((e=args.isError())>0) {
347        GMessage("%s\nInvalid argument: %s\n", USAGE, argv[e]);
348        exit(224);
349        }
350    debug=(args.getOpt('Y')!=NULL);
351 <  debug=(args.getOpt('V')!=NULL);
351 >  verbose=(args.getOpt('V')!=NULL);
352    convert_phred=(args.getOpt('Q')!=NULL);
353    doCollapse=(args.getOpt('C')!=NULL);
354    doDust=(args.getOpt('D')!=NULL);
# Line 327 | Line 372
372       }
373    s=args.getOpt('q');
374    if (!s.is_empty()) {
375 <     qvtrim_min=s.asInt();
375 >     qvtrim_qmin=s.asInt();
376 >     }
377 >  s=args.getOpt('t');
378 >  if (!s.is_empty()) {
379 >     qvtrim_max=s.asInt();
380       }
381    s=args.getOpt('p');
382    if (!s.is_empty()) {
# Line 353 | Line 402
402      adapter5.upper();
403      a5len=adapter5.length();
404      }
405 +  s=args.getOpt('a');
406 +  if (!s.is_empty()) {
407 +     int a_minmatch=s.asInt();
408 +     a_min_score=a_minmatch<<1;
409 +     }
410 +  
411 +  if (args.getOpt('o')!=NULL) outsuffix=args.getOpt('o');
412 +                         else outsuffix="-";
413    trashReport=  (args.getOpt('r')!=NULL);
414 <  if (args.startNonOpt()==0) {
414 >  int fcount=args.startNonOpt();
415 >  if (fcount==0) {
416      GMessage(USAGE);
417      exit(224);
418      }
419 <
420 <  openfw(f_out, args, 'o');
421 <  if (f_out==NULL) f_out=stdout;
419 >   if (fcount>1 && doCollapse) {
420 >    GError("%s Sorry, the -C option only works with a single input.\n", USAGE);
421 >    }
422 >  //openfw(f_out, args, 'o');
423 >  //if (f_out==NULL) f_out=stdout;
424    if (trashReport)
425      openfw(freport, args, 'r');
426    char* infile=NULL;
427    while ((infile=args.nextNonOpt())!=NULL) {
428 <    GStr infname(infile);
429 <    if (strcmp(infile,"-")==0) {
430 <       f_in=stdin; infname="stdin"; }
431 <     else {
432 <        f_in=fopen(infile,"r");
433 <        if (f_in==NULL)
434 <            GError("Cannot open input file %s!\n",infile);
435 <        }
436 <     GLineReader fq(f_in);
437 <     char* l=NULL;
438 <     while ((l=fq.getLine())!=NULL) {
439 <        GStr rname; //current read name
440 <        GStr rseq;  //current read sequence
441 <        GStr rqv;   //current read quality values
442 <        GStr s;
443 <        /* if (rawFormat) {
444 <          //TODO: implement qseq parsing here
445 <          //if (raw type=N) then continue; //skip invalid/bad records
446 <          
447 <          } //raw qseq format
448 <         else { // FASTQ or FASTA */
449 <          isfasta=(l[0]=='>');
450 <          if (!isfasta && l[0]!='@') GError("Error: fastq record marker not detected!\n");
451 <          s=l;
452 <          rname=&(l[1]);
453 <          icounter++;
454 <          for (int i=0;i<rname.length();i++)
455 <            if (rname[i]<=' ') { rname.cut(i); break; }
456 <          //now get the sequence
457 <          if ((l=fq.getLine())==NULL)
458 <              GError("Error: unexpected EOF after header for %s\n",rname.chars());
459 <          rseq=l; //this must be the DNA line
460 <          while ((l=fq.getLine())!=NULL) {
461 <              //seq can span multiple lines
462 <              if (l[0]=='>' || l[0]=='+') {
463 <                   fq.pushBack();
464 <                   break; //
428 >    int incounter=0; //counter for input reads
429 >    int outcounter=0; //counter for output reads
430 >    int trash_s=0; //too short from the get go
431 >    int trash_Q=0;
432 >    int trash_N=0;
433 >    int trash_D=0;
434 >    int trash_A3=0;
435 >    int trash_A5=0;
436 >    s=infile;
437 >    GStr infname;
438 >    GStr infname2;
439 >    FILE* f_in=NULL;
440 >    FILE* f_in2=NULL;
441 >    FILE* f_out=NULL;
442 >    FILE* f_out2=NULL;
443 >    bool paired_reads=false;
444 >    setupFiles(f_in, f_in2, f_out, f_out2, s, infname, infname2);
445 >    GLineReader fq(f_in);
446 >    GLineReader* fq2=NULL;
447 >    if (f_in2!=NULL) {
448 >       fq2=new GLineReader(f_in2);
449 >       paired_reads=true;
450 >       }
451 >    GStr rseq, rqv, seqid, seqinfo;
452 >    GStr rseq2, rqv2, seqid2, seqinfo2;
453 >    while (getFastxRec(fq, rseq, rqv, seqid, seqinfo, infname)) {
454 >       incounter++;
455 >       int a5=0, a3=0, b5=0, b3=0;
456 >       char tcode=0, tcode2=0;
457 >       tcode=process_read(seqid, rseq, rqv, a5, a3);
458 >       //if (!doCollapse) {
459 >         if (fq2!=NULL) {
460 >            getFastxRec(*fq2, rseq2, rqv2, seqid2, seqinfo2, infname2);
461 >            if (seqid.substr(0,seqid.length()-1)!=seqid2.substr(0,seqid2.length()-1)) {
462 >               GError("Error: no paired match for read %s vs %s (%s,%s)\n",
463 >                  seqid.chars(), seqid2.chars(), infname.chars(), infname2.chars());
464 >               }
465 >            tcode2=process_read(seqid2, rseq2, rqv2, b5, b3);
466 >            //decide what to do with this pair and print rseq2 if the pair makes it
467 >            if (tcode>1 && tcode2<=1) {
468 >               //"untrash" rseq
469 >               if (a3-a5+1<min_read_len) {
470 >                   a5=1;
471 >                   if (a3<min_read_len) { a3= GMIN(rseq.length()-1, min_read_len+1); }
472                     }
473 <              rseq+=l;
474 <              } //check for multi-line seq
475 <          if (!isfasta) { //reading fastq quality values, which can also be multi-line
476 <            if ((l=fq.getLine())==NULL)
477 <                GError("Error: unexpected EOF after sequence for %s\n", rname.chars());
478 <            if (l[0]!='+') GError("Error: fastq qv header marker not detected!\n");
479 <            if ((l=fq.getLine())==NULL)
480 <                GError("Error: unexpected EOF after qv header for %s\n", rname.chars());
481 <            rqv=l;
482 <            //if (rqv.length()!=rseq.length())
483 <            //  GError("Error: qv len != seq len for %s\n", rname.chars());
484 <            while (rqv.length()<rseq.length() && ((l=fq.getLine())!=NULL)) {
485 <              rqv+=l; //append to qv string
486 <              }
420 <            }// fastq
421 <        // } //<-- FASTA or FASTQ
422 <        rseq.upper();
423 <        int l5=0;
424 <        int l3=rseq.length()-1;
425 <        if (l3-l5+1<min_read_len) {
426 <           if (trashReport) {
427 <                  fprintf(freport, "%s\ts\t%s\n",rname.chars(), rseq.chars());
428 <                  }
429 <           continue;
430 <           }
431 <        if (ntrim(rseq, l5, l3)) { // N-trimming
432 <           //GMessage("before: %s\n",rseq.chars());
433 <           //GMessage("after : %s (%d)\n",rseq.substr(l5,l3-l5+1).chars(),l3-l5+1);
434 <           if (l3-l5+1<min_read_len) {
435 <             if (trashReport) {
436 <                    fprintf(freport, "%s\tN\t%s\n", rname.chars(), rseq.chars());
437 <                    }
438 <             continue; //invalid read
439 <             }
440 <            //-- keep only the l5..l3 range
441 <           rseq=rseq.substr(l5, l3-l5+1);
442 <           if (!rqv.is_empty())
443 <              rqv=rqv.substr(l5, l3-l5+1);
444 <           l5=0;
445 <           l3=rseq.length()-1;
446 <           }
447 <        if (qvtrim_min!=0 && !rqv.is_empty() && qtrim(rqv, l5, l3)) { // qv-threshold trimming
448 <           if (l3-l5+1<min_read_len) {
449 <             if (trashReport) {
450 <                    fprintf(freport, "%s\tQ\t%s\n", rname.chars(), rseq.chars());
451 <                    }
452 <             continue; //invalid read
453 <             }
454 <            //-- keep only the l5..l3 range
455 <           rseq=rseq.substr(l5, l3-l5+1);
456 <           if (!rqv.is_empty())
457 <              rqv=rqv.substr(l5, l3-l5+1);
458 <           } //qv trimming
459 <        if (a3len>0) {
460 <          if (trim_adapter3(rseq, l5, l3)) {
461 <             if (l3-l5+1<min_read_len) {
462 <                 if (trashReport) {
463 <                     fprintf(freport, "%s\tA3\t%s\n",rname.chars(), rseq.chars());
464 <                     }
465 <                 continue;
466 <                 }
467 <              //-- keep only the l5..l3 range
468 <              rseq=rseq.substr(l5, l3-l5+1);
469 <              if (!rqv.is_empty())
470 <                 rqv=rqv.substr(l5, l3-l5+1);
471 <              }//some adapter was trimmed
472 <           } //adapter trimming
473 <        if (a5len>0) {
474 <          if (trim_adapter5(rseq, l5, l3)) {
475 <             if (l3-l5+1<min_read_len) {
476 <                 if (trashReport) {
477 <                     fprintf(freport, "%s\tA5\t%s\n",rname.chars(), rseq.chars());
478 <                     }
479 <                 continue;
473 >               tcode=1;
474 >               }
475 >             else if (tcode<=1 && tcode2>1) {
476 >               //"untrash" rseq2
477 >               if (b3-b5+1<min_read_len) {
478 >                   b5=1;
479 >                   if (b3<min_read_len) { b3= GMIN((rseq2.length()-1),(min_read_len+1)); }
480 >                   }
481 >               tcode2=1;
482 >               }
483 >            if (tcode<=1) { //trimmed or left intact -- write it!
484 >               if (tcode>0) {
485 >                 rseq2=rseq2.substr(b5,b3-b5+1);
486 >                 if (!rqv2.is_empty()) rqv2=rqv2.substr(b5,b3-b5+1);
487                   }
488 <              //-- keep only the l5..l3 range
489 <              rseq=rseq.substr(l5, l3-l5+1);
490 <              if (!rqv.is_empty())
491 <                 rqv=rqv.substr(l5, l3-l5+1);
492 <              }//some adapter was trimmed
493 <           } //adapter trimming
494 <        if (doCollapse) {
495 <           //keep read for later
496 <           FqDupRec* dr=dhash.Find(rseq.chars());
497 <           if (dr==NULL) { //new entry
498 <                  //if (prefix.is_empty())
499 <                     dhash.Add(rseq.chars(),
500 <                          new FqDupRec(&rqv, rname.chars()));
501 <                  //else dhash.Add(rseq.chars(), new FqDupRec(rqv.chars(),rqv.length()));
488 >               int nocounter=0;
489 >               writeRead(f_out2, seqid2, seqinfo2, rseq2, rqv2, nocounter);
490 >               }
491 >            } //paired read
492 >       // }
493 >       if (tcode>1) { //trashed
494 >          if (tcode=='s') trash_s++;
495 >            else if (tcode=='Q') trash_Q++;
496 >              else if (tcode=='N') trash_N++;
497 >               else if (tcode=='D') trash_D++;
498 >                else if (tcode=='3') trash_A3++;
499 >                 else if (tcode=='5') trash_A5++;
500 >          if (trashReport) trash_report(tcode, seqid, freport);
501 >          }
502 >         else if (!doCollapse) { //write it
503 >          if (tcode>0) {
504 >            rseq=rseq.substr(a5,a3-a5+1);
505 >            if (!rqv.is_empty()) rqv=rqv.substr(a5,a3-a5+1);
506 >            }
507 >          writeRead(f_out, seqid, seqinfo, rseq, rqv, outcounter);
508 >          }
509 >       } //for each fastq record
510 >    delete fq2;
511 >    FRCLOSE(f_in);
512 >    FRCLOSE(f_in2);
513 >    if (doCollapse) {
514 >       outcounter=0;
515 >       int maxdup_count=1;
516 >       char* maxdup_seq=NULL;
517 >       dhash.startIterate();
518 >       FqDupRec* qd=NULL;
519 >       char* seq=NULL;
520 >       while ((qd=dhash.NextData(seq))!=NULL) {
521 >         GStr rseq(seq);
522 >         //do the dusting here
523 >         if (doDust) {
524 >            int dustbases=dust(rseq);
525 >            if (dustbases>(rseq.length()>>1)) {
526 >               if (trashReport && qd->firstname!=NULL) {
527 >                 fprintf(freport, "%s_x%d\tD\n",qd->firstname, qd->count);
528                   }
529 <              else    
530 <                 dr->add(rqv);
531 <           } //collapsing duplicates
532 <         else { //not collapsing duplicates
533 <           //do the dust filter now
534 <           if (doDust) {
535 <             int dustbases=dust(rseq);
536 <             if (dustbases>(rseq.length()>>1)) {
537 <                if (trashReport) {
538 <                  fprintf(freport, "%s\tD\t%s\n",rname.chars(),rseq.chars());
539 <                  }
540 <                continue;
541 <                }
509 <             }
510 <           //print this record here  
511 <           outcounter++;
512 <           if (isfasta) {
513 <            if (prefix.is_empty())
514 <               fprintf(f_out, ">%s\n%s\n", rname.chars(), rseq.chars());
515 <              else
516 <               fprintf(f_out, ">%s%08d\n%s\n", prefix.chars(), outcounter,
517 <                                  rseq.chars());
529 >               trash_D+=qd->count;
530 >               continue;
531 >               }
532 >            }
533 >         outcounter++;
534 >         if (qd->count>maxdup_count) {
535 >            maxdup_count=qd->count;
536 >            maxdup_seq=seq;
537 >            }
538 >         if (isfasta) {
539 >           if (prefix.is_empty()) {
540 >             fprintf(f_out, ">%s_x%d\n%s\n", qd->firstname, qd->count,
541 >                           rseq.chars());
542               }
543 <           else {  //fastq
544 <            if (convert_phred) convertPhred(rqv);
545 <            if (prefix.is_empty())
522 <               fprintf(f_out, "@%s\n%s\n+\n%s\n", rname.chars(), rseq.chars(),rqv.chars());
523 <              else
524 <               fprintf(f_out, "@%s_%08d\n%s\n+\n%s\n", prefix.chars(), outcounter,
525 <                                  rseq.chars(),rqv.chars() );
543 >           else { //use custom read name
544 >             fprintf(f_out, ">%s%08d_x%d\n%s\n", prefix.chars(), outcounter,
545 >                        qd->count, rseq.chars());
546               }
547 <           } //not collapsing duplicates
548 <        } //for each fastq record
549 <   } //while each input file
550 < FRCLOSE(f_in);
551 < if (doCollapse) {
552 <    outcounter=0;
533 <    int maxdup_count=1;
534 <    char* maxdup_seq=NULL;
535 <    dhash.startIterate();
536 <    FqDupRec* qd=NULL;
537 <    char* seq=NULL;
538 <    while ((qd=dhash.NextData(seq))!=NULL) {
539 <      GStr rseq(seq);
540 <      //do the dusting here
541 <      if (doDust) {
542 <         int dustbases=dust(rseq);
543 <         if (dustbases>(rseq.length()>>1)) {
544 <            if (trashReport && qd->firstname!=NULL) {
545 <              fprintf(freport, "%s_x%d\tD\t%s\n",qd->firstname, qd->count,seq);
546 <              }
547 <            continue;
547 >           }
548 >         else { //fastq format
549 >          if (convert_phred) convertPhred(qd->qv, qd->len);
550 >          if (prefix.is_empty()) {
551 >            fprintf(f_out, "@%s_x%d\n%s\n+\n%s\n", qd->firstname, qd->count,
552 >                           rseq.chars(), qd->qv);
553              }
554 +          else { //use custom read name
555 +            fprintf(f_out, "@%s%08d_x%d\n%s\n+\n%s\n", prefix.chars(), outcounter,
556 +                        qd->count, rseq.chars(), qd->qv);
557 +            }
558 +           }
559 +         }//for each element of dhash
560 +       if (maxdup_count>1) {
561 +         GMessage("Maximum read multiplicity: x %d (read: %s)\n",maxdup_count, maxdup_seq);
562           }
563 <      outcounter++;
564 <      if (qd->count>maxdup_count) {
565 <         maxdup_count=qd->count;
566 <         maxdup_seq=seq;
567 <         }
568 <      if (isfasta) {
569 <        if (prefix.is_empty()) {
570 <          fprintf(f_out, ">%s_x%d\n%s\n", qd->firstname, qd->count,
571 <                        rseq.chars());
572 <          }
573 <        else { //use custom read name
574 <          fprintf(f_out, ">%s%08d_x%d\n%s\n", prefix.chars(), outcounter,
575 <                     qd->count, rseq.chars());
563 >       } //collapse entries
564 >    if (verbose) {
565 >       if (paired_reads) {
566 >           GMessage(">Input files : %s , %s\n", infname.chars(), infname2.chars());
567 >           GMessage("Number of input pairs :%9d\n", incounter);
568 >           GMessage("         Output pairs :%9d\n", outcounter);
569 >           }
570 >         else {
571 >           GMessage(">Input file : %s\n", infname.chars());
572 >           GMessage("Number of input reads :%9d\n", incounter);
573 >           GMessage("         Output reads :%9d\n", outcounter);
574 >           }
575 >       GMessage("------------------------------------\n");
576 >       if (num_trimmed5)
577 >          GMessage("           5' trimmed :%9d  (min. trim: %d)\n", num_trimmed5, min_trimmed5);
578 >       if (num_trimmed3)
579 >          GMessage("           3' trimmed :%9d  (min. trim: %d)\n", num_trimmed3, min_trimmed3);
580 >       GMessage("------------------------------------\n");
581 >       if (trash_s>0)
582 >         GMessage("     Trashed by length:%9d\n", trash_s);
583 >       if (trash_N>0)
584 >         GMessage("         Trashed by N%%:%9d\n", trash_N);
585 >       if (trash_Q>0)
586 >         GMessage("Trashed by low quality:%9d\n", trash_Q);
587 >       if (trash_A5>0)
588 >         GMessage(" Trashed by 5' adapter:%9d\n", trash_A5);
589 >       if (trash_A3>0)
590 >         GMessage(" Trashed by 3' adapter:%9d\n", trash_A3);
591 >       }
592 >    if (trashReport) {
593 >          FWCLOSE(freport);
594            }
595 <        }
596 <      else { //fastq format
597 <       if (convert_phred) convertPhred(qd->qv, qd->len);
567 <       if (prefix.is_empty()) {
568 <         fprintf(f_out, "@%s_x%d\n%s\n+\n%s\n", qd->firstname, qd->count,
569 <                        rseq.chars(), qd->qv);
570 <         }
571 <       else { //use custom read name
572 <         fprintf(f_out, "@%s%08d_x%d\n%s\n+\n%s\n", prefix.chars(), outcounter,
573 <                     qd->count, rseq.chars(), qd->qv);
574 <         }
575 <        }
576 <      }//for each element of dhash
577 <    if (maxdup_count>1) {
578 <      GMessage("Maximum read multiplicity: x %d (read: %s)\n",maxdup_count, maxdup_seq);
579 <      }
580 <   } //report collapsed dhash entries
581 < GMessage("Number of input reads: %9d\n", icounter);
582 < GMessage("       Output records: %9d\n", outcounter);
583 < if (trashReport) {
584 <    FWCLOSE(freport);
585 <    }
595 >    FWCLOSE(f_out);
596 >    FWCLOSE(f_out2);
597 >   } //while each input file
598  
587 FWCLOSE(f_out);
599   //getc(stdin);
600   }
601  
# Line 670 | Line 681
681  
682  
683   bool qtrim(GStr& qvs, int &l5, int &l3) {
684 < if (qvtrim_min==0 || qvs.is_empty()) return false;
684 > if (qvtrim_qmin==0 || qvs.is_empty()) return false;
685   if (qv_phredtype==0) {
686    //try to guess the Phred type
687    int vmin=256, vmax=0;
# Line 683 | Line 694
694    if (qv_phredtype==0) {
695      GError("Error: couldn't determine Phred type, please use the -p33 or -p64 !\n");
696      }
697 <  } //guessing the Phred type
697 >  if (verbose)
698 >    GMessage("Input reads have Phred-%d quality values.\n", (qv_phredtype==33 ? 33 : 64));
699 >  } //guessing Phred type
700   for (l3=qvs.length()-1;l3>2;l3--) {
701 <  if (qvs[l3]-qv_phredtype>=qvtrim_min && qvs[l3-1]-qv_phredtype>=qvtrim_min) break;
701 >  if (qvs[l3]-qv_phredtype>=qvtrim_qmin && qvs[l3-1]-qv_phredtype>=qvtrim_qmin) break;
702    }
703   //just in case, check also the 5' the end (?)
704   for (l5=0;l5<qvs.length()-3;l5++) {
705 <  if (qvs[l5]-qv_phredtype>=qvtrim_min && qvs[l5+1]-qv_phredtype>=qvtrim_min) break;
705 >  if (qvs[l5]-qv_phredtype>=qvtrim_qmin && qvs[l5+1]-qv_phredtype>=qvtrim_qmin) break;
706 >  }
707 > if (qvtrim_max>0) {
708 >  if (qvs.length()-1-l3>qvtrim_max) l3=qvs.length()-1-qvtrim_max;
709 >  if (l5>qvtrim_max) l5=qvtrim_max;
710    }
711   return (l5>0 || l3<qvs.length()-1);
712   }
# Line 1012 | Line 1029
1029     }
1030   }
1031   #endif
1032 + const char *pA_seed="AAAA";
1033 + const char *pT_seed="TTTT";
1034 + const int polyA_seed=*(int*)pA_seed;
1035 + const int polyT_seed=*(int*)pT_seed;
1036 +
1037 + bool trim_poly3(GStr &seq, int &l5, int &l3) {
1038 + int rlen=seq.length();
1039 + l5=0;
1040 + l3=rlen-1;
1041 + //assumes N trimming was already done
1042 + //so a poly match should be very close to the end of the read
1043 + //TODO: should we attempt polyA and polyT at the same time, same end?
1044 + // -- find the initial match (seed)
1045 + int rlo=GMAX((rlen-10), 0);
1046 + int si;
1047 + for (si=rlen-5;si>rlo;si--) {
1048 +   if (polyA_seed==*(int*)&(seq.chars()+si)) {
1049 +      break;
1050 +      }
1051 +   }
1052 + if (si<=rlo) return false;
1053 + //seed found, try to extend it to left and right
1054 + int score=4*match_score;
1055 + max_rlo=rlo;
1056 + rlo--;
1057 + while (rlo>=0) {
1058 +    rlo--;
1059 +    score+=
1060 +    
1061 +    }
1062 + }
1063  
1064   bool trim_adapter3(GStr& seq, int&l5, int &l3) {
1065   int rlen=seq.length();
# Line 1313 | Line 1361
1361   for (int i=0;i<len;i++) q[i]+=qv_cvtadd;
1362   }
1363  
1364 + bool getFastxRec(GLineReader& fq, GStr& rseq, GStr& rqv,
1365 +          GStr& rname, GStr& rinfo, GStr& infname) {
1366 + rseq="";
1367 + rqv="";
1368 + rname="";
1369 + rinfo="";
1370 + if (fq.eof()) return false;
1371 + char* l=fq.getLine();
1372 + while (l!=NULL && (l[0]==0 || isspace(l[0]))) l=fq.getLine(); //ignore empty lines
1373 + if (l==NULL) return false;
1374 + /* if (rawFormat) {
1375 +      //TODO: implement raw qseq parsing here
1376 +      //if (raw type=N) then continue; //skip invalid/bad records
1377 +      } //raw qseq format
1378 + else { // FASTQ or FASTA */
1379 + isfasta=(l[0]=='>');
1380 + if (!isfasta && l[0]!='@') GError("Error: fasta/fastq record marker not found(%s)\n%s\n",
1381 +      infname.chars(), l);
1382 + GStr s(l);
1383 + rname=&(l[1]);
1384 + for (int i=0;i<rname.length();i++)
1385 +    if (rname[i]<=' ') {
1386 +       if (i<rname.length()-2) rinfo=rname.substr(i+1);
1387 +       rname.cut(i);
1388 +       break;
1389 +       }
1390 +  //now get the sequence
1391 + if ((l=fq.getLine())==NULL)
1392 +      GError("Error: unexpected EOF after header for read %s (%s)\n",
1393 +                   rname.chars(), infname.chars());
1394 + rseq=l; //this must be the DNA line
1395 + while ((l=fq.getLine())!=NULL) {
1396 +      //seq can span multiple lines
1397 +      if (l[0]=='>' || l[0]=='+') {
1398 +           fq.pushBack();
1399 +           break; //
1400 +           }
1401 +      rseq+=l;
1402 +      } //check for multi-line seq
1403 + if (!isfasta) { //reading fastq quality values, which can also be multi-line
1404 +    if ((l=fq.getLine())==NULL)
1405 +        GError("Error: unexpected EOF after sequence for %s\n", rname.chars());
1406 +    if (l[0]!='+') GError("Error: fastq qv header marker not detected!\n");
1407 +    if ((l=fq.getLine())==NULL)
1408 +        GError("Error: unexpected EOF after qv header for %s\n", rname.chars());
1409 +    rqv=l;
1410 +    //if (rqv.length()!=rseq.length())
1411 +    //  GError("Error: qv len != seq len for %s\n", rname.chars());
1412 +    while (rqv.length()<rseq.length() && ((l=fq.getLine())!=NULL)) {
1413 +      rqv+=l; //append to qv string
1414 +      }
1415 +    }// fastq
1416 + // } //<-- FASTA or FASTQ
1417 + rseq.upper(); //TODO: what if we care about masking?
1418 + return true;
1419 + }
1420 +
1421 + char process_read(GStr& rname, GStr& rseq, GStr& rqv, int &l5, int &l3) {
1422 + //returns 0 if the read was untouched, 1 if it was just trimmed
1423 + // and a trash code if it was trashed
1424 + l5=0;
1425 + l3=rseq.length()-1;
1426 + if (l3-l5+1<min_read_len) {
1427 +   return 's';
1428 +   }
1429 + GStr wseq(rseq.chars());
1430 + GStr wqv(rqv.chars());
1431 + int w5=l5;
1432 + int w3=l3;
1433 + //first do the q-based trimming
1434 + if (qvtrim_qmin!=0 && !wqv.is_empty() && qtrim(wqv, w5, w3)) { // qv-threshold trimming
1435 +   if (w3-w5+1<min_read_len) {
1436 +     return 'Q'; //invalid read
1437 +     }
1438 +    //-- keep only the w5..w3 range
1439 +   l5=w5;
1440 +   l3=w3;
1441 +   wseq=wseq.substr(w5, w3-w5+1);
1442 +   if (!wqv.is_empty())
1443 +      wqv=wqv.substr(w5, w3-w5+1);
1444 +   } //qv trimming
1445 + // N-trimming on the remaining read seq
1446 + if (ntrim(wseq, w5, w3)) {
1447 +   //GMessage("before: %s\n",wseq.chars());
1448 +   //GMessage("after : %s (%d)\n",wseq.substr(w5,w3-w5+1).chars(),w3-w5+1);
1449 +   l5+=w5;
1450 +   l3-=(wseq.length()-1-w3);
1451 +   if (w3-w5+1<min_read_len) {
1452 +     return 'N'; //to be trashed
1453 +     }
1454 +    //-- keep only the w5..w3 range
1455 +   wseq=wseq.substr(w5, w3-w5+1);
1456 +   if (!wqv.is_empty())
1457 +      wqv=wqv.substr(w5, w3-w5+1);
1458 +   w5=0;
1459 +   w3=wseq.length()-1;
1460 +   }
1461 + if (a3len>0) {
1462 +  if (trim_adapter3(wseq, w5, w3)) {
1463 +     int trimlen=wseq.length()-(w3-w5+1);
1464 +     num_trimmed3++;
1465 +     if (trimlen<min_trimmed3)
1466 +         min_trimmed3=trimlen;
1467 +     l5+=w5;
1468 +     l3-=(wseq.length()-1-w3);
1469 +     if (w3-w5+1<min_read_len) {
1470 +         return '3';
1471 +         }
1472 +      //-- keep only the w5..w3 range
1473 +      wseq=wseq.substr(w5, w3-w5+1);
1474 +      if (!wqv.is_empty())
1475 +         wqv=wqv.substr(w5, w3-w5+1);
1476 +      }//some adapter was trimmed
1477 +   } //adapter trimming
1478 + if (a5len>0) {
1479 +  if (trim_adapter5(wseq, w5, w3)) {
1480 +     int trimlen=wseq.length()-(w3-w5+1);
1481 +     num_trimmed5++;
1482 +     if (trimlen<min_trimmed5)
1483 +         min_trimmed5=trimlen;
1484 +     l5+=w5;
1485 +     l3-=(wseq.length()-1-w3);
1486 +     if (w3-w5+1<min_read_len) {
1487 +         return '5';
1488 +         }
1489 +      //-- keep only the w5..w3 range
1490 +      wseq=wseq.substr(w5, w3-w5+1);
1491 +      if (!wqv.is_empty())
1492 +         wqv=wqv.substr(w5, w3-w5+1);
1493 +      }//some adapter was trimmed
1494 +   } //adapter trimming
1495 + if (doCollapse) {
1496 +   //keep read for later
1497 +   FqDupRec* dr=dhash.Find(wseq.chars());
1498 +   if (dr==NULL) { //new entry
1499 +          //if (prefix.is_empty())
1500 +             dhash.Add(wseq.chars(),
1501 +                  new FqDupRec(&wqv, rname.chars()));
1502 +          //else dhash.Add(wseq.chars(), new FqDupRec(wqv.chars(),wqv.length()));
1503 +         }
1504 +      else
1505 +         dr->add(wqv);
1506 +   } //collapsing duplicates
1507 + else { //not collapsing duplicates
1508 +   //apply the dust filter now
1509 +   if (doDust) {
1510 +     int dustbases=dust(wseq);
1511 +     if (dustbases>(wseq.length()>>1)) {
1512 +        return 'D';
1513 +        }
1514 +     }
1515 +   } //not collapsing duplicates
1516 + return (l5>0 || l3<rseq.length()-1) ? 1 : 0;
1517 + }
1518 +
1519 + void printHeader(FILE* f_out, char recmarker, GStr& rname, GStr& rinfo) {
1520 + //GMessage("printing Header..%c%s\n",recmarker, rname.chars());
1521 + if (rinfo.is_empty()) fprintf(f_out, "%c%s\n",recmarker,rname.chars());
1522 +  else fprintf(f_out, "%c%s %s\n",recmarker, rname.chars(), rinfo.chars());
1523 + }
1524 +
1525 + void writeRead(FILE* f_out, GStr& rname, GStr& rinfo, GStr& rseq, GStr& rqv, int& outcounter) {
1526 +   outcounter++;
1527 +   bool asFasta=(rqv.is_empty() || fastaOutput);
1528 +   if (asFasta) {
1529 +    if (prefix.is_empty()) {
1530 +       printHeader(f_out, '>',rname,rinfo);
1531 +       fprintf(f_out, "%s\n", rseq.chars()); //plain one-line fasta for now
1532 +       }
1533 +      else {
1534 +       fprintf(f_out, ">%s%08d\n%s\n", prefix.chars(), outcounter,
1535 +                          rseq.chars());
1536 +       }
1537 +     }
1538 +   else {  //fastq
1539 +    if (convert_phred) convertPhred(rqv);
1540 +    if (prefix.is_empty()) {
1541 +       printHeader(f_out, '@', rname, rinfo);
1542 +       fprintf(f_out, "%s\n+\n%s\n", rseq.chars(), rqv.chars());
1543 +       }
1544 +      else
1545 +       fprintf(f_out, "@%s_%08d\n%s\n+\n%s\n", prefix.chars(), outcounter,
1546 +                          rseq.chars(),rqv.chars() );
1547 +     }
1548 + }
1549 +
1550 + void trash_report(char trashcode, GStr& rname, FILE* freport) {
1551 + if (freport==NULL || trashcode<=' ') return;
1552 + if (trashcode=='3' || trashcode=='5') {
1553 +   fprintf(freport, "%s\tA%c\n",rname.chars(),trashcode);
1554 +   }
1555 + else {
1556 +   fprintf(freport, "%s\t%c\n",rname.chars(),trashcode);
1557 +   }
1558 + //tcounter++;
1559 + }
1560 +
1561 + GStr getFext(GStr& s, int* xpos=NULL) {
1562 + //s must be a filename without a path
1563 + GStr r("");
1564 + if (xpos!=NULL) *xpos=0;
1565 + if (s.is_empty() || s=="-") return r;
1566 + int p=s.rindex('.');
1567 + int d=s.rindex('/');
1568 + if (p<=0 || p>s.length()-2 || p<s.length()-7 || p<d) return r;
1569 + r=s.substr(p+1);
1570 + if (xpos!=NULL) *xpos=p+1;
1571 + r.lower();
1572 + return r;
1573 + }
1574 +
1575 + void baseFileName(GStr& fname) {
1576 + //remove all known extensions, like .txt,fq,fastq,fasta,fa)(.gz .gzip .bz2 .bzip2) .
1577 + int xpos=0;
1578 + GStr fext=getFext(fname, &xpos);
1579 + if (xpos<=1) return;
1580 + bool extdel=false;
1581 + GStr f2;
1582 + if (fext=="z" || fext=="zip") {
1583 +   extdel=true;
1584 +   }
1585 +  else if (fext.length()>=2) {
1586 +   f2=fext.substr(0,2);
1587 +   extdel=(f2=="gz" || f2=="bz");
1588 +   }
1589 + if (extdel) {
1590 +   fname.cut(xpos-1);
1591 +   fext=getFext(fname, &xpos);
1592 +   if (xpos<=1) return;
1593 +   }
1594 + extdel=false;
1595 + if (fext=="f" || fext=="fq" || fext=="txt" || fext=="seq" || fext=="sequence") {
1596 +   extdel=true;
1597 +   }
1598 +  else if (fext.length()>=2) {
1599 +   extdel=(fext.substr(0,2)=="fa");
1600 +   }
1601 + if (extdel) fname.cut(xpos-1);
1602 + GStr fncp(fname);
1603 + fncp.lower();
1604 + fncp.chomp("seq");
1605 + fncp.chomp("sequence");
1606 + fncp.trimR("_.");
1607 + if (fncp.length()<fname.length()) fname.cut(fncp.length());
1608 + }
1609 +
1610 + FILE* prepOutFile(GStr& infname, GStr& pocmd) {
1611 +  FILE* f_out=NULL;
1612 +  GStr fname(getFileName(infname.chars()));
1613 +  //eliminate known extensions
1614 +  baseFileName(fname);
1615 +  if (outsuffix.is_empty() || outsuffix=="-") { return stdout; }
1616 +    else if (pocmd.is_empty()) {
1617 +               GStr oname(fname);
1618 +               oname.append('.');
1619 +               oname.append(outsuffix);
1620 +               f_out=fopen(oname.chars(),"w");
1621 +               if (f_out==NULL) GError("Error: cannot create '%s'\n",oname.chars());
1622 +               }
1623 +            else {
1624 +              GStr oname(">");
1625 +              oname.append(fname);
1626 +              oname.append('.');
1627 +              oname.append(outsuffix);
1628 +              pocmd.append(oname);
1629 +              f_out=popen(pocmd.chars(), "w");
1630 +              if (f_out==NULL) GError("Error: cannot popen '%s'\n",pocmd.chars());
1631 +              }
1632 + return f_out;
1633 + }
1634 +
1635 + void guess_unzip(GStr& fname, GStr& picmd) {
1636 + GStr fext=getFext(fname);
1637 + if (fext=="gz" || fext=="gzip" || fext=="z") {
1638 +    picmd="gzip -cd ";
1639 +    }
1640 +   else if (fext=="bz2" || fext=="bzip2" || fext=="bz" || fext=="bzip") {
1641 +    picmd="bzip2 -cd ";
1642 +    }
1643 + }
1644 +
1645 + void setupFiles(FILE*& f_in, FILE*& f_in2, FILE*& f_out, FILE*& f_out2,
1646 +                       GStr& s, GStr& infname, GStr& infname2) {
1647 + // uses outsuffix to generate output file names and open file handles as needed
1648 + infname="";
1649 + infname2="";
1650 + f_in=NULL;
1651 + f_in2=NULL;
1652 + f_out=NULL;
1653 + f_out2=NULL;
1654 + //analyze outsuffix intent
1655 + GStr pocmd;
1656 + if (outsuffix=="-") {
1657 +    f_out=stdout;
1658 +    }
1659 +   else {
1660 +    GStr ox=getFext(outsuffix);
1661 +    if (ox.length()>2) ox=ox.substr(0,2);
1662 +    if (ox=="gz") pocmd="gzip -9 -c ";
1663 +        else if (ox=="bz") pocmd="bzip2 -9 -c ";
1664 +    }
1665 + if (s=="-") {
1666 +    f_in=stdin;
1667 +    infname="stdin";
1668 +    f_out=prepOutFile(infname, pocmd);
1669 +    return;
1670 +    } // streaming from stdin
1671 + s.startTokenize(",:");
1672 + s.nextToken(infname);
1673 + bool paired=s.nextToken(infname2);
1674 + if (fileExists(infname.chars())==0)
1675 +    GError("Error: cannot find file %s!\n",infname.chars());
1676 + GStr fname(getFileName(infname.chars()));
1677 + GStr picmd;
1678 + guess_unzip(fname, picmd);
1679 + if (picmd.is_empty()) {
1680 +   f_in=fopen(infname.chars(), "r");
1681 +   if (f_in==NULL) GError("Error opening file '%s'!\n",infname.chars());
1682 +   }
1683 +  else {
1684 +   picmd.append(infname);
1685 +   f_in=popen(picmd.chars(), "r");
1686 +   if (f_in==NULL) GError("Error at popen %s!\n", picmd.chars());
1687 +   }
1688 + if (f_out==stdout) {
1689 +   if (paired) GError("Error: output suffix required for paired reads\n");
1690 +   return;
1691 +   }
1692 + f_out=prepOutFile(infname, pocmd);
1693 + if (!paired) return;
1694 + if (doCollapse) GError("Error: sorry, -C option cannot be used with paired reads!\n");
1695 + // ---- paired reads:-------------
1696 + if (fileExists(infname2.chars())==0)
1697 +     GError("Error: cannot find file %s!\n",infname2.chars());
1698 + picmd="";
1699 + GStr fname2(getFileName(infname2.chars()));
1700 + guess_unzip(fname2, picmd);
1701 + if (picmd.is_empty()) {
1702 +   f_in2=fopen(infname2.chars(), "r");
1703 +   if (f_in2==NULL) GError("Error opening file '%s'!\n",infname2.chars());
1704 +   }
1705 +  else {
1706 +   picmd.append(infname2);
1707 +   f_in2=popen(picmd.chars(), "r");
1708 +   if (f_in2==NULL) GError("Error at popen %s!\n", picmd.chars());
1709 +   }
1710 + f_out2=prepOutFile(infname2, pocmd);
1711 + }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines