5 * Created by westcott on 11/3/09.
6 * Copyright 2009 Schloss Lab. All rights reserved.
12 #include "phylosummary.h"
13 #include "referencedb.h"
14 /**************************************************************************************************/
15 Bayesian::Bayesian(string tfile, string tempFile, string method, int ksize, int cutoff, int i, int tid) :
16 Classify(), kmerSize(ksize), confidenceThreshold(cutoff), iters(i) {
18 ReferenceDB* rdb = ReferenceDB::getInstance();
21 string baseName = tempFile;
22 if (baseName == "saved") { baseName = rdb->getSavedReference(); }
24 string baseTName = tfile;
25 if (baseTName == "saved") { baseTName = rdb->getSavedTaxonomy(); }
27 /************calculate the probablity that each word will be in a specific taxonomy*************/
28 string tfileroot = baseTName.substr(0,baseTName.find_last_of(".")+1);
29 string tempfileroot = m->getRootName(m->getSimpleName(baseName));
30 string phyloTreeName = tfileroot + "tree.train";
31 string phyloTreeSumName = tfileroot + "tree.sum";
32 string probFileName = tfileroot + tempfileroot + char('0'+ kmerSize) + "mer.prob";
33 string probFileName2 = tfileroot + tempfileroot + char('0'+ kmerSize) + "mer.numNonZero";
38 ifstream phyloTreeTest(phyloTreeName.c_str());
39 ifstream probFileTest2(probFileName2.c_str());
40 ifstream probFileTest(probFileName.c_str());
41 ifstream probFileTest3(phyloTreeSumName.c_str());
43 int start = time(NULL);
45 //if they are there make sure they were created after this release date
46 bool FilesGood = false;
47 if(probFileTest && probFileTest2 && phyloTreeTest && probFileTest3){
48 FilesGood = checkReleaseDate(probFileTest, probFileTest2, phyloTreeTest, probFileTest3);
51 //if you want to save, but you dont need to calculate then just read
52 if (rdb->save && probFileTest && probFileTest2 && phyloTreeTest && probFileTest3 && FilesGood) {
54 m->openInputFile(tempFile, saveIn);
56 while (!saveIn.eof()) {
57 Sequence temp(saveIn);
60 rdb->referenceSeqs.push_back(temp);
65 if(probFileTest && probFileTest2 && phyloTreeTest && probFileTest3 && FilesGood){
66 if (tempFile == "saved") { m->mothurOutEndLine(); m->mothurOut("Using sequences from " + rdb->getSavedReference() + " that are saved in memory."); m->mothurOutEndLine(); }
68 m->mothurOut("Reading template taxonomy... "); cout.flush();
70 phyloTree = new PhyloTree(phyloTreeTest, phyloTreeName);
72 m->mothurOut("DONE."); m->mothurOutEndLine();
74 genusNodes = phyloTree->getGenusNodes();
75 genusTotals = phyloTree->getGenusTotals();
77 if (tfile == "saved") {
78 m->mothurOutEndLine(); m->mothurOut("Using probabilties from " + rdb->getSavedTaxonomy() + " that are saved in memory... "); cout.flush();;
79 wordGenusProb = rdb->wordGenusProb;
81 m->mothurOut("Reading template probabilities... "); cout.flush();
82 readProbFile(probFileTest, probFileTest2, probFileName, probFileName2);
86 if (rdb->save) { rdb->wordGenusProb = wordGenusProb; }
89 //create search database and names vector
90 generateDatabaseAndNames(tfile, tempFile, method, ksize, 0.0, 0.0, 0.0, 0.0);
92 //prevents errors caused by creating shortcut files if you had an error in the sanity check.
93 if (m->control_pressed) { m->mothurRemove(phyloTreeName); m->mothurRemove(probFileName); m->mothurRemove(probFileName2); }
95 genusNodes = phyloTree->getGenusNodes();
96 genusTotals = phyloTree->getGenusTotals();
98 m->mothurOut("Calculating template taxonomy tree... "); cout.flush();
100 phyloTree->printTreeNodes(phyloTreeName);
102 m->mothurOut("DONE."); m->mothurOutEndLine();
104 m->mothurOut("Calculating template probabilities... "); cout.flush();
106 numKmers = database->getMaxKmer() + 1;
108 //initialze probabilities
109 wordGenusProb.resize(numKmers);
110 //cout << numKmers << '\t' << genusNodes.size() << endl;
111 for (int j = 0; j < wordGenusProb.size(); j++) { wordGenusProb[j].resize(genusNodes.size()); }
112 //cout << numKmers << '\t' << genusNodes.size() << endl;
118 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
124 m->openOutputFile(probFileName, out);
126 //output mothur version
127 out << "#" << m->getVersion() << endl;
129 out << numKmers << endl;
131 m->openOutputFile(probFileName2, out2);
133 //output mothur version
134 out2 << "#" << m->getVersion() << endl;
142 for (int i = 0; i < numKmers; i++) {
143 if (m->control_pressed) { break; }
146 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
157 vector<int> seqsWithWordi = database->getSequencesWithKmer(i);
160 for (int k = 0; k < genusNodes.size(); k++) { count[genusNodes[k]] = 0; }
162 //for each sequence with that word
163 for (int j = 0; j < seqsWithWordi.size(); j++) {
164 int temp = phyloTree->getIndex(names[seqsWithWordi[j]]);
165 count[temp]++; //increment count of seq in this genus who have this word
168 //probabilityInTemplate = (# of seqs with that word in template + 0.50) / (total number of seqs in template + 1);
169 float probabilityInTemplate = (seqsWithWordi.size() + 0.50) / (float) (names.size() + 1);
172 for (int k = 0; k < genusNodes.size(); k++) {
173 //probabilityInThisTaxonomy = (# of seqs with that word in this taxonomy + probabilityInTemplate) / (total number of seqs in this taxonomy + 1);
176 wordGenusProb[i][k] = log((count[genusNodes[k]] + probabilityInTemplate) / (float) (genusTotals[k] + 1));
178 if (count[genusNodes[k]] != 0) {
181 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
186 out << k << '\t' << wordGenusProb[i][k] << '\t';
197 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
203 out2 << probabilityInTemplate << '\t' << numNotZero << endl;
211 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
223 //read in new phylotree with less info. - its faster
224 ifstream phyloTreeTest(phyloTreeName.c_str());
227 phyloTree = new PhyloTree(phyloTreeTest, phyloTreeName);
230 if (rdb->save) { rdb->wordGenusProb = wordGenusProb; }
234 m->mothurOut("DONE."); m->mothurOutEndLine();
235 m->mothurOut("It took " + toString(time(NULL) - start) + " seconds get probabilities. "); m->mothurOutEndLine();
237 catch(exception& e) {
238 m->errorOut(e, "Bayesian", "Bayesian");
242 /**************************************************************************************************/
243 Bayesian::~Bayesian() {
247 if (database != NULL) { delete database; }
249 catch(exception& e) {
250 m->errorOut(e, "Bayesian", "~Bayesian");
255 /**************************************************************************************************/
256 string Bayesian::getTaxonomy(Sequence* seq) {
261 //get words contained in query
262 //getKmerString returns a string where the index in the string is hte kmer number
263 //and the character at that index can be converted to be the number of times that kmer was seen
265 string queryKmerString = kmer.getKmerString(seq->getUnaligned());
267 vector<int> queryKmers;
268 for (int i = 0; i < queryKmerString.length()-1; i++) { // the -1 is to ignore any kmer with an N in it
269 if (queryKmerString[i] != '!') { //this kmer is in the query
270 queryKmers.push_back(i);
274 if (queryKmers.size() == 0) { m->mothurOut(seq->getName() + "is bad."); m->mothurOutEndLine(); return "bad seq"; }
277 int index = getMostProbableTaxonomy(queryKmers);
279 if (m->control_pressed) { return tax; }
281 //bootstrap - to set confidenceScore
282 int numToSelect = queryKmers.size() / 8;
284 tax = bootstrapResults(queryKmers, index, numToSelect);
288 catch(exception& e) {
289 m->errorOut(e, "Bayesian", "getTaxonomy");
293 /**************************************************************************************************/
294 string Bayesian::bootstrapResults(vector<int> kmers, int tax, int numToSelect) {
297 map<int, int> confidenceScores;
299 //initialize confidences to 0
301 TaxNode seq = phyloTree->get(tax);
302 confidenceScores[tax] = 0;
304 while (seq.level != 0) { //while you are not at the root
305 seqIndex = seq.parent;
306 confidenceScores[seqIndex] = 0;
307 seq = phyloTree->get(seq.parent);
310 map<int, int>::iterator itBoot;
311 map<int, int>::iterator itBoot2;
312 map<int, int>::iterator itConvert;
314 for (int i = 0; i < iters; i++) {
315 if (m->control_pressed) { return "control"; }
318 for (int j = 0; j < numToSelect; j++) {
319 int index = int(rand() % kmers.size());
322 temp.push_back(kmers[index]);
326 int newTax = getMostProbableTaxonomy(temp);
328 TaxNode taxonomyTemp = phyloTree->get(newTax);
330 //add to confidence results
331 while (taxonomyTemp.level != 0) { //while you are not at the root
332 itBoot2 = confidenceScores.find(newTax); //is this a classification we already have a count on
334 if (itBoot2 != confidenceScores.end()) { //this is a classification we need a confidence for
338 newTax = taxonomyTemp.parent;
339 taxonomyTemp = phyloTree->get(newTax);
344 string confidenceTax = "";
347 int seqTaxIndex = tax;
348 TaxNode seqTax = phyloTree->get(tax);
350 while (seqTax.level != 0) { //while you are not at the root
352 itBoot2 = confidenceScores.find(seqTaxIndex); //is this a classification we already have a count on
355 if (itBoot2 != confidenceScores.end()) { //already in confidence scores
356 confidence = itBoot2->second;
359 if (((confidence/(float)iters) * 100) >= confidenceThreshold) {
360 confidenceTax = seqTax.name + "(" + toString(((confidence/(float)iters) * 100)) + ");" + confidenceTax;
361 simpleTax = seqTax.name + ";" + simpleTax;
364 seqTaxIndex = seqTax.parent;
365 seqTax = phyloTree->get(seqTax.parent);
368 if (confidenceTax == "") { confidenceTax = "unclassified;"; simpleTax = "unclassified;"; }
369 return confidenceTax;
372 catch(exception& e) {
373 m->errorOut(e, "Bayesian", "bootstrapResults");
377 /**************************************************************************************************/
378 int Bayesian::getMostProbableTaxonomy(vector<int> queryKmer) {
380 int indexofGenus = 0;
382 double maxProbability = -1000000.0;
383 //find taxonomy with highest probability that this sequence is from it
386 // cout << genusNodes.size() << endl;
389 for (int k = 0; k < genusNodes.size(); k++) {
390 //for each taxonomy calc its probability
392 double prob = 0.0000;
393 for (int i = 0; i < queryKmer.size(); i++) {
394 prob += wordGenusProb[queryKmer[i]][k];
397 // cout << phyloTree->get(genusNodes[k]).name << '\t' << prob << endl;
399 //is this the taxonomy with the greatest probability?
400 if (prob > maxProbability) {
401 indexofGenus = genusNodes[k];
402 maxProbability = prob;
409 catch(exception& e) {
410 m->errorOut(e, "Bayesian", "getMostProbableTaxonomy");
414 /*************************************************************************************************
415 map<string, int> Bayesian::parseTaxMap(string newTax) {
418 map<string, int> parsed;
420 newTax = newTax.substr(0, newTax.length()-1); //get rid of last ';'
424 while (newTax.find_first_of(';') != -1) {
425 individual = newTax.substr(0,newTax.find_first_of(';'));
426 newTax = newTax.substr(newTax.find_first_of(';')+1, newTax.length());
427 parsed[individual] = 1;
436 catch(exception& e) {
437 m->errorOut(e, "Bayesian", "parseTax");
441 /**************************************************************************************************/
442 void Bayesian::readProbFile(ifstream& in, ifstream& inNum, string inName, string inNumName) {
447 int pid, num, num2, processors;
448 vector<unsigned long int> positions;
449 vector<unsigned long int> positions2;
454 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
455 MPI_Comm_size(MPI_COMM_WORLD, &processors);
458 char inFileName[1024];
459 strcpy(inFileName, inNumName.c_str());
461 char inFileName2[1024];
462 strcpy(inFileName2, inName.c_str());
464 MPI_File_open(MPI_COMM_WORLD, inFileName, MPI_MODE_RDONLY, MPI_INFO_NULL, &inMPI); //comm, filename, mode, info, filepointer
465 MPI_File_open(MPI_COMM_WORLD, inFileName2, MPI_MODE_RDONLY, MPI_INFO_NULL, &inMPI2); //comm, filename, mode, info, filepointer
468 positions = m->setFilePosEachLine(inNumName, num);
469 positions2 = m->setFilePosEachLine(inName, num2);
471 for(int i = 1; i < processors; i++) {
472 MPI_Send(&num, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
473 MPI_Send(&positions[0], (num+1), MPI_LONG, i, tag, MPI_COMM_WORLD);
475 MPI_Send(&num2, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
476 MPI_Send(&positions2[0], (num2+1), MPI_LONG, i, tag, MPI_COMM_WORLD);
480 MPI_Recv(&num, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
481 positions.resize(num+1);
482 MPI_Recv(&positions[0], (num+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
484 MPI_Recv(&num2, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
485 positions2.resize(num2+1);
486 MPI_Recv(&positions2[0], (num2+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
490 int length = positions2[1] - positions2[0];
491 char* buf5 = new char[length];
493 MPI_File_read_at(inMPI2, positions2[0], buf5, length, MPI_CHAR, &status);
497 length = positions2[2] - positions2[1];
498 char* buf = new char[length];
500 MPI_File_read_at(inMPI2, positions2[1], buf, length, MPI_CHAR, &status);
502 string tempBuf = buf;
503 if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
506 istringstream iss (tempBuf,istringstream::in);
509 //initialze probabilities
510 wordGenusProb.resize(numKmers);
512 for (int j = 0; j < wordGenusProb.size(); j++) { wordGenusProb[j].resize(genusNodes.size()); }
515 vector<int> numbers; numbers.resize(numKmers);
517 vector<float> zeroCountProb; zeroCountProb.resize(numKmers);
520 length = positions[1] - positions[0];
521 char* buf6 = new char[length];
523 MPI_File_read_at(inMPI2, positions[0], buf6, length, MPI_CHAR, &status);
527 for(int i=1;i<num;i++){
529 length = positions[i+1] - positions[i];
530 char* buf4 = new char[length];
532 MPI_File_read_at(inMPI, positions[i], buf4, length, MPI_CHAR, &status);
535 if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
538 istringstream iss (tempBuf,istringstream::in);
539 iss >> zeroCountProb[i] >> numbers[i];
542 MPI_File_close(&inMPI);
544 for(int i=2;i<num2;i++){
546 length = positions2[i+1] - positions2[i];
547 char* buf4 = new char[length];
549 MPI_File_read_at(inMPI2, positions2[i], buf4, length, MPI_CHAR, &status);
552 if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
555 istringstream iss (tempBuf,istringstream::in);
559 //set them all to zero value
560 for (int i = 0; i < genusNodes.size(); i++) {
561 wordGenusProb[kmer][i] = log(zeroCountProb[kmer] / (float) (genusTotals[i]+1));
564 //get probs for nonzero values
565 for (int i = 0; i < numbers[kmer]; i++) {
567 wordGenusProb[kmer][name] = prob;
571 MPI_File_close(&inMPI2);
572 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
575 string line = m->getline(in); m->gobble(in);
577 in >> numKmers; m->gobble(in);
579 //initialze probabilities
580 wordGenusProb.resize(numKmers);
582 for (int j = 0; j < wordGenusProb.size(); j++) { wordGenusProb[j].resize(genusNodes.size()); }
584 int kmer, name, count; count = 0;
585 vector<int> num; num.resize(numKmers);
587 vector<float> zeroCountProb; zeroCountProb.resize(numKmers);
590 string line2 = m->getline(inNum); m->gobble(inNum);
593 inNum >> zeroCountProb[count] >> num[count];
602 //set them all to zero value
603 for (int i = 0; i < genusNodes.size(); i++) {
604 wordGenusProb[kmer][i] = log(zeroCountProb[kmer] / (float) (genusTotals[i]+1));
607 //get probs for nonzero values
608 for (int i = 0; i < num[kmer]; i++) {
610 wordGenusProb[kmer][name] = prob;
619 catch(exception& e) {
620 m->errorOut(e, "Bayesian", "readProbFile");
624 /**************************************************************************************************/
625 bool Bayesian::checkReleaseDate(ifstream& file1, ifstream& file2, ifstream& file3, ifstream& file4) {
630 vector<string> lines;
631 lines.push_back(m->getline(file1));
632 lines.push_back(m->getline(file2));
633 lines.push_back(m->getline(file3));
634 lines.push_back(m->getline(file4));
636 //before we added this check
637 if ((lines[0][0] != '#') || (lines[1][0] != '#') || (lines[2][0] != '#') || (lines[3][0] != '#')) { good = false; }
640 for (int i = 0; i < lines.size(); i++) { lines[i] = lines[i].substr(1); }
642 //get mothurs current version
643 string version = m->getVersion();
645 vector<string> versionVector;
646 m->splitAtChar(version, versionVector, '.');
648 //check each files version
649 for (int i = 0; i < lines.size(); i++) {
650 vector<string> linesVector;
651 m->splitAtChar(lines[i], linesVector, '.');
653 if (versionVector.size() != linesVector.size()) { good = false; break; }
655 for (int j = 0; j < versionVector.size(); j++) {
657 convert(versionVector[j], num1);
658 convert(linesVector[j], num2);
660 //if mothurs version is newer than this files version, then we want to remake it
661 if (num1 > num2) { good = false; break; }
665 if (!good) { break; }
669 if (!good) { file1.close(); file2.close(); file3.close(); file4.close(); }
670 else { file1.seekg(0); file2.seekg(0); file3.seekg(0); file4.seekg(0); }
674 catch(exception& e) {
675 m->errorOut(e, "Bayesian", "checkReleaseDate");
679 /**************************************************************************************************/