use of beast.math.distributions.Prior in project beast2 by CompEvol.
the class BeautiDoc method deepCopyPlugin.
/**
* Create a deep copy of a beastObject, but in a different partition context
* First, find all beastObjects that are predecessors of the beastObject to be copied
* that are ancestors of StateNodes
*
* @param beastObject
* @param parent
* @return
*/
public static BEASTInterface deepCopyPlugin(BEASTInterface beastObject, BEASTInterface parent, MCMC mcmc, PartitionContext oldContext, PartitionContext newContext, BeautiDoc doc, List<BEASTInterface> tabooList) {
/**
* taboo = list of beastObjects that should not be copied *
*/
Set<BEASTInterface> taboo = new HashSet<>();
taboo.add(parent);
// add state
taboo.add(mcmc.startStateInput.get());
// add likelihood and prior
if (mcmc.posteriorInput.get() instanceof CompoundDistribution) {
for (Distribution distr : ((CompoundDistribution) mcmc.posteriorInput.get()).pDistributions.get()) {
if (distr instanceof CompoundDistribution) {
taboo.add(distr);
}
}
}
// add posterior
taboo.add(mcmc.posteriorInput.get());
// parent of operators
taboo.add(mcmc);
// add loggers
taboo.addAll(mcmc.loggersInput.get());
// add exception for *BEAST logger (perhaps need to be generalised?)
if (doc.pluginmap.containsKey("SpeciesTreeLoggerX")) {
taboo.add(doc.pluginmap.get("SpeciesTreeLoggerX"));
}
// add trees
for (StateNode node : mcmc.startStateInput.get().stateNodeInput.get()) {
if (node instanceof Tree) {
taboo.add(node);
}
}
// add MRCAPriors
for (String id : doc.pluginmap.keySet()) {
BEASTInterface o = doc.pluginmap.get(id);
if (o instanceof MRCAPrior) {
taboo.add(o);
}
}
if (tabooList != null) {
taboo.addAll(tabooList);
}
// find predecessors of beastObject to be copied
List<BEASTInterface> predecessors = new ArrayList<>();
collectPredecessors(beastObject, predecessors);
// find ancestors of StateNodes that are predecessors + the beastObject
// itself
Set<BEASTInterface> ancestors = new HashSet<>();
collectAncestors(beastObject, ancestors, taboo);
Log.info.print(Arrays.toString(ancestors.toArray()));
for (BEASTInterface beastObject2 : predecessors) {
if (beastObject2 instanceof StateNode) {
Set<BEASTInterface> ancestors2 = new HashSet<>();
collectAncestors(beastObject2, ancestors2, taboo);
ancestors.addAll(ancestors2);
} else if (beastObject2 instanceof Alignment || beastObject2 instanceof FilteredAlignment) {
for (Object output : beastObject2.getOutputs()) {
if (!taboo.contains(output)) {
Set<BEASTInterface> ancestors2 = new HashSet<>();
collectAncestors((BEASTInterface) output, ancestors2, taboo);
ancestors.addAll(ancestors2);
}
}
}
}
// collect priors
predecessors.addAll(ancestors);
for (BEASTInterface o : predecessors) {
if (o instanceof Prior) {
List<BEASTInterface> priorPredecessors = new ArrayList<>();
collectPredecessors(o, priorPredecessors);
ancestors.addAll(priorPredecessors);
}
}
Log.info.print(Arrays.toString(predecessors.toArray()));
for (BEASTInterface p : ancestors) {
Log.info.print("(");
try {
for (BEASTInterface p2 : p.listActiveBEASTObjects()) {
if (ancestors.contains(p2)) {
Log.info.print(p2.getID() + " ");
}
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
Log.info.print(") ");
Log.info.println(p.getID());
}
// now the ancestors contain all beastObjects to be copied
// make a copy of all individual BEASTObjects, before connecting them up
Map<String, BEASTInterface> copySet = new HashMap<>();
for (BEASTInterface beastObject2 : ancestors) {
String id = beastObject2.getID();
if (id == null) {
id = beastObject.getClass().getName().replaceAll(".*\\.", "");
int i = 0;
while (doc.pluginmap.containsKey(id + "." + i)) {
i++;
}
id = id + "." + i;
beastObject2.setID(id);
}
String copyID = renameId(id, oldContext, newContext);
if (!id.equals(copyID)) {
if (doc.pluginmap.containsKey(copyID)) {
BEASTInterface org = doc.pluginmap.get(copyID);
copySet.put(id, org);
} else {
BEASTInterface copy;
try {
copy = beastObject2.getClass().newInstance();
copy.setID(copyID);
copySet.put(id, copy);
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
throw new RuntimeException("Programmer error: every object in the model should have a default constructor that is publicly accessible");
}
}
}
Log.warning.println("Copy: " + id + " -> " + copyID);
}
// set all inputs of copied beastObjects + outputs to taboo
for (BEASTInterface beastObject2 : ancestors) {
String id = beastObject2.getID();
BEASTInterface copy = copySet.get(id);
if (copy != null) {
Log.warning.println("Processing: " + id + " -> " + copy.getID());
// set inputs
for (Input<?> input : beastObject2.listInputs()) {
if (input.get() != null) {
if (input.get() instanceof List) {
// ((List)copy.getInput(input.getName())).clear();
for (Object o : (List<?>) input.get()) {
if (o instanceof BEASTInterface) {
BEASTInterface value = getCopyValue((BEASTInterface) o, copySet, oldContext, newContext, doc);
// make sure it is not already in the list
Object o2 = copy.getInput(input.getName()).get();
boolean alreadyInList = false;
if (o2 instanceof List) {
List<?> currentList = (List<?>) o2;
for (Object v : currentList) {
if (v == value) {
alreadyInList = true;
break;
}
}
}
if (!alreadyInList) {
// add to the list
copy.setInputValue(input.getName(), value);
}
} else {
// it is a primitive value
if (copy instanceof Parameter.Base && input.getName().equals("value")) {
// // prevent appending to parameter values
Parameter.Base<?> p = ((Parameter.Base<?>) copy);
((List<?>) p.valuesInput.get()).clear();
}
copy.setInputValue(input.getName(), input.get());
}
}
} else if (input.get() instanceof BEASTInterface) {
// handle BEASTObject
BEASTInterface value = getCopyValue((BEASTInterface) input.get(), copySet, oldContext, newContext, doc);
copy.setInputValue(input.getName(), value);
} else if (input.get() instanceof String) {
// may need to replace partition info
String s = (String) input.get();
s = s.replaceAll("\\.c:[a-zA-Z0-9_]*", ".c:" + newContext.clockModel);
s = s.replaceAll("\\.s:[a-zA-Z0-9_]*", ".s:" + newContext.siteModel);
s = s.replaceAll("\\.t:[a-zA-Z0-9_]*", ".t:" + newContext.tree);
copy.setInputValue(input.getName(), s);
} else {
// it is a primitive value
copy.setInputValue(input.getName(), input.get());
}
}
}
// set outputs
for (Object output : beastObject2.getOutputs()) {
if (taboo.contains(output) && output != parent) {
BEASTInterface output2 = getCopyValue((BEASTInterface) output, copySet, oldContext, newContext, doc);
for (Input<?> input : ((BEASTInterface) output).listInputs()) {
// do not add state node initialisers automatically
if (input.get() instanceof List && // do not update state node initialisers
!(taboo.contains(output2) && input.getName().equals("init"))) {
List<?> list = (List<?>) input.get();
if (list.contains(beastObject2)) {
List<?> list2 = (List<?>) output2.getInput(input.getName()).get();
if (!list2.contains(copy)) {
output2.setInputValue(input.getName(), copy);
}
}
}
}
}
}
copySet.put(id, copy);
// Log.warning.println(base.operatorsAsString());
}
}
// deep copy must be obtained from copyset, before sorting
// since the sorting changes (deletes items) from the copySet map
BEASTInterface deepCopy = copySet.get(beastObject.getID());
// first need to sort copySet by topology, before we can initAndValidate
// them
List<BEASTInterface> sorted = new ArrayList<>();
Collection<BEASTInterface> values = copySet.values();
while (values.size() > 0) {
for (BEASTInterface copy : values) {
boolean found = false;
for (BEASTInterface beastObject2 : copy.listActiveBEASTObjects()) {
if (values.contains(beastObject2)) {
found = true;
break;
}
}
if (!found) {
sorted.add(copy);
}
}
values.remove(sorted.get(sorted.size() - 1));
}
// initialise copied beastObjects
Set<BEASTInterface> done = new HashSet<>();
for (BEASTInterface copy : sorted) {
try {
if (!done.contains(copy)) {
copy.initAndValidate();
done.add(copy);
}
} catch (Exception e) {
// ignore
Log.warning.print(e.getMessage());
}
if (doc != null) {
doc.addPlugin(copy);
}
}
doc.scrubAll(true, false);
return deepCopy;
}
use of beast.math.distributions.Prior 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());
}
}
use of beast.math.distributions.Prior 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);
}
use of beast.math.distributions.Prior in project beast2 by CompEvol.
the class BeautiBase method assertParameterCountInPriorIs.
void assertParameterCountInPriorIs(int i) {
// count nr of parameters in Prior objects in prior
// including those for prior distributions (Normal, etc)
// useful to make sure they do (or do not) get linked
Set<Function> parameters = new LinkedHashSet<>();
CompoundDistribution prior = (CompoundDistribution) doc.pluginmap.get("prior");
for (Distribution p : prior.pDistributions.get()) {
if (p instanceof Prior) {
Prior p2 = (Prior) p;
parameters.add(p2.m_x.get());
for (BEASTInterface o : p2.distInput.get().listActiveBEASTObjects()) {
if (o instanceof Parameter) {
parameters.add((Parameter<?>) o);
}
}
}
}
System.err.println("Number of parameters in prior = " + parameters.size());
if (i >= 0) {
assertThat(parameters.size()).as("Expected " + i + " parameters in prior").isEqualTo(i);
}
}
Aggregations