]> git.donarmstrong.com Git - mothur.git/blob - classifyseqscommand.cpp
working on chimera change to add trim feature, fixed bug in print of distance file...
[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, 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                         }
563         #else
564                         numFastaSeqs = driver(lines[0], newTaxonomyFile, tempTaxonomyFile, fastaFileNames[s]);
565         #endif  
566 #endif
567
568                 m->mothurOutEndLine();
569                 m->mothurOut("It took " + toString(time(NULL) - start) + " secs to classify " + toString(numFastaSeqs) + " sequences."); m->mothurOutEndLine(); m->mothurOutEndLine();
570                 start = time(NULL);
571
572
573                 #ifdef USE_MPI  
574                         if (pid == 0) {  //this part does not need to be paralellized
575                         
576                                 if(namefile != "") { m->mothurOut("Reading " + namefileNames[s] + "..."); cout.flush();  MPIReadNamesFile(namefileNames[s]);  m->mothurOut("  Done."); m->mothurOutEndLine(); }
577                 #else
578                         //read namefile
579                         if(namefile != "") {
580                         
581                             m->mothurOut("Reading " + namefileNames[s] + "..."); cout.flush();
582                                 
583                                 nameMap.clear(); //remove old names
584                                 
585                                 ifstream inNames;
586                                 m->openInputFile(namefileNames[s], inNames);
587                                 
588                                 string firstCol, secondCol;
589                                 while(!inNames.eof()) {
590                                         inNames >> firstCol >> secondCol; m->gobble(inNames);
591                                         
592                                         vector<string> temp;
593                                         m->splitAtComma(secondCol, temp);
594                         
595                                         nameMap[firstCol] = temp;  
596                                 }
597                                 inNames.close();
598                                 
599                                 m->mothurOut("  Done."); m->mothurOutEndLine();
600                         }
601                 #endif
602
603                         string group = "";
604                         if (groupfile != "") {  group = groupfileNames[s]; }
605                         
606                         PhyloSummary taxaSum(taxonomyFileName, group);
607                         
608                         if (m->control_pressed) { outputTypes.clear();  for (int i = 0; i < outputNames.size(); i++) {  remove(outputNames[i].c_str()); } delete classify; return 0; }
609                 
610                         if (namefile == "") {  taxaSum.summarize(tempTaxonomyFile);  }
611                         else {
612                                 ifstream in;
613                                 m->openInputFile(tempTaxonomyFile, in);
614                                 
615                                 //read in users taxonomy file and add sequences to tree
616                                 string name, taxon;
617                                 
618                                 while(!in.eof()){
619                                         in >> name >> taxon; m->gobble(in);
620                                         
621                                         itNames = nameMap.find(name);
622                 
623                                         if (itNames == nameMap.end()) { 
624                                                 m->mothurOut(name + " is not in your name file please correct."); m->mothurOutEndLine(); exit(1);
625                                         }else{
626                                                 for (int i = 0; i < itNames->second.size(); i++) { 
627                                                         taxaSum.addSeqToTree(itNames->second[i], taxon);  //add it as many times as there are identical seqs
628                                                 }
629                                                 itNames->second.clear();
630                                                 nameMap.erase(itNames->first);
631                                         }
632                                 }
633                                 in.close();
634                         }
635                         remove(tempTaxonomyFile.c_str());
636                         
637                         if (m->control_pressed) {  outputTypes.clear(); for (int i = 0; i < outputNames.size(); i++) {  remove(outputNames[i].c_str()); } delete classify; return 0; }
638                         
639                         //print summary file
640                         ofstream outTaxTree;
641                         m->openOutputFile(taxSummary, outTaxTree);
642                         taxaSum.print(outTaxTree);
643                         outTaxTree.close();
644                         
645                         //output taxonomy with the unclassified bins added
646                         ifstream inTax;
647                         m->openInputFile(newTaxonomyFile, inTax);
648                         
649                         ofstream outTax;
650                         string unclass = newTaxonomyFile + ".unclass.temp";
651                         m->openOutputFile(unclass, outTax);
652                         
653                         //get maxLevel from phylotree so you know how many 'unclassified's to add
654                         int maxLevel = taxaSum.getMaxLevel();
655                                                         
656                         //read taxfile - this reading and rewriting is done to preserve the confidence scores.
657                         string name, taxon;
658                         while (!inTax.eof()) {
659                                 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; }
660
661                                 inTax >> name >> taxon; m->gobble(inTax);
662                                 
663                                 string newTax = addUnclassifieds(taxon, maxLevel);
664                                 
665                                 outTax << name << '\t' << newTax << endl;
666                         }
667                         inTax.close();  
668                         outTax.close();
669                         
670                         remove(newTaxonomyFile.c_str());
671                         rename(unclass.c_str(), newTaxonomyFile.c_str());
672                         
673                         m->mothurOutEndLine();
674                         m->mothurOut("It took " + toString(time(NULL) - start) + " secs to create the summary file for " + toString(numFastaSeqs) + " sequences."); m->mothurOutEndLine(); m->mothurOutEndLine();
675                         
676                         #ifdef USE_MPI  
677                                 }
678                         #endif
679
680                         m->mothurOutEndLine();
681                         m->mothurOut("Output File Names: "); m->mothurOutEndLine();
682                         for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }
683                         m->mothurOutEndLine();
684                 }
685                 
686                 delete classify;
687                 return 0;
688         }
689         catch(exception& e) {
690                 m->errorOut(e, "ClassifySeqsCommand", "execute");
691                 exit(1);
692         }
693 }
694
695 /**************************************************************************************************/
696 string ClassifySeqsCommand::addUnclassifieds(string tax, int maxlevel) {
697         try{
698                 string newTax, taxon;
699                 int level = 0;
700                 
701                 //keep what you have counting the levels
702                 while (tax.find_first_of(';') != -1) {
703                         //get taxon
704                         taxon = tax.substr(0,tax.find_first_of(';'))+';';
705                         tax = tax.substr(tax.find_first_of(';')+1, tax.length());
706                         newTax += taxon;
707                         level++;
708                 }
709                 
710                 //add "unclassified" until you reach maxLevel
711                 while (level < maxlevel) {
712                         newTax += "unclassified;";
713                         level++;
714                 }
715                 
716                 return newTax;
717         }
718         catch(exception& e) {
719                 m->errorOut(e, "ClassifySeqsCommand", "addUnclassifieds");
720                 exit(1);
721         }
722 }
723
724 /**************************************************************************************************/
725
726 int ClassifySeqsCommand::createProcesses(string taxFileName, string tempTaxFile, string filename) {
727         try {
728 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
729                 int process = 1;
730                 int num = 0;
731                 
732                 //loop through and create all the processes you want
733                 while (process != processors) {
734                         int pid = fork();
735                         
736                         if (pid > 0) {
737                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
738                                 process++;
739                         }else if (pid == 0){
740                                 num = driver(lines[process], taxFileName + toString(getpid()) + ".temp", tempTaxFile + toString(getpid()) + ".temp", filename);
741                                 
742                                 //pass numSeqs to parent
743                                 ofstream out;
744                                 string tempFile = filename + toString(getpid()) + ".num.temp";
745                                 m->openOutputFile(tempFile, out);
746                                 out << num << endl;
747                                 out.close();
748
749                                 exit(0);
750                         }else { 
751                                 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); 
752                                 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
753                                 exit(0);
754                         }
755                 }
756                 
757                 //parent does its part
758                 num = driver(lines[0], taxFileName, tempTaxFile, filename);
759                 
760                 //force parent to wait until all the processes are done
761                 for (int i=0;i<processIDS.size();i++) { 
762                         int temp = processIDS[i];
763                         wait(&temp);
764                 }
765                 
766                 for (int i = 0; i < processIDS.size(); i++) {
767                         ifstream in;
768                         string tempFile =  filename + toString(processIDS[i]) + ".num.temp";
769                         m->openInputFile(tempFile, in);
770                         if (!in.eof()) { int tempNum = 0; in >> tempNum; num += tempNum; }
771                         in.close(); remove(tempFile.c_str());
772                 }
773                 
774                 for(int i=0;i<processIDS.size();i++){
775                         appendTaxFiles((taxFileName + toString(processIDS[i]) + ".temp"), taxFileName);
776                         appendTaxFiles((tempTaxFile + toString(processIDS[i]) + ".temp"), tempTaxFile);
777                         remove((taxFileName + toString(processIDS[i]) + ".temp").c_str());
778                         remove((tempTaxFile + toString(processIDS[i]) + ".temp").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                         
840                                 taxonomy = classify->getTaxonomy(candidateSeq);
841                                 
842                                 if (m->control_pressed) { delete candidateSeq; return 0; }
843
844                                 if (taxonomy != "bad seq") {
845                                         //output confidence scores or not
846                                         if (probs) {
847                                                 outTax << candidateSeq->getName() << '\t' << taxonomy << endl;
848                                         }else{
849                                                 outTax << candidateSeq->getName() << '\t' << classify->getSimpleTax() << endl;
850                                         }
851                                         
852                                         outTaxSimple << candidateSeq->getName() << '\t' << classify->getSimpleTax() << endl;
853                                 }
854                                 count++;
855                         }
856                         delete candidateSeq;
857                         
858                         #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
859                                 unsigned long int pos = inFASTA.tellg();
860                                 if ((pos == -1) || (pos >= filePos->end)) { break; }
861                         #else
862                                 if (inFASTA.eof()) { break; }
863                         #endif
864                         
865                         //report progress
866                         if((count) % 100 == 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine();         }
867                         
868                 }
869                 //report progress
870                 if((count) % 100 != 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine();         }
871                         
872                 inFASTA.close();
873                 outTax.close();
874                 outTaxSimple.close();
875                 
876                 return count;
877         }
878         catch(exception& e) {
879                 m->errorOut(e, "ClassifySeqsCommand", "driver");
880                 exit(1);
881         }
882 }
883 //**********************************************************************************************************************
884 #ifdef USE_MPI
885 int ClassifySeqsCommand::driverMPI(int start, int num, MPI_File& inMPI, MPI_File& newFile, MPI_File& tempFile, vector<unsigned long int>& MPIPos){
886         try {
887                 MPI_Status statusNew; 
888                 MPI_Status statusTemp; 
889                 MPI_Status status; 
890                 
891                 int pid;
892                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
893         
894                 string taxonomy;
895                 string outputString;
896
897                 for(int i=0;i<num;i++){
898                 
899                         if (m->control_pressed) { return 0; }
900                 
901                         //read next sequence
902                         int length = MPIPos[start+i+1] - MPIPos[start+i];
903                         char* buf4 = new char[length];
904                         MPI_File_read_at(inMPI, MPIPos[start+i], buf4, length, MPI_CHAR, &status);
905                         
906                         string tempBuf = buf4;
907                         if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length);  }
908                         istringstream iss (tempBuf,istringstream::in);
909                         delete buf4;
910
911                         Sequence* candidateSeq = new Sequence(iss);
912                         
913                         if (candidateSeq->getName() != "") {
914                                 taxonomy = classify->getTaxonomy(candidateSeq);
915                                 
916                                 if (taxonomy != "bad seq") {
917                                         //output confidence scores or not
918                                         if (probs) {
919                                                 outputString =  candidateSeq->getName() + "\t" + taxonomy + "\n";
920                                         }else{
921                                                 outputString =  candidateSeq->getName() + "\t" + classify->getSimpleTax() + "\n";
922                                         }
923                                         
924                                         int length = outputString.length();
925                                         char* buf2 = new char[length];
926                                         memcpy(buf2, outputString.c_str(), length);
927                                 
928                                         MPI_File_write_shared(newFile, buf2, length, MPI_CHAR, &statusNew);
929                                         delete buf2;
930
931                                         outputString =  candidateSeq->getName() + "\t" + classify->getSimpleTax() + "\n";
932                                         length = outputString.length();
933                                         char* buf = new char[length];
934                                         memcpy(buf, outputString.c_str(), length);
935                                 
936                                         MPI_File_write_shared(tempFile, buf, length, MPI_CHAR, &statusTemp);
937                                         delete buf;
938                                 }
939                         }                               
940                         delete candidateSeq;
941                         
942                         if((i+1) % 100 == 0){   cout << "Classifying sequence " << (i+1) << endl;       }
943                 }
944                 
945                 if(num % 100 != 0){     cout << "Classifying sequence " << (num) << endl;       }
946                 
947                 
948                 return 1;
949         }
950         catch(exception& e) {
951                 m->errorOut(e, "ClassifySeqsCommand", "driverMPI");
952                 exit(1);
953         }
954 }
955
956 //**********************************************************************************************************************
957 int ClassifySeqsCommand::MPIReadNamesFile(string nameFilename){
958         try {
959         
960                 nameMap.clear(); //remove old names
961                 
962                 MPI_File inMPI;
963                 MPI_Offset size;
964                 MPI_Status status;
965
966                 //char* inFileName = new char[nameFilename.length()];
967                 //memcpy(inFileName, nameFilename.c_str(), nameFilename.length());
968                 
969                 char inFileName[1024];
970                 strcpy(inFileName, nameFilename.c_str());
971
972                 MPI_File_open(MPI_COMM_WORLD, inFileName, MPI_MODE_RDONLY, MPI_INFO_NULL, &inMPI);  
973                 MPI_File_get_size(inMPI, &size);
974                 //delete inFileName;
975
976                 char* buffer = new char[size];
977                 MPI_File_read(inMPI, buffer, size, MPI_CHAR, &status);
978
979                 string tempBuf = buffer;
980                 if (tempBuf.length() > size) { tempBuf = tempBuf.substr(0, size);  }
981                 istringstream iss (tempBuf,istringstream::in);
982                 delete buffer;
983                 
984                 string firstCol, secondCol;
985                 while(!iss.eof()) {
986                         iss >> firstCol >> secondCol; m->gobble(iss);
987                         
988                         vector<string> temp;
989                         m->splitAtComma(secondCol, temp);
990                         
991                         nameMap[firstCol] = temp;  
992                 }
993         
994                 MPI_File_close(&inMPI);
995                 
996                 return 1;
997         }
998         catch(exception& e) {
999                 m->errorOut(e, "ClassifySeqsCommand", "MPIReadNamesFile");
1000                 exit(1);
1001         }
1002 }
1003 #endif
1004 /**************************************************************************************************/