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()); }
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()); }
77 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
83 openOutputFile(probFileName, out);
85 out << numKmers << endl;
88 openOutputFile(probFileName2, out2);
96 for (int i = 0; i < numKmers; i++) {
97 if (m->control_pressed) { break; }
100 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
111 vector<int> seqsWithWordi = database->getSequencesWithKmer(i);
114 for (int k = 0; k < genusNodes.size(); k++) { count[genusNodes[k]] = 0; }
116 //for each sequence with that word
117 for (int j = 0; j < seqsWithWordi.size(); j++) {
118 int temp = phyloTree->getIndex(names[seqsWithWordi[j]]);
119 count[temp]++; //increment count of seq in this genus who have this word
122 //probabilityInTemplate = (# of seqs with that word in template + 0.05) / (total number of seqs in template + 1);
123 float probabilityInTemplate = (seqsWithWordi.size() + 0.50) / (float) (names.size() + 1);
126 for (int k = 0; k < genusNodes.size(); k++) {
127 //probabilityInThisTaxonomy = (# of seqs with that word in this taxonomy + probabilityInTemplate) / (total number of seqs in this taxonomy + 1);
128 wordGenusProb[i][k] = log((count[genusNodes[k]] + probabilityInTemplate) / (float) (genusTotals[k] + 1));
129 if (count[genusNodes[k]] != 0) {
131 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
135 out << k << '\t' << wordGenusProb[i][k] << '\t';
146 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
151 out2 << probabilityInTemplate << '\t' << numNotZero << endl;
159 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
170 //read in new phylotree with less info. - its faster
171 ifstream phyloTreeTest(phyloTreeName.c_str());
174 phyloTree = new PhyloTree(phyloTreeTest, phyloTreeName);
177 m->mothurOut("DONE."); m->mothurOutEndLine();
178 m->mothurOut("It took " + toString(time(NULL) - start) + " seconds get probabilities. "); m->mothurOutEndLine();
180 catch(exception& e) {
181 m->errorOut(e, "Bayesian", "Bayesian");
185 /**************************************************************************************************/
186 Bayesian::~Bayesian() {
189 if (database != NULL) { delete database; }
191 catch(exception& e) {
192 m->errorOut(e, "Bayesian", "~Bayesian");
197 /**************************************************************************************************/
198 string Bayesian::getTaxonomy(Sequence* seq) {
203 //get words contained in query
204 //getKmerString returns a string where the index in the string is hte kmer number
205 //and the character at that index can be converted to be the number of times that kmer was seen
207 string queryKmerString = kmer.getKmerString(seq->getUnaligned());
209 vector<int> queryKmers;
210 for (int i = 0; i < queryKmerString.length(); i++) {
211 if (queryKmerString[i] != '!') { //this kmer is in the query
212 queryKmers.push_back(i);
216 if (queryKmers.size() == 0) { m->mothurOut(seq->getName() + "is bad."); m->mothurOutEndLine(); return "bad seq"; }
218 int index = getMostProbableTaxonomy(queryKmers);
220 if (m->control_pressed) { return tax; }
221 //cout << seq->getName() << '\t' << index << endl;
222 //bootstrap - to set confidenceScore
223 int numToSelect = queryKmers.size() / 8;
224 tax = bootstrapResults(queryKmers, index, numToSelect);
228 catch(exception& e) {
229 m->errorOut(e, "Bayesian", "getTaxonomy");
233 /**************************************************************************************************/
234 string Bayesian::bootstrapResults(vector<int> kmers, int tax, int numToSelect) {
237 map<int, int> confidenceScores;
239 map<int, int>::iterator itBoot;
240 map<int, int>::iterator itBoot2;
241 map<int, int>::iterator itConvert;
243 for (int i = 0; i < iters; i++) {
244 if (m->control_pressed) { return "control"; }
248 for (int j = 0; j < numToSelect; j++) {
249 int index = int(rand() % kmers.size());
252 temp.push_back(kmers[index]);
256 int newTax = getMostProbableTaxonomy(temp);
257 TaxNode taxonomyTemp = phyloTree->get(newTax);
259 //add to confidence results
260 while (taxonomyTemp.level != 0) { //while you are not at the root
262 itBoot2 = confidenceScores.find(newTax); //is this a classification we already have a count on
264 if (itBoot2 == confidenceScores.end()) { //not already in confidence scores
265 confidenceScores[newTax] = 1;
267 confidenceScores[newTax]++;
270 newTax = taxonomyTemp.parent;
271 taxonomyTemp = phyloTree->get(newTax);
276 string confidenceTax = "";
279 int seqTaxIndex = tax;
280 TaxNode seqTax = phyloTree->get(tax);
282 while (seqTax.level != 0) { //while you are not at the root
284 itBoot2 = confidenceScores.find(seqTaxIndex); //is this a classification we already have a count on
287 if (itBoot2 != confidenceScores.end()) { //already in confidence scores
288 confidence = confidenceScores[seqTaxIndex];
291 if (((confidence/(float)iters) * 100) >= confidenceThreshold) {
292 confidenceTax = seqTax.name + "(" + toString(((confidence/(float)iters) * 100)) + ");" + confidenceTax;
293 simpleTax = seqTax.name + ";" + simpleTax;
296 seqTaxIndex = seqTax.parent;
297 seqTax = phyloTree->get(seqTax.parent);
300 if (confidenceTax == "") { confidenceTax = "unclassified;"; simpleTax = "unclassified;"; }
301 return confidenceTax;
304 catch(exception& e) {
305 m->errorOut(e, "Bayesian", "bootstrapResults");
309 /**************************************************************************************************/
310 int Bayesian::getMostProbableTaxonomy(vector<int> queryKmer) {
312 int indexofGenus = 0;
314 double maxProbability = -1000000.0;
315 //find taxonomy with highest probability that this sequence is from it
316 for (int k = 0; k < genusNodes.size(); k++) {
317 //for each taxonomy calc its probability
319 for (int i = 0; i < queryKmer.size(); i++) {
320 prob += wordGenusProb[queryKmer[i]][k];
323 //is this the taxonomy with the greatest probability?
324 if (prob > maxProbability) {
325 indexofGenus = genusNodes[k];
326 maxProbability = prob;
332 catch(exception& e) {
333 m->errorOut(e, "Bayesian", "getMostProbableTaxonomy");
337 /*************************************************************************************************
338 map<string, int> Bayesian::parseTaxMap(string newTax) {
341 map<string, int> parsed;
343 newTax = newTax.substr(0, newTax.length()-1); //get rid of last ';'
347 while (newTax.find_first_of(';') != -1) {
348 individual = newTax.substr(0,newTax.find_first_of(';'));
349 newTax = newTax.substr(newTax.find_first_of(';')+1, newTax.length());
350 parsed[individual] = 1;
359 catch(exception& e) {
360 m->errorOut(e, "Bayesian", "parseTax");
364 /**************************************************************************************************/
365 void Bayesian::readProbFile(ifstream& in, ifstream& inNum, string inName, string inNumName) {
370 int pid, num, num2, processors;
371 vector<unsigned long int> positions;
372 vector<unsigned long int> positions2;
377 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
378 MPI_Comm_size(MPI_COMM_WORLD, &processors);
381 char inFileName[1024];
382 strcpy(inFileName, inNumName.c_str());
384 char inFileName2[1024];
385 strcpy(inFileName2, inName.c_str());
387 MPI_File_open(MPI_COMM_WORLD, inFileName, MPI_MODE_RDONLY, MPI_INFO_NULL, &inMPI); //comm, filename, mode, info, filepointer
388 MPI_File_open(MPI_COMM_WORLD, inFileName2, MPI_MODE_RDONLY, MPI_INFO_NULL, &inMPI2); //comm, filename, mode, info, filepointer
391 positions = setFilePosEachLine(inNumName, num);
392 positions2 = setFilePosEachLine(inName, num2);
394 for(int i = 1; i < processors; i++) {
395 MPI_Send(&num, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
396 MPI_Send(&positions[0], (num+1), MPI_LONG, i, tag, MPI_COMM_WORLD);
398 MPI_Send(&num2, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
399 MPI_Send(&positions2[0], (num2+1), MPI_LONG, i, tag, MPI_COMM_WORLD);
403 MPI_Recv(&num, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
404 positions.resize(num+1);
405 MPI_Recv(&positions[0], (num+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
407 MPI_Recv(&num2, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
408 positions2.resize(num2+1);
409 MPI_Recv(&positions2[0], (num2+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
413 int length = positions2[1] - positions2[0];
414 char* buf = new char[length];
416 MPI_File_read_at(inMPI2, positions2[0], buf, length, MPI_CHAR, &status);
418 string tempBuf = buf;
419 if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
422 istringstream iss (tempBuf,istringstream::in);
425 //initialze probabilities
426 wordGenusProb.resize(numKmers);
428 for (int j = 0; j < wordGenusProb.size(); j++) { wordGenusProb[j].resize(genusNodes.size()); }
431 vector<int> numbers; numbers.resize(numKmers);
433 vector<float> zeroCountProb; zeroCountProb.resize(numKmers);
436 for(int i=0;i<num;i++){
438 length = positions[i+1] - positions[i];
439 char* buf4 = new char[length];
441 MPI_File_read_at(inMPI, positions[i], buf4, length, MPI_CHAR, &status);
444 if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
447 istringstream iss (tempBuf,istringstream::in);
448 iss >> zeroCountProb[i] >> numbers[i];
451 MPI_File_close(&inMPI);
453 for(int i=1;i<num2;i++){
455 length = positions2[i+1] - positions2[i];
456 char* buf4 = new char[length];
458 MPI_File_read_at(inMPI2, positions2[i], buf4, length, MPI_CHAR, &status);
461 if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
464 istringstream iss (tempBuf,istringstream::in);
468 //set them all to zero value
469 for (int i = 0; i < genusNodes.size(); i++) {
470 wordGenusProb[kmer][i] = log(zeroCountProb[kmer] / (float) (genusTotals[i]+1));
473 //get probs for nonzero values
474 for (int i = 0; i < numbers[kmer]; i++) {
476 wordGenusProb[kmer][name] = prob;
480 MPI_File_close(&inMPI2);
481 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
484 in >> numKmers; gobble(in);
486 //initialze probabilities
487 wordGenusProb.resize(numKmers);
489 for (int j = 0; j < wordGenusProb.size(); j++) { wordGenusProb[j].resize(genusNodes.size()); }
491 int kmer, name, count; count = 0;
492 vector<int> num; num.resize(numKmers);
494 vector<float> zeroCountProb; zeroCountProb.resize(numKmers);
497 inNum >> zeroCountProb[count] >> num[count];
506 //set them all to zero value
507 for (int i = 0; i < genusNodes.size(); i++) {
508 wordGenusProb[kmer][i] = log(zeroCountProb[kmer] / (float) (genusTotals[i]+1));
511 //get probs for nonzero values
512 for (int i = 0; i < num[kmer]; i++) {
514 wordGenusProb[kmer][name] = prob;
523 catch(exception& e) {
524 m->errorOut(e, "Bayesian", "readProbFile");
528 /**************************************************************************************************/