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