]> git.donarmstrong.com Git - mothur.git/blob - trimseqscommand.cpp
ca7a927134f1f904401ab017d456ff1f6859a569
[mothur.git] / trimseqscommand.cpp
1 /*
2  *  trimseqscommand.cpp
3  *  Mothur
4  *
5  *  Created by Pat Schloss on 6/6/09.
6  *  Copyright 2009 Patrick D. Schloss. All rights reserved.
7  *
8  */
9
10 #include "trimseqscommand.h"
11
12 //***************************************************************************************************************
13
14 TrimSeqsCommand::TrimSeqsCommand(string option){
15         try {
16                 
17                 abort = false;
18                 
19                 //allow user to run help
20                 if(option == "help") { help(); abort = true; }
21                 
22                 else {
23                         //valid paramters for this command
24                         string AlignArray[] =  {"fasta", "flip", "oligos", "maxambig", "maxhomop", "minlength", "maxlength", "qfile", "qthreshold", "qaverage", "allfiles", "qtrim"};
25                         
26                         vector<string> myArray (AlignArray, AlignArray+(sizeof(AlignArray)/sizeof(string)));
27                         
28                         OptionParser parser(option);
29                         map<string,string> parameters = parser.getParameters();
30                         
31                         ValidParameters validParameter;
32                         
33                         //check to make sure all parameters are valid for command
34                         for (map<string,string>::iterator it = parameters.begin(); it != parameters.end(); it++) { 
35                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
36                         }
37                         
38                         //check for required parameters
39                         fastaFile = validParameter.validFile(parameters, "fasta", true);
40                         if (fastaFile == "not found") { mothurOut("fasta is a required parameter for the screen.seqs command."); mothurOutEndLine(); abort = true; }
41                         else if (fastaFile == "not open") { abort = true; }     
42                 
43                 
44                         //check for optional parameter and set defaults
45                         // ...at some point should added some additional type checking...
46                         string temp;
47                         temp = validParameter.validFile(parameters, "flip", false);
48                         if (temp == "not found"){       flip = 0;       }
49                         else if(isTrue(temp))   {       flip = 1;       }
50                 
51                         temp = validParameter.validFile(parameters, "oligos", true);
52                         if (temp == "not found"){       oligoFile = "";         }
53                         else if(temp == "not open"){    abort = true;   } 
54                         else                                    {       oligoFile = temp;               }
55                         
56                         temp = validParameter.validFile(parameters, "maxambig", false);         if (temp == "not found") { temp = "-1"; }
57                         convert(temp, maxAmbig);  
58
59                         temp = validParameter.validFile(parameters, "maxhomop", false);         if (temp == "not found") { temp = "0"; }
60                         convert(temp, maxHomoP);  
61
62                         temp = validParameter.validFile(parameters, "minlength", false);        if (temp == "not found") { temp = "0"; }
63                         convert(temp, minLength); 
64                         
65                         temp = validParameter.validFile(parameters, "maxlength", false);        if (temp == "not found") { temp = "0"; }
66                         convert(temp, maxLength);
67                         
68                         temp = validParameter.validFile(parameters, "qfile", true);     
69                         if (temp == "not found")        {       qFileName = "";         }
70                         else if(temp == "not open")     {       abort = 0;              }
71                         else                                            {       qFileName = temp;       }
72                         
73                         temp = validParameter.validFile(parameters, "qthreshold", false);       if (temp == "not found") { temp = "0"; }
74                         convert(temp, qThreshold);
75                         
76                         temp = validParameter.validFile(parameters, "qtrim", false);    if (temp == "not found") { temp = "F"; }
77                         qtrim = isTrue(temp);
78
79                         temp = validParameter.validFile(parameters, "qaverage", false);         if (temp == "not found") { temp = "0"; }
80                         convert(temp, qAverage);
81                         
82                         temp = validParameter.validFile(parameters, "allfiles", false);         if (temp == "not found") { temp = "F"; }
83                         allFiles = isTrue(temp);
84                         
85                         if(allFiles && oligoFile == ""){
86                                 mothurOut("You selected allfiles, but didn't enter an oligos file.  Ignoring the allfiles request."); mothurOutEndLine();
87                         }
88                         if((qAverage != 0 && qThreshold != 0) && qFileName == ""){
89                                 mothurOut("You didn't provide a quality file name, quality criteria will be ignored."); mothurOutEndLine();
90                                 qAverage=0;
91                                 qThreshold=0;
92                         }
93                         if(!flip && oligoFile=="" && !maxLength && !minLength && (maxAmbig==-1) && !maxHomoP && qFileName == ""){               
94                                 mothurOut("You didn't set any options... quiting command."); mothurOutEndLine();
95                                 abort = true;
96                         }
97                 }
98
99         }
100         catch(exception& e) {
101                 errorOut(e, "TrimSeqsCommand", "TrimSeqsCommand");
102                 exit(1);
103         }
104 }
105 //**********************************************************************************************************************
106
107 void TrimSeqsCommand::help(){
108         try {
109                 mothurOut("The trim.seqs command reads a fastaFile and creates .....\n");
110                 mothurOut("The trim.seqs command parameters are fasta, flip, oligos, maxambig, maxhomop, minlength, maxlength, qfile, qthreshold, qaverage, qtrim and allfiles.\n");
111                 mothurOut("The fasta parameter is required.\n");
112                 mothurOut("The flip parameter .... The default is 0.\n");
113                 mothurOut("The oligos parameter .... The default is "".\n");
114                 mothurOut("The maxambig parameter .... The default is -1.\n");
115                 mothurOut("The maxhomop parameter .... The default is 0.\n");
116                 mothurOut("The minlength parameter .... The default is 0.\n");
117                 mothurOut("The maxlength parameter .... The default is 0.\n");
118                 mothurOut("The qfile parameter .....\n");
119                 mothurOut("The qthreshold parameter .... The default is 0.\n");
120                 mothurOut("The qaverage parameter .... The default is 0.\n");
121                 mothurOut("The allfiles parameter .... The default is F.\n");
122                 mothurOut("The qtrim parameter .... The default is F.\n");
123                 mothurOut("The trim.seqs command should be in the following format: \n");
124                 mothurOut("trim.seqs(fasta=yourFastaFile, flip=yourFlip, oligos=yourOligos, maxambig=yourMaxambig,  \n");
125                 mothurOut("maxhomop=yourMaxhomop, minlength=youMinlength, maxlength=yourMaxlength)  \n");       
126                 mothurOut("Example trim.seqs(fasta=abrecovery.fasta, flip=..., oligos=..., maxambig=..., maxhomop=..., minlength=..., maxlength=...).\n");
127                 mothurOut("Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFasta).\n");
128                 mothurOut("For more details please check out the wiki http://www.mothur.org/wiki/Trim.seqs .\n\n");
129
130         }
131         catch(exception& e) {
132                 errorOut(e, "TrimSeqsCommand", "help");
133                 exit(1);
134         }
135 }
136
137
138 //***************************************************************************************************************
139
140 TrimSeqsCommand::~TrimSeqsCommand(){    /*      do nothing      */      }
141
142 //***************************************************************************************************************
143
144 int TrimSeqsCommand::execute(){
145         try{
146         
147                 if (abort == true) { return 0; }
148
149                 ifstream inFASTA;
150                 openInputFile(fastaFile, inFASTA);
151                 
152                 ofstream outFASTA;
153                 string trimSeqFile = getRootName(fastaFile) + "trim.fasta";
154                 openOutputFile(trimSeqFile, outFASTA);
155                 
156                 ofstream outGroups;
157                 vector<ofstream*> fastaFileNames;
158                 if(oligoFile != ""){
159                         string groupFile = getRootName(fastaFile) + "groups"; 
160                         openOutputFile(groupFile, outGroups);
161                         getOligos(fastaFileNames);
162                 }
163                 
164                 ofstream scrapFASTA;
165                 string scrapSeqFile = getRootName(fastaFile) + "scrap.fasta";
166                 openOutputFile(scrapSeqFile, scrapFASTA);
167                 
168                 ifstream qFile;
169                 if(qFileName != "")     {       openInputFile(qFileName, qFile);        }
170                 
171                 bool success;
172                         
173                 while(!inFASTA.eof()){
174                         Sequence currSeq(inFASTA);
175                         string origSeq = currSeq.getUnaligned();
176                         if (origSeq != "") {
177                                 int group;
178                                 string trashCode = "";
179                                 
180                                 if(qFileName != ""){
181                                         if(qThreshold != 0)             {       success = stripQualThreshold(currSeq, qFile);   }
182                                         else if(qAverage != 0)  {       success = cullQualAverage(currSeq, qFile);              }
183                                         if ((!qtrim) && (origSeq.length() != currSeq.getUnaligned().length())) { 
184                                                 success = 0; //if you don't want to trim and the sequence does not meet quality requirements, move to scrap
185                                         }
186                                         if(!success)                    {       trashCode += 'q';                                                               }
187                                 }
188                                 if(barcodes.size() != 0){
189                                         
190                                         success = stripBarcode(currSeq, group);
191                                         if(!success){   trashCode += 'b';       }
192                                 }
193                                 if(numFPrimers != 0){
194                                         success = stripForward(currSeq);
195                                         if(!success){   trashCode += 'f';       }
196                                 }
197                                 if(numRPrimers != 0){
198                                         success = stripReverse(currSeq);
199                                         if(!success){   trashCode += 'r';       }
200                                 }
201                                 if(minLength > 0 || maxLength > 0){
202                                         success = cullLength(currSeq);
203                                         if ((currSeq.getUnaligned().length() > 300) && (success)) {  cout << "too long " << currSeq.getUnaligned().length() << endl;  }
204                                         if(!success){   trashCode += 'l'; }
205                                 }
206                                 if(maxHomoP > 0){
207                                         success = cullHomoP(currSeq);
208                                         if(!success){   trashCode += 'h';       }
209                                 }
210                                 if(maxAmbig != -1){
211                                         success = cullAmbigs(currSeq);
212                                         if(!success){   trashCode += 'n';       }
213                                 }
214                                 
215                                 if(flip){       currSeq.reverseComplement();    }               // should go last                       
216                                 
217                                 if(trashCode.length() == 0){
218                                         currSeq.setAligned(currSeq.getUnaligned());  //this is because of a modification we made to the sequence class to fix a bug.  all seqs have an aligned version, which is the version that gets printed.
219                                         currSeq.printSequence(outFASTA);
220                                         if(barcodes.size() != 0){
221                                                 outGroups << currSeq.getName() << '\t' << groupVector[group] << endl;
222                                                 
223                                                 if(allFiles){
224                                                         currSeq.printSequence(*fastaFileNames[group]);                                  
225                                                 }
226                                         }
227                                 }
228                                 else{
229                                         currSeq.setName(currSeq.getName() + '|' + trashCode);
230                                         currSeq.setUnaligned(origSeq);
231                                         currSeq.printSequence(scrapFASTA);
232                                 }
233                         }
234                         gobble(inFASTA);
235                 }
236                 inFASTA.close();
237                 outFASTA.close();
238                 scrapFASTA.close();
239                 outGroups.close();
240                 if(qFileName != "")     {       qFile.close();  }
241                 
242                 for(int i=0;i<fastaFileNames.size();i++){
243                         fastaFileNames[i]->close();
244                         delete fastaFileNames[i];
245                 }               
246                 
247                 for(int i=0;i<fastaFileNames.size();i++){
248                         string seqName;
249                         openInputFile(getRootName(fastaFile) + groupVector[i] + ".fasta", inFASTA);
250                         ofstream outGroups;
251                         openOutputFile(getRootName(fastaFile) + groupVector[i] + ".groups", outGroups);
252                         
253                         while(!inFASTA.eof()){
254                                 if(inFASTA.get() == '>'){
255                                         inFASTA >> seqName;
256                                         outGroups << seqName << '\t' << groupVector[i] << endl;
257                                 }
258                                 while (!inFASTA.eof())  {       char c = inFASTA.get(); if (c == 10 || c == 13){        break;  }       }
259                         }
260                         outGroups.close();
261                         inFASTA.close();
262                 }
263                 
264                 
265                 return 0;               
266         }
267         catch(exception& e) {
268                 errorOut(e, "TrimSeqsCommand", "execute");
269                 exit(1);
270         }
271 }
272
273 //***************************************************************************************************************
274
275 void TrimSeqsCommand::getOligos(vector<ofstream*>& outFASTAVec){
276         try {
277                 ifstream inOligos;
278                 openInputFile(oligoFile, inOligos);
279                 
280                 ofstream test;
281                 
282                 string type, oligo, group;
283                 int index=0;
284                 
285                 while(!inOligos.eof()){
286                         inOligos >> type;
287                         
288                         if(type[0] == '#'){
289                                 while (!inOligos.eof()) {       char c = inOligos.get(); if (c == 10 || c == 13){       break;  }       } // get rest of line if there's any crap there
290                         }
291                         else{
292                                 inOligos >> oligo;
293                                 
294                                 for(int i=0;i<oligo.length();i++){
295                                         oligo[i] = toupper(oligo[i]);
296                                         if(oligo[i] == 'U')     {       oligo[i] = 'T'; }
297                                 }
298                                 
299                                 if(type == "forward"){
300                                         forPrimer.push_back(oligo);
301                                 }
302                                 else if(type == "reverse"){
303                                         revPrimer.push_back(oligo);
304                                 }
305                                 else if(type == "barcode"){
306                                         inOligos >> group;
307                                         barcodes[oligo]=index++;
308                                         groupVector.push_back(group);
309                                         
310                                         if(allFiles){
311                                                 outFASTAVec.push_back(new ofstream((getRootName(fastaFile) + group + ".fasta").c_str(), ios::ate));
312                                         }
313                                 }
314                         }
315                 }
316                 
317                 inOligos.close();
318                 
319                 numFPrimers = forPrimer.size();
320                 numRPrimers = revPrimer.size();
321                 
322         }
323         catch(exception& e) {
324                 errorOut(e, "TrimSeqsCommand", "getOligos");
325                 exit(1);
326         }
327
328 }
329
330 //***************************************************************************************************************
331
332 bool TrimSeqsCommand::stripBarcode(Sequence& seq, int& group){
333         try {
334                 string rawSequence = seq.getUnaligned();
335                 bool success = 0;       //guilty until proven innocent
336                 
337                 for(map<string,int>::iterator it=barcodes.begin();it!=barcodes.end();it++){
338                         string oligo = it->first;
339                         if(rawSequence.length() < oligo.length()){      //let's just assume that the barcodes are the same length
340                                 success = 0;
341                                 break;
342                         }
343                         
344                         if(compareDNASeq(oligo, rawSequence.substr(0,oligo.length()))){
345                                 group = it->second;
346                                 seq.setUnaligned(rawSequence.substr(oligo.length()));
347                                 success = 1;
348                                 break;
349                         }
350                 }
351                 return success;
352                 
353         }
354         catch(exception& e) {
355                 errorOut(e, "TrimSeqsCommand", "stripBarcode");
356                 exit(1);
357         }
358
359 }
360
361 //***************************************************************************************************************
362
363 bool TrimSeqsCommand::stripForward(Sequence& seq){
364         try {
365                 string rawSequence = seq.getUnaligned();
366                 bool success = 0;       //guilty until proven innocent
367                 
368                 for(int i=0;i<numFPrimers;i++){
369                         string oligo = forPrimer[i];
370                         
371                         if(rawSequence.length() < oligo.length()){
372                                 success = 0;
373                                 break;
374                         }
375                         
376                         if(compareDNASeq(oligo, rawSequence.substr(0,oligo.length()))){
377                                 seq.setUnaligned(rawSequence.substr(oligo.length()));
378                                 success = 1;
379                                 break;
380                         }
381                 }
382                 
383                 return success;
384                 
385         }
386         catch(exception& e) {
387                 errorOut(e, "TrimSeqsCommand", "stripForward");
388                 exit(1);
389         }
390 }
391
392 //***************************************************************************************************************
393
394 bool TrimSeqsCommand::stripReverse(Sequence& seq){
395         try {
396                 string rawSequence = seq.getUnaligned();
397                 bool success = 0;       //guilty until proven innocent
398                 
399                 for(int i=0;i<numRPrimers;i++){
400                         string oligo = revPrimer[i];
401                         
402                         if(rawSequence.length() < oligo.length()){
403                                 success = 0;
404                                 break;
405                         }
406                         
407                         if(compareDNASeq(oligo, rawSequence.substr(rawSequence.length()-oligo.length(),oligo.length()))){
408                                 seq.setUnaligned(rawSequence.substr(rawSequence.length()-oligo.length()));
409                                 success = 1;
410                                 break;
411                         }
412                 }       
413                 return success;
414                 
415         }
416         catch(exception& e) {
417                 errorOut(e, "TrimSeqsCommand", "stripReverse");
418                 exit(1);
419         }
420 }
421
422 //***************************************************************************************************************
423
424 bool TrimSeqsCommand::cullLength(Sequence& seq){
425         try {
426         
427                 int length = seq.getNumBases();
428                 bool success = 0;       //guilty until proven innocent
429                 
430                 if(length >= minLength && maxLength == 0)                       {       success = 1;    }
431                 else if(length >= minLength && length <= maxLength)     {       success = 1;    }
432                 else                                                                                            {       success = 0;    }
433                 
434                 return success;
435         
436         }
437         catch(exception& e) {
438                 errorOut(e, "TrimSeqsCommand", "cullLength");
439                 exit(1);
440         }
441         
442 }
443
444 //***************************************************************************************************************
445
446 bool TrimSeqsCommand::cullHomoP(Sequence& seq){
447         try {
448                 int longHomoP = seq.getLongHomoPolymer();
449                 bool success = 0;       //guilty until proven innocent
450                 
451                 if(longHomoP <= maxHomoP){      success = 1;    }
452                 else                                    {       success = 0;    }
453                 
454                 return success;
455         }
456         catch(exception& e) {
457                 errorOut(e, "TrimSeqsCommand", "cullHomoP");
458                 exit(1);
459         }
460         
461 }
462
463 //***************************************************************************************************************
464
465 bool TrimSeqsCommand::cullAmbigs(Sequence& seq){
466         try {
467                 int numNs = seq.getAmbigBases();
468                 bool success = 0;       //guilty until proven innocent
469                 
470                 if(numNs <= maxAmbig)   {       success = 1;    }
471                 else                                    {       success = 0;    }
472                 
473                 return success;
474         }
475         catch(exception& e) {
476                 errorOut(e, "TrimSeqsCommand", "cullAmbigs");
477                 exit(1);
478         }
479         
480 }
481
482 //***************************************************************************************************************
483
484 bool TrimSeqsCommand::compareDNASeq(string oligo, string seq){
485         try {
486                 bool success = 1;
487                 int length = oligo.length();
488                 
489                 for(int i=0;i<length;i++){
490                         
491                         if(oligo[i] != seq[i]){
492                                 if(oligo[i] == 'A' || oligo[i] == 'T' || oligo[i] == 'G' || oligo[i] == 'C')    {       success = 0;    }
493                                 else if((oligo[i] == 'N' || oligo[i] == 'I') && (seq[i] == 'N'))                                {       success = 0;    }
494                                 else if(oligo[i] == 'R' && (seq[i] != 'A' && seq[i] != 'G'))                                    {       success = 0;    }
495                                 else if(oligo[i] == 'Y' && (seq[i] != 'C' && seq[i] != 'T'))                                    {       success = 0;    }
496                                 else if(oligo[i] == 'M' && (seq[i] != 'C' && seq[i] != 'A'))                                    {       success = 0;    }
497                                 else if(oligo[i] == 'K' && (seq[i] != 'T' && seq[i] != 'G'))                                    {       success = 0;    }
498                                 else if(oligo[i] == 'W' && (seq[i] != 'T' && seq[i] != 'A'))                                    {       success = 0;    }
499                                 else if(oligo[i] == 'S' && (seq[i] != 'C' && seq[i] != 'G'))                                    {       success = 0;    }
500                                 else if(oligo[i] == 'B' && (seq[i] != 'C' && seq[i] != 'T' && seq[i] != 'G'))   {       success = 0;    }
501                                 else if(oligo[i] == 'D' && (seq[i] != 'A' && seq[i] != 'T' && seq[i] != 'G'))   {       success = 0;    }
502                                 else if(oligo[i] == 'H' && (seq[i] != 'A' && seq[i] != 'T' && seq[i] != 'C'))   {       success = 0;    }
503                                 else if(oligo[i] == 'V' && (seq[i] != 'A' && seq[i] != 'C' && seq[i] != 'G'))   {       success = 0;    }                       
504                                 
505                                 if(success == 0)        {       break;  }
506                         }
507                         else{
508                                 success = 1;
509                         }
510                 }
511                 
512                 return success;
513         }
514         catch(exception& e) {
515                 errorOut(e, "TrimSeqsCommand", "compareDNASeq");
516                 exit(1);
517         }
518
519 }
520
521 //***************************************************************************************************************
522
523 bool TrimSeqsCommand::stripQualThreshold(Sequence& seq, ifstream& qFile){
524         try {
525                 string rawSequence = seq.getUnaligned();
526                 int seqLength = rawSequence.length();
527                 string name;
528                 
529                 qFile >> name;
530                 if (name.length() != 0) {  if(name.substr(1) != seq.getName())  {       mothurOut("sequence name mismatch btwn fasta and qual file"); mothurOutEndLine();       }  } 
531                 while (!qFile.eof())    {       char c = qFile.get(); if (c == 10 || c == 13){  break;  }       }
532                 
533                 int score;
534                 int end = seqLength;
535                 
536                 for(int i=0;i<seqLength;i++){
537                         qFile >> score;
538                         
539                         if(score <= qThreshold){
540                                 end = i;
541                                 break;
542                         }
543                 }
544                 for(int i=end+1;i<seqLength;i++){
545                         qFile >> score;
546                 }
547                 
548                 seq.setUnaligned(rawSequence.substr(0,end));
549                 
550                 return 1;
551         }
552         catch(exception& e) {
553                 errorOut(e, "TrimSeqsCommand", "stripQualThreshold");
554                 exit(1);
555         }
556 }
557
558 //***************************************************************************************************************
559
560 bool TrimSeqsCommand::cullQualAverage(Sequence& seq, ifstream& qFile){
561         try {
562                 string rawSequence = seq.getUnaligned();
563                 int seqLength = seq.getNumBases();
564                 bool success = 0;       //guilty until proven innocent
565                 string name;
566                 
567                 qFile >> name;
568                 if (name[0] == '>') {  if(name.substr(1) != seq.getName())      {       mothurOut("sequence name mismatch btwn fasta: " + seq.getName() + " and qual file: " + name); mothurOutEndLine();       } }
569                 
570                 while (!qFile.eof())    {       char c = qFile.get(); if (c == 10 || c == 13){  break;  }       }
571                 
572                 float score;    
573                 float average = 0;
574                 
575                 for(int i=0;i<seqLength;i++){
576                         qFile >> score;
577                         average += score;
578                 }
579                 average /= seqLength;
580
581                 if(average >= qAverage) {       success = 1;    }
582                 else                                    {       success = 0;    }
583                 
584                 return success;
585         }
586         catch(exception& e) {
587                 errorOut(e, "TrimSeqsCommand", "cullQualAverage");
588                 exit(1);
589         }
590 }
591
592 //***************************************************************************************************************