]> git.donarmstrong.com Git - mothur.git/blob - bayesian.cpp
some changes while testing 1.9
[mothur.git] / bayesian.cpp
1 /*
2  *  bayesian.cpp
3  *  Mothur
4  *
5  *  Created by westcott on 11/3/09.
6  *  Copyright 2009 Schloss Lab. All rights reserved.
7  *
8  */
9
10 #include "bayesian.h"
11 #include "kmer.hpp"
12
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)  {
16         try {
17                                         
18                 numKmers = database->getMaxKmer() + 1;
19                 
20                 //initialze probabilities
21                 wordGenusProb.resize(numKmers);
22                 
23                 genusNodes = phyloTree->getGenusNodes(); 
24                 
25                 for (int j = 0; j < wordGenusProb.size(); j++) {        wordGenusProb[j].resize(genusNodes.size());             }
26                         
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());
31                 }
32
33                 
34                 /************calculate the probablity that each word will be in a specific taxonomy*************/
35                 ofstream out;
36                 string probFileName = tfile.substr(0,tfile.find_last_of(".")+1) + tempFile.substr(0,tempFile.find_last_of(".")+1) + char('0'+ kmerSize) + "mer.prob";
37                 ifstream probFileTest(probFileName.c_str());
38                 
39                 ofstream out2;
40                 string probFileName2 = tfile.substr(0,tfile.find_last_of(".")+1) + tempFile.substr(0,tempFile.find_last_of(".")+1) + char('0'+ kmerSize) + "mer.numNonZero";
41                 ifstream probFileTest2(probFileName2.c_str());
42                 
43                 int start = time(NULL);
44                 
45                 if(probFileTest && probFileTest2){      
46                         m->mothurOut("Reading template probabilities...     "); cout.flush();
47                         readProbFile(probFileTest, probFileTest2);      
48                 }else{
49                         m->mothurOut("Calculating template probabilities...     "); cout.flush();
50
51                         ofstream out;
52                         openOutputFile(probFileName, out);
53                         
54                         ofstream out2;
55                         openOutputFile(probFileName2, out2);
56                         
57                         //for each word
58                         for (int i = 0; i < numKmers; i++) {
59                                 if (m->control_pressed) { break; }
60                                 
61                                 out << i << '\t';
62                                 
63                                 vector<int> seqsWithWordi = database->getSequencesWithKmer(i);
64                                 
65                                 map<int, int> count;
66                                 for (int k = 0; k < genusNodes.size(); k++) {  count[genusNodes[k]] = 0;  }                     
67                                                 
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
72                                 }
73                                 
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);
76                                 
77                                 int numNotZero = 0;
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++;  }
82                                 }
83                                 out << endl;
84                                 out2 << probabilityInTemplate << '\t' << numNotZero << endl;
85                         }
86                         
87                         out.close();
88                         out2.close();
89                 }
90                 
91                 
92                 m->mothurOut("DONE."); m->mothurOutEndLine();
93                 m->mothurOut("It took " + toString(time(NULL) - start) + " seconds get probabilities. "); m->mothurOutEndLine();
94         }
95         catch(exception& e) {
96                 m->errorOut(e, "Bayesian", "Bayesian");
97                 exit(1);
98         }
99 }
100 /**************************************************************************************************/
101 string Bayesian::getTaxonomy(Sequence* seq) {
102         try {
103                 string tax = "";
104                 Kmer kmer(kmerSize);
105                 
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
110                 string queryKmerString = kmer.getKmerString(seq->getUnaligned()); 
111
112                 vector<int> queryKmers;
113                 for (int i = 0; i < queryKmerString.length(); i++) {
114                         if (queryKmerString[i] != '!') { //this kmer is in the query
115                                 queryKmers.push_back(i);
116  
117                         }
118                 }
119                 
120                 if (queryKmers.size() == 0) {  m->mothurOut(seq->getName() + "is bad."); m->mothurOutEndLine(); return "bad seq"; }
121                 
122                 int index = getMostProbableTaxonomy(queryKmers);
123
124                 
125                 if (m->control_pressed) { return tax; }
126                                         
127                 //bootstrap - to set confidenceScore
128                 int numToSelect = queryKmers.size() / 8;
129                 tax = bootstrapResults(queryKmers, index, numToSelect);
130                                                 
131                 return tax;     
132         }
133         catch(exception& e) {
134                 m->errorOut(e, "Bayesian", "getTaxonomy");
135                 exit(1);
136         }
137 }
138 /**************************************************************************************************/
139 string Bayesian::bootstrapResults(vector<int> kmers, int tax, int numToSelect) {
140         try {
141                 
142                 //taxConfidenceScore.clear(); //clear out previous seqs scores
143                                 
144                 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
145                                                                                 //map of classification to confidence for all areas seen
146                                                                            //ie. Bacteria;Alphaproteobacteria;Rhizobiales;Azorhizobium_et_rel.;Methylobacterium_et_rel.;Bosea;
147                                                                            //ie. Bacteria -> 100, Alphaproteobacteria -> 100, Rhizobiales -> 87, Azorhizobium_et_rel. -> 78, Methylobacterium_et_rel. -> 70, Bosea -> 50
148                 confidenceScores.resize(100);  //if you have more than 100 levels of classification...
149                 
150                 map<string, int>::iterator itBoot;
151                 map<string, int>::iterator itBoot2;
152                 map<int, int>::iterator itConvert;
153                 
154                 for (int i = 0; i < iters; i++) {
155                         if (m->control_pressed) { return "control"; }
156                         
157                         vector<int> temp;
158                                                 
159                         for (int j = 0; j < numToSelect; j++) {
160                                 int index = int(rand() % kmers.size());
161                                 
162                                 //add word to temp
163                                 temp.push_back(kmers[index]);
164                         }
165                         
166                         //get taxonomy
167                         int newTax = getMostProbableTaxonomy(temp);
168                         TaxNode taxonomy = phyloTree->get(newTax);
169                         
170                         //add to confidence results
171                         while (taxonomy.level != 0) { //while you are not at the root
172                                 
173                                 itBoot2 = confidenceScores[taxonomy.level].find(taxonomy.name); //is this a classification we already have a count on
174                                 
175                                 if (itBoot2 == confidenceScores[taxonomy.level].end()) { //not already in confidence scores
176                                         confidenceScores[taxonomy.level][taxonomy.name] = 1;
177                                 }else{
178                                         confidenceScores[taxonomy.level][taxonomy.name]++;
179                                 }
180                 
181                                 taxonomy = phyloTree->get(taxonomy.parent);
182                         }
183         
184                 }
185                 
186                 string confidenceTax = "";
187                 simpleTax = "";
188                 TaxNode seqTax = phyloTree->get(tax);
189                 
190                 while (seqTax.level != 0) { //while you are not at the root
191                                         
192                                 itBoot2 = confidenceScores[seqTax.level].find(seqTax.name); //is this a classification we already have a count on
193                                 
194                                 int confidence = 0;
195                                 if (itBoot2 != confidenceScores[seqTax.level].end()) { //not already in confidence scores
196                                         confidence = confidenceScores[seqTax.level][seqTax.name];
197                                 }
198                                 
199                                 if (confidence >= confidenceThreshold) {
200                                         confidenceTax = seqTax.name + "(" + toString(((confidence/(float)iters) * 100)) + ");" + confidenceTax;
201                                         simpleTax = seqTax.name + ";" + simpleTax;
202                                 }
203                                 
204                                 seqTax = phyloTree->get(seqTax.parent);
205                 }
206                 
207                 if (confidenceTax == "") { confidenceTax = "unclassified;"; simpleTax = "unclassified;"; }
208                 return confidenceTax;
209                 
210         }
211         catch(exception& e) {
212                 m->errorOut(e, "Bayesian", "bootstrapResults");
213                 exit(1);
214         }
215 }
216 /**************************************************************************************************/
217 int Bayesian::getMostProbableTaxonomy(vector<int> queryKmer) {
218         try {
219                 int indexofGenus = 0;
220                 
221                 double maxProbability = -1000000.0;
222                 //find taxonomy with highest probability that this sequence is from it
223                 for (int k = 0; k < genusNodes.size(); k++) {
224                         //for each taxonomy calc its probability
225                         double prob = 1.0;
226                         for (int i = 0; i < queryKmer.size(); i++) {
227                                 prob += wordGenusProb[queryKmer[i]][k];
228                         }
229                 
230                         //is this the taxonomy with the greatest probability?
231                         if (prob > maxProbability) { 
232                                 indexofGenus = genusNodes[k];
233                                 maxProbability = prob;
234                         }
235                 }
236
237                 return indexofGenus;
238         }
239         catch(exception& e) {
240                 m->errorOut(e, "Bayesian", "getMostProbableTaxonomy");
241                 exit(1);
242         }
243 }
244 /*************************************************************************************************
245 map<string, int> Bayesian::parseTaxMap(string newTax) {
246         try{
247         
248                 map<string, int> parsed;
249                 
250                 newTax = newTax.substr(0, newTax.length()-1);  //get rid of last ';'
251         
252                 //parse taxonomy
253                 string individual;
254                 while (newTax.find_first_of(';') != -1) {
255                         individual = newTax.substr(0,newTax.find_first_of(';'));
256                         newTax = newTax.substr(newTax.find_first_of(';')+1, newTax.length());
257                         parsed[individual] = 1;
258                 }
259                 
260                 //get last one
261                 parsed[newTax] = 1;
262
263                 return parsed;
264                 
265         }
266         catch(exception& e) {
267                 m->errorOut(e, "Bayesian", "parseTax");
268                 exit(1);
269         }
270 }
271 /**************************************************************************************************/
272 void Bayesian::readProbFile(ifstream& in, ifstream& inNum) {
273         try{
274                 
275                 int kmer, name, count;  count = 0;
276                 vector<int> num; num.resize(numKmers);
277                 float prob;
278                 vector<float> zeroCountProb; zeroCountProb.resize(numKmers);            
279                 
280                 while (inNum) {
281                         inNum >> zeroCountProb[count] >> num[count];  
282                         count++;
283                         gobble(inNum);
284                 }
285                 inNum.close();
286                 
287                 while(in) {
288                         in >> kmer;
289                         
290                         //set them all to zero value
291                         for (int i = 0; i < genusNodes.size(); i++) {
292                                 wordGenusProb[kmer][i] = log(zeroCountProb[kmer] / (float) (genusTotals[i]+1));
293                         }
294                         
295                         //get probs for nonzero values
296                         for (int i = 0; i < num[kmer]; i++) {
297                                 in >> name >> prob;
298                                 wordGenusProb[kmer][name] = prob;
299                         }
300                         
301                         gobble(in);
302                 }
303                 in.close();
304         }
305         catch(exception& e) {
306                 m->errorOut(e, "Bayesian", "readProbFile");
307                 exit(1);
308         }
309 }
310 /**************************************************************************************************/
311
312
313
314
315
316