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