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