use of beast.evolution.likelihood.GenericTreeLikelihood in project beast2 by CompEvol.
the class BeautiDoc method addTraitSet.
/**
* assigns trait to first available tree *
*/
void addTraitSet(TraitSet trait) {
if (trait != null) {
CompoundDistribution likelihood = (CompoundDistribution) pluginmap.get("likelihood");
for (Distribution d : likelihood.pDistributions.get()) {
if (d instanceof GenericTreeLikelihood) {
try {
// TODO: this might not be a valid type conversion from TreeInterface to Tree
Tree tree = (Tree) ((GenericTreeLikelihood) d).treeInput.get();
tree.m_traitList.setValue(trait, tree);
} catch (Exception e) {
e.printStackTrace();
}
scrubAll(true, false);
return;
}
}
}
}
use of beast.evolution.likelihood.GenericTreeLikelihood in project beast2 by CompEvol.
the class BeautiDoc method setClockRate.
void setClockRate() {
boolean needsEstimationBySPTree = false;
if (pluginmap.containsKey("Tree.t:Species")) {
Tree sptree = (Tree) pluginmap.get("Tree.t:Species");
// check whether there is a calibration
for (Object beastObject : sptree.getOutputs()) {
if (beastObject instanceof MRCAPrior) {
MRCAPrior prior = (MRCAPrior) beastObject;
if (prior.distInput.get() != null) {
needsEstimationBySPTree = true;
}
}
}
}
BEASTInterface likelihood = pluginmap.get("likelihood");
if (likelihood instanceof CompoundDistribution) {
int i = 0;
RealParameter firstClock = null;
for (Distribution distr : ((CompoundDistribution) likelihood).pDistributions.get()) {
if (distr instanceof GenericTreeLikelihood) {
GenericTreeLikelihood treeLikelihood = (GenericTreeLikelihood) distr;
boolean needsEstimation = needsEstimationBySPTree;
if (i > 0) {
BranchRateModel.Base model = treeLikelihood.branchRateModelInput.get();
needsEstimation = (model.meanRateInput.get() != firstClock) || firstClock.isEstimatedInput.get();
} else {
// TODO: this might not be a valid type conversion from TreeInterface to Tree
Tree tree = (Tree) treeLikelihood.treeInput.get();
// check whether there are tip dates
if (tree.hasDateTrait()) {
needsEstimation = true;
}
// check whether there is a calibration
for (Object beastObject : tree.getOutputs()) {
if (beastObject instanceof MRCAPrior) {
MRCAPrior prior = (MRCAPrior) beastObject;
if (prior.distInput.get() != null) {
needsEstimation = true;
}
}
}
}
BranchRateModel.Base model = treeLikelihood.branchRateModelInput.get();
if (model != null) {
RealParameter clockRate = model.meanRateInput.get();
clockRate.isEstimatedInput.setValue(needsEstimation, clockRate);
if (firstClock == null) {
firstClock = clockRate;
}
}
i++;
}
}
}
}
use of beast.evolution.likelihood.GenericTreeLikelihood in project beast2 by CompEvol.
the class BeautiDoc method extractSequences.
void extractSequences(String xml) throws XMLParserException, SAXException, IOException, ParserConfigurationException {
// parse the XML fragment into a DOM document
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
Document doc = factory.newDocumentBuilder().parse(new InputSource(new StringReader(xml)));
doc.normalize();
// find top level beast element
NodeList nodes = doc.getElementsByTagName("*");
Node topNode = nodes.item(0);
String beautiTemplate = XMLParser.getAttribute(topNode, "beautitemplate");
if (beautiTemplate == null) {
int choice = JOptionPane.showConfirmDialog(getFrame(), "This file does not appear to be generated by BEAUti. If you load it, unexpected behaviour may follow");
if (choice != JOptionPane.OK_OPTION) {
return;
}
// load standard template
if (beautiConfig == null) {
String templateXML = processTemplate(STANDARD_TEMPLATE);
loadTemplate(templateXML);
}
} else {
String templateXML = processTemplate(beautiTemplate + ".xml");
loadTemplate(templateXML);
}
String beautiStatus = XMLParser.getAttribute(topNode, "beautistatus");
if (beautiStatus == null) {
beautiStatus = "";
}
autoSetClockRate = !beautiStatus.contains("noAutoSetClockRate");
beauti.autoSetClockRate.setSelected(autoSetClockRate);
allowLinking = beautiStatus.contains("allowLinking");
beauti.allowLinking.setSelected(allowLinking);
autoUpdateFixMeanSubstRate = !beautiStatus.contains("noAutoUpdateFixMeanSubstRate");
beauti.autoUpdateFixMeanSubstRate.setSelected(autoUpdateFixMeanSubstRate);
// parse file
XMLParser parser = new XMLParser();
BEASTInterface MCMC = parser.parseFragment(xml, true);
mcmc.setValue(MCMC, this);
BEASTObjectPanel.addPluginToMap(MCMC, this);
// reconstruct all objects from templates
try {
CompoundDistribution posterior = (CompoundDistribution) ((beast.core.MCMC) mcmc.get()).posteriorInput.get();
for (Distribution distr : posterior.pDistributions.get()) {
if (distr.getID().equals("likelihood")) {
for (Distribution likelihood : ((CompoundDistribution) distr).pDistributions.get()) {
if (likelihood instanceof GenericTreeLikelihood) {
GenericTreeLikelihood treeLikelihood = (GenericTreeLikelihood) likelihood;
PartitionContext context = new PartitionContext(treeLikelihood);
try {
beautiConfig.partitionTemplate.get().createSubNet(context, false);
} catch (Exception e) {
// e.printStackTrace();
}
for (BeautiSubTemplate subTemplate : beautiConfig.subTemplates) {
try {
subTemplate.createSubNet(context, false);
} catch (Exception e) {
// e.printStackTrace();
}
}
}
}
}
}
} catch (Exception e) {
// e.printStackTrace();
}
// MCMC = parser.parseFragment(xml, true);
// mcmc.setValue(MCMC, this);
// PluginPanel.addPluginToMap(MCMC, this);
// if (xml.indexOf(XMLProducer.DO_NOT_EDIT_WARNING) > 0) {
// int start = xml.indexOf(XMLProducer.DO_NOT_EDIT_WARNING);
// int end = xml.lastIndexOf("-->");
// xml = xml.substring(start, end);
// xml = xml.replaceAll(XMLProducer.DO_NOT_EDIT_WARNING, "");
// xml = "<beast namespace='" + XMLProducer.DEFAULT_NAMESPACE + "'>" + xml + "</beast>";
// List<BEASTObject> beastObjects = parser.parseBareFragments(xml, true);
// for (BEASTObject beastObject : beastObjects) {
// PluginPanel.addPluginToMap(beastObject, this);
// }
// }
// extract alignments
determinePartitions();
}
use of beast.evolution.likelihood.GenericTreeLikelihood in project beast2 by CompEvol.
the class BeautiSubTemplate method createSubNet.
private BEASTInterface createSubNet(PartitionContext context, /*BeautiDoc doc,*/
HashMap<String, BEASTInterface> idMap, boolean init) {
subNetDepth++;
if (subNetDepth > 10) {
// looks like we cannot find what we are looking for
throw new IllegalArgumentException("Potential programmer error: It looks like there is a required input that was not specified in the tenmplate");
}
// wrap in a beast element with appropriate name spaces
String _sXML = "<beast version='2.0' \n" + "namespace='beast.app.beauti:beast.core:beast.evolution.branchratemodel:beast.evolution.speciation:beast.evolution.tree.coalescent:beast.core.util:beast.evolution.nuc:beast.evolution.operators:beast.evolution.sitemodel:beast.evolution.substitutionmodel:beast.evolution.likelihood:beast.evolution:beast.math.distributions'>\n" + xml + "</beast>\n";
// resolve alignment references
_sXML = _sXML.replaceAll("idref=[\"']data['\"]", "idref='" + context.partition + "'");
_sXML = _sXML.replaceAll("[\"']@data['\"]", "'@" + context.partition + "'");
// ensure uniqueness of IDs
// _sXML.replaceAll("\\$\\(n\\)", partition);
_sXML = BeautiDoc.translatePartitionNames(_sXML, context);
XMLParser parser = new XMLParser();
parser.setRequiredInputProvider(doc, context);
List<BEASTInterface> beastObjects = null;
try {
beastObjects = parser.parseTemplate(_sXML, idMap, true);
for (BEASTInterface beastObject : beastObjects) {
doc.addPlugin(beastObject);
try {
Log.warning.println("Adding " + beastObject.getClass().getName() + " " + beastObject);
} catch (Exception e) {
Log.err.println("Adding " + beastObject.getClass().getName());
}
}
for (BeautiConnector connector : connectors) {
if (init && connector.atInitialisationOnly()) {
// ||
doc.connect(connector, context);
}
// System.out.println(connector.sourceID + " == " + connector.targetID);
if (connector.targetID != null && connector.targetID.equals("prior")) {
Log.warning.println(">>> No description for connector " + connector.sourceID + " == " + connector.targetID);
}
if (connector.getTipText() != null) {
String ID = BeautiDoc.translatePartitionNames(connector.sourceID, context);
String tipText = BeautiDoc.translatePartitionNames(connector.getTipText(), context).trim().replaceAll("\\s+", " ");
// System.out.println(ID + " -> " + tipText);
doc.tipTextMap.put(ID, tipText);
}
}
if (suppressedInputs.get() != null) {
String[] inputs = suppressedInputs.get().split(",");
for (String input : inputs) {
input = input.trim();
doc.beautiConfig.suppressBEASTObjects.add(input);
}
}
if (inlineInput.get() != null) {
String[] inputs = inlineInput.get().split(",");
for (String input : inputs) {
input = input.trim();
doc.beautiConfig.inlineBEASTObject.add(input);
}
}
if (collapsedInput.get() != null) {
String[] inputs = collapsedInput.get().split(",");
for (String input : inputs) {
input = input.trim();
doc.beautiConfig.collapsedBEASTObjects.add(input);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (mainID.equals("[top]")) {
subNetDepth--;
return beastObjects.get(0);
}
String id = mainID;
// id.replaceAll("\\$\\(n\\)", partition);
id = BeautiDoc.translatePartitionNames(id, context);
BEASTInterface beastObject = doc.pluginmap.get(id);
if (this == doc.beautiConfig.partitionTemplate.get()) {
// HACK: need to make sure the subst model is of the correct type
BEASTInterface treeLikelihood = doc.pluginmap.get("treeLikelihood." + context.partition);
if (treeLikelihood != null && ((GenericTreeLikelihood) treeLikelihood).siteModelInput.get() instanceof SiteModel.Base) {
SiteModel.Base siteModel = (SiteModel.Base) ((GenericTreeLikelihood) treeLikelihood).siteModelInput.get();
SubstitutionModel substModel = siteModel.substModelInput.get();
try {
if (!siteModel.canSetSubstModel(substModel)) {
setUpSubstModel(siteModel, context);
}
} catch (Exception e) {
setUpSubstModel(siteModel, context);
}
}
// HACK2: rename file name for trace log if it has the default value
Logger logger = (Logger) doc.pluginmap.get("tracelog");
if (logger != null) {
String fileName = logger.fileNameInput.get();
if (fileName.startsWith("beast.") && treeLikelihood != null) {
Alignment data = ((GenericTreeLikelihood) treeLikelihood).dataInput.get();
while (data instanceof FilteredAlignment) {
data = ((FilteredAlignment) data).alignmentInput.get();
}
fileName = data.getID() + fileName.substring(5);
try {
logger.fileNameInput.setValue(fileName, logger);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
subNetDepth--;
// System.err.println(new XMLProducer().toXML(beastObject));
return beastObject;
}
use of beast.evolution.likelihood.GenericTreeLikelihood 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();
}
Aggregations