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 probFileName = tfileroot + tempfileroot + char('0'+ kmerSize) + "mer.prob";
24 string probFileName2 = tfileroot + tempfileroot + char('0'+ kmerSize) + "mer.numNonZero";
29 ifstream phyloTreeTest(phyloTreeName.c_str());
30 ifstream probFileTest2(probFileName2.c_str());
31 ifstream probFileTest(probFileName.c_str());
33 int start = time(NULL);
35 if(probFileTest && probFileTest2 && phyloTreeTest){
36 m->mothurOut("Reading template taxonomy... "); cout.flush();
38 phyloTree = new PhyloTree(phyloTreeTest, phyloTreeName);
40 m->mothurOut("DONE."); m->mothurOutEndLine();
42 genusNodes = phyloTree->getGenusNodes();
43 genusTotals = phyloTree->getGenusTotals();
45 m->mothurOut("Reading template probabilities... "); cout.flush();
46 readProbFile(probFileTest, probFileTest2, probFileName, probFileName2);
50 //create search database and names vector
51 generateDatabaseAndNames(tfile, tempFile, method, ksize, 0.0, 0.0, 0.0, 0.0);
53 //prevents errors caused by creating shortcut files if you had an error in the sanity check.
54 if (m->control_pressed) { remove(phyloTreeName.c_str()); remove(probFileName.c_str()); remove(probFileName2.c_str()); }
56 genusNodes = phyloTree->getGenusNodes();
57 genusTotals = phyloTree->getGenusTotals();
59 m->mothurOut("Calculating template taxonomy tree... "); cout.flush();
61 phyloTree->printTreeNodes(phyloTreeName);
63 m->mothurOut("DONE."); m->mothurOutEndLine();
65 m->mothurOut("Calculating template probabilities... "); cout.flush();
67 numKmers = database->getMaxKmer() + 1;
69 //initialze probabilities
70 wordGenusProb.resize(numKmers);
72 for (int j = 0; j < wordGenusProb.size(); j++) { wordGenusProb[j].resize(genusNodes.size()); }
79 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
85 openOutputFile(probFileName, out);
87 out << numKmers << endl;
89 openOutputFile(probFileName2, out2);
97 for (int i = 0; i < numKmers; i++) {
98 if (m->control_pressed) { break; }
101 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
112 vector<int> seqsWithWordi = database->getSequencesWithKmer(i);
115 for (int k = 0; k < genusNodes.size(); k++) { count[genusNodes[k]] = 0; }
117 //for each sequence with that word
118 for (int j = 0; j < seqsWithWordi.size(); j++) {
119 int temp = phyloTree->getIndex(names[seqsWithWordi[j]]);
120 count[temp]++; //increment count of seq in this genus who have this word
123 //probabilityInTemplate = (# of seqs with that word in template + 0.05) / (total number of seqs in template + 1);
124 float probabilityInTemplate = (seqsWithWordi.size() + 0.50) / (float) (names.size() + 1);
127 for (int k = 0; k < genusNodes.size(); k++) {
128 //probabilityInThisTaxonomy = (# of seqs with that word in this taxonomy + probabilityInTemplate) / (total number of seqs in this taxonomy + 1);
129 wordGenusProb[i][k] = log((count[genusNodes[k]] + probabilityInTemplate) / (float) (genusTotals[k] + 1));
130 if (count[genusNodes[k]] != 0) {
133 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
138 out << k << '\t' << wordGenusProb[i][k] << '\t';
149 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
155 out2 << probabilityInTemplate << '\t' << numNotZero << endl;
163 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
175 //read in new phylotree with less info. - its faster
176 ifstream phyloTreeTest(phyloTreeName.c_str());
179 phyloTree = new PhyloTree(phyloTreeTest, phyloTreeName);
183 m->mothurOut("DONE."); m->mothurOutEndLine();
184 m->mothurOut("It took " + toString(time(NULL) - start) + " seconds get probabilities. "); m->mothurOutEndLine();
186 catch(exception& e) {
187 m->errorOut(e, "Bayesian", "Bayesian");
191 /**************************************************************************************************/
192 Bayesian::~Bayesian() {
195 if (database != NULL) { delete database; }
197 catch(exception& e) {
198 m->errorOut(e, "Bayesian", "~Bayesian");
203 /**************************************************************************************************/
204 string Bayesian::getTaxonomy(Sequence* seq) {
209 //get words contained in query
210 //getKmerString returns a string where the index in the string is hte kmer number
211 //and the character at that index can be converted to be the number of times that kmer was seen
213 string queryKmerString = kmer.getKmerString(seq->getUnaligned());
215 vector<int> queryKmers;
216 for (int i = 0; i < queryKmerString.length(); i++) {
217 if (queryKmerString[i] != '!') { //this kmer is in the query
218 queryKmers.push_back(i);
222 if (queryKmers.size() == 0) { m->mothurOut(seq->getName() + "is bad."); m->mothurOutEndLine(); return "bad seq"; }
224 int index = getMostProbableTaxonomy(queryKmers);
226 if (m->control_pressed) { return tax; }
227 //cout << seq->getName() << '\t' << index << endl;
228 //bootstrap - to set confidenceScore
229 int numToSelect = queryKmers.size() / 8;
230 tax = bootstrapResults(queryKmers, index, numToSelect);
234 catch(exception& e) {
235 m->errorOut(e, "Bayesian", "getTaxonomy");
239 /**************************************************************************************************/
240 string Bayesian::bootstrapResults(vector<int> kmers, int tax, int numToSelect) {
243 map<int, int> confidenceScores;
245 map<int, int>::iterator itBoot;
246 map<int, int>::iterator itBoot2;
247 map<int, int>::iterator itConvert;
249 for (int i = 0; i < iters; i++) {
250 if (m->control_pressed) { return "control"; }
254 for (int j = 0; j < numToSelect; j++) {
255 int index = int(rand() % kmers.size());
258 temp.push_back(kmers[index]);
262 int newTax = getMostProbableTaxonomy(temp);
263 TaxNode taxonomyTemp = phyloTree->get(newTax);
265 //add to confidence results
266 while (taxonomyTemp.level != 0) { //while you are not at the root
268 itBoot2 = confidenceScores.find(newTax); //is this a classification we already have a count on
270 if (itBoot2 == confidenceScores.end()) { //not already in confidence scores
271 confidenceScores[newTax] = 1;
273 confidenceScores[newTax]++;
276 newTax = taxonomyTemp.parent;
277 taxonomyTemp = phyloTree->get(newTax);
282 string confidenceTax = "";
285 int seqTaxIndex = tax;
286 TaxNode seqTax = phyloTree->get(tax);
288 while (seqTax.level != 0) { //while you are not at the root
290 itBoot2 = confidenceScores.find(seqTaxIndex); //is this a classification we already have a count on
293 if (itBoot2 != confidenceScores.end()) { //already in confidence scores
294 confidence = confidenceScores[seqTaxIndex];
297 if (((confidence/(float)iters) * 100) >= confidenceThreshold) {
298 confidenceTax = seqTax.name + "(" + toString(((confidence/(float)iters) * 100)) + ");" + confidenceTax;
299 simpleTax = seqTax.name + ";" + simpleTax;
302 seqTaxIndex = seqTax.parent;
303 seqTax = phyloTree->get(seqTax.parent);
306 if (confidenceTax == "") { confidenceTax = "unclassified;"; simpleTax = "unclassified;"; }
307 return confidenceTax;
310 catch(exception& e) {
311 m->errorOut(e, "Bayesian", "bootstrapResults");
315 /**************************************************************************************************/
316 int Bayesian::getMostProbableTaxonomy(vector<int> queryKmer) {
318 int indexofGenus = 0;
320 double maxProbability = -1000000.0;
321 //find taxonomy with highest probability that this sequence is from it
322 for (int k = 0; k < genusNodes.size(); k++) {
323 //for each taxonomy calc its probability
325 for (int i = 0; i < queryKmer.size(); i++) {
326 prob += wordGenusProb[queryKmer[i]][k];
329 //is this the taxonomy with the greatest probability?
330 if (prob > maxProbability) {
331 indexofGenus = genusNodes[k];
332 maxProbability = prob;
338 catch(exception& e) {
339 m->errorOut(e, "Bayesian", "getMostProbableTaxonomy");
343 /*************************************************************************************************
344 map<string, int> Bayesian::parseTaxMap(string newTax) {
347 map<string, int> parsed;
349 newTax = newTax.substr(0, newTax.length()-1); //get rid of last ';'
353 while (newTax.find_first_of(';') != -1) {
354 individual = newTax.substr(0,newTax.find_first_of(';'));
355 newTax = newTax.substr(newTax.find_first_of(';')+1, newTax.length());
356 parsed[individual] = 1;
365 catch(exception& e) {
366 m->errorOut(e, "Bayesian", "parseTax");
370 /**************************************************************************************************/
371 void Bayesian::readProbFile(ifstream& in, ifstream& inNum, string inName, string inNumName) {
376 int pid, num, num2, processors;
377 vector<unsigned long int> positions;
378 vector<unsigned long int> positions2;
383 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
384 MPI_Comm_size(MPI_COMM_WORLD, &processors);
387 char inFileName[1024];
388 strcpy(inFileName, inNumName.c_str());
390 char inFileName2[1024];
391 strcpy(inFileName2, inName.c_str());
393 MPI_File_open(MPI_COMM_WORLD, inFileName, MPI_MODE_RDONLY, MPI_INFO_NULL, &inMPI); //comm, filename, mode, info, filepointer
394 MPI_File_open(MPI_COMM_WORLD, inFileName2, MPI_MODE_RDONLY, MPI_INFO_NULL, &inMPI2); //comm, filename, mode, info, filepointer
397 positions = setFilePosEachLine(inNumName, num);
398 positions2 = setFilePosEachLine(inName, num2);
400 for(int i = 1; i < processors; i++) {
401 MPI_Send(&num, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
402 MPI_Send(&positions[0], (num+1), MPI_LONG, i, tag, MPI_COMM_WORLD);
404 MPI_Send(&num2, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
405 MPI_Send(&positions2[0], (num2+1), MPI_LONG, i, tag, MPI_COMM_WORLD);
409 MPI_Recv(&num, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
410 positions.resize(num+1);
411 MPI_Recv(&positions[0], (num+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
413 MPI_Recv(&num2, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
414 positions2.resize(num2+1);
415 MPI_Recv(&positions2[0], (num2+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
419 int length = positions2[1] - positions2[0];
420 char* buf = new char[length];
422 MPI_File_read_at(inMPI2, positions2[0], buf, length, MPI_CHAR, &status);
424 string tempBuf = buf;
425 if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
428 istringstream iss (tempBuf,istringstream::in);
431 //initialze probabilities
432 wordGenusProb.resize(numKmers);
434 for (int j = 0; j < wordGenusProb.size(); j++) { wordGenusProb[j].resize(genusNodes.size()); }
437 vector<int> numbers; numbers.resize(numKmers);
439 vector<float> zeroCountProb; zeroCountProb.resize(numKmers);
442 for(int i=0;i<num;i++){
444 length = positions[i+1] - positions[i];
445 char* buf4 = new char[length];
447 MPI_File_read_at(inMPI, positions[i], buf4, length, MPI_CHAR, &status);
450 if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
453 istringstream iss (tempBuf,istringstream::in);
454 iss >> zeroCountProb[i] >> numbers[i];
457 MPI_File_close(&inMPI);
459 for(int i=1;i<num2;i++){
461 length = positions2[i+1] - positions2[i];
462 char* buf4 = new char[length];
464 MPI_File_read_at(inMPI2, positions2[i], buf4, length, MPI_CHAR, &status);
467 if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
470 istringstream iss (tempBuf,istringstream::in);
474 //set them all to zero value
475 for (int i = 0; i < genusNodes.size(); i++) {
476 wordGenusProb[kmer][i] = log(zeroCountProb[kmer] / (float) (genusTotals[i]+1));
479 //get probs for nonzero values
480 for (int i = 0; i < numbers[kmer]; i++) {
482 wordGenusProb[kmer][name] = prob;
486 MPI_File_close(&inMPI2);
487 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
490 in >> numKmers; gobble(in);
492 //initialze probabilities
493 wordGenusProb.resize(numKmers);
495 for (int j = 0; j < wordGenusProb.size(); j++) { wordGenusProb[j].resize(genusNodes.size()); }
497 int kmer, name, count; count = 0;
498 vector<int> num; num.resize(numKmers);
500 vector<float> zeroCountProb; zeroCountProb.resize(numKmers);
503 inNum >> zeroCountProb[count] >> num[count];
512 //set them all to zero value
513 for (int i = 0; i < genusNodes.size(); i++) {
514 wordGenusProb[kmer][i] = log(zeroCountProb[kmer] / (float) (genusTotals[i]+1));
517 //get probs for nonzero values
518 for (int i = 0; i < num[kmer]; i++) {
520 wordGenusProb[kmer][name] = prob;
529 catch(exception& e) {
530 m->errorOut(e, "Bayesian", "readProbFile");
534 /**************************************************************************************************/