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;
23 if (baseName == "saved") { baseName = rdb->getSavedReference(); }
25 string baseTName = tfile;
26 if (baseTName == "saved") { baseTName = rdb->getSavedTaxonomy(); }
28 /************calculate the probablity that each word will be in a specific taxonomy*************/
29 string tfileroot = baseTName.substr(0,baseTName.find_last_of(".")+1);
30 string tempfileroot = m->getRootName(m->getSimpleName(baseName));
31 string phyloTreeName = tfileroot + "tree.train";
32 string phyloTreeSumName = tfileroot + "tree.sum";
33 string probFileName = tfileroot + tempfileroot + char('0'+ kmerSize) + "mer.prob";
34 string probFileName2 = tfileroot + tempfileroot + char('0'+ kmerSize) + "mer.numNonZero";
39 ifstream phyloTreeTest(phyloTreeName.c_str());
40 ifstream probFileTest2(probFileName2.c_str());
41 ifstream probFileTest(probFileName.c_str());
42 ifstream probFileTest3(phyloTreeSumName.c_str());
44 int start = time(NULL);
46 //if they are there make sure they were created after this release date
47 bool FilesGood = false;
48 if(probFileTest && probFileTest2 && phyloTreeTest && probFileTest3){
49 FilesGood = checkReleaseDate(probFileTest, probFileTest2, phyloTreeTest, probFileTest3);
52 //if you want to save, but you dont need to calculate then just read
53 if (rdb->save && probFileTest && probFileTest2 && phyloTreeTest && probFileTest3 && FilesGood && (tempFile != "saved")) {
55 m->openInputFile(tempFile, saveIn);
57 while (!saveIn.eof()) {
58 Sequence temp(saveIn);
61 rdb->referenceSeqs.push_back(temp);
66 if(probFileTest && probFileTest2 && phyloTreeTest && probFileTest3 && FilesGood){
67 if (tempFile == "saved") { m->mothurOutEndLine(); m->mothurOut("Using sequences from " + rdb->getSavedReference() + " that are saved in memory."); m->mothurOutEndLine(); }
69 m->mothurOut("Reading template taxonomy... "); cout.flush();
71 phyloTree = new PhyloTree(phyloTreeTest, phyloTreeName);
73 m->mothurOut("DONE."); m->mothurOutEndLine();
75 genusNodes = phyloTree->getGenusNodes();
76 genusTotals = phyloTree->getGenusTotals();
78 if (tfile == "saved") {
79 m->mothurOutEndLine(); m->mothurOut("Using probabilties from " + rdb->getSavedTaxonomy() + " that are saved in memory... "); cout.flush();;
80 wordGenusProb = rdb->wordGenusProb;
82 m->mothurOut("Reading template probabilities... "); cout.flush();
83 readProbFile(probFileTest, probFileTest2, probFileName, probFileName2);
87 if (rdb->save) { rdb->wordGenusProb = wordGenusProb; }
90 //create search database and names vector
91 generateDatabaseAndNames(tfile, tempFile, method, ksize, 0.0, 0.0, 0.0, 0.0);
93 //prevents errors caused by creating shortcut files if you had an error in the sanity check.
94 if (m->control_pressed) { m->mothurRemove(phyloTreeName); m->mothurRemove(probFileName); m->mothurRemove(probFileName2); }
96 genusNodes = phyloTree->getGenusNodes();
97 genusTotals = phyloTree->getGenusTotals();
99 m->mothurOut("Calculating template taxonomy tree... "); cout.flush();
101 phyloTree->printTreeNodes(phyloTreeName);
103 m->mothurOut("DONE."); m->mothurOutEndLine();
105 m->mothurOut("Calculating template probabilities... "); cout.flush();
107 numKmers = database->getMaxKmer() + 1;
109 //initialze probabilities
110 wordGenusProb.resize(numKmers);
111 //cout << numKmers << '\t' << genusNodes.size() << endl;
112 for (int j = 0; j < wordGenusProb.size(); j++) { wordGenusProb[j].resize(genusNodes.size()); }
113 //cout << numKmers << '\t' << genusNodes.size() << endl;
119 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
125 m->openOutputFile(probFileName, out);
127 //output mothur version
128 out << "#" << m->getVersion() << endl;
130 out << numKmers << endl;
132 m->openOutputFile(probFileName2, out2);
134 //output mothur version
135 out2 << "#" << m->getVersion() << endl;
143 for (int i = 0; i < numKmers; i++) {
144 if (m->control_pressed) { break; }
147 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
158 vector<int> seqsWithWordi = database->getSequencesWithKmer(i);
161 for (int k = 0; k < genusNodes.size(); k++) { count[genusNodes[k]] = 0; }
163 //for each sequence with that word
164 for (int j = 0; j < seqsWithWordi.size(); j++) {
165 int temp = phyloTree->getIndex(names[seqsWithWordi[j]]);
166 count[temp]++; //increment count of seq in this genus who have this word
169 //probabilityInTemplate = (# of seqs with that word in template + 0.50) / (total number of seqs in template + 1);
170 float probabilityInTemplate = (seqsWithWordi.size() + 0.50) / (float) (names.size() + 1);
173 for (int k = 0; k < genusNodes.size(); k++) {
174 //probabilityInThisTaxonomy = (# of seqs with that word in this taxonomy + probabilityInTemplate) / (total number of seqs in this taxonomy + 1);
177 wordGenusProb[i][k] = log((count[genusNodes[k]] + probabilityInTemplate) / (float) (genusTotals[k] + 1));
179 if (count[genusNodes[k]] != 0) {
182 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
187 out << k << '\t' << wordGenusProb[i][k] << '\t';
198 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
204 out2 << probabilityInTemplate << '\t' << numNotZero << endl;
212 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
224 //read in new phylotree with less info. - its faster
225 ifstream phyloTreeTest(phyloTreeName.c_str());
228 phyloTree = new PhyloTree(phyloTreeTest, phyloTreeName);
231 if (rdb->save) { rdb->wordGenusProb = wordGenusProb; }
235 m->mothurOut("DONE."); m->mothurOutEndLine();
236 m->mothurOut("It took " + toString(time(NULL) - start) + " seconds get probabilities. "); m->mothurOutEndLine();
238 catch(exception& e) {
239 m->errorOut(e, "Bayesian", "Bayesian");
243 /**************************************************************************************************/
244 Bayesian::~Bayesian() {
248 if (database != NULL) { delete database; }
250 catch(exception& e) {
251 m->errorOut(e, "Bayesian", "~Bayesian");
256 /**************************************************************************************************/
257 string Bayesian::getTaxonomy(Sequence* seq) {
262 //get words contained in query
263 //getKmerString returns a string where the index in the string is hte kmer number
264 //and the character at that index can be converted to be the number of times that kmer was seen
266 string queryKmerString = kmer.getKmerString(seq->getUnaligned());
268 vector<int> queryKmers;
269 for (int i = 0; i < queryKmerString.length()-1; i++) { // the -1 is to ignore any kmer with an N in it
270 if (queryKmerString[i] != '!') { //this kmer is in the query
271 queryKmers.push_back(i);
275 if (queryKmers.size() == 0) { m->mothurOut(seq->getName() + "is bad."); m->mothurOutEndLine(); return "bad seq"; }
278 int index = getMostProbableTaxonomy(queryKmers);
280 if (m->control_pressed) { return tax; }
282 //bootstrap - to set confidenceScore
283 int numToSelect = queryKmers.size() / 8;
285 tax = bootstrapResults(queryKmers, index, numToSelect);
289 catch(exception& e) {
290 m->errorOut(e, "Bayesian", "getTaxonomy");
294 /**************************************************************************************************/
295 string Bayesian::bootstrapResults(vector<int> kmers, int tax, int numToSelect) {
298 map<int, int> confidenceScores;
300 //initialize confidences to 0
302 TaxNode seq = phyloTree->get(tax);
303 confidenceScores[tax] = 0;
305 while (seq.level != 0) { //while you are not at the root
306 seqIndex = seq.parent;
307 confidenceScores[seqIndex] = 0;
308 seq = phyloTree->get(seq.parent);
311 map<int, int>::iterator itBoot;
312 map<int, int>::iterator itBoot2;
313 map<int, int>::iterator itConvert;
315 for (int i = 0; i < iters; i++) {
316 if (m->control_pressed) { return "control"; }
319 for (int j = 0; j < numToSelect; j++) {
320 int index = int(rand() % kmers.size());
323 temp.push_back(kmers[index]);
327 int newTax = getMostProbableTaxonomy(temp);
329 TaxNode taxonomyTemp = phyloTree->get(newTax);
331 //add to confidence results
332 while (taxonomyTemp.level != 0) { //while you are not at the root
333 itBoot2 = confidenceScores.find(newTax); //is this a classification we already have a count on
335 if (itBoot2 != confidenceScores.end()) { //this is a classification we need a confidence for
339 newTax = taxonomyTemp.parent;
340 taxonomyTemp = phyloTree->get(newTax);
345 string confidenceTax = "";
348 int seqTaxIndex = tax;
349 TaxNode seqTax = phyloTree->get(tax);
351 while (seqTax.level != 0) { //while you are not at the root
353 itBoot2 = confidenceScores.find(seqTaxIndex); //is this a classification we already have a count on
356 if (itBoot2 != confidenceScores.end()) { //already in confidence scores
357 confidence = itBoot2->second;
360 if (((confidence/(float)iters) * 100) >= confidenceThreshold) {
361 confidenceTax = seqTax.name + "(" + toString(((confidence/(float)iters) * 100)) + ");" + confidenceTax;
362 simpleTax = seqTax.name + ";" + simpleTax;
365 seqTaxIndex = seqTax.parent;
366 seqTax = phyloTree->get(seqTax.parent);
369 if (confidenceTax == "") { confidenceTax = "unclassified;"; simpleTax = "unclassified;"; }
370 return confidenceTax;
373 catch(exception& e) {
374 m->errorOut(e, "Bayesian", "bootstrapResults");
378 /**************************************************************************************************/
379 int Bayesian::getMostProbableTaxonomy(vector<int> queryKmer) {
381 int indexofGenus = 0;
383 double maxProbability = -1000000.0;
384 //find taxonomy with highest probability that this sequence is from it
387 // cout << genusNodes.size() << endl;
390 for (int k = 0; k < genusNodes.size(); k++) {
391 //for each taxonomy calc its probability
393 double prob = 0.0000;
394 for (int i = 0; i < queryKmer.size(); i++) {
395 prob += wordGenusProb[queryKmer[i]][k];
398 // cout << phyloTree->get(genusNodes[k]).name << '\t' << prob << endl;
400 //is this the taxonomy with the greatest probability?
401 if (prob > maxProbability) {
402 indexofGenus = genusNodes[k];
403 maxProbability = prob;
410 catch(exception& e) {
411 m->errorOut(e, "Bayesian", "getMostProbableTaxonomy");
415 /*************************************************************************************************
416 map<string, int> Bayesian::parseTaxMap(string newTax) {
419 map<string, int> parsed;
421 newTax = newTax.substr(0, newTax.length()-1); //get rid of last ';'
425 while (newTax.find_first_of(';') != -1) {
426 individual = newTax.substr(0,newTax.find_first_of(';'));
427 newTax = newTax.substr(newTax.find_first_of(';')+1, newTax.length());
428 parsed[individual] = 1;
437 catch(exception& e) {
438 m->errorOut(e, "Bayesian", "parseTax");
442 /**************************************************************************************************/
443 void Bayesian::readProbFile(ifstream& in, ifstream& inNum, string inName, string inNumName) {
448 int pid, num, num2, processors;
449 vector<unsigned long long> positions;
450 vector<unsigned long long> positions2;
455 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
456 MPI_Comm_size(MPI_COMM_WORLD, &processors);
459 char inFileName[1024];
460 strcpy(inFileName, inNumName.c_str());
462 char inFileName2[1024];
463 strcpy(inFileName2, inName.c_str());
465 MPI_File_open(MPI_COMM_WORLD, inFileName, MPI_MODE_RDONLY, MPI_INFO_NULL, &inMPI); //comm, filename, mode, info, filepointer
466 MPI_File_open(MPI_COMM_WORLD, inFileName2, MPI_MODE_RDONLY, MPI_INFO_NULL, &inMPI2); //comm, filename, mode, info, filepointer
469 positions = m->setFilePosEachLine(inNumName, num);
470 positions2 = m->setFilePosEachLine(inName, num2);
472 for(int i = 1; i < processors; i++) {
473 MPI_Send(&num, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
474 MPI_Send(&positions[0], (num+1), MPI_LONG, i, tag, MPI_COMM_WORLD);
476 MPI_Send(&num2, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
477 MPI_Send(&positions2[0], (num2+1), MPI_LONG, i, tag, MPI_COMM_WORLD);
481 MPI_Recv(&num, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
482 positions.resize(num+1);
483 MPI_Recv(&positions[0], (num+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
485 MPI_Recv(&num2, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
486 positions2.resize(num2+1);
487 MPI_Recv(&positions2[0], (num2+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
491 int length = positions2[1] - positions2[0];
492 char* buf5 = new char[length];
494 MPI_File_read_at(inMPI2, positions2[0], buf5, length, MPI_CHAR, &status);
498 length = positions2[2] - positions2[1];
499 char* buf = new char[length];
501 MPI_File_read_at(inMPI2, positions2[1], buf, length, MPI_CHAR, &status);
503 string tempBuf = buf;
504 if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
507 istringstream iss (tempBuf,istringstream::in);
510 //initialze probabilities
511 wordGenusProb.resize(numKmers);
513 for (int j = 0; j < wordGenusProb.size(); j++) { wordGenusProb[j].resize(genusNodes.size()); }
516 vector<int> numbers; numbers.resize(numKmers);
518 vector<float> zeroCountProb; zeroCountProb.resize(numKmers);
521 length = positions[1] - positions[0];
522 char* buf6 = new char[length];
524 MPI_File_read_at(inMPI2, positions[0], buf6, length, MPI_CHAR, &status);
528 for(int i=1;i<num;i++){
530 length = positions[i+1] - positions[i];
531 char* buf4 = new char[length];
533 MPI_File_read_at(inMPI, positions[i], buf4, length, MPI_CHAR, &status);
536 if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
539 istringstream iss (tempBuf,istringstream::in);
540 iss >> zeroCountProb[i] >> numbers[i];
543 MPI_File_close(&inMPI);
545 for(int i=2;i<num2;i++){
547 length = positions2[i+1] - positions2[i];
548 char* buf4 = new char[length];
550 MPI_File_read_at(inMPI2, positions2[i], buf4, length, MPI_CHAR, &status);
553 if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
556 istringstream iss (tempBuf,istringstream::in);
560 //set them all to zero value
561 for (int i = 0; i < genusNodes.size(); i++) {
562 wordGenusProb[kmer][i] = log(zeroCountProb[kmer] / (float) (genusTotals[i]+1));
565 //get probs for nonzero values
566 for (int i = 0; i < numbers[kmer]; i++) {
568 wordGenusProb[kmer][name] = prob;
572 MPI_File_close(&inMPI2);
573 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
576 string line = m->getline(in); m->gobble(in);
578 in >> numKmers; m->gobble(in);
579 //cout << threadID << '\t' << line << '\t' << numKmers << &in << '\t' << &inNum << '\t' << genusNodes.size() << endl;
580 //initialze probabilities
581 wordGenusProb.resize(numKmers);
583 for (int j = 0; j < wordGenusProb.size(); j++) { wordGenusProb[j].resize(genusNodes.size()); }
585 int kmer, name, count; count = 0;
586 vector<int> num; num.resize(numKmers);
588 vector<float> zeroCountProb; zeroCountProb.resize(numKmers);
591 string line2 = m->getline(inNum); m->gobble(inNum);
592 //cout << threadID << '\t' << line2 << '\t' << this << endl;
594 inNum >> zeroCountProb[count] >> num[count];
597 //cout << threadID << '\t' << count << endl;
600 //cout << threadID << '\t' << "here1 " << &wordGenusProb << '\t' << &num << endl; //
601 //cout << threadID << '\t' << &genusTotals << '\t' << endl;
602 //cout << threadID << '\t' << genusNodes.size() << endl;
605 //cout << threadID << '\t' << kmer << endl;
606 //set them all to zero value
607 for (int i = 0; i < genusNodes.size(); i++) {
608 wordGenusProb[kmer][i] = log(zeroCountProb[kmer] / (float) (genusTotals[i]+1));
610 //cout << threadID << '\t' << num[kmer] << "here" << endl;
611 //get probs for nonzero values
612 for (int i = 0; i < num[kmer]; i++) {
614 wordGenusProb[kmer][name] = prob;
620 //cout << threadID << '\t' << "here" << endl;
623 catch(exception& e) {
624 m->errorOut(e, "Bayesian", "readProbFile");
628 /**************************************************************************************************/
629 bool Bayesian::checkReleaseDate(ifstream& file1, ifstream& file2, ifstream& file3, ifstream& file4) {
634 vector<string> lines;
635 lines.push_back(m->getline(file1));
636 lines.push_back(m->getline(file2));
637 lines.push_back(m->getline(file3));
638 lines.push_back(m->getline(file4));
640 //before we added this check
641 if ((lines[0][0] != '#') || (lines[1][0] != '#') || (lines[2][0] != '#') || (lines[3][0] != '#')) { good = false; }
644 for (int i = 0; i < lines.size(); i++) { lines[i] = lines[i].substr(1); }
646 //get mothurs current version
647 string version = m->getVersion();
649 vector<string> versionVector;
650 m->splitAtChar(version, versionVector, '.');
652 //check each files version
653 for (int i = 0; i < lines.size(); i++) {
654 vector<string> linesVector;
655 m->splitAtChar(lines[i], linesVector, '.');
657 if (versionVector.size() != linesVector.size()) { good = false; break; }
659 for (int j = 0; j < versionVector.size(); j++) {
661 convert(versionVector[j], num1);
662 convert(linesVector[j], num2);
664 //if mothurs version is newer than this files version, then we want to remake it
665 if (num1 > num2) { good = false; break; }
669 if (!good) { break; }
673 if (!good) { file1.close(); file2.close(); file3.close(); file4.close(); }
674 else { file1.seekg(0); file2.seekg(0); file3.seekg(0); file4.seekg(0); }
678 catch(exception& e) {
679 m->errorOut(e, "Bayesian", "checkReleaseDate");
683 /**************************************************************************************************/