/* Generates a gene tree and set of sequences according to the specified * GSR model. The edge rates in the gene tree are drawn independently from * a gamma distribution. The rate in a sequence is constant over the sites. * * * File: genGSR.cc * Author: fmattias * * Created on November 16, 2009, 11:53 AM */ #include #include #include "cmdline.h" #include "BDTreeGenerator.hh" #include "ConstRateModel.hh" #include "DummyMCMC.hh" #include "EdgeWeightMCMC.hh" #include "EdgeRateMCMC_common.hh" #include "GammaDensity.hh" #include "InvGaussDensity.hh" #include "LogNormDensity.hh" #include "MatrixTransitionHandler.hh" #include "TreeIO.hh" #include "SequenceGenerator.hh" #include "UniformDensity.hh" #include "lsd/LSDGeneTreeGenerator.hh" #include "lsd/LSDTimeProbs.hh" #include "EdgeDiscTree.hh" #include using namespace beep; using namespace std; /* Maximum number of generated gene trees with less than two leaves. */ const int MAX_GENE_TREE_TRIES = 500; /* Names used when an output directory is specified */ const char *DEFAULT_G_FILENAME = "g"; const char *DEFAULT_GS_FILENAME = "gs"; const char *DEFAULT_SEQS_FILENAME = "seqs"; /* Handles paths */ typedef struct PathHolder { // Flags deciding whether files have been specified bool geneTreeFileGiven; bool geneSpeciesFileGiven; bool sequenceFileGiven; // File names string geneTreeFile; string geneSpeciesFile; string sequenceFile; public: PathHolder() : geneTreeFileGiven(false), geneSpeciesFileGiven(false), sequenceFileGiven(false) { } } PathHolder; /** * Constructs a density function according to the type, which is one of * INVG, LOGN, GAMMA, UNIFORM, along with mean and variance. If the type * is not known, 0 (null) will be returned. * * type - The alias of the density function (see above). * mean - The mean of the density function that will be created. * variance - The variance of the density function that will be created. */ Density2P *createDensity(string type, float mean, float variance); void setupPaths(PathHolder *paths, struct gengetopt_args_info *args_info); string createPath(const char *directory, const char *filename); void readLSDProbabilities(const char *path, Tree &speciesTree, LSDTimeProbs &lsdTimes); /** * Opens the location path, writes the parameter outputString to the opened * file and closes the file. * * path - Path to the output file. * outputString - The string that will be written to the file specified in path. */ void writeStringToFile(const string &path, const string &outputString); /** * Generates a gene tree inside the given species tree according to the * specified birth-death process. * * speciesTree - The species tree where the gene tree will evolve. * birthRate - Birth rate in the birth-death process. * deathRate - Death rate in the birth-death process. * topTime - The length of the top edge in the gene tree, if topTime <= 0 then * no top edge will be modelled. * geneTree - The generated gene tree will be stored here. * */ void generateGeneTree(Tree &speciesTree, float birthRate, float deathRate, float topTime, Tree &geneTree); /** * Returns a set of generated sequences in the given gene tree according to the * specified substitution parameters. * * in_geneTree - Gene tree where the sequences will be generated. * in_densityFunction - The density function that is used when sampling rates. * in_sequenceLength - The length of the generated sequences. * in_substitutionModel - The substitution model that specifies how sequences * is evoloving. * in_alpha - Shape parameter for the gamma distribution used to set * substitution rates for sites. * in_numberOfCategories - The number of categories (intervals) used when * discretizing the gamme distribution. See Yang (1994). * in_saveAncestral - Determines if ancestral sequences for should be * returned along with the leaf sequences. */ SequenceData generateSequences(Tree &in_geneTree, Density2P &in_densityFunction, int in_sequenceLength, string in_substitutionModel, float in_alpha, float in_numberOfCategories, bool in_saveAncestral); int main(int argc, char** argv) { /* Initialize command options parser */ struct gengetopt_args_info args_info; if(cmdline_parser(argc, argv, &args_info) != 0){ exit(EXIT_FAILURE); } if(args_info.inputs_num < 1){ cerr << "genGSR: Error: No species tree specified." << endl; exit(EXIT_FAILURE); } else if(args_info.inputs_num > 2){ cerr << "genGSR: Error: Too many arguments." << endl; exit(EXIT_FAILURE); } /* Read species tree */ TreeIO treeReader = TreeIO::fromFile(args_info.inputs[0]); Tree speciesTree = treeReader.readHostTree(); /* Read LSD probabilities */ LSDTimeProbs lsdTimes; if(args_info.inputs_num == 2){ readLSDProbabilities(args_info.inputs[1], speciesTree, lsdTimes); } /* Setup outputPaths */ PathHolder outputPaths; setupPaths(&outputPaths, &args_info); /* Generate gene tree */ Tree geneTree; LSDGeneTreeGenerator geneTreeGenerator(speciesTree, args_info.birth_rate_arg, args_info.death_rate_arg, lsdTimes); geneTreeGenerator.setMaxNumberOfTries(args_info.max_number_of_tries_arg); geneTreeGenerator.setMaxNumberOfLeaves(args_info.max_number_of_leaves_arg); geneTreeGenerator.setMinNumberOfLeaves(args_info.min_number_of_leaves_arg); if(args_info.seed_given) { geneTreeGenerator.setSeed(args_info.seed_arg); } geneTreeGenerator.generateTree(geneTree, args_info.top_time_arg); StrStrMap geneSpeciesMap(geneTreeGenerator.exportGeneSpeciesMap()); /* Setup density function to use when sampling edge rates */ boost::scoped_ptr densityFunction(createDensity(args_info.density_function_arg, args_info.mean_arg, args_info.variance_arg)); /* Generate sequences */ SequenceData sequences = generateSequences(geneTree, *densityFunction, args_info.sequence_length_arg, args_info.substitution_model_arg, args_info.alpha_arg, args_info.number_of_categories_arg, args_info.generate_ancestral_flag == 1); /* Write the sequences to stdout or file according to user preferences */ if(!outputPaths.sequenceFileGiven){ cout << sequences.data4fasta() << endl; } else{ string sequenceOutString = sequences.data4fasta(); writeStringToFile(outputPaths.sequenceFile, sequenceOutString); } /* Write the gene species map if the user wanted it */ if(outputPaths.geneSpeciesFileGiven){ stringstream gsOutString; gsOutString << geneSpeciesMap; writeStringToFile(outputPaths.geneSpeciesFile, gsOutString.str()); } /* Save gene tree if the user wanted it to be saved */ if(outputPaths.geneTreeFileGiven){ /* Setup file format, showing gene tree IDs and branch lengths */ TreeIOTraits traits; traits.setID(true); traits.setBL(true); traits.setNW(true); string geneTreeOutString = TreeIO::writeBeepTree(geneTree, traits, 0); writeStringToFile(outputPaths.geneTreeFile, geneTreeOutString); } return (EXIT_SUCCESS); } Density2P * createDensity(string density, float mean, float variance) { Density2P *densityFunction; if(density == "INVG"){ densityFunction = new InvGaussDensity(mean, variance); } else if(density == "LOGN"){ densityFunction = new LogNormDensity(mean, variance); } else if(density == "GAMMA"){ densityFunction = new GammaDensity(mean, variance); } else if(density == "UNIFORM"){ densityFunction = new UniformDensity(mean, variance, true); } else{ return 0; } /* Check that density function does not include negative rates */ Real min, max; densityFunction->getRange(min, max); if(min <= 0){ cerr << "genGSR: Error: Parameters of density function allows " "negative rates." << endl; exit(EXIT_FAILURE); } return densityFunction; } void setupPaths(PathHolder *paths, struct gengetopt_args_info *args_info) { /* If the user specifed a directory for output, set up paths for all * output files. */ if(args_info->output_directory_given) { paths->geneTreeFileGiven = true; paths->geneTreeFile = createPath(args_info->output_directory_arg, DEFAULT_G_FILENAME); paths->geneSpeciesFileGiven = true; paths->geneSpeciesFile = createPath(args_info->output_directory_arg, DEFAULT_GS_FILENAME); paths->sequenceFileGiven = true; paths->sequenceFile = createPath(args_info->output_directory_arg, DEFAULT_SEQS_FILENAME); } else { /* Setup given files */ if(args_info->output_gene_tree_file_given) { paths->geneTreeFileGiven = true; paths->geneTreeFile = string(args_info->output_gene_tree_file_arg); } if(args_info->output_gene_tree_file_given) { paths->geneSpeciesFileGiven = true; paths->geneSpeciesFile = string(args_info->output_gs_map_file_arg); } if(args_info->output_gene_tree_file_given) { paths->sequenceFileGiven = true; paths->sequenceFile = string(args_info->output_sequence_file_arg); } } } string createPath(const char *directory, const char *filename) { ostringstream path; path << directory << "/" << filename; return path.str(); } void generateGeneTree(Tree &speciesTree, float birthRate, float deathRate, float topTime, Tree &geneTree) { /* Set up gene tree generator */ BDTreeGenerator geneTreeGenerator(speciesTree, birthRate, deathRate); /* Determine if the top edge should be modelled */ bool useTopTime = topTime > 0.0; if(useTopTime){ geneTreeGenerator.setTopTime(topTime); } /* Generate a gene tree with at least two nodes */ int tries = 0; while(geneTree.getNumberOfNodes() <= 1 && tries < MAX_GENE_TREE_TRIES){ geneTree.clear(); geneTreeGenerator.generateTree(geneTree, useTopTime); tries++; } if(tries >= MAX_GENE_TREE_TRIES){ cerr << "genGSR: Error: No gene tree with more than one leaf was created in " << MAX_GENE_TREE_TRIES << " tries. Please try to change the birth-death parameters." << endl; exit(EXIT_FAILURE); } } SequenceData generateSequences(Tree &in_geneTree, Density2P &densityFunction, int sequenceLength, string in_substitutionModel, float in_alpha, float in_numberOfCategories, bool in_saveAncestral) { /* Set up substitution model */ MatrixTransitionHandler substitutionModel = MatrixTransitionHandler::create(in_substitutionModel); /* Set up constant rate handler for each nucleotide site (position) */ ConstRateModel constantRates(densityFunction, in_geneTree); SiteRateHandler siteRateGenerator(in_numberOfCategories, constantRates); siteRateGenerator.setAlpha(in_alpha); /* Set up i.i.d. rate handler for edges in the gene tree */ DummyMCMC dummy; iidRateMCMC edgeRateGenerator(dummy, densityFunction, in_geneTree, "EdgeRates"); /* Set up handler that updates branch lengths */ EdgeTimeRateHandler edgeLengthHandler(edgeRateGenerator); /* Generate edge rates and update branch lengths */ edgeRateGenerator.generateRates(); in_geneTree.setRates(edgeRateGenerator.getWeightVector()); edgeLengthHandler.update(); /* Set up pseudo random generator */ PRNG randomGenerator; /* Set up sequence generator and generate sequences */ SequenceGenerator generator(in_geneTree, substitutionModel, siteRateGenerator, edgeLengthHandler, randomGenerator); return generator.generateData(sequenceLength, in_saveAncestral); } void readLSDProbabilities(const char *path, Tree &speciesTree, LSDTimeProbs &lsdTimes) { ifstream lsdFile; lsdFile.open(path); LSDTimeProbs::readFromFile(lsdFile, speciesTree, lsdTimes); lsdFile.close(); } void writeStringToFile(const string &path, const string &outputString) { ofstream outputFile; outputFile.open(path.c_str()); outputFile << outputString; outputFile.close(); }