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 phyloTreeName = tfile.substr(0,tfile.find_last_of(".")+1) + "tree.train";
21 string probFileName = tfile.substr(0,tfile.find_last_of(".")+1) + tempFile.substr(0,tempFile.find_last_of(".")+1) + char('0'+ kmerSize) + "mer.prob";
22 string probFileName2 = tfile.substr(0,tfile.find_last_of(".")+1) + tempFile.substr(0,tempFile.find_last_of(".")+1) + char('0'+ kmerSize) + "mer.numNonZero";
27 ifstream phyloTreeTest(phyloTreeName.c_str());
28 ifstream probFileTest2(probFileName2.c_str());
29 ifstream probFileTest(probFileName.c_str());
31 int start = time(NULL);
33 if(probFileTest && probFileTest2 && phyloTreeTest){
34 m->mothurOut("Reading template taxonomy... "); cout.flush();
36 phyloTree = new PhyloTree(phyloTreeTest, phyloTreeName);
38 m->mothurOut("DONE."); m->mothurOutEndLine();
40 genusNodes = phyloTree->getGenusNodes();
41 genusTotals = phyloTree->getGenusTotals();
43 m->mothurOut("Reading template probabilities... "); cout.flush();
44 readProbFile(probFileTest, probFileTest2, probFileName, probFileName2);
48 //create search database and names vector
49 generateDatabaseAndNames(tfile, tempFile, method, ksize, 0.0, 0.0, 0.0, 0.0);
51 genusNodes = phyloTree->getGenusNodes();
52 genusTotals = phyloTree->getGenusTotals();
54 m->mothurOut("Calculating template taxonomy tree... "); cout.flush();
56 phyloTree->printTreeNodes(phyloTreeName);
58 m->mothurOut("DONE."); m->mothurOutEndLine();
60 m->mothurOut("Calculating template probabilities... "); cout.flush();
62 numKmers = database->getMaxKmer() + 1;
64 //initialze probabilities
65 wordGenusProb.resize(numKmers);
67 for (int j = 0; j < wordGenusProb.size(); j++) { wordGenusProb[j].resize(genusNodes.size()); }
72 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
78 openOutputFile(probFileName, out);
80 out << numKmers << endl;
83 openOutputFile(probFileName2, out2);
91 for (int i = 0; i < numKmers; i++) {
92 if (m->control_pressed) { break; }
95 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
106 vector<int> seqsWithWordi = database->getSequencesWithKmer(i);
109 for (int k = 0; k < genusNodes.size(); k++) { count[genusNodes[k]] = 0; }
111 //for each sequence with that word
112 for (int j = 0; j < seqsWithWordi.size(); j++) {
113 int temp = phyloTree->getIndex(names[seqsWithWordi[j]]);
114 count[temp]++; //increment count of seq in this genus who have this word
117 //probabilityInTemplate = (# of seqs with that word in template + 0.05) / (total number of seqs in template + 1);
118 float probabilityInTemplate = (seqsWithWordi.size() + 0.50) / (float) (names.size() + 1);
121 for (int k = 0; k < genusNodes.size(); k++) {
122 //probabilityInThisTaxonomy = (# of seqs with that word in this taxonomy + probabilityInTemplate) / (total number of seqs in this taxonomy + 1);
123 wordGenusProb[i][k] = log((count[genusNodes[k]] + probabilityInTemplate) / (float) (genusTotals[k] + 1));
124 if (count[genusNodes[k]] != 0) {
126 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
130 out << k << '\t' << wordGenusProb[i][k] << '\t';
141 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
146 out2 << probabilityInTemplate << '\t' << numNotZero << endl;
154 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
165 //read in new phylotree with less info. - its faster
166 ifstream phyloTreeTest(phyloTreeName.c_str());
169 phyloTree = new PhyloTree(phyloTreeTest, phyloTreeName);
172 m->mothurOut("DONE."); m->mothurOutEndLine();
173 m->mothurOut("It took " + toString(time(NULL) - start) + " seconds get probabilities. "); m->mothurOutEndLine();
175 catch(exception& e) {
176 m->errorOut(e, "Bayesian", "Bayesian");
180 /**************************************************************************************************/
181 string Bayesian::getTaxonomy(Sequence* seq) {
186 //get words contained in query
187 //getKmerString returns a string where the index in the string is hte kmer number
188 //and the character at that index can be converted to be the number of times that kmer was seen
190 string queryKmerString = kmer.getKmerString(seq->getUnaligned());
192 vector<int> queryKmers;
193 for (int i = 0; i < queryKmerString.length(); i++) {
194 if (queryKmerString[i] != '!') { //this kmer is in the query
195 queryKmers.push_back(i);
199 if (queryKmers.size() == 0) { m->mothurOut(seq->getName() + "is bad."); m->mothurOutEndLine(); return "bad seq"; }
201 int index = getMostProbableTaxonomy(queryKmers);
203 if (m->control_pressed) { return tax; }
205 //bootstrap - to set confidenceScore
206 int numToSelect = queryKmers.size() / 8;
207 tax = bootstrapResults(queryKmers, index, numToSelect);
211 catch(exception& e) {
212 m->errorOut(e, "Bayesian", "getTaxonomy");
216 /**************************************************************************************************/
217 string Bayesian::bootstrapResults(vector<int> kmers, int tax, int numToSelect) {
220 map<int, int> confidenceScores;
222 map<int, int>::iterator itBoot;
223 map<int, int>::iterator itBoot2;
224 map<int, int>::iterator itConvert;
226 for (int i = 0; i < iters; i++) {
227 if (m->control_pressed) { return "control"; }
231 for (int j = 0; j < numToSelect; j++) {
232 int index = int(rand() % kmers.size());
235 temp.push_back(kmers[index]);
239 int newTax = getMostProbableTaxonomy(temp);
240 TaxNode taxonomy = phyloTree->get(newTax);
242 //add to confidence results
243 while (taxonomy.level != 0) { //while you are not at the root
245 itBoot2 = confidenceScores.find(newTax); //is this a classification we already have a count on
247 if (itBoot2 == confidenceScores.end()) { //not already in confidence scores
248 confidenceScores[newTax] = 1;
250 confidenceScores[newTax]++;
253 newTax = taxonomy.parent;
254 taxonomy = phyloTree->get(taxonomy.parent);
259 string confidenceTax = "";
262 int seqTaxIndex = tax;
263 TaxNode seqTax = phyloTree->get(tax);
265 while (seqTax.level != 0) { //while you are not at the root
267 itBoot2 = confidenceScores.find(seqTaxIndex); //is this a classification we already have a count on
270 if (itBoot2 != confidenceScores.end()) { //already in confidence scores
271 confidence = confidenceScores[seqTaxIndex];
274 if (((confidence/(float)iters) * 100) >= confidenceThreshold) {
275 confidenceTax = seqTax.name + "(" + toString(((confidence/(float)iters) * 100)) + ");" + confidenceTax;
276 simpleTax = seqTax.name + ";" + simpleTax;
279 seqTaxIndex = seqTax.parent;
280 seqTax = phyloTree->get(seqTax.parent);
283 if (confidenceTax == "") { confidenceTax = "unclassified;"; simpleTax = "unclassified;"; }
284 return confidenceTax;
287 catch(exception& e) {
288 m->errorOut(e, "Bayesian", "bootstrapResults");
292 /**************************************************************************************************/
293 int Bayesian::getMostProbableTaxonomy(vector<int> queryKmer) {
295 int indexofGenus = 0;
297 double maxProbability = -1000000.0;
298 //find taxonomy with highest probability that this sequence is from it
299 for (int k = 0; k < genusNodes.size(); k++) {
300 //for each taxonomy calc its probability
302 for (int i = 0; i < queryKmer.size(); i++) {
303 prob += wordGenusProb[queryKmer[i]][k];
306 //is this the taxonomy with the greatest probability?
307 if (prob > maxProbability) {
308 indexofGenus = genusNodes[k];
309 maxProbability = prob;
315 catch(exception& e) {
316 m->errorOut(e, "Bayesian", "getMostProbableTaxonomy");
320 /*************************************************************************************************
321 map<string, int> Bayesian::parseTaxMap(string newTax) {
324 map<string, int> parsed;
326 newTax = newTax.substr(0, newTax.length()-1); //get rid of last ';'
330 while (newTax.find_first_of(';') != -1) {
331 individual = newTax.substr(0,newTax.find_first_of(';'));
332 newTax = newTax.substr(newTax.find_first_of(';')+1, newTax.length());
333 parsed[individual] = 1;
342 catch(exception& e) {
343 m->errorOut(e, "Bayesian", "parseTax");
347 /**************************************************************************************************/
348 void Bayesian::readProbFile(ifstream& in, ifstream& inNum, string inName, string inNumName) {
354 vector<long> positions;
355 vector<long> positions2;
360 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
362 char inFileName[1024];
363 strcpy(inFileName, inNumName.c_str());
365 char inFileName2[1024];
366 strcpy(inFileName2, inName.c_str());
368 MPI_File_open(MPI_COMM_WORLD, inFileName, MPI_MODE_RDONLY, MPI_INFO_NULL, &inMPI); //comm, filename, mode, info, filepointer
369 MPI_File_open(MPI_COMM_WORLD, inFileName2, MPI_MODE_RDONLY, MPI_INFO_NULL, &inMPI2); //comm, filename, mode, info, filepointer
372 positions = setFilePosEachLine(inNumName, num);
374 //send file positions to all processes
375 MPI_Bcast(&num, 1, MPI_INT, 0, MPI_COMM_WORLD); //send numSeqs
376 MPI_Bcast(&positions[0], (num+1), MPI_LONG, 0, MPI_COMM_WORLD); //send file pos
378 positions2 = setFilePosEachLine(inName, num2);
380 //send file positions to all processes
381 MPI_Bcast(&num2, 1, MPI_INT, 0, MPI_COMM_WORLD); //send numSeqs
382 MPI_Bcast(&positions2[0], (num2+1), MPI_LONG, 0, MPI_COMM_WORLD); //send file pos
385 MPI_Bcast(&num, 1, MPI_INT, 0, MPI_COMM_WORLD); //get numSeqs
386 positions.resize(num);
387 MPI_Bcast(&positions[0], (num+1), MPI_LONG, 0, MPI_COMM_WORLD); //get file positions
389 MPI_Bcast(&num2, 1, MPI_INT, 0, MPI_COMM_WORLD); //get numSeqs
390 positions2.resize(num2);
391 MPI_Bcast(&positions2[0], (num2+1), MPI_LONG, 0, MPI_COMM_WORLD); //get file positions
396 int length = positions2[1] - positions2[0];
397 char* buf = new char[length];
399 MPI_File_read_at(inMPI2, positions2[0], buf, length, MPI_CHAR, &status);
401 string tempBuf = buf;
402 if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
405 istringstream iss (tempBuf,istringstream::in);
408 //initialze probabilities
409 wordGenusProb.resize(numKmers);
411 for (int j = 0; j < wordGenusProb.size(); j++) { wordGenusProb[j].resize(genusNodes.size()); }
414 vector<int> numbers; numbers.resize(numKmers);
416 vector<float> zeroCountProb; zeroCountProb.resize(numKmers);
419 for(int i=0;i<num;i++){
421 length = positions[i+1] - positions[i];
422 char* buf4 = new char[length];
424 MPI_File_read_at(inMPI, positions[i], buf4, length, MPI_CHAR, &status);
427 if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
430 istringstream iss (tempBuf,istringstream::in);
431 iss >> zeroCountProb[i] >> numbers[i];
434 MPI_File_close(&inMPI);
436 for(int i=1;i<num2;i++){
438 length = positions2[i+1] - positions2[i];
439 char* buf4 = new char[length];
441 MPI_File_read_at(inMPI2, positions2[i], buf4, length, MPI_CHAR, &status);
444 if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
447 istringstream iss (tempBuf,istringstream::in);
451 //set them all to zero value
452 for (int i = 0; i < genusNodes.size(); i++) {
453 wordGenusProb[kmer][i] = log(zeroCountProb[kmer] / (float) (genusTotals[i]+1));
456 //get probs for nonzero values
457 for (int i = 0; i < numbers[kmer]; i++) {
459 wordGenusProb[kmer][name] = prob;
463 MPI_File_close(&inMPI2);
466 in >> numKmers; gobble(in);
468 //initialze probabilities
469 wordGenusProb.resize(numKmers);
471 for (int j = 0; j < wordGenusProb.size(); j++) { wordGenusProb[j].resize(genusNodes.size()); }
473 int kmer, name, count; count = 0;
474 vector<int> num; num.resize(numKmers);
476 vector<float> zeroCountProb; zeroCountProb.resize(numKmers);
479 inNum >> zeroCountProb[count] >> num[count];
488 //set them all to zero value
489 for (int i = 0; i < genusNodes.size(); i++) {
490 wordGenusProb[kmer][i] = log(zeroCountProb[kmer] / (float) (genusTotals[i]+1));
493 //get probs for nonzero values
494 for (int i = 0; i < num[kmer]; i++) {
496 wordGenusProb[kmer][name] = prob;
505 catch(exception& e) {
506 m->errorOut(e, "Bayesian", "readProbFile");
510 /**************************************************************************************************/