ViewVC Help
View File | Revision Log | Show Annotations | View Changeset | Root Listing
root/gclib/fqtrim/fqtrim.cpp
(Generate patch)
# Line 6 | Line 6
6   #include "GAlnExtend.h"
7  
8   #define USAGE "Usage:\n\
9 < fqtrim [{-5 <5adapter> -3 <3adapter>|-f <adapters_file>}] [-a <min_matchlen>]\\\n\
9 > fqtrim [{-5 <5adaptor> -3 <3adaptor>|-f <adaptors_file>}] [-a <min_matchlen>]\\\n\
10     [-R] [-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 the 3' end and can trim adapter sequence(s), filter\n\
14 > Trim low quality bases at the 3' end and can trim adaptor 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\
# Line 25 | Line 25
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\
28 > -f  file with adaptor sequences to trim, each line having this format:\n\
29 >    <5'-adaptor-sequence> <3'-adaptor-sequence>\n\
30 > -5  trim the given adaptor 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\
32 > -3  trim the given adaptor sequence at the 3' end of each read\n\
33      (e.g. -3 TCGTATGCCGTCTTCTGCTTG)\n\
34   -A  disable polyA/T trimming (enabled by default)\n\
35   -y  minimum length of exact match to adaptor sequence at the proper end (6)\n\
# Line 53 | Line 53
53   //   <zcmd> command, which must output to stdout (e.g. -z 'bzip2 -9 -c')\n
54  
55  
56 < // example 3' adapter for miRNAs: TCGTATGCCGTCTTCTGCTTG
56 > // example 3' adaptor for miRNAs: TCGTATGCCGTCTTCTGCTTG
57  
58   //For paired reads sequencing:
59   //3' : ACACTCTTTCCCTACACGACGCTCTTCCGATCT
# Line 94 | Line 94
94   int qv_cvtadd=0; //could be -31 or +31
95  
96   // adaptor matching metrics -- for X-drop ungapped extension
97 + //const int match_reward=2;
98 + //const int mismatch_penalty=3;
99   const int match_reward=2;
100 < const int mismatch_penalty=3;
101 < const int Xdrop=8;
100 > const int mismatch_penalty=4;
101 > const int Xdrop=10;
102  
103   const int poly_m_score=2; //match score
104   const int poly_mis_score=-3; //mismatch
# Line 107 | Line 109
109   const char *polyT_seed="TTTT";
110  
111   struct CASeqData {
112 <   //positional data for every possible hexamer in an adapter
113 <   GVec<uint16>* pz[4096]; //0-based coordinates of all possible hexamers in the adapter sequence
114 <   GVec<uint16>* pzr[4096]; //0-based coordinates of all possible hexamers for the reverse complement of the adapter sequence
115 <   GStr seq; //actual adapter sequence data
112 >   //positional data for every possible hexamer in an adaptor
113 >   GVec<uint16>* pz[4096]; //0-based coordinates of all possible hexamers in the adaptor sequence
114 >   GVec<uint16>* pzr[4096]; //0-based coordinates of all possible hexamers for the reverse complement of the adaptor sequence
115 >   GStr seq; //actual adaptor sequence data
116     GStr seqr; //reverse complement sequence
117 +   int amlen; //fraction of adaptor length matching that's
118 +              //enough to consider the alignment
119 +   GAlnTrimType trim_type;
120     bool use_reverse;
121 <   CASeqData(bool rev=false):seq(),seqr() {
122 <     use_reverse=rev;
121 >   CASeqData(bool rev=false):seq(),seqr(),
122 >             amlen(0), use_reverse(rev) {
123 >     trim_type=galn_None; //should be updated later!
124       for (int i=0;i<4096;i++) {
125          pz[i]=NULL;
126          pzr[i]=NULL;
# Line 122 | Line 128
128       }
129  
130     void update(const char* s) {
131 <   seq=s;
132 <   table6mers(seq.chars(), seq.length(), pz);
133 <   if (!use_reverse) return;
134 <   //reverse complement
135 <   seqr=s;
136 <   int slen=seq.length();
137 <   for (int i=0;i<slen;i++)
138 <     seqr[i]=ntComplement(seq[slen-i-1]);
139 <   table6mers(seqr.chars(), seqr.length(), pzr);
131 >         seq=s;
132 >         table6mers(seq.chars(), seq.length(), pz);
133 >         amlen=iround(double(seq.length())*0.8);
134 >         if (amlen<12)
135 >                amlen=12;
136 >         if (!use_reverse) return;
137 >         //reverse complement
138 >         seqr=s;
139 >         int slen=seq.length();
140 >         for (int i=0;i<slen;i++)
141 >           seqr[i]=ntComplement(seq[slen-i-1]);
142 >         table6mers(seqr.chars(), seqr.length(), pzr);
143     }
144  
145     ~CASeqData() {
# Line 141 | Line 150
150     }
151   };
152  
153 < GVec<CASeqData> adapters5;
154 < GVec<CASeqData> adapters3;
153 > GVec<CASeqData> adaptors5;
154 > GVec<CASeqData> adaptors3;
155  
156   CGreedyAlignData* gxmem_l=NULL;
157   CGreedyAlignData* gxmem_r=NULL;
# Line 195 | Line 204
204  
205   GHash<FqDupRec> dhash; //hash to keep track of duplicates
206  
207 < void addAdapter(GVec<CASeqData>& adapters, GStr& seq);
208 < int loadAdapters(const char* fname);
207 > void addAdaptor(GVec<CASeqData>& adaptors, GStr& seq, GAlnTrimType trim_type);
208 > int loadAdaptors(const char* fname);
209  
210   void setupFiles(FILE*& f_in, FILE*& f_in2, FILE*& f_out, FILE*& f_out2,
211                         GStr& s, GStr& infname, GStr& infname2);
# Line 216 | Line 225
225   int dust(GStr& seq);
226   bool trim_poly5(GStr &seq, int &l5, int &l3, const char* poly_seed); //returns true if any trimming occured
227   bool trim_poly3(GStr &seq, int &l5, int &l3, const char* poly_seed);
228 < bool trim_adapter5(GStr& seq, int &l5, int &l3); //returns true if any trimming occured
229 < bool trim_adapter3(GStr& seq, int &l5, int &l3);
228 > bool trim_adaptor5(GStr& seq, int &l5, int &l3); //returns true if any trimming occured
229 > bool trim_adaptor3(GStr& seq, int &l5, int &l3);
230  
231   void convertPhred(char* q, int len);
232   void convertPhred(GStr& q);
# Line 278 | Line 287
287       }
288    s=args.getOpt('f');
289    if (!s.is_empty()) {
290 <   loadAdapters(s.chars());
290 >   loadAdaptors(s.chars());
291     }
292 <  bool fileAdapters=adapters5.Count()+adapters3.Count();
292 >  bool fileAdaptors=adaptors5.Count()+adaptors3.Count();
293    s=args.getOpt('5');
294    if (!s.is_empty()) {
295 <    if (fileAdapters)
295 >    if (fileAdaptors)
296        GError("Error: options -5 and -f cannot be used together!\n");
297      s.upper();
298 <    addAdapter(adapters5, s);
298 >    addAdaptor(adaptors5, s, galn_TrimLeft);
299      }
300    s=args.getOpt('3');
301    if (!s.is_empty()) {
302 <    if (fileAdapters)
302 >    if (fileAdaptors)
303        GError("Error: options -3 and -f cannot be used together!\n");
304        s.upper();
305 <      addAdapter(adapters3, s);
305 >      addAdaptor(adaptors3, s, galn_TrimRight);
306      }
307    s=args.getOpt('y');
308    if (!s.is_empty()) {
# Line 318 | Line 327
327      openfw(freport, args, 'r');
328    char* infile=NULL;
329  
330 <  if (adapters5.Count()>0)
331 <    gxmem_l=new CGreedyAlignData(match_reward, mismatch_penalty, Xdrop-2);
332 <  if (adapters3.Count()>0)
330 >  if (adaptors5.Count()>0)
331 >    //gxmem_l=new CGreedyAlignData(match_reward, mismatch_penalty, Xdrop-2);
332 >        gxmem_l=new CGreedyAlignData(match_reward, mismatch_penalty, Xdrop);
333 >  if (adaptors3.Count()>0)
334      gxmem_r=new CGreedyAlignData(match_reward, mismatch_penalty, Xdrop);
335  
336    while ((infile=args.nextNonOpt())!=NULL) {
# Line 391 | Line 401
401              } //pair read
402         if (tcode>1) { //trashed
403           #ifdef GDEBUG
404 <         GMessage(" !!!!TRASH => 'N'\n");
404 >         GMessage(" !!!!TRASH code = %c\n",tcode);
405           #endif
406            if (tcode=='s') trash_s++;
407            else if (tcode=='A' || tcode=='T') trash_poly++;
# Line 494 | Line 504
504         if (trash_poly>0)
505           GMessage("   Trashed by poly-A/T:%9d\n", trash_poly);
506         if (trash_A5>0)
507 <         GMessage(" Trashed by 5' adapter:%9d\n", trash_A5);
507 >         GMessage(" Trashed by 5' adaptor:%9d\n", trash_A5);
508         if (trash_A3>0)
509 <         GMessage(" Trashed by 3' adapter:%9d\n", trash_A3);
509 >         GMessage(" Trashed by 3' adaptor:%9d\n", trash_A3);
510         }
511      if (trashReport) {
512            FWCLOSE(freport);
# Line 937 | Line 947
947   return false;
948   }
949  
950 < bool trim_adapter3(GStr& seq, int&l5, int &l3) {
951 < if (adapters3.Count()==0) return false;
950 > bool trim_adaptor3(GStr& seq, int&l5, int &l3) {
951 > if (adaptors3.Count()==0) return false;
952   int rlen=seq.length();
953   l5=0;
954   l3=rlen-1;
955   bool trimmed=false;
956 < GStr wseq(seq.chars());
956 > GStr wseq(seq);
957   int wlen=rlen;
958 < for (int ai=0;ai<adapters3.Count();ai++) {
959 <  //if (adapters3[ai].is_empty()) continue;
960 <  int alen=adapters3[ai].seq.length();
961 <  GStr& aseq=adapters3[ai].seq;
962 <  GXAlnInfo* r_bestaln=match_RightEnd(aseq.chars(), alen, adapters3[ai].pz,
963 <                            wseq.chars(), wlen, gxmem_r, 74);
964 <  if (r_bestaln) {
958 > GXSeqData seqdata;
959 > int numruns=revCompl ? 2 : 1;
960 >
961 > for (int ai=0;ai<adaptors3.Count();ai++) {
962 >   for (int r=0;r<numruns;r++) {
963 >     if (r) {
964 >          seqdata.update(adaptors3[ai].seqr.chars(), adaptors3[ai].seqr.length(),
965 >                 adaptors3[ai].pzr, wseq.chars(), wlen, adaptors3[ai].amlen);
966 >        }
967 >     else {
968 >            seqdata.update(adaptors3[ai].seq.chars(), adaptors3[ai].seq.length(),
969 >                 adaptors3[ai].pz, wseq.chars(), wlen, adaptors3[ai].amlen);
970 >        }
971 >
972 >  GXAlnInfo* aln=match_adaptor(seqdata, adaptors3[ai].trim_type, gxmem_r, 86);
973 >  if (aln) {
974       trimmed=true;
975 <     //keep unmatched region on the left, if any
976 <     l3-=(wlen-r_bestaln->sl+1);
977 <     delete r_bestaln;
978 <     if (l3<0) l3=0;
975 >     //keep unmatched region on the left OR right (the longer one)
976 >     if (aln->sl > wlen-aln->sr) {
977 >         //keep left side
978 >         l3-=(wlen-aln->sl+1);
979 >         if (l3<0) l3=0;
980 >         }
981 >     else { //keep right side
982 >         l5+=aln->sr;
983 >         if (l5>=rlen) l5=rlen-1;
984 >         }
985 >     delete aln;
986       if (l3-l5+1<min_read_len) return true;
987       wseq=seq.substr(l5,l3-l5+1);
988       wlen=wseq.length();
989       }
990 <  }//for each 5' adapter
990 >   }//forward and reverse adaptors
991 >  }//for each 3' adaptor
992    return trimmed;
993   }
994  
995 < bool trim_adapter5(GStr& seq, int&l5, int &l3) {
996 < if (adapters5.Count()==0) return false;
995 > bool trim_adaptor5(GStr& seq, int&l5, int &l3) {
996 > if (adaptors5.Count()==0) return false;
997   int rlen=seq.length();
998   l5=0;
999   l3=rlen-1;
1000   bool trimmed=false;
1001 < GStr wseq(seq.chars());
1001 > GStr wseq(seq);
1002   int wlen=rlen;
1003 < for (int ai=0;ai<adapters5.Count();ai++) {
1004 <  //if (adapters5[ai].is_empty()) continue;
1005 <  int alen=adapters5[ai].seq.length();
1006 <  GStr& aseq=adapters5[ai].seq;
1007 <  GXAlnInfo* l_bestaln=match_LeftEnd(aseq.chars(), alen, adapters5[ai].pz,
1008 <                 wseq.chars(), wlen, gxmem_l, 84);
1009 <  if (l_bestaln) {
1010 <     trimmed=true;
1011 <     l5+=l_bestaln->sr;
1012 <     delete l_bestaln;
1013 <     if (l5>=rlen) l5=rlen-1;
1014 <     if (l3-l5+1<min_read_len) return true;
1015 <     wseq=seq.substr(l5,l3-l5+1);
1016 <     wlen=wseq.length();
1003 > GXSeqData seqdata;
1004 > int numruns=revCompl ? 2 : 1;
1005 > GList<GXAlnInfo> bestalns(true, true, false);
1006 > for (int ai=0;ai<adaptors5.Count();ai++) {
1007 >   for (int r=0;r<numruns;r++) {
1008 >     if (r) {
1009 >          seqdata.update(adaptors5[ai].seqr.chars(), adaptors5[ai].seqr.length(),
1010 >                 adaptors5[ai].pzr, wseq.chars(), wlen, adaptors5[ai].amlen);
1011 >        }
1012 >     else {
1013 >            seqdata.update(adaptors5[ai].seq.chars(), adaptors5[ai].seq.length(),
1014 >                 adaptors5[ai].pz, wseq.chars(), wlen, adaptors5[ai].amlen);
1015 >        }
1016 >         GXAlnInfo* aln=match_adaptor(seqdata, adaptors5[ai].trim_type, gxmem_l, 90);
1017 >         if (aln) {
1018 >           if (aln->strong) {
1019 >                   trimmed=true;
1020 >                   bestalns.Add(aln);
1021 >                   break; //will check the rest next time
1022 >                   }
1023 >            else bestalns.Add(aln);
1024 >           }
1025 >         } //forward and reverse?
1026 >   if (trimmed) break; //will check the rest in the next cycle
1027 >  }//for each 5' adaptor
1028 >  if (bestalns.Count()>0) {
1029 >           GXAlnInfo* aln=bestalns[0];
1030 >           if (aln->sl-1 > wlen-aln->sr) {
1031 >                   //keep left side
1032 >                   l3-=(wlen-aln->sl+1);
1033 >                   if (l3<0) l3=0;
1034 >                   }
1035 >           else { //keep right side
1036 >                   l5+=aln->sr;
1037 >                   if (l5>=rlen) l5=rlen-1;
1038 >                   }
1039 >           //delete aln;
1040 >           //if (l3-l5+1<min_read_len) return true;
1041 >           wseq=seq.substr(l5,l3-l5+1);
1042 >           wlen=wseq.length();
1043 >           return true; //break the loops here to report a good find
1044       }
1045 <  }//for each 5' adapter
992 <  return trimmed;
1045 >  return false;
1046   }
1047  
1048   //convert qvs to/from phred64 from/to phread33
# Line 1060 | Line 1113
1113  
1114   #ifdef GDEBUG
1115   void showTrim(GStr& s, int l5, int l3) {
1116 <  if (l5>0) {
1116 >  if (l5>0 || l3==0) {
1117      color_bg(c_red);
1118      }
1119    for (int i=0;i<s.length()-1;i++) {
1120      if (i && i==l5) color_resetbg();
1121      fprintf(stderr, "%c", s[i]);
1122 <    if (i==l3) color_bg(c_red);
1122 >    if (i && i==l3) color_bg(c_red);
1123     }
1124    fprintf(stderr, "%c", s[s.length()-1]);
1125    color_reset();
# Line 1120 | Line 1173
1173     w3=wseq.length()-1;
1174     }
1175   char trim_code;
1176 + //clean the more dirty end first - 3'
1177 + int prev_w5=0;
1178 + int prev_w3=0;
1179 + bool w3upd=true;
1180 + bool w5upd=true;
1181   do {
1182    trim_code=0;
1183 <  if (trim_poly5(wseq, w5, w3, polyA_seed)) {
1183 >  if (w3upd && trim_poly3(wseq, w5, w3, polyA_seed)) {
1184        trim_code='A';
1185        }
1186 <  else if (trim_poly5(wseq, w5, w3, polyT_seed)) {
1186 >  else if (w3upd && trim_poly3(wseq, w5, w3, polyT_seed)) {
1187        trim_code='T';
1188        }
1189 <  else if (trim_adapter5(wseq, w5, w3)) {
1132 <      trim_code='5';
1133 <      }
1134 <  if (trim_code) {
1135 <     #ifdef GDEBUG
1136 <      GMessage("#### TRIM by '%c' code ( w5-w3 = %d-%d ):\n",trim_code, w5,w3);
1137 <      showTrim(wseq, w5, w3);
1138 <     #endif
1139 <     int trimlen=wseq.length()-(w3-w5+1);
1140 <     num_trimmed5++;
1141 <     if (trimlen<min_trimmed5)
1142 <         min_trimmed5=trimlen;
1143 <     l5+=w5;
1144 <     l3-=(wseq.length()-1-w3);
1145 <     if (w3-w5+1<min_read_len) {
1146 <         return trim_code;
1147 <         }
1148 <      //-- keep only the w5..w3 range
1149 <      wseq=wseq.substr(w5, w3-w5+1);
1150 <      if (!wqv.is_empty())
1151 <         wqv=wqv.substr(w5, w3-w5+1);
1152 <      }// trimmed at 5' end
1153 < } while (trim_code);
1154 <
1155 < do {
1156 <  trim_code=0;
1157 <  if (trim_poly3(wseq, w5, w3, polyA_seed)) {
1189 >  else if (w5upd && trim_poly5(wseq, w5, w3, polyA_seed)) {
1190        trim_code='A';
1191        }
1192 <  else if (trim_poly3(wseq, w5, w3, polyT_seed)) {
1192 >  else if (w5upd && trim_poly5(wseq, w5, w3, polyT_seed)) {
1193        trim_code='T';
1194        }
1195 <  else if (trim_adapter3(wseq, w5, w3)) {
1195 >  else if (trim_adaptor5(wseq, w5, w3)) {
1196 >      trim_code='5';
1197 >      }
1198 >  else if (trim_adaptor3(wseq, w5, w3)) {
1199        trim_code='3';
1200        }
1201    if (trim_code) {
1202 <     #ifdef GDEBUG
1202 >     w3upd=(w3!=prev_w3);
1203 >         w5upd=(w5!=prev_w5);
1204 >         if (w3upd) prev_w3=w3;
1205 >         if (w5upd) prev_w5=w5;
1206 >   #ifdef GDEBUG
1207       GMessage("#### TRIM by '%c' code ( w5-w3 = %d-%d ):\n",trim_code, w5,w3);
1208       showTrim(wseq, w5, w3);
1209 <     #endif
1209 >   #endif
1210       int trimlen=wseq.length()-(w3-w5+1);
1211       num_trimmed3++;
1212       if (trimlen<min_trimmed3)
# Line 1184 | Line 1223
1223        }//trimming at 3' end
1224   } while (trim_code);
1225  
1187
1226   if (doCollapse) {
1227     //keep read for later
1228     FqDupRec* dr=dhash.Find(wseq.chars());
# Line 1335 | Line 1373
1373      }
1374   }
1375  
1376 < void addAdapter(GVec<CASeqData>& adapters, GStr& seq) {
1376 > void addAdaptor(GVec<CASeqData>& adaptors, GStr& seq, GAlnTrimType trim_type) {
1377   //TODO: prepare CASeqData here, and collect hexamers as well
1378 +  if (seq.is_empty() || seq=="-" ||
1379 +          seq=="N/A" || seq==".") return;
1380 +
1381   CASeqData adata(revCompl);
1382 < int idx=adapters.Add(adata);
1382 > int idx=adaptors.Add(adata);
1383   if (idx<0) GError("Error: failed to add adaptor!\n");
1384 < adapters[idx].update(seq.chars());
1384 > adaptors[idx].trim_type=trim_type;
1385 > adaptors[idx].update(seq.chars());
1386   }
1387  
1388  
1389 < int loadAdapters(const char* fname) {
1389 > int loadAdaptors(const char* fname) {
1390    GLineReader lr(fname);
1391    char* l;
1392    while ((l=lr.nextLine())!=NULL) {
# Line 1360 | Line 1402
1402        #ifdef GDEBUG
1403            //s.reverse();
1404        #endif
1405 <        addAdapter(adapters3, s);
1405 >        addAdaptor(adaptors3, s, galn_TrimRight);
1406          continue;
1407          }
1408        }
# Line 1369 | Line 1411
1411        s.startTokenize("\t ;,:");
1412        GStr a5,a3;
1413        if (s.nextToken(a5))
1414 <         s.nextToken(a3);
1414 >            s.nextToken(a3);
1415 >        else continue; //no tokens on this line
1416 >      GAlnTrimType ttype5=galn_TrimLeft;
1417        a5.upper();
1418        a3.upper();
1419 +      if (a3.is_empty() || a3==a5 || a3=="=") {
1420 +         a3.clear();
1421 +         ttype5=galn_TrimEither;
1422 +         }
1423       #ifdef GDEBUG
1424       //   a5.reverse();
1425       //   a3.reverse();
1426       #endif
1427 <      addAdapter(adapters5, a5);
1428 <      addAdapter(adapters3, a3);
1427 >      addAdaptor(adaptors5, a5, ttype5);
1428 >      addAdaptor(adaptors3, a3, galn_TrimRight);
1429        }
1430     }
1431 <   return adapters5.Count()+adapters3.Count();
1431 >   return adaptors5.Count()+adaptors3.Count();
1432   }
1433  
1434   void setupFiles(FILE*& f_in, FILE*& f_in2, FILE*& f_out, FILE*& f_out2,

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines