#include "AnError.hh" #include "Density2P.hh" #include "EpochBDTProbs.hh" #include "EpochDLTRS.hh" #include "Node.hh" #include "Probability.hh" #include "StrStrMap.hh" #include "TreeIO.hh" #include "TreePerturbationEvent.hh" #include #include #include namespace beep { using namespace std; EpochDLTRS::EpochDLTRS( Tree& G, EpochTree& ES, StrStrMap& GSMap, Density2P& edgeRateDF, EpochBDTProbs& BDTProbs) : EdgeWeightModel(), PerturbationObserver(), m_G(G), m_ES(ES), m_GSMap(GSMap), m_edgeRateDF(edgeRateDF), m_BDTProbs(BDTProbs), m_Qef(BDTProbs.getOneToOneProbs()), m_sigma(G, ES.getOrigTree(), GSMap), m_sigmaLeaves(G), m_lengths(NULL), m_loLims(G), m_upLims(G), m_ats(G, ProbabilityEpochPtMap(ES, 0.0)), m_lins(G, ProbabilityEpochPtMap(ES, 0.0)), m_counts(0), m_atsk(), m_linsk(), m_rateDelta(0.0) { // We assign space for transfer counts k=0,...,cnt-1. unsigned cnt = m_BDTProbs.getNoOfTransferCounts(); m_atsk.assign(cnt, PtMapVector(G, ProbabilityEpochPtMap(ES, 0.0))); m_linsk.assign(cnt, PtMapVector(G, ProbabilityEpochPtMap(ES, 0.0))); // Let get reference to or create G's edge weights. if (G.hasLengths()) { m_lengths = &G.getLengths(); } else { m_lengths = new RealVector(G.getNumberOfNodes(), edgeRateDF.getMean()); G.setLengths(*m_lengths, true); } // Set rate delta to a quarter of smallest timestep (for instance). m_rateDelta = ES.getMinTimestep() / 4; // Compute values to have something to start with. updateHelpStructs(); updateProbsFull(); // Register as listener on parameter holders we depend on. m_G.addPertObserver(this); m_BDTProbs.addPertObserver(this); m_edgeRateDF.addPertObserver(this); } EpochDLTRS::~EpochDLTRS() { } const Tree& EpochDLTRS::getTree() const { return m_G; } unsigned EpochDLTRS::nWeights() const { // Top time edge is never perturbed. // TODO: Consider adding support for shared // root edges (implying one parameter less). return (m_G.getNumberOfNodes() - 1); } RealVector& EpochDLTRS::getWeightVector() const { return (*m_lengths); } Real EpochDLTRS::getWeight(const Node& node) const { return (*m_lengths)[node]; } void EpochDLTRS::setWeight(const Real& weight, const Node& u) { // TODO: Consider adding support for shared root edges // (implying setting the other too whenever one is set). (*m_lengths)[u] = weight; } void EpochDLTRS::getRange(Real& low, Real& high) { m_edgeRateDF.getRange(low, high); } string EpochDLTRS::print() const { ostringstream oss; oss << "The edge rate is modeled using a" << endl << m_edgeRateDF.print(); return oss.str(); } void EpochDLTRS::perturbationUpdate(const PerturbationObservable* sender, const PerturbationEvent* event) { // We may have access to details if sender is G. const TreePerturbationEvent* details = dynamic_cast(event); // Restore or recompute probabilities depending on event. // If G is sender, look for detailed info to make optimized update. // Sometimes we override a partial update with a full, to prevent accumulating numeric errors, etc. static long iter = 0; if (event != NULL && event->getType() == PerturbationEvent::RESTORATION) { restoreCachedProbs(); // Restore before updating help structures! updateHelpStructs(); // Unnecessary, but included for symmetry/debugging clarity. } else if (iter % 20 != 0 && sender == &m_G && details != NULL) { updateHelpStructs(); cacheProbs(details); updateProbsPartial(details); } else { updateHelpStructs(); cacheProbs(NULL); updateProbsFull(); } ++iter; } void EpochDLTRS::update() { } void EpochDLTRS::updateHelpStructs() { m_sigma.update(m_G, m_ES.getOrigTree()); // Retrieve edge index in leaf epoch for each leaf in guest tree. const nodevec& lz = m_ES[0].getEdges(); for (Tree::const_iterator it = m_G.begin(); it != m_G.end(); ++it) { const Node* u = (*it); if (u->isLeaf()) { const Node* sigma = m_sigma[u]; for (unsigned i = 0; true; ++i) { if (lz[i] == sigma) { m_sigmaLeaves[u] = i; break; } } } } // Retrieve placement bounds for each node u of G. const Node* uRoot = m_G.getRootNode(); updateLoLim(uRoot); updateUpLim(uRoot); // Verify that guest tree fits within discretization. for (Tree::const_iterator it = m_G.begin(); it != m_G.end(); ++it) { if (m_upLims[*it] < m_loLims[*it]) throw AnError("Too few discretization steps -- guest tree won't fit!", 1); } } void EpochDLTRS::updateLoLim(const Node* u) { if (u->isLeaf()) { m_loLims[u] = EpochTime(0, 0); } else { // Update children first. updateLoLim(u->getLeftChild()); updateLoLim(u->getRightChild()); // Set limit of u to above childrens' limits. EpochTime lcLo = m_loLims[u->getLeftChild()]; EpochTime rcLo = m_loLims[u->getRightChild()]; m_loLims[u] = m_ES.getEpochTimeAboveStrict((lcLo > rcLo) ? lcLo : rcLo); } } void EpochDLTRS::updateUpLim(const Node* u) { if (u->isLeaf()) { m_upLims[u] = EpochTime(0, 0); } else if (u->isRoot()) { // Beneath very tip of host tree. Placement on the actual // tip is disallowed. EpochTime top = m_ES.getEpochTimeAtTop(); m_upLims[u] = EpochTime(top.first, top.second - 1); } else { // Normal case: set u's limit just beneth parent's limit. m_upLims[u] = m_ES.getEpochTimeBelowStrict(m_upLims[u->getParent()]); } // Update children afterwards. if (!u->isLeaf()) { updateUpLim(u->getLeftChild()); updateUpLim(u->getRightChild()); } } Probability EpochDLTRS::calculateDataProbability() { // Return value for planted tree G^u with lineage // starting at tip of host tree. const Node* uRoot = m_G.getRootNode(); return m_lins[uRoot].getTopmost(); } void EpochDLTRS::updateProbsFull() { updateAtProbs(m_G.getRootNode(), true); updateLinProbsForTop(); } void EpochDLTRS::updateProbsPartial(const TreePerturbationEvent* details) { // Do a recursive update on all changed subtrees. const nodeset& subtrees = details->getSubtrees(); for (nodeset::iterator it = subtrees.begin(); it != subtrees.end(); ++it) { updateAtProbs(*it, true); } // Do a non-recursive update along the changed root paths. // If we have two paths, follow the second one up to intersection // with the first, then do entire first. const Node* p1; const Node* p2; details->getRootPaths(p1, p2); if (p2 != NULL) { const Node* lca = m_G.mostRecentCommonAncestor(p1, p2); while (p2 != lca) { updateAtProbs(p2, false); p2 = p2->getParent(); } } while (p1 != NULL) { updateAtProbs(p1, false); p1 = p1->getParent(); } // Finally, update lineage from top. updateLinProbsForTop(); } void EpochDLTRS::updateAtProbs(const Node* u, bool doRecurse) { if (u->isLeaf()) { return; } if (doRecurse) { // Must do children first, if specified. updateAtProbs(u->getLeftChild(), true); updateAtProbs(u->getRightChild(), true); } // Retrieve placement bounds for u. // Note: Time index of upLim in epoch in question is 0. EpochTime upLim = m_upLims[u]; EpochTime s = m_loLims[u]; // For each valid placement time s. while (s <= upLim) { if (s.second == 0) { atSpec(u, s); // Speciation at s. } else { atDupOrTrans(u, s); // Duplication or transfer at s. } s = m_ES.getEpochTimeAbove(s); } } void EpochDLTRS::atSpec(const Node* u, const EpochTime& s) { const Node* lc = u->getLeftChild(); const Node* rc = u->getRightChild(); probvec& ats = m_ats[u](s); unsigned sz = ats.size(); EpochTime sb = m_ES.getEpochTimeBelow(s); unsigned split = m_ES.getSplitIndex(s.first); // Get speciation probability by multiplying lineage values // from children. At the moment, we set values for all remaining // contemporaries to 0. ats.assign(sz, Probability(0.0)); ats[split] = m_lins[lc](sb, split) * m_lins[rc](sb, split+1) + m_lins[lc](sb, split+1) * m_lins[rc](sb, split); // When counting transfers, do analogously with above, // but maintain k transfers along the way. for (unsigned k = 0; k < m_counts; ++k) { probvec& atsk = m_atsk[k][u](s); atsk.assign(sz, Probability(0.0)); for (unsigned kp = 0, kb = k - kp; kp <= k; ++kp, --kb) { atsk[split] += m_linsk[kp][lc](sb, split) * m_linsk[kb][rc](sb, split+1) + m_linsk[kp][lc](sb, split+1) * m_linsk[kb][rc](sb, split); } } } void EpochDLTRS::atDupOrTrans(const Node* u, const EpochTime& s) { // Note: We perform two approximations: // 1) Only one adjacent duplication/transfer event is allowed // per subinterval. // 2) The probability of an event in a subinterval is estimated // by multiplying the density for the event at the midpoint // with the interval timestep. Real dt = m_ES.getTimestep(s.first); const Node* lc = u->getLeftChild(); const Node* rc = u->getRightChild(); probvec& ats = m_ats[u](s); unsigned sz = ats.size(); Real dupFact = 2 * m_BDTProbs.getBirthRate(); Real trFact = m_BDTProbs.getTransferRate() / (sz - 1); // Compute probs for all planted subtrees G^lc and G^rc with // lineages starting at time s. updateLinProbs(lc, s); updateLinProbs(rc, s); // Compute probs for all rooted subtrees G_u at s. const probvec& lclins = m_lins[lc](s); const probvec& rclins = m_lins[rc](s); if (sz > 1) { Probability lcsum = accumulate(lclins.begin(), lclins.end(), Probability(0.0)); Probability rcsum = accumulate(rclins.begin(), rclins.end(), Probability(0.0)); for (unsigned e = 0; e < sz; ++e) { ats[e] = dt * (dupFact * lclins[e] * rclins[e] + trFact * (lclins[e] * (rcsum - rclins[e]) + rclins[e] * (lcsum - lclins[e]))); } } else { // Case with top time edge. No transfer possible. ats[0] = dt * dupFact * lclins[0] * rclins[0]; } // When counting transfers, do analogously with above, // but maintain k transfers along the way. for (unsigned k = 0; k < m_counts; ++k) { probvec& atsk = m_atsk[k][u](s); atsk.assign(sz, Probability(0.0)); // Reset all first. if (sz > 1) { // First handle the duplication case. for (unsigned kp = 0, kb = k - kp; kp <= k; ++kp, --kb) { for (unsigned e = 0; e < sz; ++e) { atsk[e] += (dt * dupFact * m_linsk[kp][lc](s)[e] * m_linsk[kb][rc](s)[e]); } } // ...then the transfer case with k-1 transfers below. Notice <. for (unsigned kp = 0, kb = k - 1 - kp; kp < k; ++kp, --kb) { const probvec& lclinskp = m_linsk[kp][lc](s); const probvec& rclinskp = m_linsk[kp][rc](s); const probvec& lclinskb = m_linsk[kb][lc](s); const probvec& rclinskb = m_linsk[kb][rc](s); Probability lcsumkb = accumulate(lclinskb.begin(), lclinskb.end(), Probability(0.0)); Probability rcsumkb = accumulate(rclinskb.begin(), rclinskb.end(), Probability(0.0)); for (unsigned e = 0; e < sz; ++e) { atsk[e] += (dt * trFact * (lclinskp[e] * (rcsumkb - rclinskb[e]) + rclinskp[e] * (lcsumkb - lclinskb[e]))); } } } else { // Case with top time edge. No transfer possible. for (unsigned kp = 0, kb = k - kp; kp <= k; ++kp, --kb) { atsk[0] += dt * dupFact * m_linsk[kp][lc](s)[0] * m_linsk[kb][rc](s)[0]; } } } } void EpochDLTRS::updateLinProbs(const Node* u, const EpochTime& s) { Real sTime = m_ES.getTime(s); Real l = (*m_lengths)[u]; probvec& lins = m_lins[u](s); unsigned sz = lins.size(); if (u->isLeaf()) { unsigned sigma = m_sigmaLeaves[u]; Probability rateDens = u->isRoot() ? 1.0 : calcRateDensity(l, sTime); // For each edge e where lineage can start at time s. for (unsigned e = 0; e < sz; ++e) { lins[e] = m_Qef(s.first, s.second, e, 0, 0, sigma) * rateDens; } // When counting transfers, do analogously with above, // but maintain k transfers along the way. for (unsigned k = 0; k < m_counts; ++k) { probvec& linsk = m_linsk[k][u](s); const RealEpochPtPtMap& Qefk = (*m_Qefk)[k]; for (unsigned e = 0; e < sz; ++e) { linsk[e] = Qefk(s.first, s.second, e, 0, 0, sigma) * rateDens; } } } else { // Reset values. lins.assign(sz, Probability(0.0)); for (unsigned k = 0; k < m_counts; ++k) { m_linsk[k][u](s).assign(sz, Probability(0.0)); } // We always ignore last time index for at-probs of current epoch, // since such values are correctly stored at index 0 of next epoch. EpochTime t = m_loLims[u]; if (m_ES.isLastEpochTime(t)) { t = EpochTime(t.first+1, 0); } // For each valid time t where u can be placed. while (t < s) { Probability rateDens = u->isRoot() ? 1.0 : calcRateDensity(l, sTime - m_ES.getTime(t)); // For each edge e where lineage can start at time s. const probvec& ats = m_ats[u](t); for (unsigned e = 0; e < sz; ++e) { // For each edge f where u can be placed at time t. for (unsigned f = 0; f < ats.size(); ++f) { lins[e] += m_Qef(s, e, t, f) * rateDens * ats[f]; } } // When counting transfers, do analogously with above, // but maintain k transfers along the way. for (unsigned k = 0; k < m_counts; ++k) { probvec& linsk = m_linsk[k][u](s); for (unsigned kp = 0, kb = k - kp; kp <= k; ++kp, --kb) { const RealEpochPtPtMap& Qefkp = (*m_Qefk)[kp]; const probvec& atskb = m_atsk[kb][u](t); for (unsigned e = 0; e < sz; ++e) { for (unsigned f = 0; f < atskb.size(); ++f) { linsk[e] += Qefkp(s, e, t, f) * rateDens * atskb[f]; } } } } t = m_ES.getEpochTimeAboveNotLast(t); } } } void EpochDLTRS::updateLinProbsForTop() { EpochTime sTop = m_ES.getEpochTimeAtTop(); updateLinProbs(m_G.getRootNode(), sTop); } void EpochDLTRS::cacheProbs(const TreePerturbationEvent* details) { clearAllCachedProbs(); if (details == NULL) { // Store all values. cacheNodeProbs(m_G.getRootNode(), true); } else { // Store only relevant values. const nodeset& subtrees = details->getSubtrees(); for (nodeset::const_iterator it = subtrees.begin(); it != subtrees.end(); ++it) { cacheNodeProbs(*it, true); } const Node* p1; const Node* p2; details->getRootPaths(p1, p2); if (p2 != NULL) { const Node* lca = m_G.mostRecentCommonAncestor(p1, p2); while (p2 != lca) { cacheNodeProbs(p2, false); p2 = p2->getParent(); } } while (p1 != NULL) { cacheNodeProbs(p1, false); p1 = p1->getParent(); } } } void EpochDLTRS::cacheNodeProbs(const Node* u, bool doRecurse) { m_lins[u].cache(); if (!u->isLeaf()) { m_ats[u].cache(); // Leaves's "ats" are never used. if (doRecurse) { cacheNodeProbs(u->getLeftChild(), true); cacheNodeProbs(u->getRightChild(), true); } } } void EpochDLTRS::restoreCachedProbs() { for (Tree::const_iterator it = m_G.begin(); it != m_G.end(); ++it) { m_lins[*it].restoreCache(); m_ats[*it].restoreCache(); } } void EpochDLTRS::clearAllCachedProbs() { for (Tree::const_iterator it = m_G.begin(); it != m_G.end(); ++it) { m_lins[*it].invalidateCache(); m_ats[*it].invalidateCache(); } } bool EpochDLTRS::hasOwnStatus() { return (m_BDTProbs.getNoOfTransferCounts() > 0); } string EpochDLTRS::ownStatusHeader() { ostringstream oss; unsigned cnts = m_BDTProbs.getNoOfTransferCounts(); //oss << "TransferAll(logfloat);\t"; for (unsigned k = 0; k < cnts; ++k) { oss << "TransferRatio" << k << "(float);" << "\t"; } oss << "TransferCountRatio(float);\t"; return oss.str(); } string EpochDLTRS::ownStatusStrRep() { std::ostringstream oss; // Turn on counting. m_counts = m_BDTProbs.getNoOfTransferCounts(); // First, make full update of BDT probabilities with counts enabled. m_Qefk = m_BDTProbs.getOneToOneProbsForCounts(); // Make full update of at- and lin-probabilities including counts. updateHelpStructs(); updateProbsFull(); // Print count ratios. const Node* uRoot = m_G.getRootNode(); Probability totProb = m_lins[uRoot].getTopmost(); Probability accProb = 0.0; //oss << totProb << '\t'; for (unsigned k = 0; k < m_counts; ++k) { Probability kProb = m_linsk[k][uRoot].getTopmost(); oss << (kProb / totProb).val() << ";\t"; accProb += kProb; } oss << (accProb / totProb).val() << ";\t"; // Turn off counting. m_counts = 0; return oss.str(); } string EpochDLTRS::getDebugInfo(bool inclAtAndLinProbs) const { ostringstream oss; oss << "# =================================== EPOCHDLTRS ===================================" << endl; oss << "# Node:\tName:\tP:\tLC:\tRC:\tLeaf-sigma:\tLength:\tSpan:" << endl; for (Tree::iterator it = m_G.begin(); it != m_G.end(); ++it) { const Node* u = (*it); oss << "# " << u->getNumber() << '\t' << (u->isLeaf() ? u->getName() : (u->isRoot() ? "Root" : " ")) << '\t' << (u->isRoot() ? -1 : static_cast(u->getParent()->getNumber())) << '\t' << (u->isLeaf() ? -1 : static_cast(u->getLeftChild()->getNumber())) << '\t' << (u->isLeaf() ? -1 : static_cast(u->getRightChild()->getNumber())) << '\t' << (u->isLeaf() ? static_cast(m_sigmaLeaves[u]) : -1) << '\t' << (*m_lengths)[u] << '\t' << '(' << m_loLims[u].first << ',' << m_loLims[u].second << ")..." << '(' << m_upLims[u].first << ',' << m_upLims[u].second << ")" << '\t' << endl; } if (inclAtAndLinProbs) { for (Tree::iterator it = m_G.begin(); it != m_G.end(); ++it) { const Node* u = (*it); oss << "# At and lin probs for " << u->getNumber() << " " << (u->isLeaf() ? u->getName() : (u->isRoot() ? "Root" : "")) << endl; if (!u->isLeaf()) { oss << m_ats[u]; } oss << m_lins[u]; } } oss << "# =====================================================================================" << endl; return oss.str(); } } // end namespace beep