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, bool f, bool sh) :
16 Classify(), kmerSize(ksize), confidenceThreshold(cutoff), iters(i) {
18 ReferenceDB* rdb = ReferenceDB::getInstance();
23 string baseName = tempFile;
25 if (baseName == "saved") { baseName = rdb->getSavedReference(); }
27 string baseTName = tfile;
28 if (baseTName == "saved") { baseTName = rdb->getSavedTaxonomy(); }
30 /************calculate the probablity that each word will be in a specific taxonomy*************/
31 string tfileroot = m->getFullPathName(baseTName.substr(0,baseTName.find_last_of(".")+1));
32 string tempfileroot = m->getRootName(m->getSimpleName(baseName));
33 string phyloTreeName = tfileroot + "tree.train";
34 string phyloTreeSumName = tfileroot + "tree.sum";
35 string probFileName = tfileroot + tempfileroot + char('0'+ kmerSize) + "mer.prob";
36 string probFileName2 = tfileroot + tempfileroot + char('0'+ kmerSize) + "mer.numNonZero";
41 ifstream phyloTreeTest(phyloTreeName.c_str());
42 ifstream probFileTest2(probFileName2.c_str());
43 ifstream probFileTest(probFileName.c_str());
44 ifstream probFileTest3(phyloTreeSumName.c_str());
46 int start = time(NULL);
48 //if they are there make sure they were created after this release date
49 bool FilesGood = false;
50 if(probFileTest && probFileTest2 && phyloTreeTest && probFileTest3){
51 FilesGood = checkReleaseDate(probFileTest, probFileTest2, phyloTreeTest, probFileTest3);
54 //if you want to save, but you dont need to calculate then just read
55 if (rdb->save && probFileTest && probFileTest2 && phyloTreeTest && probFileTest3 && FilesGood && (tempFile != "saved")) {
57 m->openInputFile(tempFile, saveIn);
59 while (!saveIn.eof()) {
60 Sequence temp(saveIn);
63 rdb->referenceSeqs.push_back(temp);
68 if(probFileTest && probFileTest2 && phyloTreeTest && probFileTest3 && FilesGood){
69 if (tempFile == "saved") { m->mothurOutEndLine(); m->mothurOut("Using sequences from " + rdb->getSavedReference() + " that are saved in memory."); m->mothurOutEndLine(); }
71 m->mothurOut("Reading template taxonomy... "); cout.flush();
73 phyloTree = new PhyloTree(phyloTreeTest, phyloTreeName);
75 m->mothurOut("DONE."); m->mothurOutEndLine();
77 genusNodes = phyloTree->getGenusNodes();
78 genusTotals = phyloTree->getGenusTotals();
80 if (tfile == "saved") {
81 m->mothurOutEndLine(); m->mothurOut("Using probabilties from " + rdb->getSavedTaxonomy() + " that are saved in memory... "); cout.flush();;
82 wordGenusProb = rdb->wordGenusProb;
83 WordPairDiffArr = rdb->WordPairDiffArr;
85 m->mothurOut("Reading template probabilities... "); cout.flush();
86 readProbFile(probFileTest, probFileTest2, probFileName, probFileName2);
90 if (rdb->save) { rdb->wordGenusProb = wordGenusProb; rdb->WordPairDiffArr = WordPairDiffArr; }
93 //create search database and names vector
94 generateDatabaseAndNames(tfile, tempFile, method, ksize, 0.0, 0.0, 0.0, 0.0);
96 //prevents errors caused by creating shortcut files if you had an error in the sanity check.
97 if (m->control_pressed) { m->mothurRemove(phyloTreeName); m->mothurRemove(probFileName); m->mothurRemove(probFileName2); }
99 genusNodes = phyloTree->getGenusNodes();
100 genusTotals = phyloTree->getGenusTotals();
102 m->mothurOut("Calculating template taxonomy tree... "); cout.flush();
104 phyloTree->printTreeNodes(phyloTreeName);
106 m->mothurOut("DONE."); m->mothurOutEndLine();
108 m->mothurOut("Calculating template probabilities... "); cout.flush();
110 numKmers = database->getMaxKmer() + 1;
112 //initialze probabilities
113 wordGenusProb.resize(numKmers);
114 WordPairDiffArr.resize(numKmers);
116 for (int j = 0; j < wordGenusProb.size(); j++) { wordGenusProb[j].resize(genusNodes.size()); }
122 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
129 m->openOutputFile(probFileName, out);
131 //output mothur version
132 out << "#" << m->getVersion() << endl;
134 out << numKmers << endl;
136 m->openOutputFile(probFileName2, out2);
138 //output mothur version
139 out2 << "#" << m->getVersion() << endl;
147 for (int i = 0; i < numKmers; i++) {
148 if (m->control_pressed) { break; }
151 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
156 if (shortcuts) { out << i << '\t'; }
162 vector<int> seqsWithWordi = database->getSequencesWithKmer(i);
164 //for each sequence with that word
165 vector<int> count; count.resize(genusNodes.size(), 0);
166 for (int j = 0; j < seqsWithWordi.size(); j++) {
167 int temp = phyloTree->getGenusIndex(names[seqsWithWordi[j]]);
168 count[temp]++; //increment count of seq in this genus who have this word
171 //probabilityInTemplate = (# of seqs with that word in template + 0.50) / (total number of seqs in template + 1);
172 float probabilityInTemplate = (seqsWithWordi.size() + 0.50) / (float) (names.size() + 1);
173 diffPair tempProb(log(probabilityInTemplate), 0.0);
174 WordPairDiffArr[i] = tempProb;
177 for (int k = 0; k < genusNodes.size(); k++) {
178 //probabilityInThisTaxonomy = (# of seqs with that word in this taxonomy + probabilityInTemplate) / (total number of seqs in this taxonomy + 1);
181 wordGenusProb[i][k] = log((count[k] + probabilityInTemplate) / (float) (genusTotals[k] + 1));
186 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
191 if (shortcuts) { out << k << '\t' << wordGenusProb[i][k] << '\t' ; }
202 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
209 out2 << probabilityInTemplate << '\t' << numNotZero << '\t' << log(probabilityInTemplate) << endl;
218 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
231 //read in new phylotree with less info. - its faster
232 ifstream phyloTreeTest(phyloTreeName.c_str());
235 phyloTree = new PhyloTree(phyloTreeTest, phyloTreeName);
238 if (rdb->save) { rdb->wordGenusProb = wordGenusProb; rdb->WordPairDiffArr = WordPairDiffArr; }
242 generateWordPairDiffArr();
245 if (rdb->save) { rdb->wordGenusProb = wordGenusProb; rdb->WordPairDiffArr = WordPairDiffArr; }
247 m->mothurOut("DONE."); m->mothurOutEndLine();
248 m->mothurOut("It took " + toString(time(NULL) - start) + " seconds get probabilities. "); m->mothurOutEndLine();
250 catch(exception& e) {
251 m->errorOut(e, "Bayesian", "Bayesian");
255 /**************************************************************************************************/
256 Bayesian::~Bayesian() {
258 if (phyloTree != NULL) { delete phyloTree; }
259 if (database != NULL) { delete database; }
261 catch(exception& e) {
262 m->errorOut(e, "Bayesian", "~Bayesian");
267 /**************************************************************************************************/
268 string Bayesian::getTaxonomy(Sequence* seq) {
274 //get words contained in query
275 //getKmerString returns a string where the index in the string is hte kmer number
276 //and the character at that index can be converted to be the number of times that kmer was seen
277 string queryKmerString = kmer.getKmerString(seq->getUnaligned());
279 vector<int> queryKmers;
280 for (int i = 0; i < queryKmerString.length()-1; i++) { // the -1 is to ignore any kmer with an N in it
281 if (queryKmerString[i] != '!') { //this kmer is in the query
282 queryKmers.push_back(i);
286 //if user wants to test reverse compliment and its reversed use that instead
288 if (isReversed(queryKmers)) {
290 seq->reverseComplement();
291 queryKmerString = kmer.getKmerString(seq->getUnaligned());
293 for (int i = 0; i < queryKmerString.length()-1; i++) { // the -1 is to ignore any kmer with an N in it
294 if (queryKmerString[i] != '!') { //this kmer is in the query
295 queryKmers.push_back(i);
301 if (queryKmers.size() == 0) { m->mothurOut(seq->getName() + "is bad."); m->mothurOutEndLine(); simpleTax = "unknown;"; return "unknown;"; }
304 int index = getMostProbableTaxonomy(queryKmers);
306 if (m->control_pressed) { return tax; }
308 //bootstrap - to set confidenceScore
309 int numToSelect = queryKmers.size() / 8;
311 if (m->debug) { m->mothurOut(seq->getName() + "\t"); }
313 tax = bootstrapResults(queryKmers, index, numToSelect);
315 if (m->debug) { m->mothurOut("\n"); }
319 catch(exception& e) {
320 m->errorOut(e, "Bayesian", "getTaxonomy");
324 /**************************************************************************************************/
325 string Bayesian::bootstrapResults(vector<int> kmers, int tax, int numToSelect) {
328 map<int, int> confidenceScores;
330 //initialize confidences to 0
332 TaxNode seq = phyloTree->get(tax);
333 confidenceScores[tax] = 0;
335 while (seq.level != 0) { //while you are not at the root
336 seqIndex = seq.parent;
337 confidenceScores[seqIndex] = 0;
338 seq = phyloTree->get(seq.parent);
341 map<int, int>::iterator itBoot;
342 map<int, int>::iterator itBoot2;
343 map<int, int>::iterator itConvert;
345 for (int i = 0; i < iters; i++) {
346 if (m->control_pressed) { return "control"; }
349 for (int j = 0; j < numToSelect; j++) {
350 int index = int(rand() % kmers.size());
353 temp.push_back(kmers[index]);
357 int newTax = getMostProbableTaxonomy(temp);
359 TaxNode taxonomyTemp = phyloTree->get(newTax);
361 //add to confidence results
362 while (taxonomyTemp.level != 0) { //while you are not at the root
363 itBoot2 = confidenceScores.find(newTax); //is this a classification we already have a count on
365 if (itBoot2 != confidenceScores.end()) { //this is a classification we need a confidence for
369 newTax = taxonomyTemp.parent;
370 taxonomyTemp = phyloTree->get(newTax);
375 string confidenceTax = "";
378 int seqTaxIndex = tax;
379 TaxNode seqTax = phyloTree->get(tax);
382 while (seqTax.level != 0) { //while you are not at the root
384 itBoot2 = confidenceScores.find(seqTaxIndex); //is this a classification we already have a count on
387 if (itBoot2 != confidenceScores.end()) { //already in confidence scores
388 confidence = itBoot2->second;
391 if (m->debug) { m->mothurOut(seqTax.name + "(" + toString(((confidence/(float)iters) * 100)) + ");"); }
393 if (((confidence/(float)iters) * 100) >= confidenceThreshold) {
394 confidenceTax = seqTax.name + "(" + toString(((confidence/(float)iters) * 100)) + ");" + confidenceTax;
395 simpleTax = seqTax.name + ";" + simpleTax;
398 seqTaxIndex = seqTax.parent;
399 seqTax = phyloTree->get(seqTax.parent);
402 if (confidenceTax == "") { confidenceTax = "unknown;"; simpleTax = "unknown;"; }
404 return confidenceTax;
407 catch(exception& e) {
408 m->errorOut(e, "Bayesian", "bootstrapResults");
412 /**************************************************************************************************/
413 int Bayesian::getMostProbableTaxonomy(vector<int> queryKmer) {
415 int indexofGenus = 0;
417 double maxProbability = -1000000.0;
418 //find taxonomy with highest probability that this sequence is from it
421 // cout << genusNodes.size() << endl;
424 for (int k = 0; k < genusNodes.size(); k++) {
425 //for each taxonomy calc its probability
427 double prob = 0.0000;
428 for (int i = 0; i < queryKmer.size(); i++) {
429 prob += wordGenusProb[queryKmer[i]][k];
432 // cout << phyloTree->get(genusNodes[k]).name << '\t' << prob << endl;
434 //is this the taxonomy with the greatest probability?
435 if (prob > maxProbability) {
436 indexofGenus = genusNodes[k];
437 maxProbability = prob;
444 catch(exception& e) {
445 m->errorOut(e, "Bayesian", "getMostProbableTaxonomy");
449 //********************************************************************************************************************
450 //if it is more probable that the reverse compliment kmers are in the template, then we assume the sequence is reversed.
451 bool Bayesian::isReversed(vector<int>& queryKmers){
453 bool reversed = false;
455 float reverseProb = 0;
457 for (int i = 0; i < queryKmers.size(); i++){
458 int kmer = queryKmers[i];
460 prob += WordPairDiffArr[kmer].prob;
461 reverseProb += WordPairDiffArr[kmer].reverseProb;
465 if (reverseProb > prob){ reversed = true; }
469 catch(exception& e) {
470 m->errorOut(e, "Bayesian", "isReversed");
474 //********************************************************************************************************************
475 int Bayesian::generateWordPairDiffArr(){
478 for (int i = 0; i < WordPairDiffArr.size(); i++) {
479 int reversedWord = kmer.getReverseKmerNumber(i);
480 WordPairDiffArr[i].reverseProb = WordPairDiffArr[reversedWord].prob;
484 }catch(exception& e) {
485 m->errorOut(e, "Bayesian", "generateWordPairDiffArr");
489 /*************************************************************************************************
490 map<string, int> Bayesian::parseTaxMap(string newTax) {
493 map<string, int> parsed;
495 newTax = newTax.substr(0, newTax.length()-1); //get rid of last ';'
499 while (newTax.find_first_of(';') != -1) {
500 individual = newTax.substr(0,newTax.find_first_of(';'));
501 newTax = newTax.substr(newTax.find_first_of(';')+1, newTax.length());
502 parsed[individual] = 1;
511 catch(exception& e) {
512 m->errorOut(e, "Bayesian", "parseTax");
516 **************************************************************************************************/
517 void Bayesian::readProbFile(ifstream& in, ifstream& inNum, string inName, string inNumName) {
522 int pid, num, num2, processors;
523 vector<unsigned long long> positions;
524 vector<unsigned long long> positions2;
529 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
530 MPI_Comm_size(MPI_COMM_WORLD, &processors);
533 char inFileName[1024];
534 strcpy(inFileName, inNumName.c_str());
536 char inFileName2[1024];
537 strcpy(inFileName2, inName.c_str());
539 MPI_File_open(MPI_COMM_WORLD, inFileName, MPI_MODE_RDONLY, MPI_INFO_NULL, &inMPI); //comm, filename, mode, info, filepointer
540 MPI_File_open(MPI_COMM_WORLD, inFileName2, MPI_MODE_RDONLY, MPI_INFO_NULL, &inMPI2); //comm, filename, mode, info, filepointer
543 positions = m->setFilePosEachLine(inNumName, num);
544 positions2 = m->setFilePosEachLine(inName, num2);
546 for(int i = 1; i < processors; i++) {
547 MPI_Send(&num, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
548 MPI_Send(&positions[0], (num+1), MPI_LONG, i, tag, MPI_COMM_WORLD);
550 MPI_Send(&num2, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
551 MPI_Send(&positions2[0], (num2+1), MPI_LONG, i, tag, MPI_COMM_WORLD);
555 MPI_Recv(&num, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
556 positions.resize(num+1);
557 MPI_Recv(&positions[0], (num+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
559 MPI_Recv(&num2, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
560 positions2.resize(num2+1);
561 MPI_Recv(&positions2[0], (num2+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
565 int length = positions2[1] - positions2[0];
566 char* buf5 = new char[length];
568 MPI_File_read_at(inMPI2, positions2[0], buf5, length, MPI_CHAR, &status);
572 length = positions2[2] - positions2[1];
573 char* buf = new char[length];
575 MPI_File_read_at(inMPI2, positions2[1], buf, length, MPI_CHAR, &status);
577 string tempBuf = buf;
578 if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
581 istringstream iss (tempBuf,istringstream::in);
584 //initialze probabilities
585 wordGenusProb.resize(numKmers);
587 for (int j = 0; j < wordGenusProb.size(); j++) { wordGenusProb[j].resize(genusNodes.size()); }
590 vector<int> numbers; numbers.resize(numKmers);
592 vector<float> zeroCountProb; zeroCountProb.resize(numKmers);
593 WordPairDiffArr.resize(numKmers);
596 length = positions[1] - positions[0];
597 char* buf6 = new char[length];
599 MPI_File_read_at(inMPI2, positions[0], buf6, length, MPI_CHAR, &status);
603 for(int i=1;i<num;i++){
605 length = positions[i+1] - positions[i];
606 char* buf4 = new char[length];
608 MPI_File_read_at(inMPI, positions[i], buf4, length, MPI_CHAR, &status);
611 if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
614 istringstream iss (tempBuf,istringstream::in);
616 iss >> zeroCountProb[i] >> numbers[i] >> probTemp;
617 WordPairDiffArr[i].prob = probTemp;
621 MPI_File_close(&inMPI);
623 for(int i=2;i<num2;i++){
625 length = positions2[i+1] - positions2[i];
626 char* buf4 = new char[length];
628 MPI_File_read_at(inMPI2, positions2[i], buf4, length, MPI_CHAR, &status);
631 if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
634 istringstream iss (tempBuf,istringstream::in);
638 //set them all to zero value
639 for (int i = 0; i < genusNodes.size(); i++) {
640 wordGenusProb[kmer][i] = log(zeroCountProb[kmer] / (float) (genusTotals[i]+1));
643 //get probs for nonzero values
644 for (int i = 0; i < numbers[kmer]; i++) {
646 wordGenusProb[kmer][name] = prob;
650 MPI_File_close(&inMPI2);
651 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
654 string line = m->getline(in); m->gobble(in);
656 in >> numKmers; m->gobble(in);
657 //cout << threadID << '\t' << line << '\t' << numKmers << &in << '\t' << &inNum << '\t' << genusNodes.size() << endl;
658 //initialze probabilities
659 wordGenusProb.resize(numKmers);
661 for (int j = 0; j < wordGenusProb.size(); j++) { wordGenusProb[j].resize(genusNodes.size()); }
663 int kmer, name, count; count = 0;
664 vector<int> num; num.resize(numKmers);
666 vector<float> zeroCountProb; zeroCountProb.resize(numKmers);
667 WordPairDiffArr.resize(numKmers);
670 string line2 = m->getline(inNum); m->gobble(inNum);
672 //cout << threadID << '\t' << line2 << '\t' << this << endl;
674 inNum >> zeroCountProb[count] >> num[count] >> probTemp;
675 WordPairDiffArr[count].prob = probTemp;
678 //cout << threadID << '\t' << count << endl;
681 //cout << threadID << '\t' << "here1 " << &wordGenusProb << '\t' << &num << endl; //
682 //cout << threadID << '\t' << &genusTotals << '\t' << endl;
683 //cout << threadID << '\t' << genusNodes.size() << endl;
686 //cout << threadID << '\t' << kmer << endl;
687 //set them all to zero value
688 for (int i = 0; i < genusNodes.size(); i++) {
689 wordGenusProb[kmer][i] = log(zeroCountProb[kmer] / (float) (genusTotals[i]+1));
691 //cout << threadID << '\t' << num[kmer] << "here" << endl;
692 //get probs for nonzero values
693 for (int i = 0; i < num[kmer]; i++) {
695 wordGenusProb[kmer][name] = prob;
701 //cout << threadID << '\t' << "here" << endl;
704 catch(exception& e) {
705 m->errorOut(e, "Bayesian", "readProbFile");
709 /**************************************************************************************************/
710 bool Bayesian::checkReleaseDate(ifstream& file1, ifstream& file2, ifstream& file3, ifstream& file4) {
715 vector<string> lines;
716 lines.push_back(m->getline(file1));
717 lines.push_back(m->getline(file2));
718 lines.push_back(m->getline(file3));
719 lines.push_back(m->getline(file4));
721 //before we added this check
722 if ((lines[0][0] != '#') || (lines[1][0] != '#') || (lines[2][0] != '#') || (lines[3][0] != '#')) { good = false; }
725 for (int i = 0; i < lines.size(); i++) { lines[i] = lines[i].substr(1); }
727 //get mothurs current version
728 string version = m->getVersion();
730 vector<string> versionVector;
731 m->splitAtChar(version, versionVector, '.');
733 //check each files version
734 for (int i = 0; i < lines.size(); i++) {
735 vector<string> linesVector;
736 m->splitAtChar(lines[i], linesVector, '.');
738 if (versionVector.size() != linesVector.size()) { good = false; break; }
740 for (int j = 0; j < versionVector.size(); j++) {
742 convert(versionVector[j], num1);
743 convert(linesVector[j], num2);
745 //if mothurs version is newer than this files version, then we want to remake it
746 if (num1 > num2) { good = false; break; }
750 if (!good) { break; }
754 if (!good) { file1.close(); file2.close(); file3.close(); file4.close(); }
755 else { file1.seekg(0); file2.seekg(0); file3.seekg(0); file4.seekg(0); }
759 catch(exception& e) {
760 m->errorOut(e, "Bayesian", "checkReleaseDate");
764 /**************************************************************************************************/