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 genusNodes = phyloTree->getGenusNodes();
54 genusTotals = phyloTree->getGenusTotals();
56 m->mothurOut("Calculating template taxonomy tree... "); cout.flush();
58 phyloTree->printTreeNodes(phyloTreeName);
60 m->mothurOut("DONE."); m->mothurOutEndLine();
62 m->mothurOut("Calculating template probabilities... "); cout.flush();
64 numKmers = database->getMaxKmer() + 1;
66 //initialze probabilities
67 wordGenusProb.resize(numKmers);
69 for (int j = 0; j < wordGenusProb.size(); j++) { wordGenusProb[j].resize(genusNodes.size()); }
74 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
80 openOutputFile(probFileName, out);
82 out << numKmers << endl;
85 openOutputFile(probFileName2, out2);
93 for (int i = 0; i < numKmers; i++) {
94 if (m->control_pressed) { break; }
97 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
108 vector<int> seqsWithWordi = database->getSequencesWithKmer(i);
111 for (int k = 0; k < genusNodes.size(); k++) { count[genusNodes[k]] = 0; }
113 //for each sequence with that word
114 for (int j = 0; j < seqsWithWordi.size(); j++) {
115 int temp = phyloTree->getIndex(names[seqsWithWordi[j]]);
116 count[temp]++; //increment count of seq in this genus who have this word
119 //probabilityInTemplate = (# of seqs with that word in template + 0.05) / (total number of seqs in template + 1);
120 float probabilityInTemplate = (seqsWithWordi.size() + 0.50) / (float) (names.size() + 1);
123 for (int k = 0; k < genusNodes.size(); k++) {
124 //probabilityInThisTaxonomy = (# of seqs with that word in this taxonomy + probabilityInTemplate) / (total number of seqs in this taxonomy + 1);
125 wordGenusProb[i][k] = log((count[genusNodes[k]] + probabilityInTemplate) / (float) (genusTotals[k] + 1));
126 if (count[genusNodes[k]] != 0) {
128 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
132 out << k << '\t' << wordGenusProb[i][k] << '\t';
143 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
148 out2 << probabilityInTemplate << '\t' << numNotZero << endl;
156 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
167 //read in new phylotree with less info. - its faster
168 ifstream phyloTreeTest(phyloTreeName.c_str());
171 phyloTree = new PhyloTree(phyloTreeTest, phyloTreeName);
174 m->mothurOut("DONE."); m->mothurOutEndLine();
175 m->mothurOut("It took " + toString(time(NULL) - start) + " seconds get probabilities. "); m->mothurOutEndLine();
177 catch(exception& e) {
178 m->errorOut(e, "Bayesian", "Bayesian");
182 /**************************************************************************************************/
183 Bayesian::~Bayesian() {
186 if (database != NULL) { delete database; }
188 catch(exception& e) {
189 m->errorOut(e, "Bayesian", "~Bayesian");
194 /**************************************************************************************************/
195 string Bayesian::getTaxonomy(Sequence* seq) {
200 //get words contained in query
201 //getKmerString returns a string where the index in the string is hte kmer number
202 //and the character at that index can be converted to be the number of times that kmer was seen
204 string queryKmerString = kmer.getKmerString(seq->getUnaligned());
206 vector<int> queryKmers;
207 for (int i = 0; i < queryKmerString.length(); i++) {
208 if (queryKmerString[i] != '!') { //this kmer is in the query
209 queryKmers.push_back(i);
213 if (queryKmers.size() == 0) { m->mothurOut(seq->getName() + "is bad."); m->mothurOutEndLine(); return "bad seq"; }
215 int index = getMostProbableTaxonomy(queryKmers);
217 if (m->control_pressed) { return tax; }
218 //cout << seq->getName() << '\t' << index << endl;
219 //bootstrap - to set confidenceScore
220 int numToSelect = queryKmers.size() / 8;
221 tax = bootstrapResults(queryKmers, index, numToSelect);
225 catch(exception& e) {
226 m->errorOut(e, "Bayesian", "getTaxonomy");
230 /**************************************************************************************************/
231 string Bayesian::bootstrapResults(vector<int> kmers, int tax, int numToSelect) {
234 map<int, int> confidenceScores;
236 map<int, int>::iterator itBoot;
237 map<int, int>::iterator itBoot2;
238 map<int, int>::iterator itConvert;
240 for (int i = 0; i < iters; i++) {
241 if (m->control_pressed) { return "control"; }
245 for (int j = 0; j < numToSelect; j++) {
246 int index = int(rand() % kmers.size());
249 temp.push_back(kmers[index]);
253 int newTax = getMostProbableTaxonomy(temp);
254 TaxNode taxonomyTemp = phyloTree->get(newTax);
256 //add to confidence results
257 while (taxonomyTemp.level != 0) { //while you are not at the root
259 itBoot2 = confidenceScores.find(newTax); //is this a classification we already have a count on
261 if (itBoot2 == confidenceScores.end()) { //not already in confidence scores
262 confidenceScores[newTax] = 1;
264 confidenceScores[newTax]++;
267 newTax = taxonomyTemp.parent;
268 taxonomyTemp = phyloTree->get(newTax);
273 string confidenceTax = "";
276 int seqTaxIndex = tax;
277 TaxNode seqTax = phyloTree->get(tax);
279 while (seqTax.level != 0) { //while you are not at the root
281 itBoot2 = confidenceScores.find(seqTaxIndex); //is this a classification we already have a count on
284 if (itBoot2 != confidenceScores.end()) { //already in confidence scores
285 confidence = confidenceScores[seqTaxIndex];
288 if (((confidence/(float)iters) * 100) >= confidenceThreshold) {
289 confidenceTax = seqTax.name + "(" + toString(((confidence/(float)iters) * 100)) + ");" + confidenceTax;
290 simpleTax = seqTax.name + ";" + simpleTax;
293 seqTaxIndex = seqTax.parent;
294 seqTax = phyloTree->get(seqTax.parent);
297 if (confidenceTax == "") { confidenceTax = "unclassified;"; simpleTax = "unclassified;"; }
298 return confidenceTax;
301 catch(exception& e) {
302 m->errorOut(e, "Bayesian", "bootstrapResults");
306 /**************************************************************************************************/
307 int Bayesian::getMostProbableTaxonomy(vector<int> queryKmer) {
309 int indexofGenus = 0;
311 double maxProbability = -1000000.0;
312 //find taxonomy with highest probability that this sequence is from it
313 for (int k = 0; k < genusNodes.size(); k++) {
314 //for each taxonomy calc its probability
316 for (int i = 0; i < queryKmer.size(); i++) {
317 prob += wordGenusProb[queryKmer[i]][k];
320 //is this the taxonomy with the greatest probability?
321 if (prob > maxProbability) {
322 indexofGenus = genusNodes[k];
323 maxProbability = prob;
329 catch(exception& e) {
330 m->errorOut(e, "Bayesian", "getMostProbableTaxonomy");
334 /*************************************************************************************************
335 map<string, int> Bayesian::parseTaxMap(string newTax) {
338 map<string, int> parsed;
340 newTax = newTax.substr(0, newTax.length()-1); //get rid of last ';'
344 while (newTax.find_first_of(';') != -1) {
345 individual = newTax.substr(0,newTax.find_first_of(';'));
346 newTax = newTax.substr(newTax.find_first_of(';')+1, newTax.length());
347 parsed[individual] = 1;
356 catch(exception& e) {
357 m->errorOut(e, "Bayesian", "parseTax");
361 /**************************************************************************************************/
362 void Bayesian::readProbFile(ifstream& in, ifstream& inNum, string inName, string inNumName) {
367 int pid, num, num2, processors;
368 vector<long> positions;
369 vector<long> positions2;
374 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
375 MPI_Comm_size(MPI_COMM_WORLD, &processors);
378 char inFileName[1024];
379 strcpy(inFileName, inNumName.c_str());
381 char inFileName2[1024];
382 strcpy(inFileName2, inName.c_str());
384 MPI_File_open(MPI_COMM_WORLD, inFileName, MPI_MODE_RDONLY, MPI_INFO_NULL, &inMPI); //comm, filename, mode, info, filepointer
385 MPI_File_open(MPI_COMM_WORLD, inFileName2, MPI_MODE_RDONLY, MPI_INFO_NULL, &inMPI2); //comm, filename, mode, info, filepointer
388 positions = setFilePosEachLine(inNumName, num);
389 positions2 = setFilePosEachLine(inName, num2);
391 for(int i = 1; i < processors; i++) {
392 MPI_Send(&num, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
393 MPI_Send(&positions[0], (num+1), MPI_LONG, i, tag, MPI_COMM_WORLD);
395 MPI_Send(&num2, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
396 MPI_Send(&positions2[0], (num2+1), MPI_LONG, i, tag, MPI_COMM_WORLD);
400 MPI_Recv(&num, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
401 positions.resize(num+1);
402 MPI_Recv(&positions[0], (num+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
404 MPI_Recv(&num2, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
405 positions2.resize(num2+1);
406 MPI_Recv(&positions2[0], (num2+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
410 int length = positions2[1] - positions2[0];
411 char* buf = new char[length];
413 MPI_File_read_at(inMPI2, positions2[0], buf, length, MPI_CHAR, &status);
415 string tempBuf = buf;
416 if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
419 istringstream iss (tempBuf,istringstream::in);
422 //initialze probabilities
423 wordGenusProb.resize(numKmers);
425 for (int j = 0; j < wordGenusProb.size(); j++) { wordGenusProb[j].resize(genusNodes.size()); }
428 vector<int> numbers; numbers.resize(numKmers);
430 vector<float> zeroCountProb; zeroCountProb.resize(numKmers);
433 for(int i=0;i<num;i++){
435 length = positions[i+1] - positions[i];
436 char* buf4 = new char[length];
438 MPI_File_read_at(inMPI, positions[i], buf4, length, MPI_CHAR, &status);
441 if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
444 istringstream iss (tempBuf,istringstream::in);
445 iss >> zeroCountProb[i] >> numbers[i];
448 MPI_File_close(&inMPI);
450 for(int i=1;i<num2;i++){
452 length = positions2[i+1] - positions2[i];
453 char* buf4 = new char[length];
455 MPI_File_read_at(inMPI2, positions2[i], buf4, length, MPI_CHAR, &status);
458 if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
461 istringstream iss (tempBuf,istringstream::in);
465 //set them all to zero value
466 for (int i = 0; i < genusNodes.size(); i++) {
467 wordGenusProb[kmer][i] = log(zeroCountProb[kmer] / (float) (genusTotals[i]+1));
470 //get probs for nonzero values
471 for (int i = 0; i < numbers[kmer]; i++) {
473 wordGenusProb[kmer][name] = prob;
477 MPI_File_close(&inMPI2);
478 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
481 in >> numKmers; gobble(in);
483 //initialze probabilities
484 wordGenusProb.resize(numKmers);
486 for (int j = 0; j < wordGenusProb.size(); j++) { wordGenusProb[j].resize(genusNodes.size()); }
488 int kmer, name, count; count = 0;
489 vector<int> num; num.resize(numKmers);
491 vector<float> zeroCountProb; zeroCountProb.resize(numKmers);
494 inNum >> zeroCountProb[count] >> num[count];
503 //set them all to zero value
504 for (int i = 0; i < genusNodes.size(); i++) {
505 wordGenusProb[kmer][i] = log(zeroCountProb[kmer] / (float) (genusTotals[i]+1));
508 //get probs for nonzero values
509 for (int i = 0; i < num[kmer]; i++) {
511 wordGenusProb[kmer][name] = prob;
520 catch(exception& e) {
521 m->errorOut(e, "Bayesian", "readProbFile");
525 /**************************************************************************************************/