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