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) :
16 Classify(), kmerSize(ksize), confidenceThreshold(cutoff), iters(i) {
18 ReferenceDB* rdb = ReferenceDB::getInstance();
22 string baseName = tempFile;
24 if (baseName == "saved") { baseName = rdb->getSavedReference(); }
26 string baseTName = tfile;
27 if (baseTName == "saved") { baseTName = rdb->getSavedTaxonomy(); }
29 /************calculate the probablity that each word will be in a specific taxonomy*************/
30 string tfileroot = baseTName.substr(0,baseTName.find_last_of(".")+1);
31 string tempfileroot = m->getRootName(m->getSimpleName(baseName));
32 string phyloTreeName = tfileroot + "tree.train";
33 string phyloTreeSumName = tfileroot + "tree.sum";
34 string probFileName = tfileroot + tempfileroot + char('0'+ kmerSize) + "mer.prob";
35 string probFileName2 = tfileroot + tempfileroot + char('0'+ kmerSize) + "mer.numNonZero";
40 ifstream phyloTreeTest(phyloTreeName.c_str());
41 ifstream probFileTest2(probFileName2.c_str());
42 ifstream probFileTest(probFileName.c_str());
43 ifstream probFileTest3(phyloTreeSumName.c_str());
45 int start = time(NULL);
47 //if they are there make sure they were created after this release date
48 bool FilesGood = false;
49 if(probFileTest && probFileTest2 && phyloTreeTest && probFileTest3){
50 FilesGood = checkReleaseDate(probFileTest, probFileTest2, phyloTreeTest, probFileTest3);
53 //if you want to save, but you dont need to calculate then just read
54 if (rdb->save && probFileTest && probFileTest2 && phyloTreeTest && probFileTest3 && FilesGood && (tempFile != "saved")) {
56 m->openInputFile(tempFile, saveIn);
58 while (!saveIn.eof()) {
59 Sequence temp(saveIn);
62 rdb->referenceSeqs.push_back(temp);
67 if(probFileTest && probFileTest2 && phyloTreeTest && probFileTest3 && FilesGood){
68 if (tempFile == "saved") { m->mothurOutEndLine(); m->mothurOut("Using sequences from " + rdb->getSavedReference() + " that are saved in memory."); m->mothurOutEndLine(); }
70 m->mothurOut("Reading template taxonomy... "); cout.flush();
72 phyloTree = new PhyloTree(phyloTreeTest, phyloTreeName);
74 m->mothurOut("DONE."); m->mothurOutEndLine();
76 genusNodes = phyloTree->getGenusNodes();
77 genusTotals = phyloTree->getGenusTotals();
79 if (tfile == "saved") {
80 m->mothurOutEndLine(); m->mothurOut("Using probabilties from " + rdb->getSavedTaxonomy() + " that are saved in memory... "); cout.flush();;
81 wordGenusProb = rdb->wordGenusProb;
82 WordPairDiffArr = rdb->WordPairDiffArr;
84 m->mothurOut("Reading template probabilities... "); cout.flush();
85 readProbFile(probFileTest, probFileTest2, probFileName, probFileName2);
89 if (rdb->save) { rdb->wordGenusProb = wordGenusProb; rdb->WordPairDiffArr = WordPairDiffArr; }
92 //create search database and names vector
93 generateDatabaseAndNames(tfile, tempFile, method, ksize, 0.0, 0.0, 0.0, 0.0);
95 //prevents errors caused by creating shortcut files if you had an error in the sanity check.
96 if (m->control_pressed) { m->mothurRemove(phyloTreeName); m->mothurRemove(probFileName); m->mothurRemove(probFileName2); }
98 genusNodes = phyloTree->getGenusNodes();
99 genusTotals = phyloTree->getGenusTotals();
101 m->mothurOut("Calculating template taxonomy tree... "); cout.flush();
103 phyloTree->printTreeNodes(phyloTreeName);
105 m->mothurOut("DONE."); m->mothurOutEndLine();
107 m->mothurOut("Calculating template probabilities... "); cout.flush();
109 numKmers = database->getMaxKmer() + 1;
111 //initialze probabilities
112 wordGenusProb.resize(numKmers);
113 WordPairDiffArr.resize(numKmers);
114 //cout << numKmers << '\t' << genusNodes.size() << endl;
115 for (int j = 0; j < wordGenusProb.size(); j++) { wordGenusProb[j].resize(genusNodes.size()); }
116 //cout << numKmers << '\t' << genusNodes.size() << endl;
122 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
128 m->openOutputFile(probFileName, out);
130 //output mothur version
131 out << "#" << m->getVersion() << endl;
133 out << numKmers << endl;
135 m->openOutputFile(probFileName2, out2);
137 //output mothur version
138 out2 << "#" << m->getVersion() << endl;
146 for (int i = 0; i < numKmers; i++) {
147 if (m->control_pressed) { break; }
150 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
161 vector<int> seqsWithWordi = database->getSequencesWithKmer(i);
164 for (int k = 0; k < genusNodes.size(); k++) { count[genusNodes[k]] = 0; }
166 //for each sequence with that word
167 for (int j = 0; j < seqsWithWordi.size(); j++) {
168 int temp = phyloTree->getIndex(names[seqsWithWordi[j]]);
169 count[temp]++; //increment count of seq in this genus who have this word
172 //probabilityInTemplate = (# of seqs with that word in template + 0.50) / (total number of seqs in template + 1);
173 float probabilityInTemplate = (seqsWithWordi.size() + 0.50) / (float) (names.size() + 1);
174 diffPair tempProb(log(probabilityInTemplate), 0.0);
175 WordPairDiffArr[i] = tempProb;
178 for (int k = 0; k < genusNodes.size(); k++) {
179 //probabilityInThisTaxonomy = (# of seqs with that word in this taxonomy + probabilityInTemplate) / (total number of seqs in this taxonomy + 1);
182 wordGenusProb[i][k] = log((count[genusNodes[k]] + probabilityInTemplate) / (float) (genusTotals[k] + 1));
184 if (count[genusNodes[k]] != 0) {
187 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
192 out << k << '\t' << wordGenusProb[i][k] << '\t' ;
203 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
209 out2 << probabilityInTemplate << '\t' << numNotZero << '\t' << log(probabilityInTemplate) << endl;
217 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
229 //read in new phylotree with less info. - its faster
230 ifstream phyloTreeTest(phyloTreeName.c_str());
233 phyloTree = new PhyloTree(phyloTreeTest, phyloTreeName);
236 if (rdb->save) { rdb->wordGenusProb = wordGenusProb; rdb->WordPairDiffArr = WordPairDiffArr; }
240 generateWordPairDiffArr();
243 if (rdb->save) { rdb->wordGenusProb = wordGenusProb; rdb->WordPairDiffArr = WordPairDiffArr; }
245 m->mothurOut("DONE."); m->mothurOutEndLine();
246 m->mothurOut("It took " + toString(time(NULL) - start) + " seconds get probabilities. "); m->mothurOutEndLine();
248 catch(exception& e) {
249 m->errorOut(e, "Bayesian", "Bayesian");
253 /**************************************************************************************************/
254 Bayesian::~Bayesian() {
258 if (database != NULL) { delete database; }
260 catch(exception& e) {
261 m->errorOut(e, "Bayesian", "~Bayesian");
266 /**************************************************************************************************/
267 string Bayesian::getTaxonomy(Sequence* seq) {
273 //get words contained in query
274 //getKmerString returns a string where the index in the string is hte kmer number
275 //and the character at that index can be converted to be the number of times that kmer was seen
276 string queryKmerString = kmer.getKmerString(seq->getUnaligned());
278 vector<int> queryKmers;
279 for (int i = 0; i < queryKmerString.length()-1; i++) { // the -1 is to ignore any kmer with an N in it
280 if (queryKmerString[i] != '!') { //this kmer is in the query
281 queryKmers.push_back(i);
285 //if user wants to test reverse compliment and its reversed use that instead
287 if (isReversed(queryKmers)) {
289 seq->reverseComplement();
290 queryKmerString = kmer.getKmerString(seq->getUnaligned());
292 for (int i = 0; i < queryKmerString.length()-1; i++) { // the -1 is to ignore any kmer with an N in it
293 if (queryKmerString[i] != '!') { //this kmer is in the query
294 queryKmers.push_back(i);
300 if (queryKmers.size() == 0) { m->mothurOut(seq->getName() + "is bad."); m->mothurOutEndLine(); simpleTax = "unknown;"; return "unknown;"; }
303 int index = getMostProbableTaxonomy(queryKmers);
305 if (m->control_pressed) { return tax; }
307 //bootstrap - to set confidenceScore
308 int numToSelect = queryKmers.size() / 8;
310 tax = bootstrapResults(queryKmers, index, numToSelect);
314 catch(exception& e) {
315 m->errorOut(e, "Bayesian", "getTaxonomy");
319 /**************************************************************************************************/
320 string Bayesian::bootstrapResults(vector<int> kmers, int tax, int numToSelect) {
323 map<int, int> confidenceScores;
325 //initialize confidences to 0
327 TaxNode seq = phyloTree->get(tax);
328 confidenceScores[tax] = 0;
330 while (seq.level != 0) { //while you are not at the root
331 seqIndex = seq.parent;
332 confidenceScores[seqIndex] = 0;
333 seq = phyloTree->get(seq.parent);
336 map<int, int>::iterator itBoot;
337 map<int, int>::iterator itBoot2;
338 map<int, int>::iterator itConvert;
340 for (int i = 0; i < iters; i++) {
341 if (m->control_pressed) { return "control"; }
344 for (int j = 0; j < numToSelect; j++) {
345 int index = int(rand() % kmers.size());
348 temp.push_back(kmers[index]);
352 int newTax = getMostProbableTaxonomy(temp);
354 TaxNode taxonomyTemp = phyloTree->get(newTax);
356 //add to confidence results
357 while (taxonomyTemp.level != 0) { //while you are not at the root
358 itBoot2 = confidenceScores.find(newTax); //is this a classification we already have a count on
360 if (itBoot2 != confidenceScores.end()) { //this is a classification we need a confidence for
364 newTax = taxonomyTemp.parent;
365 taxonomyTemp = phyloTree->get(newTax);
370 string confidenceTax = "";
373 int seqTaxIndex = tax;
374 TaxNode seqTax = phyloTree->get(tax);
376 while (seqTax.level != 0) { //while you are not at the root
378 itBoot2 = confidenceScores.find(seqTaxIndex); //is this a classification we already have a count on
381 if (itBoot2 != confidenceScores.end()) { //already in confidence scores
382 confidence = itBoot2->second;
385 if (((confidence/(float)iters) * 100) >= confidenceThreshold) {
386 confidenceTax = seqTax.name + "(" + toString(((confidence/(float)iters) * 100)) + ");" + confidenceTax;
387 simpleTax = seqTax.name + ";" + simpleTax;
390 seqTaxIndex = seqTax.parent;
391 seqTax = phyloTree->get(seqTax.parent);
394 if (confidenceTax == "") { confidenceTax = "unknown;"; simpleTax = "unknown;"; }
396 return confidenceTax;
399 catch(exception& e) {
400 m->errorOut(e, "Bayesian", "bootstrapResults");
404 /**************************************************************************************************/
405 int Bayesian::getMostProbableTaxonomy(vector<int> queryKmer) {
407 int indexofGenus = 0;
409 double maxProbability = -1000000.0;
410 //find taxonomy with highest probability that this sequence is from it
413 // cout << genusNodes.size() << endl;
416 for (int k = 0; k < genusNodes.size(); k++) {
417 //for each taxonomy calc its probability
419 double prob = 0.0000;
420 for (int i = 0; i < queryKmer.size(); i++) {
421 prob += wordGenusProb[queryKmer[i]][k];
424 // cout << phyloTree->get(genusNodes[k]).name << '\t' << prob << endl;
426 //is this the taxonomy with the greatest probability?
427 if (prob > maxProbability) {
428 indexofGenus = genusNodes[k];
429 maxProbability = prob;
436 catch(exception& e) {
437 m->errorOut(e, "Bayesian", "getMostProbableTaxonomy");
441 //********************************************************************************************************************
442 //if it is more probable that the reverse compliment kmers are in the template, then we assume the sequence is reversed.
443 bool Bayesian::isReversed(vector<int>& queryKmers){
445 bool reversed = false;
447 float reverseProb = 0;
449 for (int i = 0; i < queryKmers.size(); i++){
450 int kmer = queryKmers[i];
452 prob += WordPairDiffArr[kmer].prob;
453 reverseProb += WordPairDiffArr[kmer].reverseProb;
457 if (reverseProb > prob){ reversed = true; }
461 catch(exception& e) {
462 m->errorOut(e, "Bayesian", "isReversed");
466 //********************************************************************************************************************
467 int Bayesian::generateWordPairDiffArr(){
470 for (int i = 0; i < WordPairDiffArr.size(); i++) {
471 int reversedWord = kmer.getReverseKmerNumber(i);
472 WordPairDiffArr[i].reverseProb = WordPairDiffArr[reversedWord].prob;
476 }catch(exception& e) {
477 m->errorOut(e, "Bayesian", "generateWordPairDiffArr");
481 /*************************************************************************************************
482 map<string, int> Bayesian::parseTaxMap(string newTax) {
485 map<string, int> parsed;
487 newTax = newTax.substr(0, newTax.length()-1); //get rid of last ';'
491 while (newTax.find_first_of(';') != -1) {
492 individual = newTax.substr(0,newTax.find_first_of(';'));
493 newTax = newTax.substr(newTax.find_first_of(';')+1, newTax.length());
494 parsed[individual] = 1;
503 catch(exception& e) {
504 m->errorOut(e, "Bayesian", "parseTax");
508 /**************************************************************************************************/
509 void Bayesian::readProbFile(ifstream& in, ifstream& inNum, string inName, string inNumName) {
514 int pid, num, num2, processors;
515 vector<unsigned long long> positions;
516 vector<unsigned long long> positions2;
521 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
522 MPI_Comm_size(MPI_COMM_WORLD, &processors);
525 char inFileName[1024];
526 strcpy(inFileName, inNumName.c_str());
528 char inFileName2[1024];
529 strcpy(inFileName2, inName.c_str());
531 MPI_File_open(MPI_COMM_WORLD, inFileName, MPI_MODE_RDONLY, MPI_INFO_NULL, &inMPI); //comm, filename, mode, info, filepointer
532 MPI_File_open(MPI_COMM_WORLD, inFileName2, MPI_MODE_RDONLY, MPI_INFO_NULL, &inMPI2); //comm, filename, mode, info, filepointer
535 positions = m->setFilePosEachLine(inNumName, num);
536 positions2 = m->setFilePosEachLine(inName, num2);
538 for(int i = 1; i < processors; i++) {
539 MPI_Send(&num, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
540 MPI_Send(&positions[0], (num+1), MPI_LONG, i, tag, MPI_COMM_WORLD);
542 MPI_Send(&num2, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
543 MPI_Send(&positions2[0], (num2+1), MPI_LONG, i, tag, MPI_COMM_WORLD);
547 MPI_Recv(&num, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
548 positions.resize(num+1);
549 MPI_Recv(&positions[0], (num+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
551 MPI_Recv(&num2, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
552 positions2.resize(num2+1);
553 MPI_Recv(&positions2[0], (num2+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
557 int length = positions2[1] - positions2[0];
558 char* buf5 = new char[length];
560 MPI_File_read_at(inMPI2, positions2[0], buf5, length, MPI_CHAR, &status);
564 length = positions2[2] - positions2[1];
565 char* buf = new char[length];
567 MPI_File_read_at(inMPI2, positions2[1], buf, length, MPI_CHAR, &status);
569 string tempBuf = buf;
570 if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
573 istringstream iss (tempBuf,istringstream::in);
576 //initialze probabilities
577 wordGenusProb.resize(numKmers);
579 for (int j = 0; j < wordGenusProb.size(); j++) { wordGenusProb[j].resize(genusNodes.size()); }
582 vector<int> numbers; numbers.resize(numKmers);
584 vector<float> zeroCountProb; zeroCountProb.resize(numKmers);
585 WordPairDiffArr.resize(numKmers);
588 length = positions[1] - positions[0];
589 char* buf6 = new char[length];
591 MPI_File_read_at(inMPI2, positions[0], buf6, length, MPI_CHAR, &status);
595 for(int i=1;i<num;i++){
597 length = positions[i+1] - positions[i];
598 char* buf4 = new char[length];
600 MPI_File_read_at(inMPI, positions[i], buf4, length, MPI_CHAR, &status);
603 if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
606 istringstream iss (tempBuf,istringstream::in);
608 iss >> zeroCountProb[i] >> numbers[i] >> probTemp;
609 WordPairDiffArr[i].prob = tempProb;
613 MPI_File_close(&inMPI);
615 for(int i=2;i<num2;i++){
617 length = positions2[i+1] - positions2[i];
618 char* buf4 = new char[length];
620 MPI_File_read_at(inMPI2, positions2[i], buf4, length, MPI_CHAR, &status);
623 if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
626 istringstream iss (tempBuf,istringstream::in);
630 //set them all to zero value
631 for (int i = 0; i < genusNodes.size(); i++) {
632 wordGenusProb[kmer][i] = log(zeroCountProb[kmer] / (float) (genusTotals[i]+1));
635 //get probs for nonzero values
636 for (int i = 0; i < numbers[kmer]; i++) {
638 wordGenusProb[kmer][name] = prob;
642 MPI_File_close(&inMPI2);
643 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
646 string line = m->getline(in); m->gobble(in);
648 in >> numKmers; m->gobble(in);
649 //cout << threadID << '\t' << line << '\t' << numKmers << &in << '\t' << &inNum << '\t' << genusNodes.size() << endl;
650 //initialze probabilities
651 wordGenusProb.resize(numKmers);
653 for (int j = 0; j < wordGenusProb.size(); j++) { wordGenusProb[j].resize(genusNodes.size()); }
655 int kmer, name, count; count = 0;
656 vector<int> num; num.resize(numKmers);
658 vector<float> zeroCountProb; zeroCountProb.resize(numKmers);
659 WordPairDiffArr.resize(numKmers);
662 string line2 = m->getline(inNum); m->gobble(inNum);
664 //cout << threadID << '\t' << line2 << '\t' << this << endl;
666 inNum >> zeroCountProb[count] >> num[count] >> probTemp;
667 WordPairDiffArr[count].prob = probTemp;
670 //cout << threadID << '\t' << count << endl;
673 //cout << threadID << '\t' << "here1 " << &wordGenusProb << '\t' << &num << endl; //
674 //cout << threadID << '\t' << &genusTotals << '\t' << endl;
675 //cout << threadID << '\t' << genusNodes.size() << endl;
678 //cout << threadID << '\t' << kmer << endl;
679 //set them all to zero value
680 for (int i = 0; i < genusNodes.size(); i++) {
681 wordGenusProb[kmer][i] = log(zeroCountProb[kmer] / (float) (genusTotals[i]+1));
683 //cout << threadID << '\t' << num[kmer] << "here" << endl;
684 //get probs for nonzero values
685 for (int i = 0; i < num[kmer]; i++) {
687 wordGenusProb[kmer][name] = prob;
693 //cout << threadID << '\t' << "here" << endl;
696 catch(exception& e) {
697 m->errorOut(e, "Bayesian", "readProbFile");
701 /**************************************************************************************************/
702 bool Bayesian::checkReleaseDate(ifstream& file1, ifstream& file2, ifstream& file3, ifstream& file4) {
707 vector<string> lines;
708 lines.push_back(m->getline(file1));
709 lines.push_back(m->getline(file2));
710 lines.push_back(m->getline(file3));
711 lines.push_back(m->getline(file4));
713 //before we added this check
714 if ((lines[0][0] != '#') || (lines[1][0] != '#') || (lines[2][0] != '#') || (lines[3][0] != '#')) { good = false; }
717 for (int i = 0; i < lines.size(); i++) { lines[i] = lines[i].substr(1); }
719 //get mothurs current version
720 string version = m->getVersion();
722 vector<string> versionVector;
723 m->splitAtChar(version, versionVector, '.');
725 //check each files version
726 for (int i = 0; i < lines.size(); i++) {
727 vector<string> linesVector;
728 m->splitAtChar(lines[i], linesVector, '.');
730 if (versionVector.size() != linesVector.size()) { good = false; break; }
732 for (int j = 0; j < versionVector.size(); j++) {
734 convert(versionVector[j], num1);
735 convert(linesVector[j], num2);
737 //if mothurs version is newer than this files version, then we want to remake it
738 if (num1 > num2) { good = false; break; }
742 if (!good) { break; }
746 if (!good) { file1.close(); file2.close(); file3.close(); file4.close(); }
747 else { file1.seekg(0); file2.seekg(0); file3.seekg(0); file4.seekg(0); }
751 catch(exception& e) {
752 m->errorOut(e, "Bayesian", "checkReleaseDate");
756 /**************************************************************************************************/