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