5 * Created by westcott on 11/3/09.
6 * Copyright 2009 Schloss Lab. All rights reserved.
13 /**************************************************************************************************/
14 Bayesian::Bayesian(string tfile, string tempFile, string method, int ksize, int cutoff, int i) :
15 Classify(tfile, tempFile, method, ksize, 0.0, 0.0, 0.0, 0.0), kmerSize(ksize), confidenceThreshold(cutoff), iters(i) {
18 numKmers = database->getMaxKmer() + 1;
20 //initialze probabilities
21 wordGenusProb.resize(numKmers);
23 genusNodes = phyloTree->getGenusNodes();
25 for (int j = 0; j < wordGenusProb.size(); j++) { wordGenusProb[j].resize(genusNodes.size()); }
27 //reset counts because we are on a new word
28 for (int j = 0; j < genusNodes.size(); j++) {
29 TaxNode temp = phyloTree->get(genusNodes[j]);
30 genusTotals.push_back(temp.accessions.size());
34 /************calculate the probablity that each word will be in a specific taxonomy*************/
36 string probFileName = tempFile.substr(0,tempFile.find_last_of(".")+1) + char('0'+ kmerSize) + "mer.prob";
37 ifstream probFileTest(probFileName.c_str());
40 string probFileName2 = tempFile.substr(0,tempFile.find_last_of(".")+1) + char('0'+ kmerSize) + "mer.numNonZero";
41 ifstream probFileTest2(probFileName2.c_str());
43 int start = time(NULL);
45 if(probFileTest && probFileTest2){
46 m->mothurOut("Reading template probabilities... "); cout.flush();
47 readProbFile(probFileTest, probFileTest2);
49 m->mothurOut("Calculating template probabilities... "); cout.flush();
52 openOutputFile(probFileName, out);
55 openOutputFile(probFileName2, out2);
58 for (int i = 0; i < numKmers; i++) {
59 if (m->control_pressed) { break; }
63 vector<int> seqsWithWordi = database->getSequencesWithKmer(i);
66 for (int k = 0; k < genusNodes.size(); k++) { count[genusNodes[k]] = 0; }
68 //for each sequence with that word
69 for (int j = 0; j < seqsWithWordi.size(); j++) {
70 int temp = phyloTree->getIndex(names[seqsWithWordi[j]]);
71 count[temp]++; //increment count of seq in this genus who have this word
74 //probabilityInTemplate = (# of seqs with that word in template + 0.05) / (total number of seqs in template + 1);
75 float probabilityInTemplate = (seqsWithWordi.size() + 0.50) / (float) (names.size() + 1);
78 for (int k = 0; k < genusNodes.size(); k++) {
79 //probabilityInThisTaxonomy = (# of seqs with that word in this taxonomy + probabilityInTemplate) / (total number of seqs in this taxonomy + 1);
80 wordGenusProb[i][k] = log((count[genusNodes[k]] + probabilityInTemplate) / (float) (genusTotals[k] + 1));
81 if (count[genusNodes[k]] != 0) { out << k << '\t' << wordGenusProb[i][k] << '\t'; numNotZero++; }
84 out2 << probabilityInTemplate << '\t' << numNotZero << endl;
92 m->mothurOut("DONE."); m->mothurOutEndLine();
93 m->mothurOut("It took " + toString(time(NULL) - start) + " seconds get probabilities. "); m->mothurOutEndLine();
96 m->errorOut(e, "Bayesian", "Bayesian");
100 /**************************************************************************************************/
101 string Bayesian::getTaxonomy(Sequence* seq) {
106 //get words contained in query
107 //getKmerString returns a string where the index in the string is hte kmer number
108 //and the character at that index can be converted to be the number of times that kmer was seen
109 string queryKmerString = kmer.getKmerString(seq->getUnaligned());
110 vector<int> queryKmers;
111 for (int i = 0; i < queryKmerString.length(); i++) {
112 if (queryKmerString[i] != '!') { //this kmer is in the query
113 queryKmers.push_back(i);
117 int index = getMostProbableTaxonomy(queryKmers);
119 if (m->control_pressed) { return tax; }
121 //bootstrap - to set confidenceScore
122 int numToSelect = queryKmers.size() / 8;
123 tax = bootstrapResults(queryKmers, index, numToSelect);
127 catch(exception& e) {
128 m->errorOut(e, "Bayesian", "getTaxonomy");
132 /**************************************************************************************************/
133 string Bayesian::bootstrapResults(vector<int> kmers, int tax, int numToSelect) {
136 //taxConfidenceScore.clear(); //clear out previous seqs scores
138 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
139 //map of classification to confidence for all areas seen
140 //ie. Bacteria;Alphaproteobacteria;Rhizobiales;Azorhizobium_et_rel.;Methylobacterium_et_rel.;Bosea;
141 //ie. Bacteria -> 100, Alphaproteobacteria -> 100, Rhizobiales -> 87, Azorhizobium_et_rel. -> 78, Methylobacterium_et_rel. -> 70, Bosea -> 50
142 confidenceScores.resize(100); //if you have more than 100 levels of classification...
144 map<string, int>::iterator itBoot;
145 map<string, int>::iterator itBoot2;
146 map<int, int>::iterator itConvert;
148 for (int i = 0; i < iters; i++) {
149 if (m->control_pressed) { return "control"; }
153 for (int j = 0; j < numToSelect; j++) {
154 int index = int(rand() % kmers.size());
157 temp.push_back(kmers[index]);
161 int newTax = getMostProbableTaxonomy(temp);
162 TaxNode taxonomy = phyloTree->get(newTax);
164 //add to confidence results
165 while (taxonomy.level != 0) { //while you are not at the root
167 itBoot2 = confidenceScores[taxonomy.level].find(taxonomy.name); //is this a classification we already have a count on
169 if (itBoot2 == confidenceScores[taxonomy.level].end()) { //not already in confidence scores
170 confidenceScores[taxonomy.level][taxonomy.name] = 1;
172 confidenceScores[taxonomy.level][taxonomy.name]++;
175 taxonomy = phyloTree->get(taxonomy.parent);
179 string confidenceTax = "";
181 TaxNode seqTax = phyloTree->get(tax);
183 while (seqTax.level != 0) { //while you are not at the root
185 itBoot2 = confidenceScores[seqTax.level].find(seqTax.name); //is this a classification we already have a count on
188 if (itBoot2 != confidenceScores[seqTax.level].end()) { //not already in confidence scores
189 confidence = confidenceScores[seqTax.level][seqTax.name];
192 if (confidence >= confidenceThreshold) {
193 confidenceTax = seqTax.name + "(" + toString(((confidence/(float)iters) * 100)) + ");" + confidenceTax;
194 simpleTax = seqTax.name + ";" + simpleTax;
197 seqTax = phyloTree->get(seqTax.parent);
200 return confidenceTax;
203 catch(exception& e) {
204 m->errorOut(e, "Bayesian", "bootstrapResults");
208 /**************************************************************************************************/
209 int Bayesian::getMostProbableTaxonomy(vector<int> queryKmer) {
213 double maxProbability = -1000000.0;
214 //find taxonomy with highest probability that this sequence is from it
215 for (int k = 0; k < genusNodes.size(); k++) {
217 //for each taxonomy calc its probability
219 for (int i = 0; i < queryKmer.size(); i++) {
220 prob += wordGenusProb[queryKmer[i]][k];
223 //is this the taxonomy with the greatest probability?
224 if (prob > maxProbability) {
225 indexofGenus = genusNodes[k];
226 maxProbability = prob;
232 catch(exception& e) {
233 m->errorOut(e, "Bayesian", "getMostProbableTaxonomy");
237 /*************************************************************************************************
238 map<string, int> Bayesian::parseTaxMap(string newTax) {
241 map<string, int> parsed;
243 newTax = newTax.substr(0, newTax.length()-1); //get rid of last ';'
247 while (newTax.find_first_of(';') != -1) {
248 individual = newTax.substr(0,newTax.find_first_of(';'));
249 newTax = newTax.substr(newTax.find_first_of(';')+1, newTax.length());
250 parsed[individual] = 1;
259 catch(exception& e) {
260 m->errorOut(e, "Bayesian", "parseTax");
264 /**************************************************************************************************/
265 void Bayesian::readProbFile(ifstream& in, ifstream& inNum) {
268 int kmer, name, count; count = 0;
269 vector<int> num; num.resize(numKmers);
271 vector<float> zeroCountProb; zeroCountProb.resize(numKmers);
274 inNum >> zeroCountProb[count] >> num[count];
283 //set them all to zero value
284 for (int i = 0; i < genusNodes.size(); i++) {
285 wordGenusProb[kmer][i] = log(zeroCountProb[kmer] / (float) (genusTotals[i]+1));
288 //get probs for nonzero values
289 for (int i = 0; i < num[kmer]; i++) {
291 wordGenusProb[kmer][name] = prob;
298 catch(exception& e) {
299 m->errorOut(e, "Bayesian", "readProbFile");
303 /**************************************************************************************************/