2 * classifyseqscommand.cpp
5 * Created by westcott on 11/2/09.
6 * Copyright 2009 Schloss Lab. All rights reserved.
10 #include "classifyseqscommand.h"
11 #include "sequence.hpp"
13 #include "phylotree.h"
16 //**********************************************************************************************************************
18 ClassifySeqsCommand::ClassifySeqsCommand(string option){
22 //allow user to run help
23 if(option == "help") { help(); abort = true; }
27 //valid paramters for this command
28 string AlignArray[] = {"template","fasta","search","ksize","method","processors","taxonomy","match","mismatch","gapopen","gapextend","numwanted","cutoff"};
29 vector<string> myArray (AlignArray, AlignArray+(sizeof(AlignArray)/sizeof(string)));
31 OptionParser parser(option);
32 map<string, string> parameters = parser.getParameters();
34 ValidParameters validParameter;
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; }
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.");
48 else if (templateFileName == "not open") { abort = true; }
50 fastaFileName = validParameter.validFile(parameters, "fasta", true);
51 if (fastaFileName == "not found") {
52 mothurOut("fasta is a required parameter for the classify.seqs command.");
56 else if (fastaFileName == "not open") { abort = true; }
58 taxonomyFileName = validParameter.validFile(parameters, "taxonomy", true);
59 if (taxonomyFileName == "not found") {
60 mothurOut("taxonomy is a required parameter for the classify.seqs command.");
64 else if (taxonomyFileName == "not open") { abort = true; }
67 //check for optional parameter and set defaults
68 // ...at some point should added some additional type checking...
70 temp = validParameter.validFile(parameters, "ksize", false); if (temp == "not found"){ temp = "8"; }
71 convert(temp, kmerSize);
73 temp = validParameter.validFile(parameters, "processors", false); if (temp == "not found"){ temp = "1"; }
74 convert(temp, processors);
76 search = validParameter.validFile(parameters, "search", false); if (search == "not found"){ search = "kmer"; }
78 method = validParameter.validFile(parameters, "method", false); if (method == "not found"){ method = "bayesian"; }
80 temp = validParameter.validFile(parameters, "match", false); if (temp == "not found"){ temp = "1.0"; }
83 temp = validParameter.validFile(parameters, "mismatch", false); if (temp == "not found"){ temp = "-1.0"; }
84 convert(temp, misMatch);
86 temp = validParameter.validFile(parameters, "gapopen", false); if (temp == "not found"){ temp = "-2.0"; }
87 convert(temp, gapOpen);
89 temp = validParameter.validFile(parameters, "gapextend", false); if (temp == "not found"){ temp = "-1.0"; }
90 convert(temp, gapExtend);
92 temp = validParameter.validFile(parameters, "numwanted", false); if (temp == "not found"){ temp = "10"; }
93 convert(temp, numWanted);
95 temp = validParameter.validFile(parameters, "cutoff", false); if (temp == "not found"){ temp = "0"; }
96 convert(temp, cutoff);
99 if ((method == "bayesian") && (search != "kmer")) {
100 mothurOut("The bayesian method requires the kmer search." + search + "will be disregarded." ); mothurOutEndLine();
106 catch(exception& e) {
107 errorOut(e, "ClassifySeqsCommand", "ClassifySeqsCommand");
112 //**********************************************************************************************************************
114 ClassifySeqsCommand::~ClassifySeqsCommand(){
116 if (abort == false) {
117 for (int i = 0; i < lines.size(); i++) { delete lines[i]; } lines.clear();
121 //**********************************************************************************************************************
123 void ClassifySeqsCommand::help(){
125 mothurOut("The classify.seqs command reads a fasta file containing sequences and creates a .taxonomy file and a .tax.summary file.\n");
126 mothurOut("The classify.seqs command parameters are template, fasta, search, ksize, method, taxonomy, processors, match, mismatch, gapopen, gapextend and numwanted.\n");
127 mothurOut("The template, fasta and taxonomy parameters are required.\n");
128 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");
129 mothurOut("The method parameter allows you to specify classification method to use. Your options are: bayesian and knn. The default is bayesian.\n");
130 mothurOut("The ksize parameter allows you to specify the kmer size for finding most similar template to candidate. The default is 8.\n");
131 mothurOut("The processors parameter allows you to specify the number of processors to use. The default is 1.\n");
132 mothurOut("The match parameter allows you to specify the bonus for having the same base. The default is 1.0.\n");
133 mothurOut("The mistmatch parameter allows you to specify the penalty for having different bases. The default is -1.0.\n");
134 mothurOut("The gapopen parameter allows you to specify the penalty for opening a gap in an alignment. The default is -1.0.\n");
135 mothurOut("The gapextend parameter allows you to specify the penalty for extending a gap in an alignment. The default is -2.0.\n");
136 mothurOut("The numwanted parameter allows you to specify the number of sequence matches you want with the knn method. The default is 10.\n");
137 mothurOut("The cutoff parameter allows you to specify a bootstrap confidence threshold for your taxonomy. The default is 0.\n");
138 mothurOut("The classify.seqs command should be in the following format: \n");
139 mothurOut("classify.seqs(template=yourTemplateFile, fasta=yourFastaFile, method=yourClassificationMethod, search=yourSearchmethod, ksize=yourKmerSize, taxonomy=yourTaxonomyFile, processors=yourProcessors) \n");
140 mothurOut("Example classify.seqs(fasta=amazon.fasta, template=core.filtered, method=knn, search=gotoh, ksize=8, processors=2)\n");
141 mothurOut("The .taxonomy file consists of 2 columns: 1 = your sequence name, 2 = the taxonomy for your sequence. \n");
142 mothurOut("The .tax.summary is a summary of the different taxonomies represented in your fasta file. \n");
143 mothurOut("Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFastaFile).\n\n");
145 catch(exception& e) {
146 errorOut(e, "ClassifySeqsCommand", "help");
152 //**********************************************************************************************************************
154 int ClassifySeqsCommand::execute(){
156 if (abort == true) { return 0; }
160 if(method == "bayesian") { classify = new Bayesian(taxonomyFileName, templateFileName, search, kmerSize, cutoff); }
161 else if(method == "knn") { classify = new Knn(taxonomyFileName, templateFileName, search, kmerSize, gapOpen, gapExtend, match, misMatch, numWanted); }
163 mothurOut(search + " is not a valid method option. I will run the command using bayesian.");
165 classify = new Bayesian(taxonomyFileName, templateFileName, search, kmerSize, cutoff);
168 int numFastaSeqs = 0;
170 string newTaxonomyFile = getRootName(fastaFileName) + "taxonomy";
171 string tempTaxonomyFile = getRootName(fastaFileName) + "taxonomy.temp";
172 string taxSummary = getRootName(fastaFileName) + "tax.summary";
174 int start = time(NULL);
175 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
178 openInputFile(fastaFileName, inFASTA);
179 numFastaSeqs=count(istreambuf_iterator<char>(inFASTA),istreambuf_iterator<char>(), '>');
182 lines.push_back(new linePair(0, numFastaSeqs));
184 driver(lines[0], newTaxonomyFile, tempTaxonomyFile);
187 vector<int> positions;
188 processIDS.resize(0);
191 openInputFile(fastaFileName, inFASTA);
194 while(!inFASTA.eof()){
195 input = getline(inFASTA);
196 if (input.length() != 0) {
197 if(input[0] == '>'){ int pos = inFASTA.tellg(); positions.push_back(pos - input.length() - 1); }
202 numFastaSeqs = positions.size();
204 int numSeqsPerProcessor = numFastaSeqs / processors;
206 for (int i = 0; i < processors; i++) {
207 int startPos = positions[ i * numSeqsPerProcessor ];
208 if(i == processors - 1){
209 numSeqsPerProcessor = numFastaSeqs - i * numSeqsPerProcessor;
211 lines.push_back(new linePair(startPos, numSeqsPerProcessor));
213 createProcesses(newTaxonomyFile, tempTaxonomyFile);
215 rename((newTaxonomyFile + toString(processIDS[0]) + ".temp").c_str(), newTaxonomyFile.c_str());
216 rename((tempTaxonomyFile + toString(processIDS[0]) + ".temp").c_str(), tempTaxonomyFile.c_str());
218 for(int i=1;i<processors;i++){
219 appendTaxFiles((newTaxonomyFile + toString(processIDS[i]) + ".temp"), newTaxonomyFile);
220 appendTaxFiles((tempTaxonomyFile + toString(processIDS[i]) + ".temp"), tempTaxonomyFile);
221 remove((newTaxonomyFile + toString(processIDS[i]) + ".temp").c_str());
222 remove((tempTaxonomyFile + toString(processIDS[i]) + ".temp").c_str());
228 openInputFile(fastaFileName, inFASTA);
229 numFastaSeqs=count(istreambuf_iterator<char>(inFASTA),istreambuf_iterator<char>(), '>');
232 lines.push_back(new linePair(0, numFastaSeqs));
234 driver(lines[0], newTaxonomyFile, tempTaxonomyFile);
238 //make taxonomy tree from new taxonomy file
240 openInputFile(tempTaxonomyFile, inTaxonomy);
242 string accession, taxaList;
243 PhyloTree taxaBrowser;
245 //read in users taxonomy file and add sequences to tree
246 while(!inTaxonomy.eof()){
247 inTaxonomy >> accession >> taxaList;
249 taxaBrowser.addSeqToTree(accession, taxaList);
254 remove(tempTaxonomyFile.c_str());
256 taxaBrowser.assignHeirarchyIDs(0);
259 openOutputFile(taxSummary, outTaxTree);
261 taxaBrowser.print(outTaxTree);
264 mothurOut("It took " + toString(time(NULL) - start) + " secs to classify " + toString(numFastaSeqs) + " sequences.");
270 catch(exception& e) {
271 errorOut(e, "ClassifySeqsCommand", "execute");
275 /**************************************************************************************************/
277 void ClassifySeqsCommand::createProcesses(string taxFileName, string tempTaxFile) {
279 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
281 // processIDS.resize(0);
283 //loop through and create all the processes you want
284 while (process != processors) {
288 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
291 driver(lines[process], taxFileName + toString(getpid()) + ".temp", tempTaxFile + toString(getpid()) + ".temp");
293 }else { mothurOut("unable to spawn the necessary processes."); mothurOutEndLine(); exit(0); }
296 //force parent to wait until all the processes are done
297 for (int i=0;i<processors;i++) {
298 int temp = processIDS[i];
303 catch(exception& e) {
304 errorOut(e, "ClassifySeqsCommand", "createProcesses");
308 /**************************************************************************************************/
310 void ClassifySeqsCommand::appendTaxFiles(string temp, string filename) {
315 openOutputFileAppend(filename, output);
316 openInputFile(temp, input);
318 while(char c = input.get()){
319 if(input.eof()) { break; }
320 else { output << c; }
326 catch(exception& e) {
327 errorOut(e, "ClassifySeqsCommand", "appendTaxFiles");
332 //**********************************************************************************************************************
334 int ClassifySeqsCommand::driver(linePair* line, string taxFName, string tempTFName){
337 openOutputFile(taxFName, outTax);
339 ofstream outTaxSimple;
340 openOutputFile(tempTFName, outTaxSimple);
343 openInputFile(fastaFileName, inFASTA);
345 inFASTA.seekg(line->start);
349 for(int i=0;i<line->numSeqs;i++){
351 Sequence* candidateSeq = new Sequence(inFASTA);
353 if (candidateSeq->getName() != "") {
354 taxonomy = classify->getTaxonomy(candidateSeq);
356 if (taxonomy != "bad seq") {
357 outTax << candidateSeq->getName() << '\t' << taxonomy << endl;
358 outTaxSimple << candidateSeq->getName() << '\t' << classify->getSimpleTax() << endl;
363 if((i+1) % 100 == 0){
364 mothurOut("Classifying sequence " + toString(i+1)); mothurOutEndLine();
370 outTaxSimple.close();
374 catch(exception& e) {
375 errorOut(e, "ClassifySeqsCommand", "driver");
380 /**************************************************************************************************/