5 // Created by Patrick Schloss on 4/3/12.
6 // Copyright (c) 2012 University of Michigan. All rights reserved.
10 #include "aligntree.h"
12 /**************************************************************************************************/
14 AlignTree::AlignTree(string referenceFileName, string taxonomyFileName, int cutoff) : Classify(), confidenceThreshold(cutoff){
16 AlignNode* newNode = new AlignNode("Root", 0);
17 tree.push_back(newNode); // the tree is stored as a vector of elements of type TaxonomyNode
21 readTaxonomy(taxonomyFileName);
23 ifstream referenceFile;
24 m->openInputFile(referenceFileName, referenceFile);
26 map<int, int> lengths;
27 while(!referenceFile.eof()){
29 if (m->control_pressed) { break; }
31 Sequence seq(referenceFile); m->gobble(referenceFile);
33 if (seq.getName() != "") {
34 map<string, string>::iterator it = taxonomy.find(seq.getName());
36 if (it != taxonomy.end()) {
37 refTaxonomy = it->second; // lookup the taxonomy string for the current reference sequence
38 string aligned = seq.getAligned();
39 lengths[aligned.length()] = 1;
40 if (lengths.size() > 1) { error = true; m->mothurOut("[ERROR]: reference sequences must be aligned to use the align method, quitting.\n"); break; }
41 addTaxonomyToTree(seq.getName(), refTaxonomy, aligned);
43 m->mothurOut(seq.getName() + " is in your reference file, but not in your taxonomy file, please correct.\n"); error = true;
47 referenceFile.close();
49 length = (lengths.begin())->first;
51 if (error) { m->control_pressed = true; }
53 numTaxa = (int)tree.size();
56 for(int i=0;i<numTaxa;i++){
57 int level = tree[i]->getLevel();
58 if(level > numLevels){ numLevels = level; }
64 int dbSize = tree[0]->getNumSeqs();
66 for(int i=0;i<numTaxa;i++){
67 tree[i]->checkTheta();
68 tree[i]->setTotalSeqs(dbSize);
73 m->errorOut(e, "AlignTree", "AlignTree");
78 /**************************************************************************************************/
80 AlignTree::~AlignTree(){
82 for(int i=0;i<tree.size();i++){
87 m->errorOut(e, "AlignTree", "~AlignTree");
92 /**************************************************************************************************/
94 int AlignTree::addTaxonomyToTree(string seqName, string& taxonomy, string& sequence){
97 string taxonName = "";
98 int treePosition = 0; // the root is element 0
102 for(int i=0;i<taxonomy.length();i++){ // step through taxonomy string...
104 if (m->control_pressed) { break; }
106 if(taxonomy[i] == ';'){ // looking for semicolons...
108 if (taxonName == "") { m->mothurOut(seqName + " has an error in the taxonomy. This may be due to a ;;"); m->mothurOutEndLine(); m->control_pressed = true; }
110 int newIndex = tree[treePosition]->getChildIndex(taxonName); // look to see if your current node already
111 // has a child with the new taxonName
112 if(newIndex != -1) { treePosition = newIndex; } // if you've seen it before, jump to that
113 else { // position in the tree
114 int newChildIndex = (int)tree.size(); // otherwise, we'll have to create one...
115 tree[treePosition]->makeChild(taxonName, newChildIndex);
117 newNode = new AlignNode(taxonName, level);
119 newNode->setParent(treePosition);
121 tree.push_back(newNode);
122 treePosition = newChildIndex;
125 // sequence data to that node to update that node's theta - seems slow...
126 taxonName = ""; // clear out the taxon name that we will build as we look
130 taxonName += taxonomy[i]; // keep adding letters until we reach a semicolon
133 tree[treePosition]->loadSequence(sequence); // now that we've gotten to the correct node, add the
137 catch(exception& e) {
138 m->errorOut(e, "AlignTree", "addTaxonomyToTree");
143 /**************************************************************************************************/
145 int AlignTree::aggregateThetas(){
147 vector<vector<int> > levelMatrix(numLevels+1);
149 for(int i=0;i<tree.size();i++){
150 if (m->control_pressed) { return 0; }
151 levelMatrix[tree[i]->getLevel()].push_back(i);
154 for(int i=numLevels-1;i>0;i--){
155 if (m->control_pressed) { return 0; }
156 for(int j=0;j<levelMatrix[i].size();j++){
158 AlignNode* holder = tree[levelMatrix[i][j]];
160 tree[holder->getParent()]->addThetas(holder->getTheta(), holder->getNumSeqs());
165 catch(exception& e) {
166 m->errorOut(e, "AlignTree", "aggregateThetas");
171 /**************************************************************************************************/
173 double AlignTree::getOutlierLogProbability(string& sequence){
177 for(int i=0;i<sequence.length();i++){
179 if(sequence[i] != '.'){ count++; }
183 return count * log(0.2);
185 catch(exception& e) {
186 m->errorOut(e, "AlignTree", "getOutlierLogProbability");
191 /**************************************************************************************************/
193 int AlignTree::getMinRiskIndexAlign(string& sequence, vector<int>& taxaIndices, vector<double>& probabilities){
195 int numProbs = (int)probabilities.size();
197 vector<double> G(numProbs, 0.2); //a random sequence will, on average, be 20% similar to any other sequence
198 vector<double> risk(numProbs, 0);
200 for(int i=1;i<numProbs;i++){ //use if you want the outlier group
201 if (m->control_pressed) { return 0; }
202 G[i] = tree[taxaIndices[i]]->getSimToConsensus(sequence);
205 double minRisk = 1e6;
206 int minRiskIndex = 0;
208 for(int i=0;i<numProbs;i++){
209 if (m->control_pressed) { return 0; }
210 for(int j=0;j<numProbs;j++){
212 risk[i] += probabilities[j] * G[j];
216 if(risk[i] < minRisk){
224 catch(exception& e) {
225 m->errorOut(e, "AlignTree", "getMinRiskIndexAlign");
231 /**************************************************************************************************/
233 int AlignTree::sanityCheck(vector<vector<int> >& indices, vector<int>& maxIndices){
235 int finalLevel = (int)indices.size()-1;
237 for(int position=1;position<indices.size();position++){
238 if (m->control_pressed) { return 0; }
239 int predictedParent = tree[indices[position][maxIndices[position]]]->getParent();
240 int actualParent = indices[position-1][maxIndices[position-1]];
242 if(predictedParent != actualParent){
243 finalLevel = position - 1;
249 catch(exception& e) {
250 m->errorOut(e, "AlignTree", "sanityCheck");
255 /**************************************************************************************************/
257 string AlignTree::getTaxonomy(Sequence* seq){
259 string seqName = seq->getName(); string querySequence = seq->getAligned(); string taxonProbabilityString = "";
260 if (querySequence.length() != length) {
261 m->mothurOut("[ERROR]: " + seq->getName() + " has length " + toString(querySequence.length()) + ", reference sequences length is " + toString(length) + ". Are your sequences aligned? Sequences must be aligned to use the align search method.\n"); m->control_pressed = true; return "";
263 double logPOutlier = getOutlierLogProbability(querySequence);
265 vector<vector<double> > pXgivenKj_D_j(numLevels);
266 vector<vector<int> > indices(numLevels);
267 for(int i=0;i<numLevels;i++){
268 if (m->control_pressed) { return taxonProbabilityString; }
269 pXgivenKj_D_j[i].push_back(logPOutlier);
270 indices[i].push_back(-1);
274 for(int i=0;i<numTaxa;i++){
275 // cout << i << '\t' << tree[i]->getName() << '\t' << tree[i]->getLevel() << '\t' << tree[i]->getPxGivenkj_D_j(querySequence) << endl;
276 if (m->control_pressed) { return taxonProbabilityString; }
277 pXgivenKj_D_j[tree[i]->getLevel()].push_back(tree[i]->getPxGivenkj_D_j(querySequence));
278 indices[tree[i]->getLevel()].push_back(i);
281 vector<double> sumLikelihood(numLevels, 0);
282 vector<double> bestPosterior(numLevels, 0);
283 vector<int> maxIndex(numLevels, 0);
284 int maxPosteriorIndex;
287 //cout << "before best level" << endl;
289 //let's find the best level and taxa within that level
290 for(int i=0;i<numLevels;i++){ //go across all j's - from the root to genus
291 if (m->control_pressed) { return taxonProbabilityString; }
292 int numTaxaInLevel = (int)indices[i].size();
294 //cout << "numTaxaInLevel:\t" << numTaxaInLevel << endl;
296 vector<double> posteriors(numTaxaInLevel, 0);
297 sumLikelihood[i] = getLogExpSum(pXgivenKj_D_j[i], maxPosteriorIndex);
299 maxPosteriorIndex = 0;
300 for(int j=0;j<numTaxaInLevel;j++){
301 posteriors[j] = exp(pXgivenKj_D_j[i][j] - sumLikelihood[i]);
303 if(posteriors[j] > posteriors[maxPosteriorIndex]){
304 maxPosteriorIndex = j;
309 maxIndex[i] = getMinRiskIndexAlign(querySequence, indices[i], posteriors);
311 maxIndex[i] = maxPosteriorIndex;
312 bestPosterior[i] = posteriors[maxIndex[i]];
315 // vector<double> pX_level(numLevels, 0);
317 // for(int i=0;i<numLevels;i++){
318 // pX_level[i] = pXgivenKj_D_j[i][maxIndex[i]] - tree[indices[i][maxIndex[i]]]->getNumSeqs();
321 // int max_pLevel_X_index = -1;
322 // double pX_level_sum = getLogExpSum(pX_level, max_pLevel_X_index);
323 // double max_pLevel_X = exp(pX_level[max_pLevel_X_index] - pX_level_sum);
325 // vector<double> pLevel_X(numLevels, 0);
326 // for(int i=0;i<numLevels;i++){
327 // pLevel_X[i] = exp(pX_level[i] - pX_level_sum);
333 int saneDepth = sanityCheck(indices, maxIndex);
337 taxonProbabilityString = "";
338 for(int i=1;i<=saneDepth;i++){
339 if (m->control_pressed) { return taxonProbabilityString; }
340 int confidenceScore = (int) (bestPosterior[i] * 100);
341 if (confidenceScore >= confidenceThreshold) {
342 if(indices[i][maxIndex[i]] != -1){
343 taxonProbabilityString += tree[indices[i][maxIndex[i]]]->getName() + '(' + toString(confidenceScore) + ");";
344 simpleTax += tree[indices[i][maxIndex[i]]]->getName() + ";";
345 // levelProbabilityOutput << tree[indices[i][maxIndex[i]]]->getName() << '(' << setprecision(6) << pLevel_X[i] << ");";
348 taxonProbabilityString + "unclassified" + '(' + toString(confidenceScore) + ");";
349 // levelProbabilityOutput << "unclassified" << '(' << setprecision(6) << pLevel_X[i] << ");";
350 simpleTax += "unclassified;";
356 for(int i=savedspot+1;i<numLevels;i++){
357 if (m->control_pressed) { return taxonProbabilityString; }
358 taxonProbabilityString + "unclassified(0);";
359 simpleTax += "unclassified;";
362 return taxonProbabilityString;
364 catch(exception& e) {
365 m->errorOut(e, "AlignTree", "getTaxonomy");
371 /**************************************************************************************************/