Search in sources :

Example 51 with Tree

use of beast.evolution.tree.Tree in project beast2 by CompEvol.

the class BeautiDoc method addMRCAPrior.

public void addMRCAPrior(MRCAPrior mrcaPrior) {
    Tree tree = (Tree) pluginmap.get("Tree.t:" + alignments.get(0).getID());
    if (tree == null) {
        for (String key : pluginmap.keySet()) {
            if (key.startsWith("Tree.t:")) {
                tree = (Tree) pluginmap.get(key);
                break;
            }
        }
    }
    // make sure we have the appropriate tree:
    if (alignments.size() > 1) {
        String testTaxon = mrcaPrior.taxonsetInput.get().toString().split("\n")[1].trim();
        // = tree.getTaxaNames();
        String[] taxaNames;
        int index = -1;
        int j = 0;
        while (index < 0 && j++ < alignments.size()) {
            tree = (Tree) pluginmap.get("Tree.t:" + alignments.get(j - 1).getID());
            taxaNames = tree.getTaxaNames();
            for (int i = 0; i < taxaNames.length && index < 0; i++) if (testTaxon.equals(taxaNames[i]))
                index = i;
        }
    }
    CompoundDistribution prior = (CompoundDistribution) pluginmap.get("prior");
    mrcaPrior.treeInput.setValue(tree, mrcaPrior);
    ParametricDistribution distr = mrcaPrior.distInput.get();
    TaxonSet t = mrcaPrior.taxonsetInput.get();
    if (taxaset.keySet().contains(t.getID())) {
        Log.warning.println("taxonset " + t.getID() + " already exists: MRCAPrior " + mrcaPrior.getID() + " can not be added");
    } else {
        taxaset.put(t.getID(), t);
        // ensure TaxonSets are not duplicated
        List<Taxon> taxa = t.taxonsetInput.get();
        for (int i = 0; i < taxa.size(); i++) {
            if (taxaset.containsKey(taxa.get(i).getID())) {
                taxa.set(i, taxaset.get(taxa.get(i).getID()));
            } else {
                taxaset.put(taxa.get(i).getID(), taxa.get(i));
            }
        }
        if (distr instanceof Normal && (Double.isInfinite(((Normal) distr).sigmaInput.get().getValue()))) {
        // it is a 'fixed' calibration, no need to add a distribution
        } else {
            prior.pDistributions.setValue(mrcaPrior, prior);
            connect(mrcaPrior, "tracelog", "log");
        }
    }
    if (t.taxonsetInput.get().size() == 1 && distr != null) {
        // only add operators if it is NOT a 'fixed' calibration
        if (!(distr instanceof Normal && (Double.isInfinite(((Normal) distr).sigmaInput.get().getValue())))) {
            TipDatesRandomWalker operator = new TipDatesRandomWalker();
            t.initAndValidate();
            operator.initByName("taxonset", t, "weight", 1.0, "tree", tree, "windowSize", 1.0);
            operator.setID("TipDatesRandomWalker." + t.getID());
            MCMC mcmc = (MCMC) this.mcmc.get();
            mcmc.operatorsInput.setValue(operator, mcmc);
        }
        // set up date trait
        double date = distr.getMean();
        TraitSet dateTrait = null;
        for (TraitSet ts : tree.m_traitList.get()) {
            if (ts.isDateTrait()) {
                dateTrait = ts;
            }
        }
        if (dateTrait == null) {
            dateTrait = new TraitSet();
            dateTrait.setID("traitsetDate");
            registerPlugin(dateTrait);
            dateTrait.initByName("traitname", TraitSet.DATE_BACKWARD_TRAIT, "taxa", tree.getTaxonset(), "value", t.taxonsetInput.get().get(0).getID() + "=" + date);
            tree.m_traitList.setValue(dateTrait, tree);
            tree.initAndValidate();
        } else {
            dateTrait.traitsInput.setValue(dateTrait.traitsInput.get() + ",\n" + t.taxonsetInput.get().get(0).getID() + "=" + date, dateTrait);
        }
        mrcaPrior.onlyUseTipsInput.setValue(true, mrcaPrior);
    }
}
Also used : Taxon(beast.evolution.alignment.Taxon) MCMC(beast.core.MCMC) TaxonSet(beast.evolution.alignment.TaxonSet) Normal(beast.math.distributions.Normal) CompoundDistribution(beast.core.util.CompoundDistribution) ParametricDistribution(beast.math.distributions.ParametricDistribution) TraitSet(beast.evolution.tree.TraitSet) Tree(beast.evolution.tree.Tree) TipDatesRandomWalker(beast.evolution.operators.TipDatesRandomWalker)

Example 52 with Tree

use of beast.evolution.tree.Tree in project beast2 by CompEvol.

the class BeautiDoc method collectClockModels.

private void collectClockModels() {
    // collect branch rate models from model
    CompoundDistribution likelihood = (CompoundDistribution) pluginmap.get("likelihood");
    while (clockModels.size() < partitionNames.size()) {
        try {
            GenericTreeLikelihood treelikelihood = new GenericTreeLikelihood();
            treelikelihood.branchRateModelInput.setValue(new StrictClockModel(), treelikelihood);
            List<BeautiSubTemplate> availableBEASTObjects = inputEditorFactory.getAvailableTemplates(treelikelihood.branchRateModelInput, treelikelihood, null, this);
            BEASTInterface beastObject = availableBEASTObjects.get(0).createSubNet(partitionNames.get(clockModels.size()), true);
            clockModels.add((BranchRateModel.Base) beastObject);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    int k = 0;
    for (Distribution d : likelihood.pDistributions.get()) {
        BranchRateModel clockModel = ((GenericTreeLikelihood) d).branchRateModelInput.get();
        // sanity check
        Tree tree = null;
        try {
            for (Input<?> input : ((BEASTInterface) clockModel).listInputs()) {
                if (input.getName().equals("tree")) {
                    tree = (Tree) input.get();
                }
            }
            if (tree != null && tree != ((GenericTreeLikelihood) d).treeInput.get()) {
                clockModel = clockModels.get(k);
                Log.warning.println("WARNING: unlinking clock model for " + d.getID());
                // TODO #557: this should move to the event of clock model drop box
                // JOptionPane.showMessageDialog(beauti.getSelectedComponent(),
                // "Cannot link all clock model(s) except strict clock with different trees !");
                ((GenericTreeLikelihood) d).branchRateModelInput.setValue(clockModel, d);
            }
        } catch (Exception e) {
        // ignore
        }
        if (clockModel != null) {
            String id = ((BEASTInterface) clockModel).getID();
            id = parsePartition(id);
            String partition = alignments.get(k).getID();
            if (id.equals(partition)) {
                clockModels.set(k, clockModel);
            }
            k++;
        }
    }
}
Also used : GenericTreeLikelihood(beast.evolution.likelihood.GenericTreeLikelihood) XMLParserException(beast.util.XMLParserException) SAXException(org.xml.sax.SAXException) TransformerException(javax.xml.transform.TransformerException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) CompoundDistribution(beast.core.util.CompoundDistribution) StrictClockModel(beast.evolution.branchratemodel.StrictClockModel) BranchRateModel(beast.evolution.branchratemodel.BranchRateModel) CompoundDistribution(beast.core.util.CompoundDistribution) ParametricDistribution(beast.math.distributions.ParametricDistribution) Distribution(beast.core.Distribution) Tree(beast.evolution.tree.Tree) BEASTInterface(beast.core.BEASTInterface)

Example 53 with Tree

use of beast.evolution.tree.Tree in project beast2 by CompEvol.

the class TreeDistributionInputEditor method validateInput.

@Override
public void validateInput() {
    TreeDistribution distr = (TreeDistribution) m_beastObject;
    // TODO: robustify for the case the tree is not a simple binary tree
    Tree tree = (Tree) distr.treeInput.get();
    if (tree == null) {
        tree = distr.treeIntervalsInput.get().treeInput.get();
    }
    if (tree.hasDateTrait()) {
        if (!distr.canHandleTipDates()) {
            m_validateLabel.setToolTipText("This tree prior cannot handle dated tips. Choose another tree prior.");
            m_validateLabel.m_circleColor = Color.red;
            m_validateLabel.setVisible(true);
            return;
        }
    }
    super.validateInput();
}
Also used : TreeDistribution(beast.evolution.tree.TreeDistribution) Tree(beast.evolution.tree.Tree)

Example 54 with Tree

use of beast.evolution.tree.Tree in project beast2 by CompEvol.

the class SequenceSimulator method main.

// printUsageAndExit
@SuppressWarnings("unchecked")
public static void main(String[] args) {
    try {
        // parse arguments
        if (args.length < 2) {
            printUsageAndExit();
        }
        String fileName = args[0];
        int replications = Integer.parseInt(args[1]);
        PrintStream out = System.out;
        if (args.length == 3) {
            File file = new File(args[2]);
            out = new PrintStream(file);
        }
        // grab the file
        String xml = "";
        BufferedReader fin = new BufferedReader(new FileReader(fileName));
        while (fin.ready()) {
            xml += fin.readLine();
        }
        fin.close();
        // parse the xml
        XMLParser parser = new XMLParser();
        BEASTInterface beastObject = parser.parseFragment(xml, true);
        // find relevant objects from the model
        TreeLikelihood treeLikelihood = getTreeLikelihood(beastObject);
        if (treeLikelihood == null) {
            throw new IllegalArgumentException("No treelikelihood found in file. Giving up now.");
        }
        Alignment data = ((Input<Alignment>) treeLikelihood.getInput("data")).get();
        Tree tree = ((Input<Tree>) treeLikelihood.getInput("tree")).get();
        SiteModel pSiteModel = ((Input<SiteModel>) treeLikelihood.getInput("siteModel")).get();
        BranchRateModel pBranchRateModel = ((Input<BranchRateModel>) treeLikelihood.getInput("branchRateModel")).get();
        // feed to sequence simulator and generate leaves
        SequenceSimulator treeSimulator = new SequenceSimulator();
        treeSimulator.init(data, tree, pSiteModel, pBranchRateModel, replications);
        XMLProducer producer = new XMLProducer();
        Alignment alignment = treeSimulator.simulate();
        xml = producer.toRawXML(alignment);
        out.println("<beast version='2.0'>");
        out.println(xml);
        out.println("</beast>");
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : PrintStream(java.io.PrintStream) XMLProducer(beast.util.XMLProducer) TreeLikelihood(beast.evolution.likelihood.TreeLikelihood) SiteModel(beast.evolution.sitemodel.SiteModel) XMLParserException(beast.util.XMLParserException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) Alignment(beast.evolution.alignment.Alignment) Input(beast.core.Input) BranchRateModel(beast.evolution.branchratemodel.BranchRateModel) BufferedReader(java.io.BufferedReader) Tree(beast.evolution.tree.Tree) FileReader(java.io.FileReader) BEASTInterface(beast.core.BEASTInterface) XMLParser(beast.util.XMLParser) File(java.io.File)

Example 55 with Tree

use of beast.evolution.tree.Tree in project beast2 by CompEvol.

the class StateNodeInitialiserListInputEditor method customConnector.

public static boolean customConnector(BeautiDoc doc) {
    // scrub Tree initialisers
    // 0. collect state node info
    List<StateNodeInitialiser> inits = ((MCMC) doc.mcmc.get()).initialisersInput.get();
    State state = ((MCMC) doc.mcmc.get()).startStateInput.get();
    List<StateNode> stateNodes = state.stateNodeInput.get();
    List<Tree> trees = new ArrayList<>();
    for (StateNode s : stateNodes) {
        if (s instanceof Tree) {
            trees.add((Tree) s);
        }
    }
    List<List<StateNode>> initStateNodes = new ArrayList<>();
    for (StateNodeInitialiser init : inits) {
        List<StateNode> initStateNodes0 = new ArrayList<>();
        init.getInitialisedStateNodes(initStateNodes0);
        for (int i = initStateNodes0.size() - 1; i >= 0; i--) {
            if (!(initStateNodes0.get(i) instanceof Tree)) {
                initStateNodes0.remove(i);
            }
        }
        initStateNodes.add(initStateNodes0);
    }
    // 1. remove initialisers that have no stateNode in state
    for (int i = inits.size() - 1; i >= 0; i--) {
        boolean found = false;
        for (StateNode stateNode : initStateNodes.get(i)) {
            if (trees.contains(stateNode)) {
                found = true;
                break;
            }
        }
        if (!found) {
            inits.remove(i);
            initStateNodes.remove(i);
        }
    }
    // 2. remove initialisers that share stateNodes
    for (int i = inits.size() - 1; i >= 0; i--) {
        for (int j = i - 1; j >= 0; j--) {
            boolean found = false;
            for (StateNode stateNode : initStateNodes.get(i)) {
                if (initStateNodes.get(j).contains(stateNode)) {
                    found = true;
                    break;
                }
            }
            if (found) {
                inits.remove(i);
                initStateNodes.remove(i);
            }
        }
    }
    // 3. add RandomTree for those trees not having a stateNodeInitialiser
    boolean[] hasInitialiser = new boolean[trees.size()];
    for (int i = inits.size() - 1; i >= 0; i--) {
        for (StateNode stateNode : initStateNodes.get(i)) {
            int k = trees.indexOf(stateNode);
            if (k >= 0) {
                hasInitialiser[k] = true;
                break;
            }
        }
    }
    for (int i = 0; i < hasInitialiser.length; i++) {
        if (!hasInitialiser[i]) {
            for (BeautiSubTemplate tmp : doc.beautiConfig.subTemplates) {
                if (tmp.getID().equals("RandomTree")) {
                    PartitionContext partition = doc.getContextFor(trees.get(i));
                    Object o = tmp.createSubNet(partition, false);
                    inits.add((StateNodeInitialiser) o);
                }
            }
        }
    }
    return true;
}
Also used : StateNode(beast.core.StateNode) ArrayList(java.util.ArrayList) StateNodeInitialiser(beast.core.StateNodeInitialiser) State(beast.core.State) Tree(beast.evolution.tree.Tree) ArrayList(java.util.ArrayList) List(java.util.List)

Aggregations

Tree (beast.evolution.tree.Tree)70 Alignment (beast.evolution.alignment.Alignment)29 Test (org.junit.Test)26 TreeLikelihood (beast.evolution.likelihood.TreeLikelihood)22 SiteModel (beast.evolution.sitemodel.SiteModel)21 BeagleTreeLikelihood (beast.evolution.likelihood.BeagleTreeLikelihood)19 RealParameter (beast.core.parameter.RealParameter)17 UncertainAlignmentTest (test.beast.evolution.alignment.UncertainAlignmentTest)17 Node (beast.evolution.tree.Node)14 Frequencies (beast.evolution.substitutionmodel.Frequencies)13 ArrayList (java.util.ArrayList)10 TaxonSet (beast.evolution.alignment.TaxonSet)9 RandomTree (beast.evolution.tree.RandomTree)7 ClusterTree (beast.util.ClusterTree)7 ParametricDistribution (beast.math.distributions.ParametricDistribution)6 BEASTInterface (beast.core.BEASTInterface)5 CompoundDistribution (beast.core.util.CompoundDistribution)5 Sequence (beast.evolution.alignment.Sequence)5 Taxon (beast.evolution.alignment.Taxon)5 HKY (beast.evolution.substitutionmodel.HKY)5