]> git.donarmstrong.com Git - mothur.git/blob - trimflowscommand.cpp
shhh.seqs and trim.flows modifications.
[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                 outputNames.push_back(flowFileName);
326                 
327                 m->mothurOutEndLine();
328                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
329                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }
330                 m->mothurOutEndLine();
331                 
332                 return 0;       
333         }
334         catch(exception& e) {
335                 m->errorOut(e, "TrimSeqsCommand", "execute");
336                 exit(1);
337         }
338 }
339
340 //***************************************************************************************************************
341
342 int TrimFlowsCommand::driverCreateTrim(string flowFileName, string trimFlowFileName, string scrapFlowFileName, string fastaFileName, vector<vector<string> > barcodePrimerComboFileNames, linePair* line){
343         
344         try {
345                 
346                 ofstream trimFlowFile;
347                 m->openOutputFile(trimFlowFileName, trimFlowFile);
348                 trimFlowFile.setf(ios::fixed, ios::floatfield); trimFlowFile.setf(ios::showpoint);
349
350                 ofstream scrapFlowFile;
351                 m->openOutputFile(scrapFlowFileName, scrapFlowFile);
352                 scrapFlowFile.setf(ios::fixed, ios::floatfield); scrapFlowFile.setf(ios::showpoint);
353
354                 if(line->start == 4){
355                         scrapFlowFile << maxFlows << endl;
356                         trimFlowFile << maxFlows << endl;
357                         if(allFiles){
358                                 for(int i=0;i<barcodePrimerComboFileNames.size();i++){
359                                         for(int j=0;j<barcodePrimerComboFileNames[0].size();j++){
360                                                 //                              barcodePrimerComboFileNames[i][j] += toString(getpid()) + ".temp";
361                                                 ofstream temp;
362                                                 m->openOutputFile(barcodePrimerComboFileNames[i][j], temp);
363                                                 temp << maxFlows << endl;
364                                                 temp.close();
365                                         }
366                                 }                       
367                         }
368                 }
369                 
370                 FlowData flowData(numFlows, signal, noise, maxHomoP);
371                 
372                 ofstream fastaFile;
373                 if(fasta){      m->openOutputFile(fastaFileName, fastaFile);    }
374                 
375                 ifstream flowFile;
376                 m->openInputFile(flowFileName, flowFile);
377                 
378                 flowFile.seekg(line->start);
379
380                 int count = 0;
381                 bool moreSeqs = 1;
382                         
383                 while(moreSeqs) {
384                         
385                         int success = 1;
386                         int currentSeqDiffs = 0;
387                         string trashCode = "";
388                         
389                         flowData.getNext(flowFile);
390                         flowData.capFlows(maxFlows);    
391                         
392                         Sequence currSeq = flowData.getSequence();
393                         if(!flowData.hasMinFlows(minFlows)){    //screen to see if sequence is of a minimum number of flows
394                                 success = 0;
395                                 trashCode += 'l';
396                         }
397                         
398                         if(minLength > 0 || maxLength > 0){     //screen to see if sequence is above and below a specific number of bases
399                                 int seqLength = currSeq.getNumBases();
400                                 if(seqLength < minLength || seqLength > maxLength){
401                                         success = 0;
402                                         trashCode += 'l';
403                                 }
404                         }
405                         
406                         int primerIndex = 0;
407                         int barcodeIndex = 0;
408                         
409                         if(barcodes.size() != 0){
410                                 success = stripBarcode(currSeq, barcodeIndex);
411                                 if(success > bdiffs)            {       trashCode += 'b';       }
412                                 else{ currentSeqDiffs += success;  }
413                         }
414                         
415                         if(numFPrimers != 0){
416                                 success = stripForward(currSeq, primerIndex);
417                                 if(success > pdiffs)            {       trashCode += 'f';       }
418                                 else{ currentSeqDiffs += success;  }
419                         }
420                         
421                         if (currentSeqDiffs > tdiffs)   {       trashCode += 't';   }
422                         
423                         if(numRPrimers != 0){
424                                 success = stripReverse(currSeq);
425                                 if(!success)                            {       trashCode += 'r';       }
426                         }
427
428                         if(trashCode.length() == 0){
429                                                         
430                                 flowData.printFlows(trimFlowFile);
431                         
432                                 if(fasta)       {       currSeq.printSequence(fastaFile);       }
433                                 
434                                 if(allFiles){
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                         else{
444                                 flowData.printFlows(scrapFlowFile, trashCode);
445                         }
446                                 
447                         count++;
448                                                 
449                         //report progress
450                         if((count) % 10000 == 0){       m->mothurOut(toString(count)); m->mothurOutEndLine();           }
451
452 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
453                         unsigned long int pos = flowFile.tellg();
454
455                         if ((pos == -1) || (pos >= line->end)) { break; }
456 #else
457                         if (flowFile.eof()) { break; }
458 #endif
459                         
460                 }
461                 //report progress
462                 if((count) % 10000 != 0){       m->mothurOut(toString(count)); m->mothurOutEndLine();           }
463                 
464                 trimFlowFile.close();
465                 scrapFlowFile.close();
466                 flowFile.close();
467                 if(fasta){      fastaFile.close();      }
468                 
469                 return count;
470         }
471         catch(exception& e) {
472                 m->errorOut(e, "TrimSeqsCommand", "driverCreateTrim");
473                 exit(1);
474         }
475 }
476
477 //***************************************************************************************************************
478
479 void TrimFlowsCommand::getOligos(vector<vector<string> >& outFlowFileNames){
480         try {
481                 ifstream oligosFile;
482                 m->openInputFile(oligoFileName, oligosFile);
483                 
484                 string type, oligo, group;
485
486                 int indexPrimer = 0;
487                 int indexBarcode = 0;
488                 
489                 while(!oligosFile.eof()){
490                 
491                         oligosFile >> type; m->gobble(oligosFile);      //get the first column value of the row - is it a comment or a feature we are interested in?
492
493                         if(type[0] == '#'){     //igore the line because there's a comment
494                                 while (!oligosFile.eof())       {       char c = oligosFile.get(); if (c == 10 || c == 13){     break;  }       } // get rest of line if there's any crap there
495                         }
496                         else{                           //there's a feature we're interested in
497
498                                 for(int i=0;i<type.length();i++){       type[i] = toupper(type[i]);  }                                  //make type case insensitive
499
500                                 oligosFile >> oligo;    //get the DNA sequence for the feature
501
502                                 for(int i=0;i<oligo.length();i++){      //make type case insensitive and change any U's to T's
503                                         oligo[i] = toupper(oligo[i]);
504                                         if(oligo[i] == 'U')     {       oligo[i] = 'T'; }
505                                 }
506
507                                 if(type == "FORWARD"){  //if the feature is a forward primer...
508                                         group = "";
509
510                                         while (!oligosFile.eof())       {       // get rest of line in case there is a primer name = will have the name of the primer
511                                                 char c = oligosFile.get(); 
512                                                 if (c == 10 || c == 13){        break;  }
513                                                 else if (c == 32 || c == 9){;} //space or tab
514                                                 else {  group += c;  }
515                                         } 
516
517                                         //have we seen this primer already?
518                                         map<string, int>::iterator itPrimer = primers.find(oligo);
519                                         if (itPrimer != primers.end()) { m->mothurOut("primer " + oligo + " is in your oligos file already."); m->mothurOutEndLine();  }
520
521                                         primers[oligo]=indexPrimer; indexPrimer++;
522                                         primerNameVector.push_back(group);
523
524                                 }
525                                 else if(type == "REVERSE"){
526                                         Sequence oligoRC("reverse", oligo);
527                                         oligoRC.reverseComplement();
528                                         revPrimer.push_back(oligoRC.getUnaligned());
529                                 }
530                                 else if(type == "BARCODE"){
531                                         oligosFile >> group;
532
533                                         //check for repeat barcodes
534                                         map<string, int>::iterator itBar = barcodes.find(oligo);
535                                         if (itBar != barcodes.end()) { m->mothurOut("barcode " + oligo + " is in your oligos file already."); m->mothurOutEndLine();  }
536
537                                         barcodes[oligo]=indexBarcode; indexBarcode++;
538                                         barcodeNameVector.push_back(group);
539                                 }
540                                 else{
541                                         m->mothurOut(type + " is not recognized as a valid type. Choices are forward, reverse, and barcode. Ignoring " + oligo + "."); m->mothurOutEndLine();  
542                                 }
543                         }
544
545                         m->gobble(oligosFile);
546                 }
547                 oligosFile.close();
548                 
549                 if(barcodeNameVector.size() == 0 && primerNameVector[0] == ""){ allFiles = 0;   }
550                 
551                 //add in potential combos
552                 if(barcodeNameVector.size() == 0){
553                         barcodes[""] = 0;
554                         barcodeNameVector.push_back("");                        
555                 }
556                 
557                 if(primerNameVector.size() == 0){
558                         primers[""] = 0;
559                         primerNameVector.push_back("");                 
560                 }
561                 
562                 
563                 outFlowFileNames.resize(barcodeNameVector.size());
564                 for(int i=0;i<outFlowFileNames.size();i++){
565                         outFlowFileNames[i].assign(primerNameVector.size(), "");
566                 }
567                 
568                 if(allFiles){
569
570                         for(map<string, int>::iterator itBar = barcodes.begin();itBar != barcodes.end();itBar++){
571                                 for(map<string, int>::iterator itPrimer = primers.begin();itPrimer != primers.end(); itPrimer++){
572
573                                         string primerName = primerNameVector[itPrimer->second];
574                                         string barcodeName = barcodeNameVector[itBar->second];
575                                                                                 
576                                         string comboGroupName = "";
577                                         string fileName = "";
578                                         
579                                         if(primerName == ""){
580                                                 comboGroupName = barcodeNameVector[itBar->second];
581                                                 fileName = outputDir + m->getRootName(m->getSimpleName(flowFileName)) + comboGroupName + ".flow";
582                                         }
583                                         else{
584                                                 if(barcodeName == ""){
585                                                         comboGroupName = primerNameVector[itPrimer->second];
586                                                 }
587                                                 else{
588                                                         comboGroupName = barcodeNameVector[itBar->second] + "." + primerNameVector[itPrimer->second];
589                                                 }
590                                                 fileName = outputDir + m->getRootName(m->getSimpleName(flowFileName)) + comboGroupName + ".flow";
591                                         }
592                                         
593                                         outputNames.push_back(fileName);
594                                         outputTypes["flow"].push_back(fileName);
595                                         outFlowFileNames[itBar->second][itPrimer->second] = fileName;
596                                         
597                                         ofstream temp;
598                                         m->openOutputFile(fileName, temp);
599                                         temp.close();
600                                 }
601                         }
602                 }
603                 
604                 numFPrimers = primers.size();
605                 numRPrimers = revPrimer.size();
606                 
607         }
608         catch(exception& e) {
609                 m->errorOut(e, "TrimSeqsCommand", "getOligos");
610                 exit(1);
611         }
612 }
613
614 //***************************************************************************************************************
615
616 int TrimFlowsCommand::stripBarcode(Sequence& seq, int& group){
617         try {
618                 
619                 string rawSequence = seq.getUnaligned();
620                 int success = bdiffs + 1;       //guilty until proven innocent
621                 
622                 //can you find the barcode
623                 for(map<string,int>::iterator it=barcodes.begin();it!=barcodes.end();it++){
624                         string oligo = it->first;
625                         if(rawSequence.length() < oligo.length()){      //let's just assume that the barcodes are the same length
626                                 success = bdiffs + 10;                                  //if the sequence is shorter than the barcode then bail out
627                                 break;  
628                         }
629                         
630                         if(compareDNASeq(oligo, rawSequence.substr(0,oligo.length()))){
631                                 group = it->second;
632                                 seq.setUnaligned(rawSequence.substr(oligo.length()));
633                                 
634                                 success = 0;
635                                 break;
636                         }
637                 }
638                 
639                 //if you found the barcode or if you don't want to allow for diffs
640                 if ((bdiffs == 0) || (success == 0)) { return success;  }
641                 
642                 else { //try aligning and see if you can find it
643                         
644                         int maxLength = 0;
645                         
646                         Alignment* alignment;
647                         if (barcodes.size() > 0) {
648                                 map<string,int>::iterator it=barcodes.begin();
649                                 
650                                 for(it;it!=barcodes.end();it++){
651                                         if(it->first.length() > maxLength){
652                                                 maxLength = it->first.length();
653                                         }
654                                 }
655                                 alignment = new NeedlemanOverlap(-1.0, 1.0, -1.0, (maxLength+bdiffs+1));  
656                                 
657                         }else{ alignment = NULL; } 
658                         
659                         //can you find the barcode
660                         int minDiff = 1e6;
661                         int minCount = 1;
662                         int minGroup = -1;
663                         int minPos = 0;
664                         
665                         for(map<string,int>::iterator it=barcodes.begin();it!=barcodes.end();it++){
666                                 string oligo = it->first;
667                                 //                              int length = oligo.length();
668                                 
669                                 if(rawSequence.length() < maxLength){   //let's just assume that the barcodes are the same length
670                                         success = bdiffs + 10;
671                                         break;
672                                 }
673                                 
674                                 //use needleman to align first barcode.length()+numdiffs of sequence to each barcode
675                                 alignment->align(oligo, rawSequence.substr(0,oligo.length()+bdiffs));
676                                 oligo = alignment->getSeqAAln();
677                                 string temp = alignment->getSeqBAln();
678                                 
679                                 int alnLength = oligo.length();
680                                 
681                                 for(int i=oligo.length()-1;i>=0;i--){
682                                         if(oligo[i] != '-'){    alnLength = i+1;        break;  }
683                                 }
684                                 oligo = oligo.substr(0,alnLength);
685                                 temp = temp.substr(0,alnLength);
686                                 
687                                 int numDiff = countDiffs(oligo, temp);
688                                 
689                                 if(numDiff < minDiff){
690                                         minDiff = numDiff;
691                                         minCount = 1;
692                                         minGroup = it->second;
693                                         minPos = 0;
694                                         for(int i=0;i<alnLength;i++){
695                                                 if(temp[i] != '-'){
696                                                         minPos++;
697                                                 }
698                                         }
699                                 }
700                                 else if(numDiff == minDiff){
701                                         minCount++;
702                                 }
703                                 
704                         }
705                         
706                         if(minDiff > bdiffs)    {       success = minDiff;              }       //no good matches
707                         else if(minCount > 1)   {       success = bdiffs + 100; }       //can't tell the difference between multiple barcodes
708                         else{                                                                                                   //use the best match
709                                 group = minGroup;
710                                 seq.setUnaligned(rawSequence.substr(minPos));
711                                 success = minDiff;
712                         }
713                         
714                         if (alignment != NULL) {  delete alignment;  }
715                         
716                 }
717                 
718                 return success;
719                 
720         }
721         catch(exception& e) {
722                 m->errorOut(e, "TrimFlowsCommand", "stripBarcode");
723                 exit(1);
724         }
725         
726 }
727
728 //***************************************************************************************************************
729
730 int TrimFlowsCommand::stripForward(Sequence& seq, int& group){
731         try {
732                 
733                 string rawSequence = seq.getUnaligned();
734                 int success = pdiffs + 1;       //guilty until proven innocent
735                 
736                 //can you find the primer
737                 for(map<string,int>::iterator it=primers.begin();it!=primers.end();it++){
738                         string oligo = it->first;
739                         if(rawSequence.length() < oligo.length()){      //let's just assume that the primers are the same length
740                                 success = pdiffs + 10;                                  //if the sequence is shorter than the barcode then bail out
741                                 break;  
742                         }
743                         
744                         if(compareDNASeq(oligo, rawSequence.substr(0,oligo.length()))){
745                                 group = it->second;
746                                 seq.setUnaligned(rawSequence.substr(oligo.length()));
747                                 success = 0;
748                                 break;
749                         }
750                 }
751                 
752                 //if you found the barcode or if you don't want to allow for diffs
753                 if ((pdiffs == 0) || (success == 0)) {  return success;  }
754                 
755                 else { //try aligning and see if you can find it
756                         
757                         int maxLength = 0;
758                         
759                         Alignment* alignment;
760                         if (primers.size() > 0) {
761                                 map<string,int>::iterator it=primers.begin();
762                                 
763                                 for(it;it!=primers.end();it++){
764                                         if(it->first.length() > maxLength){
765                                                 maxLength = it->first.length();
766                                         }
767                                 }
768                                 alignment = new NeedlemanOverlap(-1.0, 1.0, -1.0, (maxLength+pdiffs+1));  
769                                 
770                         }else{ alignment = NULL; } 
771                         
772                         //can you find the barcode
773                         int minDiff = 1e6;
774                         int minCount = 1;
775                         int minGroup = -1;
776                         int minPos = 0;
777                         
778                         for(map<string,int>::iterator it=primers.begin();it!=primers.end();it++){
779                                 string oligo = it->first;
780                                 //                              int length = oligo.length();
781                                 
782                                 if(rawSequence.length() < maxLength){   
783                                         success = pdiffs + 100;
784                                         break;
785                                 }
786                                 
787                                 //use needleman to align first barcode.length()+numdiffs of sequence to each barcode
788                                 alignment->align(oligo, rawSequence.substr(0,oligo.length()+pdiffs));
789                                 oligo = alignment->getSeqAAln();
790                                 string temp = alignment->getSeqBAln();
791                                 
792                                 int alnLength = oligo.length();
793                                 
794                                 for(int i=oligo.length()-1;i>=0;i--){
795                                         if(oligo[i] != '-'){    alnLength = i+1;        break;  }
796                                 }
797                                 oligo = oligo.substr(0,alnLength);
798                                 temp = temp.substr(0,alnLength);
799                                 
800                                 int numDiff = countDiffs(oligo, temp);
801                                 
802                                 if(numDiff < minDiff){
803                                         minDiff = numDiff;
804                                         minCount = 1;
805                                         minGroup = it->second;
806                                         minPos = 0;
807                                         for(int i=0;i<alnLength;i++){
808                                                 if(temp[i] != '-'){
809                                                         minPos++;
810                                                 }
811                                         }
812                                 }
813                                 else if(numDiff == minDiff){
814                                         minCount++;
815                                 }
816                                 
817                         }
818                         
819                         if(minDiff > pdiffs)    {       success = minDiff;              }       //no good matches
820                         else if(minCount > 1)   {       success = pdiffs + 10;  }       //can't tell the difference between multiple primers
821                         else{                                                                                                   //use the best match
822                                 group = minGroup;
823                                 seq.setUnaligned(rawSequence.substr(minPos));
824                                 success = minDiff;
825                         }
826                         
827                         if (alignment != NULL) {  delete alignment;  }
828                         
829                 }
830                 
831                 return success;
832                 
833         }
834         catch(exception& e) {
835                 m->errorOut(e, "TrimFlowsCommand", "stripForward");
836                 exit(1);
837         }
838 }
839
840 //***************************************************************************************************************
841
842 bool TrimFlowsCommand::stripReverse(Sequence& seq){
843         try {
844
845                 string rawSequence = seq.getUnaligned();
846                 bool success = 0;       //guilty until proven innocent
847                 
848                 for(int i=0;i<numRPrimers;i++){
849                         string oligo = revPrimer[i];
850                         
851                         if(rawSequence.length() < oligo.length()){
852                                 success = 0;
853                                 break;
854                         }
855                         
856                         if(compareDNASeq(oligo, rawSequence.substr(rawSequence.length()-oligo.length(),oligo.length()))){
857                                 seq.setUnaligned(rawSequence.substr(0,rawSequence.length()-oligo.length()));
858                                 success = 1;
859                                 break;
860                         }
861                 }       
862
863                 return success;
864                 
865         }
866         catch(exception& e) {
867                 m->errorOut(e, "TrimFlowsCommand", "stripReverse");
868                 exit(1);
869         }
870 }
871
872
873 //***************************************************************************************************************
874
875 bool TrimFlowsCommand::compareDNASeq(string oligo, string seq){
876         try {
877                 bool success = 1;
878                 int length = oligo.length();
879                 
880                 for(int i=0;i<length;i++){
881                         
882                         if(oligo[i] != seq[i]){
883                                 if(oligo[i] == 'A' || oligo[i] == 'T' || oligo[i] == 'G' || oligo[i] == 'C')    {       success = 0;    }
884                                 else if((oligo[i] == 'N' || oligo[i] == 'I') && (seq[i] == 'N'))                                {       success = 0;    }
885                                 else if(oligo[i] == 'R' && (seq[i] != 'A' && seq[i] != 'G'))                                    {       success = 0;    }
886                                 else if(oligo[i] == 'Y' && (seq[i] != 'C' && seq[i] != 'T'))                                    {       success = 0;    }
887                                 else if(oligo[i] == 'M' && (seq[i] != 'C' && seq[i] != 'A'))                                    {       success = 0;    }
888                                 else if(oligo[i] == 'K' && (seq[i] != 'T' && seq[i] != 'G'))                                    {       success = 0;    }
889                                 else if(oligo[i] == 'W' && (seq[i] != 'T' && seq[i] != 'A'))                                    {       success = 0;    }
890                                 else if(oligo[i] == 'S' && (seq[i] != 'C' && seq[i] != 'G'))                                    {       success = 0;    }
891                                 else if(oligo[i] == 'B' && (seq[i] != 'C' && seq[i] != 'T' && seq[i] != 'G'))   {       success = 0;    }
892                                 else if(oligo[i] == 'D' && (seq[i] != 'A' && seq[i] != 'T' && seq[i] != 'G'))   {       success = 0;    }
893                                 else if(oligo[i] == 'H' && (seq[i] != 'A' && seq[i] != 'T' && seq[i] != 'C'))   {       success = 0;    }
894                                 else if(oligo[i] == 'V' && (seq[i] != 'A' && seq[i] != 'C' && seq[i] != 'G'))   {       success = 0;    }                       
895                                 
896                                 if(success == 0)        {       break;   }
897                         }
898                         else{
899                                 success = 1;
900                         }
901                 }
902                 
903                 return success;
904         }
905         catch(exception& e) {
906                 m->errorOut(e, "TrimFlowsCommand", "compareDNASeq");
907                 exit(1);
908         }
909         
910 }
911
912 //***************************************************************************************************************
913
914 int TrimFlowsCommand::countDiffs(string oligo, string seq){
915         try {
916                 
917                 int length = oligo.length();
918                 int countDiffs = 0;
919                 
920                 for(int i=0;i<length;i++){
921                         
922                         if(oligo[i] != seq[i]){
923                                 if(oligo[i] == 'A' || oligo[i] == 'T' || oligo[i] == 'G' || oligo[i] == 'C' || oligo[i] == '-' || oligo[i] == '.')      {       countDiffs++;   }
924                                 else if((oligo[i] == 'N' || oligo[i] == 'I') && (seq[i] == 'N'))                                {       countDiffs++;   }
925                                 else if(oligo[i] == 'R' && (seq[i] != 'A' && seq[i] != 'G'))                                    {       countDiffs++;   }
926                                 else if(oligo[i] == 'Y' && (seq[i] != 'C' && seq[i] != 'T'))                                    {       countDiffs++;   }
927                                 else if(oligo[i] == 'M' && (seq[i] != 'C' && seq[i] != 'A'))                                    {       countDiffs++;   }
928                                 else if(oligo[i] == 'K' && (seq[i] != 'T' && seq[i] != 'G'))                                    {       countDiffs++;   }
929                                 else if(oligo[i] == 'W' && (seq[i] != 'T' && seq[i] != 'A'))                                    {       countDiffs++;   }
930                                 else if(oligo[i] == 'S' && (seq[i] != 'C' && seq[i] != 'G'))                                    {       countDiffs++;   }
931                                 else if(oligo[i] == 'B' && (seq[i] != 'C' && seq[i] != 'T' && seq[i] != 'G'))   {       countDiffs++;   }
932                                 else if(oligo[i] == 'D' && (seq[i] != 'A' && seq[i] != 'T' && seq[i] != 'G'))   {       countDiffs++;   }
933                                 else if(oligo[i] == 'H' && (seq[i] != 'A' && seq[i] != 'T' && seq[i] != 'C'))   {       countDiffs++;   }
934                                 else if(oligo[i] == 'V' && (seq[i] != 'A' && seq[i] != 'C' && seq[i] != 'G'))   {       countDiffs++;   }       
935                         }
936                         
937                 }
938                 
939                 return countDiffs;
940         }
941         catch(exception& e) {
942                 m->errorOut(e, "TrimFlowsCommand", "countDiffs");
943                 exit(1);
944         }
945         
946 }
947
948 /**************************************************************************************************/
949
950 vector<unsigned long int> TrimFlowsCommand::getFlowFileBreaks() {
951
952         try{
953                         
954                 vector<unsigned long int> filePos;
955                 filePos.push_back(0);
956                                         
957                 FILE * pFile;
958                 unsigned long int size;
959                 
960                 //get num bytes in file
961                 pFile = fopen (flowFileName.c_str(),"rb");
962                 if (pFile==NULL) perror ("Error opening file");
963                 else{
964                         fseek (pFile, 0, SEEK_END);
965                         size=ftell (pFile);
966                         fclose (pFile);
967                 }
968                                 
969                 //estimate file breaks
970                 unsigned long int chunkSize = 0;
971                 chunkSize = size / processors;
972
973                 //file too small to divide by processors
974                 if (chunkSize == 0)  {  processors = 1; filePos.push_back(size); return filePos;        }
975                 
976                 //for each process seekg to closest file break and search for next '>' char. make that the filebreak
977                 for (int i = 0; i < processors; i++) {
978                         unsigned long int spot = (i+1) * chunkSize;
979                         
980                         ifstream in;
981                         m->openInputFile(flowFileName, in);
982                         in.seekg(spot);
983                         
984                         string dummy = m->getline(in);
985                         
986                         //there was not another sequence before the end of the file
987                         unsigned long int sanityPos = in.tellg();
988                         
989 //                      if (sanityPos == -1) {  break;  }
990 //                      else {  filePos.push_back(newSpot);  }
991                         if (sanityPos == -1) {  break;  }
992                         else {  filePos.push_back(sanityPos);  }
993                         
994                         in.close();
995                 }
996                 
997                 //save end pos
998                 filePos.push_back(size);
999                 
1000                 //sanity check filePos
1001                 for (int i = 0; i < (filePos.size()-1); i++) {
1002                         if (filePos[(i+1)] <= filePos[i]) {  filePos.erase(filePos.begin()+(i+1)); i--; }
1003                 }
1004
1005                 ifstream in;
1006                 m->openInputFile(flowFileName, in);
1007                 in >> numFlows;
1008                 m->gobble(in);
1009                 unsigned long int spot = in.tellg();
1010                 filePos[0] = spot;
1011                 in.close();
1012                 
1013                 processors = (filePos.size() - 1);
1014                 
1015                 return filePos; 
1016         }
1017         catch(exception& e) {
1018                 m->errorOut(e, "TrimSeqsCommand", "getFlowFileBreaks");
1019                 exit(1);
1020         }
1021 }
1022
1023 /**************************************************************************************************/
1024
1025 int TrimFlowsCommand::createProcessesCreateTrim(string flowFileName, string trimFlowFileName, string scrapFlowFileName, string fastaFileName, vector<vector<string> > barcodePrimerComboFileNames){
1026
1027         try {
1028 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
1029                 int process = 1;
1030                 int exitCommand = 1;
1031                 processIDS.clear();
1032                 
1033                 //loop through and create all the processes you want
1034                 while (process != processors) {
1035                         int pid = fork();
1036                         
1037                         if (pid > 0) {
1038                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
1039                                 process++;
1040                         }else if (pid == 0){
1041                                 
1042                                 vector<vector<string> > tempBarcodePrimerComboFileNames = barcodePrimerComboFileNames;
1043                                 if(allFiles){
1044                                         for(int i=0;i<tempBarcodePrimerComboFileNames.size();i++){
1045                                                 for(int j=0;j<tempBarcodePrimerComboFileNames[0].size();j++){
1046                                                         tempBarcodePrimerComboFileNames[i][j] += toString(getpid()) + ".temp";
1047                                                         ofstream temp;
1048                                                         m->openOutputFile(tempBarcodePrimerComboFileNames[i][j], temp);
1049                                                         temp.close();
1050                                                         
1051                                                 }
1052                                         }
1053                                 }
1054                                 driverCreateTrim(flowFileName,
1055                                                                  (trimFlowFileName + toString(getpid()) + ".temp"),
1056                                                                  (scrapFlowFileName + toString(getpid()) + ".temp"),
1057                                                                  (fastaFileName + toString(getpid()) + ".temp"),
1058                                                                  tempBarcodePrimerComboFileNames, lines[process]);
1059
1060                                 exit(0);
1061                         }else { 
1062                                 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); 
1063                                 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
1064                                 exit(0);
1065                         }
1066                 }
1067                 
1068                 //parent do my part
1069                 ofstream temp;
1070                 m->openOutputFile(trimFlowFileName, temp);
1071                 temp.close();
1072
1073                 m->openOutputFile(scrapFlowFileName, temp);
1074                 temp.close();
1075                 
1076                 if(fasta){
1077                         m->openOutputFile(fastaFileName, temp);
1078                         temp.close();
1079                 }
1080                 
1081                 driverCreateTrim(flowFileName, trimFlowFileName, scrapFlowFileName, fastaFileName, barcodePrimerComboFileNames, lines[0]);
1082
1083                 //force parent to wait until all the processes are done
1084                 for (int i=0;i<processIDS.size();i++) { 
1085                         int temp = processIDS[i];
1086                         wait(&temp);
1087                 }
1088                 
1089                 //append files
1090                 m->mothurOutEndLine();
1091                 for(int i=0;i<processIDS.size();i++){
1092                         
1093                         m->mothurOut("Appending files from process " + toString(processIDS[i])); m->mothurOutEndLine();
1094                         
1095                         m->appendFiles((trimFlowFileName + toString(processIDS[i]) + ".temp"), trimFlowFileName);
1096                         remove((trimFlowFileName + toString(processIDS[i]) + ".temp").c_str());
1097 //                      m->mothurOut("\tDone with trim.flow file"); m->mothurOutEndLine();
1098
1099                         m->appendFiles((scrapFlowFileName + toString(processIDS[i]) + ".temp"), scrapFlowFileName);
1100                         remove((scrapFlowFileName + toString(processIDS[i]) + ".temp").c_str());
1101 //                      m->mothurOut("\tDone with scrap.flow file"); m->mothurOutEndLine();
1102
1103                         if(fasta){
1104                                 m->appendFiles((fastaFileName + toString(processIDS[i]) + ".temp"), fastaFileName);
1105                                 remove((fastaFileName + toString(processIDS[i]) + ".temp").c_str());
1106 //                              m->mothurOut("\tDone with flow.fasta file"); m->mothurOutEndLine();
1107                         }
1108                         if(allFiles){                                           
1109                                 for (int j = 0; j < barcodePrimerComboFileNames.size(); j++) {
1110                                         for (int k = 0; k < barcodePrimerComboFileNames[0].size(); k++) {
1111                                                 m->appendFiles((barcodePrimerComboFileNames[j][k] + toString(processIDS[i]) + ".temp"), barcodePrimerComboFileNames[j][k]);
1112                                                 remove((barcodePrimerComboFileNames[j][k] + toString(processIDS[i]) + ".temp").c_str());
1113                                         }
1114                                 }
1115                         }
1116                 }
1117                 
1118                 return exitCommand;
1119 #endif          
1120         }
1121         catch(exception& e) {
1122                 m->errorOut(e, "TrimFlowsCommand", "createProcessesCreateTrim");
1123                 exit(1);
1124         }
1125 }
1126
1127 //***************************************************************************************************************