Search in sources :

Example 71 with Taxa

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

the class OldCoalescentSimulatorParser method parseXMLObject.

public Object parseXMLObject(XMLObject xo) throws XMLParseException {
    CoalescentSimulator simulator = new CoalescentSimulator();
    DemographicModel demoModel = (DemographicModel) xo.getChild(DemographicModel.class);
    List<TaxonList> taxonLists = new ArrayList<TaxonList>();
    List<Tree> subtrees = new ArrayList<Tree>();
    double rootHeight = xo.getAttribute(ROOT_HEIGHT, -1.0);
    if (xo.hasAttribute(RESCALE_HEIGHT)) {
        rootHeight = xo.getDoubleAttribute(RESCALE_HEIGHT);
    }
    // should have one child that is node
    for (int i = 0; i < xo.getChildCount(); i++) {
        final Object child = xo.getChild(i);
        // AER - swapped the order of these round because Trees are TaxonLists...
        if (child instanceof Tree) {
            subtrees.add((Tree) child);
        } else if (child instanceof TaxonList) {
            taxonLists.add((TaxonList) child);
        } else if (xo.getChildName(i).equals(CONSTRAINED_TAXA)) {
            XMLObject constrainedTaxa = (XMLObject) child;
            // all taxa
            final TaxonList taxa = (TaxonList) constrainedTaxa.getChild(TaxonList.class);
            List<CoalescentSimulator.TaxaConstraint> constraints = new ArrayList<CoalescentSimulator.TaxaConstraint>();
            final String setsNotCompatibleMessage = "taxa sets not compatible";
            for (int nc = 0; nc < constrainedTaxa.getChildCount(); ++nc) {
                final Object object = constrainedTaxa.getChild(nc);
                if (object instanceof XMLObject) {
                    final XMLObject constraint = (XMLObject) object;
                    if (constraint.getName().equals(TMRCA_CONSTRAINT)) {
                        TaxonList taxaSubSet = (TaxonList) constraint.getChild(TaxonList.class);
                        ParametricDistributionModel dist = (ParametricDistributionModel) constraint.getChild(ParametricDistributionModel.class);
                        boolean isMono = constraint.getAttribute(IS_MONOPHYLETIC, true);
                        final CoalescentSimulator.TaxaConstraint taxaConstraint = new CoalescentSimulator.TaxaConstraint(taxaSubSet, dist, isMono);
                        int insertPoint;
                        for (insertPoint = 0; insertPoint < constraints.size(); ++insertPoint) {
                            // if new <= constraints[insertPoint] insert before insertPoint
                            final CoalescentSimulator.TaxaConstraint iConstraint = constraints.get(insertPoint);
                            if (iConstraint.isMonophyletic) {
                                if (!taxaConstraint.isMonophyletic) {
                                    continue;
                                }
                                final TaxonList taxonsip = iConstraint.taxons;
                                final int nIn = simulator.sizeOfIntersection(taxonsip, taxaSubSet);
                                if (nIn == taxaSubSet.getTaxonCount()) {
                                    break;
                                }
                                if (nIn > 0 && nIn != taxonsip.getTaxonCount()) {
                                    throw new XMLParseException(setsNotCompatibleMessage);
                                }
                            } else {
                                // reached non mono area
                                if (!taxaConstraint.isMonophyletic) {
                                    if (iConstraint.upper >= taxaConstraint.upper) {
                                        break;
                                    }
                                } else {
                                    break;
                                }
                            }
                        }
                        constraints.add(insertPoint, taxaConstraint);
                    }
                }
            }
            final int nConstraints = constraints.size();
            if (nConstraints == 0) {
                if (taxa != null) {
                    taxonLists.add(taxa);
                }
            } else {
                for (int nc = 0; nc < nConstraints; ++nc) {
                    CoalescentSimulator.TaxaConstraint cnc = constraints.get(nc);
                    if (!cnc.isMonophyletic) {
                        for (int nc1 = nc - 1; nc1 >= 0; --nc1) {
                            CoalescentSimulator.TaxaConstraint cnc1 = constraints.get(nc1);
                            int x = simulator.sizeOfIntersection(cnc.taxons, cnc1.taxons);
                            if (x > 0) {
                                Taxa combinedTaxa = new Taxa(cnc.taxons);
                                combinedTaxa.addTaxa(cnc1.taxons);
                                cnc = new CoalescentSimulator.TaxaConstraint(combinedTaxa, cnc.lower, cnc.upper, cnc.isMonophyletic);
                                constraints.set(nc, cnc);
                            }
                        }
                    }
                }
                // determine upper bound for each set.
                double[] upper = new double[nConstraints];
                for (int nc = nConstraints - 1; nc >= 0; --nc) {
                    final CoalescentSimulator.TaxaConstraint cnc = constraints.get(nc);
                    if (cnc.realLimits()) {
                        upper[nc] = cnc.upper;
                    } else {
                        upper[nc] = Double.POSITIVE_INFINITY;
                    }
                }
                for (int nc = nConstraints - 1; nc >= 0; --nc) {
                    final CoalescentSimulator.TaxaConstraint cnc = constraints.get(nc);
                    if (upper[nc] < Double.POSITIVE_INFINITY) {
                        for (int nc1 = nc - 1; nc1 >= 0; --nc1) {
                            final CoalescentSimulator.TaxaConstraint cnc1 = constraints.get(nc1);
                            if (simulator.contained(cnc1.taxons, cnc.taxons)) {
                                upper[nc1] = Math.min(upper[nc1], upper[nc]);
                                if (cnc1.realLimits() && cnc1.lower > upper[nc1]) {
                                    throw new XMLParseException(setsNotCompatibleMessage);
                                }
                                break;
                            }
                        }
                    }
                }
                // collect subtrees here
                List<Tree> st = new ArrayList<Tree>();
                for (int nc = 0; nc < constraints.size(); ++nc) {
                    final CoalescentSimulator.TaxaConstraint nxt = constraints.get(nc);
                    // collect all previously built subtrees which are a subset of taxa set to be added
                    List<Tree> subs = new ArrayList<Tree>();
                    Taxa newTaxons = new Taxa(nxt.taxons);
                    for (int k = 0; k < st.size(); ++k) {
                        final Tree stk = st.get(k);
                        int x = simulator.sizeOfIntersection(stk, nxt.taxons);
                        if (x == st.get(k).getTaxonCount()) {
                            final Tree tree = st.remove(k);
                            --k;
                            subs.add(tree);
                            newTaxons.removeTaxa(tree);
                        }
                    }
                    SimpleTree tree = simulator.simulateTree(newTaxons, demoModel);
                    final double lower = nxt.realLimits() ? nxt.lower : 0;
                    if (upper[nc] < Double.MAX_VALUE) {
                        simulator.attemptToScaleTree(tree, (lower + upper[nc]) / 2);
                    }
                    if (subs.size() > 0) {
                        if (tree.getTaxonCount() > 0)
                            subs.add(tree);
                        double h = -1;
                        if (upper[nc] < Double.MAX_VALUE) {
                            for (Tree t : subs) {
                                // protect against 1 taxa tree with height 0
                                final double rh = t.getNodeHeight(t.getRoot());
                                h = Math.max(h, rh > 0 ? rh : (lower + upper[nc]) / 2);
                            }
                            h = (h + upper[nc]) / 2;
                        }
                        tree = simulator.simulateTree(subs.toArray(new Tree[subs.size()]), demoModel, h, true);
                    }
                    st.add(tree);
                }
                // add a taxon list for remaining taxa
                if (taxa != null) {
                    final Taxa list = new Taxa();
                    for (int j = 0; j < taxa.getTaxonCount(); ++j) {
                        Taxon taxonj = taxa.getTaxon(j);
                        for (Tree aSt : st) {
                            if (aSt.getTaxonIndex(taxonj) >= 0) {
                                taxonj = null;
                                break;
                            }
                        }
                        if (taxonj != null) {
                            list.addTaxon(taxonj);
                        }
                    }
                    if (list.getTaxonCount() > 0) {
                        taxonLists.add(list);
                    }
                }
                if (st.size() > 1) {
                    final Tree t = simulator.simulateTree(st.toArray(new Tree[st.size()]), demoModel, -1, false);
                    subtrees.add(t);
                } else {
                    subtrees.add(st.get(0));
                }
            }
        }
    }
    if (taxonLists.size() == 0) {
        if (subtrees.size() == 1) {
            return subtrees.get(0);
        }
        throw new XMLParseException("Expected at least one taxonList or two subtrees in " + getParserName() + " element.");
    }
    try {
        Tree[] trees = new Tree[taxonLists.size() + subtrees.size()];
        // simulate each taxonList separately
        for (int i = 0; i < taxonLists.size(); i++) {
            trees[i] = simulator.simulateTree(taxonLists.get(i), demoModel);
        }
        // add the preset trees
        for (int i = 0; i < subtrees.size(); i++) {
            trees[i + taxonLists.size()] = subtrees.get(i);
        }
        return simulator.simulateTree(trees, demoModel, rootHeight, trees.length != 1);
    } catch (IllegalArgumentException iae) {
        throw new XMLParseException(iae.getMessage());
    }
}
Also used : TaxonList(dr.evolution.util.TaxonList) Taxon(dr.evolution.util.Taxon) ArrayList(java.util.ArrayList) DemographicModel(dr.evomodel.coalescent.demographicmodel.DemographicModel) SimpleTree(dr.evolution.tree.SimpleTree) CoalescentSimulator(dr.evomodel.coalescent.CoalescentSimulator) Taxa(dr.evolution.util.Taxa) ParametricDistributionModel(dr.inference.distribution.ParametricDistributionModel) Tree(dr.evolution.tree.Tree) SimpleTree(dr.evolution.tree.SimpleTree)

Example 72 with Taxa

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

the class AncestralTraitTreeModelParser method parseAncestor.

private static AncestralTaxonInTree parseAncestor(MutableTreeModel tree, XMLObject xo, final int index) throws XMLParseException {
    Taxon ancestor = (Taxon) xo.getChild(Taxon.class);
    Parameter pseudoBranchLength = (Parameter) xo.getChild(Parameter.class);
    AncestralTaxonInTree ancestorInTree;
    NodeRef node = new NodeRef() {

        @Override
        public int getNumber() {
            return index;
        }

        @Override
        public void setNumber(int n) {
            throw new RuntimeException("Do not set");
        }
    };
    if (xo.hasChildNamed(MonophylyStatisticParser.MRCA)) {
        TaxonList descendants = MonophylyStatisticParser.parseTaxonListOrTaxa(xo.getChild(MonophylyStatisticParser.MRCA));
        try {
            ancestorInTree = new AncestralTaxonInTree(ancestor, tree, descendants, pseudoBranchLength, null, node, index, 0.0);
        } catch (TreeUtils.MissingTaxonException e) {
            throw new XMLParseException("Unable to find taxa for " + ancestor.getId());
        }
    } else {
        XMLObject cxo = xo.getChild(ANCESTRAL_PATH);
        Taxon taxon = (Taxon) cxo.getChild(Taxon.class);
        Parameter time = (Parameter) cxo.getChild(Parameter.class);
        boolean relativeHeight = cxo.getAttribute(RELATIVE_HEIGHT, false);
        double offset = 0;
        if (relativeHeight) {
            Object date = taxon.getAttribute("date");
            if (date != null && date instanceof Date) {
                offset = taxon.getHeight();
            } else {
                throw new XMLParseException("Taxon '" + taxon.getId() + "' has no specified date");
            }
        } else {
            if (time.getParameterValue(0) <= taxon.getHeight()) {
                throw new XMLParseException("Ancestral path time must be > sampling time for taxon '" + taxon.getId() + "'");
            }
        }
        Taxa descendent = new Taxa();
        descendent.addTaxon(taxon);
        try {
            ancestorInTree = new AncestralTaxonInTree(ancestor, tree, descendent, pseudoBranchLength, time, node, index, // TODO Refactor into separate class from MRCA version
            offset);
        } catch (TreeUtils.MissingTaxonException e) {
            throw new XMLParseException("Unable to find taxa for " + ancestor.getId());
        }
    }
    return ancestorInTree;
}
Also used : TaxonList(dr.evolution.util.TaxonList) Taxon(dr.evolution.util.Taxon) Date(dr.evolution.util.Date) NodeRef(dr.evolution.tree.NodeRef) Taxa(dr.evolution.util.Taxa) AncestralTaxonInTree(dr.evomodel.continuous.AncestralTaxonInTree) FastMatrixParameter(dr.inference.model.FastMatrixParameter) Parameter(dr.inference.model.Parameter) TreeUtils(dr.evolution.tree.TreeUtils)

Example 73 with Taxa

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

the class ExternalLengthStatisticParser method parseXMLObject.

public Object parseXMLObject(XMLObject xo) throws XMLParseException {
    String name = xo.getAttribute(Statistic.NAME, xo.getId());
    Tree tree = (Tree) xo.getChild(Tree.class);
    TaxonList taxa = (TaxonList) xo.getChild(Taxa.class);
    try {
        return new ExternalLengthStatistic(name, tree, taxa);
    } catch (TreeUtils.MissingTaxonException mte) {
        throw new XMLParseException("Taxon, " + mte + ", in " + getParserName() + "was not found in the tree.");
    }
}
Also used : Taxa(dr.evolution.util.Taxa) TaxonList(dr.evolution.util.TaxonList) Tree(dr.evolution.tree.Tree) ExternalLengthStatistic(dr.evomodel.tree.ExternalLengthStatistic) TreeUtils(dr.evolution.tree.TreeUtils)

Example 74 with Taxa

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

the class AncestralStateTreeLikelihoodTest method testJointLikelihood.

public void testJointLikelihood() {
    TreeModel treeModel = new DefaultTreeModel("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);
    AncestralStateTreeLikelihood treeLikelihood = new AncestralStateTreeLikelihood(alignment, treeModel, new GammaSiteModel(hky), new StrictClockBranchRates(mu), false, true, Nucleotides.INSTANCE, "state", false, // useMap = true
    true, false);
    double logLike = treeLikelihood.getLogLikelihood();
    StringBuffer buffer = new StringBuffer();
    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.oldevomodel.substmodel.FrequencyModel) Taxon(dr.evolution.util.Taxon) AncestralStateTreeLikelihood(dr.oldevomodel.treelikelihood.AncestralStateTreeLikelihood) DefaultTreeModel(dr.evomodel.tree.DefaultTreeModel) Sequence(dr.evolution.sequence.Sequence) StrictClockBranchRates(dr.evomodel.branchratemodel.StrictClockBranchRates) TreeModel(dr.evomodel.tree.TreeModel) DefaultTreeModel(dr.evomodel.tree.DefaultTreeModel) Taxa(dr.evolution.util.Taxa) GammaSiteModel(dr.oldevomodel.sitemodel.GammaSiteModel) SimpleAlignment(dr.evolution.alignment.SimpleAlignment) HKY(dr.oldevomodel.substmodel.HKY) Parameter(dr.inference.model.Parameter)

Example 75 with Taxa

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

the class MsatFullLikelihoodTest method setUpExample3.

private void setUpExample3() throws Exception {
    // taxa
    ArrayList<Taxon> taxonList3 = new ArrayList<Taxon>();
    Collections.addAll(taxonList3, new Taxon("taxon1"), new Taxon("taxon2"), new Taxon("taxon3"), new Taxon("taxon4"), new Taxon("taxon5"), new Taxon("taxon6"), new Taxon("taxon7"));
    Taxa taxa3 = new Taxa(taxonList3);
    // msat datatype
    Microsatellite msat = new Microsatellite(1, 4);
    Patterns msatPatterns = new Patterns(msat, taxa3);
    // pattern in the correct code form.
    msatPatterns.addPattern(new int[] { 0, 3, 1, 2, 3, 0, 1 });
    // create tree
    NewickImporter importer = new NewickImporter("(((taxon1:0.3,taxon2:0.3):0.6,taxon3:0.9):0.9,((taxon4:0.5,taxon5:0.5):0.3,(taxon6:0.7,taxon7:0.7):0.1):1.0);");
    Tree tree = importer.importTree(null);
    // treeModel
    TreeModel treeModel = new DefaultTreeModel(tree);
    // msatsubstModel
    AsymmetricQuadraticModel aqm3 = new AsymmetricQuadraticModel(msat, null);
    // siteModel
    GammaSiteModel siteModel = new GammaSiteModel(aqm3);
    // treeLikelihood
    treeLikelihood3 = new TreeLikelihood(msatPatterns, treeModel, siteModel, null, null, false, false, true, false, false);
}
Also used : Microsatellite(dr.evolution.datatype.Microsatellite) Taxon(dr.evolution.util.Taxon) ArrayList(java.util.ArrayList) TreeLikelihood(dr.oldevomodel.treelikelihood.TreeLikelihood) DefaultTreeModel(dr.evomodel.tree.DefaultTreeModel) Taxa(dr.evolution.util.Taxa) TreeModel(dr.evomodel.tree.TreeModel) DefaultTreeModel(dr.evomodel.tree.DefaultTreeModel) GammaSiteModel(dr.oldevomodel.sitemodel.GammaSiteModel) NewickImporter(dr.evolution.io.NewickImporter) AsymmetricQuadraticModel(dr.oldevomodel.substmodel.AsymmetricQuadraticModel) Tree(dr.evolution.tree.Tree) Patterns(dr.evolution.alignment.Patterns)

Aggregations

Taxa (dr.evolution.util.Taxa)75 Taxon (dr.evolution.util.Taxon)34 ArrayList (java.util.ArrayList)23 Tree (dr.evolution.tree.Tree)19 TaxonList (dr.evolution.util.TaxonList)15 Attribute (dr.util.Attribute)13 DefaultTreeModel (dr.evomodel.tree.DefaultTreeModel)10 TreeModel (dr.evomodel.tree.TreeModel)10 Patterns (dr.evolution.alignment.Patterns)9 Microsatellite (dr.evolution.datatype.Microsatellite)9 IOException (java.io.IOException)8 NewickImporter (dr.evolution.io.NewickImporter)7 Parameter (dr.inference.model.Parameter)6 Date (dr.evolution.util.Date)5 GammaSiteModel (dr.oldevomodel.sitemodel.GammaSiteModel)5 SimpleAlignment (dr.evolution.alignment.SimpleAlignment)4 ImportException (dr.evolution.io.Importer.ImportException)4 BranchRateModel (dr.evomodel.branchratemodel.BranchRateModel)4 CoalescentSimulator (dr.evomodel.coalescent.CoalescentSimulator)4 PartitionTreeModel (dr.app.beauti.options.PartitionTreeModel)3