Search in sources :

Example 76 with BEASTInterface

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

the class JSONParser method createObject.

// checkType
/**
 * create a BEAST object based on the info in the node.
 * @param node
 * @param className default class name -- this means a spec attribute does not need to be
 * specified if all outputs of this BEAST object have as Input type the class of this object.
 * @return
 * @throws JSONParserException
 */
BEASTInterface createObject(JSONObject node, String className) throws JSONParserException {
    // try the IDMap first
    String ID = getID(node);
    if (ID != null) {
        if (IDMap.containsKey(ID)) {
            BEASTInterface beastObject = IDMap.get(ID);
            if (checkType(className, beastObject)) {
                return beastObject;
            }
            throw new JSONParserException(node, "id=" + ID + ". Expected object of type " + className + " instead of " + beastObject.getClass().getName(), 105);
        }
    }
    String IDRef = getIDRef(node);
    if (IDRef != null) {
        // produce warning if there are other attributes than idref
        if (node.keySet().size() > 1) {
            // check if there is just 1 attribute
            Log.warning.println("Element " + getAttribute((JSONObject) node.getParent(), "name") + " found with idref='" + IDRef + "'. All other attributes are ignored.\n");
        }
        if (IDMap.containsKey(IDRef)) {
            BEASTInterface beastObject = IDMap.get(IDRef);
            if (checkType(className, beastObject)) {
                return beastObject;
            }
            throw new JSONParserException(node, "id=" + IDRef + ". Expected object of type " + className + " instead of " + beastObject.getClass().getName(), 106);
        } else if (IDNodeMap.containsKey(IDRef)) {
            BEASTInterface beastObject = createObject(IDNodeMap.get(IDRef), className);
            if (checkType(className, beastObject)) {
                return beastObject;
            }
            throw new JSONParserException(node, "id=" + IDRef + ". Expected object of type " + className + " instead of " + beastObject.getClass().getName(), 107);
        }
        throw new JSONParserException(node, "Could not find object associated with idref " + IDRef, 170);
    }
    // it's not in the ID map yet, so we have to create a new object
    String specClass = className;
    String elementName = getElementName(node);
    if (element2ClassMap.containsKey(elementName)) {
        specClass = element2ClassMap.get(elementName);
    }
    String spec = getAttribute(node, "spec");
    if (spec != null) {
        specClass = spec;
    }
    String clazzName = null;
    // determine clazzName from specName, taking name spaces in account
    for (String nameSpace : nameSpaces) {
        if (clazzName == null) {
            if (XMLParserUtils.beastObjectNames.contains(nameSpace + specClass)) {
                clazzName = nameSpace + specClass;
                break;
            }
        }
    }
    if (clazzName == null) {
        // try to create the old-fashioned way by creating the class
        boolean isDone = false;
        for (final String nameSpace : nameSpaces) {
            try {
                if (!isDone) {
                    Class.forName(nameSpace + specClass);
                    clazzName = nameSpace + specClass;
                    isDone = true;
                }
            } catch (ClassNotFoundException e) {
            // class does not exist -- try another namespace
            }
        }
    }
    if (clazzName == null) {
        throw new JSONParserException(node, "Class could not be found. Did you mean " + XMLParserUtils.guessClass(specClass) + "?", 1017);
    // throw new ClassNotFoundException(specClass);
    }
    // sanity check
    try {
        Class<?> clazz = Class.forName(clazzName);
        if (!BEASTInterface.class.isAssignableFrom(clazz)) {
            // } else {
            throw new JSONParserException(node, "Expected object to be instance of BEASTObject", 108);
        // }
        }
    } catch (ClassNotFoundException e1) {
        // should never happen since clazzName is in the list of classes collected by the PackageManager
        e1.printStackTrace();
        throw new RuntimeException(e1);
    }
    // process inputs
    List<NameValuePair> inputInfo = parseInputs(node, clazzName);
    BEASTInterface beastObject = createBeastObject(node, ID, clazzName, inputInfo);
    // initialise
    if (initialise) {
        try {
            beastObject.determindClassOfInputs();
            beastObject.validateInputs();
            objectsWaitingToInit.add(new BEASTObjectWrapper(beastObject, node));
        // beastObject.initAndValidate();
        } catch (IllegalArgumentException e) {
            // next lines for debugging only
            // beastObject.validateInputs();
            // beastObject.initAndValidate();
            e.printStackTrace();
            throw new JSONParserException(node, "validate and intialize error: " + e.getMessage(), 110);
        }
    }
    return beastObject;
}
Also used : NameValuePair(beast.util.XMLParser.NameValuePair) JSONObject(org.json.JSONObject) BEASTInterface(beast.core.BEASTInterface)

Example 77 with BEASTInterface

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

the class JSONParser method createBeastObject.

/**
 * create BEASTInterface either using Inputs, or using annotated constructor *
 */
private BEASTInterface createBeastObject(JSONObject node, String ID, String clazzName, List<NameValuePair> inputInfo) throws JSONParserException {
    BEASTInterface beastObject = useAnnotatedConstructor(node, ID, clazzName, inputInfo);
    if (beastObject != null) {
        return beastObject;
    }
    // create new instance using class name
    Object o = null;
    try {
        Class<?> c = Class.forName(clazzName);
        o = c.newInstance();
    } catch (InstantiationException e) {
        // created for instance because it is abstract
        throw new JSONParserException(node, "Cannot instantiate class. Please check the spec attribute.", 1006);
    } catch (ClassNotFoundException e) {
    // ignore -- class was found in beastObjectNames before
    } catch (IllegalAccessException e) {
        // T O D O Auto-generated catch block
        e.printStackTrace();
        throw new JSONParserException(node, "Cannot access class. Please check the spec attribute.", 1011);
    }
    // set id
    beastObject = (BEASTInterface) o;
    beastObject.setID(ID);
    // hack required to make log-parsing easier
    if (o instanceof State) {
        state = (State) o;
    }
    // process inputs for annotated constructors
    for (NameValuePair pair : inputInfo) {
        setInput(node, beastObject, pair.name, pair.value);
    }
    // fill in missing inputs, if an input provider is available
    try {
        if (requiredInputProvider != null) {
            for (Input<?> input : beastObject.listInputs()) {
                if (input.get() == null && input.getRule() == Validate.REQUIRED) {
                    Object o2 = requiredInputProvider.createInput(beastObject, input, partitionContext);
                    if (o2 != null) {
                        input.setValue(o2, beastObject);
                    }
                }
            }
        }
    } catch (Exception e) {
        throw new JSONParserException(node, e.getMessage(), 1008);
    }
    // sanity check: all attributes should be valid input names
    if (!(beastObject instanceof Map)) {
        for (String name : node.keySet()) {
            if (!(name.equals("id") || name.equals("idref") || name.equals("spec") || name.equals("name"))) {
                try {
                    beastObject.getInput(name);
                } catch (Exception e) {
                    throw new JSONParserException(node, e.getMessage(), 1009);
                }
            }
        }
    }
    // make sure object o is in outputs of inputs
    for (NameValuePair pair : inputInfo) {
        if (pair.value instanceof BEASTInterface) {
            ((BEASTInterface) pair.value).getOutputs().add((BEASTInterface) o);
        }
    }
    register(node, beastObject);
    return beastObject;
}
Also used : NameValuePair(beast.util.XMLParser.NameValuePair) JSONException(org.json.JSONException) IOException(java.io.IOException) InvocationTargetException(java.lang.reflect.InvocationTargetException) State(beast.core.State) BEASTInterface(beast.core.BEASTInterface) JSONObject(org.json.JSONObject) HashMap(java.util.HashMap) Map(beast.core.parameter.Map)

Example 78 with BEASTInterface

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

the class JSONParser method main.

/**
 * parses file and formats it using the XMLProducer *
 */
public static void main(String[] args) {
    try {
        // redirect stdout to stderr
        PrintStream out = System.out;
        System.setOut(System.err);
        // parse the file
        JSONParser parser = new JSONParser();
        BEASTInterface beastObject = parser.parseFile(new File(args[0]));
        // restore stdout
        System.setOut(out);
        if (args.length > 1) {
            FileWriter outfile = new FileWriter(args[1]);
            outfile.write(new XMLProducer().toXML(beastObject));
            outfile.close();
        } else {
            System.out.println(new XMLProducer().toXML(beastObject));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : PrintStream(java.io.PrintStream) FileWriter(java.io.FileWriter) BEASTInterface(beast.core.BEASTInterface) File(java.io.File) JSONException(org.json.JSONException) IOException(java.io.IOException) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 79 with BEASTInterface

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

the class XMLProducer method getPackagesAndVersions.

/**
 * traverse model graph starting at o, and collect packageAndVersion strings
 * along the way.
 */
private void getPackagesAndVersions(BEASTInterface o, Set<String> packagesAndVersions) {
    Map<String, String> classToPackageMap = PackageManager.getClassToPackageMap();
    String packageAndVersion = classToPackageMap.get(o.getClass().getName());
    if (packageAndVersion != null) {
        packagesAndVersions.add(packageAndVersion);
    }
    for (BEASTInterface o2 : o.listActiveBEASTObjects()) {
        getPackagesAndVersions(o2, packagesAndVersions);
    }
}
Also used : BEASTInterface(beast.core.BEASTInterface)

Example 80 with BEASTInterface

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

the class BeautiDoc method addAlignmentWithSubnet.

public BEASTInterface addAlignmentWithSubnet(PartitionContext context, BeautiSubTemplate template) {
    BEASTInterface data = template.createSubNet(context, true);
    alignments.add((Alignment) data);
    // re-determine partitions
    determinePartitions();
    return data;
}
Also used : 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