Search in sources :

Example 16 with NewickImporter

use of dr.evolution.io.NewickImporter in project beast-mcmc by beast-dev.

the class BetaTreeDiversityStatistic method main.

public static void main(String[] arg) throws IOException, Importer.ImportException {
    Tree tree = (new NewickImporter("((A:1,B:1):1,(C:1, D:1):1);")).importNextTree();
    BetaTreeDiversityStatistic statistic = (BetaTreeDiversityStatistic) BetaTreeDiversityStatistic.FACTORY.createStatistic();
    Taxa taxa = new Taxa();
    taxa.addTaxon(new Taxon("A"));
    taxa.addTaxon(new Taxon("C"));
    statistic.setTaxonList(taxa);
    System.out.println(statistic.getSummaryStatistic(tree)[0]);
}
Also used : Taxa(dr.evolution.util.Taxa) NewickImporter(dr.evolution.io.NewickImporter) Taxon(dr.evolution.util.Taxon) Tree(dr.evolution.tree.Tree)

Example 17 with NewickImporter

use of dr.evolution.io.NewickImporter in project beast-mcmc by beast-dev.

the class BirthDeathSerialSkylineModel method main.

public static void main(String[] args) throws IOException, Importer.ImportException {
    // test framework
    Variable<Double> times = new Variable.D(1, 10);
    Variable<Double> mu = new Variable.D(1, 10);
    for (int i = 0; i < mu.getSize(); i++) {
        times.setValue(i, (i + 1) * 2.0);
        mu.setValue(i, i + 1.0);
    }
    Variable<Double> lambda = new Variable.D(1, 10);
    Variable<Double> psi = new Variable.D(0.5, 1);
    Variable<Double> p = new Variable.D(0.5, 1);
    Variable<Double> origin = new Variable.D(0.5, 1);
    boolean relativeDeath = false;
    boolean sampledIndividualsRemainInfectious = false;
    boolean timesStartFromOrigin = false;
    BirthDeathSerialSkylineModel model = new BirthDeathSerialSkylineModel(times, lambda, mu, psi, p, origin, relativeDeath, sampledIndividualsRemainInfectious, timesStartFromOrigin, Type.SUBSTITUTIONS);
    NewickImporter importer = new NewickImporter("((A:6,B:5):4,(C:3,D:2):1);");
    Tree tree = importer.importNextTree();
    model.calculateTreeLogLikelihood(tree);
    for (int i = 0; i < times.getSize(); i += 1) {
        System.out.println("mu at time " + i + " is " + model.mu(i));
        System.out.println("p0 at time " + i + " is " + model.p0(0, i, i));
    }
}
Also used : NewickImporter(dr.evolution.io.NewickImporter) Tree(dr.evolution.tree.Tree)

Example 18 with NewickImporter

use of dr.evolution.io.NewickImporter in project beast-mcmc by beast-dev.

the class NewickParser method parseXMLObject.

public Object parseXMLObject(XMLObject xo) throws XMLParseException {
    final Units.Type units = XMLUnits.Utils.getUnitsAttr(xo);
    //        boolean usingDates = xo.getAttribute(USING_DATES, true);
    boolean usingDates = true;
    if (xo.hasAttribute(USING_DATES)) {
        usingDates = xo.getAttribute(USING_DATES, true);
    }
    boolean usingHeights = false;
    if (xo.hasAttribute(USING_HEIGHTS)) {
        usingHeights = xo.getAttribute(USING_HEIGHTS, true);
    }
    if (usingDates && usingHeights) {
        throw new XMLParseException("Unable to use both dates and node heights. Specify value of usingDates attribute.");
    }
    //		else if (!usingDates && !usingHeights) {
    //			System.out.println("Tree is assumed to be ultrametric");
    //		}
    StringBuffer buffer = new StringBuffer();
    for (int i = 0; i < xo.getChildCount(); i++) {
        if (xo.getChild(i) instanceof String) {
            buffer.append((String) xo.getChild(i));
        } else {
            throw new XMLParseException("illegal element in newick element");
        }
    }
    java.io.Reader reader = new java.io.StringReader(buffer.toString());
    NewickImporter importer = new NewickImporter(reader);
    FlexibleTree tree;
    try {
        tree = (FlexibleTree) importer.importTree(null);
    } catch (IOException ioe) {
        throw new XMLParseException("error parsing tree in newick element");
    } catch (NewickImporter.BranchMissingException bme) {
        throw new XMLParseException("branch missing in tree in newick element");
    } catch (Importer.ImportException ime) {
        throw new XMLParseException("error parsing tree in newick element - " + ime.getMessage());
    }
    if (tree == null) {
        throw new XMLParseException("Failed to read tree");
    }
    tree.setUnits(units);
    for (int i = 0; i < tree.getTaxonCount(); i++) {
        FlexibleNode node = (FlexibleNode) tree.getExternalNode(i);
        String id = node.getTaxon().getId();
        Taxon taxon = null;
        XMLObject obj = getStore().get(id);
        if (obj != null && obj.getNativeObject() instanceof Taxon) {
            taxon = (Taxon) obj.getNativeObject();
        }
        if (taxon != null) {
            node.setTaxon(taxon);
        } else {
            throw new XMLParseException("unknown taxon, " + id + ", in newick tree");
        }
    }
    if (usingDates) {
        for (int i = 0; i < tree.getTaxonCount(); i++) {
            NodeRef node = tree.getExternalNode(i);
            dr.evolution.util.Date date = (dr.evolution.util.Date) tree.getTaxonAttribute(i, dr.evolution.util.Date.DATE);
            if (date == null) {
                date = (dr.evolution.util.Date) tree.getNodeAttribute(tree.getExternalNode(i), dr.evolution.util.Date.DATE);
            }
            double height = 0.0;
            double nodeHeight = tree.getNodeHeight(node);
            if (date != null) {
                height = Taxon.getHeightFromDate(date);
            }
            if (Math.abs(nodeHeight - height) > 1e-5) {
                System.out.println("  Changing height of node " + tree.getTaxon(node.getNumber()) + " from " + nodeHeight + " to " + height);
                tree.setNodeHeight(node, height);
            }
        }
        for (int i = 0; i < tree.getInternalNodeCount(); i++) {
            dr.evolution.util.Date date = (dr.evolution.util.Date) tree.getNodeAttribute(tree.getInternalNode(i), dr.evolution.util.Date.DATE);
            if (date != null) {
                double height = Taxon.getHeightFromDate(date);
                tree.setNodeHeight(tree.getInternalNode(i), height);
            }
        }
        // END: i loop
        MutableTree.Utils.correctHeightsForTips(tree);
    } else if (!usingDates && !usingHeights) {
        System.out.println("Tree is assumed to be ultrametric");
        // not using dates or heights
        for (int i = 0; i < tree.getTaxonCount(); i++) {
            final NodeRef leaf = tree.getExternalNode(i);
            final double h = tree.getNodeHeight(leaf);
            if (h != 0.0) {
                double zero = 0.0;
                System.out.println("  Changing height of leaf node " + tree.getTaxon(leaf.getNumber()) + " from " + h + " to " + zero);
                tree.setNodeHeight(leaf, zero);
            }
        }
    // END: i loop
    } else {
        System.out.println("Using node heights.");
    }
    if (xo.hasAttribute(RESCALE_HEIGHT)) {
        double rescaleHeight = xo.getDoubleAttribute(RESCALE_HEIGHT);
        double scale = rescaleHeight / tree.getNodeHeight(tree.getRoot());
        for (int i = 0; i < tree.getInternalNodeCount(); i++) {
            NodeRef n = tree.getInternalNode(i);
            tree.setNodeHeight(n, tree.getNodeHeight(n) * scale);
        }
    }
    if (xo.hasAttribute(RESCALE_LENGTH)) {
        double rescaleLength = xo.getDoubleAttribute(RESCALE_LENGTH);
        double scale = rescaleLength / TreeUtils.getTreeLength(tree, tree.getRoot());
        for (int i = 0; i < tree.getInternalNodeCount(); i++) {
            NodeRef n = tree.getInternalNode(i);
            tree.setNodeHeight(n, tree.getNodeHeight(n) * scale);
        }
    }
    //System.out.println("Constructed newick tree = " + Tree.Utils.uniqueNewick(tree, tree.getRoot()));
    return tree;
}
Also used : NewickImporter(dr.evolution.io.NewickImporter) Importer(dr.evolution.io.Importer) NewickImporter(dr.evolution.io.NewickImporter) Taxon(dr.evolution.util.Taxon) IOException(java.io.IOException) Units(dr.evolution.util.Units) XMLUnits(dr.evoxml.util.XMLUnits)

Example 19 with NewickImporter

use of dr.evolution.io.NewickImporter in project beast-mcmc by beast-dev.

the class TimeSlicer method readAndAnalyzeTrees.

//    private List<Tree> importTrees(String treeFileName, int burnin) throws IOException, Importer.ImportException {
//
//        int totalTrees = 10000;
//
//        progressStream.println("Reading trees (bar assumes 10,000 trees)...");
//        progressStream.println("0              25             50             75            100");
//        progressStream.println("|--------------|--------------|--------------|--------------|");
//
//        int stepSize = totalTrees / 60;
//        if (stepSize < 1) stepSize = 1;
//
//        List<Tree> treeList = new ArrayList<Tree>();
//        BufferedReader reader1 = new BufferedReader(new FileReader(treeFileName));
//
//        String line1 = reader1.readLine();
//        TreeImporter importer1;
//        if (line1.toUpperCase().startsWith("#NEXUS")) {
//            importer1 = new NexusImporter(new FileReader(treeFileName));
//        } else {
//            importer1 = new NewickImporter(new FileReader(treeFileName));
//        }
//        totalTrees = 0;
//        while (importer1.hasTree()) {
//            Tree treeTime = importer1.importNextTree();
//
//            if (totalTrees > burnin)
//                treeList.add(treeTime);
//
//            if (totalTrees > 0 && totalTrees % stepSize == 0) {
//                progressStream.print("*");
//                progressStream.flush();
//            }
//            totalTrees++;
//        }
//        return treeList;
//    }
private void readAndAnalyzeTrees(String treeFileName, int burnin, int skipEvery, String[] traits, double[] slices, boolean impute, boolean trueNoise, Normalization normalize, boolean divideByBranchLength, BranchSet branchset, Set taxaSet) throws IOException, Importer.ImportException {
    int totalTrees = 10000;
    int totalStars = 0;
    progressStream.println("Reading and analyzing trees (bar assumes 10,000 trees)...");
    progressStream.println("0              25             50             75            100");
    progressStream.println("|--------------|--------------|--------------|--------------|");
    int stepSize = totalTrees / 60;
    if (stepSize < 1)
        stepSize = 1;
    BufferedReader reader1 = new BufferedReader(new FileReader(treeFileName));
    String line1 = reader1.readLine();
    TreeImporter importer1;
    if (line1.toUpperCase().startsWith("#NEXUS")) {
        importer1 = new NexusImporter(new FileReader(treeFileName));
    } else {
        importer1 = new NewickImporter(new FileReader(treeFileName));
    }
    totalTrees = 0;
    while (importer1.hasTree()) {
        Tree treeTime = importer1.importNextTree();
        if (totalTrees % skipEvery == 0) {
            treesRead++;
            if (totalTrees >= burnin) {
                analyzeTree(treeTime, traits, slices, impute, trueNoise, normalize, divideByBranchLength, branchset, taxaSet);
            }
        }
        if (totalTrees > 0 && totalTrees % stepSize == 0) {
            progressStream.print("*");
            totalStars++;
            if (totalStars % 61 == 0)
                progressStream.print("\n");
            progressStream.flush();
        }
        totalTrees++;
    }
    progressStream.print("\n");
}
Also used : NexusImporter(dr.evolution.io.NexusImporter) NewickImporter(dr.evolution.io.NewickImporter) TreeImporter(dr.evolution.io.TreeImporter) Tree(dr.evolution.tree.Tree)

Example 20 with NewickImporter

use of dr.evolution.io.NewickImporter in project beast-mcmc by beast-dev.

the class TraceCorrelationAssert method createSpecifiedTree.

protected void createSpecifiedTree(String t) throws Exception {
    //        Tree.Utils.newick(tree)
    //create tree
    NewickImporter importer = new NewickImporter(t);
    Tree tree = importer.importTree(null);
    //treeModel
    treeModel = new TreeModel(tree);
}
Also used : TreeModel(dr.evomodel.tree.TreeModel) NewickImporter(dr.evolution.io.NewickImporter) SimpleTree(dr.evolution.tree.SimpleTree) Tree(dr.evolution.tree.Tree)

Aggregations

NewickImporter (dr.evolution.io.NewickImporter)53 Tree (dr.evolution.tree.Tree)32 TreeModel (dr.evomodel.tree.TreeModel)21 ArrayList (java.util.ArrayList)13 Parameter (dr.inference.model.Parameter)12 BranchRateModel (dr.evomodel.branchratemodel.BranchRateModel)11 IOException (java.io.IOException)10 BeagleSequenceSimulator (dr.app.beagle.tools.BeagleSequenceSimulator)9 Partition (dr.app.beagle.tools.Partition)9 HomogeneousBranchModel (dr.evomodel.branchmodel.HomogeneousBranchModel)9 DefaultBranchRateModel (dr.evomodel.branchratemodel.DefaultBranchRateModel)9 GammaSiteRateModel (dr.evomodel.siteratemodel.GammaSiteRateModel)9 FrequencyModel (dr.evomodel.substmodel.FrequencyModel)9 ImportException (dr.evolution.io.Importer.ImportException)8 NexusImporter (dr.evolution.io.NexusImporter)8 Importer (dr.evolution.io.Importer)7 Taxon (dr.evolution.util.Taxon)7 Taxa (dr.evolution.util.Taxa)6 HKY (dr.evomodel.substmodel.nucleotide.HKY)6 TreeImporter (dr.evolution.io.TreeImporter)5