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