]> git.donarmstrong.com Git - mothur.git/blob - classifyseqscommand.cpp
Merge remote-tracking branch 'mothur/master'
[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
12
13
14 //**********************************************************************************************************************
15 vector<string> ClassifySeqsCommand::setParameters(){    
16         try {
17                 CommandParameter ptaxonomy("taxonomy", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(ptaxonomy);
18                 CommandParameter ptemplate("reference", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(ptemplate);
19                 CommandParameter pfasta("fasta", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(pfasta);
20                 CommandParameter pname("name", "InputTypes", "", "", "none", "none", "none",false,false); parameters.push_back(pname);
21                 CommandParameter pgroup("group", "InputTypes", "", "", "none", "none", "none",false,false); parameters.push_back(pgroup);
22                 CommandParameter psearch("search", "Multiple", "kmer-blast-suffix-distance", "kmer", "", "", "",false,false); parameters.push_back(psearch);
23                 CommandParameter pksize("ksize", "Number", "", "8", "", "", "",false,false); parameters.push_back(pksize);
24                 CommandParameter pmethod("method", "Multiple", "bayesian-knn", "bayesian", "", "", "",false,false); parameters.push_back(pmethod);
25                 CommandParameter pprocessors("processors", "Number", "", "1", "", "", "",false,false); parameters.push_back(pprocessors);
26                 CommandParameter pmatch("match", "Number", "", "1.0", "", "", "",false,false); parameters.push_back(pmatch);
27                 CommandParameter pmismatch("mismatch", "Number", "", "-1.0", "", "", "",false,false); parameters.push_back(pmismatch);
28                 CommandParameter pgapopen("gapopen", "Number", "", "-2.0", "", "", "",false,false); parameters.push_back(pgapopen);
29                 CommandParameter pgapextend("gapextend", "Number", "", "-1.0", "", "", "",false,false); parameters.push_back(pgapextend);
30                 //CommandParameter pflip("flip", "Boolean", "", "F", "", "", "",false,false); parameters.push_back(pflip);
31                 CommandParameter pcutoff("cutoff", "Number", "", "0", "", "", "",false,true); parameters.push_back(pcutoff);
32                 CommandParameter pprobs("probs", "Boolean", "", "T", "", "", "",false,false); parameters.push_back(pprobs);
33                 CommandParameter piters("iters", "Number", "", "100", "", "", "",false,true); parameters.push_back(piters);
34                 CommandParameter psave("save", "Boolean", "", "F", "", "", "",false,false); parameters.push_back(psave);
35                 CommandParameter pnumwanted("numwanted", "Number", "", "10", "", "", "",false,true); parameters.push_back(pnumwanted);
36                 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "",false,false); parameters.push_back(pinputdir);
37                 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "",false,false); parameters.push_back(poutputdir);
38                 
39                 vector<string> myArray;
40                 for (int i = 0; i < parameters.size(); i++) {   myArray.push_back(parameters[i].name);          }
41                 return myArray;
42         }
43         catch(exception& e) {
44                 m->errorOut(e, "ClassifySeqsCommand", "setParameters");
45                 exit(1);
46         }
47 }
48 //**********************************************************************************************************************
49 string ClassifySeqsCommand::getHelpString(){    
50         try {
51                 string helpString = "";
52                 helpString += "The classify.seqs command reads a fasta file containing sequences and creates a .taxonomy file and a .tax.summary file.\n";
53                 helpString += "The classify.seqs command parameters are reference, fasta, name, search, ksize, method, taxonomy, processors, match, mismatch, gapopen, gapextend, numwanted and probs.\n";
54                 helpString += "The reference, 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";
55                 helpString += "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";
56                 helpString += "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";
57                 helpString += "The group parameter allows you add a group file so you can have the summary totals broken up by group.\n";
58                 helpString += "The method parameter allows you to specify classification method to use.  Your options are: bayesian and knn. The default is bayesian.\n";
59                 helpString += "The ksize parameter allows you to specify the kmer size for finding most similar template to candidate.  The default is 8.\n";
60                 helpString += "The processors parameter allows you to specify the number of processors to use. The default is 1.\n";
61 #ifdef USE_MPI
62                 helpString += "When using MPI, the processors parameter is set to the number of MPI processes running. \n";
63 #endif
64                 helpString += "If the save parameter is set to true the reference sequences will be saved in memory, to clear them later you can use the clear.memory command. Default=f.";
65                 helpString += "The match parameter allows you to specify the bonus for having the same base. The default is 1.0.\n";
66                 helpString += "The mistmatch parameter allows you to specify the penalty for having different bases.  The default is -1.0.\n";
67                 helpString += "The gapopen parameter allows you to specify the penalty for opening a gap in an alignment. The default is -2.0.\n";
68                 helpString += "The gapextend parameter allows you to specify the penalty for extending a gap in an alignment.  The default is -1.0.\n";
69                 helpString += "The numwanted parameter allows you to specify the number of sequence matches you want with the knn method.  The default is 10.\n";
70                 helpString += "The cutoff parameter allows you to specify a bootstrap confidence threshold for your taxonomy.  The default is 0.\n";
71                 helpString += "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";
72                 helpString += "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";
73                 //helpString += "The flip parameter allows you shut off mothur's   The default is T.\n";
74                 helpString += "The classify.seqs command should be in the following format: \n";
75                 helpString += "classify.seqs(reference=yourTemplateFile, fasta=yourFastaFile, method=yourClassificationMethod, search=yourSearchmethod, ksize=yourKmerSize, taxonomy=yourTaxonomyFile, processors=yourProcessors) \n";
76                 helpString += "Example classify.seqs(fasta=amazon.fasta, reference=core.filtered, method=knn, search=gotoh, ksize=8, processors=2)\n";
77                 helpString += "The .taxonomy file consists of 2 columns: 1 = your sequence name, 2 = the taxonomy for your sequence. \n";
78                 helpString += "The .tax.summary is a summary of the different taxonomies represented in your fasta file. \n";
79                 helpString += "Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFastaFile).\n";
80                 return helpString;
81         }
82         catch(exception& e) {
83                 m->errorOut(e, "ClassifySeqsCommand", "getHelpString");
84                 exit(1);
85         }
86 }
87 //**********************************************************************************************************************
88 string ClassifySeqsCommand::getOutputFileNameTag(string type, string inputName=""){     
89         try {
90         string outputFileName = "";
91                 map<string, vector<string> >::iterator it;
92         
93         //is this a type this command creates
94         it = outputTypes.find(type);
95         if (it == outputTypes.end()) {  m->mothurOut("[ERROR]: this command doesn't create a " + type + " output file.\n"); }
96         else {
97             if (type == "taxonomy") {  outputFileName =  "taxonomy"; }
98             else if (type == "accnos") {  outputFileName =  "flip.accnos"; }
99             else if (type == "taxsummary") {  outputFileName =  "tax.summary"; }
100             else if (type == "matchdist") {  outputFileName =  "match.dist"; }
101             else { m->mothurOut("[ERROR]: No definition for type " + type + " output file tag.\n"); m->control_pressed = true;  }
102         }
103         return outputFileName;
104         }
105         catch(exception& e) {
106                 m->errorOut(e, "ClassifySeqsCommand", "getOutputFileNameTag");
107                 exit(1);
108         }
109 }
110 //**********************************************************************************************************************
111 ClassifySeqsCommand::ClassifySeqsCommand(){     
112         try {
113                 abort = true; calledHelp = true; 
114                 setParameters();
115                 vector<string> tempOutNames;
116                 outputTypes["taxonomy"] = tempOutNames;
117                 outputTypes["accnos"] = tempOutNames;
118                 outputTypes["taxsummary"] = tempOutNames;
119                 outputTypes["matchdist"] = tempOutNames;
120         }
121         catch(exception& e) {
122                 m->errorOut(e, "ClassifySeqsCommand", "ClassifySeqsCommand");
123                 exit(1);
124         }
125 }
126 //**********************************************************************************************************************
127 ClassifySeqsCommand::ClassifySeqsCommand(string option)  {
128         try {
129                 abort = false; calledHelp = false;   
130                 rdb = ReferenceDB::getInstance();
131                 
132                 //allow user to run help
133                 if(option == "help") { help(); abort = true; calledHelp = true; }
134                 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
135                 
136                 else {
137                         vector<string> myArray = setParameters();
138                         
139                         OptionParser parser(option);
140                         map<string, string> parameters = parser.getParameters(); 
141                         
142                         ValidParameters validParameter("classify.seqs");
143                         map<string, string>::iterator it;
144                         
145                         //check to make sure all parameters are valid for command
146                         for (it = parameters.begin(); it != parameters.end(); it++) { 
147                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
148                         }
149                         
150                         //initialize outputTypes
151                         vector<string> tempOutNames;
152                         outputTypes["taxonomy"] = tempOutNames;
153                         outputTypes["taxsummary"] = tempOutNames;
154                         outputTypes["matchdist"] = tempOutNames;
155                         outputTypes["accnos"] = tempOutNames;
156                         
157                         //if the user changes the output directory command factory will send this info to us in the output parameter 
158                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  outputDir = "";         }
159                         
160                         //if the user changes the input directory command factory will send this info to us in the output parameter 
161                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
162                         if (inputDir == "not found"){   inputDir = "";          }
163                         else {
164                                 string path;
165                                 it = parameters.find("reference");
166                                 //user has given a template file
167                                 if(it != parameters.end()){ 
168                                         path = m->hasPath(it->second);
169                                         //if the user has not given a path then, add inputdir. else leave path alone.
170                                         if (path == "") {       parameters["reference"] = inputDir + it->second;                }
171                                 }
172                                 
173                                 it = parameters.find("taxonomy");
174                                 //user has given a template file
175                                 if(it != parameters.end()){ 
176                                         path = m->hasPath(it->second);
177                                         //if the user has not given a path then, add inputdir. else leave path alone.
178                                         if (path == "") {       parameters["taxonomy"] = inputDir + it->second;         }
179                                 }
180                                 
181                                 it = parameters.find("group");
182                                 //user has given a template file
183                                 if(it != parameters.end()){ 
184                                         path = m->hasPath(it->second);
185                                         //if the user has not given a path then, add inputdir. else leave path alone.
186                                         if (path == "") {       parameters["group"] = inputDir + it->second;            }
187                                 }
188                         }
189
190                         fastaFileName = validParameter.validFile(parameters, "fasta", false);
191                         if (fastaFileName == "not found") {                             
192                                 //if there is a current fasta file, use it
193                                 string filename = m->getFastaFile(); 
194                                 if (filename != "") { fastaFileNames.push_back(filename); m->mothurOut("Using " + filename + " as input file for the fasta parameter."); m->mothurOutEndLine(); }
195                                 else {  m->mothurOut("You have no current fastafile and the fasta parameter is required."); m->mothurOutEndLine(); abort = true; }
196                         }
197                         else { 
198                                 m->splitAtDash(fastaFileName, fastaFileNames);
199                                 
200                                 //go through files and make sure they are good, if not, then disregard them
201                                 for (int i = 0; i < fastaFileNames.size(); i++) {
202                                         
203                                         bool ignore = false;
204                                         if (fastaFileNames[i] == "current") { 
205                                                 fastaFileNames[i] = m->getFastaFile(); 
206                                                 if (fastaFileNames[i] != "") {  m->mothurOut("Using " + fastaFileNames[i] + " as input file for the fasta parameter where you had given current."); m->mothurOutEndLine(); }
207                                                 else {  
208                                                         m->mothurOut("You have no current fastafile, ignoring current."); m->mothurOutEndLine(); ignore=true; 
209                                                         //erase from file list
210                                                         fastaFileNames.erase(fastaFileNames.begin()+i);
211                                                         i--;
212                                                 }
213                                         }
214                                         
215                                         if (!ignore) {
216                                                 
217                                                 if (inputDir != "") {
218                                                         string path = m->hasPath(fastaFileNames[i]);
219                                                         //if the user has not given a path then, add inputdir. else leave path alone.
220                                                         if (path == "") {       fastaFileNames[i] = inputDir + fastaFileNames[i];               }
221                                                 }
222                                                 
223                                                 int ableToOpen;
224                                                 
225                                                 ifstream in;
226                                                 ableToOpen = m->openInputFile(fastaFileNames[i], in, "noerror");
227                                         
228                                                 //if you can't open it, try default location
229                                                 if (ableToOpen == 1) {
230                                                         if (m->getDefaultPath() != "") { //default path is set
231                                                                 string tryPath = m->getDefaultPath() + m->getSimpleName(fastaFileNames[i]);
232                                                                 m->mothurOut("Unable to open " + fastaFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
233                                                                 ifstream in2;
234                                                                 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
235                                                                 in2.close();
236                                                                 fastaFileNames[i] = tryPath;
237                                                         }
238                                                 }
239                                                 
240                                                 if (ableToOpen == 1) {
241                                                         if (m->getOutputDir() != "") { //default path is set
242                                                                 string tryPath = m->getOutputDir() + m->getSimpleName(fastaFileNames[i]);
243                                                                 m->mothurOut("Unable to open " + fastaFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
244                                                                 ifstream in2;
245                                                                 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
246                                                                 in2.close();
247                                                                 fastaFileNames[i] = tryPath;
248                                                         }
249                                                 }
250                                                 
251                                                 in.close();
252                                                 
253                                                 if (ableToOpen == 1) { 
254                                                         m->mothurOut("Unable to open " + fastaFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine(); 
255                                                         //erase from file list
256                                                         fastaFileNames.erase(fastaFileNames.begin()+i);
257                                                         i--;
258                                                 }else {
259                                                         m->setFastaFile(fastaFileNames[i]);
260                                                 }
261                                         }
262                                         
263                                 }
264                                 
265                                 //make sure there is at least one valid file left
266                                 if (fastaFileNames.size() == 0) { m->mothurOut("no valid files."); m->mothurOutEndLine(); abort = true; }
267                         }
268
269                         namefile = validParameter.validFile(parameters, "name", false);
270                         if (namefile == "not found") { namefile = "";  }
271
272                         else { 
273                                 m->splitAtDash(namefile, namefileNames);
274                                 
275                                 //go through files and make sure they are good, if not, then disregard them
276                                 for (int i = 0; i < namefileNames.size(); i++) {
277                                         bool ignore = false;
278                                         if (namefileNames[i] == "current") { 
279                                                 namefileNames[i] = m->getNameFile(); 
280                                                 if (namefileNames[i] != "") {  m->mothurOut("Using " + namefileNames[i] + " as input file for the name parameter where you had given current."); m->mothurOutEndLine(); }
281                                                 else {  
282                                                         m->mothurOut("You have no current namefile, ignoring current."); m->mothurOutEndLine(); ignore=true; 
283                                                         //erase from file list
284                                                         namefileNames.erase(namefileNames.begin()+i);
285                                                         i--;
286                                                 }
287                                         }
288                                         
289                                         if (!ignore) {
290                                                 
291                                                 if (inputDir != "") {
292                                                         string path = m->hasPath(namefileNames[i]);
293                                                         //if the user has not given a path then, add inputdir. else leave path alone.
294                                                         if (path == "") {       namefileNames[i] = inputDir + namefileNames[i];         }
295                                                 }
296                                                 int ableToOpen;
297                                                 
298                                                 ifstream in;
299                                                 ableToOpen = m->openInputFile(namefileNames[i], in, "noerror");
300                                         
301                                                 //if you can't open it, try default location
302                                                 if (ableToOpen == 1) {
303                                                         if (m->getDefaultPath() != "") { //default path is set
304                                                                 string tryPath = m->getDefaultPath() + m->getSimpleName(namefileNames[i]);
305                                                                 m->mothurOut("Unable to open " + namefileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
306                                                                 ifstream in2;
307                                                                 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
308                                                                 in2.close();
309                                                                 namefileNames[i] = tryPath;
310                                                         }
311                                                 }
312                                                 
313                                                 if (ableToOpen == 1) {
314                                                         if (m->getOutputDir() != "") { //default path is set
315                                                                 string tryPath = m->getOutputDir() + m->getSimpleName(namefileNames[i]);
316                                                                 m->mothurOut("Unable to open " + namefileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
317                                                                 ifstream in2;
318                                                                 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
319                                                                 in2.close();
320                                                                 namefileNames[i] = tryPath;
321                                                         }
322                                                 }
323                                                 in.close();
324                                                 
325                                                 if (ableToOpen == 1) { 
326                                                         m->mothurOut("Unable to open " + namefileNames[i] + ". It will be disregarded."); m->mothurOutEndLine();  abort = true;
327                                                         //erase from file list
328                                                         namefileNames.erase(namefileNames.begin()+i);
329                                                         i--;
330                                                 }else {
331                                                         m->setNameFile(namefileNames[i]);
332                                                 }
333                                         }
334                                 }
335                         }
336
337                         if (namefile != "") {
338                                 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(); }
339                         }
340                         
341                         groupfile = validParameter.validFile(parameters, "group", false);
342                         if (groupfile == "not found") { groupfile = "";  }
343                         else { 
344                                 m->splitAtDash(groupfile, groupfileNames);
345                                 
346                                 //go through files and make sure they are good, if not, then disregard them
347                                 for (int i = 0; i < groupfileNames.size(); i++) {
348                                         if (inputDir != "") {
349                                                 string path = m->hasPath(groupfileNames[i]);
350                                                 //if the user has not given a path then, add inputdir. else leave path alone.
351                                                 if (path == "") {       groupfileNames[i] = inputDir + groupfileNames[i];               }
352                                         }
353                                         int ableToOpen;
354                                         
355                                         ifstream in;
356                                         ableToOpen = m->openInputFile(groupfileNames[i], in, "noerror");
357                                 
358                                         //if you can't open it, try default location
359                                         if (ableToOpen == 1) {
360                                                 if (m->getDefaultPath() != "") { //default path is set
361                                                         string tryPath = m->getDefaultPath() + m->getSimpleName(groupfileNames[i]);
362                                                         m->mothurOut("Unable to open " + groupfileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
363                                                         ifstream in2;
364                                                         ableToOpen = m->openInputFile(tryPath, in2, "noerror");
365                                                         in2.close();
366                                                         groupfileNames[i] = tryPath;
367                                                 }
368                                         }
369                                         
370                                         if (ableToOpen == 1) {
371                                                 if (m->getOutputDir() != "") { //default path is set
372                                                         string tryPath = m->getOutputDir() + m->getSimpleName(groupfileNames[i]);
373                                                         m->mothurOut("Unable to open " + groupfileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
374                                                         ifstream in2;
375                                                         ableToOpen = m->openInputFile(tryPath, in2, "noerror");
376                                                         in2.close();
377                                                         groupfileNames[i] = tryPath;
378                                                 }
379                                         }
380                                         
381                                         in.close();
382                                         
383                                         if (ableToOpen == 1) { 
384                                                 m->mothurOut("Unable to open " + groupfileNames[i] + ". It will be disregarded."); m->mothurOutEndLine(); groupfileNames[i] = "";
385                                                 //erase from file list
386                                                 groupfileNames.erase(groupfileNames.begin()+i);
387                                                 i--;
388                                         }else {
389                                                 m->setGroupFile(groupfileNames[i]);
390                                         }
391                                 }
392                         }
393
394                         if (groupfile != "") {
395                                 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(); }
396                         }else {
397                                 for (int i = 0; i < fastaFileNames.size(); i++) {  groupfileNames.push_back("");  }
398                         }
399                         
400                         //check for optional parameter and set defaults
401                         // ...at some point should added some additional type checking...
402                         string temp;
403                         temp = validParameter.validFile(parameters, "ksize", false);            if (temp == "not found"){       temp = "8";                             }
404                         m->mothurConvert(temp, kmerSize); 
405                         
406                         temp = validParameter.validFile(parameters, "processors", false);       if (temp == "not found"){       temp = m->getProcessors();      }
407                         m->setProcessors(temp);
408                         m->mothurConvert(temp, processors); 
409                         
410                         temp = validParameter.validFile(parameters, "save", false);                     if (temp == "not found"){       temp = "f";                             }
411                         save = m->isTrue(temp); 
412                         rdb->save = save; 
413                         if (save) { //clear out old references
414                                 rdb->clearMemory();     
415                         }
416                         
417                         //this has to go after save so that if the user sets save=t and provides no reference we abort
418                         templateFileName = validParameter.validFile(parameters, "reference", true);
419                         if (templateFileName == "not found") { 
420                                 //check for saved reference sequences
421                                 if (rdb->referenceSeqs.size() != 0) {
422                                         templateFileName = "saved";
423                                 }else {
424                                         m->mothurOut("[ERROR]: You don't have any saved reference sequences and the reference parameter is a required for the classify.seqs command."); 
425                                         m->mothurOutEndLine();
426                                         abort = true; 
427                                 }
428                         }else if (templateFileName == "not open") { abort = true; }     
429                         else {  if (save) {     rdb->setSavedReference(templateFileName);       }       }
430                         
431                         //this has to go after save so that if the user sets save=t and provides no reference we abort
432                         taxonomyFileName = validParameter.validFile(parameters, "taxonomy", true);
433                         if (taxonomyFileName == "not found") { 
434                                 //check for saved reference sequences
435                                 if (rdb->wordGenusProb.size() != 0) {
436                                         taxonomyFileName = "saved";
437                                 }else {
438                                         m->mothurOut("[ERROR]: You don't have any saved taxonomy information and the taxonomy parameter is a required for the classify.seqs command."); 
439                                         m->mothurOutEndLine();
440                                         abort = true; 
441                                 }
442                         }else if (taxonomyFileName == "not open") { abort = true; }     
443                         else {  if (save) {     rdb->setSavedTaxonomy(taxonomyFileName);        }       }
444                         
445                         search = validParameter.validFile(parameters, "search", false);         if (search == "not found"){     search = "kmer";                }
446                         
447                         method = validParameter.validFile(parameters, "method", false);         if (method == "not found"){     method = "bayesian";    }
448                         
449                         temp = validParameter.validFile(parameters, "match", false);            if (temp == "not found"){       temp = "1.0";                   }
450                         m->mothurConvert(temp, match);  
451                         
452                         temp = validParameter.validFile(parameters, "mismatch", false);         if (temp == "not found"){       temp = "-1.0";                  }
453                         m->mothurConvert(temp, misMatch);  
454                         
455                         temp = validParameter.validFile(parameters, "gapopen", false);          if (temp == "not found"){       temp = "-2.0";                  }
456                         m->mothurConvert(temp, gapOpen);  
457                         
458                         temp = validParameter.validFile(parameters, "gapextend", false);        if (temp == "not found"){       temp = "-1.0";                  }
459                         m->mothurConvert(temp, gapExtend); 
460                         
461                         temp = validParameter.validFile(parameters, "numwanted", false);        if (temp == "not found"){       temp = "10";                    }
462                         m->mothurConvert(temp, numWanted);
463                         
464                         temp = validParameter.validFile(parameters, "cutoff", false);           if (temp == "not found"){       temp = "0";                             }
465                         m->mothurConvert(temp, cutoff);
466                         
467                         temp = validParameter.validFile(parameters, "probs", false);            if (temp == "not found"){       temp = "true";                  }
468                         probs = m->isTrue(temp);
469                         
470                         //temp = validParameter.validFile(parameters, "flip", false);                   if (temp == "not found"){       temp = "T";                             }
471                         //flip = m->isTrue(temp); 
472                         flip = true;
473                         
474                         temp = validParameter.validFile(parameters, "iters", false);            if (temp == "not found") { temp = "100";                        }
475                         m->mothurConvert(temp, iters); 
476
477                         
478                         if ((method == "bayesian") && (search != "kmer"))  { 
479                                 m->mothurOut("The bayesian method requires the kmer search." + search + "will be disregarded." ); m->mothurOutEndLine();
480                                 search = "kmer";
481                         }
482                         
483             if (!abort) {
484                 if (namefileNames.size() == 0){
485                     if (fastaFileNames.size() != 0) {
486                         vector<string> files; files.push_back(fastaFileNames[fastaFileNames.size()-1]); 
487                         parser.getNameFile(files);
488                     }
489                 }
490             }
491         }
492         }
493         catch(exception& e) {
494                 m->errorOut(e, "ClassifySeqsCommand", "ClassifySeqsCommand");
495                 exit(1);
496         }
497 }
498
499 //**********************************************************************************************************************
500 ClassifySeqsCommand::~ClassifySeqsCommand(){    
501         if (abort == false) {
502                 for (int i = 0; i < lines.size(); i++) {  delete lines[i];  }  lines.clear();
503         }
504 }
505 //**********************************************************************************************************************
506
507 int ClassifySeqsCommand::execute(){
508         try {
509                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
510         
511                 if(method == "bayesian"){       classify = new Bayesian(taxonomyFileName, templateFileName, search, kmerSize, cutoff, iters, rand(), flip);             }
512                 else if(method == "knn"){       classify = new Knn(taxonomyFileName, templateFileName, search, kmerSize, gapOpen, gapExtend, match, misMatch, numWanted, rand());                               }
513                 else {
514                         m->mothurOut(search + " is not a valid method option. I will run the command using bayesian.");
515                         m->mothurOutEndLine();
516                         classify = new Bayesian(taxonomyFileName, templateFileName, search, kmerSize, cutoff, iters, rand(), flip);     
517                 }
518                 
519                 if (m->control_pressed) { delete classify; return 0; }
520                                 
521                 for (int s = 0; s < fastaFileNames.size(); s++) {
522                 
523                         m->mothurOut("Classifying sequences from " + fastaFileNames[s] + " ..." ); m->mothurOutEndLine();
524                         
525                         string baseTName = taxonomyFileName;
526                         if (taxonomyFileName == "saved") {baseTName = rdb->getSavedTaxonomy();  }
527                         
528             //set rippedTaxName to 
529                         string RippedTaxName = "";
530             bool foundDot = false;
531             for (int i = baseTName.length()-1; i >= 0; i--) {
532                 if (foundDot && (baseTName[i] != '.')) {  RippedTaxName = baseTName[i] + RippedTaxName; }
533                 else if (foundDot && (baseTName[i] == '.')) {  break; }
534                 else if (!foundDot && (baseTName[i] == '.')) {  foundDot = true; }
535             }
536             if (RippedTaxName != "") { RippedTaxName +=  "."; }   
537           
538                         if (outputDir == "") { outputDir += m->hasPath(fastaFileNames[s]); }
539                         string newTaxonomyFile = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + RippedTaxName + getOutputFileNameTag("taxonomy");
540                         string newaccnosFile = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + RippedTaxName + getOutputFileNameTag("accnos");
541                         string tempTaxonomyFile = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + "taxonomy.temp";
542                         string taxSummary = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + RippedTaxName + getOutputFileNameTag("taxsummary");
543                         
544                         if ((method == "knn") && (search == "distance")) { 
545                                 string DistName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + getOutputFileNameTag("matchdist");
546                                 classify->setDistName(DistName);  outputNames.push_back(DistName); outputTypes["matchdist"].push_back(DistName);
547                         }
548                         
549                         outputNames.push_back(newTaxonomyFile); outputTypes["taxonomy"].push_back(newTaxonomyFile);
550                         outputNames.push_back(newaccnosFile); outputTypes["accnos"].push_back(newaccnosFile);
551                         outputNames.push_back(taxSummary);      outputTypes["taxsummary"].push_back(taxSummary);
552                         
553                         int start = time(NULL);
554                         int numFastaSeqs = 0;
555                         for (int i = 0; i < lines.size(); i++) {  delete lines[i];  }  lines.clear();
556                         
557 #ifdef USE_MPI  
558                                 int pid, numSeqsPerProcessor; 
559                                 int tag = 2001;
560                                 vector<unsigned long long> MPIPos;
561                                 
562                                 MPI_Status status; 
563                                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
564                                 MPI_Comm_size(MPI_COMM_WORLD, &processors); 
565
566                                 MPI_File inMPI;
567                                 MPI_File outMPINewTax;
568                                 MPI_File outMPITempTax;
569                                 MPI_File outMPIAcc;
570                                                         
571                                 int outMode=MPI_MODE_CREATE|MPI_MODE_WRONLY; 
572                                 int inMode=MPI_MODE_RDONLY; 
573                                 
574                                 char outNewTax[1024];
575                                 strcpy(outNewTax, newTaxonomyFile.c_str());
576                                 
577                                 char outTempTax[1024];
578                                 strcpy(outTempTax, tempTaxonomyFile.c_str());
579                         
580                                 char outAcc[1024];
581                                 strcpy(outAcc, newaccnosFile.c_str());
582                                 
583                                 char inFileName[1024];
584                                 strcpy(inFileName, fastaFileNames[s].c_str());
585
586                                 MPI_File_open(MPI_COMM_WORLD, inFileName, inMode, MPI_INFO_NULL, &inMPI);  //comm, filename, mode, info, filepointer
587                                 MPI_File_open(MPI_COMM_WORLD, outNewTax, outMode, MPI_INFO_NULL, &outMPINewTax);
588                                 MPI_File_open(MPI_COMM_WORLD, outTempTax, outMode, MPI_INFO_NULL, &outMPITempTax);
589                                 MPI_File_open(MPI_COMM_WORLD, outAcc, outMode, MPI_INFO_NULL, &outMPIAcc);
590                                 
591                                 if (m->control_pressed) { outputTypes.clear(); MPI_File_close(&inMPI);  MPI_File_close(&outMPINewTax);  MPI_File_close(&outMPIAcc);   MPI_File_close(&outMPITempTax);  delete classify;  return 0;  }
592                                 
593                                 if (pid == 0) { //you are the root process 
594                                         
595                                         MPIPos = m->setFilePosFasta(fastaFileNames[s], numFastaSeqs); //fills MPIPos, returns numSeqs
596                                         
597                                         //send file positions to all processes
598                                         for(int i = 1; i < processors; i++) { 
599                                                 MPI_Send(&numFastaSeqs, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
600                                                 MPI_Send(&MPIPos[0], (numFastaSeqs+1), MPI_LONG, i, tag, MPI_COMM_WORLD);
601                                         }
602                                         
603                                         //figure out how many sequences you have to align
604                                         numSeqsPerProcessor = numFastaSeqs / processors;
605                                         int startIndex =  pid * numSeqsPerProcessor;
606                                         if(pid == (processors - 1)){    numSeqsPerProcessor = numFastaSeqs - pid * numSeqsPerProcessor;         }
607                                         
608                                 
609                                         //align your part
610                                         driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPINewTax, outMPITempTax, outMPIAcc, MPIPos);
611                                         
612                                         if (m->control_pressed) {  outputTypes.clear(); MPI_File_close(&inMPI);  MPI_File_close(&outMPINewTax); MPI_File_close(&outMPIAcc);   MPI_File_close(&outMPITempTax);  for (int i = 0; i < outputNames.size(); i++) {   m->mothurRemove(outputNames[i]);        } delete classify; return 0;  }
613                                         
614                                         for (int i = 1; i < processors; i++) {
615                                                 int done;
616                                                 MPI_Recv(&done, 1, MPI_INT, i, tag, MPI_COMM_WORLD, &status);
617                                         }
618                                 }else{ //you are a child process
619                                         MPI_Recv(&numFastaSeqs, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
620                                         MPIPos.resize(numFastaSeqs+1);
621                                         MPI_Recv(&MPIPos[0], (numFastaSeqs+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
622                                         
623                                         //figure out how many sequences you have to align
624                                         numSeqsPerProcessor = numFastaSeqs / processors;
625                                         int startIndex =  pid * numSeqsPerProcessor;
626                                         if(pid == (processors - 1)){    numSeqsPerProcessor = numFastaSeqs - pid * numSeqsPerProcessor;         }
627                                         
628                                         
629                                         //align your part
630                                         driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPINewTax, outMPITempTax, outMPIAcc, MPIPos);
631                                         
632                                         if (m->control_pressed) {  outputTypes.clear(); MPI_File_close(&inMPI);  MPI_File_close(&outMPINewTax);  MPI_File_close(&outMPIAcc);  MPI_File_close(&outMPITempTax);  delete classify; return 0;  }
633
634                                         int done = 0;
635                                         MPI_Send(&done, 1, MPI_INT, 0, tag, MPI_COMM_WORLD); 
636                                 }
637                                 
638                                 //close files 
639                                 MPI_File_close(&inMPI);
640                                 MPI_File_close(&outMPINewTax);
641                                 MPI_File_close(&outMPITempTax);
642                                 MPI_File_close(&outMPIAcc); 
643                                 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
644                                 
645 #else
646                 
647                         vector<unsigned long long> positions; 
648 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
649                         positions = m->divideFile(fastaFileNames[s], processors);
650                         for (int i = 0; i < (positions.size()-1); i++) {        lines.push_back(new linePair(positions[i], positions[(i+1)]));  }
651 #else
652                         if (processors == 1) {
653                                 lines.push_back(new linePair(0, 1000));
654                         }else {
655                                 positions = m->setFilePosFasta(fastaFileNames[s], numFastaSeqs); 
656                 if (positions.size() < processors) { processors = positions.size(); }
657                                 
658                                 //figure out how many sequences you have to process
659                                 int numSeqsPerProcessor = numFastaSeqs / processors;
660                                 for (int i = 0; i < processors; i++) {
661                                         int startIndex =  i * numSeqsPerProcessor;
662                                         if(i == (processors - 1)){      numSeqsPerProcessor = numFastaSeqs - i * numSeqsPerProcessor;   }
663                                         lines.push_back(new linePair(positions[startIndex], numSeqsPerProcessor));
664                                 }
665                         }
666 #endif
667                         if(processors == 1){
668                                 numFastaSeqs = driver(lines[0], newTaxonomyFile, tempTaxonomyFile, newaccnosFile, fastaFileNames[s]);
669                         }else{
670                                 numFastaSeqs = createProcesses(newTaxonomyFile, tempTaxonomyFile, newaccnosFile, fastaFileNames[s]); 
671                         }
672 #endif
673                         
674                         if (!m->isBlank(newaccnosFile)) { m->mothurOutEndLine(); m->mothurOut("[WARNING]: mothur suspects some of your sequences may be reversed, please check " + newaccnosFile + " for the list of the sequences."); m->mothurOutEndLine(); }
675
676                 m->mothurOutEndLine();
677                 m->mothurOut("It took " + toString(time(NULL) - start) + " secs to classify " + toString(numFastaSeqs) + " sequences."); m->mothurOutEndLine(); m->mothurOutEndLine();
678                 start = time(NULL);
679                 
680                 
681
682                 #ifdef USE_MPI  
683                         if (pid == 0) {  //this part does not need to be paralellized
684                         
685                                 if(namefile != "") { m->mothurOut("Reading " + namefileNames[s] + "..."); cout.flush();  MPIReadNamesFile(namefileNames[s]);  m->mothurOut("  Done."); m->mothurOutEndLine(); }
686                 #else
687                         //read namefile
688                         if(namefile != "") {
689                         
690                             m->mothurOut("Reading " + namefileNames[s] + "..."); cout.flush();
691                                 nameMap.clear(); //remove old names
692                                 m->readNames(namefileNames[s], nameMap);                                
693                                 m->mothurOut("  Done."); m->mothurOutEndLine();
694                         }
695                 #endif
696
697                         string group = "";
698                         if (groupfile != "") {  group = groupfileNames[s]; }
699                         
700                         PhyloSummary taxaSum(baseTName, group);
701                         
702                         if (m->control_pressed) { outputTypes.clear();  for (int i = 0; i < outputNames.size(); i++) {  m->mothurRemove(outputNames[i]);        } delete classify; return 0; }
703                 
704                         if (namefile == "") {  taxaSum.summarize(tempTaxonomyFile);  }
705                         else {
706                                 ifstream in;
707                                 m->openInputFile(tempTaxonomyFile, in);
708                                 
709                                 //read in users taxonomy file and add sequences to tree
710                                 string name, taxon;
711                                 
712                                 while(!in.eof()){
713                                         in >> name >> taxon; m->gobble(in);
714                                         
715                                         itNames = nameMap.find(name);
716                 
717                                         if (itNames == nameMap.end()) { 
718                                                 m->mothurOut(name + " is not in your name file please correct."); m->mothurOutEndLine(); exit(1);
719                                         }else{
720                                                 for (int i = 0; i < itNames->second.size(); i++) { 
721                                                         taxaSum.addSeqToTree(itNames->second[i], taxon);  //add it as many times as there are identical seqs
722                                                 }
723                                                 itNames->second.clear();
724                                                 nameMap.erase(itNames->first);
725                                         }
726                                 }
727                                 in.close();
728                         }
729                         m->mothurRemove(tempTaxonomyFile);
730                         
731                         if (m->control_pressed) {  outputTypes.clear(); for (int i = 0; i < outputNames.size(); i++) {  m->mothurRemove(outputNames[i]);        } delete classify; return 0; }
732                         
733                         //print summary file
734                         ofstream outTaxTree;
735                         m->openOutputFile(taxSummary, outTaxTree);
736                         taxaSum.print(outTaxTree);
737                         outTaxTree.close();
738                         
739                         //output taxonomy with the unclassified bins added
740                         ifstream inTax;
741                         m->openInputFile(newTaxonomyFile, inTax);
742                         
743                         ofstream outTax;
744                         string unclass = newTaxonomyFile + ".unclass.temp";
745                         m->openOutputFile(unclass, outTax);
746                         
747                         //get maxLevel from phylotree so you know how many 'unclassified's to add
748                         int maxLevel = taxaSum.getMaxLevel();
749                                                         
750                         //read taxfile - this reading and rewriting is done to preserve the confidence scores.
751                         string name, taxon;
752                         while (!inTax.eof()) {
753                                 if (m->control_pressed) { outputTypes.clear();  for (int i = 0; i < outputNames.size(); i++) {  m->mothurRemove(outputNames[i]);        } m->mothurRemove(unclass); delete classify; return 0; }
754
755                                 inTax >> name >> taxon; m->gobble(inTax);
756                                 
757                                 string newTax = addUnclassifieds(taxon, maxLevel);
758                                 
759                                 outTax << name << '\t' << newTax << endl;
760                         }
761                         inTax.close();  
762                         outTax.close();
763                         
764                         m->mothurRemove(newTaxonomyFile);
765                         rename(unclass.c_str(), newTaxonomyFile.c_str());
766                         
767                         m->mothurOutEndLine();
768                         m->mothurOut("It took " + toString(time(NULL) - start) + " secs to create the summary file for " + toString(numFastaSeqs) + " sequences."); m->mothurOutEndLine(); m->mothurOutEndLine();
769                         
770                         #ifdef USE_MPI  
771                                 }
772                         #endif
773
774                         m->mothurOutEndLine();
775                         m->mothurOut("Output File Names: "); m->mothurOutEndLine();
776                         for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }
777                         m->mothurOutEndLine();
778                 }
779                 
780                 //set taxonomy file as new current taxonomyfile
781                 string current = "";
782                 itTypes = outputTypes.find("taxonomy");
783                 if (itTypes != outputTypes.end()) {
784                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setTaxonomyFile(current); }
785                 }
786                 
787                 current = "";
788                 itTypes = outputTypes.find("accnos");
789                 if (itTypes != outputTypes.end()) {
790                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setAccnosFile(current); }
791                 }
792                 
793                 delete classify;
794                 
795                 return 0;
796         }
797         catch(exception& e) {
798                 m->errorOut(e, "ClassifySeqsCommand", "execute");
799                 exit(1);
800         }
801 }
802
803 /**************************************************************************************************/
804 string ClassifySeqsCommand::addUnclassifieds(string tax, int maxlevel) {
805         try{
806                 string newTax, taxon;
807                 int level = 0;
808                 
809                 //keep what you have counting the levels
810                 while (tax.find_first_of(';') != -1) {
811                         //get taxon
812                         taxon = tax.substr(0,tax.find_first_of(';'))+';';
813                         tax = tax.substr(tax.find_first_of(';')+1, tax.length());
814                         newTax += taxon;
815                         level++;
816                 }
817                 
818                 //add "unclassified" until you reach maxLevel
819                 while (level < maxlevel) {
820                         newTax += "unclassified;";
821                         level++;
822                 }
823                 
824                 return newTax;
825         }
826         catch(exception& e) {
827                 m->errorOut(e, "ClassifySeqsCommand", "addUnclassifieds");
828                 exit(1);
829         }
830 }
831
832 /**************************************************************************************************/
833
834 int ClassifySeqsCommand::createProcesses(string taxFileName, string tempTaxFile, string accnos, string filename) {
835         try {
836                 
837                 int num = 0;
838                 processIDS.clear();
839                 
840 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
841                 int process = 1;
842                 
843                 //loop through and create all the processes you want
844                 while (process != processors) {
845                         int pid = fork();
846                         
847                         if (pid > 0) {
848                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
849                                 process++;
850                         }else if (pid == 0){
851                                 num = driver(lines[process], taxFileName + toString(getpid()) + ".temp", tempTaxFile + toString(getpid()) + ".temp", accnos + toString(getpid()) + ".temp", filename);
852
853                                 //pass numSeqs to parent
854                                 ofstream out;
855                                 string tempFile = filename + toString(getpid()) + ".num.temp";
856                                 m->openOutputFile(tempFile, out);
857                                 out << num << endl;
858                                 out.close();
859
860                                 exit(0);
861                         }else { 
862                                 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); 
863                                 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
864                                 exit(0);
865                         }
866                 }
867                 
868                 //parent does its part
869                 num = driver(lines[0], taxFileName, tempTaxFile, accnos, filename);
870                 
871                 //force parent to wait until all the processes are done
872                 for (int i=0;i<processIDS.size();i++) { 
873                         int temp = processIDS[i];
874                         wait(&temp);
875                 }
876                 
877                 for (int i = 0; i < processIDS.size(); i++) {
878                         ifstream in;
879                         string tempFile =  filename + toString(processIDS[i]) + ".num.temp";
880                         m->openInputFile(tempFile, in);
881                         if (!in.eof()) { int tempNum = 0; in >> tempNum; num += tempNum; }
882                         in.close(); m->mothurRemove(m->getFullPathName(tempFile));
883                 }
884 #else
885                 //////////////////////////////////////////////////////////////////////////////////////////////////////
886                 //Windows version shared memory, so be careful when passing variables through the alignData struct. 
887                 //Above fork() will clone, so memory is separate, but that's not the case with windows, 
888                 //////////////////////////////////////////////////////////////////////////////////////////////////////
889                 
890                 vector<classifyData*> pDataArray; 
891                 DWORD   dwThreadIdArray[processors-1];
892                 HANDLE  hThreadArray[processors-1]; 
893                 
894                 //Create processor worker threads.
895                 for( int i=0; i<processors-1; i++ ){
896                         // Allocate memory for thread data.
897                         string extension = "";
898                         if (i != 0) { extension = toString(i) + ".temp"; processIDS.push_back(i); }
899                         
900                         classifyData* tempclass = new classifyData((accnos + extension), probs, method, templateFileName, taxonomyFileName, (taxFileName + extension), (tempTaxFile + extension), filename, search, kmerSize, iters, numWanted, m, lines[i]->start, lines[i]->end, match, misMatch, gapOpen, gapExtend, cutoff, i, flip);
901                         pDataArray.push_back(tempclass);
902                         
903                         //MySeqSumThreadFunction is in header. It must be global or static to work with the threads.
904                         //default security attributes, thread function name, argument to thread function, use default creation flags, returns the thread identifier
905                         hThreadArray[i] = CreateThread(NULL, 0, MyClassThreadFunction, pDataArray[i], 0, &dwThreadIdArray[i]);  
906                         
907                 }
908                 
909                 //parent does its part
910                 num = driver(lines[processors-1], taxFileName + toString(processors-1) + ".temp", tempTaxFile + toString(processors-1) + ".temp", accnos + toString(processors-1) + ".temp", filename);
911                 processIDS.push_back((processors-1));
912                 
913                 //Wait until all threads have terminated.
914                 WaitForMultipleObjects(processors-1, hThreadArray, TRUE, INFINITE);
915                 
916                 //Close all thread handles and free memory allocations.
917                 for(int i=0; i < pDataArray.size(); i++){
918                         num += pDataArray[i]->count;
919                         CloseHandle(hThreadArray[i]);
920                         delete pDataArray[i];
921                 }
922                 
923         #endif  
924         vector<string> nonBlankAccnosFiles;
925                 if (!(m->isBlank(accnos))) { nonBlankAccnosFiles.push_back(accnos); }
926                 else { m->mothurRemove(accnos); } //remove so other files can be renamed to it
927         
928                 for(int i=0;i<processIDS.size();i++){
929                         m->appendFiles((taxFileName + toString(processIDS[i]) + ".temp"), taxFileName);
930                         m->appendFiles((tempTaxFile + toString(processIDS[i]) + ".temp"), tempTaxFile);
931             if (!(m->isBlank(accnos + toString(processIDS[i]) + ".temp"))) {
932                                 nonBlankAccnosFiles.push_back(accnos + toString(processIDS[i]) + ".temp");
933                         }else { m->mothurRemove((accnos + toString(processIDS[i]) + ".temp"));  }
934
935                         m->mothurRemove((m->getFullPathName(taxFileName) + toString(processIDS[i]) + ".temp"));
936                         m->mothurRemove((m->getFullPathName(tempTaxFile) + toString(processIDS[i]) + ".temp"));
937                 }
938                 
939         //append accnos files
940                 if (nonBlankAccnosFiles.size() != 0) { 
941                         rename(nonBlankAccnosFiles[0].c_str(), accnos.c_str());
942                         
943                         for (int h=1; h < nonBlankAccnosFiles.size(); h++) {
944                                 m->appendFiles(nonBlankAccnosFiles[h], accnos);
945                                 m->mothurRemove(nonBlankAccnosFiles[h]);
946                         }
947                 }else { //recreate the accnosfile if needed
948                         ofstream out;
949                         m->openOutputFile(accnos, out);
950                         out.close();
951                 }
952
953                 return num;
954                 
955         }
956         catch(exception& e) {
957                 m->errorOut(e, "ClassifySeqsCommand", "createProcesses");
958                 exit(1);
959         }
960 }
961 //**********************************************************************************************************************
962
963 int ClassifySeqsCommand::driver(linePair* filePos, string taxFName, string tempTFName, string accnos, string filename){
964         try {
965                 ofstream outTax;
966                 m->openOutputFile(taxFName, outTax);
967                 
968                 ofstream outTaxSimple;
969                 m->openOutputFile(tempTFName, outTaxSimple);
970                 
971                 ofstream outAcc;
972                 m->openOutputFile(accnos, outAcc);
973         
974                 ifstream inFASTA;
975                 m->openInputFile(filename, inFASTA);
976                 
977                 string taxonomy;
978
979                 inFASTA.seekg(filePos->start);
980
981                 bool done = false;
982                 int count = 0;
983                 
984                 while (!done) {
985                         if (m->control_pressed) { 
986                                 inFASTA.close();
987                                 outTax.close();
988                                 outTaxSimple.close();
989                                 outAcc.close(); return 0; }
990                 
991                         Sequence* candidateSeq = new Sequence(inFASTA); m->gobble(inFASTA);
992                         
993                         if (candidateSeq->getName() != "") {
994                         
995                                 taxonomy = classify->getTaxonomy(candidateSeq);
996                                 
997                                 if (m->control_pressed) { delete candidateSeq; return 0; }
998                                 
999                                 if (taxonomy == "unknown;") { m->mothurOut("[WARNING]: " + candidateSeq->getName() + " could not be classified. You can use the remove.lineage command with taxon=unknown; to remove such sequences."); m->mothurOutEndLine(); }
1000                                 
1001                                 //output confidence scores or not
1002                                 if (probs) {
1003                                         outTax << candidateSeq->getName() << '\t' << taxonomy << endl;
1004                                 }else{
1005                                         outTax << candidateSeq->getName() << '\t' << classify->getSimpleTax() << endl;
1006                                 }
1007                                 
1008                                 if (classify->getFlipped()) { outAcc << candidateSeq->getName() << endl; }
1009                                 
1010                                 outTaxSimple << candidateSeq->getName() << '\t' << classify->getSimpleTax() << endl;
1011                                 
1012                                 count++;
1013                         }
1014                         delete candidateSeq;
1015                         
1016                         #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
1017                                 unsigned long long pos = inFASTA.tellg();
1018                                 if ((pos == -1) || (pos >= filePos->end)) { break; }
1019                         #else
1020                                 if (inFASTA.eof()) { break; }
1021                         #endif
1022                         
1023                         //report progress
1024                         if((count) % 100 == 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine();         }
1025                         
1026                 }
1027                 //report progress
1028                 if((count) % 100 != 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine();         }
1029                         
1030                 inFASTA.close();
1031                 outTax.close();
1032                 outTaxSimple.close();
1033                 outAcc.close();
1034                 
1035                 return count;
1036         }
1037         catch(exception& e) {
1038                 m->errorOut(e, "ClassifySeqsCommand", "driver");
1039                 exit(1);
1040         }
1041 }
1042 //**********************************************************************************************************************
1043 #ifdef USE_MPI
1044 int ClassifySeqsCommand::driverMPI(int start, int num, MPI_File& inMPI, MPI_File& newFile, MPI_File& tempFile, MPI_File& accFile, vector<unsigned long long>& MPIPos){
1045         try {
1046                 MPI_Status statusNew; 
1047                 MPI_Status statusTemp; 
1048                 MPI_Status statusAcc; 
1049                 MPI_Status status; 
1050                 
1051                 int pid;
1052                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
1053         
1054                 string taxonomy;
1055                 string outputString;
1056
1057                 for(int i=0;i<num;i++){
1058                 
1059                         if (m->control_pressed) { return 0; }
1060                 
1061                         //read next sequence
1062                         int length = MPIPos[start+i+1] - MPIPos[start+i];
1063                         char* buf4 = new char[length];
1064                         MPI_File_read_at(inMPI, MPIPos[start+i], buf4, length, MPI_CHAR, &status);
1065                         
1066                         string tempBuf = buf4;
1067                         if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length);  }
1068                         istringstream iss (tempBuf,istringstream::in);
1069                         delete buf4;
1070
1071                         Sequence* candidateSeq = new Sequence(iss);
1072                         
1073                         if (candidateSeq->getName() != "") {
1074                                 taxonomy = classify->getTaxonomy(candidateSeq);
1075                                 
1076                                 if (taxonomy == "unknown;") { m->mothurOut("[WARNING]: " + candidateSeq->getName() + " could not be classified. You can use the remove.lineage command with taxon=unknown; to remove such sequences."); m->mothurOutEndLine(); }
1077                                 
1078                                 //output confidence scores or not
1079                                 if (probs) {
1080                                         outputString =  candidateSeq->getName() + "\t" + taxonomy + "\n";
1081                                 }else{
1082                                         outputString =  candidateSeq->getName() + "\t" + classify->getSimpleTax() + "\n";
1083                                 }
1084                                 
1085                                 int length = outputString.length();
1086                                 char* buf2 = new char[length];
1087                                 memcpy(buf2, outputString.c_str(), length);
1088                                 
1089                                 MPI_File_write_shared(newFile, buf2, length, MPI_CHAR, &statusNew);
1090                                 delete buf2;
1091                                 
1092                                 outputString =  candidateSeq->getName() + "\t" + classify->getSimpleTax() + "\n";
1093                                 length = outputString.length();
1094                                 char* buf = new char[length];
1095                                 memcpy(buf, outputString.c_str(), length);
1096                                 
1097                                 MPI_File_write_shared(tempFile, buf, length, MPI_CHAR, &statusTemp);
1098                                 delete buf;
1099                                 
1100                                 if (classify->getFlipped()) { 
1101                                         outputString =  candidateSeq->getName() + "\n";
1102                                         length = outputString.length();
1103                                         char* buf3 = new char[length];
1104                                         memcpy(buf3, outputString.c_str(), length);
1105                                         
1106                                         MPI_File_write_shared(accFile, buf3, length, MPI_CHAR, &statusAcc);
1107                                         delete buf3;
1108                                 }
1109                                 
1110                         }                               
1111                         delete candidateSeq;
1112                         
1113                         if((i+1) % 100 == 0){   cout << "Classifying sequence " << (i+1) << endl;       }
1114                 }
1115                 
1116                 if(num % 100 != 0){     cout << "Classifying sequence " << (num) << endl;       }
1117                 
1118                 
1119                 return 1;
1120         }
1121         catch(exception& e) {
1122                 m->errorOut(e, "ClassifySeqsCommand", "driverMPI");
1123                 exit(1);
1124         }
1125 }
1126
1127 //**********************************************************************************************************************
1128 int ClassifySeqsCommand::MPIReadNamesFile(string nameFilename){
1129         try {
1130         
1131                 nameMap.clear(); //remove old names
1132                 
1133                 MPI_File inMPI;
1134                 MPI_Offset size;
1135                 MPI_Status status;
1136
1137                 //char* inFileName = new char[nameFilename.length()];
1138                 //memcpy(inFileName, nameFilename.c_str(), nameFilename.length());
1139                 
1140                 char inFileName[1024];
1141                 strcpy(inFileName, nameFilename.c_str());
1142
1143                 MPI_File_open(MPI_COMM_WORLD, inFileName, MPI_MODE_RDONLY, MPI_INFO_NULL, &inMPI);  
1144                 MPI_File_get_size(inMPI, &size);
1145                 //delete inFileName;
1146
1147                 char* buffer = new char[size];
1148                 MPI_File_read(inMPI, buffer, size, MPI_CHAR, &status);
1149
1150                 string tempBuf = buffer;
1151                 if (tempBuf.length() > size) { tempBuf = tempBuf.substr(0, size);  }
1152                 istringstream iss (tempBuf,istringstream::in);
1153                 delete buffer;
1154                 
1155                 string firstCol, secondCol;
1156                 while(!iss.eof()) {
1157                         iss >> firstCol >> secondCol; m->gobble(iss);
1158                         
1159                         vector<string> temp;
1160                         m->splitAtComma(secondCol, temp);
1161                         
1162                         nameMap[firstCol] = temp;  
1163                 }
1164         
1165                 MPI_File_close(&inMPI);
1166                 
1167                 return 1;
1168         }
1169         catch(exception& e) {
1170                 m->errorOut(e, "ClassifySeqsCommand", "MPIReadNamesFile");
1171                 exit(1);
1172         }
1173 }
1174 #endif
1175 /**************************************************************************************************/