Search in sources :

Example 16 with FlexibleTree

use of dr.evolution.tree.FlexibleTree in project beast-mcmc by beast-dev.

the class NormaliseMeanTreeRate method analyze.

/**
     * Normalises individual trees to the mean rate
     *
     * @param tree                tree to normalise
     * @param normaliseMeanRateTo rate to normalise to
     *          if the trace file is in the wrong format or corrupted
     */
public static void analyze(Tree tree, double normaliseMeanRateTo) {
    double treeRate = 0;
    double treeTime = 0;
    for (int i = 0; i < tree.getNodeCount(); i++) {
        NodeRef node = tree.getNode(i);
        if (tree.getClass().getName().equals("dr.evomodel.tree.TreeModel")) {
            throw new RuntimeException("Does not currently handle TreeModel");
        }
        if (!tree.isRoot(node)) {
            if (tree.getNodeAttribute(node, "rate") == null) {
                System.out.println("Tree file does not contain rate information. ");
                System.setOut(System.out);
                System.err.println("Tree file does not contain rate information. Program terminated");
                System.exit(0);
            }
            treeRate += tree.getNodeRate(node) * tree.getBranchLength(node);
            treeTime += tree.getBranchLength(node);
        }
    }
    treeRate /= treeTime;
    /* Normalise the rates here */
    FlexibleTree modifiedTree = (FlexibleTree) tree;
    for (int i = 0; i < modifiedTree.getNodeCount(); i++) {
        NodeRef node = modifiedTree.getNode(i);
        if (!modifiedTree.isRoot(node)) {
            double nodeRate = normaliseMeanRateTo * modifiedTree.getNodeRate(node) / treeRate;
            modifiedTree.setNodeAttribute(node, "rate", Double.valueOf(nodeRate));
            double nodeTime = modifiedTree.getBranchLength(node);
            nodeTime = nodeTime * treeRate / normaliseMeanRateTo;
            modifiedTree.setBranchLength(node, nodeTime);
        }
    }
}
Also used : NodeRef(dr.evolution.tree.NodeRef) FlexibleTree(dr.evolution.tree.FlexibleTree)

Example 17 with FlexibleTree

use of dr.evolution.tree.FlexibleTree in project beast-mcmc by beast-dev.

the class TaxaOriginTrait method main.

/*
    * Arguments:
    * 0: Trait name
    * 1: File name for list of taxaNames of interest
    * 2: File name for trees (output from BranchJumpPlotter)
    * 3: Output file name root
    * */
public static void main(String[] args) {
    try {
        BufferedReader taxonReader = new BufferedReader(new FileReader(args[1]));
        HashSet<String> tempTaxa = new HashSet<String>();
        String line;
        while ((line = taxonReader.readLine()) != null) {
            tempTaxa.add(line);
        }
        String[] taxa = tempTaxa.toArray(new String[tempTaxa.size()]);
        NexusImporter importer = new NexusImporter(new FileReader(args[2]));
        importer.setSuppressWarnings(true);
        ArrayList<FlexibleTree> tempTrees = new ArrayList<FlexibleTree>();
        int count = 0;
        while (importer.hasTree()) {
            if (count % 100 == 0) {
                System.out.println("Loaded " + count + " trees");
            }
            tempTrees.add((FlexibleTree) importer.importNextTree());
            count++;
        }
        FlexibleTree[] trees = tempTrees.toArray(new FlexibleTree[tempTrees.size()]);
        TaxaOriginTrait examiner = new TaxaOriginTrait(taxa, trees, args[0], args[3]);
        examiner.tabulateOrigins();
    } catch (IOException e) {
        System.out.println("Failed to read files");
    } catch (Importer.ImportException e) {
        System.out.println("Failed to import trees");
    }
}
Also used : NexusImporter(dr.evolution.io.NexusImporter) ArrayList(java.util.ArrayList) FlexibleTree(dr.evolution.tree.FlexibleTree) HashSet(java.util.HashSet) NexusImporter(dr.evolution.io.NexusImporter) Importer(dr.evolution.io.Importer)

Example 18 with FlexibleTree

use of dr.evolution.tree.FlexibleTree in project beast-mcmc by beast-dev.

the class NexusImporter method readNextTree.

private Tree readNextTree(HashMap<String, Taxon> translationList, String[] lastToken, TaxonList taxonList) throws ImportException, IOException {
    try {
        Tree tree = null;
        String token = lastToken[0];
        if (token.equalsIgnoreCase("UTREE") || token.equalsIgnoreCase("TREE")) {
            if (nextCharacter() == '*') {
                // Star is used to specify a default tree - ignore it
                readCharacter();
            }
            String token2 = readToken("=;");
            // Save tree comment and attach it later
            final String comment = getLastMetaComment();
            clearLastMetaComment();
            if (getLastDelimiter() != '=') {
                throw new BadFormatException("Missing label for tree'" + token2 + "' or missing '=' in TREE command of TREES block");
            }
            try {
                if (nextCharacter() != '(') {
                    throw new BadFormatException("Missing tree definition in TREE command of TREES block");
                }
                // tree special comments
                final String scomment = getLastMetaComment();
                clearLastMetaComment();
                FlexibleNode root = readInternalNode(translationList);
                if (translationList != null) {
                    // this ensures that if a translation list is used, the external node numbers
                    // of the trees correspond as well.
                    Map<Taxon, Integer> taxonNumberMap = new HashMap<Taxon, Integer>();
                    int count = 0;
                    for (String label : translationList.keySet()) {
                        Taxon taxon = translationList.get(label);
                        int number;
                        if (taxonList != null) {
                            // Map back to original numbering from TaxonList
                            number = taxonList.getTaxonIndex(taxon);
                        } else {
                            // Old functionality
                            try {
                                number = Integer.parseInt(label) - 1;
                            } catch (NumberFormatException nfe) {
                                number = count;
                            }
                        }
                        taxonNumberMap.put(taxon, number);
                        count++;
                    }
                    tree = new FlexibleTree(root, false, true, taxonNumberMap);
                } else {
                    tree = new FlexibleTree(root, false, true, null);
                }
                tree.setId(token2);
                if (getLastDelimiter() == ':') {
                    // in case the root has a branch length, skip it
                    readToken(";");
                    if (getLastMetaComment() != null) {
                        // \[&label[=value][,label[=value]>[,/..]]\]
                        try {
                            parseMetaCommentPairs(getLastMetaComment(), root);
                        } catch (BadFormatException bfe) {
                        // ignore it
                        }
                        clearLastMetaComment();
                    }
                }
                if (getLastDelimiter() != ';') {
                    throw new BadFormatException("Expecting ';' after tree, '" + token2 + "', TREE command of TREES block");
                }
                if (scomment != null) {
                    // below is correct only if [&W] appears on it own
                    String c = scomment;
                    while (c.length() > 0) {
                        final char ch = c.charAt(0);
                        if (ch == ';') {
                            c = c.substring(1);
                            continue;
                        }
                        if (ch == 'R') {
                            // we only have rooted trees anyway
                            c = c.substring(1);
                        } else if (ch == 'W') {
                            int e = c.indexOf(';');
                            if (e < 0)
                                e = c.length();
                            try {
                                final Float value = new Float(c.substring(2, e));
                                tree.setAttribute("weight", value);
                            } catch (NumberFormatException ex) {
                            // don't fail, ignore
                            }
                            c = c.substring(e);
                        } else {
                            c = c.substring(1);
                        }
                    }
                }
                if (comment != null) {
                    try {
                        parseMetaCommentPairs(comment, tree);
                    } catch (Importer.BadFormatException e) {
                        // set generic comment attribute
                        tree.setAttribute("comment", comment);
                    }
                }
            } catch (EOFException e) {
                // If we reach EOF we may as well return what we have?
                return tree;
            }
            token = readToken(";");
        } else if (token.equalsIgnoreCase("ENDBLOCK") || token.equalsIgnoreCase("END")) {
            return null;
        } else {
            throw new BadFormatException("Unknown command '" + token + "' in TREES block");
        }
        //added this to escape readNextTree loop correctly -- AJD
        lastToken[0] = token;
        return tree;
    } catch (EOFException e) {
        return null;
    }
}
Also used : HashMap(java.util.HashMap) FlexibleTree(dr.evolution.tree.FlexibleTree) FlexibleNode(dr.evolution.tree.FlexibleNode) FlexibleTree(dr.evolution.tree.FlexibleTree) Tree(dr.evolution.tree.Tree)

Example 19 with FlexibleTree

use of dr.evolution.tree.FlexibleTree in project beast-mcmc by beast-dev.

the class TiterImporter method importNextTree.

/**
     * import the next tree.
     * return the tree or null if no more trees are available
     */
public Tree importNextTree() throws IOException, ImportException {
    FlexibleTree tree = null;
    try {
        skipUntil("(");
        unreadCharacter('(');
        FlexibleNode root = readInternalNode(lastTree);
        tree = new FlexibleTree(root, false, true);
    } catch (EOFException e) {
    //
    }
    lastTree = tree;
    return tree;
}
Also used : FlexibleTree(dr.evolution.tree.FlexibleTree) FlexibleNode(dr.evolution.tree.FlexibleNode) EOFException(java.io.EOFException)

Example 20 with FlexibleTree

use of dr.evolution.tree.FlexibleTree in project beast-mcmc by beast-dev.

the class TiterImporter method importTree.

/**
     * importTree.
     */
public Tree importTree(TaxonList taxonList) throws IOException, ImportException {
    setCommentDelimiters('[', ']', '\0', '\0', '&');
    try {
        skipUntil("(");
        unreadCharacter('(');
        final FlexibleNode root = readInternalNode(taxonList);
        if (getLastMetaComment() != null) {
            root.setAttribute(COMMENT, getLastMetaComment());
        }
        return new FlexibleTree(root, false, true);
    } catch (EOFException e) {
        throw new ImportException("incomplete tree");
    }
}
Also used : FlexibleTree(dr.evolution.tree.FlexibleTree) FlexibleNode(dr.evolution.tree.FlexibleNode) EOFException(java.io.EOFException)

Aggregations

FlexibleTree (dr.evolution.tree.FlexibleTree)27 FlexibleNode (dr.evolution.tree.FlexibleNode)12 Tree (dr.evolution.tree.Tree)8 NodeRef (dr.evolution.tree.NodeRef)7 EOFException (java.io.EOFException)6 NexusExporter (dr.app.tools.NexusExporter)5 NewickImporter (dr.evolution.io.NewickImporter)3 TreeModel (dr.evomodel.tree.TreeModel)3 IOException (java.io.IOException)3 PrintStream (java.io.PrintStream)3 ArrayList (java.util.ArrayList)3 Importer (dr.evolution.io.Importer)2 NexusImporter (dr.evolution.io.NexusImporter)2 Regression (dr.stats.Regression)2 HashMap (java.util.HashMap)2 TreeExporter (dr.evolution.io.TreeExporter)1 TreeImporter (dr.evolution.io.TreeImporter)1 MutableTree (dr.evolution.tree.MutableTree)1 ExchangeOperator (dr.evomodel.operators.ExchangeOperator)1 ImportancePruneAndRegraft (dr.evomodel.operators.ImportancePruneAndRegraft)1