]> git.donarmstrong.com Git - mothur.git/blob - classifyseqscommand.cpp
added mergesfffiles command. added current directories to get.current commands output...
[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 pnumwanted("numwanted", "Number", "", "10", "", "", "","",false,true); parameters.push_back(pnumwanted);
38                 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "","",false,false); parameters.push_back(pinputdir);
39                 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "","",false,false); parameters.push_back(poutputdir);
40                 
41                 vector<string> myArray;
42                 for (int i = 0; i < parameters.size(); i++) {   myArray.push_back(parameters[i].name);          }
43                 return myArray;
44         }
45         catch(exception& e) {
46                 m->errorOut(e, "ClassifySeqsCommand", "setParameters");
47                 exit(1);
48         }
49 }
50 //**********************************************************************************************************************
51 string ClassifySeqsCommand::getHelpString(){    
52         try {
53                 string helpString = "";
54                 helpString += "The classify.seqs command reads a fasta file containing sequences and creates a .taxonomy file and a .tax.summary file.\n";
55                 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";
56                 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";
57                 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";
58                 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";
59                 helpString += "The group parameter allows you add a group file so you can have the summary totals broken up by group.\n";
60         helpString += "The count parameter allows you add a count file so you can have the summary totals broken up by group.\n";
61                 helpString += "The method parameter allows you to specify classification method to use.  Your options are: wang, knn and zap. The default is wang.\n";
62                 helpString += "The ksize parameter allows you to specify the kmer size for finding most similar template to candidate.  The default is 8.\n";
63                 helpString += "The processors parameter allows you to specify the number of processors to use. The default is 1.\n";
64 #ifdef USE_MPI
65                 helpString += "When using MPI, the processors parameter is set to the number of MPI processes running. \n";
66 #endif
67                 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.";
68                 helpString += "The match parameter allows you to specify the bonus for having the same base. The default is 1.0.\n";
69                 helpString += "The mistmatch parameter allows you to specify the penalty for having different bases.  The default is -1.0.\n";
70                 helpString += "The gapopen parameter allows you to specify the penalty for opening a gap in an alignment. The default is -2.0.\n";
71                 helpString += "The gapextend parameter allows you to specify the penalty for extending a gap in an alignment.  The default is -1.0.\n";
72                 helpString += "The numwanted parameter allows you to specify the number of sequence matches you want with the knn method.  The default is 10.\n";
73                 helpString += "The cutoff parameter allows you to specify a bootstrap confidence threshold for your taxonomy.  The default is 0.\n";
74                 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";
75                 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";
76                 //helpString += "The flip parameter allows you shut off mothur's   The default is T.\n";
77                 helpString += "The classify.seqs command should be in the following format: \n";
78                 helpString += "classify.seqs(reference=yourTemplateFile, fasta=yourFastaFile, method=yourClassificationMethod, search=yourSearchmethod, ksize=yourKmerSize, taxonomy=yourTaxonomyFile, processors=yourProcessors) \n";
79                 helpString += "Example classify.seqs(fasta=amazon.fasta, reference=core.filtered, method=knn, search=gotoh, ksize=8, processors=2)\n";
80                 helpString += "The .taxonomy file consists of 2 columns: 1 = your sequence name, 2 = the taxonomy for your sequence. \n";
81                 helpString += "The .tax.summary is a summary of the different taxonomies represented in your fasta file. \n";
82                 helpString += "Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFastaFile).\n";
83                 return helpString;
84         }
85         catch(exception& e) {
86                 m->errorOut(e, "ClassifySeqsCommand", "getHelpString");
87                 exit(1);
88         }
89 }
90 //**********************************************************************************************************************
91 string ClassifySeqsCommand::getOutputPattern(string type) {
92     try {
93         string pattern = "";
94         
95         if (type == "taxonomy") {  pattern = "[filename],[tag],[tag2],taxonomy"; } 
96         else if (type == "taxsummary") {  pattern = "[filename],[tag],[tag2],tax.summary"; } 
97         else if (type == "accnos") {  pattern =  "[filename],[tag],[tag2],flip.accnos"; }
98         else if (type == "matchdist") {  pattern =  "[filename],[tag],[tag2],match.dist"; }
99         else { m->mothurOut("[ERROR]: No definition for type " + type + " output pattern.\n"); m->control_pressed = true;  }
100         
101         return pattern;
102     }
103     catch(exception& e) {
104         m->errorOut(e, "ClassifySeqsCommand", "getOutputPattern");
105         exit(1);
106     }
107 }
108 //**********************************************************************************************************************
109 ClassifySeqsCommand::ClassifySeqsCommand(){     
110         try {
111                 abort = true; calledHelp = true; 
112                 setParameters();
113                 vector<string> tempOutNames;
114                 outputTypes["taxonomy"] = tempOutNames;
115                 outputTypes["accnos"] = tempOutNames;
116                 outputTypes["taxsummary"] = tempOutNames;
117                 outputTypes["matchdist"] = tempOutNames;
118         }
119         catch(exception& e) {
120                 m->errorOut(e, "ClassifySeqsCommand", "ClassifySeqsCommand");
121                 exit(1);
122         }
123 }
124 //**********************************************************************************************************************
125 ClassifySeqsCommand::ClassifySeqsCommand(string option)  {
126         try {
127                 abort = false; calledHelp = false;   
128                 rdb = ReferenceDB::getInstance(); hasName = false; hasCount=false;
129                 
130                 //allow user to run help
131                 if(option == "help") { help(); abort = true; calledHelp = true; }
132                 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
133                 
134                 else {
135                         vector<string> myArray = setParameters();
136                         
137                         OptionParser parser(option);
138                         map<string, string> parameters = parser.getParameters(); 
139                         
140                         ValidParameters validParameter("classify.seqs");
141                         map<string, string>::iterator it;
142                         
143                         //check to make sure all parameters are valid for command
144                         for (it = parameters.begin(); it != parameters.end(); it++) { 
145                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
146                         }
147                         
148                         //initialize outputTypes
149                         vector<string> tempOutNames;
150                         outputTypes["taxonomy"] = tempOutNames;
151                         outputTypes["taxsummary"] = tempOutNames;
152                         outputTypes["matchdist"] = tempOutNames;
153                         outputTypes["accnos"] = tempOutNames;
154                         
155                         //if the user changes the output directory command factory will send this info to us in the output parameter 
156                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  outputDir = "";         }
157                         
158                         //if the user changes the input directory command factory will send this info to us in the output parameter 
159                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
160                         if (inputDir == "not found"){   inputDir = "";          }
161                         else {
162                                 string path;
163                                 it = parameters.find("reference");
164                                 //user has given a template file
165                                 if(it != parameters.end()){ 
166                                         path = m->hasPath(it->second);
167                                         //if the user has not given a path then, add inputdir. else leave path alone.
168                                         if (path == "") {       parameters["reference"] = inputDir + it->second;                }
169                                 }
170                                 
171                                 it = parameters.find("taxonomy");
172                                 //user has given a template file
173                                 if(it != parameters.end()){ 
174                                         path = m->hasPath(it->second);
175                                         //if the user has not given a path then, add inputdir. else leave path alone.
176                                         if (path == "") {       parameters["taxonomy"] = inputDir + it->second;         }
177                                 }
178             }
179
180                         fastaFileName = validParameter.validFile(parameters, "fasta", false);
181                         if (fastaFileName == "not found") {                             
182                                 //if there is a current fasta file, use it
183                                 string filename = m->getFastaFile(); 
184                                 if (filename != "") { fastaFileNames.push_back(filename); m->mothurOut("Using " + filename + " as input file for the fasta parameter."); m->mothurOutEndLine(); }
185                                 else {  m->mothurOut("You have no current fastafile and the fasta parameter is required."); m->mothurOutEndLine(); abort = true; }
186                         }
187                         else { 
188                                 m->splitAtDash(fastaFileName, fastaFileNames);
189                                 
190                                 //go through files and make sure they are good, if not, then disregard them
191                                 for (int i = 0; i < fastaFileNames.size(); i++) {
192                                         
193                                         bool ignore = false;
194                                         if (fastaFileNames[i] == "current") { 
195                                                 fastaFileNames[i] = m->getFastaFile(); 
196                                                 if (fastaFileNames[i] != "") {  m->mothurOut("Using " + fastaFileNames[i] + " as input file for the fasta parameter where you had given current."); m->mothurOutEndLine(); }
197                                                 else {  
198                                                         m->mothurOut("You have no current fastafile, ignoring current."); m->mothurOutEndLine(); ignore=true; 
199                                                         //erase from file list
200                                                         fastaFileNames.erase(fastaFileNames.begin()+i);
201                                                         i--;
202                                                 }
203                                         }
204                                         
205                                         if (!ignore) {
206                                                 
207                                                 if (inputDir != "") {
208                                                         string path = m->hasPath(fastaFileNames[i]);
209                                                         //if the user has not given a path then, add inputdir. else leave path alone.
210                                                         if (path == "") {       fastaFileNames[i] = inputDir + fastaFileNames[i];               }
211                                                 }
212                                                 
213                                                 int ableToOpen;
214                                                 
215                                                 ifstream in;
216                                                 ableToOpen = m->openInputFile(fastaFileNames[i], in, "noerror");
217                                         
218                                                 //if you can't open it, try default location
219                                                 if (ableToOpen == 1) {
220                                                         if (m->getDefaultPath() != "") { //default path is set
221                                                                 string tryPath = m->getDefaultPath() + m->getSimpleName(fastaFileNames[i]);
222                                                                 m->mothurOut("Unable to open " + fastaFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
223                                                                 ifstream in2;
224                                                                 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
225                                                                 in2.close();
226                                                                 fastaFileNames[i] = tryPath;
227                                                         }
228                                                 }
229                                                 
230                                                 if (ableToOpen == 1) {
231                                                         if (m->getOutputDir() != "") { //default path is set
232                                                                 string tryPath = m->getOutputDir() + m->getSimpleName(fastaFileNames[i]);
233                                                                 m->mothurOut("Unable to open " + fastaFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
234                                                                 ifstream in2;
235                                                                 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
236                                                                 in2.close();
237                                                                 fastaFileNames[i] = tryPath;
238                                                         }
239                                                 }
240                                                 
241                                                 in.close();
242                                                 
243                                                 if (ableToOpen == 1) { 
244                                                         m->mothurOut("Unable to open " + fastaFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine(); 
245                                                         //erase from file list
246                                                         fastaFileNames.erase(fastaFileNames.begin()+i);
247                                                         i--;
248                                                 }else {
249                                                         m->setFastaFile(fastaFileNames[i]);
250                                                 }
251                                         }
252                                         
253                                 }
254                                 
255                                 //make sure there is at least one valid file left
256                                 if (fastaFileNames.size() == 0) { m->mothurOut("no valid files."); m->mothurOutEndLine(); abort = true; }
257                         }
258
259                         namefile = validParameter.validFile(parameters, "name", false);
260                         if (namefile == "not found") { namefile = "";  }
261                         else { 
262                                 m->splitAtDash(namefile, namefileNames);
263                                 
264                                 //go through files and make sure they are good, if not, then disregard them
265                                 for (int i = 0; i < namefileNames.size(); i++) {
266                                         bool ignore = false;
267                                         if (namefileNames[i] == "current") { 
268                                                 namefileNames[i] = m->getNameFile(); 
269                                                 if (namefileNames[i] != "") {  m->mothurOut("Using " + namefileNames[i] + " as input file for the name parameter where you had given current."); m->mothurOutEndLine(); }
270                                                 else {  
271                                                         m->mothurOut("You have no current namefile, ignoring current."); m->mothurOutEndLine(); ignore=true; 
272                                                         //erase from file list
273                                                         namefileNames.erase(namefileNames.begin()+i);
274                                                         i--;
275                                                 }
276                                         }
277                                         
278                                         if (!ignore) {
279                                                 
280                                                 if (inputDir != "") {
281                                                         string path = m->hasPath(namefileNames[i]);
282                                                         //if the user has not given a path then, add inputdir. else leave path alone.
283                                                         if (path == "") {       namefileNames[i] = inputDir + namefileNames[i];         }
284                                                 }
285                                                 int ableToOpen;
286                                                 
287                                                 ifstream in;
288                                                 ableToOpen = m->openInputFile(namefileNames[i], in, "noerror");
289                                         
290                                                 //if you can't open it, try default location
291                                                 if (ableToOpen == 1) {
292                                                         if (m->getDefaultPath() != "") { //default path is set
293                                                                 string tryPath = m->getDefaultPath() + m->getSimpleName(namefileNames[i]);
294                                                                 m->mothurOut("Unable to open " + namefileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
295                                                                 ifstream in2;
296                                                                 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
297                                                                 in2.close();
298                                                                 namefileNames[i] = tryPath;
299                                                         }
300                                                 }
301                                                 
302                                                 if (ableToOpen == 1) {
303                                                         if (m->getOutputDir() != "") { //default path is set
304                                                                 string tryPath = m->getOutputDir() + m->getSimpleName(namefileNames[i]);
305                                                                 m->mothurOut("Unable to open " + namefileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
306                                                                 ifstream in2;
307                                                                 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
308                                                                 in2.close();
309                                                                 namefileNames[i] = tryPath;
310                                                         }
311                                                 }
312                                                 in.close();
313                                                 
314                                                 if (ableToOpen == 1) { 
315                                                         m->mothurOut("Unable to open " + namefileNames[i] + ". It will be disregarded."); m->mothurOutEndLine();  abort = true;
316                                                         //erase from file list
317                                                         namefileNames.erase(namefileNames.begin()+i);
318                                                         i--;
319                                                 }else {
320                                                         m->setNameFile(namefileNames[i]);
321                                                 }
322                                         }
323                                 }
324                         }
325             
326             if (namefileNames.size() != 0) { hasName = true; }
327             
328                         if (namefile != "") {
329                                 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(); }
330                         }
331                         
332             //check for required parameters
333                         countfile = validParameter.validFile(parameters, "count", false);
334                         if (countfile == "not found") { 
335                 countfile = "";  
336                         }else { 
337                                 m->splitAtDash(countfile, countfileNames);
338                                 
339                                 //go through files and make sure they are good, if not, then disregard them
340                                 for (int i = 0; i < countfileNames.size(); i++) {
341                                         
342                                         bool ignore = false;
343                                         if (countfileNames[i] == "current") { 
344                                                 countfileNames[i] = m->getCountTableFile(); 
345                                                 if (countfileNames[i] != "") {  m->mothurOut("Using " + countfileNames[i] + " as input file for the count parameter where you had given current."); m->mothurOutEndLine(); }
346                                                 else {  
347                                                         m->mothurOut("You have no current count file, ignoring current."); m->mothurOutEndLine(); ignore=true; 
348                                                         //erase from file list
349                                                         countfileNames.erase(countfileNames.begin()+i);
350                                                         i--;
351                                                 }
352                                         }
353                                         
354                                         if (!ignore) {
355                                                 
356                                                 if (inputDir != "") {
357                                                         string path = m->hasPath(countfileNames[i]);
358                                                         //if the user has not given a path then, add inputdir. else leave path alone.
359                                                         if (path == "") {       countfileNames[i] = inputDir + countfileNames[i];               }
360                                                 }
361                                                 
362                                                 int ableToOpen;
363                                                 ifstream in;
364                                                 
365                                                 ableToOpen = m->openInputFile(countfileNames[i], in, "noerror");
366                                                 
367                                                 //if you can't open it, try default location
368                                                 if (ableToOpen == 1) {
369                                                         if (m->getDefaultPath() != "") { //default path is set
370                                                                 string tryPath = m->getDefaultPath() + m->getSimpleName(countfileNames[i]);
371                                                                 m->mothurOut("Unable to open " + countfileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
372                                                                 ifstream in2;
373                                                                 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
374                                                                 in2.close();
375                                                                 countfileNames[i] = tryPath;
376                                                         }
377                                                 }
378                                                 
379                                                 if (ableToOpen == 1) {
380                                                         if (m->getOutputDir() != "") { //default path is set
381                                                                 string tryPath = m->getOutputDir() + m->getSimpleName(countfileNames[i]);
382                                                                 m->mothurOut("Unable to open " + countfileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
383                                                                 ifstream in2;
384                                                                 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
385                                                                 in2.close();
386                                                                 countfileNames[i] = tryPath;
387                                                         }
388                                                 }
389                                                 
390                                                 in.close();
391                                                 
392                                                 if (ableToOpen == 1) { 
393                                                         m->mothurOut("Unable to open " + countfileNames[i] + ". It will be disregarded."); m->mothurOutEndLine(); 
394                                                         //erase from file list
395                                                         countfileNames.erase(countfileNames.begin()+i);
396                                                         i--;
397                                                 }else {
398                                                         m->setCountTableFile(countfileNames[i]);
399                                                 }
400                                         }
401                                 }
402                         }
403             
404             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(); } }
405             
406                         //make sure there is at least one valid file left
407             if (hasName && hasCount) { m->mothurOut("[ERROR]: You must enter ONLY ONE of the following: count or name."); m->mothurOutEndLine(); abort = true; }
408
409                         groupfile = validParameter.validFile(parameters, "group", false);
410                         if (groupfile == "not found") { groupfile = "";  }
411                         else { 
412                                 m->splitAtDash(groupfile, groupfileNames);
413                                 
414                                 //go through files and make sure they are good, if not, then disregard them
415                                 for (int i = 0; i < groupfileNames.size(); i++) {
416                                         
417                                         bool ignore = false;
418                                         if (groupfileNames[i] == "current") { 
419                                                 groupfileNames[i] = m->getGroupFile(); 
420                                                 if (groupfileNames[i] != "") {  m->mothurOut("Using " + groupfileNames[i] + " as input file for the group parameter where you had given current."); m->mothurOutEndLine(); }
421                                                 else {  
422                                                         m->mothurOut("You have no current group file, ignoring current."); m->mothurOutEndLine(); ignore=true; 
423                                                         //erase from file list
424                                                         groupfileNames.erase(groupfileNames.begin()+i);
425                                                         i--;
426                                                 }
427                                         }
428                                         
429                                         if (!ignore) {
430                                                 
431                                                 if (inputDir != "") {
432                                                         string path = m->hasPath(groupfileNames[i]);
433                             cout << path << '\t' << inputDir << endl;
434                                                         //if the user has not given a path then, add inputdir. else leave path alone.
435                                                         if (path == "") {       groupfileNames[i] = inputDir + groupfileNames[i];               }
436                                                 }
437                                                 
438                                                 int ableToOpen;
439                                                 
440                                                 ifstream in;
441                                                 ableToOpen = m->openInputFile(groupfileNames[i], in, "noerror");
442                         
443                                                 //if you can't open it, try default location
444                                                 if (ableToOpen == 1) {
445                                                         if (m->getDefaultPath() != "") { //default path is set
446                                                                 string tryPath = m->getDefaultPath() + m->getSimpleName(groupfileNames[i]);
447                                                                 m->mothurOut("Unable to open " + groupfileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
448                                                                 ifstream in2;
449                                                                 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
450                                                                 in2.close();
451                                                                 groupfileNames[i] = tryPath;
452                                                         }
453                                                 }
454                                                 
455                                                 if (ableToOpen == 1) {
456                                                         if (m->getOutputDir() != "") { //default path is set
457                                                                 string tryPath = m->getOutputDir() + m->getSimpleName(groupfileNames[i]);
458                                                                 m->mothurOut("Unable to open " + groupfileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
459                                                                 ifstream in2;
460                                                                 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
461                                                                 in2.close();
462                                                                 groupfileNames[i] = tryPath;
463                                                         }
464                                                 }
465                                                 
466                                                 in.close();
467                                                 
468                                                 if (ableToOpen == 1) { 
469                                                         m->mothurOut("Unable to open " + groupfileNames[i] + ". It will be disregarded."); m->mothurOutEndLine(); 
470                                                         //erase from file list
471                                                         groupfileNames.erase(groupfileNames.begin()+i);
472                                                         i--;
473                                                 }else {
474                                                         m->setGroupFile(groupfileNames[i]);
475                                                 }
476                                         }
477                                         
478                                 }
479                         }
480
481                         if (groupfile != "") {
482                                 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(); }
483                 if (hasCount) { m->mothurOut("[ERROR]: You must enter ONLY ONE of the following: count or group."); m->mothurOutEndLine(); abort = true; }
484                         }else {
485                                 for (int i = 0; i < fastaFileNames.size(); i++) {  groupfileNames.push_back("");  }
486                         }
487                         
488                         //check for optional parameter and set defaults
489                         // ...at some point should added some additional type checking...
490                         string temp;
491                         temp = validParameter.validFile(parameters, "processors", false);       if (temp == "not found"){       temp = m->getProcessors();      }
492                         m->setProcessors(temp);
493                         m->mothurConvert(temp, processors); 
494                         
495                         temp = validParameter.validFile(parameters, "save", false);                     if (temp == "not found"){       temp = "f";                             }
496                         save = m->isTrue(temp); 
497                         rdb->save = save; 
498                         if (save) { //clear out old references
499                                 rdb->clearMemory();     
500                         }
501                         
502                         //this has to go after save so that if the user sets save=t and provides no reference we abort
503                         templateFileName = validParameter.validFile(parameters, "reference", true);
504                         if (templateFileName == "not found") { 
505                                 //check for saved reference sequences
506                                 if (rdb->referenceSeqs.size() != 0) {
507                                         templateFileName = "saved";
508                                 }else {
509                                         m->mothurOut("[ERROR]: You don't have any saved reference sequences and the reference parameter is a required for the classify.seqs command."); 
510                                         m->mothurOutEndLine();
511                                         abort = true; 
512                                 }
513                         }else if (templateFileName == "not open") { abort = true; }     
514                         else {  if (save) {     rdb->setSavedReference(templateFileName);       }       }
515                         
516                         //this has to go after save so that if the user sets save=t and provides no reference we abort
517                         taxonomyFileName = validParameter.validFile(parameters, "taxonomy", true);
518                         if (taxonomyFileName == "not found") { 
519                                 //check for saved reference sequences
520                                 if (rdb->wordGenusProb.size() != 0) {
521                                         taxonomyFileName = "saved";
522                                 }else {
523                                         m->mothurOut("[ERROR]: You don't have any saved taxonomy information and the taxonomy parameter is a required for the classify.seqs command."); 
524                                         m->mothurOutEndLine();
525                                         abort = true; 
526                                 }
527                         }else if (taxonomyFileName == "not open") { abort = true; }     
528                         else {  if (save) {     rdb->setSavedTaxonomy(taxonomyFileName);        }       }
529                         
530                         search = validParameter.validFile(parameters, "search", false);         if (search == "not found"){     search = "kmer";                }
531                         
532                         method = validParameter.validFile(parameters, "method", false);         if (method == "not found"){     method = "wang";        }
533             
534             temp = validParameter.validFile(parameters, "ksize", false);                if (temp == "not found"){       
535                 temp = "8";     
536                 if (method == "zap") { temp = "7"; }
537             }
538                         m->mothurConvert(temp, kmerSize); 
539                         
540                         temp = validParameter.validFile(parameters, "match", false);            if (temp == "not found"){       temp = "1.0";                   }
541                         m->mothurConvert(temp, match);  
542                         
543                         temp = validParameter.validFile(parameters, "mismatch", false);         if (temp == "not found"){       temp = "-1.0";                  }
544                         m->mothurConvert(temp, misMatch);  
545                         
546                         temp = validParameter.validFile(parameters, "gapopen", false);          if (temp == "not found"){       temp = "-2.0";                  }
547                         m->mothurConvert(temp, gapOpen);  
548                         
549                         temp = validParameter.validFile(parameters, "gapextend", false);        if (temp == "not found"){       temp = "-1.0";                  }
550                         m->mothurConvert(temp, gapExtend); 
551                         
552                         temp = validParameter.validFile(parameters, "numwanted", false);        if (temp == "not found"){       temp = "10";                    }
553                         m->mothurConvert(temp, numWanted);
554                         
555                         temp = validParameter.validFile(parameters, "cutoff", false);           if (temp == "not found"){       temp = "0";                             }
556                         m->mothurConvert(temp, cutoff);
557                         
558                         temp = validParameter.validFile(parameters, "probs", false);            if (temp == "not found"){       temp = "true";                  }
559                         probs = m->isTrue(temp);
560             
561             temp = validParameter.validFile(parameters, "shortcuts", false);    if (temp == "not found"){       temp = "true";                  }
562                         writeShortcuts = m->isTrue(temp);
563                         
564                         //temp = validParameter.validFile(parameters, "flip", false);                   if (temp == "not found"){       temp = "T";                             }
565                         //flip = m->isTrue(temp); 
566                         flip = true;
567                         
568                         temp = validParameter.validFile(parameters, "iters", false);            if (temp == "not found") { temp = "100";                        }
569                         m->mothurConvert(temp, iters); 
570
571                         
572                         if ((method == "wang") && (search != "kmer"))  { 
573                                 m->mothurOut("The wang method requires the kmer search. " + search + " will be disregarded, and kmer will be used." ); m->mothurOutEndLine();
574                                 search = "kmer";
575                         }
576             
577             if ((method == "zap") && ((search != "kmer") && (search != "align")))  { 
578                                 m->mothurOut("The zap method requires the kmer or align search. " + search + " will be disregarded, and kmer will be used." ); m->mothurOutEndLine();
579                                 search = "kmer";
580                         }
581                         
582             if (!abort) {
583                 if (!hasCount) {
584                     if (namefileNames.size() == 0){
585                         if (fastaFileNames.size() != 0) {
586                             vector<string> files; files.push_back(fastaFileNames[fastaFileNames.size()-1]); 
587                             parser.getNameFile(files);
588                         }
589                     }
590                 }
591             }
592         }
593         }
594         catch(exception& e) {
595                 m->errorOut(e, "ClassifySeqsCommand", "ClassifySeqsCommand");
596                 exit(1);
597         }
598 }
599
600 //**********************************************************************************************************************
601 ClassifySeqsCommand::~ClassifySeqsCommand(){    
602         if (abort == false) {
603                 for (int i = 0; i < lines.size(); i++) {  delete lines[i];  }  lines.clear();
604         }
605 }
606 //**********************************************************************************************************************
607
608 int ClassifySeqsCommand::execute(){
609         try {
610                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
611         
612         string outputMethodTag = method;
613                 if(method == "wang"){   classify = new Bayesian(taxonomyFileName, templateFileName, search, kmerSize, cutoff, iters, rand(), flip, writeShortcuts);     }
614                 else if(method == "knn"){       classify = new Knn(taxonomyFileName, templateFileName, search, kmerSize, gapOpen, gapExtend, match, misMatch, numWanted, rand());                               }
615         else if(method == "zap"){       
616             outputMethodTag = search + "_" + outputMethodTag;
617             if (search == "kmer") {   classify = new KmerTree(templateFileName, taxonomyFileName, kmerSize, cutoff); }
618             else {  classify = new AlignTree(templateFileName, taxonomyFileName, cutoff);  }
619         }
620                 else {
621                         m->mothurOut(search + " is not a valid method option. I will run the command using wang.");
622                         m->mothurOutEndLine();
623                         classify = new Bayesian(taxonomyFileName, templateFileName, search, kmerSize, cutoff, iters, rand(), flip, writeShortcuts);     
624                 }
625                 
626                 if (m->control_pressed) { delete classify; return 0; }
627                                 
628                 for (int s = 0; s < fastaFileNames.size(); s++) {
629                 
630                         m->mothurOut("Classifying sequences from " + fastaFileNames[s] + " ..." ); m->mothurOutEndLine();
631                         
632                         string baseTName = m->getSimpleName(taxonomyFileName);
633                         if (taxonomyFileName == "saved") {  baseTName = rdb->getSavedTaxonomy();        }
634                         
635             //set rippedTaxName to 
636                         string RippedTaxName = "";
637             bool foundDot = false;
638             for (int i = baseTName.length()-1; i >= 0; i--) {
639                 if (foundDot && (baseTName[i] != '.')) {  RippedTaxName = baseTName[i] + RippedTaxName; }
640                 else if (foundDot && (baseTName[i] == '.')) {  break; }
641                 else if (!foundDot && (baseTName[i] == '.')) {  foundDot = true; }
642             }
643             //if (RippedTaxName != "") { RippedTaxName +=  "."; }   
644           
645                         if (outputDir == "") { outputDir += m->hasPath(fastaFileNames[s]); }
646             map<string, string> variables; 
647             variables["[filename]"] = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s]));
648             variables["[tag]"] = RippedTaxName;
649             variables["[tag2]"] = outputMethodTag;
650                         string newTaxonomyFile = getOutputFileName("taxonomy", variables);
651                         string newaccnosFile = getOutputFileName("accnos", variables);
652                         string tempTaxonomyFile = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + "taxonomy.temp";
653                         string taxSummary = getOutputFileName("taxsummary", variables);
654                         
655                         if ((method == "knn") && (search == "distance")) { 
656                                 string DistName = getOutputFileName("matchdist", variables);
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 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(); 
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], true, false);
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             if (pDataArray[i]->count != pDataArray[i]->end) {
1047                 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; 
1048             }
1049                         CloseHandle(hThreadArray[i]);
1050                         delete pDataArray[i];
1051                 }
1052                 
1053         #endif  
1054         vector<string> nonBlankAccnosFiles;
1055                 if (!(m->isBlank(accnos))) { nonBlankAccnosFiles.push_back(accnos); }
1056                 else { m->mothurRemove(accnos); } //remove so other files can be renamed to it
1057         
1058                 for(int i=0;i<processIDS.size();i++){
1059                         m->appendFiles((taxFileName + toString(processIDS[i]) + ".temp"), taxFileName);
1060                         m->appendFiles((tempTaxFile + toString(processIDS[i]) + ".temp"), tempTaxFile);
1061             if (!(m->isBlank(accnos + toString(processIDS[i]) + ".temp"))) {
1062                                 nonBlankAccnosFiles.push_back(accnos + toString(processIDS[i]) + ".temp");
1063                         }else { m->mothurRemove((accnos + toString(processIDS[i]) + ".temp"));  }
1064
1065                         m->mothurRemove((m->getFullPathName(taxFileName) + toString(processIDS[i]) + ".temp"));
1066                         m->mothurRemove((m->getFullPathName(tempTaxFile) + toString(processIDS[i]) + ".temp"));
1067                 }
1068                 
1069         //append accnos files
1070                 if (nonBlankAccnosFiles.size() != 0) { 
1071                         rename(nonBlankAccnosFiles[0].c_str(), accnos.c_str());
1072                         
1073                         for (int h=1; h < nonBlankAccnosFiles.size(); h++) {
1074                                 m->appendFiles(nonBlankAccnosFiles[h], accnos);
1075                                 m->mothurRemove(nonBlankAccnosFiles[h]);
1076                         }
1077                 }else { //recreate the accnosfile if needed
1078                         ofstream out;
1079                         m->openOutputFile(accnos, out);
1080                         out.close();
1081                 }
1082
1083                 return num;
1084                 
1085         }
1086         catch(exception& e) {
1087                 m->errorOut(e, "ClassifySeqsCommand", "createProcesses");
1088                 exit(1);
1089         }
1090 }
1091 //**********************************************************************************************************************
1092
1093 int ClassifySeqsCommand::driver(linePair* filePos, string taxFName, string tempTFName, string accnos, string filename){
1094         try {
1095                 ofstream outTax;
1096                 m->openOutputFile(taxFName, outTax);
1097                 
1098                 ofstream outTaxSimple;
1099                 m->openOutputFile(tempTFName, outTaxSimple);
1100                 
1101                 ofstream outAcc;
1102                 m->openOutputFile(accnos, outAcc);
1103         
1104                 ifstream inFASTA;
1105                 m->openInputFile(filename, inFASTA);
1106                 
1107                 string taxonomy;
1108
1109                 inFASTA.seekg(filePos->start);
1110
1111                 bool done = false;
1112                 int count = 0;
1113                 
1114                 while (!done) {
1115                         if (m->control_pressed) { 
1116                                 inFASTA.close();
1117                                 outTax.close();
1118                                 outTaxSimple.close();
1119                                 outAcc.close(); return 0; }
1120                 
1121                         Sequence* candidateSeq = new Sequence(inFASTA); m->gobble(inFASTA);
1122                         
1123                         if (candidateSeq->getName() != "") {
1124                         
1125                                 taxonomy = classify->getTaxonomy(candidateSeq);
1126                                 
1127                                 if (m->control_pressed) { delete candidateSeq; return 0; }
1128                                 
1129                                 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(); }
1130                                 
1131                                 //output confidence scores or not
1132                                 if (probs) {
1133                                         outTax << candidateSeq->getName() << '\t' << taxonomy << endl;
1134                                 }else{
1135                                         outTax << candidateSeq->getName() << '\t' << classify->getSimpleTax() << endl;
1136                                 }
1137                                 
1138                                 if (classify->getFlipped()) { outAcc << candidateSeq->getName() << endl; }
1139                                 
1140                                 outTaxSimple << candidateSeq->getName() << '\t' << classify->getSimpleTax() << endl;
1141                                 
1142                                 count++;
1143                         }
1144                         delete candidateSeq;
1145                         
1146                         #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
1147                                 unsigned long long pos = inFASTA.tellg();
1148                                 if ((pos == -1) || (pos >= filePos->end)) { break; }
1149                         #else
1150                                 if (inFASTA.eof()) { break; }
1151                         #endif
1152                         
1153                         //report progress
1154                         if((count) % 100 == 0){ m->mothurOutJustToScreen("Processing sequence: " + toString(count) +"\n");              }
1155                         
1156                 }
1157                 //report progress
1158                 if((count) % 100 != 0){ m->mothurOutJustToScreen("Processing sequence: " + toString(count)+"\n");               }
1159                         
1160                 inFASTA.close();
1161                 outTax.close();
1162                 outTaxSimple.close();
1163                 outAcc.close();
1164                 
1165                 return count;
1166         }
1167         catch(exception& e) {
1168                 m->errorOut(e, "ClassifySeqsCommand", "driver");
1169                 exit(1);
1170         }
1171 }
1172 //**********************************************************************************************************************
1173 #ifdef USE_MPI
1174 int ClassifySeqsCommand::driverMPI(int start, int num, MPI_File& inMPI, MPI_File& newFile, MPI_File& tempFile, MPI_File& accFile, vector<unsigned long long>& MPIPos){
1175         try {
1176                 MPI_Status statusNew; 
1177                 MPI_Status statusTemp; 
1178                 MPI_Status statusAcc; 
1179                 MPI_Status status; 
1180                 
1181                 int pid;
1182                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
1183         
1184                 string taxonomy;
1185                 string outputString;
1186
1187                 for(int i=0;i<num;i++){
1188                 
1189                         if (m->control_pressed) { return 0; }
1190                 
1191                         //read next sequence
1192                         int length = MPIPos[start+i+1] - MPIPos[start+i];
1193                         char* buf4 = new char[length];
1194                         MPI_File_read_at(inMPI, MPIPos[start+i], buf4, length, MPI_CHAR, &status);
1195                         
1196                         string tempBuf = buf4;
1197                         if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length);  }
1198                         istringstream iss (tempBuf,istringstream::in);
1199                         delete buf4;
1200
1201                         Sequence* candidateSeq = new Sequence(iss);
1202                         
1203                         if (candidateSeq->getName() != "") {
1204                                 taxonomy = classify->getTaxonomy(candidateSeq);
1205                                 
1206                                 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(); }
1207                                 
1208                                 //output confidence scores or not
1209                                 if (probs) {
1210                                         outputString =  candidateSeq->getName() + "\t" + taxonomy + "\n";
1211                                 }else{
1212                                         outputString =  candidateSeq->getName() + "\t" + classify->getSimpleTax() + "\n";
1213                                 }
1214                                 
1215                                 int length = outputString.length();
1216                                 char* buf2 = new char[length];
1217                                 memcpy(buf2, outputString.c_str(), length);
1218                                 
1219                                 MPI_File_write_shared(newFile, buf2, length, MPI_CHAR, &statusNew);
1220                                 delete buf2;
1221                                 
1222                                 outputString =  candidateSeq->getName() + "\t" + classify->getSimpleTax() + "\n";
1223                                 length = outputString.length();
1224                                 char* buf = new char[length];
1225                                 memcpy(buf, outputString.c_str(), length);
1226                                 
1227                                 MPI_File_write_shared(tempFile, buf, length, MPI_CHAR, &statusTemp);
1228                                 delete buf;
1229                                 
1230                                 if (classify->getFlipped()) { 
1231                                         outputString =  candidateSeq->getName() + "\n";
1232                                         length = outputString.length();
1233                                         char* buf3 = new char[length];
1234                                         memcpy(buf3, outputString.c_str(), length);
1235                                         
1236                                         MPI_File_write_shared(accFile, buf3, length, MPI_CHAR, &statusAcc);
1237                                         delete buf3;
1238                                 }
1239                                 
1240                         }                               
1241                         delete candidateSeq;
1242                         
1243                         if((i+1) % 100 == 0){   cout << "Classifying sequence " << (i+1) << endl;       }
1244                 }
1245                 
1246                 if(num % 100 != 0){     cout << "Classifying sequence " << (num) << endl;       }
1247                 
1248                 
1249                 return 1;
1250         }
1251         catch(exception& e) {
1252                 m->errorOut(e, "ClassifySeqsCommand", "driverMPI");
1253                 exit(1);
1254         }
1255 }
1256
1257 //**********************************************************************************************************************
1258 int ClassifySeqsCommand::MPIReadNamesFile(string nameFilename){
1259         try {
1260         
1261                 nameMap.clear(); //remove old names
1262                 
1263                 MPI_File inMPI;
1264                 MPI_Offset size;
1265                 MPI_Status status;
1266
1267                 //char* inFileName = new char[nameFilename.length()];
1268                 //memcpy(inFileName, nameFilename.c_str(), nameFilename.length());
1269                 
1270                 char inFileName[1024];
1271                 strcpy(inFileName, nameFilename.c_str());
1272
1273                 MPI_File_open(MPI_COMM_WORLD, inFileName, MPI_MODE_RDONLY, MPI_INFO_NULL, &inMPI);  
1274                 MPI_File_get_size(inMPI, &size);
1275                 //delete inFileName;
1276
1277                 char* buffer = new char[size];
1278                 MPI_File_read(inMPI, buffer, size, MPI_CHAR, &status);
1279
1280                 string tempBuf = buffer;
1281                 if (tempBuf.length() > size) { tempBuf = tempBuf.substr(0, size);  }
1282                 istringstream iss (tempBuf,istringstream::in);
1283                 delete buffer;
1284                 
1285                 string firstCol, secondCol;
1286                 while(!iss.eof()) {
1287                         iss >> firstCol >> secondCol; m->gobble(iss);
1288                         
1289                         vector<string> temp;
1290                         m->splitAtComma(secondCol, temp);
1291                         
1292                         nameMap[firstCol] = temp;  
1293                 }
1294         
1295                 MPI_File_close(&inMPI);
1296                 
1297                 return 1;
1298         }
1299         catch(exception& e) {
1300                 m->errorOut(e, "ClassifySeqsCommand", "MPIReadNamesFile");
1301                 exit(1);
1302         }
1303 }
1304 #endif
1305 /**************************************************************************************************/