use of beast.core.Input in project beast2 by CompEvol.
the class GeneTreeForSpeciesTreeDistributionInputEditor method createPloidyEditor.
public InputEditor createPloidyEditor() {
InputEditor editor = new InputEditor.Base(doc) {
private static final long serialVersionUID = 1L;
@Override
public Class<?> type() {
return null;
}
@Override
public void init(Input<?> input, BEASTInterface beastObject, int itemNr, ExpandOption isExpandOption, boolean addButtons) {
m_beastObject = beastObject;
m_input = input;
m_bAddButtons = addButtons;
this.itemNr = itemNr;
addInputLabel();
m_selectBeastObjectBox = new JComboBox<>(valuesString);
setSelection();
String selectString = input.get().toString();
m_selectBeastObjectBox.setSelectedItem(selectString);
m_selectBeastObjectBox.addActionListener(e -> {
int i = m_selectBeastObjectBox.getSelectedIndex();
if (i == OTHER) {
setSelection();
return;
}
try {
setValue(_values[i]);
// lm_input.setValue(selected, m_beastObject);
} catch (Exception e1) {
e1.printStackTrace();
}
});
m_selectBeastObjectBox.setToolTipText(input.getHTMLTipText());
add(m_selectBeastObjectBox);
add(Box.createGlue());
}
private void setSelection() {
Double value = (Double) m_input.get();
m_selectBeastObjectBox.setSelectedIndex(OTHER);
for (int i = 0; i < _values.length; i++) {
if (value.equals(_values[i])) {
m_selectBeastObjectBox.setSelectedIndex(i);
}
}
}
};
editor.init(((GeneTreeForSpeciesTreeDistribution) m_beastObject).ploidyInput, m_beastObject, -1, ExpandOption.FALSE, true);
return editor;
}
use of beast.core.Input in project beast2 by CompEvol.
the class XMLParserUtils method listInputs.
// replace
/**
* return list of input types specified by Inputs or Param annotations
* @param clazz Class to generate the list for
* @param beastObject instantiation of the class, or null if not available
* @return
* @throws InstantiationException
* @throws IllegalAccessException
* @throws SecurityException
* @throws NoSuchMethodException
* @throws IllegalArgumentException
*/
public static List<InputType> listInputs(Class<?> clazz, BEASTInterface beastObject) throws InstantiationException, IllegalAccessException, IllegalArgumentException, NoSuchMethodException, SecurityException {
List<InputType> inputTypes = new ArrayList<>();
// First, collect Input members
try {
if (beastObject == null) {
beastObject = (BEASTInterface) clazz.newInstance();
}
List<Input<?>> inputs = null;
inputs = beastObject.listInputs();
for (Input<?> input : inputs) {
if (!(input instanceof InputForAnnotatedConstructor)) {
try {
// force class types to be determined
if (input.getType() == null) {
input.determineClass(beastObject);
}
inputTypes.add(new InputType(input.getName(), input.getType(), true, input.defaultValue));
} catch (Exception e) {
// seems safe to ignore
e.printStackTrace();
}
}
}
} catch (InstantiationException e) {
// this can happen if there is no constructor without arguments,
// e.g. when there are annotated constructors only
}
// Second, collect types of annotated constructor
Constructor<?>[] allConstructors = clazz.getDeclaredConstructors();
for (Constructor<?> ctor : allConstructors) {
Annotation[][] annotations = ctor.getParameterAnnotations();
List<Param> paramAnnotations = new ArrayList<>();
for (Annotation[] a0 : annotations) {
for (Annotation a : a0) {
if (a instanceof Param) {
paramAnnotations.add((Param) a);
}
}
}
Class<?>[] types = ctor.getParameterTypes();
Type[] gtypes = ctor.getGenericParameterTypes();
if (types.length > 0 && paramAnnotations.size() > 0) {
int offset = 0;
if (types.length == paramAnnotations.size() + 1) {
offset = 1;
}
for (int i = 0; i < paramAnnotations.size(); i++) {
Param param = paramAnnotations.get(i);
Type type = types[i + offset];
Class<?> clazz2 = null;
try {
clazz2 = Class.forName(type.getTypeName());
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (clazz2.isAssignableFrom(List.class)) {
Type[] genericTypes2 = ((ParameterizedType) gtypes[i + offset]).getActualTypeArguments();
Class<?> theClass = (Class<?>) genericTypes2[0];
InputType t = new InputType(param.name(), theClass, false, param.defaultValue());
inputTypes.add(t);
} else {
InputType t = new InputType(param.name(), types[i + offset], false, param.defaultValue());
inputTypes.add(t);
}
}
}
}
return inputTypes;
}
use of beast.core.Input in project beast2 by CompEvol.
the class XMLProducer method beastObjectToXML.
/**
* produce elements for a beast object with name name, putting results in buf.
* It tries to create XML conforming to the XML transformation rules (see XMLParser)
* that is moderately readable.
* @throws ClassNotFoundException
*/
@SuppressWarnings("rawtypes")
void beastObjectToXML(BEASTInterface beastObject, StringBuffer buf, String name, boolean isTopLevel) throws ClassNotFoundException {
// determine element name, default is input, otherswise find one of the defaults
String elementName = "input";
for (String key : element2ClassMap.keySet()) {
String className = element2ClassMap.get(key);
Class _class = Class.forName(className);
if (_class.equals(beastObject.getClass())) {
elementName = key;
}
}
if (isTopLevel) {
elementName = XMLParser.RUN_ELEMENT;
}
for (int i = 0; i < indent; i++) {
buf.append(" ");
}
indent++;
// open element
buf.append("<").append(elementName);
if (beastObject.getID() == null) {
String id = beastObject.getClass().getName();
if (id.contains(".")) {
id = id.substring(id.lastIndexOf('.') + 1);
}
if (IDs.contains(id)) {
int k = 1;
while (IDs.contains(id + k)) {
k++;
}
id = id + k;
}
beastObject.setID(id);
}
boolean skipInputs = false;
// isDone.contains(beastObject) fails when BEASTObjects override equals(), so use a stream with == instead
if (isDone.stream().anyMatch(x -> x == beastObject)) {
// XML is already produced, we can idref it
buf.append(" idref='" + normalise(beastObject.getID()) + "'");
skipInputs = true;
} else {
// see whether a reasonable id can be generated
if (beastObject.getID() != null && !beastObject.getID().equals("")) {
String id = beastObject.getID();
// ensure ID is unique, if not add index behind
uniqueID(id, buf);
}
isDone.add(beastObject);
}
String className = beastObject.getClass().getName();
if (skipInputs == false && (!element2ClassMap.containsKey(elementName) || !element2ClassMap.get(elementName).equals(className))) {
// only add spec element if it cannot be deduced otherwise (i.e., by idref or default mapping
buf.append(" spec='" + className + "'");
}
if (name != null && !name.equals(elementName)) {
// only add name element if it differs from element = default name
buf.append(" name='" + name + "'");
}
if (!skipInputs) {
// process inputs of this beast object
// first, collect values as attributes
List<Input<?>> inputs = beastObject.listInputs();
for (Input<?> input : inputs) {
Object value = input.get();
inputToXML(input, value, beastObject, buf, true);
}
// next, collect values as input elements
StringBuffer buf2 = new StringBuffer();
for (Input input : inputs) {
Object value = input.get();
inputToXML(input, value, beastObject, buf2, false);
}
if (buf2.length() == 0) {
// if nothing was added by the inputs, close element
indent--;
buf.append("/>\n");
} else {
// add contribution of inputs
if (buf2.indexOf("<") >= 0) {
buf.append(">\n");
buf.append(buf2);
indent--;
for (int i = 0; i < indent; i++) {
buf.append(" ");
}
} else {
buf.append(">");
buf.append(buf2.toString().trim());
indent--;
}
// add closing element
buf.append("</" + elementName + ">\n");
}
} else {
// close element
indent--;
buf.append("/>\n");
}
if (indent < 2) {
buf.append("\n");
}
}
use of beast.core.Input in project beast2 by CompEvol.
the class DocMaker method getType.
// getHTML
/**
* determine type of input of a plug in with name name
*/
String getType(BEASTObject beastObject, String name) {
try {
Field[] fields = beastObject.getClass().getFields();
for (int i = 0; i < fields.length; i++) {
if (fields[i].getType().isAssignableFrom(Input.class)) {
final Input<?> input = (Input<?>) fields[i].get(beastObject);
if (input.getName().equals(name)) {
Type t = fields[i].getGenericType();
Type[] genericTypes = ((ParameterizedType) t).getActualTypeArguments();
if (input.getType() != null) {
return (input.getType().isAssignableFrom(BEASTObject.class) ? "<a href='" + input.getType().getName() + ".html'>" : "") + input.getType().getName() + (input.get() != null && input.get() instanceof List<?> ? "***" : "") + (input.getType().isAssignableFrom(BEASTObject.class) ? "</a>" : "");
}
if (input.get() != null && input.get() instanceof List<?>) {
Type[] genericTypes2 = ((ParameterizedType) genericTypes[0]).getActualTypeArguments();
Class<?> _class = (Class<?>) genericTypes2[0];
Object o = null;
try {
o = Class.forName(_class.getName()).newInstance();
} catch (Exception e) {
}
if (o != null && o instanceof BEASTObject) {
return "<a href='" + _class.getName() + ".html'>" + _class.getName() + "***</a>";
} else {
return _class.getName() + "***";
}
} else {
Class<?> genericType = (Class<?>) genericTypes[0];
Class<?> _class = genericType;
Object o = null;
try {
o = Class.forName(_class.getName()).newInstance();
} catch (Exception e) {
}
if (o != null && o instanceof BEASTObject) {
return "<a href='" + _class.getName() + ".html'>" + _class.getName() + "</a>";
} else {
return _class.getName();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return "?";
}
use of beast.core.Input 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