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