Search in sources :

Example 6 with TaxonSet

use of beast.evolution.alignment.TaxonSet in project beast2 by CompEvol.

the class RandomTreeTest method testCoalescentTimes.

@Test
public void testCoalescentTimes() throws Exception {
    Randomizer.setSeed(53);
    int Nleaves = 10;
    int Niter = 5000;
    // (Serially sampled) coalescent time means and variances
    // estimated from 50000 trees simulated using MASTER
    double[] coalTimeMeansTruth = { 1.754662, 2.833337, 3.843532, 4.850805, 5.849542, 6.847016, 7.8482, 8.855137, 10.15442 };
    double[] coalTimeVarsTruth = { 0.2751625, 0.2727121, 0.2685172, 0.2705117, 0.2678611, 0.2671793, 0.2686952, 0.2828477, 1.076874 };
    // Assemble BEASTObjects needed by RandomTree
    StringBuilder traitSB = new StringBuilder();
    List<Sequence> seqList = new ArrayList<Sequence>();
    for (int i = 0; i < Nleaves; i++) {
        String taxonID = "t " + i;
        seqList.add(new Sequence(taxonID, "?"));
        if (i > 0)
            traitSB.append(",");
        traitSB.append(taxonID).append("=").append(i);
    }
    Alignment alignment = new Alignment(seqList, "nucleotide");
    TaxonSet taxonSet = new TaxonSet(alignment);
    TraitSet timeTrait = new TraitSet();
    timeTrait.initByName("traitname", "date-backward", "taxa", taxonSet, "value", traitSB.toString());
    ConstantPopulation popFunc = new ConstantPopulation();
    popFunc.initByName("popSize", new RealParameter("1.0"));
    // Create RandomTree and TreeInterval instances
    RandomTree tree = new RandomTree();
    TreeIntervals intervals = new TreeIntervals();
    // Estimate coalescence time moments
    double[] coalTimeMeans = new double[Nleaves - 1];
    double[] coalTimeVars = new double[Nleaves - 1];
    double[] coalTimes = new double[Nleaves - 1];
    for (int i = 0; i < Niter; i++) {
        tree.initByName("taxa", alignment, "populationModel", popFunc, "trait", timeTrait);
        intervals.initByName("tree", tree);
        intervals.getCoalescentTimes(coalTimes);
        for (int j = 0; j < Nleaves - 1; j++) {
            coalTimeMeans[j] += coalTimes[j];
            coalTimeVars[j] += coalTimes[j] * coalTimes[j];
        }
    }
    // Normalise means and variances
    for (int j = 0; j < Nleaves - 1; j++) {
        coalTimeMeans[j] /= Niter;
        coalTimeVars[j] /= Niter;
        coalTimeVars[j] -= coalTimeMeans[j] * coalTimeMeans[j];
    }
    // Test means and variances against independently estimated values
    for (int j = 0; j < Nleaves - 1; j++) {
        assert (relError(coalTimeMeans[j], coalTimeMeansTruth[j]) < 5e-3);
        assert (relError(coalTimeVars[j], coalTimeVarsTruth[j]) < 5e-2);
    }
}
Also used : ArrayList(java.util.ArrayList) RealParameter(beast.core.parameter.RealParameter) Sequence(beast.evolution.alignment.Sequence) TaxonSet(beast.evolution.alignment.TaxonSet) TreeIntervals(beast.evolution.tree.coalescent.TreeIntervals) Alignment(beast.evolution.alignment.Alignment) ConstantPopulation(beast.evolution.tree.coalescent.ConstantPopulation) RandomTree(beast.evolution.tree.RandomTree) TraitSet(beast.evolution.tree.TraitSet) Test(org.junit.Test)

Example 7 with TaxonSet

use of beast.evolution.alignment.TaxonSet in project beast2 by CompEvol.

the class MRCAPriorTest method testMRCATimePrior.

@Test
public void testMRCATimePrior() throws Exception {
    Alignment data = BEASTTestCase.getAlignment();
    TreeParser tree = new TreeParser();
    tree.initByName("taxa", data, "newick", "((human:0.024003,(chimp:0.010772,bonobo:0.010772):0.013231):0.012035," + "(gorilla:0.024003,(orangutan:0.010772,siamang:0.010772):0.013231):0.012035);", "IsLabelledNewick", true);
    Taxon human = new Taxon();
    human.setID("human");
    Taxon bonobo = new Taxon();
    bonobo.setID("bonobo");
    Taxon chimp = new Taxon();
    chimp.setID("chimp");
    Taxon gorilla = new Taxon();
    gorilla.setID("gorilla");
    Taxon orangutan = new Taxon();
    orangutan.setID("orangutan");
    Taxon siamang = new Taxon();
    siamang.setID("siamang");
    MRCAPrior prior = new MRCAPrior();
    TaxonSet set = new TaxonSet();
    set.initByName("taxon", human, "taxon", bonobo, "taxon", chimp);
    Exponential exp = new Exponential();
    /* get distribution for set (human, bonobo, chimp) */
    prior.initByName("tree", tree, "taxonset", set, "monophyletic", true, "distr", exp);
    double logP = prior.calculateLogP();
    assertEquals(-0.024003, logP, BEASTTestCase.PRECISION);
    /* get distribution for set (human, chimp), do not require the set to by monophyletic */
    set = new TaxonSet();
    set.initByName("taxon", human, "taxon", chimp);
    prior.initByName("tree", tree, "taxonset", set, "monophyletic", false);
    logP = prior.calculateLogP();
    assertEquals(-0.024003, logP, BEASTTestCase.PRECISION);
    /* get distribution for set (human, chimp), DO require the set to by monophyletic */
    prior.initByName("tree", tree, "taxonset", set, "monophyletic", true);
    logP = prior.calculateLogP();
    assertEquals(Double.NEGATIVE_INFINITY, logP, 0);
    /* get distribution for set (human, gorilla) = root, not monophyletic */
    set = new TaxonSet();
    set.initByName("taxon", human, "taxon", gorilla);
    prior.initByName("tree", tree, "taxonset", set, "monophyletic", false);
    logP = prior.calculateLogP();
    assertEquals(-0.024003 - 0.012035, logP, BEASTTestCase.PRECISION);
}
Also used : Alignment(beast.evolution.alignment.Alignment) TreeParser(beast.util.TreeParser) Taxon(beast.evolution.alignment.Taxon) MRCAPrior(beast.math.distributions.MRCAPrior) Exponential(beast.math.distributions.Exponential) TaxonSet(beast.evolution.alignment.TaxonSet) Test(org.junit.Test)

Example 8 with TaxonSet

use of beast.evolution.alignment.TaxonSet in project beast2 by CompEvol.

the class MRCAPriorTest method testSingleMonophyleticConstraint.

@Test
public void testSingleMonophyleticConstraint() throws Exception {
    Alignment data = BEASTTestCase.getAlignment();
    TreeParser tree = new TreeParser();
    tree.initByName("taxa", data, "newick", "((human:0.024003,(chimp:0.010772,bonobo:0.010772):0.013231):0.012035," + "(gorilla:0.024003,(orangutan:0.010772,siamang:0.010772):0.013231):0.012035);", "IsLabelledNewick", true);
    Taxon human = new Taxon();
    human.setID("human");
    Taxon bonobo = new Taxon();
    bonobo.setID("bonobo");
    Taxon chimp = new Taxon();
    chimp.setID("chimp");
    Taxon gorilla = new Taxon();
    gorilla.setID("gorilla");
    Taxon orangutan = new Taxon();
    orangutan.setID("orangutan");
    Taxon siamang = new Taxon();
    siamang.setID("siamang");
    MRCAPrior prior = new MRCAPrior();
    /* check (human, bonobo, chimp) is monophyletic **/
    TaxonSet set = new TaxonSet();
    set.initByName("taxon", human, "taxon", bonobo, "taxon", chimp);
    prior.initByName("tree", tree, "taxonset", set, "monophyletic", true);
    double logP = prior.calculateLogP();
    assertEquals(logP, 0, 0);
    /* check (gorilla, siamang) is NOT monophyletic **/
    set = new TaxonSet();
    set.initByName("taxon", gorilla, "taxon", siamang);
    prior.initByName("tree", tree, "taxonset", set, "monophyletic", true);
    logP = prior.calculateLogP();
    assertEquals(logP, Double.NEGATIVE_INFINITY, 0);
    /* check (gorilla, orangutan, siamang) is monophyletic **/
    set = new TaxonSet();
    set.initByName("taxon", gorilla, "taxon", orangutan, "taxon", siamang);
    prior.initByName("tree", tree, "taxonset", set, "monophyletic", true);
    logP = prior.calculateLogP();
    assertEquals(logP, 0, 0);
    /* check (human, gorilla) is NOT monophyletic **/
    set = new TaxonSet();
    set.initByName("taxon", human, "taxon", gorilla);
    prior.initByName("tree", tree, "taxonset", set, "monophyletic", true);
    logP = prior.calculateLogP();
    assertEquals(logP, Double.NEGATIVE_INFINITY, 0);
    set.setID("test");
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PrintStream ps = new PrintStream(baos);
    prior.init(ps);
    String log = new String(baos.toByteArray(), StandardCharsets.UTF_8);
    assertEquals(log, "mrcatime(test)\t");
    baos = new ByteArrayOutputStream();
    ps = new PrintStream(baos);
    prior.initByName("tree", tree, "taxonset", set, "monophyletic", true, "useOriginate", true);
    prior.init(ps);
    log = new String(baos.toByteArray(), StandardCharsets.UTF_8);
    assertEquals(log, "mrcatime(test.originate)\t");
}
Also used : PrintStream(java.io.PrintStream) Alignment(beast.evolution.alignment.Alignment) TreeParser(beast.util.TreeParser) Taxon(beast.evolution.alignment.Taxon) MRCAPrior(beast.math.distributions.MRCAPrior) ByteArrayOutputStream(java.io.ByteArrayOutputStream) TaxonSet(beast.evolution.alignment.TaxonSet) Test(org.junit.Test)

Example 9 with TaxonSet

use of beast.evolution.alignment.TaxonSet in project beast2 by CompEvol.

the class TaxonSetInputEditor method guessTaxonSets.

/**
 * guesses taxon sets based on pattern in regExp based on the taxa in
 * m_rawData
 */
public int guessTaxonSets(String regexp, int minSize) {
    m_taxonset.clear();
    HashMap<String, TaxonSet> map = new HashMap<>();
    Pattern m_pattern = Pattern.compile(regexp);
    Set<Taxon> taxa = new HashSet<>();
    Set<String> taxonIDs = new HashSet<>();
    for (Alignment alignment : getDoc().alignments) {
        for (String id : alignment.getTaxaNames()) {
            if (!taxonIDs.contains(id)) {
                Taxon taxon = getDoc().getTaxon(id);
                taxa.add(taxon);
                taxonIDs.add(id);
            }
        }
        for (Sequence sequence : alignment.sequenceInput.get()) {
            String id = sequence.taxonInput.get();
            if (!taxonIDs.contains(id)) {
                Taxon taxon = getDoc().getTaxon(sequence.taxonInput.get());
                // ensure sequence and taxon do not get same ID
                if (sequence.getID().equals(sequence.taxonInput.get())) {
                    sequence.setID("_" + sequence.getID());
                }
                taxa.add(taxon);
                taxonIDs.add(id);
            }
        }
    }
    List<String> unknowns = new ArrayList<>();
    for (Taxon taxon : taxa) {
        if (!(taxon instanceof TaxonSet)) {
            Matcher matcher = m_pattern.matcher(taxon.getID());
            String match;
            if (matcher.find()) {
                match = matcher.group(1);
            } else {
                match = "UNKNOWN";
                unknowns.add(taxon.getID());
            }
            try {
                if (map.containsKey(match)) {
                    TaxonSet set = map.get(match);
                    set.taxonsetInput.setValue(taxon, set);
                } else {
                    TaxonSet set = newTaxonSet(match);
                    set.taxonsetInput.setValue(taxon, set);
                    map.put(match, set);
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
    if (unknowns.size() > 0) {
        showMisMatchMessage(unknowns);
    }
    // add taxon sets
    int ignored = 0;
    for (TaxonSet set : map.values()) {
        if (set.taxonsetInput.get().size() > minSize) {
            m_taxonset.add(set);
        } else {
            ignored += set.taxonsetInput.get().size();
        }
    }
    return ignored;
}
Also used : Pattern(java.util.regex.Pattern) HashMap(java.util.HashMap) Matcher(java.util.regex.Matcher) Taxon(beast.evolution.alignment.Taxon) ArrayList(java.util.ArrayList) Sequence(beast.evolution.alignment.Sequence) TaxonSet(beast.evolution.alignment.TaxonSet) PatternSyntaxException(java.util.regex.PatternSyntaxException) FilteredAlignment(beast.evolution.alignment.FilteredAlignment) Alignment(beast.evolution.alignment.Alignment) HashSet(java.util.HashSet)

Example 10 with TaxonSet

use of beast.evolution.alignment.TaxonSet in project beast2 by CompEvol.

the class TaxonSetInputEditor method getContent.

private Component getContent(List<Taxon> taxonset) {
    m_taxonset = taxonset;
    m_taxonMap = new HashMap<>();
    m_lineageset = new ArrayList<>();
    for (Taxon taxonset2 : m_taxonset) {
        if (taxonset2 instanceof TaxonSet) {
            for (Taxon taxon : ((TaxonSet) taxonset2).taxonsetInput.get()) {
                m_lineageset.add(taxon);
                m_taxonMap.put(taxon.getID(), taxonset2.getID());
            }
        }
    }
    // set up table.
    // special features: background shading of rows
    // custom editor allowing only Date column to be edited.
    m_model = new DefaultTableModel();
    m_model.addColumn("Taxon");
    m_model.addColumn("Species/Population");
    taxonSetToModel();
    m_table = new JTable(m_model) {

        private static final long serialVersionUID = 1L;

        // method that induces table row shading
        @Override
        public Component prepareRenderer(TableCellRenderer renderer, int Index_row, int Index_col) {
            Component comp = super.prepareRenderer(renderer, Index_row, Index_col);
            // even index, selected or not selected
            if (isCellSelected(Index_row, Index_col)) {
                comp.setBackground(Color.gray);
            } else if (Index_row % 2 == 0) {
                comp.setBackground(new Color(237, 243, 255));
            } else {
                comp.setBackground(Color.white);
            }
            return comp;
        }
    };
    // set up editor that makes sure only doubles are accepted as entry
    // and only the Date column is editable.
    m_table.setDefaultEditor(Object.class, new TableCellEditor() {

        JTextField m_textField = new JTextField();

        int m_iRow, m_iCol;

        @Override
        public boolean stopCellEditing() {
            m_table.removeEditor();
            String text = m_textField.getText();
            // Log.warning.println(text);
            m_model.setValueAt(text, m_iRow, m_iCol);
            // try {
            // Double.parseDouble(text);
            // } catch (Exception e) {
            // return false;
            // }
            modelToTaxonset();
            return true;
        }

        @Override
        public boolean isCellEditable(EventObject anEvent) {
            return m_table.getSelectedColumn() == 1;
        }

        @Override
        public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int rowNr, int colNr) {
            if (!isSelected) {
                return null;
            }
            m_iRow = rowNr;
            m_iCol = colNr;
            m_textField.setText((String) value);
            return m_textField;
        }

        @Override
        public boolean shouldSelectCell(EventObject anEvent) {
            return false;
        }

        @Override
        public void removeCellEditorListener(CellEditorListener l) {
        }

        @Override
        public Object getCellEditorValue() {
            return null;
        }

        @Override
        public void cancelCellEditing() {
        }

        @Override
        public void addCellEditorListener(CellEditorListener l) {
        }
    });
    m_table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
    m_table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    int size = m_table.getFont().getSize();
    m_table.setRowHeight(20 * size / 13);
    m_table.getColumnModel().getColumn(0).setPreferredWidth(250 * size / 13);
    m_table.getColumnModel().getColumn(1).setPreferredWidth(250 * size / 13);
    JTableHeader header = m_table.getTableHeader();
    header.addMouseListener(new ColumnHeaderListener());
    JScrollPane pane = new JScrollPane(m_table);
    Box tableBox = Box.createHorizontalBox();
    tableBox.add(Box.createHorizontalGlue());
    tableBox.add(pane);
    tableBox.add(Box.createHorizontalGlue());
    Box box = Box.createVerticalBox();
    box.add(createFilterBox());
    box.add(tableBox);
    box.add(createButtonBox());
    return box;
}
Also used : JScrollPane(javax.swing.JScrollPane) TableCellRenderer(javax.swing.table.TableCellRenderer) Taxon(beast.evolution.alignment.Taxon) DefaultTableModel(javax.swing.table.DefaultTableModel) Color(java.awt.Color) JTableHeader(javax.swing.table.JTableHeader) CellEditorListener(javax.swing.event.CellEditorListener) Box(javax.swing.Box) TaxonSet(beast.evolution.alignment.TaxonSet) JTextField(javax.swing.JTextField) EventObject(java.util.EventObject) JTable(javax.swing.JTable) EventObject(java.util.EventObject) TableCellEditor(javax.swing.table.TableCellEditor) Component(java.awt.Component)

Aggregations

TaxonSet (beast.evolution.alignment.TaxonSet)36 Taxon (beast.evolution.alignment.Taxon)19 ArrayList (java.util.ArrayList)13 Alignment (beast.evolution.alignment.Alignment)11 RealParameter (beast.core.parameter.RealParameter)10 Test (org.junit.Test)10 Tree (beast.evolution.tree.Tree)9 ConstantPopulation (beast.evolution.tree.coalescent.ConstantPopulation)8 MRCAPrior (beast.math.distributions.MRCAPrior)8 Locus (bacter.Locus)5 SiteModel (beast.evolution.sitemodel.SiteModel)5 Node (beast.evolution.tree.Node)5 RandomTree (beast.evolution.tree.RandomTree)5 HashMap (java.util.HashMap)4 HashSet (java.util.HashSet)4 List (java.util.List)4 Conversion (bacter.Conversion)3 ConversionGraph (bacter.ConversionGraph)3 BEASTInterface (beast.core.BEASTInterface)3 CompoundDistribution (beast.core.util.CompoundDistribution)3