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