5 * Created by westcott on 11/3/09.
6 * Copyright 2009 Schloss Lab. All rights reserved.
12 #include "rawtrainingdatamaker.h"
14 /**************************************************************************************************/
15 Bayesian::Bayesian(string tfile, string tempFile, string method, int ksize, int cutoff, int i) :
16 Classify(), kmerSize(ksize), confidenceThreshold(cutoff), iters(i) {
19 /************calculate the probablity that each word will be in a specific taxonomy*************/
20 string phyloTreeName = tfile.substr(0,tfile.find_last_of(".")+1) + "tree.train";
21 ifstream phyloTreeTest(phyloTreeName.c_str());
24 string probFileName = tfile.substr(0,tfile.find_last_of(".")+1) + tempFile.substr(0,tempFile.find_last_of(".")+1) + char('0'+ kmerSize) + "mer.prob";
25 ifstream probFileTest(probFileName.c_str());
28 string probFileName2 = tfile.substr(0,tfile.find_last_of(".")+1) + tempFile.substr(0,tempFile.find_last_of(".")+1) + char('0'+ kmerSize) + "mer.numNonZero";
29 ifstream probFileTest2(probFileName2.c_str());
31 int start = time(NULL);
33 if(probFileTest && probFileTest2 && phyloTreeTest){
34 m->mothurOut("Reading template taxonomy... "); cout.flush();
36 phyloTree = new PhyloTree(phyloTreeTest);
38 m->mothurOut("DONE."); m->mothurOutEndLine();
40 genusNodes = phyloTree->getGenusNodes();
41 genusTotals = phyloTree->getGenusTotals();
43 m->mothurOut("Reading template probabilities... "); cout.flush();
44 readProbFile(probFileTest, probFileTest2);
48 //create search database and names vector
49 generateDatabaseAndNames(tfile, tempFile, method, ksize, 0.0, 0.0, 0.0, 0.0);
51 genusNodes = phyloTree->getGenusNodes();
52 genusTotals = phyloTree->getGenusTotals();
54 m->mothurOut("Calculating template taxonomy tree... "); cout.flush();
56 phyloTree->printTreeNodes(phyloTreeName);
58 m->mothurOut("DONE."); m->mothurOutEndLine();
60 m->mothurOut("Calculating template probabilities... "); cout.flush();
62 numKmers = database->getMaxKmer() + 1;
64 //initialze probabilities
65 wordGenusProb.resize(numKmers);
67 for (int j = 0; j < wordGenusProb.size(); j++) { wordGenusProb[j].resize(genusNodes.size()); }
70 openOutputFile(probFileName, out);
72 out << numKmers << endl;
75 openOutputFile(probFileName2, out2);
78 for (int i = 0; i < numKmers; i++) {
79 if (m->control_pressed) { break; }
83 vector<int> seqsWithWordi = database->getSequencesWithKmer(i);
86 for (int k = 0; k < genusNodes.size(); k++) { count[genusNodes[k]] = 0; }
88 //for each sequence with that word
89 for (int j = 0; j < seqsWithWordi.size(); j++) {
90 int temp = phyloTree->getIndex(names[seqsWithWordi[j]]);
91 count[temp]++; //increment count of seq in this genus who have this word
94 //probabilityInTemplate = (# of seqs with that word in template + 0.05) / (total number of seqs in template + 1);
95 float probabilityInTemplate = (seqsWithWordi.size() + 0.50) / (float) (names.size() + 1);
98 for (int k = 0; k < genusNodes.size(); k++) {
99 //probabilityInThisTaxonomy = (# of seqs with that word in this taxonomy + probabilityInTemplate) / (total number of seqs in this taxonomy + 1);
100 wordGenusProb[i][k] = log((count[genusNodes[k]] + probabilityInTemplate) / (float) (genusTotals[k] + 1));
101 if (count[genusNodes[k]] != 0) { out << k << '\t' << wordGenusProb[i][k] << '\t'; numNotZero++; }
104 out2 << probabilityInTemplate << '\t' << numNotZero << endl;
110 //read in new phylotree with less info. - its faster
111 ifstream phyloTreeTest(phyloTreeName.c_str());
114 phyloTree = new PhyloTree(phyloTreeTest);
117 m->mothurOut("DONE."); m->mothurOutEndLine();
118 m->mothurOut("It took " + toString(time(NULL) - start) + " seconds get probabilities. "); m->mothurOutEndLine();
120 catch(exception& e) {
121 m->errorOut(e, "Bayesian", "Bayesian");
125 /**************************************************************************************************/
126 string Bayesian::getTaxonomy(Sequence* seq) {
131 //get words contained in query
132 //getKmerString returns a string where the index in the string is hte kmer number
133 //and the character at that index can be converted to be the number of times that kmer was seen
135 string queryKmerString = kmer.getKmerString(seq->getUnaligned());
137 vector<int> queryKmers;
138 for (int i = 0; i < queryKmerString.length(); i++) {
139 if (queryKmerString[i] != '!') { //this kmer is in the query
140 queryKmers.push_back(i);
144 if (queryKmers.size() == 0) { m->mothurOut(seq->getName() + "is bad."); m->mothurOutEndLine(); return "bad seq"; }
146 int index = getMostProbableTaxonomy(queryKmers);
148 if (m->control_pressed) { return tax; }
150 //bootstrap - to set confidenceScore
151 int numToSelect = queryKmers.size() / 8;
152 tax = bootstrapResults(queryKmers, index, numToSelect);
156 catch(exception& e) {
157 m->errorOut(e, "Bayesian", "getTaxonomy");
161 /**************************************************************************************************/
162 string Bayesian::bootstrapResults(vector<int> kmers, int tax, int numToSelect) {
165 //taxConfidenceScore.clear(); //clear out previous seqs scores
167 vector< map<string, int> > confidenceScores; //you need the added vector level of confusion to account for the level that name is seen since they can be the same
168 //map of classification to confidence for all areas seen
169 //ie. Bacteria;Alphaproteobacteria;Rhizobiales;Azorhizobium_et_rel.;Methylobacterium_et_rel.;Bosea;
170 //ie. Bacteria -> 100, Alphaproteobacteria -> 100, Rhizobiales -> 87, Azorhizobium_et_rel. -> 78, Methylobacterium_et_rel. -> 70, Bosea -> 50
171 confidenceScores.resize(100); //if you have more than 100 levels of classification...
173 map<string, int>::iterator itBoot;
174 map<string, int>::iterator itBoot2;
175 map<int, int>::iterator itConvert;
177 for (int i = 0; i < iters; i++) {
178 if (m->control_pressed) { return "control"; }
182 for (int j = 0; j < numToSelect; j++) {
183 int index = int(rand() % kmers.size());
186 temp.push_back(kmers[index]);
190 int newTax = getMostProbableTaxonomy(temp);
191 TaxNode taxonomy = phyloTree->get(newTax);
193 //add to confidence results
194 while (taxonomy.level != 0) { //while you are not at the root
196 itBoot2 = confidenceScores[taxonomy.level].find(taxonomy.name); //is this a classification we already have a count on
198 if (itBoot2 == confidenceScores[taxonomy.level].end()) { //not already in confidence scores
199 confidenceScores[taxonomy.level][taxonomy.name] = 1;
201 confidenceScores[taxonomy.level][taxonomy.name]++;
204 taxonomy = phyloTree->get(taxonomy.parent);
209 string confidenceTax = "";
211 TaxNode seqTax = phyloTree->get(tax);
213 while (seqTax.level != 0) { //while you are not at the root
215 itBoot2 = confidenceScores[seqTax.level].find(seqTax.name); //is this a classification we already have a count on
218 if (itBoot2 != confidenceScores[seqTax.level].end()) { //not already in confidence scores
219 confidence = confidenceScores[seqTax.level][seqTax.name];
222 if (confidence >= confidenceThreshold) {
223 confidenceTax = seqTax.name + "(" + toString(((confidence/(float)iters) * 100)) + ");" + confidenceTax;
224 simpleTax = seqTax.name + ";" + simpleTax;
227 seqTax = phyloTree->get(seqTax.parent);
230 if (confidenceTax == "") { confidenceTax = "unclassified;"; simpleTax = "unclassified;"; }
231 return confidenceTax;
234 catch(exception& e) {
235 m->errorOut(e, "Bayesian", "bootstrapResults");
239 /**************************************************************************************************/
240 int Bayesian::getMostProbableTaxonomy(vector<int> queryKmer) {
242 int indexofGenus = 0;
244 double maxProbability = -1000000.0;
245 //find taxonomy with highest probability that this sequence is from it
246 for (int k = 0; k < genusNodes.size(); k++) {
247 //for each taxonomy calc its probability
249 for (int i = 0; i < queryKmer.size(); i++) {
250 prob += wordGenusProb[queryKmer[i]][k];
253 //is this the taxonomy with the greatest probability?
254 if (prob > maxProbability) {
255 indexofGenus = genusNodes[k];
256 maxProbability = prob;
262 catch(exception& e) {
263 m->errorOut(e, "Bayesian", "getMostProbableTaxonomy");
267 /*************************************************************************************************
268 map<string, int> Bayesian::parseTaxMap(string newTax) {
271 map<string, int> parsed;
273 newTax = newTax.substr(0, newTax.length()-1); //get rid of last ';'
277 while (newTax.find_first_of(';') != -1) {
278 individual = newTax.substr(0,newTax.find_first_of(';'));
279 newTax = newTax.substr(newTax.find_first_of(';')+1, newTax.length());
280 parsed[individual] = 1;
289 catch(exception& e) {
290 m->errorOut(e, "Bayesian", "parseTax");
294 /**************************************************************************************************/
295 void Bayesian::readProbFile(ifstream& in, ifstream& inNum) {
298 in >> numKmers; gobble(in);
300 //initialze probabilities
301 wordGenusProb.resize(numKmers);
303 for (int j = 0; j < wordGenusProb.size(); j++) { wordGenusProb[j].resize(genusNodes.size()); }
305 int kmer, name, count; count = 0;
306 vector<int> num; num.resize(numKmers);
308 vector<float> zeroCountProb; zeroCountProb.resize(numKmers);
311 inNum >> zeroCountProb[count] >> num[count];
320 //set them all to zero value
321 for (int i = 0; i < genusNodes.size(); i++) {
322 wordGenusProb[kmer][i] = log(zeroCountProb[kmer] / (float) (genusTotals[i]+1));
325 //get probs for nonzero values
326 for (int i = 0; i < num[kmer]; i++) {
328 wordGenusProb[kmer][name] = prob;
335 catch(exception& e) {
336 m->errorOut(e, "Bayesian", "readProbFile");
340 /**************************************************************************************************/