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