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