]> git.donarmstrong.com Git - mothur.git/blob - trimflowscommand.cpp
changes to trim.flows command
[mothur.git] / trimflowscommand.cpp
1 /*
2  *  trimflowscommand.cpp
3  *  Mothur
4  *
5  *  Created by Pat Schloss on 12/22/10.
6  *  Copyright 2010 Schloss Lab. All rights reserved.
7  *
8  */
9
10 #include "trimflowscommand.h"
11 #include "needlemanoverlap.hpp"
12
13 //**********************************************************************************************************************
14
15 vector<string> TrimFlowsCommand::getValidParameters(){  
16         try {
17                 string Array[] =  {"flow", "maxflows", "minflows",
18                         "fasta", "minlength", "maxlength", "maxhomop", "signal", "noise"
19                         "oligos", "pdiffs", "bdiffs", "tdiffs", 
20                         "allfiles", "processors",
21                         "outputdir","inputdir"
22                 
23                 };
24                 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
25                 return myArray;
26         }
27         catch(exception& e) {
28                 m->errorOut(e, "TrimFlowsCommand", "getValidParameters");
29                 exit(1);
30         }
31 }
32
33 //**********************************************************************************************************************
34
35 vector<string> TrimFlowsCommand::getRequiredParameters(){       
36         try {
37                 string Array[] =  {"flow"};
38                 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
39                 return myArray;
40         }
41         catch(exception& e) {
42                 m->errorOut(e, "TrimFlowsCommand", "getRequiredParameters");
43                 exit(1);
44         }
45 }
46
47 //**********************************************************************************************************************
48
49 vector<string> TrimFlowsCommand::getRequiredFiles(){    
50         try {
51                 vector<string> myArray;
52                 return myArray;
53         }
54         catch(exception& e) {
55                 m->errorOut(e, "TrimFlowsCommand", "getRequiredFiles");
56                 exit(1);
57         }
58 }
59
60 //**********************************************************************************************************************
61
62 TrimFlowsCommand::TrimFlowsCommand(){   
63         try {
64                 abort = true; calledHelp = true; 
65                 vector<string> tempOutNames;
66                 outputTypes["flow"] = tempOutNames;
67                 outputTypes["fasta"] = tempOutNames;
68         }
69         catch(exception& e) {
70                 m->errorOut(e, "TrimFlowsCommand", "TrimFlowsCommand");
71                 exit(1);
72         }
73 }
74
75 //***************************************************************************************************************
76
77 TrimFlowsCommand::~TrimFlowsCommand(){  /*      do nothing      */      }
78
79 //***************************************************************************************************************
80
81 void TrimFlowsCommand::help(){
82         try {
83                 m->mothurOut("The trim.flows command reads a flowgram file and creates .....\n");
84                 m->mothurOut("Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFasta).\n");
85                 m->mothurOut("For more details please check out the wiki http://www.mothur.org/wiki/Trim.flows.\n\n");
86                 
87         }
88         catch(exception& e) {
89                 m->errorOut(e, "TrimFlowsCommand", "help");
90                 exit(1);
91         }
92 }
93
94 //**********************************************************************************************************************
95
96 TrimFlowsCommand::TrimFlowsCommand(string option)  {
97         try {
98                 
99                 abort = false; calledHelp = false;   
100                 comboStarts = 0;
101                 
102                 //allow user to run help
103                 if(option == "help") { help(); abort = true; calledHelp = true; }
104                 
105                 else {
106                         //valid paramters for this command
107                         string AlignArray[] =  {"flow", "maxflows", "minflows",
108                                 "fasta", "minlength", "maxlength", "maxhomop", "signal", "noise",
109                                 "oligos", "pdiffs", "bdiffs", "tdiffs", 
110                                 "allfiles", "processors",
111                 
112                                 //                      "group",
113                                 "outputdir","inputdir"
114                                 
115                         };
116                         
117                         vector<string> myArray (AlignArray, AlignArray+(sizeof(AlignArray)/sizeof(string)));
118                         
119                         OptionParser parser(option);
120                         map<string,string> parameters = parser.getParameters();
121                         
122                         ValidParameters validParameter;
123                         map<string,string>::iterator it;
124                         
125                         //check to make sure all parameters are valid for command
126                         for (it = parameters.begin(); it != parameters.end(); it++) { 
127                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
128                         }
129                         
130                         //initialize outputTypes
131                         vector<string> tempOutNames;
132                         outputTypes["flow"] = tempOutNames;
133                         outputTypes["fasta"] = tempOutNames;
134                         
135                         //if the user changes the input directory command factory will send this info to us in the output parameter 
136                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
137                         if (inputDir == "not found"){   inputDir = "";          }
138                         else {
139                                 string path;
140                                 it = parameters.find("flow");
141                                 //user has given a template file
142                                 if(it != parameters.end()){ 
143                                         path = m->hasPath(it->second);
144                                         //if the user has not given a path then, add inputdir. else leave path alone.
145                                         if (path == "") {       parameters["flow"] = inputDir + it->second;             }
146                                 }
147                                 
148                                 it = parameters.find("oligos");
149                                 //user has given a template file
150                                 if(it != parameters.end()){ 
151                                         path = m->hasPath(it->second);
152                                         //if the user has not given a path then, add inputdir. else leave path alone.
153                                         if (path == "") {       parameters["oligos"] = inputDir + it->second;           }
154                                 }
155                                 
156                                 
157 //                              it = parameters.find("group");
158 //                              //user has given a template file
159 //                              if(it != parameters.end()){ 
160 //                                      path = m->hasPath(it->second);
161 //                                      //if the user has not given a path then, add inputdir. else leave path alone.
162 //                                      if (path == "") {       parameters["group"] = inputDir + it->second;            }
163 //                              }
164                         }
165                         
166                         
167                         //check for required parameters
168                         flowFileName = validParameter.validFile(parameters, "flow", true);
169                         if (flowFileName == "not found") { m->mothurOut("flow is a required parameter for the trim.flows command."); m->mothurOutEndLine(); abort = true; }
170                         else if (flowFileName == "not open") { abort = true; }  
171                         
172                         //if the user changes the output directory command factory will send this info to us in the output parameter 
173                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  
174                                 outputDir = ""; 
175                                 outputDir += m->hasPath(flowFileName); //if user entered a file with a path then preserve it    
176                         }
177                         
178                         
179                         //check for optional parameter and set defaults
180                         // ...at some point should added some additional type checking...
181                         
182                         string temp;
183                         temp = validParameter.validFile(parameters, "minflows", false); if (temp == "not found") { temp = "360"; }
184                         convert(temp, minFlows);  
185
186                         temp = validParameter.validFile(parameters, "maxflows", false); if (temp == "not found") { temp = "720"; }
187                         convert(temp, maxFlows);  
188                         
189                         
190                         temp = validParameter.validFile(parameters, "oligos", true);
191                         if (temp == "not found")        {       oligoFileName = "";             }
192                         else if(temp == "not open")     {       abort = true;                   } 
193                         else                                            {       oligoFileName = temp;   }
194                         
195                         temp = validParameter.validFile(parameters, "fasta", false);            if (temp == "not found"){       fasta = 0;              }
196                         else if(m->isTrue(temp))        {       fasta = 1;      }
197                         
198                         temp = validParameter.validFile(parameters, "maxhomop", false);         if (temp == "not found"){       temp = "9";             }
199                         convert(temp, maxHomoP);  
200
201                         temp = validParameter.validFile(parameters, "signal", false);           if (temp == "not found"){       temp = "0.50";  }
202                         convert(temp, signal);  
203
204                         temp = validParameter.validFile(parameters, "noise", false);            if (temp == "not found"){       temp = "0.70";  }
205                         convert(temp, noise);  
206
207                         temp = validParameter.validFile(parameters, "minlength", false);        if (temp == "not found"){       temp = "0";             }
208                         convert(temp, minLength); 
209                         
210                         temp = validParameter.validFile(parameters, "maxlength", false);        if (temp == "not found"){       temp = "0";             }
211                         convert(temp, maxLength);
212                         
213                         temp = validParameter.validFile(parameters, "bdiffs", false);           if (temp == "not found"){       temp = "0";             }
214                         convert(temp, bdiffs);
215                         
216                         temp = validParameter.validFile(parameters, "pdiffs", false);           if (temp == "not found"){       temp = "0";             }
217                         convert(temp, pdiffs);
218                         
219                         temp = validParameter.validFile(parameters, "tdiffs", false);
220                         if (temp == "not found"){ int tempTotal = pdiffs + bdiffs;  temp = toString(tempTotal); }
221                         convert(temp, tdiffs);
222                         if(tdiffs == 0){        tdiffs = bdiffs + pdiffs;       }
223                         
224                         temp = validParameter.validFile(parameters, "allfiles", false);         if (temp == "not found") { temp = "T";          }
225                         allFiles = m->isTrue(temp);
226                         
227                         temp = validParameter.validFile(parameters, "processors", false);       if (temp == "not found") { temp = "1"; }
228                         convert(temp, processors); 
229                         
230                         if(oligoFileName == ""){        allFiles = 0;           }
231
232                         numFPrimers = 0;
233                         numRPrimers = 0;
234                 }
235                 
236         }
237         catch(exception& e) {
238                 m->errorOut(e, "TrimFlowsCommand", "TrimSeqsCommand");
239                 exit(1);
240         }
241 }
242
243 //***************************************************************************************************************
244
245 int TrimFlowsCommand::execute(){
246         try{
247                 
248                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
249
250                 string trimFlowFileName = outputDir + m->getRootName(m->getSimpleName(flowFileName)) + "trim.flow";
251                 outputNames.push_back(trimFlowFileName); outputTypes["flow"].push_back(trimFlowFileName);
252                 
253                 string scrapFlowFileName = outputDir + m->getRootName(m->getSimpleName(flowFileName)) + "scrap.flow";
254                 outputNames.push_back(scrapFlowFileName); outputTypes["flow"].push_back(scrapFlowFileName);
255
256                 string fastaFileName = outputDir + m->getRootName(m->getSimpleName(flowFileName)) + "flow.fasta";
257                 if(fasta){
258                         outputNames.push_back(fastaFileName); outputTypes["fasta"].push_back(fastaFileName);
259                 }
260                 
261                 vector<unsigned long int> flowFilePos = getFlowFileBreaks();
262                 for (int i = 0; i < (flowFilePos.size()-1); i++) {
263                         lines.push_back(new linePair(flowFilePos[i], flowFilePos[(i+1)]));
264                 }       
265
266                 vector<vector<string> > barcodePrimerComboFileNames;
267                 if(oligoFileName != ""){
268                         getOligos(barcodePrimerComboFileNames); 
269                 }
270                 
271 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
272                 if(processors == 1){
273                         driverCreateTrim(flowFileName, trimFlowFileName, scrapFlowFileName, fastaFileName, barcodePrimerComboFileNames, lines[0]);
274                 }else{
275                         createProcessesCreateTrim(flowFileName, trimFlowFileName, scrapFlowFileName, fastaFileName, barcodePrimerComboFileNames); 
276                 }       
277 #else
278                 driverCreateTrim(flowFileName, trimFlowFileName, scrapFlowFileName, fastaFileName, barcodePrimerComboFileNames, lines[0]);
279 #endif
280                 
281                 if (m->control_pressed) {  return 0; }                  
282                 
283                 string flowFilesFileName;
284                 ofstream output;
285                 
286                 if(allFiles){
287                         
288                         flowFilesFileName = outputDir + m->getRootName(m->getSimpleName(flowFileName)) + "flow.files";
289                         m->openOutputFile(flowFilesFileName, output);
290
291                         for(int i=0;i<barcodePrimerComboFileNames.size();i++){
292                                 for(int j=0;j<barcodePrimerComboFileNames[0].size();j++){
293                                         
294                                         FILE * pFile;
295                                         unsigned long int size;
296                                         
297                                         //get num bytes in file
298                                         pFile = fopen (barcodePrimerComboFileNames[i][j].c_str(),"rb");
299                                         if (pFile==NULL) perror ("Error opening file");
300                                         else{
301                                                 fseek (pFile, 0, SEEK_END);
302                                                 size=ftell (pFile);
303                                                 fclose (pFile);
304                                         }
305
306                                         if(size < 10){
307                                                 remove(barcodePrimerComboFileNames[i][j].c_str());
308                                         }
309                                         else{
310                                                 output << barcodePrimerComboFileNames[i][j] << endl;
311                                         }
312                                 }
313                         }
314                         output.close();
315                 }
316                 else{
317                         flowFilesFileName = outputDir + m->getRootName(m->getSimpleName(flowFileName)) + "flow.files";
318                         m->openOutputFile(flowFilesFileName, output);
319                         
320                         output << trimFlowFileName << endl;
321                         
322                         output.close();
323                 }
324                 outputTypes["flow.files"].push_back(flowFilesFileName);
325                 
326                 m->mothurOutEndLine();
327                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
328                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }
329                 m->mothurOutEndLine();
330                 
331                 return 0;       
332         }
333         catch(exception& e) {
334                 m->errorOut(e, "TrimSeqsCommand", "execute");
335                 exit(1);
336         }
337 }
338
339 //***************************************************************************************************************
340
341 int TrimFlowsCommand::driverCreateTrim(string flowFileName, string trimFlowFileName, string scrapFlowFileName, string fastaFileName, vector<vector<string> > barcodePrimerComboFileNames, linePair* line){
342         
343         try {
344                 
345                 ofstream trimFlowFile;
346                 m->openOutputFile(trimFlowFileName, trimFlowFile);
347                 trimFlowFile.setf(ios::fixed, ios::floatfield); trimFlowFile.setf(ios::showpoint);
348
349                 ofstream scrapFlowFile;
350                 m->openOutputFile(scrapFlowFileName, scrapFlowFile);
351                 scrapFlowFile.setf(ios::fixed, ios::floatfield); scrapFlowFile.setf(ios::showpoint);
352
353                 if(line->start == 4){
354                         scrapFlowFile << maxFlows << endl;
355                         trimFlowFile << maxFlows << endl;
356                         if(allFiles){
357                                 for(int i=0;i<barcodePrimerComboFileNames.size();i++){
358                                         for(int j=0;j<barcodePrimerComboFileNames[0].size();j++){
359                                                 //                              barcodePrimerComboFileNames[i][j] += toString(getpid()) + ".temp";
360                                                 ofstream temp;
361                                                 m->openOutputFile(barcodePrimerComboFileNames[i][j], temp);
362                                                 temp << maxFlows << endl;
363                                                 temp.close();
364                                         }
365                                 }                       
366                         }
367                 }
368                 
369                 FlowData flowData(numFlows, signal, noise, maxHomoP);
370                 
371                 ofstream fastaFile;
372                 if(fasta){      m->openOutputFile(fastaFileName, fastaFile);    }
373                 
374                 ifstream flowFile;
375                 m->openInputFile(flowFileName, flowFile);
376                 
377                 flowFile.seekg(line->start);
378
379                 int count = 0;
380                 bool moreSeqs = 1;
381                         
382                 while(moreSeqs) {
383                         
384                         int success = 1;
385                         int currentSeqDiffs = 0;
386                         string trashCode = "";
387                         
388                         flowData.getNext(flowFile);
389                         flowData.capFlows(maxFlows);    
390                         
391                         Sequence currSeq = flowData.getSequence();
392                         if(!flowData.hasMinFlows(minFlows)){    //screen to see if sequence is of a minimum number of flows
393                                 success = 0;
394                                 trashCode += 'l';
395                         }
396                         
397                         if(minLength > 0 || maxLength > 0){     //screen to see if sequence is above and below a specific number of bases
398                                 int seqLength = currSeq.getNumBases();
399                                 if(seqLength < minLength || seqLength > maxLength){
400                                         success = 0;
401                                         trashCode += 'l';
402                                 }
403                         }
404                         
405                         int primerIndex = 0;
406                         int barcodeIndex = 0;
407                         
408                         if(barcodes.size() != 0){
409                                 success = stripBarcode(currSeq, barcodeIndex);
410                                 if(success > bdiffs)            {       trashCode += 'b';       }
411                                 else{ currentSeqDiffs += success;  }
412                         }
413                         
414                         if(numFPrimers != 0){
415                                 success = stripForward(currSeq, primerIndex);
416                                 if(success > pdiffs)            {       trashCode += 'f';       }
417                                 else{ currentSeqDiffs += success;  }
418                         }
419                         
420                         if (currentSeqDiffs > tdiffs)   {       trashCode += 't';   }
421                         
422                         if(numRPrimers != 0){
423                                 success = stripReverse(currSeq);
424                                 if(!success)                            {       trashCode += 'r';       }
425                         }
426
427                         if(trashCode.length() == 0){
428                                                         
429                                 flowData.printFlows(trimFlowFile);
430                         
431                                 if(fasta)       {       currSeq.printSequence(fastaFile);       }
432                                 
433                                 if(allFiles){
434 //                                      string fileName = outputDir + m->getRootName(m->getSimpleName(flowFileName)) + barcodePrimerCombos[barcodeIndex][primerIndex] + ".flow";
435                                         ofstream output;
436                                         m->openOutputFileAppend(barcodePrimerComboFileNames[barcodeIndex][primerIndex], output);
437                                         output.setf(ios::fixed, ios::floatfield); trimFlowFile.setf(ios::showpoint);
438                                         
439                                         flowData.printFlows(output);
440                                         output.close();
441                                 }
442                                 
443                         }
444                         else{
445                                 flowData.printFlows(scrapFlowFile, trashCode);
446                         }
447                                 
448                         count++;
449                                                 
450                         //report progress
451                         if((count) % 10000 == 0){       m->mothurOut(toString(count)); m->mothurOutEndLine();           }
452
453 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
454                         unsigned long int pos = flowFile.tellg();
455
456                         if ((pos == -1) || (pos >= line->end)) { break; }
457 #else
458                         if (flowFile.eof()) { break; }
459 #endif
460                         
461                 }
462                 //report progress
463                 if((count) % 10000 != 0){       m->mothurOut(toString(count)); m->mothurOutEndLine();           }
464                 
465                 trimFlowFile.close();
466                 scrapFlowFile.close();
467                 flowFile.close();
468                 if(fasta){      fastaFile.close();      }
469                 
470                 return count;
471         }
472         catch(exception& e) {
473                 m->errorOut(e, "TrimSeqsCommand", "driverCreateTrim");
474                 exit(1);
475         }
476 }
477
478 //***************************************************************************************************************
479
480 void TrimFlowsCommand::getOligos(vector<vector<string> >& outFlowFileNames){
481         try {
482                 ifstream oligosFile;
483                 m->openInputFile(oligoFileName, oligosFile);
484                 
485                 string type, oligo, group;
486
487                 int indexPrimer = 0;
488                 int indexBarcode = 0;
489                 
490                 while(!oligosFile.eof()){
491                 
492                         oligosFile >> type; m->gobble(oligosFile);      //get the first column value of the row - is it a comment or a feature we are interested in?
493
494                         if(type[0] == '#'){     //igore the line because there's a comment
495                                 while (!oligosFile.eof())       {       char c = oligosFile.get(); if (c == 10 || c == 13){     break;  }       } // get rest of line if there's any crap there
496                         }
497                         else{                           //there's a feature we're interested in
498
499                                 for(int i=0;i<type.length();i++){       type[i] = toupper(type[i]);  }                                  //make type case insensitive
500
501                                 oligosFile >> oligo;    //get the DNA sequence for the feature
502
503                                 for(int i=0;i<oligo.length();i++){      //make type case insensitive and change any U's to T's
504                                         oligo[i] = toupper(oligo[i]);
505                                         if(oligo[i] == 'U')     {       oligo[i] = 'T'; }
506                                 }
507
508                                 if(type == "FORWARD"){  //if the feature is a forward primer...
509                                         group = "";
510
511                                         while (!oligosFile.eof())       {       // get rest of line in case there is a primer name = will have the name of the primer
512                                                 char c = oligosFile.get(); 
513                                                 if (c == 10 || c == 13){        break;  }
514                                                 else if (c == 32 || c == 9){;} //space or tab
515                                                 else {  group += c;  }
516                                         } 
517
518                                         //have we seen this primer already?
519                                         map<string, int>::iterator itPrimer = primers.find(oligo);
520                                         if (itPrimer != primers.end()) { m->mothurOut("primer " + oligo + " is in your oligos file already."); m->mothurOutEndLine();  }
521
522                                         primers[oligo]=indexPrimer; indexPrimer++;
523                                         primerNameVector.push_back(group);
524
525                                 }
526                                 else if(type == "REVERSE"){
527                                         Sequence oligoRC("reverse", oligo);
528                                         oligoRC.reverseComplement();
529                                         revPrimer.push_back(oligoRC.getUnaligned());
530                                 }
531                                 else if(type == "BARCODE"){
532                                         oligosFile >> group;
533
534                                         //check for repeat barcodes
535                                         map<string, int>::iterator itBar = barcodes.find(oligo);
536                                         if (itBar != barcodes.end()) { m->mothurOut("barcode " + oligo + " is in your oligos file already."); m->mothurOutEndLine();  }
537
538                                         barcodes[oligo]=indexBarcode; indexBarcode++;
539                                         barcodeNameVector.push_back(group);
540                                 }
541                                 else{
542                                         m->mothurOut(type + " is not recognized as a valid type. Choices are forward, reverse, and barcode. Ignoring " + oligo + "."); m->mothurOutEndLine();  
543                                 }
544                         }
545
546                         m->gobble(oligosFile);
547                 }
548                 oligosFile.close();
549                 
550                 if(barcodeNameVector.size() == 0 && primerNameVector[0] == ""){ allFiles = 0;   }
551                 
552                 //add in potential combos
553                 if(barcodeNameVector.size() == 0){
554                         barcodes[""] = 0;
555                         barcodeNameVector.push_back("");                        
556                 }
557                 
558                 if(primerNameVector.size() == 0){
559                         primers[""] = 0;
560                         primerNameVector.push_back("");                 
561                 }
562                 
563                 
564                 outFlowFileNames.resize(barcodeNameVector.size());
565                 for(int i=0;i<outFlowFileNames.size();i++){
566                         outFlowFileNames[i].assign(primerNameVector.size(), "");
567                 }
568                 
569                 if(allFiles){
570
571                         for(map<string, int>::iterator itBar = barcodes.begin();itBar != barcodes.end();itBar++){
572                                 for(map<string, int>::iterator itPrimer = primers.begin();itPrimer != primers.end(); itPrimer++){
573
574                                         string primerName = primerNameVector[itPrimer->second];
575                                         string barcodeName = barcodeNameVector[itBar->second];
576                                                                                 
577                                         string comboGroupName = "";
578                                         string fileName = "";
579                                         
580                                         if(primerName == ""){
581                                                 comboGroupName = barcodeNameVector[itBar->second];
582                                                 fileName = outputDir + m->getRootName(m->getSimpleName(flowFileName)) + comboGroupName + ".flow";
583                                         }
584                                         else{
585                                                 if(barcodeName == ""){
586                                                         comboGroupName = primerNameVector[itPrimer->second];
587                                                 }
588                                                 else{
589                                                         comboGroupName = barcodeNameVector[itBar->second] + "." + primerNameVector[itPrimer->second];
590                                                 }
591                                                 fileName = outputDir + m->getRootName(m->getSimpleName(flowFileName)) + comboGroupName + ".flow";
592                                         }
593                                         
594                                         outputNames.push_back(fileName);
595                                         outputTypes["flow"].push_back(fileName);
596                                         outFlowFileNames[itBar->second][itPrimer->second] = fileName;
597                                         
598                                         ofstream temp;
599                                         m->openOutputFile(fileName, temp);
600                                         temp.close();
601                                 }
602                         }
603                 }
604                 
605                 numFPrimers = primers.size();
606                 numRPrimers = revPrimer.size();
607                 
608         }
609         catch(exception& e) {
610                 m->errorOut(e, "TrimSeqsCommand", "getOligos");
611                 exit(1);
612         }
613 }
614
615 //***************************************************************************************************************
616
617 int TrimFlowsCommand::stripBarcode(Sequence& seq, int& group){
618         try {
619                 
620                 string rawSequence = seq.getUnaligned();
621                 int success = bdiffs + 1;       //guilty until proven innocent
622                 
623                 //can you find the barcode
624                 for(map<string,int>::iterator it=barcodes.begin();it!=barcodes.end();it++){
625                         string oligo = it->first;
626                         if(rawSequence.length() < oligo.length()){      //let's just assume that the barcodes are the same length
627                                 success = bdiffs + 10;                                  //if the sequence is shorter than the barcode then bail out
628                                 break;  
629                         }
630                         
631                         if(compareDNASeq(oligo, rawSequence.substr(0,oligo.length()))){
632                                 group = it->second;
633                                 seq.setUnaligned(rawSequence.substr(oligo.length()));
634                                 
635                                 success = 0;
636                                 break;
637                         }
638                 }
639                 
640                 //if you found the barcode or if you don't want to allow for diffs
641                 if ((bdiffs == 0) || (success == 0)) { return success;  }
642                 
643                 else { //try aligning and see if you can find it
644                         
645                         int maxLength = 0;
646                         
647                         Alignment* alignment;
648                         if (barcodes.size() > 0) {
649                                 map<string,int>::iterator it=barcodes.begin();
650                                 
651                                 for(it;it!=barcodes.end();it++){
652                                         if(it->first.length() > maxLength){
653                                                 maxLength = it->first.length();
654                                         }
655                                 }
656                                 alignment = new NeedlemanOverlap(-1.0, 1.0, -1.0, (maxLength+bdiffs+1));  
657                                 
658                         }else{ alignment = NULL; } 
659                         
660                         //can you find the barcode
661                         int minDiff = 1e6;
662                         int minCount = 1;
663                         int minGroup = -1;
664                         int minPos = 0;
665                         
666                         for(map<string,int>::iterator it=barcodes.begin();it!=barcodes.end();it++){
667                                 string oligo = it->first;
668                                 //                              int length = oligo.length();
669                                 
670                                 if(rawSequence.length() < maxLength){   //let's just assume that the barcodes are the same length
671                                         success = bdiffs + 10;
672                                         break;
673                                 }
674                                 
675                                 //use needleman to align first barcode.length()+numdiffs of sequence to each barcode
676                                 alignment->align(oligo, rawSequence.substr(0,oligo.length()+bdiffs));
677                                 oligo = alignment->getSeqAAln();
678                                 string temp = alignment->getSeqBAln();
679                                 
680                                 int alnLength = oligo.length();
681                                 
682                                 for(int i=oligo.length()-1;i>=0;i--){
683                                         if(oligo[i] != '-'){    alnLength = i+1;        break;  }
684                                 }
685                                 oligo = oligo.substr(0,alnLength);
686                                 temp = temp.substr(0,alnLength);
687                                 
688                                 int numDiff = countDiffs(oligo, temp);
689                                 
690                                 if(numDiff < minDiff){
691                                         minDiff = numDiff;
692                                         minCount = 1;
693                                         minGroup = it->second;
694                                         minPos = 0;
695                                         for(int i=0;i<alnLength;i++){
696                                                 if(temp[i] != '-'){
697                                                         minPos++;
698                                                 }
699                                         }
700                                 }
701                                 else if(numDiff == minDiff){
702                                         minCount++;
703                                 }
704                                 
705                         }
706                         
707                         if(minDiff > bdiffs)    {       success = minDiff;              }       //no good matches
708                         else if(minCount > 1)   {       success = bdiffs + 100; }       //can't tell the difference between multiple barcodes
709                         else{                                                                                                   //use the best match
710                                 group = minGroup;
711                                 seq.setUnaligned(rawSequence.substr(minPos));
712                                 success = minDiff;
713                         }
714                         
715                         if (alignment != NULL) {  delete alignment;  }
716                         
717                 }
718                 
719                 return success;
720                 
721         }
722         catch(exception& e) {
723                 m->errorOut(e, "TrimFlowsCommand", "stripBarcode");
724                 exit(1);
725         }
726         
727 }
728
729 //***************************************************************************************************************
730
731 int TrimFlowsCommand::stripForward(Sequence& seq, int& group){
732         try {
733                 
734                 string rawSequence = seq.getUnaligned();
735                 int success = pdiffs + 1;       //guilty until proven innocent
736                 
737                 //can you find the primer
738                 for(map<string,int>::iterator it=primers.begin();it!=primers.end();it++){
739                         string oligo = it->first;
740                         if(rawSequence.length() < oligo.length()){      //let's just assume that the primers are the same length
741                                 success = pdiffs + 10;                                  //if the sequence is shorter than the barcode then bail out
742                                 break;  
743                         }
744                         
745                         if(compareDNASeq(oligo, rawSequence.substr(0,oligo.length()))){
746                                 group = it->second;
747                                 seq.setUnaligned(rawSequence.substr(oligo.length()));
748                                 success = 0;
749                                 break;
750                         }
751                 }
752                 
753                 //if you found the barcode or if you don't want to allow for diffs
754                 if ((pdiffs == 0) || (success == 0)) {  return success;  }
755                 
756                 else { //try aligning and see if you can find it
757                         
758                         int maxLength = 0;
759                         
760                         Alignment* alignment;
761                         if (primers.size() > 0) {
762                                 map<string,int>::iterator it=primers.begin();
763                                 
764                                 for(it;it!=primers.end();it++){
765                                         if(it->first.length() > maxLength){
766                                                 maxLength = it->first.length();
767                                         }
768                                 }
769                                 alignment = new NeedlemanOverlap(-1.0, 1.0, -1.0, (maxLength+pdiffs+1));  
770                                 
771                         }else{ alignment = NULL; } 
772                         
773                         //can you find the barcode
774                         int minDiff = 1e6;
775                         int minCount = 1;
776                         int minGroup = -1;
777                         int minPos = 0;
778                         
779                         for(map<string,int>::iterator it=primers.begin();it!=primers.end();it++){
780                                 string oligo = it->first;
781                                 //                              int length = oligo.length();
782                                 
783                                 if(rawSequence.length() < maxLength){   
784                                         success = pdiffs + 100;
785                                         break;
786                                 }
787                                 
788                                 //use needleman to align first barcode.length()+numdiffs of sequence to each barcode
789                                 alignment->align(oligo, rawSequence.substr(0,oligo.length()+pdiffs));
790                                 oligo = alignment->getSeqAAln();
791                                 string temp = alignment->getSeqBAln();
792                                 
793                                 int alnLength = oligo.length();
794                                 
795                                 for(int i=oligo.length()-1;i>=0;i--){
796                                         if(oligo[i] != '-'){    alnLength = i+1;        break;  }
797                                 }
798                                 oligo = oligo.substr(0,alnLength);
799                                 temp = temp.substr(0,alnLength);
800                                 
801                                 int numDiff = countDiffs(oligo, temp);
802                                 
803                                 if(numDiff < minDiff){
804                                         minDiff = numDiff;
805                                         minCount = 1;
806                                         minGroup = it->second;
807                                         minPos = 0;
808                                         for(int i=0;i<alnLength;i++){
809                                                 if(temp[i] != '-'){
810                                                         minPos++;
811                                                 }
812                                         }
813                                 }
814                                 else if(numDiff == minDiff){
815                                         minCount++;
816                                 }
817                                 
818                         }
819                         
820                         if(minDiff > pdiffs)    {       success = minDiff;              }       //no good matches
821                         else if(minCount > 1)   {       success = pdiffs + 10;  }       //can't tell the difference between multiple primers
822                         else{                                                                                                   //use the best match
823                                 group = minGroup;
824                                 seq.setUnaligned(rawSequence.substr(minPos));
825                                 success = minDiff;
826                         }
827                         
828                         if (alignment != NULL) {  delete alignment;  }
829                         
830                 }
831                 
832                 return success;
833                 
834         }
835         catch(exception& e) {
836                 m->errorOut(e, "TrimFlowsCommand", "stripForward");
837                 exit(1);
838         }
839 }
840
841 //***************************************************************************************************************
842
843 bool TrimFlowsCommand::stripReverse(Sequence& seq){
844         try {
845
846                 string rawSequence = seq.getUnaligned();
847                 bool success = 0;       //guilty until proven innocent
848                 
849                 for(int i=0;i<numRPrimers;i++){
850                         string oligo = revPrimer[i];
851                         
852                         if(rawSequence.length() < oligo.length()){
853                                 success = 0;
854                                 break;
855                         }
856                         
857                         if(compareDNASeq(oligo, rawSequence.substr(rawSequence.length()-oligo.length(),oligo.length()))){
858                                 seq.setUnaligned(rawSequence.substr(0,rawSequence.length()-oligo.length()));
859                                 success = 1;
860                                 break;
861                         }
862                 }       
863
864                 return success;
865                 
866         }
867         catch(exception& e) {
868                 m->errorOut(e, "TrimFlowsCommand", "stripReverse");
869                 exit(1);
870         }
871 }
872
873
874 //***************************************************************************************************************
875
876 bool TrimFlowsCommand::compareDNASeq(string oligo, string seq){
877         try {
878                 bool success = 1;
879                 int length = oligo.length();
880                 
881                 for(int i=0;i<length;i++){
882                         
883                         if(oligo[i] != seq[i]){
884                                 if(oligo[i] == 'A' || oligo[i] == 'T' || oligo[i] == 'G' || oligo[i] == 'C')    {       success = 0;    }
885                                 else if((oligo[i] == 'N' || oligo[i] == 'I') && (seq[i] == 'N'))                                {       success = 0;    }
886                                 else if(oligo[i] == 'R' && (seq[i] != 'A' && seq[i] != 'G'))                                    {       success = 0;    }
887                                 else if(oligo[i] == 'Y' && (seq[i] != 'C' && seq[i] != 'T'))                                    {       success = 0;    }
888                                 else if(oligo[i] == 'M' && (seq[i] != 'C' && seq[i] != 'A'))                                    {       success = 0;    }
889                                 else if(oligo[i] == 'K' && (seq[i] != 'T' && seq[i] != 'G'))                                    {       success = 0;    }
890                                 else if(oligo[i] == 'W' && (seq[i] != 'T' && seq[i] != 'A'))                                    {       success = 0;    }
891                                 else if(oligo[i] == 'S' && (seq[i] != 'C' && seq[i] != 'G'))                                    {       success = 0;    }
892                                 else if(oligo[i] == 'B' && (seq[i] != 'C' && seq[i] != 'T' && seq[i] != 'G'))   {       success = 0;    }
893                                 else if(oligo[i] == 'D' && (seq[i] != 'A' && seq[i] != 'T' && seq[i] != 'G'))   {       success = 0;    }
894                                 else if(oligo[i] == 'H' && (seq[i] != 'A' && seq[i] != 'T' && seq[i] != 'C'))   {       success = 0;    }
895                                 else if(oligo[i] == 'V' && (seq[i] != 'A' && seq[i] != 'C' && seq[i] != 'G'))   {       success = 0;    }                       
896                                 
897                                 if(success == 0)        {       break;   }
898                         }
899                         else{
900                                 success = 1;
901                         }
902                 }
903                 
904                 return success;
905         }
906         catch(exception& e) {
907                 m->errorOut(e, "TrimFlowsCommand", "compareDNASeq");
908                 exit(1);
909         }
910         
911 }
912
913 //***************************************************************************************************************
914
915 int TrimFlowsCommand::countDiffs(string oligo, string seq){
916         try {
917                 
918                 int length = oligo.length();
919                 int countDiffs = 0;
920                 
921                 for(int i=0;i<length;i++){
922                         
923                         if(oligo[i] != seq[i]){
924                                 if(oligo[i] == 'A' || oligo[i] == 'T' || oligo[i] == 'G' || oligo[i] == 'C' || oligo[i] == '-' || oligo[i] == '.')      {       countDiffs++;   }
925                                 else if((oligo[i] == 'N' || oligo[i] == 'I') && (seq[i] == 'N'))                                {       countDiffs++;   }
926                                 else if(oligo[i] == 'R' && (seq[i] != 'A' && seq[i] != 'G'))                                    {       countDiffs++;   }
927                                 else if(oligo[i] == 'Y' && (seq[i] != 'C' && seq[i] != 'T'))                                    {       countDiffs++;   }
928                                 else if(oligo[i] == 'M' && (seq[i] != 'C' && seq[i] != 'A'))                                    {       countDiffs++;   }
929                                 else if(oligo[i] == 'K' && (seq[i] != 'T' && seq[i] != 'G'))                                    {       countDiffs++;   }
930                                 else if(oligo[i] == 'W' && (seq[i] != 'T' && seq[i] != 'A'))                                    {       countDiffs++;   }
931                                 else if(oligo[i] == 'S' && (seq[i] != 'C' && seq[i] != 'G'))                                    {       countDiffs++;   }
932                                 else if(oligo[i] == 'B' && (seq[i] != 'C' && seq[i] != 'T' && seq[i] != 'G'))   {       countDiffs++;   }
933                                 else if(oligo[i] == 'D' && (seq[i] != 'A' && seq[i] != 'T' && seq[i] != 'G'))   {       countDiffs++;   }
934                                 else if(oligo[i] == 'H' && (seq[i] != 'A' && seq[i] != 'T' && seq[i] != 'C'))   {       countDiffs++;   }
935                                 else if(oligo[i] == 'V' && (seq[i] != 'A' && seq[i] != 'C' && seq[i] != 'G'))   {       countDiffs++;   }       
936                         }
937                         
938                 }
939                 
940                 return countDiffs;
941         }
942         catch(exception& e) {
943                 m->errorOut(e, "TrimFlowsCommand", "countDiffs");
944                 exit(1);
945         }
946         
947 }
948
949 /**************************************************************************************************/
950
951 vector<unsigned long int> TrimFlowsCommand::getFlowFileBreaks() {
952
953         try{
954                         
955                 vector<unsigned long int> filePos;
956                 filePos.push_back(0);
957                                         
958                 FILE * pFile;
959                 unsigned long int size;
960                 
961                 //get num bytes in file
962                 pFile = fopen (flowFileName.c_str(),"rb");
963                 if (pFile==NULL) perror ("Error opening file");
964                 else{
965                         fseek (pFile, 0, SEEK_END);
966                         size=ftell (pFile);
967                         fclose (pFile);
968                 }
969                                 
970                 //estimate file breaks
971                 unsigned long int chunkSize = 0;
972                 chunkSize = size / processors;
973
974                 //file too small to divide by processors
975                 if (chunkSize == 0)  {  processors = 1; filePos.push_back(size); return filePos;        }
976                 
977                 //for each process seekg to closest file break and search for next '>' char. make that the filebreak
978                 for (int i = 0; i < processors; i++) {
979                         unsigned long int spot = (i+1) * chunkSize;
980                         
981                         ifstream in;
982                         m->openInputFile(flowFileName, in);
983                         in.seekg(spot);
984                         
985                         string dummy = m->getline(in);
986                         
987                         //there was not another sequence before the end of the file
988                         unsigned long int sanityPos = in.tellg();
989                         
990 //                      if (sanityPos == -1) {  break;  }
991 //                      else {  filePos.push_back(newSpot);  }
992                         if (sanityPos == -1) {  break;  }
993                         else {  filePos.push_back(sanityPos);  }
994                         
995                         in.close();
996                 }
997                 
998                 //save end pos
999                 filePos.push_back(size);
1000                 
1001                 //sanity check filePos
1002                 for (int i = 0; i < (filePos.size()-1); i++) {
1003                         if (filePos[(i+1)] <= filePos[i]) {  filePos.erase(filePos.begin()+(i+1)); i--; }
1004                 }
1005
1006                 ifstream in;
1007                 m->openInputFile(flowFileName, in);
1008                 in >> numFlows;
1009                 m->gobble(in);
1010                 unsigned long int spot = in.tellg();
1011                 filePos[0] = spot;
1012                 in.close();
1013                 
1014                 processors = (filePos.size() - 1);
1015                 
1016                 return filePos; 
1017         }
1018         catch(exception& e) {
1019                 m->errorOut(e, "TrimSeqsCommand", "getFlowFileBreaks");
1020                 exit(1);
1021         }
1022 }
1023
1024 /**************************************************************************************************/
1025
1026 int TrimFlowsCommand::createProcessesCreateTrim(string flowFileName, string trimFlowFileName, string scrapFlowFileName, string fastaFileName, vector<vector<string> > barcodePrimerComboFileNames){
1027
1028         try {
1029 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
1030                 int process = 1;
1031                 int exitCommand = 1;
1032                 processIDS.clear();
1033                 
1034                 //loop through and create all the processes you want
1035                 while (process != processors) {
1036                         int pid = fork();
1037                         
1038                         if (pid > 0) {
1039                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
1040                                 process++;
1041                         }else if (pid == 0){
1042                                 
1043                                 vector<vector<string> > tempBarcodePrimerComboFileNames = barcodePrimerComboFileNames;
1044                                 if(allFiles){
1045                                         for(int i=0;i<tempBarcodePrimerComboFileNames.size();i++){
1046                                                 for(int j=0;j<tempBarcodePrimerComboFileNames[0].size();j++){
1047                                                         tempBarcodePrimerComboFileNames[i][j] += toString(getpid()) + ".temp";
1048                                                         ofstream temp;
1049                                                         m->openOutputFile(tempBarcodePrimerComboFileNames[i][j], temp);
1050                                                         temp.close();
1051                                                         
1052                                                 }
1053                                         }
1054                                 }
1055                                 driverCreateTrim(flowFileName,
1056                                                                  (trimFlowFileName + toString(getpid()) + ".temp"),
1057                                                                  (scrapFlowFileName + toString(getpid()) + ".temp"),
1058                                                                  (fastaFileName + toString(getpid()) + ".temp"),
1059                                                                  tempBarcodePrimerComboFileNames, lines[process]);
1060
1061                                 exit(0);
1062                         }else { 
1063                                 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); 
1064                                 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
1065                                 exit(0);
1066                         }
1067                 }
1068                 
1069                 //parent do my part
1070                 ofstream temp;
1071                 m->openOutputFile(trimFlowFileName, temp);
1072                 temp.close();
1073
1074                 m->openOutputFile(scrapFlowFileName, temp);
1075                 temp.close();
1076                 
1077                 if(fasta){
1078                         m->openOutputFile(fastaFileName, temp);
1079                         temp.close();
1080                 }
1081                 
1082                 driverCreateTrim(flowFileName, trimFlowFileName, scrapFlowFileName, fastaFileName, barcodePrimerComboFileNames, lines[0]);
1083
1084                 //force parent to wait until all the processes are done
1085                 for (int i=0;i<processIDS.size();i++) { 
1086                         int temp = processIDS[i];
1087                         wait(&temp);
1088                 }
1089                 
1090                 //append files
1091                 m->mothurOutEndLine();
1092                 for(int i=0;i<processIDS.size();i++){
1093                         
1094                         m->mothurOut("Appending files from process " + toString(processIDS[i])); m->mothurOutEndLine();
1095                         
1096                         m->appendFiles((trimFlowFileName + toString(processIDS[i]) + ".temp"), trimFlowFileName);
1097                         remove((trimFlowFileName + toString(processIDS[i]) + ".temp").c_str());
1098 //                      m->mothurOut("\tDone with trim.flow file"); m->mothurOutEndLine();
1099
1100                         m->appendFiles((scrapFlowFileName + toString(processIDS[i]) + ".temp"), scrapFlowFileName);
1101                         remove((scrapFlowFileName + toString(processIDS[i]) + ".temp").c_str());
1102 //                      m->mothurOut("\tDone with scrap.flow file"); m->mothurOutEndLine();
1103
1104                         if(fasta){
1105                                 m->appendFiles((fastaFileName + toString(processIDS[i]) + ".temp"), fastaFileName);
1106                                 remove((fastaFileName + toString(processIDS[i]) + ".temp").c_str());
1107 //                              m->mothurOut("\tDone with flow.fasta file"); m->mothurOutEndLine();
1108                         }
1109                         if(allFiles){                                           
1110                                 for (int j = 0; j < barcodePrimerComboFileNames.size(); j++) {
1111                                         for (int k = 0; k < barcodePrimerComboFileNames[0].size(); k++) {
1112                                                 m->appendFiles((barcodePrimerComboFileNames[j][k] + toString(processIDS[i]) + ".temp"), barcodePrimerComboFileNames[j][k]);
1113                                                 remove((barcodePrimerComboFileNames[j][k] + toString(processIDS[i]) + ".temp").c_str());
1114                                         }
1115                                 }
1116                         }
1117                 }
1118                 
1119                 return exitCommand;
1120 #endif          
1121         }
1122         catch(exception& e) {
1123                 m->errorOut(e, "TrimFlowsCommand", "createProcessesCreateTrim");
1124                 exit(1);
1125         }
1126 }
1127
1128 //***************************************************************************************************************