]> git.donarmstrong.com Git - mothur.git/blob - classifyseqscommand.cpp
added sorted parameter to get.oturep, added error checking to chimera classes in...
[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 "knn.h"
15
16 //**********************************************************************************************************************
17
18 ClassifySeqsCommand::ClassifySeqsCommand(string option){
19         try {
20                 abort = false;
21                 
22                 //allow user to run help
23                 if(option == "help") { help(); abort = true; }
24                 
25                 else {
26                         
27                         //valid paramters for this command
28                         string AlignArray[] =  {"template","fasta","search","ksize","method","processors","taxonomy","match","mismatch","gapopen","gapextend","numwanted","cutoff","probs"};
29                         vector<string> myArray (AlignArray, AlignArray+(sizeof(AlignArray)/sizeof(string)));
30                         
31                         OptionParser parser(option);
32                         map<string, string> parameters = parser.getParameters(); 
33                         
34                         ValidParameters validParameter;
35                         
36                         //check to make sure all parameters are valid for command
37                         for (map<string, string>::iterator it = parameters.begin(); it != parameters.end(); it++) { 
38                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
39                         }
40                         
41                         //check for required parameters
42                         templateFileName = validParameter.validFile(parameters, "template", true);
43                         if (templateFileName == "not found") { 
44                                 mothurOut("template is a required parameter for the classify.seqs command."); 
45                                 mothurOutEndLine();
46                                 abort = true; 
47                         }
48                         else if (templateFileName == "not open") { abort = true; }      
49                         
50                         fastaFileName = validParameter.validFile(parameters, "fasta", true);
51                         if (fastaFileName == "not found") { 
52                                 mothurOut("fasta is a required parameter for the classify.seqs command."); 
53                                 mothurOutEndLine();
54                                 abort = true; 
55                         }
56                         else if (fastaFileName == "not open") { abort = true; } 
57                         
58                         taxonomyFileName = validParameter.validFile(parameters, "taxonomy", true);
59                         if (taxonomyFileName == "not found") { 
60                                 mothurOut("taxonomy is a required parameter for the classify.seqs command."); 
61                                 mothurOutEndLine();
62                                 abort = true; 
63                         }
64                         else if (taxonomyFileName == "not open") { abort = true; }      
65
66                         
67                         //check for optional parameter and set defaults
68                         // ...at some point should added some additional type checking...
69                         string temp;
70                         temp = validParameter.validFile(parameters, "ksize", false);            if (temp == "not found"){       temp = "8";                             }
71                         convert(temp, kmerSize); 
72                         
73                         temp = validParameter.validFile(parameters, "processors", false);       if (temp == "not found"){       temp = "1";                             }
74                         convert(temp, processors); 
75                         
76                         search = validParameter.validFile(parameters, "search", false);         if (search == "not found"){     search = "kmer";                }
77                         
78                         method = validParameter.validFile(parameters, "method", false);         if (method == "not found"){     method = "bayesian";    }
79                         
80                         temp = validParameter.validFile(parameters, "match", false);            if (temp == "not found"){       temp = "1.0";                   }
81                         convert(temp, match);  
82                         
83                         temp = validParameter.validFile(parameters, "mismatch", false);         if (temp == "not found"){       temp = "-1.0";                  }
84                         convert(temp, misMatch);  
85                         
86                         temp = validParameter.validFile(parameters, "gapopen", false);          if (temp == "not found"){       temp = "-2.0";                  }
87                         convert(temp, gapOpen);  
88                         
89                         temp = validParameter.validFile(parameters, "gapextend", false);        if (temp == "not found"){       temp = "-1.0";                  }
90                         convert(temp, gapExtend); 
91                         
92                         temp = validParameter.validFile(parameters, "numwanted", false);        if (temp == "not found"){       temp = "10";                    }
93                         convert(temp, numWanted);
94                         
95                         temp = validParameter.validFile(parameters, "cutoff", false);           if (temp == "not found"){       temp = "0";                             }
96                         convert(temp, cutoff);
97                         
98                         temp = validParameter.validFile(parameters, "probs", false);            if (temp == "not found"){       temp = "true";                  }
99                         probs = isTrue(temp);
100
101                         
102                         if ((method == "bayesian") && (search != "kmer"))  { 
103                                 mothurOut("The bayesian method requires the kmer search." + search + "will be disregarded." ); mothurOutEndLine();
104                                 search = "kmer";
105                         }
106                 }
107                 
108         }
109         catch(exception& e) {
110                 errorOut(e, "ClassifySeqsCommand", "ClassifySeqsCommand");
111                 exit(1);
112         }
113 }
114
115 //**********************************************************************************************************************
116
117 ClassifySeqsCommand::~ClassifySeqsCommand(){    
118
119         if (abort == false) {
120                 for (int i = 0; i < lines.size(); i++) {  delete lines[i];  }  lines.clear();
121         }
122 }
123
124 //**********************************************************************************************************************
125
126 void ClassifySeqsCommand::help(){
127         try {
128                 mothurOut("The classify.seqs command reads a fasta file containing sequences and creates a .taxonomy file and a .tax.summary file.\n");
129                 mothurOut("The classify.seqs command parameters are template, fasta, search, ksize, method, taxonomy, processors, match, mismatch, gapopen, gapextend, numwanted and probs.\n");
130                 mothurOut("The template, fasta and taxonomy parameters are required.\n");
131                 mothurOut("The search parameter allows you to specify the method to find most similar template.  Your options are: suffix, kmer and blast. The default is kmer.\n");
132                 mothurOut("The method parameter allows you to specify classification method to use.  Your options are: bayesian and knn. The default is bayesian.\n");
133                 mothurOut("The ksize parameter allows you to specify the kmer size for finding most similar template to candidate.  The default is 8.\n");
134                 mothurOut("The processors parameter allows you to specify the number of processors to use. The default is 1.\n");
135                 mothurOut("The match parameter allows you to specify the bonus for having the same base. The default is 1.0.\n");
136                 mothurOut("The mistmatch parameter allows you to specify the penalty for having different bases.  The default is -1.0.\n");
137                 mothurOut("The gapopen parameter allows you to specify the penalty for opening a gap in an alignment. The default is -1.0.\n");
138                 mothurOut("The gapextend parameter allows you to specify the penalty for extending a gap in an alignment.  The default is -2.0.\n");
139                 mothurOut("The numwanted parameter allows you to specify the number of sequence matches you want with the knn method.  The default is 10.\n");
140                 mothurOut("The cutoff parameter allows you to specify a bootstrap confidence threshold for your taxonomy.  The default is 0.\n");
141                 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");
142                 mothurOut("The classify.seqs command should be in the following format: \n");
143                 mothurOut("classify.seqs(template=yourTemplateFile, fasta=yourFastaFile, method=yourClassificationMethod, search=yourSearchmethod, ksize=yourKmerSize, taxonomy=yourTaxonomyFile, processors=yourProcessors) \n");
144                 mothurOut("Example classify.seqs(fasta=amazon.fasta, template=core.filtered, method=knn, search=gotoh, ksize=8, processors=2)\n");
145                 mothurOut("The .taxonomy file consists of 2 columns: 1 = your sequence name, 2 = the taxonomy for your sequence. \n");
146                 mothurOut("The .tax.summary is a summary of the different taxonomies represented in your fasta file. \n");
147                 mothurOut("Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFastaFile).\n\n");
148         }
149         catch(exception& e) {
150                 errorOut(e, "ClassifySeqsCommand", "help");
151                 exit(1);
152         }
153 }
154
155
156 //**********************************************************************************************************************
157
158 int ClassifySeqsCommand::execute(){
159         try {
160                 if (abort == true) {    return 0;       }
161                 
162                 if(method == "bayesian")                        {       classify = new Bayesian(taxonomyFileName, templateFileName, search, kmerSize, cutoff, probs);           }
163                 else if(method == "knn")                        {       classify = new Knn(taxonomyFileName, templateFileName, search, kmerSize, gapOpen, gapExtend, match, misMatch, numWanted);                               }
164                 else {
165                         mothurOut(search + " is not a valid method option. I will run the command using bayesian.");
166                         mothurOutEndLine();
167                         classify = new Bayesian(taxonomyFileName, templateFileName, search, kmerSize, cutoff, probs);   
168                 }
169
170                 int numFastaSeqs = 0;
171                 
172                 string newTaxonomyFile = getRootName(fastaFileName) + "taxonomy";
173                 string tempTaxonomyFile = getRootName(fastaFileName) + "taxonomy.temp";
174                 string taxSummary = getRootName(fastaFileName) + "tax.summary";
175                 
176                 int start = time(NULL);
177 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
178                 if(processors == 1){
179                         ifstream inFASTA;
180                         openInputFile(fastaFileName, inFASTA);
181                         numFastaSeqs=count(istreambuf_iterator<char>(inFASTA),istreambuf_iterator<char>(), '>');
182                         inFASTA.close();
183                         
184                         lines.push_back(new linePair(0, numFastaSeqs));
185                 
186                         driver(lines[0], newTaxonomyFile, tempTaxonomyFile);
187                 }
188                 else{
189                         vector<int> positions;
190                         processIDS.resize(0);
191                         
192                         ifstream inFASTA;
193                         openInputFile(fastaFileName, inFASTA);
194                         
195                         string input;
196                         while(!inFASTA.eof()){
197                                 input = getline(inFASTA);
198                                 if (input.length() != 0) {
199                                         if(input[0] == '>'){    int pos = inFASTA.tellg(); positions.push_back(pos - input.length() - 1);       }
200                                 }
201                         }
202                         inFASTA.close();
203                         
204                         numFastaSeqs = positions.size();
205                         
206                         int numSeqsPerProcessor = numFastaSeqs / processors;
207                         
208                         for (int i = 0; i < processors; i++) {
209                                 int startPos = positions[ i * numSeqsPerProcessor ];
210                                 if(i == processors - 1){
211                                         numSeqsPerProcessor = numFastaSeqs - i * numSeqsPerProcessor;
212                                 }
213                                 lines.push_back(new linePair(startPos, numSeqsPerProcessor));
214                         }
215                         createProcesses(newTaxonomyFile, tempTaxonomyFile); 
216                         
217                         rename((newTaxonomyFile + toString(processIDS[0]) + ".temp").c_str(), newTaxonomyFile.c_str());
218                         rename((tempTaxonomyFile + toString(processIDS[0]) + ".temp").c_str(), tempTaxonomyFile.c_str());
219                         
220                         for(int i=1;i<processors;i++){
221                                 appendTaxFiles((newTaxonomyFile + toString(processIDS[i]) + ".temp"), newTaxonomyFile);
222                                 appendTaxFiles((tempTaxonomyFile + toString(processIDS[i]) + ".temp"), tempTaxonomyFile);
223                                 remove((newTaxonomyFile + toString(processIDS[i]) + ".temp").c_str());
224                                 remove((tempTaxonomyFile + toString(processIDS[i]) + ".temp").c_str());
225                         }
226                         
227                 }
228 #else
229                 ifstream inFASTA;
230                 openInputFile(fastaFileName, inFASTA);
231                 numFastaSeqs=count(istreambuf_iterator<char>(inFASTA),istreambuf_iterator<char>(), '>');
232                 inFASTA.close();
233                 
234                 lines.push_back(new linePair(0, numFastaSeqs));
235                 
236                 driver(lines[0], newTaxonomyFile, tempTaxonomyFile);
237 #endif  
238                 delete classify;
239                 
240                 //make taxonomy tree from new taxonomy file 
241                 ifstream inTaxonomy;
242                 openInputFile(tempTaxonomyFile, inTaxonomy);
243                 
244                 string accession, taxaList;
245                 PhyloTree taxaBrowser;
246                 
247                 //read in users taxonomy file and add sequences to tree
248                 while(!inTaxonomy.eof()){
249                         inTaxonomy >> accession >> taxaList;
250                         
251                         taxaBrowser.addSeqToTree(accession, taxaList);
252                         
253                         gobble(inTaxonomy);
254                 }
255                 inTaxonomy.close();
256                 remove(tempTaxonomyFile.c_str());
257                 
258                 taxaBrowser.assignHeirarchyIDs(0);
259                 
260                 ofstream outTaxTree;
261                 openOutputFile(taxSummary, outTaxTree);
262                 
263                 taxaBrowser.print(outTaxTree);
264                 
265                 mothurOutEndLine();
266                 mothurOut("It took " + toString(time(NULL) - start) + " secs to classify " + toString(numFastaSeqs) + " sequences.");
267                 mothurOutEndLine();
268                 mothurOutEndLine();
269                 
270                 return 0;
271         }
272         catch(exception& e) {
273                 errorOut(e, "ClassifySeqsCommand", "execute");
274                 exit(1);
275         }
276 }
277 /**************************************************************************************************/
278
279 void ClassifySeqsCommand::createProcesses(string taxFileName, string tempTaxFile) {
280         try {
281 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
282                 int process = 0;
283                 //              processIDS.resize(0);
284                 
285                 //loop through and create all the processes you want
286                 while (process != processors) {
287                         int pid = fork();
288                         
289                         if (pid > 0) {
290                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
291                                 process++;
292                         }else if (pid == 0){
293                                 driver(lines[process], taxFileName + toString(getpid()) + ".temp", tempTaxFile + toString(getpid()) + ".temp");
294                                 exit(0);
295                         }else { mothurOut("unable to spawn the necessary processes."); mothurOutEndLine(); exit(0); }
296                 }
297                 
298                 //force parent to wait until all the processes are done
299                 for (int i=0;i<processors;i++) { 
300                         int temp = processIDS[i];
301                         wait(&temp);
302                 }
303 #endif          
304         }
305         catch(exception& e) {
306                 errorOut(e, "ClassifySeqsCommand", "createProcesses");
307                 exit(1);
308         }
309 }
310 /**************************************************************************************************/
311
312 void ClassifySeqsCommand::appendTaxFiles(string temp, string filename) {
313         try{
314                 
315                 ofstream output;
316                 ifstream input;
317                 openOutputFileAppend(filename, output);
318                 openInputFile(temp, input);
319                 
320                 while(char c = input.get()){
321                         if(input.eof())         {       break;                  }
322                         else                            {       output << c;    }
323                 }
324                 
325                 input.close();
326                 output.close();
327         }
328         catch(exception& e) {
329                 errorOut(e, "ClassifySeqsCommand", "appendTaxFiles");
330                 exit(1);
331         }
332 }
333
334 //**********************************************************************************************************************
335
336 int ClassifySeqsCommand::driver(linePair* line, string taxFName, string tempTFName){
337         try {
338                 ofstream outTax;
339                 openOutputFile(taxFName, outTax);
340                 
341                 ofstream outTaxSimple;
342                 openOutputFile(tempTFName, outTaxSimple);
343         
344                 ifstream inFASTA;
345                 openInputFile(fastaFileName, inFASTA);
346
347                 inFASTA.seekg(line->start);
348                 
349                 string taxonomy;
350
351                 for(int i=0;i<line->numSeqs;i++){
352                         
353                         Sequence* candidateSeq = new Sequence(inFASTA);
354                         
355                         if (candidateSeq->getName() != "") {
356                                 taxonomy = classify->getTaxonomy(candidateSeq);
357                                 
358                                 if (taxonomy != "bad seq") {
359                                         outTax << candidateSeq->getName() << '\t' << taxonomy << endl;
360                                         outTaxSimple << candidateSeq->getName() << '\t' << classify->getSimpleTax() << endl;
361                                 }
362                         }                               
363                         delete candidateSeq;
364                         
365                         if((i+1) % 100 == 0){
366                                 mothurOut("Classifying sequence " + toString(i+1)); mothurOutEndLine();
367                         }
368                 }
369                 
370                 inFASTA.close();
371                 outTax.close();
372                 outTaxSimple.close();
373                 
374                 return 1;
375         }
376         catch(exception& e) {
377                 errorOut(e, "ClassifySeqsCommand", "driver");
378                 exit(1);
379         }
380 }
381
382 /**************************************************************************************************/