Search in sources :

Example 1 with TreeImporter

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

the class Branch2dRateToGrid method readAndAnalyzeTrees.

private void readAndAnalyzeTrees(String treeFileName, int burnin, int skipEvery, String traitString, boolean traitNoise, boolean rateNoise, double maxPathLength, Normalization normalize, boolean getStdev) throws IOException, Importer.ImportException {
    int totalTrees = 10000;
    int totalStars = 0;
    if (!printedBar) {
        progressStream.println("Reading and analyzing trees (bar assumes 10,000 trees)...");
        progressStream.println("0              25             50             75            100");
        progressStream.println("|--------------|--------------|--------------|--------------|");
        printedBar = true;
    }
    if (getStdev) {
        progressStream.println("summarizing standard deviations");
    }
    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, traitString, traitNoise, rateNoise, maxPathLength, normalize, getStdev);
            }
        }
        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 2 with TreeImporter

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

the class BranchRatePlotter method main.

public static void main(String[] args) throws java.io.IOException, Importer.ImportException {
    String controlFile = args[0];
    //String treeFile1 = args[0];
    //String treeFile2 = args[1];
    String targetTreeFile = args[1];
    int burnin = 0;
    if (args.length > 2) {
        burnin = Integer.parseInt(args[2]);
    }
    System.out.println("Ignoring first " + burnin + " trees as burnin.");
    BufferedReader readerTarget = new BufferedReader(new FileReader(targetTreeFile));
    String lineTarget = readerTarget.readLine();
    readerTarget.close();
    TreeImporter targetImporter;
    if (lineTarget.toUpperCase().startsWith("#NEXUS")) {
        targetImporter = new NexusImporter(new FileReader(targetTreeFile));
    } else {
        targetImporter = new NewickImporter(new FileReader(targetTreeFile));
    }
    MutableTree targetTree = new FlexibleTree(targetImporter.importNextTree());
    targetTree = TreeUtils.rotateTreeByComparator(targetTree, TreeUtils.createNodeDensityComparator(targetTree));
    BufferedReader reader = new BufferedReader(new FileReader(controlFile));
    String line = reader.readLine();
    int totalTrees = 0;
    int totalTreesUsed = 0;
    while (line != null) {
        StringTokenizer tokens = new StringTokenizer(line);
        NexusImporter importer1 = new NexusImporter(new FileReader(tokens.nextToken()));
        NexusImporter importer2 = new NexusImporter(new FileReader(tokens.nextToken()));
        int fileTotalTrees = 0;
        while (importer1.hasTree()) {
            Tree timeTree = importer1.importNextTree();
            Tree mutationTree = importer2.importNextTree();
            if (fileTotalTrees >= burnin) {
                annotateRates(targetTree, targetTree.getRoot(), timeTree, mutationTree);
                totalTreesUsed += 1;
            }
            totalTrees += 1;
            fileTotalTrees += 1;
        }
        line = reader.readLine();
    }
    System.out.println("Total trees read: " + totalTrees);
    System.out.println("Total trees summarized: " + totalTreesUsed);
    // collect all rates
    double mutations = 0.0;
    double time = 0.0;
    double[] rates = new double[targetTree.getNodeCount() - 1];
    int index = 0;
    for (int i = 0; i < targetTree.getNodeCount(); i++) {
        NodeRef node = targetTree.getNode(i);
        if (!targetTree.isRoot(node)) {
            Integer count = ((Integer) targetTree.getNodeAttribute(node, "count"));
            if (count == null) {
                throw new RuntimeException("Count missing from node in target tree");
            }
            if (!targetTree.isExternal(node)) {
                double prob = (double) (int) count / (double) (totalTreesUsed);
                if (prob >= 0.5) {
                    String label = "" + (Math.round(prob * 100) / 100.0);
                    targetTree.setNodeAttribute(node, "label", label);
                }
            }
            Number totalMutations = (Number) targetTree.getNodeAttribute(node, "totalMutations");
            Number totalTime = (Number) targetTree.getNodeAttribute(node, "totalTime");
            mutations += totalMutations.doubleValue();
            time += totalTime.doubleValue();
            rates[index] = totalMutations.doubleValue() / totalTime.doubleValue();
            System.out.println(totalMutations.doubleValue() + " / " + totalTime.doubleValue() + " = " + rates[index]);
            targetTree.setNodeRate(node, rates[index]);
            index += 1;
        }
    }
    double minRate = DiscreteStatistics.min(rates);
    double maxRate = DiscreteStatistics.max(rates);
    double medianRate = DiscreteStatistics.median(rates);
    //double topThird = DiscreteStatistics.quantile(2.0/3.0,rates);
    //double bottomThird = DiscreteStatistics.quantile(1.0/3.0,rates);
    //double unweightedMeanRate = DiscreteStatistics.mean(rates);
    double meanRate = mutations / time;
    System.out.println(minRate + "\t" + maxRate + "\t" + medianRate + "\t" + meanRate);
    for (int i = 0; i < targetTree.getNodeCount(); i++) {
        NodeRef node = targetTree.getNode(i);
        if (!targetTree.isRoot(node)) {
            double rate = targetTree.getNodeRate(node);
            //double branchTime = ((Number)targetTree.getNodeAttribute(node, "totalTime")).doubleValue();
            //double branchMutations = ((Number)targetTree.getNodeAttribute(node, "totalMutations")).doubleValue();
            float relativeRate = (float) (rate / maxRate);
            float radius = (float) Math.sqrt(relativeRate * 36.0);
            if (rate > meanRate) {
                targetTree.setNodeAttribute(node, "color", new Color(1.0f, 0.5f, 0.5f));
            } else {
                targetTree.setNodeAttribute(node, "color", new Color(0.5f, 0.5f, 1.0f));
            }
            //targetTree.setNodeAttribute(node, "color", new Color(red, green, blue));
            targetTree.setNodeAttribute(node, "line", new BasicStroke(1.0f));
            targetTree.setNodeAttribute(node, "shape", new java.awt.geom.Ellipse2D.Double(0, 0, radius * 2.0, radius * 2.0));
        }
        java.util.List heightList = (java.util.List) targetTree.getNodeAttribute(node, "heightList");
        if (heightList != null) {
            double[] heights = new double[heightList.size()];
            for (int j = 0; j < heights.length; j++) {
                heights[j] = (Double) heightList.get(j);
            }
            targetTree.setNodeHeight(node, DiscreteStatistics.mean(heights));
            //if (heights.length >= (totalTreesUsed/2)) {
            targetTree.setNodeAttribute(node, "nodeHeight.mean", DiscreteStatistics.mean(heights));
            targetTree.setNodeAttribute(node, "nodeHeight.hpdUpper", DiscreteStatistics.quantile(0.975, heights));
            targetTree.setNodeAttribute(node, "nodeHeight.hpdLower", DiscreteStatistics.quantile(0.025, heights));
        //targetTree.setNodeAttribute(node, "nodeHeight.max", new Double(DiscreteStatistics.max(heights)));
        //targetTree.setNodeAttribute(node, "nodeHeight.min", new Double(DiscreteStatistics.min(heights)));
        //}
        }
    }
    StringBuffer buffer = new StringBuffer();
    writeTree(targetTree, targetTree.getRoot(), buffer, true, false);
    buffer.append(";\n");
    writeTree(targetTree, targetTree.getRoot(), buffer, false, true);
    buffer.append(";\n");
    System.out.println(buffer.toString());
    SquareTreePainter treePainter = new SquareTreePainter();
    treePainter.setColorAttribute("color");
    treePainter.setLineAttribute("line");
    //        treePainter.setShapeAttribute("shape");
    //        treePainter.setLabelAttribute("label");
    JTreeDisplay treeDisplay = new JTreeDisplay(treePainter, targetTree);
    JTreePanel treePanel = new JTreePanel(treeDisplay);
    JFrame frame = new JFrame();
    frame.setSize(800, 600);
    frame.getContentPane().setLayout(new BorderLayout());
    frame.getContentPane().add(treePanel);
    frame.setVisible(true);
    PrinterJob printJob = PrinterJob.getPrinterJob();
    printJob.setPrintable(treeDisplay);
    if (printJob.printDialog()) {
        try {
            printJob.print();
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }
}
Also used : PrinterJob(java.awt.print.PrinterJob) NewickImporter(dr.evolution.io.NewickImporter) JTreeDisplay(dr.app.gui.tree.JTreeDisplay) FileReader(java.io.FileReader) ArrayList(java.util.ArrayList) NexusImporter(dr.evolution.io.NexusImporter) JTreePanel(dr.app.gui.tree.JTreePanel) SquareTreePainter(dr.app.gui.tree.SquareTreePainter) StringTokenizer(java.util.StringTokenizer) BufferedReader(java.io.BufferedReader) TreeImporter(dr.evolution.io.TreeImporter) java.awt(java.awt)

Example 3 with TreeImporter

use of dr.evolution.io.TreeImporter 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 4 with TreeImporter

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

the class NodeStateAnalyser method report.

/**
     * Recursively analyzes trees files.
     *
     * @param name       the file to analyze (if this is a directory then the files within it are analyzed)
     * @param burnin     the burnin to use
     */
private void report(String name, int burnin, double mrsd, double scale) {
    int count = 0;
    Map<String, List<Double>> heightMap = new HashMap<String, List<Double>>();
    Set<String> states = new TreeSet<String>();
    try {
        FileReader fileReader = new FileReader(new File(name));
        TreeImporter importer = new NexusImporter(fileReader);
        while (importer.hasTree()) {
            Tree tree = importer.importNextTree();
            if (count >= burnin) {
                for (int i = 0; i < tree.getInternalNodeCount(); i++) {
                    NodeRef node = tree.getInternalNode(i);
                    Object value = tree.getNodeAttribute(node, "state");
                    if (value != null) {
                        String state = value.toString();
                        List<Double> heights = heightMap.get(state);
                        if (heights == null) {
                            heights = new ArrayList<Double>();
                            heightMap.put(state, heights);
                            states.add(state);
                        }
                        double h = tree.getNodeHeight(node) * scale;
                        if (Double.isNaN(mrsd)) {
                            heights.add(h);
                        } else {
                            heights.add(mrsd - h);
                        }
                    } else {
                        System.out.println("Node missing state");
                    }
                }
            }
            count++;
        }
        boolean first = true;
        int maxCount = 0;
        for (String state : states) {
            if (first) {
                first = false;
            } else {
                System.out.print("\t");
            }
            System.out.print(state);
            List<Double> heights = heightMap.get(state);
            if (heights.size() > maxCount) {
                maxCount = heights.size();
            }
        }
        System.out.println();
        for (int i = 0; i < maxCount; i++) {
            first = true;
            for (String state : states) {
                if (first) {
                    first = false;
                } else {
                    System.out.print("\t");
                }
                List<Double> heights = heightMap.get(state);
                if (i < heights.size()) {
                    System.out.print(heights.get(i));
                }
            }
            System.out.println();
        }
    } catch (Importer.ImportException e) {
        System.err.println("Error Parsing Input Tree: " + e.getMessage());
    } catch (IOException e) {
        System.err.println("Error Parsing Input Tree: " + e.getMessage());
    }
}
Also used : NexusImporter(dr.evolution.io.NexusImporter) NodeRef(dr.evolution.tree.NodeRef) TreeImporter(dr.evolution.io.TreeImporter) Tree(dr.evolution.tree.Tree) NexusImporter(dr.evolution.io.NexusImporter) TreeImporter(dr.evolution.io.TreeImporter) Importer(dr.evolution.io.Importer)

Example 5 with TreeImporter

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

the class TreeSummary method summarizeTrees.

private Tree summarizeTrees(int burnin, Tree consensusTree, CladeSystem cladeSystem, String inputFileName) throws IOException {
    progressStream.println("Analyzing " + totalTreesUsed + " trees...");
    progressStream.println("0              25             50             75            100");
    progressStream.println("|--------------|--------------|--------------|--------------|");
    int stepSize = totalTrees / 60;
    if (stepSize < 1)
        stepSize = 1;
    int counter = 0;
    int bestTreeNumber = 0;
    TreeImporter importer = new NexusImporter(new FileReader(inputFileName));
    try {
        while (importer.hasTree()) {
            Tree tree = importer.importNextTree();
            if (counter >= burnin) {
                cladeSystem.addSubTrees(tree);
            }
            if (counter > 0 && counter % stepSize == 0) {
                progressStream.print("*");
                progressStream.flush();
            }
            counter++;
        }
    } catch (Importer.ImportException e) {
        System.err.println("Error Parsing Input Tree: " + e.getMessage());
        return null;
    }
    Tree bestTree = cladeSystem.getBestTree(consensusTree);
    return bestTree;
}
Also used : NexusImporter(dr.evolution.io.NexusImporter) TreeImporter(dr.evolution.io.TreeImporter) FileReader(java.io.FileReader) NexusImporter(dr.evolution.io.NexusImporter) Importer(dr.evolution.io.Importer) TreeImporter(dr.evolution.io.TreeImporter)

Aggregations

TreeImporter (dr.evolution.io.TreeImporter)12 NexusImporter (dr.evolution.io.NexusImporter)10 Importer (dr.evolution.io.Importer)8 Tree (dr.evolution.tree.Tree)8 NewickImporter (dr.evolution.io.NewickImporter)6 FileReader (java.io.FileReader)3 ArrayList (java.util.ArrayList)2 JTreeDisplay (dr.app.gui.tree.JTreeDisplay)1 JTreePanel (dr.app.gui.tree.JTreePanel)1 SquareTreePainter (dr.app.gui.tree.SquareTreePainter)1 TreeSummaryStatistic (dr.app.treestat.statistics.TreeSummaryStatistic)1 TreeExporter (dr.evolution.io.TreeExporter)1 FlexibleTree (dr.evolution.tree.FlexibleTree)1 NodeRef (dr.evolution.tree.NodeRef)1 GammaSiteModel (dr.oldevomodel.sitemodel.GammaSiteModel)1 SiteModel (dr.oldevomodel.sitemodel.SiteModel)1 FrequencyModel (dr.oldevomodel.substmodel.FrequencyModel)1 HKY (dr.oldevomodel.substmodel.HKY)1 java.awt (java.awt)1 PrinterJob (java.awt.print.PrinterJob)1