Search in sources :

Example 81 with Tree

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

the class BeautiTesterConfig method importFromFile.

public void importFromFile(String fileName, BeautiOptions options, boolean translate) {
    TaxonList taxa = null;
    Alignment alignment = null;
    Tree tree = null;
    PartitionSubstitutionModel model = null;
    java.util.List<NexusApplicationImporter.CharSet> charSets = new ArrayList<NexusApplicationImporter.CharSet>();
    try {
        FileReader reader = new FileReader(fileName);
        NexusApplicationImporter importer = new NexusApplicationImporter(reader);
        boolean done = false;
        while (!done) {
            try {
                NexusImporter.NexusBlock block = importer.findNextBlock();
                if (block == NexusImporter.TAXA_BLOCK) {
                    if (taxa != null) {
                        throw new NexusImporter.MissingBlockException("TAXA block already defined");
                    }
                    taxa = importer.parseTaxaBlock();
                } else if (block == NexusImporter.CALIBRATION_BLOCK) {
                    if (taxa == null) {
                        throw new NexusImporter.MissingBlockException("TAXA or DATA block must be defined before a CALIBRATION block");
                    }
                    importer.parseCalibrationBlock(taxa);
                } else if (block == NexusImporter.CHARACTERS_BLOCK) {
                    if (taxa == null) {
                        throw new NexusImporter.MissingBlockException("TAXA block must be defined before a CHARACTERS block");
                    }
                    if (alignment != null) {
                        throw new NexusImporter.MissingBlockException("CHARACTERS or DATA block already defined");
                    }
                    alignment = importer.parseCharactersBlock(options.taxonList);
                } else if (block == NexusImporter.DATA_BLOCK) {
                    if (alignment != null) {
                        throw new NexusImporter.MissingBlockException("CHARACTERS or DATA block already defined");
                    }
                    // A data block doesn't need a taxon block before it
                    // but if one exists then it will use it.
                    alignment = importer.parseDataBlock(options.taxonList);
                    if (taxa == null) {
                        taxa = alignment;
                    }
                } else if (block == NexusImporter.TREES_BLOCK) {
                    if (taxa == null) {
                        throw new NexusImporter.MissingBlockException("TAXA or DATA block must be defined before a TREES block");
                    }
                    if (tree != null) {
                        throw new NexusImporter.MissingBlockException("TREES block already defined");
                    }
                    Tree[] trees = importer.parseTreesBlock(taxa);
                    if (trees.length > 0) {
                        tree = trees[0];
                    }
                } else if (block == NexusApplicationImporter.PAUP_BLOCK) {
                    model = importer.parsePAUPBlock(options, charSets);
                } else if (block == NexusApplicationImporter.MRBAYES_BLOCK) {
                    model = importer.parseMrBayesBlock(options, charSets);
                } else if (block == NexusApplicationImporter.ASSUMPTIONS_BLOCK) {
                    importer.parseAssumptionsBlock(charSets);
                } else {
                // Ignore the block..
                }
            } catch (EOFException ex) {
                done = true;
            }
        }
        // Allow the user to load taxa only (perhaps from a tree file) so that they can sample from a prior...
        if (alignment == null && taxa == null) {
            throw new NexusImporter.MissingBlockException("TAXON, DATA or CHARACTERS block is missing");
        }
    } catch (FileNotFoundException fnfe) {
        System.err.println("File not found: " + fnfe);
        System.exit(1);
    } catch (Importer.ImportException ime) {
        System.err.println("Error parsing imported file: " + ime);
        System.exit(1);
    } catch (IOException ioex) {
        System.err.println("File I/O Error: " + ioex);
        System.exit(1);
    } catch (Exception ex) {
        System.err.println("Fatal exception: " + ex);
        System.exit(1);
    }
    if (options.taxonList == null) {
        // This is the first partition to be loaded...
        options.taxonList = new Taxa(taxa);
        // check the taxon names for invalid characters
        boolean foundAmp = false;
        for (int i = 0; i < taxa.getTaxonCount(); i++) {
            String name = taxa.getTaxon(i).getId();
            if (name.indexOf('&') >= 0) {
                foundAmp = true;
            }
        }
        if (foundAmp) {
            System.err.println("One or more taxon names include an illegal character ('&').");
            return;
        }
        // make sure they all have dates...
        for (int i = 0; i < taxa.getTaxonCount(); i++) {
            if (taxa.getTaxonAttribute(i, "date") == null) {
                java.util.Date origin = new java.util.Date(0);
                dr.evolution.util.Date date = dr.evolution.util.Date.createTimeSinceOrigin(0.0, Units.Type.YEARS, origin);
                taxa.getTaxon(i).setAttribute("date", date);
            }
        }
    } else {
        // This is an additional partition so check it uses the same taxa
        java.util.List<String> oldTaxa = new ArrayList<String>();
        for (int i = 0; i < options.taxonList.getTaxonCount(); i++) {
            oldTaxa.add(options.taxonList.getTaxon(i).getId());
        }
        java.util.List<String> newTaxa = new ArrayList<String>();
        for (int i = 0; i < taxa.getTaxonCount(); i++) {
            newTaxa.add(taxa.getTaxon(i).getId());
        }
        if (!(oldTaxa.containsAll(newTaxa) && oldTaxa.size() == newTaxa.size())) {
            System.err.println("This file contains different taxa from the previously loaded");
            return;
        }
    }
    String fileNameStem = dr.app.util.Utils.trimExtensions(fileName, new String[] { "NEX", "NEXUS", "TRE", "TREE" });
    if (alignment != null) {
        if (translate) {
            alignment = new ConvertAlignment(AminoAcids.INSTANCE, GeneticCode.UNIVERSAL, alignment);
        }
        java.util.List<PartitionData> partitions = new ArrayList<PartitionData>();
        if (charSets != null && charSets.size() > 0) {
            for (NexusApplicationImporter.CharSet charSet : charSets) {
                partitions.add(new PartitionData(options, charSet.getName(), fileName, new CharSetAlignment(charSet, alignment)));
            }
        } else {
            partitions.add(new PartitionData(options, fileNameStem, fileName, alignment));
        }
        for (PartitionData partition : partitions) {
            if (model != null) {
                partition.setPartitionSubstitutionModel(model);
            //                    options.addPartitionSubstitutionModel(model);
            } else {
                for (PartitionSubstitutionModel pm : options.getPartitionSubstitutionModels()) {
                    if (pm.getDataType() == alignment.getDataType()) {
                        partition.setPartitionSubstitutionModel(pm);
                    }
                }
                if (partition.getPartitionSubstitutionModel() == null) {
                    PartitionSubstitutionModel pm = new PartitionSubstitutionModel(options, partition);
                    partition.setPartitionSubstitutionModel(pm);
                //                        options.addPartitionSubstitutionModel(pm);
                }
            }
            options.dataPartitions.add(partition);
        }
    }
    calculateHeights(options);
}
Also used : ArrayList(java.util.ArrayList) NexusApplicationImporter(dr.app.beauti.util.NexusApplicationImporter) ConvertAlignment(dr.evolution.alignment.ConvertAlignment) CharSetAlignment(dr.evolution.alignment.CharSetAlignment) Alignment(dr.evolution.alignment.Alignment) PartitionData(dr.app.beauti.options.PartitionData) ConvertAlignment(dr.evolution.alignment.ConvertAlignment) Tree(dr.evolution.tree.Tree) PartitionSubstitutionModel(dr.app.beauti.options.PartitionSubstitutionModel) NexusImporter(dr.evolution.io.NexusImporter) NexusApplicationImporter(dr.app.beauti.util.NexusApplicationImporter) Importer(dr.evolution.io.Importer) NexusImporter(dr.evolution.io.NexusImporter) CharSetAlignment(dr.evolution.alignment.CharSetAlignment) dr.evolution.util(dr.evolution.util)

Example 82 with Tree

use of dr.evolution.tree.Tree 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 83 with Tree

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

the class NexusImporter method readTreesBlock.

/**
     * Reads a 'TREES' block.
     */
private Tree[] readTreesBlock(TaxonList taxonList, boolean useTaxonListNumbering) throws ImportException, IOException {
    ArrayList<Tree> trees = new ArrayList<Tree>();
    String[] lastToken = new String[1];
    HashMap<String, Taxon> translationList = readTranslationList(taxonList, lastToken);
    boolean done = false;
    do {
        Tree tree = readNextTree(translationList, lastToken, useTaxonListNumbering ? taxonList : null);
        if (tree != null) {
            trees.add(tree);
        } else {
            done = true;
        }
    } while (!done);
    if (trees.size() == 0) {
        throw new BadFormatException("No trees defined in TREES block");
    }
    Tree[] treeArray = new Tree[trees.size()];
    trees.toArray(treeArray);
    nextBlock = UNKNOWN_BLOCK;
    return treeArray;
}
Also used : ArrayList(java.util.ArrayList) FlexibleTree(dr.evolution.tree.FlexibleTree) Tree(dr.evolution.tree.Tree)

Example 84 with Tree

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

the class MigrateTreeImporter method importTrees.

public Tree[] importTrees(TaxonList taxonList) throws IOException, ImportException {
    Tree[] trees = super.importTrees(taxonList);
    for (Tree tree : trees) {
        // convert toPops to pops
        for (int i = 0; i < tree.getNodeCount(); i++) {
            NodeRef node = tree.getNode(i);
            Object toPop = tree.getNodeAttribute(node, TO_POP);
            Object pop = tree.getNodeAttribute(node, POP);
            if (toPop != null && pop != null && !toPop.equals(pop)) {
                String nodeName = node.getNumber() + "";
                if (tree.isExternal(node)) {
                    nodeName = tree.getTaxonId(node.getNumber());
                }
                if (tree.isRoot(node))
                    nodeName = "root";
                throw new RuntimeException(TO_POP + " = " + toPop + ", " + POP + " = " + pop + " in node " + nodeName);
            }
            if (pop == null && toPop != null) {
                ((MutableTree) tree).setNodeAttribute(node, POP, toPop);
            }
        }
        // convert fromPops to pops
        for (int i = 0; i < tree.getNodeCount(); i++) {
            NodeRef node = tree.getNode(i);
            if (!tree.isRoot(node)) {
                NodeRef parent = tree.getParent(node);
                Object fromPop = tree.getNodeAttribute(node, FROM_POP);
                Object pop = tree.getNodeAttribute(parent, POP);
                if (fromPop != null && pop != null && !fromPop.equals(pop)) {
                    throw new RuntimeException(FROM_POP + " = " + fromPop + ", " + POP + " = " + pop);
                }
                if (pop == null && fromPop != null) {
                    ((MutableTree) tree).setNodeAttribute(parent, POP, fromPop);
                }
            }
        }
        // fill gaps with parent pops
        fillInternalGaps(tree, tree.getRoot());
        fillExternalGaps(tree);
    }
    return trees;
}
Also used : MutableTree(dr.evolution.tree.MutableTree) NodeRef(dr.evolution.tree.NodeRef) Tree(dr.evolution.tree.Tree) MutableTree(dr.evolution.tree.MutableTree)

Example 85 with Tree

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

the class NexusImporter method main.

public static void main(String[] args) throws IOException, ImportException {
    if (args.length > 3) {
        int sampleFrequency = Integer.parseInt(args[1]);
        boolean includeBranchLengths = Boolean.getBoolean(args[2]);
        boolean isNexus = Boolean.getBoolean(args[3]);
        NexusImporter nexusImporter = null;
        BufferedReader reader = null;
        if (isNexus) {
            nexusImporter = new NexusImporter(new FileReader(args[0]));
        } else {
            reader = new BufferedReader(new FileReader(args[0]));
        }
        int index = 0;
        int count = 0;
        String line = null;
        if (!isNexus)
            line = reader.readLine();
        while (line != null || (isNexus && nexusImporter.hasTree())) {
            Tree tree;
            if (isNexus) {
                tree = nexusImporter.importNextTree();
            } else {
                String treeString = line.substring(line.indexOf('(')).trim();
                java.io.Reader stringReader = new java.io.StringReader(treeString);
                NewickImporter importer = new NewickImporter(stringReader);
                tree = importer.importNextTree();
            }
            if (index % sampleFrequency == 0) {
                if (includeBranchLengths) {
                    System.out.println(TreeUtils.newick(tree));
                } else {
                    System.out.println(TreeUtils.newickNoLengths(tree));
                    count += 1;
                }
            }
            index += 1;
            if (!isNexus)
                line = reader.readLine();
        }
        System.out.println(count + " trees");
    } else {
        System.err.println("usage: filterTrees <tree-file-name> <sample-frequency> <include-branch-lengths>");
    }
}
Also used : java.io(java.io) FlexibleTree(dr.evolution.tree.FlexibleTree) Tree(dr.evolution.tree.Tree)

Aggregations

Tree (dr.evolution.tree.Tree)128 NewickImporter (dr.evolution.io.NewickImporter)32 ArrayList (java.util.ArrayList)31 TreeModel (dr.evomodel.tree.TreeModel)26 Parameter (dr.inference.model.Parameter)26 NexusImporter (dr.evolution.io.NexusImporter)18 TaxonList (dr.evolution.util.TaxonList)18 Taxa (dr.evolution.util.Taxa)17 FlexibleTree (dr.evolution.tree.FlexibleTree)16 Taxon (dr.evolution.util.Taxon)15 BranchRateModel (dr.evomodel.branchratemodel.BranchRateModel)15 NodeRef (dr.evolution.tree.NodeRef)14 SimpleTree (dr.evolution.tree.SimpleTree)13 ImportException (dr.evolution.io.Importer.ImportException)12 Importer (dr.evolution.io.Importer)11 DefaultBranchRateModel (dr.evomodel.branchratemodel.DefaultBranchRateModel)11 BeagleSequenceSimulator (dr.app.beagle.tools.BeagleSequenceSimulator)10 Partition (dr.app.beagle.tools.Partition)10 GammaSiteRateModel (dr.evomodel.siteratemodel.GammaSiteRateModel)10 FrequencyModel (dr.evomodel.substmodel.FrequencyModel)9