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