]> git.donarmstrong.com Git - mothur.git/blob - classifyseqscommand.cpp
cluster.split fix
[mothur.git] / classifyseqscommand.cpp
1 /*
2  *  classifyseqscommand.cpp
3  *  Mothur
4  *
5  *  Created by westcott on 11/2/09.
6  *  Copyright 2009 Schloss Lab. All rights reserved.
7  *
8  */
9
10 #include "classifyseqscommand.h"
11 #include "sequence.hpp"
12 #include "bayesian.h"
13 #include "phylotree.h"
14 #include "phylosummary.h"
15 #include "knn.h"
16
17
18 //**********************************************************************************************************************
19 vector<string> ClassifySeqsCommand::getValidParameters(){       
20         try {
21                 string AlignArray[] =  {"template","fasta","name","group","search","ksize","method","processors","taxonomy","match","mismatch","gapopen","gapextend","numwanted","cutoff","probs","iters", "outputdir","inputdir"};
22                 vector<string> myArray (AlignArray, AlignArray+(sizeof(AlignArray)/sizeof(string)));
23                 return myArray;
24         }
25         catch(exception& e) {
26                 m->errorOut(e, "ClassifySeqsCommand", "getValidParameters");
27                 exit(1);
28         }
29 }
30 //**********************************************************************************************************************
31 ClassifySeqsCommand::ClassifySeqsCommand(){     
32         try {
33                 abort = true;
34                 //initialize outputTypes
35                 vector<string> tempOutNames;
36                 outputTypes["taxonomy"] = tempOutNames;
37                 outputTypes["taxsummary"] = tempOutNames;
38                 outputTypes["matchdist"] = tempOutNames;
39         }
40         catch(exception& e) {
41                 m->errorOut(e, "ClassifySeqsCommand", "ClassifySeqsCommand");
42                 exit(1);
43         }
44 }
45 //**********************************************************************************************************************
46 vector<string> ClassifySeqsCommand::getRequiredParameters(){    
47         try {
48                 string Array[] =  {"fasta","template","taxonomy"};
49                 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
50                 return myArray;
51         }
52         catch(exception& e) {
53                 m->errorOut(e, "ClassifySeqsCommand", "getRequiredParameters");
54                 exit(1);
55         }
56 }
57 //**********************************************************************************************************************
58 vector<string> ClassifySeqsCommand::getRequiredFiles(){ 
59         try {
60                 vector<string> myArray;
61                 return myArray;
62         }
63         catch(exception& e) {
64                 m->errorOut(e, "ClassifySeqsCommand", "getRequiredFiles");
65                 exit(1);
66         }
67 }
68 //**********************************************************************************************************************
69 ClassifySeqsCommand::ClassifySeqsCommand(string option)  {
70         try {
71                 abort = false;
72                 
73                 //allow user to run help
74                 if(option == "help") { help(); abort = true; }
75                 
76                 else {
77                         
78                         //valid paramters for this command
79                         string AlignArray[] =  {"template","fasta","name","group","search","ksize","method","processors","taxonomy","match","mismatch","gapopen","gapextend","numwanted","cutoff","probs","iters", "outputdir","inputdir"};
80                         vector<string> myArray (AlignArray, AlignArray+(sizeof(AlignArray)/sizeof(string)));
81                         
82                         OptionParser parser(option);
83                         map<string, string> parameters = parser.getParameters(); 
84                         
85                         ValidParameters validParameter("classify.seqs");
86                         map<string, string>::iterator it;
87                         
88                         //check to make sure all parameters are valid for command
89                         for (it = parameters.begin(); it != parameters.end(); it++) { 
90                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
91                         }
92                         
93                         //initialize outputTypes
94                         vector<string> tempOutNames;
95                         outputTypes["taxonomy"] = tempOutNames;
96                         outputTypes["taxsummary"] = tempOutNames;
97                         outputTypes["matchdist"] = tempOutNames;
98                         
99                         //if the user changes the output directory command factory will send this info to us in the output parameter 
100                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  outputDir = "";         }
101                         
102                         //if the user changes the input directory command factory will send this info to us in the output parameter 
103                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
104                         if (inputDir == "not found"){   inputDir = "";          }
105                         else {
106                                 string path;
107                                 it = parameters.find("template");
108                                 //user has given a template file
109                                 if(it != parameters.end()){ 
110                                         path = m->hasPath(it->second);
111                                         //if the user has not given a path then, add inputdir. else leave path alone.
112                                         if (path == "") {       parameters["template"] = inputDir + it->second;         }
113                                 }
114                                 
115                                 it = parameters.find("taxonomy");
116                                 //user has given a template file
117                                 if(it != parameters.end()){ 
118                                         path = m->hasPath(it->second);
119                                         //if the user has not given a path then, add inputdir. else leave path alone.
120                                         if (path == "") {       parameters["taxonomy"] = inputDir + it->second;         }
121                                 }
122                                 
123                                 it = parameters.find("group");
124                                 //user has given a template file
125                                 if(it != parameters.end()){ 
126                                         path = m->hasPath(it->second);
127                                         //if the user has not given a path then, add inputdir. else leave path alone.
128                                         if (path == "") {       parameters["group"] = inputDir + it->second;            }
129                                 }
130                         }
131
132                         //check for required parameters
133                         templateFileName = validParameter.validFile(parameters, "template", true);
134                         if (templateFileName == "not found") { 
135                                 m->mothurOut("template is a required parameter for the classify.seqs command."); 
136                                 m->mothurOutEndLine();
137                                 abort = true; 
138                         }
139                         else if (templateFileName == "not open") { abort = true; }      
140                         
141                                                 
142                         fastaFileName = validParameter.validFile(parameters, "fasta", false);
143                         if (fastaFileName == "not found") { m->mothurOut("fasta is a required parameter for the classify.seqs command."); m->mothurOutEndLine(); abort = true;  }
144                         else { 
145                                 m->splitAtDash(fastaFileName, fastaFileNames);
146                                 
147                                 //go through files and make sure they are good, if not, then disregard them
148                                 for (int i = 0; i < fastaFileNames.size(); i++) {
149                                         if (inputDir != "") {
150                                                 string path = m->hasPath(fastaFileNames[i]);
151                                                 //if the user has not given a path then, add inputdir. else leave path alone.
152                                                 if (path == "") {       fastaFileNames[i] = inputDir + fastaFileNames[i];               }
153                                         }
154                                         
155                                         int ableToOpen;
156                                         
157                                         ifstream in;
158                                         ableToOpen = m->openInputFile(fastaFileNames[i], in, "noerror");
159                                 
160                                         //if you can't open it, try default location
161                                         if (ableToOpen == 1) {
162                                                 if (m->getDefaultPath() != "") { //default path is set
163                                                         string tryPath = m->getDefaultPath() + m->getSimpleName(fastaFileNames[i]);
164                                                         m->mothurOut("Unable to open " + fastaFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
165                                                         ifstream in2;
166                                                         ableToOpen = m->openInputFile(tryPath, in2, "noerror");
167                                                         in2.close();
168                                                         fastaFileNames[i] = tryPath;
169                                                 }
170                                         }
171                                         
172                                         if (ableToOpen == 1) {
173                                                 if (m->getOutputDir() != "") { //default path is set
174                                                         string tryPath = m->getOutputDir() + m->getSimpleName(fastaFileNames[i]);
175                                                         m->mothurOut("Unable to open " + fastaFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
176                                                         ifstream in2;
177                                                         ableToOpen = m->openInputFile(tryPath, in2, "noerror");
178                                                         in2.close();
179                                                         fastaFileNames[i] = tryPath;
180                                                 }
181                                         }
182                                         
183                                         in.close();
184                                         
185                                         if (ableToOpen == 1) { 
186                                                 m->mothurOut("Unable to open " + fastaFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine(); 
187                                                 //erase from file list
188                                                 fastaFileNames.erase(fastaFileNames.begin()+i);
189                                                 i--;
190                                         }
191                                         
192                                 }
193                                 
194                                 //make sure there is at least one valid file left
195                                 if (fastaFileNames.size() == 0) { m->mothurOut("no valid files."); m->mothurOutEndLine(); abort = true; }
196                         }
197
198                         
199                         taxonomyFileName = validParameter.validFile(parameters, "taxonomy", true);
200                         if (taxonomyFileName == "not found") { 
201                                 m->mothurOut("taxonomy is a required parameter for the classify.seqs command."); 
202                                 m->mothurOutEndLine();
203                                 abort = true; 
204                         }
205                         else if (taxonomyFileName == "not open") { abort = true; }      
206                         
207                         
208                         namefile = validParameter.validFile(parameters, "name", false);
209                         if (namefile == "not found") { namefile = "";  }
210
211                         else { 
212                                 m->splitAtDash(namefile, namefileNames);
213                                 
214                                 //go through files and make sure they are good, if not, then disregard them
215                                 for (int i = 0; i < namefileNames.size(); i++) {
216                                         if (inputDir != "") {
217                                                 string path = m->hasPath(namefileNames[i]);
218                                                 //if the user has not given a path then, add inputdir. else leave path alone.
219                                                 if (path == "") {       namefileNames[i] = inputDir + namefileNames[i];         }
220                                         }
221                                         int ableToOpen;
222                                         
223                                         ifstream in;
224                                         ableToOpen = m->openInputFile(namefileNames[i], in, "noerror");
225                                 
226                                         //if you can't open it, try default location
227                                         if (ableToOpen == 1) {
228                                                 if (m->getDefaultPath() != "") { //default path is set
229                                                         string tryPath = m->getDefaultPath() + m->getSimpleName(namefileNames[i]);
230                                                         m->mothurOut("Unable to open " + namefileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
231                                                         ifstream in2;
232                                                         ableToOpen = m->openInputFile(tryPath, in2, "noerror");
233                                                         in2.close();
234                                                         namefileNames[i] = tryPath;
235                                                 }
236                                         }
237                                         
238                                         if (ableToOpen == 1) {
239                                                 if (m->getOutputDir() != "") { //default path is set
240                                                         string tryPath = m->getOutputDir() + m->getSimpleName(namefileNames[i]);
241                                                         m->mothurOut("Unable to open " + namefileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
242                                                         ifstream in2;
243                                                         ableToOpen = m->openInputFile(tryPath, in2, "noerror");
244                                                         in2.close();
245                                                         namefileNames[i] = tryPath;
246                                                 }
247                                         }
248                                         in.close();
249                                         
250                                         if (ableToOpen == 1) { 
251                                                 m->mothurOut("Unable to open " + namefileNames[i] + ". It will be disregarded."); m->mothurOutEndLine();  abort = true;
252                                                 //erase from file list
253                                                 namefileNames.erase(namefileNames.begin()+i);
254                                                 i--;
255                                         }
256
257                                 }
258                         }
259
260                         if (namefile != "") {
261                                 if (namefileNames.size() != fastaFileNames.size()) { abort = true; m->mothurOut("If you provide a name file, you must have one for each fasta file."); m->mothurOutEndLine(); }
262                         }
263                         
264                         groupfile = validParameter.validFile(parameters, "group", false);
265                         if (groupfile == "not found") { groupfile = "";  }
266                         else { 
267                                 m->splitAtDash(groupfile, groupfileNames);
268                                 
269                                 //go through files and make sure they are good, if not, then disregard them
270                                 for (int i = 0; i < groupfileNames.size(); i++) {
271                                         if (inputDir != "") {
272                                                 string path = m->hasPath(groupfileNames[i]);
273                                                 //if the user has not given a path then, add inputdir. else leave path alone.
274                                                 if (path == "") {       groupfileNames[i] = inputDir + groupfileNames[i];               }
275                                         }
276                                         int ableToOpen;
277                                         
278                                         ifstream in;
279                                         ableToOpen = m->openInputFile(groupfileNames[i], in, "noerror");
280                                 
281                                         //if you can't open it, try default location
282                                         if (ableToOpen == 1) {
283                                                 if (m->getDefaultPath() != "") { //default path is set
284                                                         string tryPath = m->getDefaultPath() + m->getSimpleName(groupfileNames[i]);
285                                                         m->mothurOut("Unable to open " + groupfileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
286                                                         ifstream in2;
287                                                         ableToOpen = m->openInputFile(tryPath, in2, "noerror");
288                                                         in2.close();
289                                                         groupfileNames[i] = tryPath;
290                                                 }
291                                         }
292                                         
293                                         if (ableToOpen == 1) {
294                                                 if (m->getOutputDir() != "") { //default path is set
295                                                         string tryPath = m->getOutputDir() + m->getSimpleName(groupfileNames[i]);
296                                                         m->mothurOut("Unable to open " + groupfileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
297                                                         ifstream in2;
298                                                         ableToOpen = m->openInputFile(tryPath, in2, "noerror");
299                                                         in2.close();
300                                                         groupfileNames[i] = tryPath;
301                                                 }
302                                         }
303                                         
304                                         in.close();
305                                         
306                                         if (ableToOpen == 1) { 
307                                                 m->mothurOut("Unable to open " + groupfileNames[i] + ". It will be disregarded."); m->mothurOutEndLine(); groupfileNames[i] = "";
308                                                 //erase from file list
309                                                 groupfileNames.erase(groupfileNames.begin()+i);
310                                                 i--;
311                                         }
312                                 }
313                         }
314
315                         if (groupfile != "") {
316                                 if (groupfileNames.size() != fastaFileNames.size()) { abort = true; m->mothurOut("If you provide a group file, you must have one for each fasta file."); m->mothurOutEndLine(); }
317                         }else {
318                                 for (int i = 0; i < fastaFileNames.size(); i++) {  groupfileNames.push_back("");  }
319                         }
320                         
321                         //check for optional parameter and set defaults
322                         // ...at some point should added some additional type checking...
323                         string temp;
324                         temp = validParameter.validFile(parameters, "ksize", false);            if (temp == "not found"){       temp = "8";                             }
325                         convert(temp, kmerSize); 
326                         
327                         temp = validParameter.validFile(parameters, "processors", false);       if (temp == "not found"){       temp = "1";                             }
328                         convert(temp, processors); 
329                         
330                         search = validParameter.validFile(parameters, "search", false);         if (search == "not found"){     search = "kmer";                }
331                         
332                         method = validParameter.validFile(parameters, "method", false);         if (method == "not found"){     method = "bayesian";    }
333                         
334                         temp = validParameter.validFile(parameters, "match", false);            if (temp == "not found"){       temp = "1.0";                   }
335                         convert(temp, match);  
336                         
337                         temp = validParameter.validFile(parameters, "mismatch", false);         if (temp == "not found"){       temp = "-1.0";                  }
338                         convert(temp, misMatch);  
339                         
340                         temp = validParameter.validFile(parameters, "gapopen", false);          if (temp == "not found"){       temp = "-2.0";                  }
341                         convert(temp, gapOpen);  
342                         
343                         temp = validParameter.validFile(parameters, "gapextend", false);        if (temp == "not found"){       temp = "-1.0";                  }
344                         convert(temp, gapExtend); 
345                         
346                         temp = validParameter.validFile(parameters, "numwanted", false);        if (temp == "not found"){       temp = "10";                    }
347                         convert(temp, numWanted);
348                         
349                         temp = validParameter.validFile(parameters, "cutoff", false);           if (temp == "not found"){       temp = "0";                             }
350                         convert(temp, cutoff);
351                         
352                         temp = validParameter.validFile(parameters, "probs", false);            if (temp == "not found"){       temp = "true";                  }
353                         probs = m->isTrue(temp);
354                         
355                         temp = validParameter.validFile(parameters, "iters", false);            if (temp == "not found") { temp = "100";                        }
356                         convert(temp, iters); 
357
358
359                         
360                         if ((method == "bayesian") && (search != "kmer"))  { 
361                                 m->mothurOut("The bayesian method requires the kmer search." + search + "will be disregarded." ); m->mothurOutEndLine();
362                                 search = "kmer";
363                         }
364                 }
365                 
366         }
367         catch(exception& e) {
368                 m->errorOut(e, "ClassifySeqsCommand", "ClassifySeqsCommand");
369                 exit(1);
370         }
371 }
372
373 //**********************************************************************************************************************
374
375 ClassifySeqsCommand::~ClassifySeqsCommand(){    
376
377         if (abort == false) {
378                 for (int i = 0; i < lines.size(); i++) {  delete lines[i];  }  lines.clear();
379         }
380 }
381
382 //**********************************************************************************************************************
383
384 void ClassifySeqsCommand::help(){
385         try {
386                 m->mothurOut("The classify.seqs command reads a fasta file containing sequences and creates a .taxonomy file and a .tax.summary file.\n");
387                 m->mothurOut("The classify.seqs command parameters are template, fasta, name, search, ksize, method, taxonomy, processors, match, mismatch, gapopen, gapextend, numwanted and probs.\n");
388                 m->mothurOut("The template, fasta and taxonomy parameters are required. You may enter multiple fasta files by separating their names with dashes. ie. fasta=abrecovery.fasta-amzon.fasta \n");
389                 m->mothurOut("The search parameter allows you to specify the method to find most similar template.  Your options are: suffix, kmer, blast and distance. The default is kmer.\n");
390                 m->mothurOut("The name parameter allows you add a names file with your fasta file, if you enter multiple fasta files, you must enter matching names files for them.\n");
391                 m->mothurOut("The group parameter allows you add a group file so you can have the summary totals broken up by group.\n");
392                 m->mothurOut("The method parameter allows you to specify classification method to use.  Your options are: bayesian and knn. The default is bayesian.\n");
393                 m->mothurOut("The ksize parameter allows you to specify the kmer size for finding most similar template to candidate.  The default is 8.\n");
394                 m->mothurOut("The processors parameter allows you to specify the number of processors to use. The default is 1.\n");
395                 #ifdef USE_MPI
396                 m->mothurOut("When using MPI, the processors parameter is set to the number of MPI processes running. \n");
397                 #endif
398                 m->mothurOut("The match parameter allows you to specify the bonus for having the same base. The default is 1.0.\n");
399                 m->mothurOut("The mistmatch parameter allows you to specify the penalty for having different bases.  The default is -1.0.\n");
400                 m->mothurOut("The gapopen parameter allows you to specify the penalty for opening a gap in an alignment. The default is -2.0.\n");
401                 m->mothurOut("The gapextend parameter allows you to specify the penalty for extending a gap in an alignment.  The default is -1.0.\n");
402                 m->mothurOut("The numwanted parameter allows you to specify the number of sequence matches you want with the knn method.  The default is 10.\n");
403                 m->mothurOut("The cutoff parameter allows you to specify a bootstrap confidence threshold for your taxonomy.  The default is 0.\n");
404                 m->mothurOut("The probs parameter shuts off the bootstrapping results for the bayesian method. The default is true, meaning you want the bootstrapping to be shown.\n");
405                 m->mothurOut("The iters parameter allows you to specify how many iterations to do when calculating the bootstrap confidence score for your taxonomy with the bayesian method.  The default is 100.\n");
406                 m->mothurOut("The classify.seqs command should be in the following format: \n");
407                 m->mothurOut("classify.seqs(template=yourTemplateFile, fasta=yourFastaFile, method=yourClassificationMethod, search=yourSearchmethod, ksize=yourKmerSize, taxonomy=yourTaxonomyFile, processors=yourProcessors) \n");
408                 m->mothurOut("Example classify.seqs(fasta=amazon.fasta, template=core.filtered, method=knn, search=gotoh, ksize=8, processors=2)\n");
409                 m->mothurOut("The .taxonomy file consists of 2 columns: 1 = your sequence name, 2 = the taxonomy for your sequence. \n");
410                 m->mothurOut("The .tax.summary is a summary of the different taxonomies represented in your fasta file. \n");
411                 m->mothurOut("Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFastaFile).\n\n");
412         }
413         catch(exception& e) {
414                 m->errorOut(e, "ClassifySeqsCommand", "help");
415                 exit(1);
416         }
417 }
418
419
420 //**********************************************************************************************************************
421
422 int ClassifySeqsCommand::execute(){
423         try {
424                 if (abort == true) {    return 0;       }
425                 
426                 if(method == "bayesian"){       classify = new Bayesian(taxonomyFileName, templateFileName, search, kmerSize, cutoff, iters);           }
427                 else if(method == "knn"){       classify = new Knn(taxonomyFileName, templateFileName, search, kmerSize, gapOpen, gapExtend, match, misMatch, numWanted);                               }
428                 else {
429                         m->mothurOut(search + " is not a valid method option. I will run the command using bayesian.");
430                         m->mothurOutEndLine();
431                         classify = new Bayesian(taxonomyFileName, templateFileName, search, kmerSize, cutoff, iters);   
432                 }
433                 
434                 if (m->control_pressed) { delete classify; return 0; }
435                 
436                                 
437                 for (int s = 0; s < fastaFileNames.size(); s++) {
438                 
439                         m->mothurOut("Classifying sequences from " + fastaFileNames[s] + " ..." ); m->mothurOutEndLine();
440                         
441                         string RippedTaxName = m->getRootName(m->getSimpleName(taxonomyFileName));
442                         RippedTaxName = m->getExtension(RippedTaxName.substr(0, RippedTaxName.length()-1));
443                         if (RippedTaxName[0] == '.') { RippedTaxName = RippedTaxName.substr(1, RippedTaxName.length()); }
444                         RippedTaxName +=  "."; 
445                 
446                         if (outputDir == "") { outputDir += m->hasPath(fastaFileNames[s]); }
447                         string newTaxonomyFile = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + RippedTaxName + "taxonomy";
448                         string tempTaxonomyFile = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + "taxonomy.temp";
449                         string taxSummary = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + RippedTaxName + "tax.summary";
450                         
451                         if ((method == "knn") && (search == "distance")) { 
452                                 string DistName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + "match.dist";
453                                 classify->setDistName(DistName);  outputNames.push_back(DistName); outputTypes["matchdist"].push_back(DistName);
454                         }
455                         
456                         outputNames.push_back(newTaxonomyFile); outputTypes["taxonomy"].push_back(newTaxonomyFile);
457                         outputNames.push_back(taxSummary);      outputTypes["taxsummary"].push_back(taxSummary);
458                         
459                         int start = time(NULL);
460                         int numFastaSeqs = 0;
461                         for (int i = 0; i < lines.size(); i++) {  delete lines[i];  }  lines.clear();
462                         
463 #ifdef USE_MPI  
464                                 int pid, end, numSeqsPerProcessor; 
465                                 int tag = 2001;
466                                 vector<unsigned long int> MPIPos;
467                                 
468                                 MPI_Status status; 
469                                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
470                                 MPI_Comm_size(MPI_COMM_WORLD, &processors); 
471
472                                 MPI_File inMPI;
473                                 MPI_File outMPINewTax;
474                                 MPI_File outMPITempTax;
475                                                         
476                                 int outMode=MPI_MODE_CREATE|MPI_MODE_WRONLY; 
477                                 int inMode=MPI_MODE_RDONLY; 
478                                 
479                                 char outNewTax[1024];
480                                 strcpy(outNewTax, newTaxonomyFile.c_str());
481                                 
482                                 char outTempTax[1024];
483                                 strcpy(outTempTax, tempTaxonomyFile.c_str());
484                                 
485                                 char inFileName[1024];
486                                 strcpy(inFileName, fastaFileNames[s].c_str());
487
488                                 MPI_File_open(MPI_COMM_WORLD, inFileName, inMode, MPI_INFO_NULL, &inMPI);  //comm, filename, mode, info, filepointer
489                                 MPI_File_open(MPI_COMM_WORLD, outNewTax, outMode, MPI_INFO_NULL, &outMPINewTax);
490                                 MPI_File_open(MPI_COMM_WORLD, outTempTax, outMode, MPI_INFO_NULL, &outMPITempTax);
491                                 
492                                 if (m->control_pressed) { outputTypes.clear(); MPI_File_close(&inMPI);  MPI_File_close(&outMPINewTax);   MPI_File_close(&outMPITempTax);  delete classify; return 0;  }
493                                 
494                                 if (pid == 0) { //you are the root process 
495                                         
496                                         MPIPos = m->setFilePosFasta(fastaFileNames[s], numFastaSeqs); //fills MPIPos, returns numSeqs
497                                         
498                                         //send file positions to all processes
499                                         for(int i = 1; i < processors; i++) { 
500                                                 MPI_Send(&numFastaSeqs, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
501                                                 MPI_Send(&MPIPos[0], (numFastaSeqs+1), MPI_LONG, i, tag, MPI_COMM_WORLD);
502                                         }
503                                         
504                                         //figure out how many sequences you have to align
505                                         numSeqsPerProcessor = numFastaSeqs / processors;
506                                         int startIndex =  pid * numSeqsPerProcessor;
507                                         if(pid == (processors - 1)){    numSeqsPerProcessor = numFastaSeqs - pid * numSeqsPerProcessor;         }
508                                         
509                                 
510                                         //align your part
511                                         driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPINewTax, outMPITempTax, MPIPos);
512                                         
513                                         if (m->control_pressed) {  outputTypes.clear(); MPI_File_close(&inMPI);  MPI_File_close(&outMPINewTax);   MPI_File_close(&outMPITempTax);  for (int i = 0; i < outputNames.size(); i++) {       remove(outputNames[i].c_str()); } delete classify; return 0;  }
514                                         
515                                         for (int i = 1; i < processors; i++) {
516                                                 int done;
517                                                 MPI_Recv(&done, 1, MPI_INT, i, tag, MPI_COMM_WORLD, &status);
518                                         }
519                                 }else{ //you are a child process
520                                         MPI_Recv(&numFastaSeqs, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
521                                         MPIPos.resize(numFastaSeqs+1);
522                                         MPI_Recv(&MPIPos[0], (numFastaSeqs+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
523                                         
524                                         //figure out how many sequences you have to align
525                                         numSeqsPerProcessor = numFastaSeqs / processors;
526                                         int startIndex =  pid * numSeqsPerProcessor;
527                                         if(pid == (processors - 1)){    numSeqsPerProcessor = numFastaSeqs - pid * numSeqsPerProcessor;         }
528                                         
529                                         
530                                         //align your part
531                                         driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPINewTax, outMPITempTax, MPIPos);
532                                         
533                                         if (m->control_pressed) {  outputTypes.clear(); MPI_File_close(&inMPI);  MPI_File_close(&outMPINewTax);   MPI_File_close(&outMPITempTax);  delete classify; return 0;  }
534
535                                         int done = 0;
536                                         MPI_Send(&done, 1, MPI_INT, 0, tag, MPI_COMM_WORLD); 
537                                 }
538                                 
539                                 //close files 
540                                 MPI_File_close(&inMPI);
541                                 MPI_File_close(&outMPINewTax);
542                                 MPI_File_close(&outMPITempTax);
543                                 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
544                                 
545 #else
546                 
547                         vector<unsigned long int> positions = m->divideFile(fastaFileNames[s], processors);
548                                 
549                         for (int i = 0; i < (positions.size()-1); i++) {
550                                 lines.push_back(new linePair(positions[i], positions[(i+1)]));
551                         }       
552                         
553                 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
554                         if(processors == 1){
555                                 numFastaSeqs = driver(lines[0], newTaxonomyFile, tempTaxonomyFile, fastaFileNames[s]);
556                         }
557                         else{
558                                 processIDS.resize(0);
559                                 
560                                 numFastaSeqs = createProcesses(newTaxonomyFile, tempTaxonomyFile, fastaFileNames[s]); 
561                                 
562                                 rename((newTaxonomyFile + toString(processIDS[0]) + ".temp").c_str(), newTaxonomyFile.c_str());
563                                 rename((tempTaxonomyFile + toString(processIDS[0]) + ".temp").c_str(), tempTaxonomyFile.c_str());
564                                 
565                                 for(int i=1;i<processors;i++){
566                                         appendTaxFiles((newTaxonomyFile + toString(processIDS[i]) + ".temp"), newTaxonomyFile);
567                                         appendTaxFiles((tempTaxonomyFile + toString(processIDS[i]) + ".temp"), tempTaxonomyFile);
568                                         remove((newTaxonomyFile + toString(processIDS[i]) + ".temp").c_str());
569                                         remove((tempTaxonomyFile + toString(processIDS[i]) + ".temp").c_str());
570                                 }
571                                 
572                         }
573         #else
574                         numFastaSeqs = driver(lines[0], newTaxonomyFile, tempTaxonomyFile, fastaFileNames[s]);
575         #endif  
576 #endif
577
578                 m->mothurOutEndLine();
579                 m->mothurOut("It took " + toString(time(NULL) - start) + " secs to classify " + toString(numFastaSeqs) + " sequences."); m->mothurOutEndLine(); m->mothurOutEndLine();
580                 start = time(NULL);
581
582
583                 #ifdef USE_MPI  
584                         if (pid == 0) {  //this part does not need to be paralellized
585                         
586                                 if(namefile != "") { m->mothurOut("Reading " + namefileNames[s] + "..."); cout.flush();  MPIReadNamesFile(namefileNames[s]);  m->mothurOut("  Done."); m->mothurOutEndLine(); }
587                 #else
588                         //read namefile
589                         if(namefile != "") {
590                         
591                             m->mothurOut("Reading " + namefileNames[s] + "..."); cout.flush();
592                                 
593                                 nameMap.clear(); //remove old names
594                                 
595                                 ifstream inNames;
596                                 m->openInputFile(namefileNames[s], inNames);
597                                 
598                                 string firstCol, secondCol;
599                                 while(!inNames.eof()) {
600                                         inNames >> firstCol >> secondCol; m->gobble(inNames);
601                                         
602                                         vector<string> temp;
603                                         m->splitAtComma(secondCol, temp);
604                         
605                                         nameMap[firstCol] = temp;  
606                                 }
607                                 inNames.close();
608                                 
609                                 m->mothurOut("  Done."); m->mothurOutEndLine();
610                         }
611                 #endif
612
613                         string group = "";
614                         if (groupfile != "") {  group = groupfileNames[s]; }
615                         
616                         PhyloSummary taxaSum(taxonomyFileName, group);
617                         
618                         if (m->control_pressed) { outputTypes.clear();  for (int i = 0; i < outputNames.size(); i++) {  remove(outputNames[i].c_str()); } delete classify; return 0; }
619                 
620                         if (namefile == "") {  taxaSum.summarize(tempTaxonomyFile);  }
621                         else {
622                                 ifstream in;
623                                 m->openInputFile(tempTaxonomyFile, in);
624                                 
625                                 //read in users taxonomy file and add sequences to tree
626                                 string name, taxon;
627                                 
628                                 while(!in.eof()){
629                                         in >> name >> taxon; m->gobble(in);
630                                         
631                                         itNames = nameMap.find(name);
632                 
633                                         if (itNames == nameMap.end()) { 
634                                                 m->mothurOut(name + " is not in your name file please correct."); m->mothurOutEndLine(); exit(1);
635                                         }else{
636                                                 for (int i = 0; i < itNames->second.size(); i++) { 
637                                                         taxaSum.addSeqToTree(itNames->second[i], taxon);  //add it as many times as there are identical seqs
638                                                 }
639                                                 itNames->second.clear();
640                                                 nameMap.erase(itNames->first);
641                                         }
642                                 }
643                                 in.close();
644                         }
645                         remove(tempTaxonomyFile.c_str());
646                         
647                         if (m->control_pressed) {  outputTypes.clear(); for (int i = 0; i < outputNames.size(); i++) {  remove(outputNames[i].c_str()); } delete classify; return 0; }
648                         
649                         //print summary file
650                         ofstream outTaxTree;
651                         m->openOutputFile(taxSummary, outTaxTree);
652                         taxaSum.print(outTaxTree);
653                         outTaxTree.close();
654                         
655                         //output taxonomy with the unclassified bins added
656                         ifstream inTax;
657                         m->openInputFile(newTaxonomyFile, inTax);
658                         
659                         ofstream outTax;
660                         string unclass = newTaxonomyFile + ".unclass.temp";
661                         m->openOutputFile(unclass, outTax);
662                         
663                         //get maxLevel from phylotree so you know how many 'unclassified's to add
664                         int maxLevel = taxaSum.getMaxLevel();
665                         
666                         //read taxfile - this reading and rewriting is done to preserve the confidence scores.
667                         string name, taxon;
668                         while (!inTax.eof()) {
669                                 if (m->control_pressed) { outputTypes.clear();  for (int i = 0; i < outputNames.size(); i++) {  remove(outputNames[i].c_str()); } remove(unclass.c_str()); delete classify; return 0; }
670
671                                 inTax >> name >> taxon; m->gobble(inTax);
672                                 
673                                 string newTax = addUnclassifieds(taxon, maxLevel);
674                                 
675                                 outTax << name << '\t' << newTax << endl;
676                         }
677                         inTax.close();  
678                         outTax.close();
679                         
680                         remove(newTaxonomyFile.c_str());
681                         rename(unclass.c_str(), newTaxonomyFile.c_str());
682                         
683                         m->mothurOutEndLine();
684                         m->mothurOut("It took " + toString(time(NULL) - start) + " secs to create the summary file for " + toString(numFastaSeqs) + " sequences."); m->mothurOutEndLine(); m->mothurOutEndLine();
685                         
686                         #ifdef USE_MPI  
687                                 }
688                         #endif
689
690                         m->mothurOutEndLine();
691                         m->mothurOut("Output File Names: "); m->mothurOutEndLine();
692                         for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }
693                         m->mothurOutEndLine();
694                 }
695                 
696                 delete classify;
697                 return 0;
698         }
699         catch(exception& e) {
700                 m->errorOut(e, "ClassifySeqsCommand", "execute");
701                 exit(1);
702         }
703 }
704
705 /**************************************************************************************************/
706 string ClassifySeqsCommand::addUnclassifieds(string tax, int maxlevel) {
707         try{
708                 string newTax, taxon;
709                 int level = 0;
710                 
711                 //keep what you have counting the levels
712                 while (tax.find_first_of(';') != -1) {
713                         //get taxon
714                         taxon = tax.substr(0,tax.find_first_of(';'))+';';
715                         tax = tax.substr(tax.find_first_of(';')+1, tax.length());
716                         newTax += taxon;
717                         level++;
718                 }
719                 
720                 //add "unclassified" until you reach maxLevel
721                 while (level < maxlevel) {
722                         newTax += "unclassified;";
723                         level++;
724                 }
725                 
726                 return newTax;
727         }
728         catch(exception& e) {
729                 m->errorOut(e, "ClassifySeqsCommand", "addUnclassifieds");
730                 exit(1);
731         }
732 }
733
734 /**************************************************************************************************/
735
736 int ClassifySeqsCommand::createProcesses(string taxFileName, string tempTaxFile, string filename) {
737         try {
738 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
739                 int process = 0;
740                 int num = 0;
741                 
742                 //loop through and create all the processes you want
743                 while (process != processors) {
744                         int pid = fork();
745                         
746                         if (pid > 0) {
747                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
748                                 process++;
749                         }else if (pid == 0){
750                                 num = driver(lines[process], taxFileName + toString(getpid()) + ".temp", tempTaxFile + toString(getpid()) + ".temp", filename);
751                                 
752                                 //pass numSeqs to parent
753                                 ofstream out;
754                                 string tempFile = filename + toString(getpid()) + ".num.temp";
755                                 m->openOutputFile(tempFile, out);
756                                 out << num << endl;
757                                 out.close();
758
759                                 exit(0);
760                         }else { 
761                                 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); 
762                                 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
763                                 exit(0);
764                         }
765                 }
766                 
767                 //force parent to wait until all the processes are done
768                 for (int i=0;i<processors;i++) { 
769                         int temp = processIDS[i];
770                         wait(&temp);
771                 }
772                 
773                 for (int i = 0; i < processIDS.size(); i++) {
774                         ifstream in;
775                         string tempFile =  filename + toString(processIDS[i]) + ".num.temp";
776                         m->openInputFile(tempFile, in);
777                         if (!in.eof()) { int tempNum = 0; in >> tempNum; num += tempNum; }
778                         in.close(); remove(tempFile.c_str());
779                 }
780                 
781                 return num;
782 #endif          
783         }
784         catch(exception& e) {
785                 m->errorOut(e, "ClassifySeqsCommand", "createProcesses");
786                 exit(1);
787         }
788 }
789 /**************************************************************************************************/
790
791 void ClassifySeqsCommand::appendTaxFiles(string temp, string filename) {
792         try{
793                 
794                 ofstream output;
795                 ifstream input;
796                 m->openOutputFileAppend(filename, output);
797                 m->openInputFile(temp, input);
798                 
799                 while(char c = input.get()){
800                         if(input.eof())         {       break;                  }
801                         else                            {       output << c;    }
802                 }
803                 
804                 input.close();
805                 output.close();
806         }
807         catch(exception& e) {
808                 m->errorOut(e, "ClassifySeqsCommand", "appendTaxFiles");
809                 exit(1);
810         }
811 }
812
813 //**********************************************************************************************************************
814
815 int ClassifySeqsCommand::driver(linePair* filePos, string taxFName, string tempTFName, string filename){
816         try {
817                 ofstream outTax;
818                 m->openOutputFile(taxFName, outTax);
819                 
820                 ofstream outTaxSimple;
821                 m->openOutputFile(tempTFName, outTaxSimple);
822         
823                 ifstream inFASTA;
824                 m->openInputFile(filename, inFASTA);
825                 
826                 string taxonomy;
827
828                 inFASTA.seekg(filePos->start);
829
830                 bool done = false;
831                 int count = 0;
832         
833                 while (!done) {
834                         if (m->control_pressed) { return 0; }
835                 
836                         Sequence* candidateSeq = new Sequence(inFASTA); m->gobble(inFASTA);
837                 
838                         if (candidateSeq->getName() != "") {
839                                 taxonomy = classify->getTaxonomy(candidateSeq);
840                                 
841                                 if (m->control_pressed) { delete candidateSeq; return 0; }
842
843                                 if (taxonomy != "bad seq") {
844                                         //output confidence scores or not
845                                         if (probs) {
846                                                 outTax << candidateSeq->getName() << '\t' << taxonomy << endl;
847                                         }else{
848                                                 outTax << candidateSeq->getName() << '\t' << classify->getSimpleTax() << endl;
849                                         }
850                                         
851                                         outTaxSimple << candidateSeq->getName() << '\t' << classify->getSimpleTax() << endl;
852                                 }
853                                 count++;
854                         }
855                         delete candidateSeq;
856                         
857                         #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
858                                 unsigned long int pos = inFASTA.tellg();
859                                 if ((pos == -1) || (pos >= filePos->end)) { break; }
860                         #else
861                                 if (inFASTA.eof()) { break; }
862                         #endif
863                         
864                         //report progress
865                         if((count) % 100 == 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine();         }
866                 }
867                 //report progress
868                 if((count) % 100 != 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine();         }
869                                 
870                 inFASTA.close();
871                 outTax.close();
872                 outTaxSimple.close();
873                 
874                 return count;
875         }
876         catch(exception& e) {
877                 m->errorOut(e, "ClassifySeqsCommand", "driver");
878                 exit(1);
879         }
880 }
881 //**********************************************************************************************************************
882 #ifdef USE_MPI
883 int ClassifySeqsCommand::driverMPI(int start, int num, MPI_File& inMPI, MPI_File& newFile, MPI_File& tempFile, vector<unsigned long int>& MPIPos){
884         try {
885                 MPI_Status statusNew; 
886                 MPI_Status statusTemp; 
887                 MPI_Status status; 
888                 
889                 int pid;
890                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
891         
892                 string taxonomy;
893                 string outputString;
894
895                 for(int i=0;i<num;i++){
896                 
897                         if (m->control_pressed) { return 0; }
898                 
899                         //read next sequence
900                         int length = MPIPos[start+i+1] - MPIPos[start+i];
901                         char* buf4 = new char[length];
902                         MPI_File_read_at(inMPI, MPIPos[start+i], buf4, length, MPI_CHAR, &status);
903                         
904                         string tempBuf = buf4;
905                         if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length);  }
906                         istringstream iss (tempBuf,istringstream::in);
907                         delete buf4;
908
909                         Sequence* candidateSeq = new Sequence(iss);
910                         
911                         if (candidateSeq->getName() != "") {
912                                 taxonomy = classify->getTaxonomy(candidateSeq);
913                                 
914                                 if (taxonomy != "bad seq") {
915                                         //output confidence scores or not
916                                         if (probs) {
917                                                 outputString =  candidateSeq->getName() + "\t" + taxonomy + "\n";
918                                         }else{
919                                                 outputString =  candidateSeq->getName() + "\t" + classify->getSimpleTax() + "\n";
920                                         }
921                                         
922                                         int length = outputString.length();
923                                         char* buf2 = new char[length];
924                                         memcpy(buf2, outputString.c_str(), length);
925                                 
926                                         MPI_File_write_shared(newFile, buf2, length, MPI_CHAR, &statusNew);
927                                         delete buf2;
928
929                                         outputString =  candidateSeq->getName() + "\t" + classify->getSimpleTax() + "\n";
930                                         length = outputString.length();
931                                         char* buf = new char[length];
932                                         memcpy(buf, outputString.c_str(), length);
933                                 
934                                         MPI_File_write_shared(tempFile, buf, length, MPI_CHAR, &statusTemp);
935                                         delete buf;
936                                 }
937                         }                               
938                         delete candidateSeq;
939                         
940                         if((i+1) % 100 == 0){   cout << "Classifying sequence " << (i+1) << endl;       }
941                 }
942                 
943                 if(num % 100 != 0){     cout << "Classifying sequence " << (num) << endl;       }
944                 
945                 
946                 return 1;
947         }
948         catch(exception& e) {
949                 m->errorOut(e, "ClassifySeqsCommand", "driverMPI");
950                 exit(1);
951         }
952 }
953
954 //**********************************************************************************************************************
955 int ClassifySeqsCommand::MPIReadNamesFile(string nameFilename){
956         try {
957         
958                 nameMap.clear(); //remove old names
959                 
960                 MPI_File inMPI;
961                 MPI_Offset size;
962                 MPI_Status status;
963
964                 //char* inFileName = new char[nameFilename.length()];
965                 //memcpy(inFileName, nameFilename.c_str(), nameFilename.length());
966                 
967                 char inFileName[1024];
968                 strcpy(inFileName, nameFilename.c_str());
969
970                 MPI_File_open(MPI_COMM_WORLD, inFileName, MPI_MODE_RDONLY, MPI_INFO_NULL, &inMPI);  
971                 MPI_File_get_size(inMPI, &size);
972                 //delete inFileName;
973
974                 char* buffer = new char[size];
975                 MPI_File_read(inMPI, buffer, size, MPI_CHAR, &status);
976
977                 string tempBuf = buffer;
978                 if (tempBuf.length() > size) { tempBuf = tempBuf.substr(0, size);  }
979                 istringstream iss (tempBuf,istringstream::in);
980                 delete buffer;
981                 
982                 string firstCol, secondCol;
983                 while(!iss.eof()) {
984                         iss >> firstCol >> secondCol; m->gobble(iss);
985                         
986                         vector<string> temp;
987                         m->splitAtComma(secondCol, temp);
988                         
989                         nameMap[firstCol] = temp;  
990                 }
991         
992                 MPI_File_close(&inMPI);
993                 
994                 return 1;
995         }
996         catch(exception& e) {
997                 m->errorOut(e, "ClassifySeqsCommand", "MPIReadNamesFile");
998                 exit(1);
999         }
1000 }
1001 #endif
1002 /**************************************************************************************************/