]> git.donarmstrong.com Git - mothur.git/blob - classifyseqscommand.cpp
bug fixes
[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 #include "sequence.hpp"
12 #include "bayesian.h"
13 #include "phylotree.h"
14 #include "phylosummary.h"
15 #include "knn.h"
16
17 //**********************************************************************************************************************
18
19 ClassifySeqsCommand::ClassifySeqsCommand(string option)  {
20         try {
21                 abort = false;
22                 
23                 //allow user to run help
24                 if(option == "help") { help(); abort = true; }
25                 
26                 else {
27                         
28                         //valid paramters for this command
29                         string AlignArray[] =  {"template","fasta","name","group","search","ksize","method","processors","taxonomy","match","mismatch","gapopen","gapextend","numwanted","cutoff","probs","iters", "outputdir","inputdir"};
30                         vector<string> myArray (AlignArray, AlignArray+(sizeof(AlignArray)/sizeof(string)));
31                         
32                         OptionParser parser(option);
33                         map<string, string> parameters = parser.getParameters(); 
34                         
35                         ValidParameters validParameter("classify.seqs");
36                         map<string, string>::iterator it;
37                         
38                         //check to make sure all parameters are valid for command
39                         for (it = parameters.begin(); it != parameters.end(); it++) { 
40                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
41                         }
42                         
43                         //if the user changes the output directory command factory will send this info to us in the output parameter 
44                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  outputDir = "";         }
45                         
46                         //if the user changes the input directory command factory will send this info to us in the output parameter 
47                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
48                         if (inputDir == "not found"){   inputDir = "";          }
49                         else {
50                                 string path;
51                                 it = parameters.find("template");
52                                 //user has given a template file
53                                 if(it != parameters.end()){ 
54                                         path = m->hasPath(it->second);
55                                         //if the user has not given a path then, add inputdir. else leave path alone.
56                                         if (path == "") {       parameters["template"] = inputDir + it->second;         }
57                                 }
58                                 
59                                 it = parameters.find("taxonomy");
60                                 //user has given a template file
61                                 if(it != parameters.end()){ 
62                                         path = m->hasPath(it->second);
63                                         //if the user has not given a path then, add inputdir. else leave path alone.
64                                         if (path == "") {       parameters["taxonomy"] = inputDir + it->second;         }
65                                 }
66                                 
67                                 it = parameters.find("group");
68                                 //user has given a template file
69                                 if(it != parameters.end()){ 
70                                         path = m->hasPath(it->second);
71                                         //if the user has not given a path then, add inputdir. else leave path alone.
72                                         if (path == "") {       parameters["group"] = inputDir + it->second;            }
73                                 }
74                         }
75
76                         //check for required parameters
77                         templateFileName = validParameter.validFile(parameters, "template", true);
78                         if (templateFileName == "not found") { 
79                                 m->mothurOut("template is a required parameter for the classify.seqs command."); 
80                                 m->mothurOutEndLine();
81                                 abort = true; 
82                         }
83                         else if (templateFileName == "not open") { abort = true; }      
84                         
85                                                 
86                         fastaFileName = validParameter.validFile(parameters, "fasta", false);
87                         if (fastaFileName == "not found") { m->mothurOut("fasta is a required parameter for the classify.seqs command."); m->mothurOutEndLine(); abort = true;  }
88                         else { 
89                                 m->splitAtDash(fastaFileName, fastaFileNames);
90                                 
91                                 //go through files and make sure they are good, if not, then disregard them
92                                 for (int i = 0; i < fastaFileNames.size(); i++) {
93                                         if (inputDir != "") {
94                                                 string path = m->hasPath(fastaFileNames[i]);
95                                                 //if the user has not given a path then, add inputdir. else leave path alone.
96                                                 if (path == "") {       fastaFileNames[i] = inputDir + fastaFileNames[i];               }
97                                         }
98                                         
99                                         int ableToOpen;
100                                         
101                                         ifstream in;
102                                         ableToOpen = m->openInputFile(fastaFileNames[i], in, "noerror");
103                                 
104                                         //if you can't open it, try default location
105                                         if (ableToOpen == 1) {
106                                                 if (m->getDefaultPath() != "") { //default path is set
107                                                         string tryPath = m->getDefaultPath() + m->getSimpleName(fastaFileNames[i]);
108                                                         m->mothurOut("Unable to open " + fastaFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
109                                                         ableToOpen = m->openInputFile(tryPath, in, "noerror");
110                                                         fastaFileNames[i] = tryPath;
111                                                 }
112                                         }
113                                         in.close();
114                                         
115                                         if (ableToOpen == 1) { 
116                                                 m->mothurOut("Unable to open " + fastaFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine(); 
117                                                 //erase from file list
118                                                 fastaFileNames.erase(fastaFileNames.begin()+i);
119                                                 i--;
120                                         }
121                                         
122                                 }
123                                 
124                                 //make sure there is at least one valid file left
125                                 if (fastaFileNames.size() == 0) { m->mothurOut("no valid files."); m->mothurOutEndLine(); abort = true; }
126                         }
127
128                         
129                         taxonomyFileName = validParameter.validFile(parameters, "taxonomy", true);
130                         if (taxonomyFileName == "not found") { 
131                                 m->mothurOut("taxonomy is a required parameter for the classify.seqs command."); 
132                                 m->mothurOutEndLine();
133                                 abort = true; 
134                         }
135                         else if (taxonomyFileName == "not open") { abort = true; }      
136                         
137                         
138                         namefile = validParameter.validFile(parameters, "name", false);
139                         if (namefile == "not found") { namefile = "";  }
140
141                         else { 
142                                 m->splitAtDash(namefile, namefileNames);
143                                 
144                                 //go through files and make sure they are good, if not, then disregard them
145                                 for (int i = 0; i < namefileNames.size(); i++) {
146                                         if (inputDir != "") {
147                                                 string path = m->hasPath(namefileNames[i]);
148                                                 //if the user has not given a path then, add inputdir. else leave path alone.
149                                                 if (path == "") {       namefileNames[i] = inputDir + namefileNames[i];         }
150                                         }
151                                         int ableToOpen;
152                                         
153                                         ifstream in;
154                                         ableToOpen = m->openInputFile(namefileNames[i], in, "noerror");
155                                 
156                                         //if you can't open it, try default location
157                                         if (ableToOpen == 1) {
158                                                 if (m->getDefaultPath() != "") { //default path is set
159                                                         string tryPath = m->getDefaultPath() + m->getSimpleName(namefileNames[i]);
160                                                         m->mothurOut("Unable to open " + namefileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
161                                                         ableToOpen = m->openInputFile(tryPath, in, "noerror");
162                                                         namefileNames[i] = tryPath;
163                                                 }
164                                         }
165                                         in.close();
166                                         
167                                         if (ableToOpen == 1) { 
168                                                 m->mothurOut("Unable to open " + namefileNames[i] + ". It will be disregarded."); m->mothurOutEndLine();  abort = true;
169                                                 //erase from file list
170                                                 namefileNames.erase(namefileNames.begin()+i);
171                                                 i--;
172                                         }
173
174                                 }
175                         }
176
177                         if (namefile != "") {
178                                 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(); }
179                         }
180                         
181                         groupfile = validParameter.validFile(parameters, "group", false);
182                         if (groupfile == "not found") { groupfile = "";  }
183                         else { 
184                                 m->splitAtDash(groupfile, groupfileNames);
185                                 
186                                 //go through files and make sure they are good, if not, then disregard them
187                                 for (int i = 0; i < groupfileNames.size(); i++) {
188                                         if (inputDir != "") {
189                                                 string path = m->hasPath(groupfileNames[i]);
190                                                 //if the user has not given a path then, add inputdir. else leave path alone.
191                                                 if (path == "") {       groupfileNames[i] = inputDir + groupfileNames[i];               }
192                                         }
193                                         int ableToOpen;
194                                         
195                                         ifstream in;
196                                         ableToOpen = m->openInputFile(groupfileNames[i], in, "noerror");
197                                 
198                                         //if you can't open it, try default location
199                                         if (ableToOpen == 1) {
200                                                 if (m->getDefaultPath() != "") { //default path is set
201                                                         string tryPath = m->getDefaultPath() + m->getSimpleName(groupfileNames[i]);
202                                                         m->mothurOut("Unable to open " + groupfileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
203                                                         ableToOpen = m->openInputFile(tryPath, in, "noerror");
204                                                         groupfileNames[i] = tryPath;
205                                                 }
206                                         }
207                                         in.close();
208                                         
209                                         if (ableToOpen == 1) { 
210                                                 m->mothurOut("Unable to open " + groupfileNames[i] + ". It will be disregarded."); m->mothurOutEndLine(); groupfileNames[i] = "";
211                                                 //erase from file list
212                                                 groupfileNames.erase(groupfileNames.begin()+i);
213                                                 i--;
214                                         }
215                                 }
216                         }
217
218                         if (groupfile != "") {
219                                 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(); }
220                         }else {
221                                 for (int i = 0; i < fastaFileNames.size(); i++) {  groupfileNames.push_back("");  }
222                         }
223                         
224                         //check for optional parameter and set defaults
225                         // ...at some point should added some additional type checking...
226                         string temp;
227                         temp = validParameter.validFile(parameters, "ksize", false);            if (temp == "not found"){       temp = "8";                             }
228                         convert(temp, kmerSize); 
229                         
230                         temp = validParameter.validFile(parameters, "processors", false);       if (temp == "not found"){       temp = "1";                             }
231                         convert(temp, processors); 
232                         
233                         search = validParameter.validFile(parameters, "search", false);         if (search == "not found"){     search = "kmer";                }
234                         
235                         method = validParameter.validFile(parameters, "method", false);         if (method == "not found"){     method = "bayesian";    }
236                         
237                         temp = validParameter.validFile(parameters, "match", false);            if (temp == "not found"){       temp = "1.0";                   }
238                         convert(temp, match);  
239                         
240                         temp = validParameter.validFile(parameters, "mismatch", false);         if (temp == "not found"){       temp = "-1.0";                  }
241                         convert(temp, misMatch);  
242                         
243                         temp = validParameter.validFile(parameters, "gapopen", false);          if (temp == "not found"){       temp = "-2.0";                  }
244                         convert(temp, gapOpen);  
245                         
246                         temp = validParameter.validFile(parameters, "gapextend", false);        if (temp == "not found"){       temp = "-1.0";                  }
247                         convert(temp, gapExtend); 
248                         
249                         temp = validParameter.validFile(parameters, "numwanted", false);        if (temp == "not found"){       temp = "10";                    }
250                         convert(temp, numWanted);
251                         
252                         temp = validParameter.validFile(parameters, "cutoff", false);           if (temp == "not found"){       temp = "0";                             }
253                         convert(temp, cutoff);
254                         
255                         temp = validParameter.validFile(parameters, "probs", false);            if (temp == "not found"){       temp = "true";                  }
256                         probs = m->isTrue(temp);
257                         
258                         temp = validParameter.validFile(parameters, "iters", false);            if (temp == "not found") { temp = "100";                        }
259                         convert(temp, iters); 
260
261
262                         
263                         if ((method == "bayesian") && (search != "kmer"))  { 
264                                 m->mothurOut("The bayesian method requires the kmer search." + search + "will be disregarded." ); m->mothurOutEndLine();
265                                 search = "kmer";
266                         }
267                 }
268                 
269         }
270         catch(exception& e) {
271                 m->errorOut(e, "ClassifySeqsCommand", "ClassifySeqsCommand");
272                 exit(1);
273         }
274 }
275
276 //**********************************************************************************************************************
277
278 ClassifySeqsCommand::~ClassifySeqsCommand(){    
279
280         if (abort == false) {
281                 for (int i = 0; i < lines.size(); i++) {  delete lines[i];  }  lines.clear();
282         }
283 }
284
285 //**********************************************************************************************************************
286
287 void ClassifySeqsCommand::help(){
288         try {
289                 m->mothurOut("The classify.seqs command reads a fasta file containing sequences and creates a .taxonomy file and a .tax.summary file.\n");
290                 m->mothurOut("The classify.seqs command parameters are template, fasta, name, search, ksize, method, taxonomy, processors, match, mismatch, gapopen, gapextend, numwanted and probs.\n");
291                 m->mothurOut("The template, 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");
292                 m->mothurOut("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");
293                 m->mothurOut("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");
294                 m->mothurOut("The group parameter allows you add a group file so you can have the summary totals broken up by group.\n");
295                 m->mothurOut("The method parameter allows you to specify classification method to use.  Your options are: bayesian and knn. The default is bayesian.\n");
296                 m->mothurOut("The ksize parameter allows you to specify the kmer size for finding most similar template to candidate.  The default is 8.\n");
297                 m->mothurOut("The processors parameter allows you to specify the number of processors to use. The default is 1.\n");
298                 #ifdef USE_MPI
299                 m->mothurOut("When using MPI, the processors parameter is set to the number of MPI processes running. \n");
300                 #endif
301                 m->mothurOut("The match parameter allows you to specify the bonus for having the same base. The default is 1.0.\n");
302                 m->mothurOut("The mistmatch parameter allows you to specify the penalty for having different bases.  The default is -1.0.\n");
303                 m->mothurOut("The gapopen parameter allows you to specify the penalty for opening a gap in an alignment. The default is -2.0.\n");
304                 m->mothurOut("The gapextend parameter allows you to specify the penalty for extending a gap in an alignment.  The default is -1.0.\n");
305                 m->mothurOut("The numwanted parameter allows you to specify the number of sequence matches you want with the knn method.  The default is 10.\n");
306                 m->mothurOut("The cutoff parameter allows you to specify a bootstrap confidence threshold for your taxonomy.  The default is 0.\n");
307                 m->mothurOut("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");
308                 m->mothurOut("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");
309                 m->mothurOut("The classify.seqs command should be in the following format: \n");
310                 m->mothurOut("classify.seqs(template=yourTemplateFile, fasta=yourFastaFile, method=yourClassificationMethod, search=yourSearchmethod, ksize=yourKmerSize, taxonomy=yourTaxonomyFile, processors=yourProcessors) \n");
311                 m->mothurOut("Example classify.seqs(fasta=amazon.fasta, template=core.filtered, method=knn, search=gotoh, ksize=8, processors=2)\n");
312                 m->mothurOut("The .taxonomy file consists of 2 columns: 1 = your sequence name, 2 = the taxonomy for your sequence. \n");
313                 m->mothurOut("The .tax.summary is a summary of the different taxonomies represented in your fasta file. \n");
314                 m->mothurOut("Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFastaFile).\n\n");
315         }
316         catch(exception& e) {
317                 m->errorOut(e, "ClassifySeqsCommand", "help");
318                 exit(1);
319         }
320 }
321
322
323 //**********************************************************************************************************************
324
325 int ClassifySeqsCommand::execute(){
326         try {
327                 if (abort == true) {    return 0;       }
328                 
329                 if(method == "bayesian"){       classify = new Bayesian(taxonomyFileName, templateFileName, search, kmerSize, cutoff, iters);           }
330                 else if(method == "knn"){       classify = new Knn(taxonomyFileName, templateFileName, search, kmerSize, gapOpen, gapExtend, match, misMatch, numWanted);                               }
331                 else {
332                         m->mothurOut(search + " is not a valid method option. I will run the command using bayesian.");
333                         m->mothurOutEndLine();
334                         classify = new Bayesian(taxonomyFileName, templateFileName, search, kmerSize, cutoff, iters);   
335                 }
336                 
337                 if (m->control_pressed) { delete classify; return 0; }
338                 
339                 vector<string> outputNames;
340                                 
341                 for (int s = 0; s < fastaFileNames.size(); s++) {
342                 
343                         m->mothurOut("Classifying sequences from " + fastaFileNames[s] + " ..." ); m->mothurOutEndLine();
344                         
345                         string RippedTaxName = m->getRootName(m->getSimpleName(taxonomyFileName));
346                         RippedTaxName = m->getExtension(RippedTaxName.substr(0, RippedTaxName.length()-1));
347                         if (RippedTaxName[0] == '.') { RippedTaxName = RippedTaxName.substr(1, RippedTaxName.length()); }
348                         RippedTaxName +=  "."; 
349                 
350                         if (outputDir == "") { outputDir += m->hasPath(fastaFileNames[s]); }
351                         string newTaxonomyFile = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + RippedTaxName + "taxonomy";
352                         string tempTaxonomyFile = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + "taxonomy.temp";
353                         string taxSummary = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + RippedTaxName + "tax.summary";
354                         
355                         if ((method == "knn") && (search == "distance")) { 
356                                 string DistName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + "match.dist";
357                                 classify->setDistName(DistName);  outputNames.push_back(DistName);
358                         }
359                         
360                         outputNames.push_back(newTaxonomyFile);
361                         outputNames.push_back(taxSummary);
362                         
363                         int start = time(NULL);
364                         int numFastaSeqs = 0;
365                         for (int i = 0; i < lines.size(); i++) {  delete lines[i];  }  lines.clear();
366                         
367 #ifdef USE_MPI  
368                                 int pid, end, numSeqsPerProcessor; 
369                                 int tag = 2001;
370                                 vector<unsigned long int> MPIPos;
371                                 
372                                 MPI_Status status; 
373                                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
374                                 MPI_Comm_size(MPI_COMM_WORLD, &processors); 
375
376                                 MPI_File inMPI;
377                                 MPI_File outMPINewTax;
378                                 MPI_File outMPITempTax;
379                                                         
380                                 int outMode=MPI_MODE_CREATE|MPI_MODE_WRONLY; 
381                                 int inMode=MPI_MODE_RDONLY; 
382                                 
383                                 //char* outNewTax = new char[newTaxonomyFile.length()];
384                                 //memcpy(outNewTax, newTaxonomyFile.c_str(), newTaxonomyFile.length());
385                                 
386                                 char outNewTax[1024];
387                                 strcpy(outNewTax, newTaxonomyFile.c_str());
388
389                                 //char* outTempTax = new char[tempTaxonomyFile.length()];
390                                 //memcpy(outTempTax, tempTaxonomyFile.c_str(), tempTaxonomyFile.length());
391                                 
392                                 char outTempTax[1024];
393                                 strcpy(outTempTax, tempTaxonomyFile.c_str());
394
395                                 //char* inFileName = new char[fastaFileNames[s].length()];
396                                 //memcpy(inFileName, fastaFileNames[s].c_str(), fastaFileNames[s].length());
397                                 
398                                 char inFileName[1024];
399                                 strcpy(inFileName, fastaFileNames[s].c_str());
400
401                                 MPI_File_open(MPI_COMM_WORLD, inFileName, inMode, MPI_INFO_NULL, &inMPI);  //comm, filename, mode, info, filepointer
402                                 MPI_File_open(MPI_COMM_WORLD, outNewTax, outMode, MPI_INFO_NULL, &outMPINewTax);
403                                 MPI_File_open(MPI_COMM_WORLD, outTempTax, outMode, MPI_INFO_NULL, &outMPITempTax);
404                                 
405                                 //delete outNewTax;
406                                 //delete outTempTax;
407                                 //delete inFileName;
408
409                                 if (m->control_pressed) {  MPI_File_close(&inMPI);  MPI_File_close(&outMPINewTax);   MPI_File_close(&outMPITempTax);  delete classify; return 0;  }
410                                 
411                                 if (pid == 0) { //you are the root process 
412                                         
413                                         MPIPos = m->setFilePosFasta(fastaFileNames[s], numFastaSeqs); //fills MPIPos, returns numSeqs
414                                         
415                                         //send file positions to all processes
416                                         for(int i = 1; i < processors; i++) { 
417                                                 MPI_Send(&numFastaSeqs, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
418                                                 MPI_Send(&MPIPos[0], (numFastaSeqs+1), MPI_LONG, i, tag, MPI_COMM_WORLD);
419                                         }
420                                         
421                                         //figure out how many sequences you have to align
422                                         numSeqsPerProcessor = numFastaSeqs / processors;
423                                         int startIndex =  pid * numSeqsPerProcessor;
424                                         if(pid == (processors - 1)){    numSeqsPerProcessor = numFastaSeqs - pid * numSeqsPerProcessor;         }
425                                         
426                                 
427                                         //align your part
428                                         driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPINewTax, outMPITempTax, MPIPos);
429                                         
430                                         if (m->control_pressed) {  MPI_File_close(&inMPI);  MPI_File_close(&outMPINewTax);   MPI_File_close(&outMPITempTax);  for (int i = 0; i < outputNames.size(); i++) {    remove(outputNames[i].c_str()); } delete classify; return 0;  }
431                                         
432                                         for (int i = 1; i < processors; i++) {
433                                                 int done;
434                                                 MPI_Recv(&done, 1, MPI_INT, i, tag, MPI_COMM_WORLD, &status);
435                                         }
436                                 }else{ //you are a child process
437                                         MPI_Recv(&numFastaSeqs, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
438                                         MPIPos.resize(numFastaSeqs+1);
439                                         MPI_Recv(&MPIPos[0], (numFastaSeqs+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
440                                         
441                                         //figure out how many sequences you have to align
442                                         numSeqsPerProcessor = numFastaSeqs / processors;
443                                         int startIndex =  pid * numSeqsPerProcessor;
444                                         if(pid == (processors - 1)){    numSeqsPerProcessor = numFastaSeqs - pid * numSeqsPerProcessor;         }
445                                         
446                                         
447                                         //align your part
448                                         driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPINewTax, outMPITempTax, MPIPos);
449                                         
450                                         if (m->control_pressed) {  MPI_File_close(&inMPI);  MPI_File_close(&outMPINewTax);   MPI_File_close(&outMPITempTax);  delete classify; return 0;  }
451
452                                         int done = 0;
453                                         MPI_Send(&done, 1, MPI_INT, 0, tag, MPI_COMM_WORLD); 
454                                 }
455                                 
456                                 //close files 
457                                 MPI_File_close(&inMPI);
458                                 MPI_File_close(&outMPINewTax);
459                                 MPI_File_close(&outMPITempTax);
460                                 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
461                                 
462 #else
463                 
464                         vector<unsigned long int> positions = m->divideFile(fastaFileNames[s], processors);
465                                 
466                         for (int i = 0; i < (positions.size()-1); i++) {
467                                 lines.push_back(new linePair(positions[i], positions[(i+1)]));
468                         }       
469                         
470                 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
471                         if(processors == 1){
472                                 numFastaSeqs = driver(lines[0], newTaxonomyFile, tempTaxonomyFile, fastaFileNames[s]);
473                         }
474                         else{
475                                 processIDS.resize(0);
476                                 
477                                 numFastaSeqs = createProcesses(newTaxonomyFile, tempTaxonomyFile, fastaFileNames[s]); 
478                                 
479                                 rename((newTaxonomyFile + toString(processIDS[0]) + ".temp").c_str(), newTaxonomyFile.c_str());
480                                 rename((tempTaxonomyFile + toString(processIDS[0]) + ".temp").c_str(), tempTaxonomyFile.c_str());
481                                 
482                                 for(int i=1;i<processors;i++){
483                                         appendTaxFiles((newTaxonomyFile + toString(processIDS[i]) + ".temp"), newTaxonomyFile);
484                                         appendTaxFiles((tempTaxonomyFile + toString(processIDS[i]) + ".temp"), tempTaxonomyFile);
485                                         remove((newTaxonomyFile + toString(processIDS[i]) + ".temp").c_str());
486                                         remove((tempTaxonomyFile + toString(processIDS[i]) + ".temp").c_str());
487                                 }
488                                 
489                         }
490         #else
491                         numFastaSeqs = driver(lines[0], newTaxonomyFile, tempTaxonomyFile, fastaFileNames[s]);
492         #endif  
493 #endif
494
495                 m->mothurOutEndLine();
496                 m->mothurOut("It took " + toString(time(NULL) - start) + " secs to classify " + toString(numFastaSeqs) + " sequences."); m->mothurOutEndLine(); m->mothurOutEndLine();
497                 start = time(NULL);
498
499
500                 #ifdef USE_MPI  
501                         if (pid == 0) {  //this part does not need to be paralellized
502                         
503                                 if(namefile != "") { m->mothurOut("Reading " + namefileNames[s] + "..."); cout.flush();  MPIReadNamesFile(namefileNames[s]);  m->mothurOut("  Done."); m->mothurOutEndLine(); }
504                 #else
505                         //read namefile
506                         if(namefile != "") {
507                         
508                             m->mothurOut("Reading " + namefileNames[s] + "..."); cout.flush();
509                                 
510                                 nameMap.clear(); //remove old names
511                                 
512                                 ifstream inNames;
513                                 m->openInputFile(namefileNames[s], inNames);
514                                 
515                                 string firstCol, secondCol;
516                                 while(!inNames.eof()) {
517                                         inNames >> firstCol >> secondCol; m->gobble(inNames);
518                                         
519                                         vector<string> temp;
520                                         m->splitAtComma(secondCol, temp);
521                         
522                                         nameMap[firstCol] = temp;  
523                                 }
524                                 inNames.close();
525                                 
526                                 m->mothurOut("  Done."); m->mothurOutEndLine();
527                         }
528                 #endif
529
530                         string group = "";
531                         if (groupfile != "") {  group = groupfileNames[s]; }
532                         
533                         PhyloSummary taxaSum(taxonomyFileName, group);
534                         
535                         if (m->control_pressed) {  for (int i = 0; i < outputNames.size(); i++) {       remove(outputNames[i].c_str()); } delete classify; return 0; }
536                 
537                         if (namefile == "") {  taxaSum.summarize(tempTaxonomyFile);  }
538                         else {
539                                 ifstream in;
540                                 m->openInputFile(tempTaxonomyFile, in);
541                                 
542                                 //read in users taxonomy file and add sequences to tree
543                                 string name, taxon;
544                                 
545                                 while(!in.eof()){
546                                         in >> name >> taxon; m->gobble(in);
547                                         
548                                         itNames = nameMap.find(name);
549                 
550                                         if (itNames == nameMap.end()) { 
551                                                 m->mothurOut(name + " is not in your name file please correct."); m->mothurOutEndLine(); exit(1);
552                                         }else{
553                                                 for (int i = 0; i < itNames->second.size(); i++) { 
554                                                         taxaSum.addSeqToTree(itNames->second[i], taxon);  //add it as many times as there are identical seqs
555                                                 }
556                                                 itNames->second.clear();
557                                                 nameMap.erase(itNames->first);
558                                         }
559                                 }
560                                 in.close();
561                         }
562                         remove(tempTaxonomyFile.c_str());
563                         
564                         if (m->control_pressed) {  for (int i = 0; i < outputNames.size(); i++) {       remove(outputNames[i].c_str()); } delete classify; return 0; }
565                         
566                         //print summary file
567                         ofstream outTaxTree;
568                         m->openOutputFile(taxSummary, outTaxTree);
569                         taxaSum.print(outTaxTree);
570                         outTaxTree.close();
571                         
572                         //output taxonomy with the unclassified bins added
573                         ifstream inTax;
574                         m->openInputFile(newTaxonomyFile, inTax);
575                         
576                         ofstream outTax;
577                         string unclass = newTaxonomyFile + ".unclass.temp";
578                         m->openOutputFile(unclass, outTax);
579                         
580                         //get maxLevel from phylotree so you know how many 'unclassified's to add
581                         int maxLevel = taxaSum.getMaxLevel();
582                         
583                         //read taxfile - this reading and rewriting is done to preserve the confidence scores.
584                         string name, taxon;
585                         while (!inTax.eof()) {
586                                 if (m->control_pressed) {  for (int i = 0; i < outputNames.size(); i++) {       remove(outputNames[i].c_str()); } remove(unclass.c_str()); delete classify; return 0; }
587
588                                 inTax >> name >> taxon; m->gobble(inTax);
589                                 
590                                 string newTax = addUnclassifieds(taxon, maxLevel);
591                                 
592                                 outTax << name << '\t' << newTax << endl;
593                         }
594                         inTax.close();  
595                         outTax.close();
596                         
597                         remove(newTaxonomyFile.c_str());
598                         rename(unclass.c_str(), newTaxonomyFile.c_str());
599                         
600                         m->mothurOutEndLine();
601                         m->mothurOut("It took " + toString(time(NULL) - start) + " secs to create the summary file for " + toString(numFastaSeqs) + " sequences."); m->mothurOutEndLine(); m->mothurOutEndLine();
602                         
603                         #ifdef USE_MPI  
604                                 }
605                         #endif
606
607                         m->mothurOutEndLine();
608                         m->mothurOut("Output File Names: "); m->mothurOutEndLine();
609                         for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }
610                         m->mothurOutEndLine();
611                 }
612                 
613                 delete classify;
614                 return 0;
615         }
616         catch(exception& e) {
617                 m->errorOut(e, "ClassifySeqsCommand", "execute");
618                 exit(1);
619         }
620 }
621
622 /**************************************************************************************************/
623 string ClassifySeqsCommand::addUnclassifieds(string tax, int maxlevel) {
624         try{
625                 string newTax, taxon;
626                 int level = 0;
627                 
628                 //keep what you have counting the levels
629                 while (tax.find_first_of(';') != -1) {
630                         //get taxon
631                         taxon = tax.substr(0,tax.find_first_of(';'))+';';
632                         tax = tax.substr(tax.find_first_of(';')+1, tax.length());
633                         newTax += taxon;
634                         level++;
635                 }
636                 
637                 //add "unclassified" until you reach maxLevel
638                 while (level < maxlevel) {
639                         newTax += "unclassified;";
640                         level++;
641                 }
642                 
643                 return newTax;
644         }
645         catch(exception& e) {
646                 m->errorOut(e, "ClassifySeqsCommand", "addUnclassifieds");
647                 exit(1);
648         }
649 }
650
651 /**************************************************************************************************/
652
653 int ClassifySeqsCommand::createProcesses(string taxFileName, string tempTaxFile, string filename) {
654         try {
655 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
656                 int process = 0;
657                 int num = 0;
658                 
659                 //loop through and create all the processes you want
660                 while (process != processors) {
661                         int pid = fork();
662                         
663                         if (pid > 0) {
664                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
665                                 process++;
666                         }else if (pid == 0){
667                                 num = driver(lines[process], taxFileName + toString(getpid()) + ".temp", tempTaxFile + toString(getpid()) + ".temp", filename);
668                                 
669                                 //pass numSeqs to parent
670                                 ofstream out;
671                                 string tempFile = filename + toString(getpid()) + ".num.temp";
672                                 m->openOutputFile(tempFile, out);
673                                 out << num << endl;
674                                 out.close();
675
676                                 exit(0);
677                         }else { m->mothurOut("unable to spawn the necessary processes."); m->mothurOutEndLine(); exit(0); }
678                 }
679                 
680                 //force parent to wait until all the processes are done
681                 for (int i=0;i<processors;i++) { 
682                         int temp = processIDS[i];
683                         wait(&temp);
684                 }
685                 
686                 for (int i = 0; i < processIDS.size(); i++) {
687                         ifstream in;
688                         string tempFile =  filename + toString(processIDS[i]) + ".num.temp";
689                         m->openInputFile(tempFile, in);
690                         if (!in.eof()) { int tempNum = 0; in >> tempNum; num += tempNum; }
691                         in.close(); remove(tempFile.c_str());
692                 }
693                 
694                 return num;
695 #endif          
696         }
697         catch(exception& e) {
698                 m->errorOut(e, "ClassifySeqsCommand", "createProcesses");
699                 exit(1);
700         }
701 }
702 /**************************************************************************************************/
703
704 void ClassifySeqsCommand::appendTaxFiles(string temp, string filename) {
705         try{
706                 
707                 ofstream output;
708                 ifstream input;
709                 m->openOutputFileAppend(filename, output);
710                 m->openInputFile(temp, input);
711                 
712                 while(char c = input.get()){
713                         if(input.eof())         {       break;                  }
714                         else                            {       output << c;    }
715                 }
716                 
717                 input.close();
718                 output.close();
719         }
720         catch(exception& e) {
721                 m->errorOut(e, "ClassifySeqsCommand", "appendTaxFiles");
722                 exit(1);
723         }
724 }
725
726 //**********************************************************************************************************************
727
728 int ClassifySeqsCommand::driver(linePair* filePos, string taxFName, string tempTFName, string filename){
729         try {
730                 ofstream outTax;
731                 m->openOutputFile(taxFName, outTax);
732                 
733                 ofstream outTaxSimple;
734                 m->openOutputFile(tempTFName, outTaxSimple);
735         
736                 ifstream inFASTA;
737                 m->openInputFile(filename, inFASTA);
738                 
739                 string taxonomy;
740
741                 inFASTA.seekg(filePos->start);
742
743                 bool done = false;
744                 int count = 0;
745         
746                 while (!done) {
747                         if (m->control_pressed) { return 0; }
748                 
749                         Sequence* candidateSeq = new Sequence(inFASTA); m->gobble(inFASTA);
750                 
751                         if (candidateSeq->getName() != "") {
752                                 taxonomy = classify->getTaxonomy(candidateSeq);
753                                 
754                                 if (m->control_pressed) { delete candidateSeq; return 0; }
755
756                                 if (taxonomy != "bad seq") {
757                                         //output confidence scores or not
758                                         if (probs) {
759                                                 outTax << candidateSeq->getName() << '\t' << taxonomy << endl;
760                                         }else{
761                                                 outTax << candidateSeq->getName() << '\t' << classify->getSimpleTax() << endl;
762                                         }
763                                         
764                                         outTaxSimple << candidateSeq->getName() << '\t' << classify->getSimpleTax() << endl;
765                                 }
766                                 count++;
767                         }
768                         delete candidateSeq;
769                         
770                         #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
771                                 unsigned long int pos = inFASTA.tellg();
772                                 if ((pos == -1) || (pos >= filePos->end)) { break; }
773                         #else
774                                 if (inFASTA.eof()) { break; }
775                         #endif
776                         
777                         //report progress
778                         if((count) % 100 == 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine();         }
779                 }
780                 //report progress
781                 if((count) % 100 != 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine();         }
782                                 
783                 inFASTA.close();
784                 outTax.close();
785                 outTaxSimple.close();
786                 
787                 return count;
788         }
789         catch(exception& e) {
790                 m->errorOut(e, "ClassifySeqsCommand", "driver");
791                 exit(1);
792         }
793 }
794 //**********************************************************************************************************************
795 #ifdef USE_MPI
796 int ClassifySeqsCommand::driverMPI(int start, int num, MPI_File& inMPI, MPI_File& newFile, MPI_File& tempFile, vector<unsigned long int>& MPIPos){
797         try {
798                 MPI_Status statusNew; 
799                 MPI_Status statusTemp; 
800                 MPI_Status status; 
801                 
802                 int pid;
803                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
804         
805                 string taxonomy;
806                 string outputString;
807
808                 for(int i=0;i<num;i++){
809                 
810                         if (m->control_pressed) { return 0; }
811                 
812                         //read next sequence
813                         int length = MPIPos[start+i+1] - MPIPos[start+i];
814                         char* buf4 = new char[length];
815                         MPI_File_read_at(inMPI, MPIPos[start+i], buf4, length, MPI_CHAR, &status);
816                         
817                         string tempBuf = buf4;
818                         if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length);  }
819                         istringstream iss (tempBuf,istringstream::in);
820                         delete buf4;
821
822                         Sequence* candidateSeq = new Sequence(iss);
823                         
824                         if (candidateSeq->getName() != "") {
825                                 taxonomy = classify->getTaxonomy(candidateSeq);
826                                 
827                                 if (taxonomy != "bad seq") {
828                                         //output confidence scores or not
829                                         if (probs) {
830                                                 outputString =  candidateSeq->getName() + "\t" + taxonomy + "\n";
831                                         }else{
832                                                 outputString =  candidateSeq->getName() + "\t" + classify->getSimpleTax() + "\n";
833                                         }
834                                         
835                                         int length = outputString.length();
836                                         char* buf2 = new char[length];
837                                         memcpy(buf2, outputString.c_str(), length);
838                                 
839                                         MPI_File_write_shared(newFile, buf2, length, MPI_CHAR, &statusNew);
840                                         delete buf2;
841
842                                         outputString =  candidateSeq->getName() + "\t" + classify->getSimpleTax() + "\n";
843                                         length = outputString.length();
844                                         char* buf = new char[length];
845                                         memcpy(buf, outputString.c_str(), length);
846                                 
847                                         MPI_File_write_shared(tempFile, buf, length, MPI_CHAR, &statusTemp);
848                                         delete buf;
849                                 }
850                         }                               
851                         delete candidateSeq;
852                         
853                         if((i+1) % 100 == 0){   cout << "Classifying sequence " << (i+1) << endl;       }
854                 }
855                 
856                 if(num % 100 != 0){     cout << "Classifying sequence " << (num) << endl;       }
857                 
858                 
859                 return 1;
860         }
861         catch(exception& e) {
862                 m->errorOut(e, "ClassifySeqsCommand", "driverMPI");
863                 exit(1);
864         }
865 }
866
867 //**********************************************************************************************************************
868 int ClassifySeqsCommand::MPIReadNamesFile(string nameFilename){
869         try {
870         
871                 nameMap.clear(); //remove old names
872                 
873                 MPI_File inMPI;
874                 MPI_Offset size;
875                 MPI_Status status;
876
877                 //char* inFileName = new char[nameFilename.length()];
878                 //memcpy(inFileName, nameFilename.c_str(), nameFilename.length());
879                 
880                 char inFileName[1024];
881                 strcpy(inFileName, nameFilename.c_str());
882
883                 MPI_File_open(MPI_COMM_WORLD, inFileName, MPI_MODE_RDONLY, MPI_INFO_NULL, &inMPI);  
884                 MPI_File_get_size(inMPI, &size);
885                 //delete inFileName;
886
887                 char* buffer = new char[size];
888                 MPI_File_read(inMPI, buffer, size, MPI_CHAR, &status);
889
890                 string tempBuf = buffer;
891                 if (tempBuf.length() > size) { tempBuf = tempBuf.substr(0, size);  }
892                 istringstream iss (tempBuf,istringstream::in);
893                 delete buffer;
894                 
895                 string firstCol, secondCol;
896                 while(!iss.eof()) {
897                         iss >> firstCol >> secondCol; m->gobble(iss);
898                         
899                         vector<string> temp;
900                         m->splitAtComma(secondCol, temp);
901                         
902                         nameMap[firstCol] = temp;  
903                 }
904         
905                 MPI_File_close(&inMPI);
906                 
907                 return 1;
908         }
909         catch(exception& e) {
910                 m->errorOut(e, "ClassifySeqsCommand", "MPIReadNamesFile");
911                 exit(1);
912         }
913 }
914 #endif
915 /**************************************************************************************************/