Search in sources :

Example 86 with Taxon

use of dr.evolution.util.Taxon in project beast-mcmc by beast-dev.

the class DateGuesser method guessDates.

public void guessDates(List<Taxon> taxonList, Map<Taxon, String> taxonDateMap) {
    dateFormat = new SimpleDateFormat(calendarDateFormat);
    dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
    for (int i = 0; i < taxonList.size(); i++) {
        Taxon taxon = taxonList.get(i);
        // Allocates a Date object and initializes it to represent the specified number of milliseconds since the
        // standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT
        java.util.Date origin = new java.util.Date(0);
        double[] values = new double[2];
        try {
            if (taxonDateMap != null) {
                String dateString = taxonDateMap.get(taxon);
                parseDate(taxon.getId(), dateString, values);
            } else {
                switch(guessType) {
                    case ORDER:
                        guessDateFromOrder(taxonList.get(i).getId(), order, fromLast, values);
                        break;
                    case PREFIX:
                        guessDateFromPrefix(taxonList.get(i).getId(), prefix, order, fromLast, values);
                        break;
                    case REGEX:
                        guessDateFromRegex(taxonList.get(i).getId(), regex, values);
                        break;
                    default:
                        throw new IllegalArgumentException("unknown GuessType");
                }
            }
        } catch (GuessDatesException gfe) {
        // @todo catch errors and give to user
        }
        double d = values[0];
        if (!parseCalendarDates && !parseCalendarDatesAndPrecision) {
            if (offset > 0) {
                if (unlessLessThan > 0) {
                    if (d < unlessLessThan) {
                        d += offset2;
                    } else {
                        d += offset;
                    }
                } else {
                    d += offset;
                }
            }
        }
        // @todo if any taxa aren't set then return warning
        Date date = Date.createTimeSinceOrigin(d, Units.Type.YEARS, origin);
        date.setPrecision(values[1]);
        taxon.setAttribute("date", date);
    }
}
Also used : java.util(java.util) Taxon(dr.evolution.util.Taxon) Date(dr.evolution.util.Date)

Example 87 with Taxon

use of dr.evolution.util.Taxon in project beast-mcmc by beast-dev.

the class XMLGenerator method writeTaxa.

// END: writeBranchRatesModel
private void writeTaxa(Taxa taxa, XMLWriter writer, String suffix) {
    // tagname
    writer.writeOpenTag(// tagname
    TaxaParser.TAXA, new Attribute[] { // attributes[]
    new Attribute.Default<String>(XMLParser.ID, TaxaParser.TAXA + suffix) });
    for (int i = 0; i < taxa.getTaxonCount(); i++) {
        Taxon taxon = taxa.getTaxon(i);
        writer.writeTag(// tagname
        TaxonParser.TAXON, new Attribute[] { // attributes[]
        new Attribute.Default<String>(XMLParser.ID, taxon.getId()) }, // close
        true);
    }
    // END: i loop
    writer.writeCloseTag(TaxaParser.TAXA);
}
Also used : Attribute(dr.util.Attribute) Taxon(dr.evolution.util.Taxon)

Example 88 with Taxon

use of dr.evolution.util.Taxon in project beast-mcmc by beast-dev.

the class BeagleSeqSimTest method simulateTopology.

// END: annotateTree
static void simulateTopology() {
    try {
        System.out.println("Test case 1: simulateTopology");
        MathUtils.setSeed(666);
        int sequenceLength = 10;
        ArrayList<Partition> partitionsList = new ArrayList<Partition>();
        // create tree
        NewickImporter importer = new NewickImporter("(SimSeq1:73.7468,(SimSeq2:25.256989999999995,SimSeq3:45.256989999999995):18.48981);");
        Tree tree = importer.importTree(null);
        // set demographic function
        ExponentialGrowth exponentialGrowth = new ExponentialGrowth(Units.Type.YEARS);
        exponentialGrowth.setN0(10);
        exponentialGrowth.setGrowthRate(0.5);
        Taxa taxa = new Taxa();
        for (Taxon taxon : tree.asList()) {
            double absoluteHeight = Utils.getAbsoluteTaxonHeight(taxon, tree);
            taxon.setAttribute(Utils.ABSOLUTE_HEIGHT, absoluteHeight);
            // taxon.setAttribute("date", new Date(absoluteHeight,
            // Units.Type.YEARS, true));
            taxa.addTaxon(taxon);
        }
        // END: taxon loop
        CoalescentSimulator topologySimulator = new CoalescentSimulator();
        TreeModel treeModel = new TreeModel(topologySimulator.simulateTree(taxa, exponentialGrowth));
        System.out.println(treeModel.toString());
        Parameter freqs = new Parameter.Default(new double[] { 0.25, 0.25, 0.25, 0.25 });
        FrequencyModel freqModel = new FrequencyModel(Nucleotides.INSTANCE, freqs);
        // create substitution model
        Parameter kappa = new Parameter.Default(1, 10);
        HKY hky = new HKY(kappa, freqModel);
        HomogeneousBranchModel substitutionModel = new HomogeneousBranchModel(hky);
        // create site model
        GammaSiteRateModel siteRateModel = new GammaSiteRateModel("siteModel");
        // create branch rate model
        BranchRateModel branchRateModel = new DefaultBranchRateModel();
        // create partition
        Partition partition1 = new //
        Partition(//
        treeModel, //
        substitutionModel, //
        siteRateModel, //
        branchRateModel, //
        freqModel, // from
        0, // to
        sequenceLength - 1, // every
        1);
        partitionsList.add(partition1);
        // feed to sequence simulator and generate data
        BeagleSequenceSimulator simulator = new BeagleSequenceSimulator(partitionsList);
        System.out.println(simulator.simulate(simulateInPar, false).toString());
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(-1);
    }
// END: try-catch block
}
Also used : FrequencyModel(dr.evomodel.substmodel.FrequencyModel) Partition(dr.app.beagle.tools.Partition) ExponentialGrowth(dr.evolution.coalescent.ExponentialGrowth) Taxon(dr.evolution.util.Taxon) ArrayList(java.util.ArrayList) HomogeneousBranchModel(dr.evomodel.branchmodel.HomogeneousBranchModel) GammaSiteRateModel(dr.evomodel.siteratemodel.GammaSiteRateModel) CoalescentSimulator(dr.evolution.coalescent.CoalescentSimulator) BeagleSequenceSimulator(dr.app.beagle.tools.BeagleSequenceSimulator) ImportException(dr.evolution.io.Importer.ImportException) IOException(java.io.IOException) DefaultBranchRateModel(dr.evomodel.branchratemodel.DefaultBranchRateModel) Taxa(dr.evolution.util.Taxa) TreeModel(dr.evomodel.tree.TreeModel) DefaultBranchRateModel(dr.evomodel.branchratemodel.DefaultBranchRateModel) BranchRateModel(dr.evomodel.branchratemodel.BranchRateModel) NewickImporter(dr.evolution.io.NewickImporter) HKY(dr.evomodel.substmodel.nucleotide.HKY) Tree(dr.evolution.tree.Tree) Parameter(dr.inference.model.Parameter)

Example 89 with Taxon

use of dr.evolution.util.Taxon in project beast-mcmc by beast-dev.

the class TestCalibratedYuleModel method yuleTester.

private void yuleTester(TreeModel treeModel, OperatorSchedule schedule, Parameter brParameter, double S, int chainLength) throws IOException, TreeUtils.MissingTaxonException {
    MCMC mcmc = new MCMC("mcmc1");
    MCMCOptions options = new MCMCOptions(chainLength);
    TreeLengthStatistic tls = new TreeLengthStatistic(TL, treeModel);
    TreeHeightStatistic rootHeight = new TreeHeightStatistic(TREE_HEIGHT, treeModel);
    SpeciationModel speciationModel = new BirthDeathGernhard08Model("yule", brParameter, null, null, BirthDeathGernhard08Model.TreeType.UNSCALED, Units.Type.SUBSTITUTIONS, false);
    Likelihood speciationLikelihood = new SpeciationLikelihood(treeModel, speciationModel, "yule.like");
    Taxa halfTaxa = new Taxa();
    for (int i = 0; i < taxa.getTaxonCount() / 2; i++) {
        halfTaxa.addTaxon(new Taxon("T" + Integer.toString(i)));
    }
    TMRCAStatistic tmrca = new TMRCAStatistic("tmrca(halfTaxa)", treeModel, halfTaxa, false, false);
    DistributionLikelihood logNormalLikelihood = new DistributionLikelihood(new LogNormalDistribution(M, S), // meanInRealSpace="false"
    0);
    logNormalLikelihood.addData(tmrca);
    MonophylyStatistic monophylyStatistic = new MonophylyStatistic("monophyly(halfTaxa)", treeModel, halfTaxa, null);
    BooleanLikelihood booleanLikelihood = new BooleanLikelihood();
    booleanLikelihood.addData(monophylyStatistic);
    //CompoundLikelihood
    List<Likelihood> likelihoods = new ArrayList<Likelihood>();
    likelihoods.add(speciationLikelihood);
    likelihoods.add(logNormalLikelihood);
    likelihoods.add(booleanLikelihood);
    Likelihood prior = new CompoundLikelihood(0, likelihoods);
    prior.setId(CompoundLikelihoodParser.PRIOR);
    ArrayLogFormatter logformatter = new ArrayLogFormatter(false);
    MCLogger[] loggers = new MCLogger[1];
    loggers[0] = new MCLogger(logformatter, (int) (options.getChainLength() / 10000), false);
    loggers[0].add(speciationLikelihood);
    loggers[0].add(rootHeight);
    loggers[0].add(tmrca);
    loggers[0].add(tls);
    loggers[0].add(brParameter);
    mcmc.setShowOperatorAnalysis(false);
    mcmc.init(options, prior, schedule, loggers);
    mcmc.run();
    List<Trace> traces = logformatter.getTraces();
    ArrayTraceList traceList = new ArrayTraceList("yuleModelTest", traces, 1000);
    for (int i = 1; i < traces.size(); i++) {
        traceList.analyseTrace(i);
    }
    NumberFormatter formatter = new NumberFormatter(8);
    TraceCorrelation tlStats = traceList.getCorrelationStatistics(traceList.getTraceIndex(TL));
    TraceCorrelation treeHeightStats = traceList.getCorrelationStatistics(traceList.getTraceIndex("tmrca(halfTaxa)"));
    //        out.write("tmrcaHeight = \t");
    out.write(formatter.format(treeHeightStats.getMean()));
    out.write("\t");
    double expectedNodeHeight = Math.pow(Math.E, (M + (Math.pow(S, 2) / 2)));
    //        out.write("expectation = \t");
    out.write(formatter.format(expectedNodeHeight));
    out.write("\t");
    double error = Math.abs((treeHeightStats.getMean() - expectedNodeHeight) / expectedNodeHeight);
    NumberFormat percentFormatter = NumberFormat.getNumberInstance();
    percentFormatter.setMinimumFractionDigits(5);
    percentFormatter.setMinimumFractionDigits(5);
    //        out.write("error = \t");
    out.write(percentFormatter.format(error));
    out.write("\t");
    //        out.write("tl.ess = \t");
    out.write(Double.toString(tlStats.getESS()));
    System.out.println("tmrcaHeight = " + formatter.format(treeHeightStats.getMean()) + ";  expectation = " + formatter.format(expectedNodeHeight) + ";  error = " + percentFormatter.format(error) + ";  tl.ess = " + tlStats.getESS());
}
Also used : BooleanLikelihood(dr.inference.model.BooleanLikelihood) CompoundLikelihood(dr.inference.model.CompoundLikelihood) Likelihood(dr.inference.model.Likelihood) DistributionLikelihood(dr.inference.distribution.DistributionLikelihood) SpeciationLikelihood(dr.evomodel.speciation.SpeciationLikelihood) BooleanLikelihood(dr.inference.model.BooleanLikelihood) BirthDeathGernhard08Model(dr.evomodel.speciation.BirthDeathGernhard08Model) MCMC(dr.inference.mcmc.MCMC) ArrayList(java.util.ArrayList) LogNormalDistribution(dr.math.distributions.LogNormalDistribution) SpeciationLikelihood(dr.evomodel.speciation.SpeciationLikelihood) Taxa(dr.evolution.util.Taxa) MCMCOptions(dr.inference.mcmc.MCMCOptions) ArrayLogFormatter(dr.inference.loggers.ArrayLogFormatter) TraceCorrelation(dr.inference.trace.TraceCorrelation) Taxon(dr.evolution.util.Taxon) CompoundLikelihood(dr.inference.model.CompoundLikelihood) SpeciationModel(dr.evomodel.speciation.SpeciationModel) Trace(dr.inference.trace.Trace) ArrayTraceList(dr.inference.trace.ArrayTraceList) DistributionLikelihood(dr.inference.distribution.DistributionLikelihood) MCLogger(dr.inference.loggers.MCLogger) NumberFormatter(dr.util.NumberFormatter) NumberFormat(java.text.NumberFormat)

Example 90 with Taxon

use of dr.evolution.util.Taxon in project beast-mcmc by beast-dev.

the class AncestralStateBeagleTreeLikelihoodTest method testJointLikelihood.

public void testJointLikelihood() {
    TreeModel treeModel = new TreeModel("treeModel", tree);
    Sequence[] sequence = new Sequence[3];
    sequence[0] = new Sequence(new Taxon("0"), "A");
    sequence[1] = new Sequence(new Taxon("1"), "C");
    sequence[2] = new Sequence(new Taxon("2"), "C");
    Taxa taxa = new Taxa();
    for (Sequence s : sequence) {
        taxa.addTaxon(s.getTaxon());
    }
    SimpleAlignment alignment = new SimpleAlignment();
    for (Sequence s : sequence) {
        alignment.addSequence(s);
    }
    Parameter mu = new Parameter.Default(1, 1.0);
    Parameter kappa = new Parameter.Default(1, 1.0);
    double[] pi = { 0.25, 0.25, 0.25, 0.25 };
    Parameter freqs = new Parameter.Default(pi);
    FrequencyModel f = new FrequencyModel(Nucleotides.INSTANCE, freqs);
    HKY hky = new HKY(kappa, f);
    GammaSiteRateModel siteRateModel = new GammaSiteRateModel("gammaModel", mu, null, -1, null);
    siteRateModel.setSubstitutionModel(hky);
    BranchModel branchModel = new HomogeneousBranchModel(siteRateModel.getSubstitutionModel());
    BranchRateModel branchRateModel = null;
    AncestralStateBeagleTreeLikelihood treeLikelihood = new AncestralStateBeagleTreeLikelihood(alignment, treeModel, branchModel, siteRateModel, branchRateModel, null, false, PartialsRescalingScheme.DEFAULT, true, null, hky.getDataType(), "stateTag", // useMap = true
    true, false);
    double logLike = treeLikelihood.getLogLikelihood();
    StringBuffer buffer = new StringBuffer();
    //        Tree.Utils.newick(treeModel, treeModel.getRoot(), false, Tree.BranchLengthType.LENGTHS_AS_TIME,
    //                null, null, new NodeAttributeProvider[]{treeLikelihood}, null, null, buffer);
    TreeUtils.newick(treeModel, treeModel.getRoot(), false, TreeUtils.BranchLengthType.LENGTHS_AS_TIME, null, null, new TreeTraitProvider[] { treeLikelihood }, null, buffer);
    System.out.println(buffer);
    System.out.println("t_CA(2) = " + t(false, 2.0));
    System.out.println("t_CC(1) = " + t(true, 1.0));
    double trueValue = 0.25 * t(false, 2.0) * Math.pow(t(true, 1.0), 3.0);
    assertEquals(logLike, Math.log(trueValue), 1e-6);
}
Also used : FrequencyModel(dr.evomodel.substmodel.FrequencyModel) Taxon(dr.evolution.util.Taxon) HomogeneousBranchModel(dr.evomodel.branchmodel.HomogeneousBranchModel) GammaSiteRateModel(dr.evomodel.siteratemodel.GammaSiteRateModel) Sequence(dr.evolution.sequence.Sequence) BranchModel(dr.evomodel.branchmodel.BranchModel) HomogeneousBranchModel(dr.evomodel.branchmodel.HomogeneousBranchModel) TreeModel(dr.evomodel.tree.TreeModel) Taxa(dr.evolution.util.Taxa) SimpleAlignment(dr.evolution.alignment.SimpleAlignment) BranchRateModel(dr.evomodel.branchratemodel.BranchRateModel) HKY(dr.evomodel.substmodel.nucleotide.HKY) Parameter(dr.inference.model.Parameter) AncestralStateBeagleTreeLikelihood(dr.evomodel.treelikelihood.AncestralStateBeagleTreeLikelihood)

Aggregations

Taxon (dr.evolution.util.Taxon)151 Taxa (dr.evolution.util.Taxa)31 ArrayList (java.util.ArrayList)24 TaxonList (dr.evolution.util.TaxonList)19 NodeRef (dr.evolution.tree.NodeRef)18 Date (dr.evolution.util.Date)18 Tree (dr.evolution.tree.Tree)15 Sequence (dr.evolution.sequence.Sequence)12 TreeModel (dr.evomodel.tree.TreeModel)12 Parameter (dr.inference.model.Parameter)12 Attribute (dr.util.Attribute)11 SimpleAlignment (dr.evolution.alignment.SimpleAlignment)10 Patterns (dr.evolution.alignment.Patterns)9 NewickImporter (dr.evolution.io.NewickImporter)7 BranchRateModel (dr.evomodel.branchratemodel.BranchRateModel)7 Microsatellite (dr.evolution.datatype.Microsatellite)6 IOException (java.io.IOException)5 HashSet (java.util.HashSet)5 PatternList (dr.evolution.alignment.PatternList)4 DataType (dr.evolution.datatype.DataType)4