]> git.donarmstrong.com Git - mothur.git/blob - trimflowscommand.cpp
added flow file to sort.seqs. added setName and setScores functions to Quality Scores...
[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::setParameters(){       
16         try {
17                 CommandParameter pflow("flow", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(pflow);
18                 CommandParameter poligos("oligos", "InputTypes", "", "", "none", "none", "none",false,false); parameters.push_back(poligos);
19                 CommandParameter pmaxhomop("maxhomop", "Number", "", "9", "", "", "",false,false); parameters.push_back(pmaxhomop);
20                 CommandParameter pmaxflows("maxflows", "Number", "", "450", "", "", "",false,false); parameters.push_back(pmaxflows);
21                 CommandParameter pminflows("minflows", "Number", "", "450", "", "", "",false,false); parameters.push_back(pminflows);
22                 CommandParameter ppdiffs("pdiffs", "Number", "", "0", "", "", "",false,false); parameters.push_back(ppdiffs);
23                 CommandParameter pbdiffs("bdiffs", "Number", "", "0", "", "", "",false,false); parameters.push_back(pbdiffs);
24                 CommandParameter ptdiffs("tdiffs", "Number", "", "0", "", "", "",false,false); parameters.push_back(ptdiffs);
25                 CommandParameter pprocessors("processors", "Number", "", "1", "", "", "",false,false); parameters.push_back(pprocessors);
26                 CommandParameter psignal("signal", "Number", "", "0.50", "", "", "",false,false); parameters.push_back(psignal);
27                 CommandParameter pnoise("noise", "Number", "", "0.70", "", "", "",false,false); parameters.push_back(pnoise);
28                 CommandParameter pallfiles("allfiles", "Boolean", "", "t", "", "", "",false,false); parameters.push_back(pallfiles);
29                 CommandParameter porder("order", "String", "", "", "", "", "",false,false); parameters.push_back(porder);
30                 CommandParameter pfasta("fasta", "Boolean", "", "F", "", "", "",false,false); parameters.push_back(pfasta);
31                 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "",false,false); parameters.push_back(pinputdir);
32                 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "",false,false); parameters.push_back(poutputdir);
33                 
34                 vector<string> myArray;
35                 for (int i = 0; i < parameters.size(); i++) {   myArray.push_back(parameters[i].name);          }
36                 return myArray;
37         }
38         catch(exception& e) {
39                 m->errorOut(e, "TrimFlowsCommand", "setParameters");
40                 exit(1);
41         }
42 }
43 //**********************************************************************************************************************
44 string TrimFlowsCommand::getHelpString(){       
45         try {
46                 string helpString = "";
47                 helpString += "The trim.flows command reads a flowgram file and creates .....\n";
48                 helpString += "Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFasta).\n";
49                 helpString += "For more details please check out the wiki http://www.mothur.org/wiki/Trim.flows.\n";
50                 return helpString;
51         }
52         catch(exception& e) {
53                 m->errorOut(e, "TrimFlowsCommand", "getHelpString");
54                 exit(1);
55         }
56 }
57
58 //**********************************************************************************************************************
59
60 TrimFlowsCommand::TrimFlowsCommand(){   
61         try {
62                 abort = true; calledHelp = true; 
63                 setParameters();
64                 vector<string> tempOutNames;
65                 outputTypes["flow"] = tempOutNames;
66                 outputTypes["fasta"] = tempOutNames;
67         }
68         catch(exception& e) {
69                 m->errorOut(e, "TrimFlowsCommand", "TrimFlowsCommand");
70                 exit(1);
71         }
72 }
73 //**********************************************************************************************************************
74
75 TrimFlowsCommand::TrimFlowsCommand(string option)  {
76         try {
77                 
78                 abort = false; calledHelp = false;   
79                 comboStarts = 0;
80                 
81                 //allow user to run help
82                 if(option == "help") { help(); abort = true; calledHelp = true; }
83                 else if(option == "citation") { citation(); 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                         
128                         
129                         //check for required parameters
130                         flowFileName = validParameter.validFile(parameters, "flow", true);
131                         if (flowFileName == "not found") { 
132                                 flowFileName = m->getFlowFile(); 
133                                 if (flowFileName != "") {  m->mothurOut("Using " + flowFileName + " as input file for the flow parameter."); m->mothurOutEndLine(); }
134                                 else { 
135                                         m->mothurOut("No valid current flow file. You must provide a flow file."); m->mothurOutEndLine(); 
136                                         abort = true;
137                                 } 
138                         }else if (flowFileName == "not open") { flowFileName = ""; abort = true; }      
139                         
140                         //if the user changes the output directory command factory will send this info to us in the output parameter 
141                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  
142                                 outputDir = ""; 
143                                 outputDir += m->hasPath(flowFileName); //if user entered a file with a path then preserve it    
144                         }
145                         
146                         
147                         //check for optional parameter and set defaults
148                         // ...at some point should added some additional type checking...
149                         
150                         string temp;
151                         temp = validParameter.validFile(parameters, "minflows", false); if (temp == "not found") { temp = "450"; }
152                         m->mothurConvert(temp, minFlows);  
153
154                         temp = validParameter.validFile(parameters, "maxflows", false); if (temp == "not found") { temp = "450"; }
155                         m->mothurConvert(temp, maxFlows);  
156                         
157                         
158                         temp = validParameter.validFile(parameters, "oligos", true);
159                         if (temp == "not found")        {       oligoFileName = "";             }
160                         else if(temp == "not open")     {       abort = true;                   } 
161                         else                                            {       oligoFileName = temp;   m->setOligosFile(oligoFileName); }
162                         
163                         temp = validParameter.validFile(parameters, "fasta", false);            if (temp == "not found"){       fasta = 0;              }
164                         else if(m->isTrue(temp))        {       fasta = 1;      }
165                         
166                         temp = validParameter.validFile(parameters, "maxhomop", false);         if (temp == "not found"){       temp = "9";             }
167                         m->mothurConvert(temp, maxHomoP);  
168
169                         temp = validParameter.validFile(parameters, "signal", false);           if (temp == "not found"){       temp = "0.50";  }
170                         m->mothurConvert(temp, signal);  
171
172                         temp = validParameter.validFile(parameters, "noise", false);            if (temp == "not found"){       temp = "0.70";  }
173                         m->mothurConvert(temp, noise);  
174         
175                         temp = validParameter.validFile(parameters, "bdiffs", false);           if (temp == "not found"){       temp = "0";             }
176                         m->mothurConvert(temp, bdiffs);
177                         
178                         temp = validParameter.validFile(parameters, "pdiffs", false);           if (temp == "not found"){       temp = "0";             }
179                         m->mothurConvert(temp, pdiffs);
180                         
181                         temp = validParameter.validFile(parameters, "tdiffs", false);
182                         if (temp == "not found"){ int tempTotal = pdiffs + bdiffs;  temp = toString(tempTotal); }
183                         m->mothurConvert(temp, tdiffs);
184                         if(tdiffs == 0){        tdiffs = bdiffs + pdiffs;       }
185                         
186                         temp = validParameter.validFile(parameters, "processors", false);       if (temp == "not found"){       temp = m->getProcessors();      }
187                         m->setProcessors(temp);
188                         m->mothurConvert(temp, processors);
189         
190                         flowOrder = validParameter.validFile(parameters, "order", false);
191                         if (flowOrder == "not found"){ flowOrder = "TACG";              }
192                         else if(flowOrder.length() != 4){
193                                 m->mothurOut("The value of the order option must be four bases long\n");
194                         }
195
196                         if(oligoFileName == "") {       allFiles = 0;           }
197                         else                                    {       allFiles = 1;           }
198
199                         numFPrimers = 0;
200                         numRPrimers = 0;
201                 }
202                 
203         }
204         catch(exception& e) {
205                 m->errorOut(e, "TrimFlowsCommand", "TrimFlowsCommand");
206                 exit(1);
207         }
208 }
209
210 //***************************************************************************************************************
211
212 int TrimFlowsCommand::execute(){
213         try{
214                 
215                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
216
217                 string trimFlowFileName = outputDir + m->getRootName(m->getSimpleName(flowFileName)) + "trim.flow";
218                 outputNames.push_back(trimFlowFileName); outputTypes["flow"].push_back(trimFlowFileName);
219                 
220                 string scrapFlowFileName = outputDir + m->getRootName(m->getSimpleName(flowFileName)) + "scrap.flow";
221                 outputNames.push_back(scrapFlowFileName); outputTypes["flow"].push_back(scrapFlowFileName);
222
223                 string fastaFileName = outputDir + m->getRootName(m->getSimpleName(flowFileName)) + "flow.fasta";
224                 if(fasta){
225                         outputNames.push_back(fastaFileName); outputTypes["fasta"].push_back(fastaFileName);
226                 }
227                 
228                 vector<unsigned long long> flowFilePos;
229         #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
230                 flowFilePos = getFlowFileBreaks();
231                 for (int i = 0; i < (flowFilePos.size()-1); i++) {
232                         lines.push_back(new linePair(flowFilePos[i], flowFilePos[(i+1)]));
233                 }       
234         #else
235                 ifstream in; m->openInputFile(flowFileName, in); in >> numFlows; in.close();
236         ///////////////////////////////////////// until I fix multiple processors for windows //////////////////        
237                 processors = 1;
238         ///////////////////////////////////////// until I fix multiple processors for windows //////////////////                
239                 if (processors == 1) {
240                         lines.push_back(new linePair(0, 1000));
241                 }else {
242                         int numFlowLines;
243                         flowFilePos = m->setFilePosEachLine(flowFileName, numFlowLines);
244                         flowFilePos.erase(flowFilePos.begin() + 1); numFlowLines--;
245                         
246                         //figure out how many sequences you have to process
247                         int numSeqsPerProcessor = numFlowLines / processors;
248                         cout << numSeqsPerProcessor << '\t' << numFlowLines << endl;
249                         for (int i = 0; i < processors; i++) {
250                                 int startIndex =  i * numSeqsPerProcessor;
251                                 if(i == (processors - 1)){      numSeqsPerProcessor = numFlowLines - i * numSeqsPerProcessor;   }
252                                 lines.push_back(new linePair(flowFilePos[startIndex], numSeqsPerProcessor));
253                                 cout << flowFilePos[startIndex] << '\t' << numSeqsPerProcessor << endl;
254                         }
255                 }
256         #endif
257                 
258                 vector<vector<string> > barcodePrimerComboFileNames;
259                 if(oligoFileName != ""){
260                         getOligos(barcodePrimerComboFileNames); 
261                 }
262                 
263                 if(processors == 1){
264                         driverCreateTrim(flowFileName, trimFlowFileName, scrapFlowFileName, fastaFileName, barcodePrimerComboFileNames, lines[0]);
265                 }else{
266                         createProcessesCreateTrim(flowFileName, trimFlowFileName, scrapFlowFileName, fastaFileName, barcodePrimerComboFileNames); 
267                 }       
268                 
269                 if (m->control_pressed) {  return 0; }                  
270                 
271                 string flowFilesFileName;
272                 ofstream output;
273                 
274                 if(allFiles){
275                         set<string> namesAlreadyProcessed;
276                         flowFilesFileName = outputDir + m->getRootName(m->getSimpleName(flowFileName)) + "flow.files";
277                         m->openOutputFile(flowFilesFileName, output);
278
279                         for(int i=0;i<barcodePrimerComboFileNames.size();i++){
280                                 for(int j=0;j<barcodePrimerComboFileNames[0].size();j++){
281                                         if (namesAlreadyProcessed.count(barcodePrimerComboFileNames[i][j]) == 0) {
282                                                 FILE * pFile;
283                                                 unsigned long long size;
284                                                 
285                                                 //get num bytes in file
286                                                 pFile = fopen (barcodePrimerComboFileNames[i][j].c_str(),"rb");
287                                                 if (pFile==NULL) perror ("Error opening file");
288                                                 else{
289                                                         fseek (pFile, 0, SEEK_END);
290                                                         size=ftell(pFile);
291                                                         fclose (pFile);
292                                                 }
293                                                 
294                                                 if(size < 10){
295                                                         m->mothurRemove(barcodePrimerComboFileNames[i][j]);
296                                                 }
297                                                 else{
298                                                         output << m->getFullPathName(barcodePrimerComboFileNames[i][j]) << endl;
299                                                         outputNames.push_back(barcodePrimerComboFileNames[i][j]);
300                                                         outputTypes["flow"].push_back(barcodePrimerComboFileNames[i][j]);
301                                                 }
302                                                 namesAlreadyProcessed.insert(barcodePrimerComboFileNames[i][j]);
303                                         }
304                                 }
305                         }
306                         output.close();
307                 }
308                 else{
309                         flowFilesFileName = outputDir + m->getRootName(m->getSimpleName(flowFileName)) + "flow.files";
310                         m->openOutputFile(flowFilesFileName, output);
311                         
312                         output << m->getFullPathName(trimFlowFileName) << endl;
313                         
314                         output.close();
315                 }
316                 outputTypes["flow.files"].push_back(flowFilesFileName);
317                 outputNames.push_back(flowFilesFileName);
318                 
319 //              set fasta file as new current fastafile
320 //              string current = "";
321 //              itTypes = outputTypes.find("fasta");
322 //              if (itTypes != outputTypes.end()) {
323 //                      if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setFastaFile(current); }
324 //              }
325                 
326                 m->mothurOutEndLine();
327                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
328                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }
329                 m->mothurOutEndLine();
330                 
331                 return 0;       
332         }
333         catch(exception& e) {
334                 m->errorOut(e, "TrimSeqsCommand", "execute");
335                 exit(1);
336         }
337 }
338
339 //***************************************************************************************************************
340
341 int TrimFlowsCommand::driverCreateTrim(string flowFileName, string trimFlowFileName, string scrapFlowFileName, string fastaFileName, vector<vector<string> > thisBarcodePrimerComboFileNames, linePair* line){
342         
343         try {
344                 ofstream trimFlowFile;
345                 m->openOutputFile(trimFlowFileName, trimFlowFile);
346                 trimFlowFile.setf(ios::fixed, ios::floatfield); trimFlowFile.setf(ios::showpoint);
347
348                 ofstream scrapFlowFile;
349                 m->openOutputFile(scrapFlowFileName, scrapFlowFile);
350                 scrapFlowFile.setf(ios::fixed, ios::floatfield); scrapFlowFile.setf(ios::showpoint);
351                 
352                 ofstream fastaFile;
353                 if(fasta){      m->openOutputFile(fastaFileName, fastaFile);    }
354                 
355                 ifstream flowFile;
356                 m->openInputFile(flowFileName, flowFile);
357                 
358                 flowFile.seekg(line->start);
359                 
360                 if(line->start == 0){
361                         flowFile >> numFlows; m->gobble(flowFile);
362                         scrapFlowFile << maxFlows << endl;
363                         trimFlowFile << maxFlows << endl;
364                         if(allFiles){
365                                 for(int i=0;i<thisBarcodePrimerComboFileNames.size();i++){
366                                         for(int j=0;j<thisBarcodePrimerComboFileNames[0].size();j++){
367                                                 ofstream temp;
368                                                 m->openOutputFile(thisBarcodePrimerComboFileNames[i][j], temp);
369                                                 temp << maxFlows << endl;
370                                                 temp.close();
371                                         }
372                                 }                       
373                         }
374                 }
375                 
376                 FlowData flowData(numFlows, signal, noise, maxHomoP, flowOrder);
377                 //cout << " driver flowdata address " <<  &flowData  << &flowFile << endl;      
378                 int count = 0;
379                 bool moreSeqs = 1;
380                 
381                 TrimOligos trimOligos(pdiffs, bdiffs, primers, barcodes, revPrimer);
382                 
383                 while(moreSeqs) {
384                         //cout << "driver " << count << endl;
385                         
386         
387                         if (m->control_pressed) { break; }
388                         
389                         int success = 1;
390                         int currentSeqDiffs = 0;
391                         string trashCode = "";
392                         
393                         flowData.getNext(flowFile); 
394                         //cout << "driver good bit " << flowFile.good() << endl;        
395                         flowData.capFlows(maxFlows);    
396                         
397                         Sequence currSeq = flowData.getSequence();
398                         
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                         int primerIndex = 0;
405                         int barcodeIndex = 0;
406                         
407                         if(barcodes.size() != 0){
408                                 success = trimOligos.stripBarcode(currSeq, barcodeIndex);
409                                 if(success > bdiffs)            {       trashCode += 'b';       }
410                                 else{ currentSeqDiffs += success;  }
411                         }
412                         
413                         if(numFPrimers != 0){
414                                 success = trimOligos.stripForward(currSeq, primerIndex);
415                                 if(success > pdiffs)            {       trashCode += 'f';       }
416                                 else{ currentSeqDiffs += success;  }
417                         }
418                         
419                         if (currentSeqDiffs > tdiffs)   {       trashCode += 't';   }
420                         
421                         if(numRPrimers != 0){
422                                 success = trimOligos.stripReverse(currSeq);
423                                 if(!success)                            {       trashCode += 'r';       }
424                         }
425                         
426                         if(trashCode.length() == 0){
427                                                         
428                                 flowData.printFlows(trimFlowFile);
429                         
430                                 if(fasta)       {       currSeq.printSequence(fastaFile);       }
431                                 
432                                 if(allFiles){
433                                         ofstream output;
434                                         m->openOutputFileAppend(thisBarcodePrimerComboFileNames[barcodeIndex][primerIndex], output);
435                                         output.setf(ios::fixed, ios::floatfield); trimFlowFile.setf(ios::showpoint);
436                                         
437                                         flowData.printFlows(output);
438                                         output.close();
439                                 }                               
440                         }
441                         else{
442                                 flowData.printFlows(scrapFlowFile, trashCode);
443                         }
444                                 
445                         count++;
446                         //cout << "driver" << '\t' << currSeq.getName() << endl;                        
447                         //report progress
448                         if((count) % 10000 == 0){       m->mothurOut(toString(count)); m->mothurOutEndLine();           }
449
450 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
451                         unsigned long long pos = flowFile.tellg();
452
453                         if ((pos == -1) || (pos >= line->end)) { break; }
454 #else
455                         if (flowFile.eof()) { break; }
456 #endif
457                         
458                 }
459                 //report progress
460                 if((count) % 10000 != 0){       m->mothurOut(toString(count)); m->mothurOutEndLine();           }
461                 
462                 trimFlowFile.close();
463                 scrapFlowFile.close();
464                 flowFile.close();
465                 if(fasta){      fastaFile.close();      }
466                 
467                 return count;
468         }
469         catch(exception& e) {
470                 m->errorOut(e, "TrimSeqsCommand", "driverCreateTrim");
471                 exit(1);
472         }
473 }
474
475 //***************************************************************************************************************
476
477 void TrimFlowsCommand::getOligos(vector<vector<string> >& outFlowFileNames){
478         try {
479                 ifstream oligosFile;
480                 m->openInputFile(oligoFileName, oligosFile);
481                 
482                 string type, oligo, group;
483
484                 int indexPrimer = 0;
485                 int indexBarcode = 0;
486                 
487                 while(!oligosFile.eof()){
488                 
489                         oligosFile >> type; m->gobble(oligosFile);      //get the first column value of the row - is it a comment or a feature we are interested in?
490
491                         if(type[0] == '#'){     //igore the line because there's a comment
492                                 while (!oligosFile.eof())       {       char c = oligosFile.get(); if (c == 10 || c == 13){     break;  }       } // get rest of line if there's any crap there
493                         }
494                         else{                           //there's a feature we're interested in
495
496                                 for(int i=0;i<type.length();i++){       type[i] = toupper(type[i]);  }                                  //make type case insensitive
497
498                                 oligosFile >> oligo;    //get the DNA sequence for the feature
499
500                                 for(int i=0;i<oligo.length();i++){      //make type case insensitive and change any U's to T's
501                                         oligo[i] = toupper(oligo[i]);
502                                         if(oligo[i] == 'U')     {       oligo[i] = 'T'; }
503                                 }
504
505                                 if(type == "FORWARD"){  //if the feature is a forward primer...
506                                         group = "";
507
508                                         while (!oligosFile.eof())       {       // get rest of line in case there is a primer name = will have the name of the primer
509                                                 char c = oligosFile.get(); 
510                                                 if (c == 10 || c == 13){        break;  }
511                                                 else if (c == 32 || c == 9){;} //space or tab
512                                                 else {  group += c;  }
513                                         } 
514
515                                         //have we seen this primer already?
516                                         map<string, int>::iterator itPrimer = primers.find(oligo);
517                                         if (itPrimer != primers.end()) { m->mothurOut("primer " + oligo + " is in your oligos file already."); m->mothurOutEndLine();  }
518
519                                         primers[oligo]=indexPrimer; indexPrimer++;
520                                         primerNameVector.push_back(group);
521
522                                 }
523                                 else if(type == "REVERSE"){
524                                         Sequence oligoRC("reverse", oligo);
525                                         oligoRC.reverseComplement();
526                                         revPrimer.push_back(oligoRC.getUnaligned());
527                                 }
528                                 else if(type == "BARCODE"){
529                                         oligosFile >> group;
530
531                                         //check for repeat barcodes
532                                         map<string, int>::iterator itBar = barcodes.find(oligo);
533                                         if (itBar != barcodes.end()) { m->mothurOut("barcode " + oligo + " is in your oligos file already."); m->mothurOutEndLine();  }
534
535                                         barcodes[oligo]=indexBarcode; indexBarcode++;
536                                         barcodeNameVector.push_back(group);
537                                 }
538                                 else{
539                                         m->mothurOut(type + " is not recognized as a valid type. Choices are forward, reverse, and barcode. Ignoring " + oligo + "."); m->mothurOutEndLine();  
540                                 }
541                         }
542
543                         m->gobble(oligosFile);
544                 }
545                 oligosFile.close();
546                 
547                 if(barcodeNameVector.size() == 0 && primerNameVector[0] == ""){ allFiles = 0;   }
548                 
549                 //add in potential combos
550                 if(barcodeNameVector.size() == 0){
551                         barcodes[""] = 0;
552                         barcodeNameVector.push_back("");                        
553                 }
554                 
555                 if(primerNameVector.size() == 0){
556                         primers[""] = 0;
557                         primerNameVector.push_back("");                 
558                 }
559                 
560                 
561                 outFlowFileNames.resize(barcodeNameVector.size());
562                 for(int i=0;i<outFlowFileNames.size();i++){
563                         outFlowFileNames[i].assign(primerNameVector.size(), "");
564                 }
565                 
566                 if(allFiles){
567
568                         for(map<string, int>::iterator itBar = barcodes.begin();itBar != barcodes.end();itBar++){
569                                 for(map<string, int>::iterator itPrimer = primers.begin();itPrimer != primers.end(); itPrimer++){
570
571                                         string primerName = primerNameVector[itPrimer->second];
572                                         string barcodeName = barcodeNameVector[itBar->second];
573                                                                                 
574                                         string comboGroupName = "";
575                                         string fileName = "";
576                                         
577                                         if(primerName == ""){
578                                                 comboGroupName = barcodeNameVector[itBar->second];
579                                                 fileName = outputDir + m->getRootName(m->getSimpleName(flowFileName)) + comboGroupName + ".flow";
580                                         }
581                                         else{
582                                                 if(barcodeName == ""){
583                                                         comboGroupName = primerNameVector[itPrimer->second];
584                                                 }
585                                                 else{
586                                                         comboGroupName = barcodeNameVector[itBar->second] + "." + primerNameVector[itPrimer->second];
587                                                 }
588                                                 fileName = outputDir + m->getRootName(m->getSimpleName(flowFileName)) + comboGroupName + ".flow";
589                                         }
590                                         
591                                         outFlowFileNames[itBar->second][itPrimer->second] = fileName;
592                                         
593                                         ofstream temp;
594                                         m->openOutputFile(fileName, temp);
595                                         temp.close();
596                                 }
597                         }
598                 }
599                 
600                 numFPrimers = primers.size();
601                 numRPrimers = revPrimer.size();
602                 
603         }
604         catch(exception& e) {
605                 m->errorOut(e, "TrimSeqsCommand", "getOligos");
606                 exit(1);
607         }
608 }
609 /**************************************************************************************************/
610 vector<unsigned long long> TrimFlowsCommand::getFlowFileBreaks() {
611
612         try{
613                         
614                 vector<unsigned long long> filePos;
615                 filePos.push_back(0);
616                                         
617                 FILE * pFile;
618                 unsigned long long size;
619                 
620                 //get num bytes in file
621                 pFile = fopen (flowFileName.c_str(),"rb");
622                 if (pFile==NULL) perror ("Error opening file");
623                 else{
624                         fseek (pFile, 0, SEEK_END);
625                         size=ftell (pFile);
626                         fclose (pFile);
627                 }
628                                 
629                 //estimate file breaks
630                 unsigned long long chunkSize = 0;
631                 chunkSize = size / processors;
632
633                 //file too small to divide by processors
634                 if (chunkSize == 0)  {  processors = 1; filePos.push_back(size); return filePos;        }
635                 
636                 //for each process seekg to closest file break and search for next '>' char. make that the filebreak
637                 for (int i = 0; i < processors; i++) {
638                         unsigned long long spot = (i+1) * chunkSize;
639                         
640                         ifstream in;
641                         m->openInputFile(flowFileName, in);
642                         in.seekg(spot);
643                         
644                         string dummy = m->getline(in);
645                         
646                         //there was not another sequence before the end of the file
647                         unsigned long long sanityPos = in.tellg();
648                         
649 //                      if (sanityPos == -1) {  break;  }
650 //                      else {  filePos.push_back(newSpot);  }
651                         if (sanityPos == -1) {  break;  }
652                         else {  filePos.push_back(sanityPos);  }
653                         
654                         in.close();
655                 }
656                 
657                 //save end pos
658                 filePos.push_back(size);
659                 
660                 //sanity check filePos
661                 for (int i = 0; i < (filePos.size()-1); i++) {
662                         if (filePos[(i+1)] <= filePos[i]) {  filePos.erase(filePos.begin()+(i+1)); i--; }
663                 }
664
665                 ifstream in;
666                 m->openInputFile(flowFileName, in);
667                 in >> numFlows;
668                 m->gobble(in);
669                 //unsigned long long spot = in.tellg();
670                 //filePos[0] = spot;
671                 in.close();
672                 
673                 processors = (filePos.size() - 1);
674                 
675                 return filePos; 
676         }
677         catch(exception& e) {
678                 m->errorOut(e, "TrimSeqsCommand", "getFlowFileBreaks");
679                 exit(1);
680         }
681 }
682
683 /**************************************************************************************************/
684
685 int TrimFlowsCommand::createProcessesCreateTrim(string flowFileName, string trimFlowFileName, string scrapFlowFileName, string fastaFileName, vector<vector<string> > barcodePrimerComboFileNames){
686
687         try {
688                 processIDS.clear();
689                 int exitCommand = 1;
690                 
691 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
692                 int process = 1;
693                 
694                 //loop through and create all the processes you want
695                 while (process != processors) {
696                         int pid = fork();
697                         
698                         if (pid > 0) {
699                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
700                                 process++;
701                         }else if (pid == 0){
702                                 
703                                 vector<vector<string> > tempBarcodePrimerComboFileNames = barcodePrimerComboFileNames;
704                                 if(allFiles){
705                                         for(int i=0;i<tempBarcodePrimerComboFileNames.size();i++){
706                                                 for(int j=0;j<tempBarcodePrimerComboFileNames[0].size();j++){
707                                                         tempBarcodePrimerComboFileNames[i][j] += toString(getpid()) + ".temp";
708                                                         ofstream temp;
709                                                         m->openOutputFile(tempBarcodePrimerComboFileNames[i][j], temp);
710                                                         temp.close();
711                                                         
712                                                 }
713                                         }
714                                 }
715                                 driverCreateTrim(flowFileName,
716                                                                  (trimFlowFileName + toString(getpid()) + ".temp"),
717                                                                  (scrapFlowFileName + toString(getpid()) + ".temp"),
718                                                                  (fastaFileName + toString(getpid()) + ".temp"),
719                                                                  tempBarcodePrimerComboFileNames, lines[process]);
720
721                                 exit(0);
722                         }else { 
723                                 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); 
724                                 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
725                                 exit(0);
726                         }
727                 }
728                 
729                 //parent do my part
730                 ofstream temp;
731                 m->openOutputFile(trimFlowFileName, temp);
732                 temp.close();
733
734                 m->openOutputFile(scrapFlowFileName, temp);
735                 temp.close();
736                 
737                 if(fasta){
738                         m->openOutputFile(fastaFileName, temp);
739                         temp.close();
740                 }
741                 
742                 driverCreateTrim(flowFileName, trimFlowFileName, scrapFlowFileName, fastaFileName, barcodePrimerComboFileNames, lines[0]);
743
744                 //force parent to wait until all the processes are done
745                 for (int i=0;i<processIDS.size();i++) { 
746                         int temp = processIDS[i];
747                         wait(&temp);
748                 }
749 #else
750                 //////////////////////////////////////////////////////////////////////////////////////////////////////
751                 //Windows version shared memory, so be careful when passing variables through the trimFlowData struct. 
752                 //Above fork() will clone, so memory is separate, but that's not the case with windows, 
753                 //////////////////////////////////////////////////////////////////////////////////////////////////////
754                 
755                 vector<trimFlowData*> pDataArray; 
756                 DWORD   dwThreadIdArray[processors-1];
757                 HANDLE  hThreadArray[processors-1]; 
758                 
759                 //Create processor worker threads.
760                 for( int i=0; i<processors-1; i++ ){
761                         // Allocate memory for thread data.
762                         string extension = "";
763                         if (i != 0) { extension = toString(i) + ".temp"; processIDS.push_back(i); }
764                         
765                         vector<vector<string> > tempBarcodePrimerComboFileNames = barcodePrimerComboFileNames;
766                         if(allFiles){
767                                 for(int i=0;i<tempBarcodePrimerComboFileNames.size();i++){
768                                         for(int j=0;j<tempBarcodePrimerComboFileNames[0].size();j++){
769                                                 tempBarcodePrimerComboFileNames[i][j] += extension;
770                                                 ofstream temp;
771                                                 m->openOutputFile(tempBarcodePrimerComboFileNames[i][j], temp);
772                                                 temp.close();
773                                                 
774                                         }
775                                 }
776                         }
777                         
778                         trimFlowData* tempflow = new trimFlowData(flowFileName, (trimFlowFileName + extension), (scrapFlowFileName + extension), fastaFileName, flowOrder, tempBarcodePrimerComboFileNames, barcodes, primers, revPrimer, fasta, allFiles, lines[i]->start, lines[i]->end, m, signal, noise, numFlows, maxFlows, minFlows, maxHomoP, tdiffs, bdiffs, pdiffs, i);
779                         pDataArray.push_back(tempflow);
780                         
781                         //MyTrimFlowThreadFunction is in header. It must be global or static to work with the threads.
782                         //default security attributes, thread function name, argument to thread function, use default creation flags, returns the thread identifier
783                         hThreadArray[i] = CreateThread(NULL, 0, MyTrimFlowThreadFunction, pDataArray[i], 0, &dwThreadIdArray[i]);   
784                 }
785                 
786                 //using the main process as a worker saves time and memory
787                 ofstream temp;
788                 m->openOutputFile(trimFlowFileName, temp);
789                 temp.close();
790                 
791                 m->openOutputFile(scrapFlowFileName, temp);
792                 temp.close();
793                 
794                 if(fasta){
795                         m->openOutputFile(fastaFileName, temp);
796                         temp.close();
797                 }
798                 
799                 vector<vector<string> > tempBarcodePrimerComboFileNames = barcodePrimerComboFileNames;
800                 if(allFiles){
801                         for(int i=0;i<tempBarcodePrimerComboFileNames.size();i++){
802                                 for(int j=0;j<tempBarcodePrimerComboFileNames[0].size();j++){
803                                         tempBarcodePrimerComboFileNames[i][j] += toString(processors-1) + ".temp";
804                                         ofstream temp;
805                                         m->openOutputFile(tempBarcodePrimerComboFileNames[i][j], temp);
806                                         temp.close();
807                                         
808                                 }
809                         }
810                 }
811                 
812                 //do my part - do last piece because windows is looking for eof
813                 int num = driverCreateTrim(flowFileName, (trimFlowFileName  + toString(processors-1) + ".temp"), (scrapFlowFileName  + toString(processors-1) + ".temp"), (fastaFileName + toString(processors-1) + ".temp"), tempBarcodePrimerComboFileNames, lines[processors-1]);
814                 processIDS.push_back((processors-1)); 
815                 
816                 //Wait until all threads have terminated.
817                 WaitForMultipleObjects(processors-1, hThreadArray, TRUE, INFINITE);
818                 
819                 //Close all thread handles and free memory allocations.
820                 for(int i=0; i < pDataArray.size(); i++){
821                         num += pDataArray[i]->count;
822                         CloseHandle(hThreadArray[i]);
823                         delete pDataArray[i];
824                 }
825                 
826                 
827 #endif  
828                 //append files
829                 m->mothurOutEndLine();
830                 for(int i=0;i<processIDS.size();i++){
831                         
832                         m->mothurOut("Appending files from process " + toString(processIDS[i])); m->mothurOutEndLine();
833                         
834                         m->appendFiles((trimFlowFileName + toString(processIDS[i]) + ".temp"), trimFlowFileName);
835                         m->mothurRemove((trimFlowFileName + toString(processIDS[i]) + ".temp"));
836 //                      m->mothurOut("\tDone with trim.flow file"); m->mothurOutEndLine();
837
838                         m->appendFiles((scrapFlowFileName + toString(processIDS[i]) + ".temp"), scrapFlowFileName);
839                         m->mothurRemove((scrapFlowFileName + toString(processIDS[i]) + ".temp"));
840 //                      m->mothurOut("\tDone with scrap.flow file"); m->mothurOutEndLine();
841
842                         if(fasta){
843                                 m->appendFiles((fastaFileName + toString(processIDS[i]) + ".temp"), fastaFileName);
844                                 m->mothurRemove((fastaFileName + toString(processIDS[i]) + ".temp"));
845 //                              m->mothurOut("\tDone with flow.fasta file"); m->mothurOutEndLine();
846                         }
847                         if(allFiles){                                           
848                                 for (int j = 0; j < barcodePrimerComboFileNames.size(); j++) {
849                                         for (int k = 0; k < barcodePrimerComboFileNames[0].size(); k++) {
850                                                 m->appendFiles((barcodePrimerComboFileNames[j][k] + toString(processIDS[i]) + ".temp"), barcodePrimerComboFileNames[j][k]);
851                                                 m->mothurRemove((barcodePrimerComboFileNames[j][k] + toString(processIDS[i]) + ".temp"));
852                                         }
853                                 }
854                         }
855                 }
856                 
857                 return exitCommand;
858         
859         }
860         catch(exception& e) {
861                 m->errorOut(e, "TrimFlowsCommand", "createProcessesCreateTrim");
862                 exit(1);
863         }
864 }
865
866 //***************************************************************************************************************