use of beast.core.MCMC in project beast2 by CompEvol.
the class BeautiDoc method scrubAll.
// TreeDistribution getTreePrior(String partition) {
// int k = 0;
// for (Alignment data : alignments) {
// if (data.getID().equals(partition)) {
// return treePriors.get(k);
// }
// k++;
// }
// return null;
// }
public synchronized void scrubAll(boolean useNotEstimatedStateNodes, boolean isInitial) {
try {
if (autoSetClockRate) {
setClockRate();
}
if (autoUpdateFixMeanSubstRate) {
SiteModelInputEditor.customConnector(this);
}
// }
if (pluginmap.containsKey("Tree.t:Species")) {
Tree tree = (Tree) pluginmap.get("Tree.t:Species");
tree.isEstimatedInput.setValue(true, tree);
}
// go through all templates, and process connectors in relevant ones
boolean progress = true;
while (progress) {
warning("============================ start scrubbing ===========================");
progress = false;
setUpActivePlugins();
// process MRCA priors
for (String id : pluginmap.keySet()) {
if (id != null && id.endsWith(".prior")) {
BEASTInterface beastObject = pluginmap.get(id);
if (beastObject instanceof MRCAPrior) {
MRCAPrior prior = (MRCAPrior) beastObject;
if (prior.treeInput.get().isEstimatedInput.get() == false) {
// disconnect
disconnect(beastObject, "prior", "distribution");
} else {
// connect
connect(beastObject, "prior", "distribution");
}
}
}
}
List<BeautiSubTemplate> templates = new ArrayList<>();
templates.add(beautiConfig.partitionTemplate.get());
templates.addAll(beautiConfig.subTemplates);
for (PartitionContext context : possibleContexts) {
applyBeautiRules(templates, isInitial, context);
}
// add 'Species' as special partition name
applyBeautiRules(templates, isInitial, new PartitionContext("Species"));
// if the model changed, some rules that use inposterior() may
// not have been triggered properly
// so we need to check that the model changed, and if so,
// revisit the BeautiConnectors
List<BEASTInterface> posteriorPredecessors2 = new ArrayList<>();
collectPredecessors(((MCMC) mcmc.get()).posteriorInput.get(), posteriorPredecessors2);
if (posteriorPredecessors.size() != posteriorPredecessors2.size()) {
progress = true;
} else {
for (BEASTInterface beastObject : posteriorPredecessors2) {
if (!posteriorPredecessors.contains(beastObject)) {
progress = true;
break;
}
}
}
}
List<BeautiSubTemplate> templates = new ArrayList<>();
templates.add(beautiConfig.hyperPriorTemplate);
for (BEASTInterface beastObject : pluginmap.values()) {
if (beastObject instanceof RealParameter) {
if (beastObject.getID() != null && beastObject.getID().startsWith("parameter.")) {
PartitionContext context = new PartitionContext(beastObject.getID().substring("parameter.".length()));
applyBeautiRules(templates, isInitial, context);
}
}
}
collectClockModels();
// collectTreePriors();
Log.warning.println("PARTITIONS:\n");
Log.warning.println(Arrays.toString(currentPartitions));
determineLinks();
} catch (Exception e) {
Log.err.println(e.getMessage());
}
}
use of beast.core.MCMC 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.core.MCMC in project beast2 by CompEvol.
the class BeautiBase method operatorsAsString.
String operatorsAsString() {
MCMC mcmc = (MCMC) doc.mcmc.get();
List<Operator> operators = mcmc.operatorsInput.get();
return "assertOperatorsEqual" + pluginListAsString(operators);
}
use of beast.core.MCMC 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();
}
use of beast.core.MCMC in project beast2 by CompEvol.
the class ExampleJSONParsingTest method test_ThatJSONExamplesRun.
public void test_ThatJSONExamplesRun(String dir) {
try {
Logger.FILE_MODE = Logger.LogFileMode.overwrite;
System.out.println("Test that JSON Examples run in " + dir);
File exampleDir = new File(dir);
String[] exampleFiles = exampleDir.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".json");
}
});
List<String> failedFiles = new ArrayList<String>();
int seed = 127;
for (String fileName : exampleFiles) {
Randomizer.setSeed(seed);
// need more than one to prevent trouble with multiMCMC logs
seed += 10;
System.out.println("Processing " + fileName);
JSONParser parser = new JSONParser();
try {
beast.core.Runnable runable = parser.parseFile(new File(dir + "/" + fileName));
if (runable instanceof MCMC) {
MCMC mcmc = (MCMC) runable;
mcmc.setInputValue("preBurnin", 0);
mcmc.setInputValue("chainLength", 1000l);
mcmc.run();
}
} catch (Exception e) {
System.out.println("ExampleJSONParsing::Failed for " + fileName + ": " + e.getMessage());
failedFiles.add(fileName);
}
System.out.println("Done " + fileName);
}
if (failedFiles.size() > 0) {
System.out.println("\ntest_ThatJSONExamplesRun::Failed for : " + failedFiles.toString());
} else {
System.out.println("SUCCESS!!!");
}
assertTrue(failedFiles.toString(), failedFiles.size() == 0);
} catch (Exception e) {
System.out.println("exception thrown ");
System.out.println(e.getMessage());
;
}
}
Aggregations