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