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