5 * Created by westcott on 11/3/09.
6 * Copyright 2009 Schloss Lab. All rights reserved.
12 #include "phylosummary.h"
14 /**************************************************************************************************/
15 Bayesian::Bayesian(string tfile, string tempFile, string method, int ksize, int cutoff, int i) :
16 Classify(), kmerSize(ksize), confidenceThreshold(cutoff), iters(i) {
19 /************calculate the probablity that each word will be in a specific taxonomy*************/
20 string tfileroot = tfile.substr(0,tfile.find_last_of(".")+1);
21 string tempfileroot = getRootName(getSimpleName(tempFile));
22 string phyloTreeName = tfileroot + "tree.train";
23 string phyloTreeSumName = tfileroot + "tree.sum";
24 string probFileName = tfileroot + tempfileroot + char('0'+ kmerSize) + "mer.prob";
25 string probFileName2 = tfileroot + tempfileroot + char('0'+ kmerSize) + "mer.numNonZero";
30 ifstream phyloTreeTest(phyloTreeName.c_str());
31 ifstream probFileTest2(probFileName2.c_str());
32 ifstream probFileTest(probFileName.c_str());
33 ifstream probFileTest3(phyloTreeSumName.c_str());
35 int start = time(NULL);
37 if(probFileTest && probFileTest2 && phyloTreeTest && probFileTest3){
38 m->mothurOut("Reading template taxonomy... "); cout.flush();
40 phyloTree = new PhyloTree(phyloTreeTest, phyloTreeName);
42 m->mothurOut("DONE."); m->mothurOutEndLine();
44 genusNodes = phyloTree->getGenusNodes();
45 genusTotals = phyloTree->getGenusTotals();
47 m->mothurOut("Reading template probabilities... "); cout.flush();
48 readProbFile(probFileTest, probFileTest2, probFileName, probFileName2);
52 //create search database and names vector
53 generateDatabaseAndNames(tfile, tempFile, method, ksize, 0.0, 0.0, 0.0, 0.0);
55 //prevents errors caused by creating shortcut files if you had an error in the sanity check.
56 if (m->control_pressed) { remove(phyloTreeName.c_str()); remove(probFileName.c_str()); remove(probFileName2.c_str()); }
58 genusNodes = phyloTree->getGenusNodes();
59 genusTotals = phyloTree->getGenusTotals();
61 m->mothurOut("Calculating template taxonomy tree... "); cout.flush();
63 phyloTree->printTreeNodes(phyloTreeName);
65 m->mothurOut("DONE."); m->mothurOutEndLine();
67 m->mothurOut("Calculating template probabilities... "); cout.flush();
69 numKmers = database->getMaxKmer() + 1;
71 //initialze probabilities
72 wordGenusProb.resize(numKmers);
74 for (int j = 0; j < wordGenusProb.size(); j++) { wordGenusProb[j].resize(genusNodes.size()); }
81 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
87 openOutputFile(probFileName, out);
89 out << numKmers << endl;
91 openOutputFile(probFileName2, out2);
99 for (int i = 0; i < numKmers; i++) {
100 if (m->control_pressed) { break; }
103 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
114 vector<int> seqsWithWordi = database->getSequencesWithKmer(i);
117 for (int k = 0; k < genusNodes.size(); k++) { count[genusNodes[k]] = 0; }
119 //for each sequence with that word
120 for (int j = 0; j < seqsWithWordi.size(); j++) {
121 int temp = phyloTree->getIndex(names[seqsWithWordi[j]]);
122 count[temp]++; //increment count of seq in this genus who have this word
125 //probabilityInTemplate = (# of seqs with that word in template + 0.05) / (total number of seqs in template + 1);
126 float probabilityInTemplate = (seqsWithWordi.size() + 0.50) / (float) (names.size() + 1);
129 for (int k = 0; k < genusNodes.size(); k++) {
130 //probabilityInThisTaxonomy = (# of seqs with that word in this taxonomy + probabilityInTemplate) / (total number of seqs in this taxonomy + 1);
131 wordGenusProb[i][k] = log((count[genusNodes[k]] + probabilityInTemplate) / (float) (genusTotals[k] + 1));
132 if (count[genusNodes[k]] != 0) {
135 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
140 out << k << '\t' << wordGenusProb[i][k] << '\t';
151 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
157 out2 << probabilityInTemplate << '\t' << numNotZero << endl;
165 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
177 //read in new phylotree with less info. - its faster
178 ifstream phyloTreeTest(phyloTreeName.c_str());
181 phyloTree = new PhyloTree(phyloTreeTest, phyloTreeName);
185 m->mothurOut("DONE."); m->mothurOutEndLine();
186 m->mothurOut("It took " + toString(time(NULL) - start) + " seconds get probabilities. "); m->mothurOutEndLine();
188 catch(exception& e) {
189 m->errorOut(e, "Bayesian", "Bayesian");
193 /**************************************************************************************************/
194 Bayesian::~Bayesian() {
197 if (database != NULL) { delete database; }
199 catch(exception& e) {
200 m->errorOut(e, "Bayesian", "~Bayesian");
205 /**************************************************************************************************/
206 string Bayesian::getTaxonomy(Sequence* seq) {
211 //get words contained in query
212 //getKmerString returns a string where the index in the string is hte kmer number
213 //and the character at that index can be converted to be the number of times that kmer was seen
215 string queryKmerString = kmer.getKmerString(seq->getUnaligned());
217 vector<int> queryKmers;
218 for (int i = 0; i < queryKmerString.length(); i++) {
219 if (queryKmerString[i] != '!') { //this kmer is in the query
220 queryKmers.push_back(i);
224 if (queryKmers.size() == 0) { m->mothurOut(seq->getName() + "is bad."); m->mothurOutEndLine(); return "bad seq"; }
226 int index = getMostProbableTaxonomy(queryKmers);
228 if (m->control_pressed) { return tax; }
229 //cout << seq->getName() << '\t' << index << endl;
230 //bootstrap - to set confidenceScore
231 int numToSelect = queryKmers.size() / 8;
232 tax = bootstrapResults(queryKmers, index, numToSelect);
236 catch(exception& e) {
237 m->errorOut(e, "Bayesian", "getTaxonomy");
241 /**************************************************************************************************/
242 string Bayesian::bootstrapResults(vector<int> kmers, int tax, int numToSelect) {
245 map<int, int> confidenceScores;
247 map<int, int>::iterator itBoot;
248 map<int, int>::iterator itBoot2;
249 map<int, int>::iterator itConvert;
251 for (int i = 0; i < iters; i++) {
252 if (m->control_pressed) { return "control"; }
256 for (int j = 0; j < numToSelect; j++) {
257 int index = int(rand() % kmers.size());
260 temp.push_back(kmers[index]);
264 int newTax = getMostProbableTaxonomy(temp);
265 TaxNode taxonomyTemp = phyloTree->get(newTax);
267 //add to confidence results
268 while (taxonomyTemp.level != 0) { //while you are not at the root
270 itBoot2 = confidenceScores.find(newTax); //is this a classification we already have a count on
272 if (itBoot2 == confidenceScores.end()) { //not already in confidence scores
273 confidenceScores[newTax] = 1;
275 confidenceScores[newTax]++;
278 newTax = taxonomyTemp.parent;
279 taxonomyTemp = phyloTree->get(newTax);
284 string confidenceTax = "";
287 int seqTaxIndex = tax;
288 TaxNode seqTax = phyloTree->get(tax);
290 while (seqTax.level != 0) { //while you are not at the root
292 itBoot2 = confidenceScores.find(seqTaxIndex); //is this a classification we already have a count on
295 if (itBoot2 != confidenceScores.end()) { //already in confidence scores
296 confidence = confidenceScores[seqTaxIndex];
299 if (((confidence/(float)iters) * 100) >= confidenceThreshold) {
300 confidenceTax = seqTax.name + "(" + toString(((confidence/(float)iters) * 100)) + ");" + confidenceTax;
301 simpleTax = seqTax.name + ";" + simpleTax;
304 seqTaxIndex = seqTax.parent;
305 seqTax = phyloTree->get(seqTax.parent);
308 if (confidenceTax == "") { confidenceTax = "unclassified;"; simpleTax = "unclassified;"; }
309 return confidenceTax;
312 catch(exception& e) {
313 m->errorOut(e, "Bayesian", "bootstrapResults");
317 /**************************************************************************************************/
318 int Bayesian::getMostProbableTaxonomy(vector<int> queryKmer) {
320 int indexofGenus = 0;
322 double maxProbability = -1000000.0;
323 //find taxonomy with highest probability that this sequence is from it
324 for (int k = 0; k < genusNodes.size(); k++) {
325 //for each taxonomy calc its probability
327 for (int i = 0; i < queryKmer.size(); i++) {
328 prob += wordGenusProb[queryKmer[i]][k];
331 //is this the taxonomy with the greatest probability?
332 if (prob > maxProbability) {
333 indexofGenus = genusNodes[k];
334 maxProbability = prob;
340 catch(exception& e) {
341 m->errorOut(e, "Bayesian", "getMostProbableTaxonomy");
345 /*************************************************************************************************
346 map<string, int> Bayesian::parseTaxMap(string newTax) {
349 map<string, int> parsed;
351 newTax = newTax.substr(0, newTax.length()-1); //get rid of last ';'
355 while (newTax.find_first_of(';') != -1) {
356 individual = newTax.substr(0,newTax.find_first_of(';'));
357 newTax = newTax.substr(newTax.find_first_of(';')+1, newTax.length());
358 parsed[individual] = 1;
367 catch(exception& e) {
368 m->errorOut(e, "Bayesian", "parseTax");
372 /**************************************************************************************************/
373 void Bayesian::readProbFile(ifstream& in, ifstream& inNum, string inName, string inNumName) {
378 int pid, num, num2, processors;
379 vector<unsigned long int> positions;
380 vector<unsigned long int> positions2;
385 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
386 MPI_Comm_size(MPI_COMM_WORLD, &processors);
389 char inFileName[1024];
390 strcpy(inFileName, inNumName.c_str());
392 char inFileName2[1024];
393 strcpy(inFileName2, inName.c_str());
395 MPI_File_open(MPI_COMM_WORLD, inFileName, MPI_MODE_RDONLY, MPI_INFO_NULL, &inMPI); //comm, filename, mode, info, filepointer
396 MPI_File_open(MPI_COMM_WORLD, inFileName2, MPI_MODE_RDONLY, MPI_INFO_NULL, &inMPI2); //comm, filename, mode, info, filepointer
399 positions = setFilePosEachLine(inNumName, num);
400 positions2 = setFilePosEachLine(inName, num2);
402 for(int i = 1; i < processors; i++) {
403 MPI_Send(&num, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
404 MPI_Send(&positions[0], (num+1), MPI_LONG, i, tag, MPI_COMM_WORLD);
406 MPI_Send(&num2, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
407 MPI_Send(&positions2[0], (num2+1), MPI_LONG, i, tag, MPI_COMM_WORLD);
411 MPI_Recv(&num, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
412 positions.resize(num+1);
413 MPI_Recv(&positions[0], (num+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
415 MPI_Recv(&num2, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
416 positions2.resize(num2+1);
417 MPI_Recv(&positions2[0], (num2+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
421 int length = positions2[1] - positions2[0];
422 char* buf = new char[length];
424 MPI_File_read_at(inMPI2, positions2[0], buf, length, MPI_CHAR, &status);
426 string tempBuf = buf;
427 if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
430 istringstream iss (tempBuf,istringstream::in);
433 //initialze probabilities
434 wordGenusProb.resize(numKmers);
436 for (int j = 0; j < wordGenusProb.size(); j++) { wordGenusProb[j].resize(genusNodes.size()); }
439 vector<int> numbers; numbers.resize(numKmers);
441 vector<float> zeroCountProb; zeroCountProb.resize(numKmers);
444 for(int i=0;i<num;i++){
446 length = positions[i+1] - positions[i];
447 char* buf4 = new char[length];
449 MPI_File_read_at(inMPI, positions[i], buf4, length, MPI_CHAR, &status);
452 if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
455 istringstream iss (tempBuf,istringstream::in);
456 iss >> zeroCountProb[i] >> numbers[i];
459 MPI_File_close(&inMPI);
461 for(int i=1;i<num2;i++){
463 length = positions2[i+1] - positions2[i];
464 char* buf4 = new char[length];
466 MPI_File_read_at(inMPI2, positions2[i], buf4, length, MPI_CHAR, &status);
469 if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
472 istringstream iss (tempBuf,istringstream::in);
476 //set them all to zero value
477 for (int i = 0; i < genusNodes.size(); i++) {
478 wordGenusProb[kmer][i] = log(zeroCountProb[kmer] / (float) (genusTotals[i]+1));
481 //get probs for nonzero values
482 for (int i = 0; i < numbers[kmer]; i++) {
484 wordGenusProb[kmer][name] = prob;
488 MPI_File_close(&inMPI2);
489 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
492 in >> numKmers; gobble(in);
494 //initialze probabilities
495 wordGenusProb.resize(numKmers);
497 for (int j = 0; j < wordGenusProb.size(); j++) { wordGenusProb[j].resize(genusNodes.size()); }
499 int kmer, name, count; count = 0;
500 vector<int> num; num.resize(numKmers);
502 vector<float> zeroCountProb; zeroCountProb.resize(numKmers);
505 inNum >> zeroCountProb[count] >> num[count];
514 //set them all to zero value
515 for (int i = 0; i < genusNodes.size(); i++) {
516 wordGenusProb[kmer][i] = log(zeroCountProb[kmer] / (float) (genusTotals[i]+1));
519 //get probs for nonzero values
520 for (int i = 0; i < num[kmer]; i++) {
522 wordGenusProb[kmer][name] = prob;
531 catch(exception& e) {
532 m->errorOut(e, "Bayesian", "readProbFile");
536 /**************************************************************************************************/