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()); }
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);
178 m->mothurOut("DONE."); m->mothurOutEndLine();
179 m->mothurOut("It took " + toString(time(NULL) - start) + " seconds get probabilities. "); m->mothurOutEndLine();
181 catch(exception& e) {
182 m->errorOut(e, "Bayesian", "Bayesian");
186 /**************************************************************************************************/
187 Bayesian::~Bayesian() {
190 if (database != NULL) { delete database; }
192 catch(exception& e) {
193 m->errorOut(e, "Bayesian", "~Bayesian");
198 /**************************************************************************************************/
199 string Bayesian::getTaxonomy(Sequence* seq) {
204 //get words contained in query
205 //getKmerString returns a string where the index in the string is hte kmer number
206 //and the character at that index can be converted to be the number of times that kmer was seen
208 string queryKmerString = kmer.getKmerString(seq->getUnaligned());
210 vector<int> queryKmers;
211 for (int i = 0; i < queryKmerString.length(); i++) {
212 if (queryKmerString[i] != '!') { //this kmer is in the query
213 queryKmers.push_back(i);
217 if (queryKmers.size() == 0) { m->mothurOut(seq->getName() + "is bad."); m->mothurOutEndLine(); return "bad seq"; }
219 int index = getMostProbableTaxonomy(queryKmers);
221 if (m->control_pressed) { return tax; }
222 //cout << seq->getName() << '\t' << index << endl;
223 //bootstrap - to set confidenceScore
224 int numToSelect = queryKmers.size() / 8;
225 tax = bootstrapResults(queryKmers, index, numToSelect);
229 catch(exception& e) {
230 m->errorOut(e, "Bayesian", "getTaxonomy");
234 /**************************************************************************************************/
235 string Bayesian::bootstrapResults(vector<int> kmers, int tax, int numToSelect) {
238 map<int, int> confidenceScores;
240 map<int, int>::iterator itBoot;
241 map<int, int>::iterator itBoot2;
242 map<int, int>::iterator itConvert;
244 for (int i = 0; i < iters; i++) {
245 if (m->control_pressed) { return "control"; }
249 for (int j = 0; j < numToSelect; j++) {
250 int index = int(rand() % kmers.size());
253 temp.push_back(kmers[index]);
257 int newTax = getMostProbableTaxonomy(temp);
258 TaxNode taxonomyTemp = phyloTree->get(newTax);
260 //add to confidence results
261 while (taxonomyTemp.level != 0) { //while you are not at the root
263 itBoot2 = confidenceScores.find(newTax); //is this a classification we already have a count on
265 if (itBoot2 == confidenceScores.end()) { //not already in confidence scores
266 confidenceScores[newTax] = 1;
268 confidenceScores[newTax]++;
271 newTax = taxonomyTemp.parent;
272 taxonomyTemp = phyloTree->get(newTax);
277 string confidenceTax = "";
280 int seqTaxIndex = tax;
281 TaxNode seqTax = phyloTree->get(tax);
283 while (seqTax.level != 0) { //while you are not at the root
285 itBoot2 = confidenceScores.find(seqTaxIndex); //is this a classification we already have a count on
288 if (itBoot2 != confidenceScores.end()) { //already in confidence scores
289 confidence = confidenceScores[seqTaxIndex];
292 if (((confidence/(float)iters) * 100) >= confidenceThreshold) {
293 confidenceTax = seqTax.name + "(" + toString(((confidence/(float)iters) * 100)) + ");" + confidenceTax;
294 simpleTax = seqTax.name + ";" + simpleTax;
297 seqTaxIndex = seqTax.parent;
298 seqTax = phyloTree->get(seqTax.parent);
301 if (confidenceTax == "") { confidenceTax = "unclassified;"; simpleTax = "unclassified;"; }
302 return confidenceTax;
305 catch(exception& e) {
306 m->errorOut(e, "Bayesian", "bootstrapResults");
310 /**************************************************************************************************/
311 int Bayesian::getMostProbableTaxonomy(vector<int> queryKmer) {
313 int indexofGenus = 0;
315 double maxProbability = -1000000.0;
316 //find taxonomy with highest probability that this sequence is from it
317 for (int k = 0; k < genusNodes.size(); k++) {
318 //for each taxonomy calc its probability
320 for (int i = 0; i < queryKmer.size(); i++) {
321 prob += wordGenusProb[queryKmer[i]][k];
324 //is this the taxonomy with the greatest probability?
325 if (prob > maxProbability) {
326 indexofGenus = genusNodes[k];
327 maxProbability = prob;
333 catch(exception& e) {
334 m->errorOut(e, "Bayesian", "getMostProbableTaxonomy");
338 /*************************************************************************************************
339 map<string, int> Bayesian::parseTaxMap(string newTax) {
342 map<string, int> parsed;
344 newTax = newTax.substr(0, newTax.length()-1); //get rid of last ';'
348 while (newTax.find_first_of(';') != -1) {
349 individual = newTax.substr(0,newTax.find_first_of(';'));
350 newTax = newTax.substr(newTax.find_first_of(';')+1, newTax.length());
351 parsed[individual] = 1;
360 catch(exception& e) {
361 m->errorOut(e, "Bayesian", "parseTax");
365 /**************************************************************************************************/
366 void Bayesian::readProbFile(ifstream& in, ifstream& inNum, string inName, string inNumName) {
371 int pid, num, num2, processors;
372 vector<unsigned long int> positions;
373 vector<unsigned long int> positions2;
378 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
379 MPI_Comm_size(MPI_COMM_WORLD, &processors);
382 char inFileName[1024];
383 strcpy(inFileName, inNumName.c_str());
385 char inFileName2[1024];
386 strcpy(inFileName2, inName.c_str());
388 MPI_File_open(MPI_COMM_WORLD, inFileName, MPI_MODE_RDONLY, MPI_INFO_NULL, &inMPI); //comm, filename, mode, info, filepointer
389 MPI_File_open(MPI_COMM_WORLD, inFileName2, MPI_MODE_RDONLY, MPI_INFO_NULL, &inMPI2); //comm, filename, mode, info, filepointer
392 positions = setFilePosEachLine(inNumName, num);
393 positions2 = setFilePosEachLine(inName, num2);
395 for(int i = 1; i < processors; i++) {
396 MPI_Send(&num, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
397 MPI_Send(&positions[0], (num+1), MPI_LONG, i, tag, MPI_COMM_WORLD);
399 MPI_Send(&num2, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
400 MPI_Send(&positions2[0], (num2+1), MPI_LONG, i, tag, MPI_COMM_WORLD);
404 MPI_Recv(&num, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
405 positions.resize(num+1);
406 MPI_Recv(&positions[0], (num+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
408 MPI_Recv(&num2, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
409 positions2.resize(num2+1);
410 MPI_Recv(&positions2[0], (num2+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
414 int length = positions2[1] - positions2[0];
415 char* buf = new char[length];
417 MPI_File_read_at(inMPI2, positions2[0], buf, length, MPI_CHAR, &status);
419 string tempBuf = buf;
420 if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
423 istringstream iss (tempBuf,istringstream::in);
426 //initialze probabilities
427 wordGenusProb.resize(numKmers);
429 for (int j = 0; j < wordGenusProb.size(); j++) { wordGenusProb[j].resize(genusNodes.size()); }
432 vector<int> numbers; numbers.resize(numKmers);
434 vector<float> zeroCountProb; zeroCountProb.resize(numKmers);
437 for(int i=0;i<num;i++){
439 length = positions[i+1] - positions[i];
440 char* buf4 = new char[length];
442 MPI_File_read_at(inMPI, positions[i], buf4, length, MPI_CHAR, &status);
445 if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
448 istringstream iss (tempBuf,istringstream::in);
449 iss >> zeroCountProb[i] >> numbers[i];
452 MPI_File_close(&inMPI);
454 for(int i=1;i<num2;i++){
456 length = positions2[i+1] - positions2[i];
457 char* buf4 = new char[length];
459 MPI_File_read_at(inMPI2, positions2[i], buf4, length, MPI_CHAR, &status);
462 if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
465 istringstream iss (tempBuf,istringstream::in);
469 //set them all to zero value
470 for (int i = 0; i < genusNodes.size(); i++) {
471 wordGenusProb[kmer][i] = log(zeroCountProb[kmer] / (float) (genusTotals[i]+1));
474 //get probs for nonzero values
475 for (int i = 0; i < numbers[kmer]; i++) {
477 wordGenusProb[kmer][name] = prob;
481 MPI_File_close(&inMPI2);
482 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
485 in >> numKmers; gobble(in);
487 //initialze probabilities
488 wordGenusProb.resize(numKmers);
490 for (int j = 0; j < wordGenusProb.size(); j++) { wordGenusProb[j].resize(genusNodes.size()); }
492 int kmer, name, count; count = 0;
493 vector<int> num; num.resize(numKmers);
495 vector<float> zeroCountProb; zeroCountProb.resize(numKmers);
498 inNum >> zeroCountProb[count] >> num[count];
507 //set them all to zero value
508 for (int i = 0; i < genusNodes.size(); i++) {
509 wordGenusProb[kmer][i] = log(zeroCountProb[kmer] / (float) (genusTotals[i]+1));
512 //get probs for nonzero values
513 for (int i = 0; i < num[kmer]; i++) {
515 wordGenusProb[kmer][name] = prob;
524 catch(exception& e) {
525 m->errorOut(e, "Bayesian", "readProbFile");
529 /**************************************************************************************************/