Search in sources :

Example 16 with BEASTInterface

use of beast.core.BEASTInterface in project beast2 by CompEvol.

the class BeautiSubTemplate method createSubNet.

public BEASTInterface createSubNet(PartitionContext partition, List<BEASTInterface> list, int item, boolean init) {
    removeSubNet(list.get(item));
    if (xml == null) {
        // this is the NULL_TEMPLATE
        list.set(item, null);
        return null;
    }
    BEASTInterface o = createSubNet(partition, doc.pluginmap, init);
    list.set(item, o);
    return o;
}
Also used : BEASTInterface(beast.core.BEASTInterface)

Example 17 with BEASTInterface

use of beast.core.BEASTInterface 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;
}
Also used : GenericTreeLikelihood(beast.evolution.likelihood.GenericTreeLikelihood) SiteModel(beast.evolution.sitemodel.SiteModel) Logger(beast.core.Logger) FilteredAlignment(beast.evolution.alignment.FilteredAlignment) TransformerException(javax.xml.transform.TransformerException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SAXException(org.xml.sax.SAXException) Base(beast.evolution.sitemodel.SiteModelInterface.Base) SubstitutionModel(beast.evolution.substitutionmodel.SubstitutionModel) FilteredAlignment(beast.evolution.alignment.FilteredAlignment) Alignment(beast.evolution.alignment.Alignment) BEASTInterface(beast.core.BEASTInterface) XMLParser(beast.util.XMLParser)

Example 18 with BEASTInterface

use of beast.core.BEASTInterface in project beast2 by CompEvol.

the class BeautiSubTemplate method removeSubNet.

void removeSubNet(Object o) {
    if (o == null) {
        // nothing to do
        return;
    }
    BEASTInterface beastObject = null;
    if (o instanceof BEASTInterface) {
        beastObject = (BEASTInterface) o;
    }
    // find template that created this beastObject
    String id = beastObject.getID();
    // String partition = BeautiDoc.parsePartition(id);
    if (id.indexOf(".") > 0) {
        id = id.substring(0, id.indexOf("."));
    }
    BeautiSubTemplate template = null;
    for (BeautiSubTemplate template2 : doc.beautiConfig.subTemplatesInput.get()) {
        if (template2.matchesName(id)) {
            template = template2;
            break;
        }
    }
    if (template == null) {
        throw new RuntimeException("Cannot find template for removing " + beastObject.getID());
    }
    PartitionContext context = doc.getContextFor(beastObject);
    removeSubNet(template, context);
}
Also used : BEASTInterface(beast.core.BEASTInterface)

Example 19 with BEASTInterface

use of beast.core.BEASTInterface 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;
}
Also used : Input(beast.core.Input) InputEditor(beast.app.draw.InputEditor) BEASTInterface(beast.core.BEASTInterface)

Example 20 with BEASTInterface

use of beast.core.BEASTInterface in project beast2 by CompEvol.

the class XMLParser method useAnnotatedConstructor.

@SuppressWarnings({ "rawtypes", "unchecked" })
private BEASTInterface useAnnotatedConstructor(Node node, String _id, String clazzName, List<NameValuePair> inputInfo) throws XMLParserException {
    Class<?> clazz = null;
    try {
        clazz = Class.forName(clazzName);
    } catch (ClassNotFoundException e) {
        // cannot get here, since we checked the class existed before
        e.printStackTrace();
    }
    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);
                }
            }
        }
        for (NameValuePair pair : inputInfo) {
            pair.processed = false;
        }
        Class<?>[] types = ctor.getParameterTypes();
        // Type[] gtypes = ctor.getGenericParameterTypes();
        if (types.length > 0 && paramAnnotations.size() == types.length) {
            try {
                Object[] args = new Object[types.length];
                for (int i = 0; i < types.length; i++) {
                    Param param = paramAnnotations.get(i);
                    Type type = types[i];
                    if (type.getTypeName().equals("java.util.List")) {
                        if (args[i] == null) {
                            // no need to parameterise list due to type erasure
                            args[i] = new ArrayList();
                        }
                        List<Object> values = getListOfValues(param, inputInfo);
                        ((List) args[i]).addAll(values);
                    } else {
                        args[i] = getValue(param, types[i], inputInfo);
                        // and the args[i] is a String -- we need to invoke the String constructor
                        if (args[i].getClass().equals(String.class) && types[i] != String.class) {
                            for (Constructor<?> argctor : types[i].getDeclaredConstructors()) {
                                Class<?>[] argtypes = argctor.getParameterTypes();
                                if (argtypes.length == 1 && argtypes[0] == String.class) {
                                    Object o = argctor.newInstance(args[i]);
                                    args[i] = o;
                                    break;
                                }
                            }
                        }
                    }
                }
                // ensure all inputs are used
                boolean allUsed = true;
                for (NameValuePair pair : inputInfo) {
                    if (!pair.processed) {
                        allUsed = false;
                    }
                }
                if (allUsed) {
                    try {
                        Object o = ctor.newInstance(args);
                        BEASTInterface beastObject = (BEASTInterface) o;
                        register(node, beastObject);
                        return beastObject;
                    } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                        throw new XMLParserException(node, "Could not create object: " + e.getMessage(), 1012);
                    }
                }
            } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            // we get here when a param value cannot be constructed from a default value
            // let's try the next constructor (if any)
            }
        }
    }
    return null;
}
Also used : ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) NodeList(org.w3c.dom.NodeList) List(java.util.List) Constructor(java.lang.reflect.Constructor) Annotation(java.lang.annotation.Annotation) InvocationTargetException(java.lang.reflect.InvocationTargetException) Type(java.lang.reflect.Type) Param(beast.core.Param) BEASTInterface(beast.core.BEASTInterface)

Aggregations

BEASTInterface (beast.core.BEASTInterface)111 ArrayList (java.util.ArrayList)43 List (java.util.List)27 IOException (java.io.IOException)22 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)18 SAXException (org.xml.sax.SAXException)18 NodeList (org.w3c.dom.NodeList)13 Input (beast.core.Input)12 MRCAPrior (beast.math.distributions.MRCAPrior)12 File (java.io.File)12 InvocationTargetException (java.lang.reflect.InvocationTargetException)12 XMLParser (beast.util.XMLParser)11 TransformerException (javax.xml.transform.TransformerException)11 Alignment (beast.evolution.alignment.Alignment)10 XMLParserException (beast.util.XMLParserException)10 BEASTObject (beast.core.BEASTObject)9 Distribution (beast.core.Distribution)9 XMLProducer (beast.util.XMLProducer)9 CompoundDistribution (beast.core.util.CompoundDistribution)8 BranchRateModel (beast.evolution.branchratemodel.BranchRateModel)8