]> git.donarmstrong.com Git - mothur.git/blob - bayesian.cpp
1.12.1
[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 #include "phylosummary.h"
13
14 /**************************************************************************************************/
15 Bayesian::Bayesian(string tfile, string tempFile, string method, int ksize, int cutoff, int i) : 
16 Classify(), kmerSize(ksize), confidenceThreshold(cutoff), iters(i)  {
17         try {
18                                         
19                 /************calculate the probablity that each word will be in a specific taxonomy*************/
20                 string tfileroot = tfile.substr(0,tfile.find_last_of(".")+1);
21                 string tempfileroot = getRootName(getSimpleName(tempFile));
22                 string phyloTreeName = tfileroot + "tree.train";
23                 string probFileName = tfileroot + tempfileroot + char('0'+ kmerSize) + "mer.prob";
24                 string probFileName2 = tfileroot + tempfileroot + char('0'+ kmerSize) + "mer.numNonZero";
25                 
26                 ofstream out;
27                 ofstream out2;
28                 
29                 ifstream phyloTreeTest(phyloTreeName.c_str());
30                 ifstream probFileTest2(probFileName2.c_str());
31                 ifstream probFileTest(probFileName.c_str());
32                 
33                 int start = time(NULL);
34                 
35                 if(probFileTest && probFileTest2 && phyloTreeTest){     
36                         m->mothurOut("Reading template taxonomy...     "); cout.flush();
37                         
38                         phyloTree = new PhyloTree(phyloTreeTest, phyloTreeName);
39                         
40                         m->mothurOut("DONE."); m->mothurOutEndLine();
41                         
42                         genusNodes = phyloTree->getGenusNodes(); 
43                         genusTotals = phyloTree->getGenusTotals();
44                 
45                         m->mothurOut("Reading template probabilities...     "); cout.flush();
46                         readProbFile(probFileTest, probFileTest2, probFileName, probFileName2); 
47                         
48                 }else{
49                 
50                         //create search database and names vector
51                         generateDatabaseAndNames(tfile, tempFile, method, ksize, 0.0, 0.0, 0.0, 0.0);
52                         
53                         //prevents errors caused by creating shortcut files if you had an error in the sanity check.
54                         if (m->control_pressed) {  remove(phyloTreeName.c_str());  remove(probFileName.c_str()); remove(probFileName2.c_str()); }
55                         else{ 
56                                 genusNodes = phyloTree->getGenusNodes(); 
57                                 genusTotals = phyloTree->getGenusTotals();
58                                 
59                                 m->mothurOut("Calculating template taxonomy tree...     "); cout.flush();
60                                 
61                                 phyloTree->printTreeNodes(phyloTreeName);
62                                                         
63                                 m->mothurOut("DONE."); m->mothurOutEndLine();
64                                 
65                                 m->mothurOut("Calculating template probabilities...     "); cout.flush();
66                                 
67                                 numKmers = database->getMaxKmer() + 1;
68                         
69                                 //initialze probabilities
70                                 wordGenusProb.resize(numKmers);
71                         
72                                 for (int j = 0; j < wordGenusProb.size(); j++) {        wordGenusProb[j].resize(genusNodes.size());             }
73                                 
74                                 ofstream out;
75                                 ofstream out2;
76                                 
77                                 #ifdef USE_MPI
78                                         int pid;
79                                         MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
80
81                                         if (pid == 0) {  
82                                 #endif
83
84                                 
85                                 openOutputFile(probFileName, out);
86                                 
87                                 out << numKmers << endl;
88                                 
89                                 openOutputFile(probFileName2, out2);
90                                 
91                                 #ifdef USE_MPI
92                                         }
93                                 #endif
94
95                                 
96                                 //for each word
97                                 for (int i = 0; i < numKmers; i++) {
98                                         if (m->control_pressed) {  break; }
99                                         
100                                         #ifdef USE_MPI
101                                                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
102
103                                                 if (pid == 0) {  
104                                         #endif
105
106                                         out << i << '\t';
107                                         
108                                         #ifdef USE_MPI
109                                                 }
110                                         #endif
111                                         
112                                         vector<int> seqsWithWordi = database->getSequencesWithKmer(i);
113                                         
114                                         map<int, int> count;
115                                         for (int k = 0; k < genusNodes.size(); k++) {  count[genusNodes[k]] = 0;  }                     
116                                                         
117                                         //for each sequence with that word
118                                         for (int j = 0; j < seqsWithWordi.size(); j++) {
119                                                 int temp = phyloTree->getIndex(names[seqsWithWordi[j]]);
120                                                 count[temp]++;  //increment count of seq in this genus who have this word
121                                         }
122                                         
123                                         //probabilityInTemplate = (# of seqs with that word in template + 0.05) / (total number of seqs in template + 1);
124                                         float probabilityInTemplate = (seqsWithWordi.size() + 0.50) / (float) (names.size() + 1);
125                                         
126                                         int numNotZero = 0;
127                                         for (int k = 0; k < genusNodes.size(); k++) {
128                                                 //probabilityInThisTaxonomy = (# of seqs with that word in this taxonomy + probabilityInTemplate) / (total number of seqs in this taxonomy + 1);
129                                                 wordGenusProb[i][k] = log((count[genusNodes[k]] + probabilityInTemplate) / (float) (genusTotals[k] + 1));  
130                                                 if (count[genusNodes[k]] != 0) { 
131                                                         #ifdef USE_MPI
132                                                                 int pid;
133                                                                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
134                                                 
135                                                                 if (pid == 0) {  
136                                                         #endif
137
138                                                         out << k << '\t' << wordGenusProb[i][k] << '\t'; 
139                                                         
140                                                         #ifdef USE_MPI
141                                                                 }
142                                                         #endif
143
144                                                         numNotZero++;  
145                                                 }
146                                         }
147                                         
148                                         #ifdef USE_MPI
149                                                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
150                                 
151                                                 if (pid == 0) {  
152                                         #endif
153                                         
154                                         out << endl;
155                                         out2 << probabilityInTemplate << '\t' << numNotZero << endl;
156                                         
157                                         #ifdef USE_MPI
158                                                 }
159                                         #endif
160                                 }
161                                 
162                                 #ifdef USE_MPI
163                                         MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
164                                 
165                                         if (pid == 0) {  
166                                 #endif
167                                 
168                                 out.close();
169                                 out2.close();
170                                 
171                                 #ifdef USE_MPI
172                                         }
173                                 #endif
174                                 
175                                 //read in new phylotree with less info. - its faster
176                                 ifstream phyloTreeTest(phyloTreeName.c_str());
177                                 delete phyloTree;
178                                 
179                                 phyloTree = new PhyloTree(phyloTreeTest, phyloTreeName);
180                         }
181                 }
182         
183                 m->mothurOut("DONE."); m->mothurOutEndLine();
184                 m->mothurOut("It took " + toString(time(NULL) - start) + " seconds get probabilities. "); m->mothurOutEndLine();
185         }
186         catch(exception& e) {
187                 m->errorOut(e, "Bayesian", "Bayesian");
188                 exit(1);
189         }
190 }
191 /**************************************************************************************************/
192 Bayesian::~Bayesian() {
193         try {
194                  delete phyloTree; 
195                  if (database != NULL) {  delete database; }
196         }
197         catch(exception& e) {
198                 m->errorOut(e, "Bayesian", "~Bayesian");
199                 exit(1);
200         }
201 }
202
203 /**************************************************************************************************/
204 string Bayesian::getTaxonomy(Sequence* seq) {
205         try {
206                 string tax = "";
207                 Kmer kmer(kmerSize);
208                 
209                 //get words contained in query
210                 //getKmerString returns a string where the index in the string is hte kmer number 
211                 //and the character at that index can be converted to be the number of times that kmer was seen
212
213                 string queryKmerString = kmer.getKmerString(seq->getUnaligned()); 
214
215                 vector<int> queryKmers;
216                 for (int i = 0; i < queryKmerString.length(); i++) {
217                         if (queryKmerString[i] != '!') { //this kmer is in the query
218                                 queryKmers.push_back(i);
219                         }
220                 }
221                 
222                 if (queryKmers.size() == 0) {  m->mothurOut(seq->getName() + "is bad."); m->mothurOutEndLine(); return "bad seq"; }
223                 
224                 int index = getMostProbableTaxonomy(queryKmers);
225                 
226                 if (m->control_pressed) { return tax; }
227 //cout << seq->getName() << '\t' << index << endl;                                      
228                 //bootstrap - to set confidenceScore
229                 int numToSelect = queryKmers.size() / 8;
230                 tax = bootstrapResults(queryKmers, index, numToSelect);
231                                                 
232                 return tax;     
233         }
234         catch(exception& e) {
235                 m->errorOut(e, "Bayesian", "getTaxonomy");
236                 exit(1);
237         }
238 }
239 /**************************************************************************************************/
240 string Bayesian::bootstrapResults(vector<int> kmers, int tax, int numToSelect) {
241         try {
242                                 
243                 map<int, int> confidenceScores; 
244                                 
245                 map<int, int>::iterator itBoot;
246                 map<int, int>::iterator itBoot2;
247                 map<int, int>::iterator itConvert;
248                 
249                 for (int i = 0; i < iters; i++) {
250                         if (m->control_pressed) { return "control"; }
251                         
252                         vector<int> temp;
253                                                 
254                         for (int j = 0; j < numToSelect; j++) {
255                                 int index = int(rand() % kmers.size());
256                                 
257                                 //add word to temp
258                                 temp.push_back(kmers[index]);
259                         }
260                         
261                         //get taxonomy
262                         int newTax = getMostProbableTaxonomy(temp);
263                         TaxNode taxonomyTemp = phyloTree->get(newTax);
264         
265                         //add to confidence results
266                         while (taxonomyTemp.level != 0) { //while you are not at the root
267                                 
268                                 itBoot2 = confidenceScores.find(newTax); //is this a classification we already have a count on
269                                 
270                                 if (itBoot2 == confidenceScores.end()) { //not already in confidence scores
271                                         confidenceScores[newTax] = 1;
272                                 }else{
273                                         confidenceScores[newTax]++;
274                                 }
275                                 
276                                 newTax = taxonomyTemp.parent;
277                                 taxonomyTemp = phyloTree->get(newTax);
278                         }
279         
280                 }
281                 
282                 string confidenceTax = "";
283                 simpleTax = "";
284                 
285                 int seqTaxIndex = tax;
286                 TaxNode seqTax = phyloTree->get(tax);
287                 
288                 while (seqTax.level != 0) { //while you are not at the root
289                                         
290                                 itBoot2 = confidenceScores.find(seqTaxIndex); //is this a classification we already have a count on
291                                 
292                                 int confidence = 0;
293                                 if (itBoot2 != confidenceScores.end()) { //already in confidence scores
294                                         confidence = confidenceScores[seqTaxIndex];
295                                 }
296                                 
297                                 if (((confidence/(float)iters) * 100) >= confidenceThreshold) {
298                                         confidenceTax = seqTax.name + "(" + toString(((confidence/(float)iters) * 100)) + ");" + confidenceTax;
299                                         simpleTax = seqTax.name + ";" + simpleTax;
300                                 }
301                                 
302                                 seqTaxIndex = seqTax.parent;
303                                 seqTax = phyloTree->get(seqTax.parent);
304                 }
305                 
306                 if (confidenceTax == "") { confidenceTax = "unclassified;"; simpleTax = "unclassified;"; }
307                 return confidenceTax;
308                 
309         }
310         catch(exception& e) {
311                 m->errorOut(e, "Bayesian", "bootstrapResults");
312                 exit(1);
313         }
314 }
315 /**************************************************************************************************/
316 int Bayesian::getMostProbableTaxonomy(vector<int> queryKmer) {
317         try {
318                 int indexofGenus = 0;
319                 
320                 double maxProbability = -1000000.0;
321                 //find taxonomy with highest probability that this sequence is from it
322                 for (int k = 0; k < genusNodes.size(); k++) {
323                         //for each taxonomy calc its probability
324                         double prob = 1.0;
325                         for (int i = 0; i < queryKmer.size(); i++) {
326                                 prob += wordGenusProb[queryKmer[i]][k];
327                         }
328                 
329                         //is this the taxonomy with the greatest probability?
330                         if (prob > maxProbability) { 
331                                 indexofGenus = genusNodes[k];
332                                 maxProbability = prob;
333                         }
334                 }
335
336                 return indexofGenus;
337         }
338         catch(exception& e) {
339                 m->errorOut(e, "Bayesian", "getMostProbableTaxonomy");
340                 exit(1);
341         }
342 }
343 /*************************************************************************************************
344 map<string, int> Bayesian::parseTaxMap(string newTax) {
345         try{
346         
347                 map<string, int> parsed;
348                 
349                 newTax = newTax.substr(0, newTax.length()-1);  //get rid of last ';'
350         
351                 //parse taxonomy
352                 string individual;
353                 while (newTax.find_first_of(';') != -1) {
354                         individual = newTax.substr(0,newTax.find_first_of(';'));
355                         newTax = newTax.substr(newTax.find_first_of(';')+1, newTax.length());
356                         parsed[individual] = 1;
357                 }
358                 
359                 //get last one
360                 parsed[newTax] = 1;
361
362                 return parsed;
363                 
364         }
365         catch(exception& e) {
366                 m->errorOut(e, "Bayesian", "parseTax");
367                 exit(1);
368         }
369 }
370 /**************************************************************************************************/
371 void Bayesian::readProbFile(ifstream& in, ifstream& inNum, string inName, string inNumName) {
372         try{
373                 
374                 #ifdef USE_MPI
375                         
376                         int pid, num, num2, processors;
377                         vector<unsigned long int> positions;
378                         vector<unsigned long int> positions2;
379                         
380                         MPI_Status status; 
381                         MPI_File inMPI;
382                         MPI_File inMPI2;
383                         MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
384                         MPI_Comm_size(MPI_COMM_WORLD, &processors);
385                         int tag = 2001;
386
387                         char inFileName[1024];
388                         strcpy(inFileName, inNumName.c_str());
389                         
390                         char inFileName2[1024];
391                         strcpy(inFileName2, inName.c_str());
392
393                         MPI_File_open(MPI_COMM_WORLD, inFileName, MPI_MODE_RDONLY, MPI_INFO_NULL, &inMPI);  //comm, filename, mode, info, filepointer
394                         MPI_File_open(MPI_COMM_WORLD, inFileName2, MPI_MODE_RDONLY, MPI_INFO_NULL, &inMPI2);  //comm, filename, mode, info, filepointer
395
396                         if (pid == 0) {
397                                 positions = setFilePosEachLine(inNumName, num);
398                                 positions2 = setFilePosEachLine(inName, num2);
399                                 
400                                 for(int i = 1; i < processors; i++) { 
401                                         MPI_Send(&num, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
402                                         MPI_Send(&positions[0], (num+1), MPI_LONG, i, tag, MPI_COMM_WORLD);
403                                         
404                                         MPI_Send(&num2, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
405                                         MPI_Send(&positions2[0], (num2+1), MPI_LONG, i, tag, MPI_COMM_WORLD);
406                                 }
407
408                         }else{
409                                 MPI_Recv(&num, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
410                                 positions.resize(num+1);
411                                 MPI_Recv(&positions[0], (num+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
412                                 
413                                 MPI_Recv(&num2, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
414                                 positions2.resize(num2+1);
415                                 MPI_Recv(&positions2[0], (num2+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
416                         }
417                 
418                         //read numKmers
419                         int length = positions2[1] - positions2[0];
420                         char* buf = new char[length];
421
422                         MPI_File_read_at(inMPI2, positions2[0], buf, length, MPI_CHAR, &status);
423
424                         string tempBuf = buf;
425                         if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
426                         delete buf;
427
428                         istringstream iss (tempBuf,istringstream::in);
429                         iss >> numKmers;  
430                         
431                         //initialze probabilities
432                         wordGenusProb.resize(numKmers);
433                         
434                         for (int j = 0; j < wordGenusProb.size(); j++) {        wordGenusProb[j].resize(genusNodes.size());             }
435                         
436                         int kmer, name;  
437                         vector<int> numbers; numbers.resize(numKmers);
438                         float prob;
439                         vector<float> zeroCountProb; zeroCountProb.resize(numKmers);            
440
441                         //read file 
442                         for(int i=0;i<num;i++){
443                                 //read next sequence
444                                 length = positions[i+1] - positions[i];
445                                 char* buf4 = new char[length];
446
447                                 MPI_File_read_at(inMPI, positions[i], buf4, length, MPI_CHAR, &status);
448
449                                 tempBuf = buf4;
450                                 if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
451                                 delete buf4;
452
453                                 istringstream iss (tempBuf,istringstream::in);
454                                 iss >> zeroCountProb[i] >> numbers[i];  
455                         }
456                         
457                         MPI_File_close(&inMPI);
458                         
459                         for(int i=1;i<num2;i++){
460                                 //read next sequence
461                                 length = positions2[i+1] - positions2[i];
462                                 char* buf4 = new char[length];
463
464                                 MPI_File_read_at(inMPI2, positions2[i], buf4, length, MPI_CHAR, &status);
465
466                                 tempBuf = buf4;
467                                 if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
468                                 delete buf4;
469
470                                 istringstream iss (tempBuf,istringstream::in);
471                                 
472                                 iss >> kmer;
473                                 
474                                 //set them all to zero value
475                                 for (int i = 0; i < genusNodes.size(); i++) {
476                                         wordGenusProb[kmer][i] = log(zeroCountProb[kmer] / (float) (genusTotals[i]+1));
477                                 }
478                                 
479                                 //get probs for nonzero values
480                                 for (int i = 0; i < numbers[kmer]; i++) {
481                                         iss >> name >> prob;
482                                         wordGenusProb[kmer][name] = prob;
483                                 }
484                                 
485                         }
486                         MPI_File_close(&inMPI2);
487                         MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
488                 #else
489                 
490                         in >> numKmers; gobble(in);
491                         
492                         //initialze probabilities
493                         wordGenusProb.resize(numKmers);
494                         
495                         for (int j = 0; j < wordGenusProb.size(); j++) {        wordGenusProb[j].resize(genusNodes.size());             }
496                         
497                         int kmer, name, count;  count = 0;
498                         vector<int> num; num.resize(numKmers);
499                         float prob;
500                         vector<float> zeroCountProb; zeroCountProb.resize(numKmers);            
501                 
502                         while (inNum) {
503                                 inNum >> zeroCountProb[count] >> num[count];  
504                                 count++;
505                                 gobble(inNum);
506                         }
507                         inNum.close();
508                 
509                         while(in) {
510                                 in >> kmer;
511                                 
512                                 //set them all to zero value
513                                 for (int i = 0; i < genusNodes.size(); i++) {
514                                         wordGenusProb[kmer][i] = log(zeroCountProb[kmer] / (float) (genusTotals[i]+1));
515                                 }
516                                 
517                                 //get probs for nonzero values
518                                 for (int i = 0; i < num[kmer]; i++) {
519                                         in >> name >> prob;
520                                         wordGenusProb[kmer][name] = prob;
521                                 }
522                                 
523                                 gobble(in);
524                         }
525                         in.close();
526                         
527                 #endif
528         }
529         catch(exception& e) {
530                 m->errorOut(e, "Bayesian", "readProbFile");
531                 exit(1);
532         }
533 }
534 /**************************************************************************************************/
535
536
537
538
539
540