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