Search in sources :

Example 1 with State

use of beast.core.State in project beast2 by CompEvol.

the class BeautiBase method assertStateEquals.

void assertStateEquals(String... ids) {
    System.err.println("assertStateEquals");
    State state = (State) doc.pluginmap.get("state");
    List<StateNode> stateNodes = state.stateNodeInput.get();
    asserListsEqual(stateNodes, ids);
}
Also used : State(beast.core.State) StateNode(beast.core.StateNode)

Example 2 with State

use of beast.core.State in project beast2 by CompEvol.

the class RealParameterListTest method test1.

@Test
public void test1() throws Exception {
    RealParameterList parameterList = new RealParameterList();
    // Parameters with which to initialise list
    RealParameter param1 = new RealParameter();
    param1.initByName("value", "2");
    RealParameter param2 = new RealParameter();
    param2.initByName("value", "3");
    // Initialise parameter list
    parameterList.initByName("initialParam", param1, "initialParam", param2);
    // Create dummy state to allow statenode editing
    State state = new State();
    state.initByName("stateNode", parameterList);
    state.initialise();
    // Test parameter value modification
    parameterList.get(0).setValue(20.0);
    // Test parameter creation and modification
    Parameter<Double> newParam = parameterList.addNewParam();
    newParam.setValue(53.0);
    assertEquals(parameterList.get(0).getValue(), 20.0, 1e-15);
    assertEquals(parameterList.get(0).getKey(), 0);
    assertEquals(parameterList.get(1).getValue(), 3.0, 1e-15);
    assertEquals(parameterList.get(1).getKey(), 1);
    assertEquals(parameterList.get(2).getValue(), 53.0, 1e-15);
    assertEquals(parameterList.get(2).getKey(), 2);
    assertEquals(parameterList.size(), 3);
    parameterList.remove(1);
    newParam = parameterList.addNewParam();
    newParam.setValue(42.0);
    assertEquals(parameterList.get(0).getValue(), 20.0, 1e-15);
    assertEquals(parameterList.get(0).getKey(), 0, 1e-15);
    assertEquals(parameterList.get(1).getValue(), 53.0, 1e-15);
    assertEquals(parameterList.get(1).getKey(), 2, 1e-15);
    assertEquals(parameterList.get(2).getValue(), 42.0, 1e-15);
    assertEquals(parameterList.get(2).getKey(), 1);
    assertEquals(parameterList.size(), 3);
    // Test state restore
    parameterList.restore();
    assertEquals(parameterList.get(0).getValue(), 2.0, 1e-15);
    assertEquals(parameterList.get(0).getKey(), 0);
    assertEquals(parameterList.get(1).getValue(), 3.0, 1e-15);
    assertEquals(parameterList.get(1).getKey(), 1);
    assertEquals(parameterList.size(), 2);
    // Test serialization
    String xmlStr = parameterList.toXML();
    assertEquals(xmlStr, "<statenode id='null'>" + "Dimension: [1, 1], " + "Bounds: [-Infinity,Infinity], " + "AvailableKeys: [], NextKey: 2, " + "Parameters: [[2.0],[3.0]], " + "ParameterKeys: [0,1]" + "</statenode>\n");
    // Test deserialization
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    Document doc = factory.newDocumentBuilder().parse(new ByteArrayInputStream(xmlStr.getBytes()));
    doc.normalize();
    NodeList nodes = doc.getElementsByTagName("*");
    org.w3c.dom.Node docNode = nodes.item(0);
    RealParameterList newParameterList = new RealParameterList();
    newParameterList.initAndValidate();
    newParameterList.fromXML(docNode);
    assertEquals(newParameterList.get(0).getValue(), 2.0, 1e-15);
    assertEquals(newParameterList.get(0).getKey(), 0);
    assertEquals(newParameterList.get(1).getValue(), 3.0, 1e-15);
    assertEquals(newParameterList.get(1).getKey(), 1);
    assertEquals(newParameterList.size(), 2);
}
Also used : RealParameterList(beast.core.parameter.RealParameterList) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) NodeList(org.w3c.dom.NodeList) RealParameter(beast.core.parameter.RealParameter) Document(org.w3c.dom.Document) ByteArrayInputStream(java.io.ByteArrayInputStream) State(beast.core.State) Test(org.junit.Test)

Example 3 with State

use of beast.core.State in project beast2 by CompEvol.

the class TestOperator method register.

public static void register(Operator operator, final Object... operands) {
    HashMap<String, StateNode> operandsMap;
    operandsMap = new HashMap<String, StateNode>();
    if (operands.length % 2 == 1) {
        throw new RuntimeException("Expected even number of arguments, name-value pairs");
    }
    for (int i = 0; i < operands.length; i += 2) {
        if (operands[i] instanceof String) {
            final String name = (String) operands[i];
            if (operands[i + 1] instanceof StateNode) {
                final StateNode node = (StateNode) operands[i + 1];
                operandsMap.put(name, node);
            } else {
                throw new IllegalArgumentException("Expected a StateNode in " + (i + 1) + "th argument ");
            }
        } else {
            throw new IllegalArgumentException("Expected a String in " + i + "th argument ");
        }
    }
    State state = new State();
    state.initByName("stateNode", new ArrayList<StateNode>(operandsMap.values()));
    state.initialise();
    Object[] operandsAndWeight = new Object[operands.length + 2];
    for (int i = 0; i < operands.length; ++i) {
        operandsAndWeight[i] = operands[i];
    }
    operandsAndWeight[operands.length] = "weight";
    operandsAndWeight[operands.length + 1] = "1";
    operator.initByName(operandsAndWeight);
    operator.validateInputs();
}
Also used : State(beast.core.State) StateNode(beast.core.StateNode)

Example 4 with State

use of beast.core.State in project beast2 by CompEvol.

the class AlignmentListInputEditor method updateModel.

/**
 * set partition of type columnNr to partition model nr rowNr *
 */
void updateModel(int columnNr, int rowNr) {
    Log.warning.println("updateModel: " + rowNr + " " + columnNr + " " + table.getSelectedRow() + " " + table.getSelectedColumn());
    for (int i = 0; i < partitionCount; i++) {
        Log.warning.println(i + " " + tableData[i][0] + " " + tableData[i][SITEMODEL_COLUMN] + " " + tableData[i][CLOCKMODEL_COLUMN] + " " + tableData[i][TREE_COLUMN]);
    }
    getDoc();
    String partition = (String) tableData[rowNr][columnNr];
    // check if partition needs renaming
    String oldName = null;
    boolean isRenaming = false;
    try {
        switch(columnNr) {
            case SITEMODEL_COLUMN:
                if (!doc.pluginmap.containsKey("SiteModel.s:" + partition)) {
                    String id = ((BEASTInterface) likelihoods[rowNr].siteModelInput.get()).getID();
                    oldName = BeautiDoc.parsePartition(id);
                    doc.renamePartition(BeautiDoc.SITEMODEL_PARTITION, oldName, partition);
                    isRenaming = true;
                }
                break;
            case CLOCKMODEL_COLUMN:
                {
                    String id = likelihoods[rowNr].branchRateModelInput.get().getID();
                    String clockModelName = id.substring(0, id.indexOf('.')) + ".c:" + partition;
                    if (!doc.pluginmap.containsKey(clockModelName)) {
                        oldName = BeautiDoc.parsePartition(id);
                        doc.renamePartition(BeautiDoc.CLOCKMODEL_PARTITION, oldName, partition);
                        isRenaming = true;
                    }
                }
                break;
            case TREE_COLUMN:
                if (!doc.pluginmap.containsKey("Tree.t:" + partition)) {
                    String id = likelihoods[rowNr].treeInput.get().getID();
                    oldName = BeautiDoc.parsePartition(id);
                    doc.renamePartition(BeautiDoc.TREEMODEL_PARTITION, oldName, partition);
                    isRenaming = true;
                }
                break;
        }
    } catch (Exception e) {
        JOptionPane.showMessageDialog(this, "Cannot rename item: " + e.getMessage());
        tableData[rowNr][columnNr] = oldName;
        return;
    }
    if (isRenaming) {
        doc.determinePartitions();
        initTableData();
        setUpComboBoxes();
        table.repaint();
        return;
    }
    int partitionID = BeautiDoc.ALIGNMENT_PARTITION;
    switch(columnNr) {
        case SITEMODEL_COLUMN:
            partitionID = BeautiDoc.SITEMODEL_PARTITION;
            break;
        case CLOCKMODEL_COLUMN:
            partitionID = BeautiDoc.CLOCKMODEL_PARTITION;
            break;
        case TREE_COLUMN:
            partitionID = BeautiDoc.TREEMODEL_PARTITION;
            break;
    }
    int partitionNr = doc.getPartitionNr(partition, partitionID);
    GenericTreeLikelihood treeLikelihood = null;
    if (partitionNr >= 0) {
        // we ar linking
        treeLikelihood = likelihoods[partitionNr];
    }
    // (TreeLikelihood) doc.pluginmap.get("treeLikelihood." +
    // tableData[rowNr][NAME_COLUMN]);
    boolean needsRePartition = false;
    PartitionContext oldContext = new PartitionContext(this.likelihoods[rowNr]);
    switch(columnNr) {
        case SITEMODEL_COLUMN:
            {
                SiteModelInterface siteModel = null;
                if (treeLikelihood != null) {
                    // getDoc().getPartitionNr(partition,
                    // BeautiDoc.SITEMODEL_PARTITION) !=
                    // rowNr) {
                    siteModel = treeLikelihood.siteModelInput.get();
                } else {
                    siteModel = (SiteModel) doc.pluginmap.get("SiteModel.s:" + partition);
                    if (siteModel != likelihoods[rowNr].siteModelInput.get()) {
                        PartitionContext context = getPartitionContext(rowNr);
                        try {
                            siteModel = (SiteModel.Base) BeautiDoc.deepCopyPlugin((BEASTInterface) likelihoods[rowNr].siteModelInput.get(), likelihoods[rowNr], (MCMC) doc.mcmc.get(), oldContext, context, doc, null);
                        } catch (RuntimeException e) {
                            JOptionPane.showMessageDialog(this, "Could not clone site model: " + e.getMessage());
                            return;
                        }
                    }
                }
                SiteModelInterface target = this.likelihoods[rowNr].siteModelInput.get();
                if (target instanceof SiteModel.Base && siteModel instanceof SiteModel.Base) {
                    if (!((SiteModel.Base) target).substModelInput.canSetValue(((SiteModel.Base) siteModel).substModelInput.get(), (SiteModel.Base) target)) {
                        throw new IllegalArgumentException("Cannot link site model: substitution models (" + ((SiteModel.Base) target).substModelInput.get().getClass().toString() + " and " + ((SiteModel.Base) siteModel).substModelInput.get().getClass().toString() + ") are incompatible");
                    }
                } else {
                    throw new IllegalArgumentException("Don't know how to link this site model");
                }
                needsRePartition = (this.likelihoods[rowNr].siteModelInput.get() != siteModel);
                this.likelihoods[rowNr].siteModelInput.setValue(siteModel, this.likelihoods[rowNr]);
                partition = ((BEASTInterface) likelihoods[rowNr].siteModelInput.get()).getID();
                partition = BeautiDoc.parsePartition(partition);
                getDoc().setCurrentPartition(BeautiDoc.SITEMODEL_PARTITION, rowNr, partition);
            }
            break;
        case CLOCKMODEL_COLUMN:
            {
                BranchRateModel clockModel = null;
                if (treeLikelihood != null) {
                    // getDoc().getPartitionNr(partition,
                    // BeautiDoc.CLOCKMODEL_PARTITION)
                    // != rowNr) {
                    clockModel = treeLikelihood.branchRateModelInput.get();
                } else {
                    clockModel = getDoc().getClockModel(partition);
                    if (clockModel != likelihoods[rowNr].branchRateModelInput.get()) {
                        PartitionContext context = getPartitionContext(rowNr);
                        try {
                            clockModel = (BranchRateModel) BeautiDoc.deepCopyPlugin(likelihoods[rowNr].branchRateModelInput.get(), likelihoods[rowNr], (MCMC) doc.mcmc.get(), oldContext, context, doc, null);
                        } catch (RuntimeException e) {
                            JOptionPane.showMessageDialog(this, "Could not clone clock model: " + e.getMessage());
                            return;
                        }
                    }
                }
                // make sure that *if* the clock model has a tree as input, it is
                // the same as
                // for the likelihood
                TreeInterface tree = null;
                for (Input<?> input : ((BEASTInterface) clockModel).listInputs()) {
                    if (input.getName().equals("tree")) {
                        tree = (TreeInterface) input.get();
                    }
                }
                if (tree != null && tree != this.likelihoods[rowNr].treeInput.get()) {
                    JOptionPane.showMessageDialog(this, "Cannot link clock model with different trees");
                    throw new IllegalArgumentException("Cannot link clock model with different trees");
                }
                needsRePartition = (this.likelihoods[rowNr].branchRateModelInput.get() != clockModel);
                this.likelihoods[rowNr].branchRateModelInput.setValue(clockModel, this.likelihoods[rowNr]);
                partition = likelihoods[rowNr].branchRateModelInput.get().getID();
                partition = BeautiDoc.parsePartition(partition);
                getDoc().setCurrentPartition(BeautiDoc.CLOCKMODEL_PARTITION, rowNr, partition);
            }
            break;
        case TREE_COLUMN:
            {
                TreeInterface tree = null;
                if (treeLikelihood != null) {
                    // getDoc().getPartitionNr(partition,
                    // BeautiDoc.TREEMODEL_PARTITION) !=
                    // rowNr) {
                    tree = treeLikelihood.treeInput.get();
                } else {
                    tree = (TreeInterface) doc.pluginmap.get("Tree.t:" + partition);
                    if (tree != likelihoods[rowNr].treeInput.get()) {
                        PartitionContext context = getPartitionContext(rowNr);
                        try {
                            tree = (TreeInterface) BeautiDoc.deepCopyPlugin((BEASTInterface) likelihoods[rowNr].treeInput.get(), likelihoods[rowNr], (MCMC) doc.mcmc.get(), oldContext, context, doc, null);
                        } catch (RuntimeException e) {
                            JOptionPane.showMessageDialog(this, "Could not clone tree model: " + e.getMessage());
                            return;
                        }
                        State state = ((MCMC) doc.mcmc.get()).startStateInput.get();
                        List<StateNode> stateNodes = new ArrayList<>();
                        stateNodes.addAll(state.stateNodeInput.get());
                        for (StateNode s : stateNodes) {
                            if (s.getID().endsWith(".t:" + oldContext.tree) && !(s instanceof TreeInterface)) {
                                try {
                                    @SuppressWarnings("unused") StateNode copy = (StateNode) BeautiDoc.deepCopyPlugin(s, likelihoods[rowNr], (MCMC) doc.mcmc.get(), oldContext, context, doc, null);
                                } catch (RuntimeException e) {
                                    JOptionPane.showMessageDialog(this, "Could not clone tree model: " + e.getMessage());
                                    return;
                                }
                            }
                        }
                    }
                }
                // sanity check: make sure taxon sets are compatible
                Taxon.assertSameTaxa(tree.getID(), tree.getTaxonset().getTaxaNames(), likelihoods[rowNr].dataInput.get().getID(), likelihoods[rowNr].dataInput.get().getTaxaNames());
                needsRePartition = (this.likelihoods[rowNr].treeInput.get() != tree);
                Log.warning.println("needsRePartition = " + needsRePartition);
                if (needsRePartition) {
                    TreeInterface oldTree = this.likelihoods[rowNr].treeInput.get();
                    List<TreeInterface> tModels = new ArrayList<>();
                    for (GenericTreeLikelihood likelihood : likelihoods) {
                        if (likelihood.treeInput.get() == oldTree) {
                            tModels.add(likelihood.treeInput.get());
                        }
                    }
                    if (tModels.size() == 1) {
                        // remove old tree from model
                        ((BEASTInterface) oldTree).setInputValue("estimate", false);
                        // use toArray to prevent ConcurrentModificationException
                        for (Object beastObject : BEASTInterface.getOutputs(oldTree).toArray()) {
                            // .toArray(new BEASTInterface[0])) {
                            for (Input<?> input : ((BEASTInterface) beastObject).listInputs()) {
                                try {
                                    if (input.get() == oldTree) {
                                        if (input.getRule() != Input.Validate.REQUIRED) {
                                            input.setValue(tree, /*null*/
                                            (BEASTInterface) beastObject);
                                        // } else {
                                        // input.setValue(tree, (BEASTInterface) beastObject);
                                        }
                                    } else if (input.get() instanceof List) {
                                        @SuppressWarnings("unchecked") List<TreeInterface> list = (List<TreeInterface>) input.get();
                                        if (list.contains(oldTree)) {
                                            // && input.getRule() != Validate.REQUIRED) {
                                            list.remove(oldTree);
                                            if (!list.contains(tree)) {
                                                list.add(tree);
                                            }
                                        }
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                }
                likelihoods[rowNr].treeInput.setValue(tree, likelihoods[rowNr]);
                // TreeDistribution d = getDoc().getTreePrior(partition);
                // CompoundDistribution prior = (CompoundDistribution)
                // doc.pluginmap.get("prior");
                // if (!getDoc().posteriorPredecessors.contains(d)) {
                // prior.pDistributions.setValue(d, prior);
                // }
                partition = likelihoods[rowNr].treeInput.get().getID();
                partition = BeautiDoc.parsePartition(partition);
                getDoc().setCurrentPartition(BeautiDoc.TREEMODEL_PARTITION, rowNr, partition);
            }
    }
    tableData[rowNr][columnNr] = partition;
    if (needsRePartition) {
        List<BeautiSubTemplate> templates = new ArrayList<>();
        templates.add(doc.beautiConfig.partitionTemplate.get());
        templates.addAll(doc.beautiConfig.subTemplates);
        // keep applying rules till model does not change
        doc.setUpActivePlugins();
        int n;
        do {
            n = doc.posteriorPredecessors.size();
            doc.applyBeautiRules(templates, false, oldContext);
            doc.setUpActivePlugins();
        } while (n != doc.posteriorPredecessors.size());
        doc.determinePartitions();
    }
    if (treeLikelihood == null) {
        initTableData();
        setUpComboBoxes();
    }
    updateStatus();
}
Also used : MCMC(beast.core.MCMC) StateNode(beast.core.StateNode) ArrayList(java.util.ArrayList) Input(beast.core.Input) List(java.util.List) ArrayList(java.util.ArrayList) GenericTreeLikelihood(beast.evolution.likelihood.GenericTreeLikelihood) SiteModel(beast.evolution.sitemodel.SiteModel) TreeInterface(beast.evolution.tree.TreeInterface) BranchRateModel(beast.evolution.branchratemodel.BranchRateModel) State(beast.core.State) BEASTInterface(beast.core.BEASTInterface) EventObject(java.util.EventObject) SiteModelInterface(beast.evolution.sitemodel.SiteModelInterface)

Example 5 with State

use of beast.core.State in project beast2 by CompEvol.

the class ExchangeOperatorTest method testNarrowExchange.

void testNarrowExchange(String sourceTree, String targetTree, int runs, Alignment data) throws Exception {
    // first test going from source to target
    double match = 0;
    for (int i = 0; i < runs; i++) {
        TreeParser tree = new TreeParser();
        tree.initByName("taxa", data, "newick", sourceTree, "IsLabelledNewick", true);
        State state = new State();
        state.initByName("stateNode", tree);
        state.initialise();
        Exchange operator = new Exchange();
        operator.initByName("isNarrow", true, "tree", tree, "weight", 1.0);
        double logHR = operator.proposal();
        String treeString = tree.getRoot().toNewick();
        if (treeString.equals(targetTree) && !Double.isInfinite(logHR)) {
            // proportion of accepts equals min(HR, 1.0)
            match += Math.min(Math.exp(logHR), 1.0);
        }
    }
    System.out.println(" Matches: " + match * 100.0 / runs + "%");
    // now test going from target to source
    double match2 = 0;
    for (int i = 0; i < runs; i++) {
        TreeParser tree = new TreeParser();
        tree.initByName("taxa", data, "newick", targetTree, "IsLabelledNewick", true);
        State state = new State();
        state.initByName("stateNode", tree);
        state.initialise();
        Exchange operator = new Exchange();
        operator.initByName("isNarrow", true, "tree", tree, "weight", 1.0);
        double logHR = operator.proposal();
        String treeString = tree.getRoot().toNewick();
        if (treeString.equals(sourceTree) && !Double.isInfinite(logHR)) {
            // proportion of accepts equals min(HR, 1.0)
            match2 += Math.min(Math.exp(logHR), 1.0);
        }
    }
    System.out.println(" Matches: " + match2 * 100.0 / runs + "%");
    assertTrue("difference(" + 100 * (match - match2) / runs + ") exceeds 1.0%", 100.0 * Math.abs(match - match2) / runs < 1.0);
}
Also used : Exchange(beast.evolution.operators.Exchange) TreeParser(beast.util.TreeParser) State(beast.core.State)

Aggregations

State (beast.core.State)27 RealParameter (beast.core.parameter.RealParameter)14 Test (org.junit.Test)14 MCMC (beast.core.MCMC)10 SCMigrationModel (beast.evolution.tree.SCMigrationModel)9 TypeSet (beast.evolution.tree.TypeSet)9 StructuredCoalescentTreeDensity (multitypetree.distributions.StructuredCoalescentTreeDensity)9 MultiTypeTreeStatLogger (multitypetree.util.MultiTypeTreeStatLogger)9 Operator (beast.core.Operator)7 IntegerParameter (beast.core.parameter.IntegerParameter)6 MultiTypeTreeFromNewick (beast.evolution.tree.MultiTypeTreeFromNewick)6 StateNode (beast.core.StateNode)5 BEASTInterface (beast.core.BEASTInterface)4 MultiTypeTree (beast.evolution.tree.MultiTypeTree)3 StructuredCoalescentMultiTypeTree (beast.evolution.tree.StructuredCoalescentMultiTypeTree)3 ByteArrayInputStream (java.io.ByteArrayInputStream)3 Map (beast.core.parameter.Map)2 UniformOperator (beast.evolution.operators.UniformOperator)2 SiteModel (beast.evolution.sitemodel.SiteModel)2 IOException (java.io.IOException)2