Search in sources :

Example 21 with RealParameter

use of beast.core.parameter.RealParameter in project beast2 by CompEvol.

the class BinaryCovarionModelTest method doWithUnEqualHFreqs.

private void doWithUnEqualHFreqs(String mode) {
    Frequencies dummyFreqs = new Frequencies();
    dummyFreqs.initByName("frequencies", "0.25 0.25 0.25 0.25", "estimate", false);
    BinaryCovarion substModel;
    double d = 0.05 + Randomizer.nextDouble() * 0.9;
    RealParameter hfrequencies = new RealParameter(new Double[] { d, 1.0 - d });
    d = 0.05 + Randomizer.nextDouble() * 0.9;
    RealParameter vfrequencies = new RealParameter(new Double[] { d, 1.0 - d });
    substModel = new BinaryCovarion();
    substModel.initByName("frequencies", dummyFreqs, "hfrequencies", hfrequencies, /* [f0, f1] */
    "vfrequencies", vfrequencies, /* [p0, p1] */
    "alpha", "0.01", "switchRate", "0.1", // "eigenSystem", "beast.evolution.substitutionmodel.RobustEigenSystem",
    "mode", mode);
    double[] matrix = new double[16];
    substModel.getTransitionProbabilities(null, 1000, 0, 1.0, matrix);
    double[] baseFreqs = new double[] { (vfrequencies.getValue(0) * hfrequencies.getValue(0)), (vfrequencies.getValue(1) * hfrequencies.getValue(0)), (vfrequencies.getValue(0) * hfrequencies.getValue(1)), (vfrequencies.getValue(1) * hfrequencies.getValue(1)) };
    System.err.println("Expected: " + Arrays.toString(baseFreqs));
    System.err.println("Calculat: " + Arrays.toString(matrix));
    for (int j = 0; j < 4; j++) {
        assertEquals(baseFreqs[j], matrix[j], 1e-3);
    }
}
Also used : BinaryCovarion(beast.evolution.substitutionmodel.BinaryCovarion) RealParameter(beast.core.parameter.RealParameter) Frequencies(beast.evolution.substitutionmodel.Frequencies)

Example 22 with RealParameter

use of beast.core.parameter.RealParameter in project beast2 by CompEvol.

the class HKYTest method testHKY.

public void testHKY() throws Exception {
    for (Instance test : all) {
        RealParameter f = new RealParameter(test.getPi());
        Frequencies freqs = new Frequencies();
        freqs.initByName("frequencies", f, "estimate", false);
        HKY hky = new HKY();
        hky.initByName("kappa", test.getKappa().toString(), "frequencies", freqs);
        double distance = test.getDistance();
        double[] mat = new double[4 * 4];
        hky.getTransitionProbabilities(null, distance, 0, 1, mat);
        final double[] result = test.getExpectedResult();
        for (int k = 0; k < mat.length; ++k) {
            assertEquals(mat[k], result[k], 1e-10);
            System.out.println(k + " : " + (mat[k] - result[k]));
        }
    }
}
Also used : HKY(beast.evolution.substitutionmodel.HKY) RealParameter(beast.core.parameter.RealParameter) Frequencies(beast.evolution.substitutionmodel.Frequencies)

Example 23 with RealParameter

use of beast.core.parameter.RealParameter 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 24 with RealParameter

use of beast.core.parameter.RealParameter in project beast2 by CompEvol.

the class SiteModelInputEditor method customConnector.

public static boolean customConnector(BeautiDoc doc) {
    try {
        DeltaExchangeOperator operator = (DeltaExchangeOperator) doc.pluginmap.get("FixMeanMutationRatesOperator");
        if (operator == null) {
            return false;
        }
        List<RealParameter> parameters = operator.parameterInput.get();
        parameters.clear();
        // String weights = "";
        CompoundDistribution likelihood = (CompoundDistribution) doc.pluginmap.get("likelihood");
        boolean hasOneEstimatedRate = false;
        List<String> rateIDs = new ArrayList<>();
        List<Integer> weights = new ArrayList<>();
        for (Distribution d : likelihood.pDistributions.get()) {
            GenericTreeLikelihood treelikelihood = (GenericTreeLikelihood) d;
            Alignment data = treelikelihood.dataInput.get();
            int weight = data.getSiteCount();
            if (data.isAscertained) {
                weight -= data.getExcludedPatternCount();
            }
            if (treelikelihood.siteModelInput.get() instanceof SiteModel) {
                SiteModel siteModel = (SiteModel) treelikelihood.siteModelInput.get();
                RealParameter mutationRate = siteModel.muParameterInput.get();
                // clockRate.m_bIsEstimated.setValue(true, clockRate);
                if (mutationRate.isEstimatedInput.get()) {
                    hasOneEstimatedRate = true;
                    if (rateIDs.indexOf(mutationRate.getID()) == -1) {
                        parameters.add(mutationRate);
                        weights.add(weight);
                        rateIDs.add(mutationRate.getID());
                    } else {
                        int k = rateIDs.indexOf(mutationRate.getID());
                        weights.set(k, weights.get(k) + weight);
                    }
                }
            }
        }
        IntegerParameter weightParameter;
        if (weights.size() == 0) {
            weightParameter = new IntegerParameter();
        } else {
            String weightString = "";
            for (int k : weights) {
                weightString += k + " ";
            }
            weightParameter = new IntegerParameter(weightString);
            weightParameter.setID("weightparameter");
        }
        weightParameter.isEstimatedInput.setValue(false, weightParameter);
        operator.parameterWeightsInput.setValue(weightParameter, operator);
        return hasOneEstimatedRate;
    } catch (Exception e) {
    }
    return false;
}
Also used : IntegerParameter(beast.core.parameter.IntegerParameter) GenericTreeLikelihood(beast.evolution.likelihood.GenericTreeLikelihood) ArrayList(java.util.ArrayList) RealParameter(beast.core.parameter.RealParameter) SiteModel(beast.evolution.sitemodel.SiteModel) InvocationTargetException(java.lang.reflect.InvocationTargetException) CompoundDistribution(beast.core.util.CompoundDistribution) Alignment(beast.evolution.alignment.Alignment) CompoundDistribution(beast.core.util.CompoundDistribution) DeltaExchangeOperator(beast.evolution.operators.DeltaExchangeOperator)

Example 25 with RealParameter

use of beast.core.parameter.RealParameter in project beast2 by CompEvol.

the class PriorInputEditor method init.

@Override
public void init(Input<?> input, BEASTInterface beastObject, int listItemNr, ExpandOption isExpandOption, boolean addButtons) {
    m_bAddButtons = addButtons;
    m_input = input;
    m_beastObject = beastObject;
    this.itemNr = listItemNr;
    Box itemBox = Box.createHorizontalBox();
    Prior prior = (Prior) beastObject;
    String text = prior.getParameterName();
    JLabel label = new JLabel(text);
    Font font = label.getFont();
    Dimension size = new Dimension(font.getSize() * 200 / 13, font.getSize() * 25 / 13);
    label.setMinimumSize(size);
    label.setPreferredSize(size);
    itemBox.add(label);
    List<BeautiSubTemplate> availableBEASTObjects = doc.getInputEditorFactory().getAvailableTemplates(prior.distInput, prior, null, doc);
    JComboBox<BeautiSubTemplate> comboBox = new JComboBox<BeautiSubTemplate>(availableBEASTObjects.toArray(new BeautiSubTemplate[] {}));
    comboBox.setName(text + ".distr");
    String id = prior.distInput.get().getID();
    // Log.warning.println("id=" + id);
    id = id.substring(0, id.indexOf('.'));
    for (BeautiSubTemplate template : availableBEASTObjects) {
        if (template.classInput.get() != null && template.shortClassName.equals(id)) {
            comboBox.setSelectedItem(template);
        }
    }
    comboBox.addActionListener(e -> {
        @SuppressWarnings("unchecked") JComboBox<BeautiSubTemplate> comboBox1 = (JComboBox<BeautiSubTemplate>) e.getSource();
        List<?> list = (List<?>) m_input.get();
        BeautiSubTemplate template = (BeautiSubTemplate) comboBox1.getSelectedItem();
        // String id = ((BEASTObject) list.get(item)).getID();
        // String partition = BeautiDoc.parsePartition(id);
        PartitionContext context = doc.getContextFor((BEASTInterface) list.get(itemNr));
        Prior prior1 = (Prior) list.get(itemNr);
        try {
            template.createSubNet(context, prior1, prior1.distInput, true);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        sync();
        refreshPanel();
    });
    JPanel panel = new JPanel();
    panel.add(comboBox);
    panel.setMaximumSize(size);
    itemBox.add(panel);
    if (prior.m_x.get() instanceof RealParameter) {
        // add range button for real parameters
        RealParameter p = (RealParameter) prior.m_x.get();
        JButton rangeButton = new JButton(paramToString(p));
        rangeButton.addActionListener(e -> {
            JButton rangeButton1 = (JButton) e.getSource();
            List<?> list = (List<?>) m_input.get();
            Prior prior1 = (Prior) list.get(itemNr);
            RealParameter p1 = (RealParameter) prior1.m_x.get();
            BEASTObjectDialog dlg = new BEASTObjectDialog(p1, RealParameter.class, doc);
            if (dlg.showDialog()) {
                dlg.accept(p1, doc);
                rangeButton1.setText(paramToString(p1));
                refreshPanel();
            }
        });
        itemBox.add(Box.createHorizontalStrut(10));
        itemBox.add(rangeButton);
    } else if (prior.m_x.get() instanceof IntegerParameter) {
        // add range button for real parameters
        IntegerParameter p = (IntegerParameter) prior.m_x.get();
        JButton rangeButton = new JButton(paramToString(p));
        rangeButton.addActionListener(e -> {
            JButton rangeButton1 = (JButton) e.getSource();
            List<?> list = (List<?>) m_input.get();
            Prior prior1 = (Prior) list.get(itemNr);
            IntegerParameter p1 = (IntegerParameter) prior1.m_x.get();
            BEASTObjectDialog dlg = new BEASTObjectDialog(p1, IntegerParameter.class, doc);
            if (dlg.showDialog()) {
                dlg.accept(p1, doc);
                rangeButton1.setText(paramToString(p1));
                refreshPanel();
            }
        });
        itemBox.add(Box.createHorizontalStrut(10));
        itemBox.add(rangeButton);
    }
    int fontsize = comboBox.getFont().getSize();
    comboBox.setMaximumSize(new Dimension(1024 * fontsize / 13, 24 * fontsize / 13));
    String tipText = getDoc().tipTextMap.get(beastObject.getID());
    // System.out.println(beastObject.getID());
    if (tipText != null) {
        JLabel tipTextLabel = new JLabel(" " + tipText);
        itemBox.add(tipTextLabel);
    }
    itemBox.add(Box.createGlue());
    add(itemBox);
}
Also used : Arrays(java.util.Arrays) JButton(javax.swing.JButton) Input(beast.core.Input) Prior(beast.math.distributions.Prior) Font(java.awt.Font) FontSizeAction(javax.swing.text.StyledEditorKit.FontSizeAction) BEASTObjectDialog(beast.app.draw.BEASTObjectDialog) Box(javax.swing.Box) IntegerParameter(beast.core.parameter.IntegerParameter) Dimension(java.awt.Dimension) List(java.util.List) InputEditor(beast.app.draw.InputEditor) JLabel(javax.swing.JLabel) RealParameter(beast.core.parameter.RealParameter) BEASTInterface(beast.core.BEASTInterface) JComboBox(javax.swing.JComboBox) JPanel(javax.swing.JPanel) JPanel(javax.swing.JPanel) IntegerParameter(beast.core.parameter.IntegerParameter) BEASTObjectDialog(beast.app.draw.BEASTObjectDialog) JComboBox(javax.swing.JComboBox) JButton(javax.swing.JButton) JLabel(javax.swing.JLabel) RealParameter(beast.core.parameter.RealParameter) Box(javax.swing.Box) JComboBox(javax.swing.JComboBox) Dimension(java.awt.Dimension) Font(java.awt.Font) Prior(beast.math.distributions.Prior) List(java.util.List)

Aggregations

RealParameter (beast.core.parameter.RealParameter)97 Test (org.junit.Test)39 IntegerParameter (beast.core.parameter.IntegerParameter)23 Tree (beast.evolution.tree.Tree)16 State (beast.core.State)14 SCMigrationModel (beast.evolution.tree.SCMigrationModel)13 Alignment (beast.evolution.alignment.Alignment)11 TypeSet (beast.evolution.tree.TypeSet)11 MCMC (beast.core.MCMC)10 SiteModel (beast.evolution.sitemodel.SiteModel)10 Frequencies (beast.evolution.substitutionmodel.Frequencies)10 ConstantPopulation (beast.evolution.tree.coalescent.ConstantPopulation)10 StructuredCoalescentTreeDensity (multitypetree.distributions.StructuredCoalescentTreeDensity)10 TaxonSet (beast.evolution.alignment.TaxonSet)9 MultiTypeTreeStatLogger (multitypetree.util.MultiTypeTreeStatLogger)9 MultiTypeTreeFromNewick (beast.evolution.tree.MultiTypeTreeFromNewick)8 Node (beast.evolution.tree.Node)8 Operator (beast.core.Operator)7 RandomTree (beast.evolution.tree.RandomTree)7 Locus (bacter.Locus)6