#include "BeepOption.hh" #include "EdgeRateMCMC_common.hh" #include "Density2PMCMC.hh" //#include "DiscreteGammaDensity.hh" #include "DummyMCMC.hh" #include "EdgeDiscTree.hh" #include "EdgeDiscBDMCMC.hh" #include "EdgeDiscBDProbs.hh" #include "EdgeDiscGSR.hh" #include "EdgeWeightHandler.hh" #include "EdgeWeightMCMC.hh" #include "GammaDensity.hh" #include "InvGaussDensity.hh" #include "LogNormDensity.hh" #include "MatrixTransitionHandler.hh" #include "PRNG.hh" #include "Probability.hh" #include "RandomTreeGenerator.hh" #include "SeqIO.hh" #include "SequenceData.hh" #include "SimpleML.hh" #include "SiteRateHandler.hh" #include "StrStrMap.hh" #include "SubstitutionMCMC.hh" #include "TreeDiscretizers.hh" #include "TreeIO.hh" #include "TreeMCMC.hh" #include "UniformDensity.hh" #include "conf_value_from_cmake_primeDLRS.hh" // Suggestion rates. Affects perturbation frequency of the various parameters. static const double SUGG_RATIO_BD_RATES = 1.0; static const double SUGG_RATIO_G_TOPO_START = 3.0; // Initial value. static const double SUGG_RATIO_G_TOPO_FINAL = 3.0; // Final value. static const unsigned SUGG_RATIO_G_TOPO_STEPS = 1; // Steps between start and final. static const double SUGG_RATIO_G_LENGTHS = 1.0; static const int NO_OF_PARAMS = 2; static const int NO_OF_OPTIONAL_PARAMS = 1; // Program arguments. Listed in expected input order. std::string ParamSeqDataFile = ""; std::string ParamSTreeFile = ""; std::string ParamGSMapFile = ""; // Optional. // Things to print before iterating (irrespective of 'quiet' setting). std::ostringstream preamble; // All options to program (and default values) in a map. beep::option::BeepOptionMap Options; // Forward declaration of helpers. void showHelpMsg(); void readParameters(int& argIndex, int argc, char **argv); void createUnderlyingObjects(beep::MatrixTransitionHandler*& Q, beep::SequenceData*& D, beep::Tree*& S, beep::EdgeDiscretizer*& discretizer, beep::EdgeDiscTree*& DS, beep::Tree*& G, beep::StrStrMap*& gsMap); beep::Density2P* createDensity2P(std::string id, double mean, double variance); void createDefaultOptions(); void iterate(beep::StdMCMCModel& mcmcEnd, std::string runType, beep::EdgeDiscGSR& gsrModel); int main(int argc, char **argv) { using namespace beep; using namespace beep::option; using namespace std; try { // Create default options. Read options and arguments. createDefaultOptions(); int argIndex = 1; if (!Options.parseOptions(argIndex, argc, argv)) { showHelpMsg(); exit(0); } readParameters(argIndex, argc, argv); // Pseudo random number generator. PRNG rand; int seed = Options.getUnsigned("Seed"); if (seed != 0) { rand.setSeed(seed); } else { seed = rand.getSeed(); } // Create substitution matrix, sequence data, trees, etc. MatrixTransitionHandler* Q; SequenceData* D; Tree* S; EdgeDiscretizer* discretizer; EdgeDiscTree* DS; Tree* G; StrStrMap* gsMap; createUnderlyingObjects(Q, D, S, discretizer, DS, G, gsMap); // MCMC: End-of-chain. DummyMCMC mcmcDummy = DummyMCMC(); // MCMC: Birth-death rates (duplication-loss rates). pair bdr = Options.getDoubleX2("BDRates"); EdgeDiscBDProbs* bdp = new EdgeDiscBDProbs(DS, bdr.first, bdr.second); EdgeDiscBDMCMC mcmcBDRates(mcmcDummy, bdp, SUGG_RATIO_BD_RATES); if (Options.getBool("BDRatesFixed")) { mcmcBDRates.fixRates(); }; // MCMC: Guest tree topology. UniformTreeMCMC mcmcGTopo(mcmcBDRates, *G, SUGG_RATIO_G_TOPO_START); mcmcGTopo.setChangingSuggestRatio(SUGG_RATIO_G_TOPO_FINAL, SUGG_RATIO_G_TOPO_STEPS); if (Options.getBool("GTreeFixed")) { mcmcGTopo.fixTree(); mcmcGTopo.fixRoot(); } // joelgs: There is no use turning on detailed notifications for // tree topologies, since partial updates is a bit tricky with this // discretization technique. However, we do it for edge weights. //mcmcGTopo.setDetailedNotification(true); // MCMC: Substitution rate variation over edges (IID). string erdfname = Options.getStringAlt("EdgeRateDistr"); pair erdfp; if (Options.hasBeenParsed("EdgeRateParams")) { erdfp = Options.getDoubleX2("EdgeRateParams"); } else { // Use coarse estimate of time length to set reasonable start rate. Real tmSum = 0; for (Tree::const_iterator it = S->begin(); it != S->end(); ++it) { tmSum += S->getEdgeTime(**it); } Real tmAvg = ((tmSum - S->getTopTime()) / (S->getNumberOfNodes() - 1)); erdfp.first = 0.25 / tmAvg; erdfp.second = (erdfp.first / 2) * (erdfp.first / 2); } Density2P* erdf = createDensity2P(erdfname, erdfp.first, erdfp.second); Density2PMCMC mcmcEdgeRate(mcmcGTopo, *erdf, true); if (Options.hasBeenParsed("EdgeRateFixed") || erdfname == "UNIFORM") { mcmcEdgeRate.fixMean(); mcmcEdgeRate.fixVariance(); } // Set up GSR integrator. EdgeDiscGSR gsrModel(G, DS, gsMap, erdf, bdp); // MCMC: Edge lengths. The GSR class holds these, and may therefore be model. EdgeWeightMCMC mcmcGLengths(mcmcEdgeRate, gsrModel, SUGG_RATIO_G_LENGTHS, true); mcmcGLengths.generateWeights(true, 0.05); mcmcGLengths.setDetailedNotification(true); // Set up edge weights, equating weights with lengths. EdgeWeightHandler ewh(gsrModel); // MCMC: Disc. gamma substitution rate variation over sites. UniformDensity srdf(0, 3, true); // Uniform prior over [0,3]. ConstRateMCMC mcmcSiteRate(mcmcGLengths, srdf, *G, "Alpha"); // Set up site rate handler. unsigned srdfn = Options.getUnsigned("SiteRateCats"); SiteRateHandler srh(srdfn, mcmcSiteRate); if (srdfn == 1) { mcmcSiteRate.fixRates(); } // MCMC: Substitution. vector partList; partList.push_back(string("all")); SubstitutionMCMC mcmcSubst(mcmcSiteRate, *D, *G, srh, *Q, ewh, partList); string runType = Options.getStringAlt("RunType"); // Get pre-run info. if (!Options.getBool("DoNotPrintRunInfo")) { preamble << "# Running: " << endl << "#"; for (int i = 0; i < argc; i++) { preamble << " " << argv[i]; } preamble << endl << "# of type " << runType << " with seed " << seed << " in directory " << getenv("PWD") << endl; } if (Options.getBool("DebugInfo")) { preamble << "# DISCTRETIZED HOST TREE TIMES:" << endl << (*DS); preamble << "# INITIAL RECONCILIATION AND PROBS:" << endl << gsrModel.getDebugInfo(false, false); } // Iterate according to choice of execution type. iterate(mcmcSubst, runType, gsrModel); // Clean up in (somewhat) reverse order of creation. delete erdf; delete bdp; delete gsMap; delete G; delete DS; delete S; delete D; delete Q; } catch (AnError& e) { e.action(); cerr << "Use '" << argv[0] << " -h' to display help."; } catch (exception& e) { cerr << e.what() << endl; cerr << "Use '" << argv[0] << " -h' to display help."; } cerr << endl; } /************************************************************************ * Starts MCMC or hill-climbing. ************************************************************************/ void iterate(beep::StdMCMCModel& mcmcEnd, std::string runType, beep::EdgeDiscGSR& gsrModel) { using namespace beep; using namespace beep::option; using namespace std; bool quiet = Options.getBool("Quiet"); // Iterate according to choice of execution type. if (runType == "PD") { // First-iteration posterior density. cout << mcmcEnd.currentStateProb() << endl; return; } // MCMC: Iterator. unsigned thinning = Options.getUnsigned("Thinning"); SimpleMCMC* iter; if (runType == "PDHC") { // Posterior density hill-climbing. iter = new SimpleML(mcmcEnd, thinning); } else { // MCMC. iter = new SimpleMCMC(mcmcEnd, thinning); // TODO: Must this be applied instead when doing LSD analysis? // iter = new SimpleMCMCPostSample(*mcmcEnd, thinning); } // Output, diagnostics, etc. string out = Options.getString("Outfile"); if (out != "") { try { iter->setOutputFile(out.c_str()); } catch (AnError& e) { e.action(); } catch (...) { cerr << "Problems opening output file '" << out << "'! " << "Reverting to stdout." << endl; } } if (quiet) { iter->setShowDiagnostics(false); } cout << preamble.str(); // Iterate!!!! time_t t0 = time(0); clock_t ct0 = clock(); iter->iterate(Options.getUnsigned("Iterations"), Options.getUnsigned("PrintFactor")); time_t t1 = time(0); clock_t ct1 = clock(); if (!Options.getBool("DoNotPrintElapsedComputeTime")) { cout << "# Wall time: " << difftime(t1, t0) << " s." << endl; cout << "# CPU time: " << (Real(ct1 - ct0) / CLOCKS_PER_SEC) << " s." << endl; } cout << "# Total acceptance ratio: " << mcmcEnd.getAcceptanceRatio() << endl << mcmcEnd.getAcceptanceInfo(); cout << "# Last iteration root probs: " << gsrModel.getRootProbDebugInfo() << endl; delete iter; } /************************************************************************ * Helper. Creates sequence data, trees, etc. * Deletion must be taken care of by invoking method. ************************************************************************/ void createUnderlyingObjects( beep::MatrixTransitionHandler*& Q, beep::SequenceData*& D, beep::Tree*& S, beep::EdgeDiscretizer*& discretizer, beep::EdgeDiscTree*& DS, beep::Tree*& G, beep::StrStrMap*& gsMap) { using namespace std; using namespace beep; using namespace beep::option; // For practical reasons, set up the substitution matrix first. // Use user-defined matrix if such has been provided. if (Options.hasBeenParsed("UserSubstModel")) { if (Options.hasBeenParsed("SubstModel")) throw AnError("Cannot use both predefined and user-defined subst. model.", 1); UserSubstModelOption* smUsr = Options.getUserSubstModelOption("UserSubstModel"); Q = new MatrixTransitionHandler(MatrixTransitionHandler::userDefined(smUsr->type, smUsr->pi, smUsr->r)); } else { string sm = Options.getStringAlt("SubstModel"); Q = new MatrixTransitionHandler(MatrixTransitionHandler::create(sm)); } // Get sequence data. This is why Q must already exist.* D = new SequenceData(SeqIO::readSequences(ParamSeqDataFile, Q->getType())); // since Q is needed for D, and for counting base frequencies in Q, we need // D (chicken and egg problem) so, as a temporary hack, I am redefining Q // for F81 model if (Options.getStringAlt("SubstModel") == "F81") { std::map bf = D->getBaseFrequencies(); Q = new MatrixTransitionHandler(MatrixTransitionHandler::create("F81", &bf)); } // set the base frequencies in Q //std::map bf = D->getBaseFrequencies(); ///for (map::iterator ii = bf.begin(); ii != bf.end(); ++ii) { // cout << (*ii).first << ": " << (*ii).second << endl; //} // Create S from file. S = new Tree(TreeIO::fromFile(ParamSTreeFile).readHostTree()); if (Options.getBool("Rescale")) { Real sc = S->rootToLeafTime(); RealVector* tms = new RealVector(S->getTimes()); for (RealVector::iterator it = tms->begin(); it != tms->end(); ++it) { (*it) /= sc; } S->setTopTime(S->getTopTime() / sc); S->setTimes(*tms, true); preamble << "# Host tree root-to-leaf span was rescaled from " << sc << " to 1.0.\n"; } //cout << S->print(false,false,true,false) << endl; //cout << *S << endl; if (Options.hasBeenParsed("TopTime")) { Real tt = Options.getDouble("TopTime"); if (tt <= 0) { tt = S->rootToLeafTime(); preamble << "# Changing root edge time span to " << tt << ".\n"; } S->setTopTime(tt); } if (S->getTopTime() < 1e-8) throw AnError("Host tree top time must be greater than 0.", 1); // Create discretized tree DS based on S. Real timestep = Options.getDouble("DiscTimestep"); unsigned minIvs = Options.getUnsigned("DiscMinIvs"); unsigned ttIvs = Options.getUnsigned("TopTimeDiscIvs"); if (timestep == 0) { if (ttIvs == 0) { ttIvs = minIvs; } discretizer = new EquiSplitEdgeDiscretizer(minIvs, ttIvs); } else { if (ttIvs == 0) { ttIvs = std::ceil(S->rootToLeafTime() / timestep); } discretizer = new StepSizeEdgeDiscretizer(timestep, minIvs, ttIvs); } DS = new EdgeDiscTree(*S, discretizer); // Create random guest tree G unless file specified. // Fill G-S map. If empty (no mapping info was found in the gene tree or a // random tree was created), we have to use file passed as parameter with that info. gsMap = new StrStrMap(); TreeIO tio = TreeIO::fromFile(Options.getString("GTreeFile")); G = (Options.hasBeenParsed("GTreeFile")) ? new Tree(tio.readBeepTree(NULL, gsMap)) : new Tree(RandomTreeGenerator::generateRandomTree(D->getAllSequenceNames())); if (gsMap->size() == 0) { if (ParamGSMapFile == "") throw AnError("Missing guest-to-host leaf map.", 1); else { delete gsMap; gsMap = new StrStrMap(TreeIO::readGeneSpeciesInfo(ParamGSMapFile)); } } G->doDeleteTimes(); G->doDeleteRates(); } /************************************************************************ * Helper. Prints usage message to stderr. ************************************************************************/ void showHelpMsg() { using std::cerr; using std::endl; cerr << "===================================================================================" << endl << "Usage: primeDLRS [] []" << endl << endl << "Description: Guest-in-host tree reconciliation tool, enabling analysis of" << endl << "e.g. guest tree topologies, reconciliation properties and duplication-loss rates." << endl << "Based on a Bayesian MCMC framework using the underlying GSR model:" << endl << "1) the guest tree topology and its divergence times are modelled with a" << endl << " duplication-loss process in accordance with the Gene Evolution Model (GEM)." << endl << "2) sequence evolution is modelled with a user-defined substitution model." << endl << "3) sequence evolution rate variation over guest tree edges (relaxed molecular" << endl << " clock) are modelled with iid values from a user-selected distribution." << endl << "4) sequence evolution rate variation over sites (positions) are modelled according" << endl << " to a discretized Gamma distribution." << endl << "The implementation uses a discretization of the host tree to perform its computations." << endl << "Please review available options, as you will need to change default settings." << endl << "Option -r may be useful to avoid numeric issues due to scaling." << endl << endl << "Parameters:" << endl << " (string), file with aligned sequences for guest tree leaves." << endl << " (string), PrIME Newick file with host tree incl. divergence times." << endl << " Leaves must have time 0 and root have time > 0." << endl << " (string), tab-delimited file relating guest tree leaves to host" << endl << " tree leaves if info not included in ." << endl << endl << "Options:" << endl << " -h/-u/-?" << endl << " Display help (this text)." << endl << Options << "===================================================================================" << endl; } /************************************************************************ * Helper. Reads program arguments (not options). ************************************************************************/ void readParameters(int& argIdx, int argc, char **argv) { if (argc - argIdx < NO_OF_PARAMS) { throw beep::AnError("Too few input parameters!", 1); } ParamSeqDataFile = argv[argIdx++]; ParamSTreeFile = argv[argIdx++]; if (argIdx < argc) { ParamGSMapFile = argv[argIdx++]; } }; /************************************************************************ * Helper. Creates a 2-parameter density function from its string ID. ************************************************************************/ beep::Density2P* createDensity2P(std::string id, double mean, double var) { using namespace beep; Density2P* df = NULL; if (id == "INVG") { df = new InvGaussDensity(mean, var); }// else if (id == "DISCGAMMA") { df = new DiscreteGammaDensity(mean, var, 200); } else if (id == "LOGN") { df = new LogNormDensity(mean, var); } else if (id == "GAMMA") { df = new GammaDensity(mean, var); } else if (id == "UNIFORM") { df = new UniformDensity(mean, var, true); } else { throw AnError("Unknown Density2P identifier: " + id + '.', 1); } return df; }; /************************************************************************ * Helper. Creates default values corresponding to options and stores * them in global map. ************************************************************************/ void createDefaultOptions() { using namespace std; using namespace beep::option; Options.addStringOption("Outfile", "o", "", " -o \n" " Output filename. Defaults to stderr.\n"); Options.addUnsignedOption("Seed", "s", 0, " -s \n" " Seed for pseudo-random number generator. Defaults to random seed.\n"); // The conf_value_from_cmake_* values are set in CMakeLists.txt Options.addUnsignedOption("Iterations", "i", conf_value_from_cmake_Iterations, " -i \n" " Number of iterations. Defaults to " conf_value_from_cmake_Iterations_string ".\n"); Options.addUnsignedOption("Thinning", "t", conf_value_from_cmake_Thinning, " -t \n" " Thinning, i.e. sample every -th iteration. Defaults to " conf_value_from_cmake_Thinning_string ".\n"); Options.addUnsignedOption("PrintFactor", "w", conf_value_from_cmake_PrintFactor, " -w \n" " Output diagnostics to stderr every -th sample. Defaults to " conf_value_from_cmake_PrintFactor_string ".\n"); Options.addBoolOption("Quiet", "q", false, " -q \n" " Do not output diagnostics. Non-quiet by default.\n"); Options.addStringAltOption("RunType", "m", conf_value_from_cmake_RunType_string, "MCMC,PDHC,PD", " -m <'MCMC'/'PDHC'/'PD'>\n" " Execution type (MCMC, posterior density hill-climbing from initial\n" " values, or just initial posterior density). Defaults to " conf_value_from_cmake_RunType_string ".\n", UPPER); Options.addStringAltOption("SubstModel", "Sm", conf_value_from_cmake_SubstModel_string, "UniformAA,JC69,F81,JTT,UniformCodon,ArveCodon", " -Sm <'UniformAA'/'JC69'/'JTT'/'F81'/'UniformCodon'/'ArveCodon'>\n" " Substitution model. " conf_value_from_cmake_SubstModel_string " by default.\n", UPPER); Options.addUserSubstModelOption("UserSubstModel", "Su", " -Su <'DNA'/'AminoAcid'/'Codon'> \n" " User-defined substitution model. The size of Pi and R must fit data type \n" " (DNA: n=4, AminoAcid: n=20, Codon: n=62). R is given as a flattened\n" " upper triangular matrix. Don't use both option -Su and -Sm.\n"); Options.addUnsignedOption("SiteRateCats", "Sn", conf_value_from_cmake_SiteRateCats, " -Sn \n" " Number of steps of discretized Gamma-distribution for sequence\n" " evolution rate variation over sites. Defaults to " conf_value_from_cmake_SiteRateCats_string " (no variation).\n"); Options.addStringAltOption("EdgeRateDistr", "Ed", conf_value_from_cmake_EdgeRateDistr_string, "Gamma,InvG,LogN,Uniform", " -Ed <'Gamma'/'InvG'/'LogN'/'Uniform'>\n" " Distribution for iid sequence evolution rate variation over guest\n" " tree edges. Defaults to " conf_value_from_cmake_EdgeRateDistr_string " (not to confuse with -Sn).\n", UPPER); Options.addDoubleX2Option("EdgeRateParams", "Ep", pair(1.0, 1.0), " -Ep \n" " Initial mean and variance of sequence evolution rate.\n" " Defaults to simple rule-of-thumb based on host tree times.\n"); Options.addBoolOption("EdgeRateFixed", "Ef", false, " -Ef \n" " Fix mean and variance of sequence evolution rate. Non-fixed by default.\n"); Options.addStringOption("GTreeFile", "Gi", "", " -Gi \n" " Filename with initial guest tree topology.\n"); Options.addBoolOption("GTreeFixed", "Gg", false, " -Gg \n" " Fix initial guest tree topology, i.e. perform no branch-swapping.\n" " Non-fixed by default.\n"); Options.addDoubleX2Option("BDRates", "Bp", pair(conf_value_from_cmake_BDRates_first, conf_value_from_cmake_BDRates_second), " -Bp \n" " Initial duplication and loss rates. Defaults to " conf_value_from_cmake_BDRates_first_string " and " conf_value_from_cmake_BDRates_second_string ".\n"); Options.addBoolOption("BDRatesFixed", "Bf", false, " -Bf \n" " Fix initial duplication and loss rates. Non-fixed by default.\n"); Options.addDoubleOption("TopTime", "Bt", 0.0, " -Bt \n" " Override time span of edge above root in host tree. If the value is <=0, the span\n" " will be set to equal the root-to-leaf time. Defaults to value in host tree file.\n" " See also option -Dtt.\n"); Options.addDoubleOption("DiscTimestep", "Dt", conf_value_from_cmake_DiscTimestep, " -Dt \n" " Approximate discretization timestep. Set to 0 to divide every edge in equally\n" " many parts (see -Di). Defaults to " conf_value_from_cmake_DiscTimestep_string ". See -Dtt for edge above root.\n"); Options.addUnsignedOption("DiscMinIvs", "Di", conf_value_from_cmake_DiscMinIvs, " -Di \n" " Minimum number of parts to slice each edge in. If -Dt is set to 0, this becomes\n" " the exact number of parts. Minimum 2. Defaults to " conf_value_from_cmake_DiscMinIvs_string ". See -Dtt for edge above root.\n"); Options.addUnsignedOption("TopTimeDiscIvs", "Dtt", 0, " -Dtt \n" " Override number of discretization points for edge above root in host tree.\n" " By default, irrespective of time span, this is set to the number\n" " of points for a (hypothetical) root-to-leaf edge.\n"); Options.addBoolOption("Rescale", "r", false, " -r \n" " Rescale the host tree so that the root-to-leaf time equals 1.0. All\n" " inferred parameters will refer to the new scale. Off by default.\n" " Note that discretization parameters are NOT rescaled.\n"); Options.addBoolOption("DoNotPrintElapsedComputeTime", "Z", false, " -Z \n" " Do not print elapsed wall time and CPU time\n"); Options.addBoolOption("DoNotPrintRunInfo", "W", false, " -W \n" " Do not print the command line\n"); Options.addBoolOption("DebugInfo", "debuginfo", false, " -debuginfo \n" " Show misc. info to stderr before iterating. Not shown by default.\n"); };