Search in sources :

Example 41 with Taxon

use of dr.evolution.util.Taxon in project beast-mcmc by beast-dev.

the class TransmissionLikelihood method setupIntervals.

private int setupIntervals(NodeRef node) throws IncompatibleException {
    double height = virusTree.getNodeHeight(node);
    int host;
    if (virusTree.isExternal(node)) {
        Taxon hostTaxon = (Taxon) virusTree.getTaxonAttribute(node.getNumber(), "host");
        if (transmissionHistoryModel != null) {
            host = transmissionHistoryModel.getHostIndex(hostTaxon);
        } else {
            host = hostTree.getTaxonIndex(hostTaxon);
        }
        intervals[host].addSampleEvent(height);
    } else {
        // Tree should be bifurcating...
        int host1 = setupIntervals(virusTree.getChild(node, 0));
        int host2 = setupIntervals(virusTree.getChild(node, 1));
        while (height > transmissionTime[host1]) {
            double time = transmissionTime[host1];
            intervals[host1].addNothingEvent(time);
            host1 = donorHost[host1];
            intervals[host1].addSampleEvent(time);
        }
        while (height > transmissionTime[host2]) {
            double time = transmissionTime[host2];
            intervals[host2].addNothingEvent(time);
            host2 = donorHost[host2];
            intervals[host2].addSampleEvent(time);
        }
        if (host1 != host2) {
            throw new IncompatibleException("Virus tree is not compatible with transmission history");
        }
        host = host1;
        intervals[host].addCoalescentEvent(height);
    }
    return host;
}
Also used : Taxon(dr.evolution.util.Taxon)

Example 42 with Taxon

use of dr.evolution.util.Taxon 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 43 with Taxon

use of dr.evolution.util.Taxon in project beast-mcmc by beast-dev.

the class UncertainAttributePatternsParser method parseXMLObject.

public Object parseXMLObject(XMLObject xo) throws XMLParseException {
    String attributeName = xo.getStringAttribute(ATTRIBUTE);
    TaxonList taxa = (TaxonList) xo.getChild(TaxonList.class);
    DataType dataType = DataTypeUtils.getDataType(xo);
    if (dataType == null) {
        throw new XMLParseException("dataType expected for attributePatterns element");
    }
    // using a SimpleSiteList rather than Patterns to allow ancestral reconstruction
    UncertainSiteList patterns = new UncertainSiteList(dataType, taxa);
    boolean normalize = xo.getAttribute(NORMALIZE, true);
    if (dataType == null) {
        // TODO Is this necessary given XMLSyntaxRules?
        throw new XMLParseException("dataType expected for attributePatterns element");
    }
    double[][] uncertainPattern = new double[taxa.getTaxonCount()][];
    // Parse attributes
    boolean attributeFound = false;
    for (int i = 0; i < taxa.getTaxonCount(); i++) {
        Taxon taxon = taxa.getTaxon(i);
        Object value = taxon.getAttribute(attributeName);
        if (value != null) {
            attributeFound = true;
            List<StateProbability> stateProbabilities;
            try {
                stateProbabilities = parseStates(value.toString(), dataType);
            } catch (StateParseException e) {
                throw new XMLParseException("State or probability for attribute (" + attributeName + ") in taxon " + taxon.getId() + " is invalid; state = \"" + e.getState() + "\" and probability =\"" + e.getProbability() + "\"");
            }
            uncertainPattern[i] = convertToPartials(stateProbabilities, dataType, normalize);
        } else {
            throw new XMLParseException("State for attribute (" + attributeName + ") in taxon " + taxon.getId() + " is unknown.");
        }
    }
    if (!attributeFound) {
        throw new XMLParseException("The attribute (" + attributeName + ") was missing in all taxa. Check the name of the attribute.");
    }
    patterns.addPattern(uncertainPattern);
    Logger.getLogger("dr.evolution").info("\n ---------------------------------\nCreating an uncertain attribute model for attribute \"" + attributeName + "\"");
    Logger.getLogger("dr.evolution").info("\tIf you publish results using this model, please reference:");
    Logger.getLogger("dr.evolution").info("\t" + Citable.Utils.getCitationString(patterns));
    Logger.getLogger("dr.evolution").info("\n");
    return patterns;
}
Also used : UncertainSiteList(dr.evolution.alignment.UncertainSiteList) TaxonList(dr.evolution.util.TaxonList) Taxon(dr.evolution.util.Taxon) DataType(dr.evolution.datatype.DataType)

Example 44 with Taxon

use of dr.evolution.util.Taxon in project beast-mcmc by beast-dev.

the class SequenceParser method parseXMLObject.

/**
     * @return a sequence object based on the XML element it was passed.
     */
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
    Sequence sequence = new Sequence();
    Taxon taxon = (Taxon) xo.getChild(Taxon.class);
    DataType dataType = null;
    if (xo.hasAttribute(DataType.DATA_TYPE)) {
        String dataTypeStr = xo.getStringAttribute(DataType.DATA_TYPE);
        if (dataTypeStr.equals(Nucleotides.DESCRIPTION)) {
            dataType = Nucleotides.INSTANCE;
        } else if (dataTypeStr.equals(AminoAcids.DESCRIPTION)) {
            dataType = AminoAcids.INSTANCE;
        } else if (dataTypeStr.equals(Codons.DESCRIPTION)) {
            dataType = Codons.UNIVERSAL;
        } else if (dataTypeStr.equals(TwoStates.DESCRIPTION)) {
            dataType = TwoStates.INSTANCE;
        }
    }
    StringBuffer seqBuf = new StringBuffer();
    for (int i = 0; i < xo.getChildCount(); i++) {
        Object child = xo.getChild(i);
        if (child instanceof String) {
            StringTokenizer st = new StringTokenizer((String) child);
            while (st.hasMoreTokens()) {
                seqBuf.append(st.nextToken());
            }
        }
    }
    // We really need to filter the input string to check for illegal characters.
    // Perhaps sequence.setSequenceString could throw an exception if any characters
    // don't fit the dataType.
    String sequenceString = seqBuf.toString();
    if (sequenceString.length() == 0) {
        throw new XMLParseException("Sequence data missing from sequence element!");
    }
    if (dataType != null) {
        sequence.setDataType(dataType);
    }
    sequence.setSequenceString(sequenceString);
    sequence.setTaxon(taxon);
    return sequence;
}
Also used : StringTokenizer(java.util.StringTokenizer) Taxon(dr.evolution.util.Taxon) Sequence(dr.evolution.sequence.Sequence)

Example 45 with Taxon

use of dr.evolution.util.Taxon in project beast-mcmc by beast-dev.

the class HiddenLinkageLikelihood method getLogLikelihood.

public double getLogLikelihood() {
    double logL = 0;
    // first check whether the reads are linked together
    // according to the linkage constraints provided as data in the
    // input file
    ArrayList<LinkedGroup> linkedGroups = hlm.getData().getConstraints();
    for (LinkedGroup lg : linkedGroups) {
        TaxonList tl = lg.getLinkedReads();
        int found = 0;
        for (int l = 0; l < hlm.getLinkageGroupCount(); l++) {
            Set<Taxon> group = hlm.getGroup(l);
            for (int i = 0; i < tl.getTaxonCount(); i++) {
                if (group.contains(tl.getTaxon(i)))
                    found++;
            }
            if (found == tl.getTaxonCount()) {
                logL += Math.log(lg.getLinkageProbability());
                break;
            } else if (found > 0) {
                logL += Math.log(1.0 - lg.getLinkageProbability());
                break;
            }
        }
    }
    // reference tree topology
    if (hlm.getData().getFixedReferenceTree()) {
        // not yet implemented.
        logL += Double.NEGATIVE_INFINITY;
    }
    return logL;
}
Also used : TaxonList(dr.evolution.util.TaxonList) LinkedGroup(dr.evolution.LinkedGroup) Taxon(dr.evolution.util.Taxon)

Aggregations

Taxon (dr.evolution.util.Taxon)151 Taxa (dr.evolution.util.Taxa)31 ArrayList (java.util.ArrayList)24 TaxonList (dr.evolution.util.TaxonList)19 NodeRef (dr.evolution.tree.NodeRef)18 Date (dr.evolution.util.Date)18 Tree (dr.evolution.tree.Tree)15 Sequence (dr.evolution.sequence.Sequence)12 TreeModel (dr.evomodel.tree.TreeModel)12 Parameter (dr.inference.model.Parameter)12 Attribute (dr.util.Attribute)11 SimpleAlignment (dr.evolution.alignment.SimpleAlignment)10 Patterns (dr.evolution.alignment.Patterns)9 NewickImporter (dr.evolution.io.NewickImporter)7 BranchRateModel (dr.evomodel.branchratemodel.BranchRateModel)7 Microsatellite (dr.evolution.datatype.Microsatellite)6 IOException (java.io.IOException)5 HashSet (java.util.HashSet)5 PatternList (dr.evolution.alignment.PatternList)4 DataType (dr.evolution.datatype.DataType)4