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