#ifndef EPOCHDLTRS_HH #define EPOCHDLTRS_HH #include #include #include "Beep.hh" #include "BeepVector.hh" #include "EdgeWeightModel.hh" #include "EpochPtSet.hh" #include "EpochPtMaps.hh" #include "LambdaMap.hh" #include "PerturbationObservable.hh" namespace beep { // Forward declarations. class Density2P; class EpochBDTProbs; class EpochTree; class Node; class Probability; class StrStrMap; class TreePerturbationEvent; /** * In accordance with the DTLRS model, computes the probability of * a guest tree topology and branch lengths given remaining parameters * and a "dated" host tree. * * DTLRS in short: * 1) A guest tree topology G evolves inside a host tree by means of * duplication, loss and transfer rates (say delta, mu, tau). * 2) Substitution rates for edges in the guest tree are drawn IID * from a gamma distribution with mean m and variance v. Rates r are * computed as r=l/t where l are the guest tree branch lengths and t are * the timespans in the host tree. This gives a relaxed molecular clock. * 3) Sequence evolution is guided by a substitution model of choice. * * The host tree topology S (including times t) is assumed to be known. * The probability Pr[G,l | delta,mu,tau,m,v] is approximated by discretizing * S and considering all possible "dated" reconciliations of G and l with * respect to the discretization using dynamic programming. * * Two approximations are made: * A) Of two adjacent duplication/transfer events in G (i.e. two connected * vertices), only one is allowed to occur in a discretization interval. * B) The probability of the duplication/transfer event in the * interval is approximated by the event density at the midpoint multiplied * with the interval timestep. * * Implementation note: * * The class naturally depends on the mentioned parameters. Therefore, it * acts as an observer listening for changes to these, S topology and times * excluded. S changes are not allowed at the moment. * * @author Joel Sjöstrand. */ class EpochDLTRS : public EdgeWeightModel, public PerturbationObserver { typedef std::set nodeset; typedef std::vector nodevec; typedef std::vector probvec; typedef BeepVector PtMapVector; public: /** * Constructor. * @param G guest tree (topology). * @param ES discretized host tree topology and times. * @param GSMap guest-to-host leaf map. * @param edgeRateDF edge rate density function. * @param BDTProbs birth, death and transfer rates * and related probabilities. */ EpochDLTRS(Tree& G, EpochTree& ES, StrStrMap& GSMap, Density2P& edgeRateDF, EpochBDTProbs& BDTProbs); /** * Destructor. */ virtual ~EpochDLTRS(); /** * Returns the guest tree. * @return the guest tree. */ virtual const Tree& getTree() const; /** * Returns the number of weights, i.e. (roughly) the number of * edges in the guest tree. * @return the number of perturbable lengths. */ virtual unsigned nWeights() const; /** * Returns the edge lengths of the guest tree. * @return the lengths of the guest tree. */ virtual RealVector& getWeightVector() const; /** * Returns the length of an edge in the guest tree. * @param node the lower node of the edge. * @return the length of the edge. */ virtual Real getWeight(const Node& node) const; /** * Sets the length of an edge in the guest tree. * @param weight the length to be set. * @param u the lower node of the edge. */ virtual void setWeight(const Real& weight, const Node& u); /** * Returns the valid range of the underlying rate density function. * Note: is this sound? * @param low the lower value of the range. * @param high the upper value of the range. */ virtual void getRange(Real& low, Real& high); /** * Returns info on how root edge weights are perturbed. * @return perturbation technique. */ virtual RootWeightPerturbation getRootWeightPerturbation() const { return EdgeWeightModel::BOTH; } /** * Has no effect. * @param rwp */ virtual void setRootWeightPerturbation(RootWeightPerturbation rwp) {} /** * Returns a string with information about the rate * probabilities of the guest tree. * @return an info string. */ virtual std::string print() const; /** * Callback method for notifying this object about changes to the * underlying parameter holders: birth-death-transfer rates, guest tree * (both topology and edge lengths), and edge rate. * Updates or restores the internal probabilities depending on event. * @param sender the address of the parameter holder which has * been perturbed. * @param event the kind of perturbation. Null value results in * full update. */ virtual void perturbationUpdate(const PerturbationObservable* sender, const PerturbationEvent* event); /** * Currently does nothing. All updates are made in (callbacks to) * perturbationUpdate(). */ virtual void update(); /** * Returns the data probability with respect to possible * reconciliations given that the lineage starts at the top. * Requires that probability data structures are up-to-date. * @return the data probability. */ virtual Probability calculateDataProbability(); /** * Returns true if we count transfers. * @return true when counting transfers. */ virtual bool hasOwnStatus(); /** * Returns a header creating names for model output * parameters. */ virtual std::string ownStatusHeader(); /** * Returns output parameters for model. */ virtual std::string ownStatusStrRep(); /** * Returns an info string for debugging. * @param inclAtAndLinProbs true shows current probabilities. * @return an info string. */ std::string getDebugInfo(bool inclAtAndLinProbs = false) const; private: /** * Helper. Updates help data structures. Invoke before computing * probabilities (partial as well as full). */ void updateHelpStructs(); /** * Recursive helper. Finds and stores the lowest possible * discretized time in ES on which a node u of G can be placed. * Recursively processes all nodes in the subtree below * (and including) the specified node. * @param u the root of the subtree of G. */ void updateLoLim(const Node* u); /** * Recursive helper. Finds and stores the highest possible * discretized time in ES on which a node u of G can be placed. * Recursively processes all nodes in the subtree below * (and including) the specified node. * @param u the root of the subtree of G. */ void updateUpLim(const Node* u); /** * Makes a clean update of probability data structures. Requires * that help data structures are up-to-date. */ void updateProbsFull(); /** * Helper. Makes a partial update of probability data structures based * on information on guest tree changes. Requires that help data * structures are up-to-date. * @param details info about guest tree changes. Must not be null. */ void updateProbsPartial(const TreePerturbationEvent* details); /** * Helper. Updates all at-probabilities for the specified node u of G, * i.e. the probabilites of the rooted subtree G_u for all valid * placements of u. Requires that help structures are up-to-date, * as well as u's children's probabilities in case of a * non-recursive call. Note: leaf values are not stored since they * can only be placed at sigma(u) by definition. * @param u the node of G. * @param doRecurse true to process children recursively first. */ void updateAtProbs(const Node* u, bool doRecurse); /** * Helper. Invoked by updateAtProbs(). * Updates all at-probabilities for node u of G being * placed at time s, where s is a speciation time, i.e. the * first time of an epoch. * @param u the non-leaf node of G. * @param s the speciation time. */ void atSpec(const Node* u, const EpochTime& s); /** * Helper. Invoked by updateAtProbs(). * Updates all at-probabilities for node u of G being * placed at time s, where s is not a speciation time, i.e. * not the first time of an epoch. Recursively updates the lin- * probabilities for u's children first. * @param u the non-leaf node of G. * @param s the duplication/transfer time. */ void atDupOrTrans(const Node* u, const EpochTime& s); /** * Helper. Updates all probabilities for the planted subtree G^u * when the lineage starts at time s. At-probabilites for all rooted * subtrees G_u strictly below s must be up-to-date. * @param u the node of G. * @param s the time when the lineage leading to u starts. */ void updateLinProbs(const Node* u, const EpochTime& s); /** * Helper. Works similarly to updateLinProbs() but for the root lineage * of G starting at the very top of ES. */ void updateLinProbsForTop(); /** * Helper. Calculates probability density function value of * specified edge substitution rate. * @param l the length. * @param t the time. * @return pdf value of l/t. */ inline Probability calcRateDensity(Real l, Real t) const { // There is apparently need for a more robust solution than just returning // the pdf value. Seemingly, this has to do with the pdf on input like 0+eps // becoming ill-conditioned. By employing some sort of simple interpolation // technique we may be able to avoid this. // Plain PDF. Gives convergence problems on small trees. //Real r = l / t; //return m_edgeRateDF(r); // Average PDF by dividing CDF with small interval length. //Real r = l / t; //Real dr = std::min(1e-6, r / 2); //return ((m_edgeRateDF.cdf(r + dr) - m_edgeRateDF.cdf(r - dr)) / (2 * dr)); // Average PDF by dividing CDF with larger interval length based on timestep. Real r2 = l / (t - m_rateDelta), r1 = l / (t + m_rateDelta); return ((m_edgeRateDF.cdf(r2) - m_edgeRateDF.cdf(r1)) / (r2 - r1)); // No rate. Use e.g. when debugging. //return 1.0; } /** * Helper. Caches at- and lin-probabilities. If null is passed * in as a parameter, all values are cached. Otherwise, only * those values correponding to parts of G which have changed are * cached. * @param details detailed pertubation info about changes to G's * topology or lengths, otherwise null for a complete caching. */ void cacheProbs(const TreePerturbationEvent* details); /** * Helper. Caches all probabilites for specified node. * @param u the node of G for which to cache. * @param doRecurse true to process children recursively. */ void cacheNodeProbs(const Node* u, bool doRecurse); /** * Helper. Restores cached probabilities. These may concern * parts of or all of the guest tree G. */ void restoreCachedProbs(); /** * Helper. Restores all cached probabilites. */ void clearAllCachedProbs(); public: private: /** The guest tree G. */ Tree& m_G; /** The discretized epoch host tree S, coined ES. */ EpochTree& m_ES; /** Guest-to-host tree leaf map. */ /*const*/ StrStrMap& m_GSMap; /** Edge rate density function. */ Density2P& m_edgeRateDF; /** Birth, death and lateral transfer probs. for points in ES. */ EpochBDTProbs& m_BDTProbs; /** Convenience shorthand to values in BDTProbs. */ const RealEpochPtPtMap& m_Qef; /** Guest-to-host tree sigma map. */ LambdaMap m_sigma; /** Guest-to-host leaf map. Refers to leaf epoch edge indices. */ UnsignedVector m_sigmaLeaves; /** * Pointer to the lengths of G. Although the tree itself takes care of * ownership and destruction, the lengths are affected using * a weight handler and methods of this class, and not through length * methods in Tree. Please be aware of this. */ mutable RealVector* m_lengths; /** * For each node u of G, the time identifier of the lowermost * placement in ES where u can be placed. Note: Time index in * epoch is 0 for leaves, but always greater than 0 for non-leaves. * This is because points below refer to the same time value. */ BeepVector m_loLims; /** * For each node u of G, the time identifier of the uppermost * placement in ES where u can be placed. Note: This is always * smaller than "last" point of epoch in question. * This is because points above refer to the same time value. */ BeepVector m_upLims; /** * For each node u of G, the probability of the * rooted subtree G_u when u is placed on a particular * discretization point in ES. Note: never used for leaves. * Only the parts contained within boundaries loLims and * upLims are used. Other values are usually (but not * necessarily reset to) zero. */ PtMapVector m_ats; /** * For each node u of G, the probability of the planted * subtree G^u when the lineage leading down to u is * placed on a particular discretization point in ES. * Note: for non-leaf nodes, values at time index 0 of * an epoch are never set, since these are implied by the * (last) contemporary points of the epoch below. * Only the parts contained within boundaries loLims and * upLims of its parent are used. Other values are usually * (but not necessarily reset to) zero. */ PtMapVector m_lins; /** * Flag for counting transfers when updating probabilities. * Is normally set to zero, but during sampling output it is * set to maxcount+1 (implying to count transfers k=0...maxcount * when updating). */ unsigned m_counts; const std::vector* m_Qefk; /**< Count-specific Qef-probs. Not cached. */ std::vector m_atsk; /**< Count-specific at-probs. Not cached. */ std::vector m_linsk; /**< Count-specific lin-probs. Not cached. */ /** For interpolating rates. */ Real m_rateDelta; }; } // end namespace beep #endif /* EPOCHDLTRS_HH */