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","name","search","ksize","method","processors","taxonomy","match","mismatch","gapopen","gapextend","numwanted","cutoff","probs","iters"};
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", false);
51 if (fastaFileName == "not found") { mothurOut("fasta is a required parameter for the classify.seqs command."); mothurOutEndLine(); abort = true; }
53 splitAtDash(fastaFileName, fastaFileNames);
55 //go through files and make sure they are good, if not, then disregard them
56 for (int i = 0; i < fastaFileNames.size(); i++) {
59 ableToOpen = openInputFile(fastaFileNames[i], in);
60 if (ableToOpen == 1) {
61 mothurOut(fastaFileNames[i] + " will be disregarded."); mothurOutEndLine();
62 //erase from file list
63 fastaFileNames.erase(fastaFileNames.begin()+i);
69 //make sure there is at least one valid file left
70 if (fastaFileNames.size() == 0) { mothurOut("no valid files."); mothurOutEndLine(); abort = true; }
74 taxonomyFileName = validParameter.validFile(parameters, "taxonomy", true);
75 if (taxonomyFileName == "not found") {
76 mothurOut("taxonomy is a required parameter for the classify.seqs command.");
80 else if (taxonomyFileName == "not open") { abort = true; }
83 namefile = validParameter.validFile(parameters, "name", false);
84 if (namefile == "not found") { namefile = ""; }
86 splitAtDash(namefile, namefileNames);
88 //go through files and make sure they are good, if not, then disregard them
89 for (int i = 0; i < namefileNames.size(); i++) {
92 ableToOpen = openInputFile(namefileNames[i], in);
93 if (ableToOpen == 1) { mothurOut("Unable to match name file with fasta file."); mothurOutEndLine(); abort = true; }
99 if (namefileNames.size() != fastaFileNames.size()) { abort = true; mothurOut("If you provide a name file, you must have one for each fasta file."); mothurOutEndLine(); }
102 //check for optional parameter and set defaults
103 // ...at some point should added some additional type checking...
105 temp = validParameter.validFile(parameters, "ksize", false); if (temp == "not found"){ temp = "8"; }
106 convert(temp, kmerSize);
108 temp = validParameter.validFile(parameters, "processors", false); if (temp == "not found"){ temp = "1"; }
109 convert(temp, processors);
111 search = validParameter.validFile(parameters, "search", false); if (search == "not found"){ search = "kmer"; }
113 method = validParameter.validFile(parameters, "method", false); if (method == "not found"){ method = "bayesian"; }
115 temp = validParameter.validFile(parameters, "match", false); if (temp == "not found"){ temp = "1.0"; }
116 convert(temp, match);
118 temp = validParameter.validFile(parameters, "mismatch", false); if (temp == "not found"){ temp = "-1.0"; }
119 convert(temp, misMatch);
121 temp = validParameter.validFile(parameters, "gapopen", false); if (temp == "not found"){ temp = "-2.0"; }
122 convert(temp, gapOpen);
124 temp = validParameter.validFile(parameters, "gapextend", false); if (temp == "not found"){ temp = "-1.0"; }
125 convert(temp, gapExtend);
127 temp = validParameter.validFile(parameters, "numwanted", false); if (temp == "not found"){ temp = "10"; }
128 convert(temp, numWanted);
130 temp = validParameter.validFile(parameters, "cutoff", false); if (temp == "not found"){ temp = "0"; }
131 convert(temp, cutoff);
133 temp = validParameter.validFile(parameters, "probs", false); if (temp == "not found"){ temp = "true"; }
134 probs = isTrue(temp);
136 temp = validParameter.validFile(parameters, "iters", false); if (temp == "not found") { temp = "100"; }
137 convert(temp, iters);
141 if ((method == "bayesian") && (search != "kmer")) {
142 mothurOut("The bayesian method requires the kmer search." + search + "will be disregarded." ); mothurOutEndLine();
148 catch(exception& e) {
149 errorOut(e, "ClassifySeqsCommand", "ClassifySeqsCommand");
154 //**********************************************************************************************************************
156 ClassifySeqsCommand::~ClassifySeqsCommand(){
158 if (abort == false) {
159 for (int i = 0; i < lines.size(); i++) { delete lines[i]; } lines.clear();
163 //**********************************************************************************************************************
165 void ClassifySeqsCommand::help(){
167 mothurOut("The classify.seqs command reads a fasta file containing sequences and creates a .taxonomy file and a .tax.summary file.\n");
168 mothurOut("The classify.seqs command parameters are template, fasta, search, ksize, method, taxonomy, processors, match, mismatch, gapopen, gapextend, numwanted and probs.\n");
169 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");
170 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");
171 mothurOut("The method parameter allows you to specify classification method to use. Your options are: bayesian and knn. The default is bayesian.\n");
172 mothurOut("The ksize parameter allows you to specify the kmer size for finding most similar template to candidate. The default is 8.\n");
173 mothurOut("The processors parameter allows you to specify the number of processors to use. The default is 1.\n");
174 mothurOut("The match parameter allows you to specify the bonus for having the same base. The default is 1.0.\n");
175 mothurOut("The mistmatch parameter allows you to specify the penalty for having different bases. The default is -1.0.\n");
176 mothurOut("The gapopen parameter allows you to specify the penalty for opening a gap in an alignment. The default is -2.0.\n");
177 mothurOut("The gapextend parameter allows you to specify the penalty for extending a gap in an alignment. The default is -1.0.\n");
178 mothurOut("The numwanted parameter allows you to specify the number of sequence matches you want with the knn method. The default is 10.\n");
179 mothurOut("The cutoff parameter allows you to specify a bootstrap confidence threshold for your taxonomy. The default is 0.\n");
180 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");
181 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");
182 mothurOut("The classify.seqs command should be in the following format: \n");
183 mothurOut("classify.seqs(template=yourTemplateFile, fasta=yourFastaFile, method=yourClassificationMethod, search=yourSearchmethod, ksize=yourKmerSize, taxonomy=yourTaxonomyFile, processors=yourProcessors) \n");
184 mothurOut("Example classify.seqs(fasta=amazon.fasta, template=core.filtered, method=knn, search=gotoh, ksize=8, processors=2)\n");
185 mothurOut("The .taxonomy file consists of 2 columns: 1 = your sequence name, 2 = the taxonomy for your sequence. \n");
186 mothurOut("The .tax.summary is a summary of the different taxonomies represented in your fasta file. \n");
187 mothurOut("Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFastaFile).\n\n");
189 catch(exception& e) {
190 errorOut(e, "ClassifySeqsCommand", "help");
196 //**********************************************************************************************************************
198 int ClassifySeqsCommand::execute(){
200 if (abort == true) { return 0; }
202 if(method == "bayesian") { classify = new Bayesian(taxonomyFileName, templateFileName, search, kmerSize, cutoff, iters); }
203 else if(method == "knn") { classify = new Knn(taxonomyFileName, templateFileName, search, kmerSize, gapOpen, gapExtend, match, misMatch, numWanted); }
205 mothurOut(search + " is not a valid method option. I will run the command using bayesian.");
207 classify = new Bayesian(taxonomyFileName, templateFileName, search, kmerSize, cutoff, iters);
211 for (int s = 0; s < fastaFileNames.size(); s++) {
215 nameMap.clear(); //remove old names
218 openInputFile(namefileNames[s], inNames);
220 string firstCol, secondCol;
221 while(!inNames.eof()) {
222 inNames >> firstCol >> secondCol; gobble(inNames);
223 nameMap[firstCol] = getNumNames(secondCol); //ex. seq1 seq1,seq3,seq5 -> seq1 = 3.
228 mothurOut("Classifying sequences from " + fastaFileNames[s] + " ..." ); mothurOutEndLine();
229 string newTaxonomyFile = getRootName(fastaFileNames[s]) + getRootName(taxonomyFileName) + "taxonomy";
230 string tempTaxonomyFile = getRootName(fastaFileNames[s]) + "taxonomy.temp";
231 string taxSummary = getRootName(fastaFileNames[s]) + getRootName(taxonomyFileName) + "tax.summary";
233 int start = time(NULL);
234 int numFastaSeqs = 0;
235 for (int i = 0; i < lines.size(); i++) { delete lines[i]; } lines.clear();
237 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
240 openInputFile(fastaFileNames[s], inFASTA);
241 numFastaSeqs=count(istreambuf_iterator<char>(inFASTA),istreambuf_iterator<char>(), '>');
244 lines.push_back(new linePair(0, numFastaSeqs));
246 driver(lines[0], newTaxonomyFile, tempTaxonomyFile, fastaFileNames[s]);
249 vector<int> positions;
250 processIDS.resize(0);
253 openInputFile(fastaFileNames[s], inFASTA);
256 while(!inFASTA.eof()){
257 input = getline(inFASTA);
258 if (input.length() != 0) {
259 if(input[0] == '>'){ int pos = inFASTA.tellg(); positions.push_back(pos - input.length() - 1); }
264 numFastaSeqs = positions.size();
266 int numSeqsPerProcessor = numFastaSeqs / processors;
268 for (int i = 0; i < processors; i++) {
269 int startPos = positions[ i * numSeqsPerProcessor ];
270 if(i == processors - 1){
271 numSeqsPerProcessor = numFastaSeqs - i * numSeqsPerProcessor;
273 lines.push_back(new linePair(startPos, numSeqsPerProcessor));
275 createProcesses(newTaxonomyFile, tempTaxonomyFile, fastaFileNames[s]);
277 rename((newTaxonomyFile + toString(processIDS[0]) + ".temp").c_str(), newTaxonomyFile.c_str());
278 rename((tempTaxonomyFile + toString(processIDS[0]) + ".temp").c_str(), tempTaxonomyFile.c_str());
280 for(int i=1;i<processors;i++){
281 appendTaxFiles((newTaxonomyFile + toString(processIDS[i]) + ".temp"), newTaxonomyFile);
282 appendTaxFiles((tempTaxonomyFile + toString(processIDS[i]) + ".temp"), tempTaxonomyFile);
283 remove((newTaxonomyFile + toString(processIDS[i]) + ".temp").c_str());
284 remove((tempTaxonomyFile + toString(processIDS[i]) + ".temp").c_str());
290 openInputFile(fastaFileNames[s], inFASTA);
291 numFastaSeqs=count(istreambuf_iterator<char>(inFASTA),istreambuf_iterator<char>(), '>');
294 lines.push_back(new linePair(0, numFastaSeqs));
296 driver(lines[0], newTaxonomyFile, tempTaxonomyFile, fastaFileNames[s]);
298 //make taxonomy tree from new taxonomy file
299 PhyloTree taxaBrowser;
302 openInputFile(tempTaxonomyFile, in);
304 //read in users taxonomy file and add sequences to tree
307 in >> name >> taxon; gobble(in);
309 if (namefile != "") {
310 itNames = nameMap.find(name);
312 if (itNames == nameMap.end()) {
313 mothurOut(name + " is not in your name file please correct."); mothurOutEndLine(); exit(1);
315 for (int i = 0; i < itNames->second; i++) {
316 taxaBrowser.addSeqToTree(name+toString(i), taxon); //add it as many times as there are identical seqs
319 }else { taxaBrowser.addSeqToTree(name, taxon); } //add it once
323 taxaBrowser.assignHeirarchyIDs(0);
325 taxaBrowser.binUnclassified();
327 remove(tempTaxonomyFile.c_str());
331 openOutputFile(taxSummary, outTaxTree);
332 taxaBrowser.print(outTaxTree);
335 //output taxonomy with the unclassified bins added
337 openInputFile(newTaxonomyFile, inTax);
340 string unclass = newTaxonomyFile + ".unclass.temp";
341 openOutputFile(unclass, outTax);
343 //get maxLevel from phylotree so you know how many 'unclassified's to add
344 int maxLevel = taxaBrowser.getMaxLevel();
346 //read taxfile - this reading and rewriting is done to preserve the confidence sscores.
347 while (!inTax.eof()) {
348 inTax >> name >> taxon; gobble(inTax);
350 string newTax = addUnclassifieds(taxon, maxLevel);
352 outTax << name << '\t' << newTax << endl;
357 remove(newTaxonomyFile.c_str());
358 rename(unclass.c_str(), newTaxonomyFile.c_str());
361 mothurOut("It took " + toString(time(NULL) - start) + " secs to classify " + toString(numFastaSeqs) + " sequences."); mothurOutEndLine(); mothurOutEndLine();
367 catch(exception& e) {
368 errorOut(e, "ClassifySeqsCommand", "execute");
373 /**************************************************************************************************/
374 string ClassifySeqsCommand::addUnclassifieds(string tax, int maxlevel) {
376 string newTax, taxon;
379 //keep what you have counting the levels
380 while (tax.find_first_of(';') != -1) {
382 taxon = tax.substr(0,tax.find_first_of(';'));
383 tax = tax.substr(tax.find_first_of(';')+1, tax.length());
388 //add "unclassified" until you reach maxLevel
389 while (level < maxlevel) {
390 newTax += "unclassified;";
396 catch(exception& e) {
397 errorOut(e, "ClassifySeqsCommand", "addUnclassifieds");
402 /**************************************************************************************************/
404 void ClassifySeqsCommand::createProcesses(string taxFileName, string tempTaxFile, string filename) {
406 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
408 // processIDS.resize(0);
410 //loop through and create all the processes you want
411 while (process != processors) {
415 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
418 driver(lines[process], taxFileName + toString(getpid()) + ".temp", tempTaxFile + toString(getpid()) + ".temp", filename);
420 }else { mothurOut("unable to spawn the necessary processes."); mothurOutEndLine(); exit(0); }
423 //force parent to wait until all the processes are done
424 for (int i=0;i<processors;i++) {
425 int temp = processIDS[i];
430 catch(exception& e) {
431 errorOut(e, "ClassifySeqsCommand", "createProcesses");
435 /**************************************************************************************************/
437 void ClassifySeqsCommand::appendTaxFiles(string temp, string filename) {
442 openOutputFileAppend(filename, output);
443 openInputFile(temp, input);
445 while(char c = input.get()){
446 if(input.eof()) { break; }
447 else { output << c; }
453 catch(exception& e) {
454 errorOut(e, "ClassifySeqsCommand", "appendTaxFiles");
459 //**********************************************************************************************************************
461 int ClassifySeqsCommand::driver(linePair* line, string taxFName, string tempTFName, string filename){
464 openOutputFile(taxFName, outTax);
466 ofstream outTaxSimple;
467 openOutputFile(tempTFName, outTaxSimple);
470 openInputFile(filename, inFASTA);
472 inFASTA.seekg(line->start);
476 for(int i=0;i<line->numSeqs;i++){
478 Sequence* candidateSeq = new Sequence(inFASTA);
480 if (candidateSeq->getName() != "") {
481 taxonomy = classify->getTaxonomy(candidateSeq);
483 if (taxonomy != "bad seq") {
484 //output confidence scores or not
486 outTax << candidateSeq->getName() << '\t' << taxonomy << endl;
488 outTax << candidateSeq->getName() << '\t' << classify->getSimpleTax() << endl;
491 outTaxSimple << candidateSeq->getName() << '\t' << classify->getSimpleTax() << endl;
496 if((i+1) % 100 == 0){
497 mothurOut("Classifying sequence " + toString(i+1)); mothurOutEndLine();
503 outTaxSimple.close();
507 catch(exception& e) {
508 errorOut(e, "ClassifySeqsCommand", "driver");
513 /**************************************************************************************************/