#ifndef EPOCHDISCBDTPROBS_HH #define EPOCHDISCBDTPROBS_HH #include #include "Beep.hh" #include "ODESolver.hh" #include "PerturbationObservable.hh" #include "EpochTree.hh" #include "EpochPtMaps.hh" namespace beep { /** * Holder of birth (duplication), death (loss) and lateral transfer rates * (all typically perturbed parameters) for a discretized host tree with * epochs. In addition, the * class keeps precomputed probabilities related to the rates for swift * access. The precomputed values are first solved numerically for points * within each epoch with aid of the ODE solver superclass. Probabilites * between points of different epochs are then assembled without need of * the solver. * * One may cache current values and restore them by calls to accordingly * named methods. * * Moreover, by invoking method getOneToOneProbsForCounts(), one can * retrieve analogous probabilities for when certain numbers of transfer * events have occurred along the way. This is achieved by a full update * and is computationally expensive, why extensive use is discouraged. * Such values are not part of the caching functionality. * * Classes dependent on the rates and the related probabilities should * implement PertubationObserver and register themselves as listeners to * this class. * * @author Joel Sjöstrand */ class EpochBDTProbs : public ODESolver, public PerturbationObservable { typedef std::vector realvec; public: /** * Relative tolerance for each component during ODE solving. */ static const Real REL_TOL = 1e-6; /** * Absolute tolerance for each component during ODE solving. */ static const Real ABS_TOL = 1e-6; /** * Constructor. * @param EDS the "epochized" discretized host tree. * @param birthRate the birth (duplication) rate. * @param deathRate the death (loss) rate. * @param transferRate the lateral transfer rate. * @param noOfTransferCounts specifies the size of the vector * returned by a call to getOneToOneProbsForCounts(). */ EpochBDTProbs( const EpochTree& EDS, Real birthRate, Real deathRate, Real transferRate, unsigned noOfTransferCounts ); /** * Destructor. */ virtual ~EpochBDTProbs(); /** * Updates the internally stored probabilities. * Must be invoked manually if the host tree has changed, * either in terms of topology or times. */ void update(); /** * Returns the birth rate. * @return the birth rate. */ Real getBirthRate() const; /** * Returns the death rate. * @return the death rate. */ Real getDeathRate() const; /** * Returns the lateral transfer rate. * @return the lateral transfer rate. */ Real getTransferRate() const; /** * Returns the sum of all three rates. * @return the sum of all rates. */ Real getRateSum() const; /** * Gets current rates. * @param birthRate the birth rate. * @param deathRate the death rate. * @param transferRate the lateral transfer rate. */ void getRates(Real& birthRate, Real& deathRate, Real& transferRate) const; /** * Sets new birth, death and lateral transfer rates. * Related probability data structures are updated * accordingly. If the underlying host tree/discretization * has changed, one must call update(). * @param newBirthRate the new birth rate. * @param newDeathRate the new death rate. * @param newTransferRate the new lateral transfer rate. */ void setRates(Real newBirthRate, Real newDeathRate, Real newTransferRate); /** * Returns the max allowed rate. Apparently there is (has been?) * a need for this since otherwise "our program will crash when * (birth_rate - death_rate) * t is too big". * @return the max allowed rate. */ Real getMaxAllowedRate() const; /** * Returns the underlying (non-discretized) tree. * @return the tree. */ const Tree& getTree() const; /** * Returns the tree name. * @return the name. */ std::string getTreeName() const; /** * Returns the discretized root-to-leaf time. * @return the time from root to leaves. */ Real getRootToLeafTime() const; /** * Returns the discretized time of the edge above * the root in the tree. * @return the top time. */ Real getTopTime() const; /** * Returns the discretized root-to-leaf time * plus the discretized top time. * @return the top time time. */ Real getTopToLeafTime() const; /** * Returns the number of transfer-counted probability sets * the class will return upon a call to getOneToOneProbsForCounts(). * @return the number of counts, i.e. 4 if probabilities * for 0,1,2,3 transfers can be retrieved. */ inline unsigned getNoOfTransferCounts() const { return m_Qefk.size(); } /** * Returns a reference to the precomputed one-to-one * ("function p11") probabilities for all pairs of * discretization points of the tree. p11(s,t) can be * interpreted as the probability of a single lineage * starting at discretization point s having one sole * mortal descendant at point t below, while the remaining * descendants are ghosts destined to go extinct. * A point is referenced using a 3-tuple; * (epochIndex,timeInEpochIndex,edgeInEpochIndex). * The returned matrix is essentially triangular (i.e. * a value is present if row point is concurrent to or * above column point). * @return the p11 probabilities for all pairs of points. */ inline const RealEpochPtPtMap& getOneToOneProbs() const { return m_Qef; } /** * Returns a reference to the precomputed extinction * probabilities for all discretization points of * the tree. For a point p, it states the probability of * a single lineage starting at p having no descendants * among the leaves. * A point is referenced using a 3-tuple; * (epochIndex,timeInEpochIndex,edgeInEpochIndex). * @return the extinction probabilites for all points. */ inline const RealEpochPtMap& getExtinctionProbs() const { return m_Qe; } /** * Returns one-to-one probabilities similar to getOneToOneProbs(), * but where values refer to instances where exactly k transfers * have occurred along the way. Causes a complete and more extensive * update than normal, implying that it is computationally expensive. * Values are not cached, and are invalidated at the next call to * setRates(...). * @return one-to-one probabilities for when exactly k transfers * have occurred along the way, for k=0,...,count-1, where * count was specified in the constructor. */ const std::vector* getOneToOneProbsForCounts(); /** * Returns an info string for debugging. * @param inclExtinc true to include precomputed extinction probs. * @param inclOneToOne true to include precomputed one-to-one probs. * @param inclCounts true to include precomputed one-to-one probs with a * certain number of transfers occurring along the way. * @return an info string. */ std::string getDebugInfo(bool inclExtinc, bool inclOneToOne, bool inclCounts) const; /** * Caches current rates and precomputed values. */ void cache(); /** * Restores cached values. */ void restoreCache(); protected: /** * Performs computation of derivative of extinction and one-to-one * probabities during ODE solving. * @param t current solver time value. * @param Q current solver extinction and one-to-one probabilites. * @param dQdt the derivatives to be computed. */ virtual void fcn(Real t, const realvec& Q, realvec& dQdt); /** * Solver callback. Stores point probabilities for current epoch * during solving. * @param no solver iteration number (irrelevant). * @param told previous solver t. * @param t current solver t. * @param Q current solver values at t. * @return code always indicating that solution has not been altered. */ virtual ExtSolResult solout(unsigned no, Real told, Real t, realvec& Q); private: /** * Helper. For all epochs, computes and stores * point-to-point probabilities for points within * the current epoch. Calculations require solving a * an ODE system, and are carried out numerically * using a Runge-Kutta solver. */ void calcProbsWithinEpochs(); /** * Helper. For all epochs, computes and stores * point-to-point probabilities for points of different * epochs. Is based on within-epoch values, meaning * that calcProbsWithinEpochs() must be invoked first. */ void calcProbsBetweenEpochs(); /** * Helper. Computes probabilities for all points * between epoch i and epoch j, i>j. Probs. for * any epoch k where i>k>j must be up-to-date, as well * as in-epoch probs. for i and j. * @param i index of upper epoch. * @param j index of lower epoch. */ void calcProbsBetweenEpochs(unsigned i, unsigned j); /** * Helper. Performs computation of derivatives for transfer counts. * Invoked by fcn() when required. * @param Q current solver extinction and one-to-one probabilites. * @param dQdt the derivatives to be computed. * @param sumqe the sum of the extinction probabilities. */ void fcnForCounts(const realvec& Q, realvec& dQdt, Real sumqe); /** * Helper. Computes P(t) and u_t "Kendall-way". * @param t size of time interval. * @param Pt P(t) value to be computed. * @param ut u_t value to be computed. */ void calcPtAndUt(Real t, Real& Pt, Real& ut) const; /** * Helper. Appends initial values to the specified * vector. Used during ODE solving. * @param Q appends initial values to Q (Q should already * contain extinction values). */ void appendInitVals(realvec& Q) const; public: private: /** The discretized tree. */ const EpochTree& m_ES; /** Birth rate. */ Real m_birthRate; Real m_birthRateOld; /** Death rate. */ Real m_deathRate; Real m_deathRateOld; /** Transfer rate. */ Real m_transferRate; Real m_transferRateOld; /** Sum of rates. */ Real m_rateSum; Real m_rateSumOld; /** * "Extinction probabilities": prob. of a sole lineage starting at a point * having no descendants at leaves. Stored for every point in the tree. */ RealEpochPtMap m_Qe; /** * "One-to-one probabilities": prob. of a single lineage starting at * time s in edge e having a sole mortal descendant at time t in edge f. * Stored for every pair of points in the tree. Saved in a lower triangular * matrix for every pair of times, where element (s,t) in turn holds an * inner matrix of values for the edges at those times. */ RealEpochPtPtMap m_Qef; /** * Flag indicating that this many transfer count computations should be * made (k=0,...,count-1) during an update. Equal to size of Qefk during * calls to getOneToOneProbsForCounts(), otherwise 0. */ unsigned m_counts; /** * Similar to m_Qef, but where values refer to when exactly k transfers * have occurred. Not cached, and values are only valid after a call * to getOneToOneProbsForCounts() until next setRates()/update(). */ std::vector m_Qefk; unsigned wi; /**< ODE work var.: epoch index. */ unsigned wt; /**< ODE work var.: lower current time index in epoch. */ unsigned ws; /**< ODE work var.: upper current time index in epoch. */ unsigned wlast; /**< ODE work var.: last time index in epoch. */ unsigned wn; /**< ODE work var.: number of edges in epoch. */ Real wnorm; /**< ODE work var.: transferRate/(wn-1). */ }; } // End namespace beep. #endif /* EPOCHBDTPROBS_HH */