Search in sources :

Example 6 with TreeInterface

use of beast.evolution.tree.TreeInterface in project beast2 by CompEvol.

the class AlignmentListInputEditor method delItem.

void delItem() {
    int[] selected = getTableRowSelection();
    if (selected.length == 0) {
        JOptionPane.showMessageDialog(this, "Select partitions to delete, before hitting the delete button");
    }
    // do the actual deleting
    for (int i = selected.length - 1; i >= 0; i--) {
        int rowNr = selected[i];
        // before deleting, unlink site model, clock model and tree
        // check whether any of the models are linked
        BranchRateModel.Base clockModel = likelihoods[rowNr].branchRateModelInput.get();
        SiteModelInterface siteModel = likelihoods[rowNr].siteModelInput.get();
        TreeInterface tree = likelihoods[rowNr].treeInput.get();
        List<GenericTreeLikelihood> cModels = new ArrayList<>();
        List<GenericTreeLikelihood> models = new ArrayList<>();
        List<GenericTreeLikelihood> tModels = new ArrayList<>();
        for (GenericTreeLikelihood likelihood : likelihoods) {
            if (likelihood != likelihoods[rowNr]) {
                if (likelihood.branchRateModelInput.get() == clockModel) {
                    cModels.add(likelihood);
                }
                if (likelihood.siteModelInput.get() == siteModel) {
                    models.add(likelihood);
                }
                if (likelihood.treeInput.get() == tree) {
                    tModels.add(likelihood);
                }
            }
        }
        try {
            if (cModels.size() > 0) {
                // clock model is linked, so we need to unlink
                if (doc.getPartitionNr(clockModel) != rowNr) {
                    tableData[rowNr][CLOCKMODEL_COLUMN] = getDoc().partitionNames.get(rowNr).partition;
                } else {
                    int freePartition = doc.getPartitionNr(cModels.get(0));
                    tableData[rowNr][CLOCKMODEL_COLUMN] = getDoc().partitionNames.get(freePartition).partition;
                }
                updateModel(CLOCKMODEL_COLUMN, rowNr);
            }
            if (models.size() > 0) {
                // site model is linked, so we need to unlink
                if (doc.getPartitionNr((BEASTInterface) siteModel) != rowNr) {
                    tableData[rowNr][SITEMODEL_COLUMN] = getDoc().partitionNames.get(rowNr).partition;
                } else {
                    int freePartition = doc.getPartitionNr(models.get(0));
                    tableData[rowNr][SITEMODEL_COLUMN] = getDoc().partitionNames.get(freePartition).partition;
                }
                updateModel(SITEMODEL_COLUMN, rowNr);
            }
            if (tModels.size() > 0) {
                // tree is linked, so we need to unlink
                if (doc.getPartitionNr((BEASTInterface) tree) != rowNr) {
                    tableData[rowNr][TREE_COLUMN] = getDoc().partitionNames.get(rowNr).partition;
                } else {
                    int freePartition = doc.getPartitionNr(tModels.get(0));
                    tableData[rowNr][TREE_COLUMN] = getDoc().partitionNames.get(freePartition).partition;
                }
                updateModel(TREE_COLUMN, rowNr);
            }
            getDoc().delAlignmentWithSubnet(alignments.get(rowNr));
            alignments.remove(rowNr);
            // remove deleted likelihood from likelihoods array
            GenericTreeLikelihood[] tmp = new GenericTreeLikelihood[likelihoods.length - 1];
            int k = 0;
            for (int j = 0; j < likelihoods.length; j++) {
                if (j != rowNr) {
                    tmp[k] = likelihoods[j];
                    k++;
                }
            }
            likelihoods = tmp;
            partitionCount--;
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Deletion failed: " + e.getMessage());
            e.printStackTrace();
        }
    }
    MRCAPriorInputEditor.customConnector(doc);
    refreshPanel();
}
Also used : BranchRateModel(beast.evolution.branchratemodel.BranchRateModel) GenericTreeLikelihood(beast.evolution.likelihood.GenericTreeLikelihood) ArrayList(java.util.ArrayList) BEASTInterface(beast.core.BEASTInterface) SiteModelInterface(beast.evolution.sitemodel.SiteModelInterface) TreeInterface(beast.evolution.tree.TreeInterface)

Example 7 with TreeInterface

use of beast.evolution.tree.TreeInterface in project beast2 by CompEvol.

the class GeneTreeForSpeciesTreeDistribution method calculateLogP.

@Override
public double calculateLogP() {
    logP = 0;
    for (final PriorityQueue<Double> m_interval : intervalsInput) {
        m_interval.clear();
    }
    Arrays.fill(nrOfLineages, 0);
    final TreeInterface stree = speciesTreeInput.get();
    final Node[] speciesNodes = stree.getNodesAsArray();
    traverseLineageTree(speciesNodes, treeInput.get().getRoot());
    // if the gene tree does not fit the species tree, logP = -infinity by now
    if (logP == 0) {
        traverseSpeciesTree(stree.getRoot());
    }
    // System.err.println("logp=" + logP);
    return logP;
}
Also used : Node(beast.evolution.tree.Node) TreeInterface(beast.evolution.tree.TreeInterface)

Example 8 with TreeInterface

use of beast.evolution.tree.TreeInterface in project beast2 by CompEvol.

the class PriorListInputEditor method init.

@Override
public void init(Input<?> input, BEASTInterface beastObject, int itemNr, ExpandOption isExpandOption, boolean addButtons) {
    List<?> list = (List<?>) input.get();
    Collections.sort(list, (Object o1, Object o2) -> {
        if (o1 instanceof BEASTInterface && o2 instanceof BEASTInterface) {
            String d1 = ((BEASTInterface) o1).getID();
            String id2 = ((BEASTInterface) o2).getID();
            // first the tree priors
            if (o1 instanceof TreeDistribution) {
                if (o2 instanceof TreeDistribution) {
                    TreeInterface tree1 = ((TreeDistribution) o1).treeInput.get();
                    if (tree1 == null) {
                        tree1 = ((TreeDistribution) o1).treeIntervalsInput.get().treeInput.get();
                    }
                    TreeInterface tree2 = ((TreeDistribution) o2).treeInput.get();
                    if (tree2 == null) {
                        tree2 = ((TreeDistribution) o2).treeIntervalsInput.get().treeInput.get();
                    }
                    return d1.compareTo(id2);
                } else {
                    return -1;
                }
            } else if (o1 instanceof MRCAPrior) {
                // last MRCA priors
                if (o2 instanceof MRCAPrior) {
                    return d1.compareTo(id2);
                } else {
                    return 1;
                }
            } else {
                if (o2 instanceof TreeDistribution) {
                    return 1;
                }
                if (o2 instanceof MRCAPrior) {
                    return -1;
                }
                if (o1 instanceof Prior) {
                    d1 = ((Prior) o1).getParameterName();
                }
                if (o2 instanceof Prior) {
                    id2 = ((Prior) o2).getParameterName();
                }
                return d1.compareTo(id2);
            }
        }
        return 0;
    });
    rangeButtons = new ArrayList<>();
    taxonButtons = new ArrayList<>();
    // m_buttonStatus = ButtonStatus.NONE;
    super.init(input, beastObject, itemNr, isExpandOption, addButtons);
    if (beastObject instanceof BeautiPanelConfig) {
        BeautiPanelConfig config = (BeautiPanelConfig) beastObject;
        if (config.parentBEASTObjects != null && config.parentBEASTObjects.size() > 0 && config.parentBEASTObjects.get(0).getID().equals("speciescoalescent")) {
            m_buttonStatus = ButtonStatus.NONE;
        }
    }
    if (m_buttonStatus == ButtonStatus.ALL || m_buttonStatus == ButtonStatus.ADD_ONLY) {
        addButton = new SmallButton("+ Add Prior", true);
        addButton.setName("addItem");
        addButton.setToolTipText("Add new prior (like an MRCA-prior) to the list of priors");
        addButton.addActionListener(e -> {
            addItem();
        });
        buttonBox.add(addButton);
        buttonBox.add(Box.createHorizontalGlue());
    }
}
Also used : TreeDistribution(beast.evolution.tree.TreeDistribution) Prior(beast.math.distributions.Prior) MRCAPrior(beast.math.distributions.MRCAPrior) MRCAPrior(beast.math.distributions.MRCAPrior) SmallButton(beast.app.draw.SmallButton) ArrayList(java.util.ArrayList) List(java.util.List) BEASTInterface(beast.core.BEASTInterface) TreeInterface(beast.evolution.tree.TreeInterface)

Example 9 with TreeInterface

use of beast.evolution.tree.TreeInterface in project beast2 by CompEvol.

the class BeautiPanel method cloneFrom.

/**
 * Clones partition identified by sourceID to targetID and type (Site/Clock/Tree model)
 * as stored in config.
 * @param sourceID
 * @param targetID
 */
public void cloneFrom(String sourceID, String targetID) {
    if (sourceID.equals(targetID)) {
        return;
    }
    String type = config.hasPartitionsInput.get().toString();
    java.util.List<BEASTInterface> list = doc.getPartitions(type);
    int source = -1, target = -1;
    for (int i = 0; i < list.size(); i++) {
        BEASTInterface partition = list.get(i);
        if (type.equals("SiteModel")) {
            partition = (BEASTInterface) ((GenericTreeLikelihood) partition).siteModelInput.get();
        } else if (type.equals("ClockModel")) {
            partition = ((GenericTreeLikelihood) partition).branchRateModelInput.get();
        } else if (type.equals("Tree")) {
            partition = (BEASTInterface) ((GenericTreeLikelihood) partition).treeInput.get();
        }
        String partitionID = partition.getID();
        partitionID = partitionID.substring(partitionID.lastIndexOf('.') + 1);
        if (partitionID.length() > 1 && partitionID.charAt(1) == ':') {
            partitionID = partitionID.substring(2);
        }
        if (partitionID.equals(sourceID)) {
            source = i;
        }
        if (partitionID.equals(targetID)) {
            target = i;
        }
    }
    if (target == -1) {
        throw new RuntimeException("Programmer error: sourceID and targetID should be in list");
    }
    CompoundDistribution likelihoods = (CompoundDistribution) doc.pluginmap.get("likelihood");
    GenericTreeLikelihood likelihoodSource = (GenericTreeLikelihood) likelihoods.pDistributions.get().get(source);
    GenericTreeLikelihood likelihood = (GenericTreeLikelihood) likelihoods.pDistributions.get().get(target);
    PartitionContext oldContext = doc.getContextFor(likelihoodSource);
    PartitionContext newContext = doc.getContextFor(likelihood);
    // this ensures the config.sync does not set any input value
    config._input.setValue(null, config);
    if (type.equals("SiteModel")) {
        SiteModelInterface siteModelSource = likelihoodSource.siteModelInput.get();
        SiteModelInterface siteModel = null;
        try {
            siteModel = (SiteModel.Base) BeautiDoc.deepCopyPlugin((BEASTInterface) siteModelSource, likelihood, (MCMC) doc.mcmc.get(), oldContext, newContext, doc, null);
        } catch (RuntimeException e) {
            JOptionPane.showMessageDialog(this, "Could not clone " + sourceID + " to " + targetID + " " + e.getMessage());
            return;
        }
        likelihood.siteModelInput.setValue(siteModel, likelihood);
        return;
    } else if (type.equals("ClockModel")) {
        BranchRateModel clockModelSource = likelihoodSource.branchRateModelInput.get();
        BranchRateModel clockModel = null;
        try {
            clockModel = (BranchRateModel) BeautiDoc.deepCopyPlugin((BEASTInterface) clockModelSource, likelihood, (MCMC) doc.mcmc.get(), oldContext, newContext, doc, null);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "Could not clone " + sourceID + " to " + targetID + " " + 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;
        try {
            for (Input<?> input : ((BEASTInterface) clockModel).listInputs()) {
                if (input.getName().equals("tree")) {
                    tree = (TreeInterface) input.get();
                }
            }
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if (tree != null && tree != likelihood.treeInput.get()) {
            // likelihood.treeInput.setValue(tree, likelihood);
            JOptionPane.showMessageDialog(null, "Cannot clone clock model with different trees");
            return;
        }
        likelihood.branchRateModelInput.setValue(clockModel, likelihood);
        return;
    } else if (type.equals("Tree")) {
        TreeInterface tree = null;
        TreeInterface treeSource = likelihoodSource.treeInput.get();
        try {
            tree = (TreeInterface) BeautiDoc.deepCopyPlugin((BEASTInterface) treeSource, likelihood, (MCMC) doc.mcmc.get(), oldContext, newContext, doc, null);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "Could not clone " + sourceID + " to " + targetID + " " + e.getMessage());
            return;
        }
        // sanity check: make sure taxon sets are compatible
        Taxon.assertSameTaxa(tree.getID(), tree.getTaxonset().getTaxaNames(), likelihood.dataInput.get().getID(), likelihood.dataInput.get().getTaxaNames());
        likelihood.treeInput.setValue(tree, likelihood);
        return;
    } else {
        throw new RuntimeException("Programmer error calling cloneFrom: Should only clone Site/Clock/Tree model");
    }
}
Also used : GenericTreeLikelihood(beast.evolution.likelihood.GenericTreeLikelihood) MCMC(beast.core.MCMC) SiteModel(beast.evolution.sitemodel.SiteModel) InvocationTargetException(java.lang.reflect.InvocationTargetException) TreeInterface(beast.evolution.tree.TreeInterface) CompoundDistribution(beast.core.util.CompoundDistribution) Input(beast.core.Input) BranchRateModel(beast.evolution.branchratemodel.BranchRateModel) BEASTInterface(beast.core.BEASTInterface) SiteModelInterface(beast.evolution.sitemodel.SiteModelInterface)

Example 10 with TreeInterface

use of beast.evolution.tree.TreeInterface in project beast2 by CompEvol.

the class CalibratedBirthDeathModel method initAndValidate.

@Override
public void initAndValidate() {
    super.initAndValidate();
    type = correctionTypeInput.get();
    final TreeInterface tree = treeInput.get();
    // shallow copy. we shall change cals later
    final List<CalibrationPoint> cals = new ArrayList<>(calibrationsInput.get());
    int calCount = cals.size();
    final List<TaxonSet> taxaSets = new ArrayList<>(calCount);
    if (cals.size() > 0) {
        xclades = new int[calCount][];
        // convenience
        for (final CalibrationPoint cal : cals) {
            taxaSets.add(cal.taxa());
        }
    } else {
        // find calibration points from prior
        for (final Object beastObject : getOutputs()) {
            if (beastObject instanceof CompoundDistribution) {
                final CompoundDistribution prior = (CompoundDistribution) beastObject;
                for (final Distribution distr : prior.pDistributions.get()) {
                    if (distr instanceof MRCAPrior) {
                        final MRCAPrior _MRCAPrior = (MRCAPrior) distr;
                        // make sure MRCAPrior is monophyletic
                        if (_MRCAPrior.distInput.get() != null) {
                            // make sure MRCAPrior is monophyletic
                            if (!_MRCAPrior.isMonophyleticInput.get()) {
                                throw new IllegalArgumentException("MRCAPriors must be monophyletic for Calibrated Yule prior");
                            }
                            // create CalibrationPoint from MRCAPrior
                            final CalibrationPoint cal = new CalibrationPoint();
                            cal.distInput.setValue(_MRCAPrior.distInput.get(), cal);
                            cal.taxonsetInput.setValue(_MRCAPrior.taxonsetInput.get(), cal);
                            cal.initAndValidate();
                            cals.add(cal);
                            taxaSets.add(cal.taxa());
                            cal.taxa().initAndValidate();
                            calCount++;
                            calcCalibrations = false;
                        } else {
                            if (_MRCAPrior.isMonophyleticInput.get()) {
                                Log.warning.println("WARNING: MRCAPriors must have a distribution when monophyletic for Calibrated Yule prior");
                            }
                        }
                    }
                }
            }
        }
        xclades = new int[calCount][];
    }
    if (calCount == 0) {
        // assume we are in beauti, back off for now
        return;
    }
    for (int k = 0; k < calCount; ++k) {
        final TaxonSet tk = taxaSets.get(k);
        for (int i = k + 1; i < calCount; ++i) {
            final TaxonSet ti = taxaSets.get(i);
            if (ti.containsAny(tk)) {
                if (!(ti.containsAll(tk) || tk.containsAll(ti))) {
                    throw new IllegalArgumentException("Overlapping taxaSets??");
                }
            }
        }
    }
    orderedCalibrations = new CalibrationPoint[calCount];
    {
        int loc = taxaSets.size() - 1;
        while (loc >= 0) {
            assert loc == taxaSets.size() - 1;
            // place maximal taxaSets at end one at a time
            int k = 0;
            for (; /**/
            k < taxaSets.size(); ++k) {
                if (isMaximal(taxaSets, k)) {
                    break;
                }
            }
            final List<String> tk = taxaSets.get(k).asStringList();
            final int tkcount = tk.size();
            this.xclades[loc] = new int[tkcount];
            for (int nt = 0; nt < tkcount; ++nt) {
                final int taxonIndex = getTaxonIndex(tree, tk.get(nt));
                this.xclades[loc][nt] = taxonIndex;
                if (taxonIndex < 0) {
                    throw new IllegalArgumentException("Taxon not found in tree: " + tk.get(nt));
                }
            }
            orderedCalibrations[loc] = cals.remove(k);
            taxaSets.remove(k);
            // cals and taxaSets should match
            --loc;
        }
    }
    // tio[i] will contain all taxaSets contained in the i'th clade, in the form of thier index into orderedCalibrations
    @SuppressWarnings("unchecked") final List<Integer>[] tio = new List[orderedCalibrations.length];
    for (int k = 0; k < orderedCalibrations.length; ++k) {
        tio[k] = new ArrayList<>();
    }
    for (int k = 0; k < orderedCalibrations.length; ++k) {
        final TaxonSet txk = orderedCalibrations[k].taxa();
        for (int i = k + 1; i < orderedCalibrations.length; ++i) {
            if (orderedCalibrations[i].taxa().containsAll(txk)) {
                tio[i].add(k);
                break;
            }
        }
    }
    this.taxaPartialOrder = new int[orderedCalibrations.length][];
    for (int k = 0; k < orderedCalibrations.length; ++k) {
        final List<Integer> tiok = tio[k];
        this.taxaPartialOrder[k] = new int[tiok.size()];
        for (int j = 0; j < tiok.size(); ++j) {
            this.taxaPartialOrder[k][j] = tiok.get(j);
        }
    }
    // true if clade is not contained in any other clade
    final boolean[] maximal = new boolean[calCount];
    for (int k = 0; k < calCount; ++k) {
        maximal[k] = true;
    }
    for (int k = 0; k < calCount; ++k) {
        for (final int i : this.taxaPartialOrder[k]) {
            maximal[i] = false;
        }
    }
    isYule = deathToBirthRatioInput.get() == null && sampleProbabilityInput.get() == null;
    userPDF = userMarInput.get();
    if (userPDF == null) {
        boolean needTables = false;
        if (type == Type.OVER_ALL_TOPOS) {
            if (calCount == 1 && isYule) {
            // closed form formula
            } else {
                boolean anyParent = false;
                for (final CalibrationPoint c : orderedCalibrations) {
                    if (c.forParentInput.get()) {
                        anyParent = true;
                    }
                }
                if (anyParent) {
                    throw new IllegalArgumentException("Sorry, not implemented: calibration on parent for more than one clade.");
                }
                if (isYule && calCount == 2 && orderedCalibrations[1].taxa().containsAll(orderedCalibrations[0].taxa())) {
                // closed form formulas
                } else {
                    needTables = true;
                    lastHeights = new double[calCount];
                }
            }
        } else if (type == Type.OVER_RANKED_COUNTS) {
            // setUpTables(tree.getLeafNodeCount() + 1);
            needTables = true;
        }
        if (needTables) {
            setUpTables(tree.getLeafNodeCount() + 1);
            linsIter = new CalibrationLineagesIterator(this.xclades, this.taxaPartialOrder, maximal, tree.getLeafNodeCount());
        }
    }
    final List<Node> leafs = tree.getExternalNodes();
    final double height = leafs.get(0).getHeight();
    for (final Node leaf : leafs) {
        if (Math.abs(leaf.getHeight() - height) > 1e-8) {
            Log.warning.println("WARNING: Calibrated Birth-Death Model does not handle dated tips correctly. " + "Consider using a coalescent prior instead.");
            break;
        }
    }
}
Also used : Node(beast.evolution.tree.Node) ArrayList(java.util.ArrayList) TaxonSet(beast.evolution.alignment.TaxonSet) TreeInterface(beast.evolution.tree.TreeInterface) CompoundDistribution(beast.core.util.CompoundDistribution) CompoundDistribution(beast.core.util.CompoundDistribution) Distribution(beast.core.Distribution) MRCAPrior(beast.math.distributions.MRCAPrior) ArrayList(java.util.ArrayList) List(java.util.List)

Aggregations

TreeInterface (beast.evolution.tree.TreeInterface)15 Node (beast.evolution.tree.Node)7 ArrayList (java.util.ArrayList)7 BEASTInterface (beast.core.BEASTInterface)4 MRCAPrior (beast.math.distributions.MRCAPrior)4 List (java.util.List)4 CompoundDistribution (beast.core.util.CompoundDistribution)3 BranchRateModel (beast.evolution.branchratemodel.BranchRateModel)3 GenericTreeLikelihood (beast.evolution.likelihood.GenericTreeLikelihood)3 SiteModelInterface (beast.evolution.sitemodel.SiteModelInterface)3 Distribution (beast.core.Distribution)2 Input (beast.core.Input)2 MCMC (beast.core.MCMC)2 TaxonSet (beast.evolution.alignment.TaxonSet)2 SiteModel (beast.evolution.sitemodel.SiteModel)2 Tree (beast.evolution.tree.Tree)2 ParametricDistribution (beast.math.distributions.ParametricDistribution)2 SmallButton (beast.app.draw.SmallButton)1 State (beast.core.State)1 StateNode (beast.core.StateNode)1