Search in sources :

Example 31 with XMLParser

use of beast.util.XMLParser in project bacter by tgvaughan.

the class SimulatedACGTest method test5Taxon.

@Test
public void test5Taxon() throws Exception {
    Randomizer.setSeed(1);
    XMLParser parser = new XMLParser();
    beast.core.Runnable runnable = parser.parseFile(new File("examples/ACGsimulations/simulateACGs5taxon.xml"));
    runnable.run();
    List<Expectation> expectations = new ArrayList<>();
    expectations.add(new Expectation("acg.CFheight", 1.606, 1e-2));
    expectations.add(new Expectation("acg.CFlength", 4.181, 1e-2));
    expectations.add(new Expectation("acg.nConv", 21.0, 5e-2));
    LogAnalyser logAnalyser = new LogAnalyser("simulateACGs5taxon.stats", expectations);
    for (int i = 0; i < expectations.size(); i++) {
        assertTrue(expectations.get(i).isValid());
        assertTrue(expectations.get(i).isPassed());
    }
    Files.deleteIfExists(Paths.get("simulateACGs5taxon.stats"));
    Files.deleteIfExists(Paths.get("simulateACGs5taxon.converted"));
    Files.deleteIfExists(Paths.get("simulateACGs5taxon.trees"));
}
Also used : LogAnalyser(test.beast.beast2vs1.trace.LogAnalyser) ArrayList(java.util.ArrayList) XMLParser(beast.util.XMLParser) Expectation(test.beast.beast2vs1.trace.Expectation) File(java.io.File) Test(org.junit.Test)

Example 32 with XMLParser

use of beast.util.XMLParser in project bacter by tgvaughan.

the class CFConvSwapExperiment method main.

public static void main(String[] args) throws Exception {
    // Load model
    XMLParser parser = new XMLParser();
    MCMC mcmc = (MCMC) parser.parseFile(new File("inferencePreSimulatedData.xml"));
    State state = mcmc.startStateInput.get();
    state.setStateFileName("problem.state");
    state.restoreFromFile();
    double oldPosterior = state.robustlyCalcPosterior(mcmc.posteriorInput.get());
    ConversionGraph acg = (ConversionGraph) state.getStateNode(0);
    PrintStream ps = new PrintStream("proposal.trees");
    ps.println(acg);
    Node srcNode = acg.getNode(3);
    Node srcNodeS = getSibling(srcNode);
    Node destNode = acg.getNode(6);
    double t_srcNodeP = srcNode.getParent().getHeight();
    disconnectEdge(acg, srcNode);
    Locus locus = acg.getLoci().get(0);
    Conversion convToReplace = acg.getConversions(locus).get(27);
    acg.deleteConversion(convToReplace);
    Node srcNodeP = srcNode.getParent();
    connectEdge(acg, srcNode, destNode, convToReplace.getHeight2());
    // Move Conversions
    for (Conversion conv : acg.getConversions(locus)) {
        boolean moved = false;
        if (conv.getNode1() == srcNode && conv.getHeight1() > srcNodeP.getHeight()) {
            conv.setNode1(destNode);
            moved = true;
        }
        if (conv.getNode2() == srcNode && conv.getHeight2() > srcNodeP.getHeight()) {
            conv.setNode2(destNode);
            moved = true;
        }
        if (moved) {
            while (conv.getHeight1() > conv.getNode1().getParent().getHeight()) conv.setNode1(conv.getNode1().getParent());
            while (conv.getHeight2() > conv.getNode2().getParent().getHeight()) conv.setNode2(conv.getNode2().getParent());
        }
    }
    Conversion convNew = new Conversion();
    convNew.setLocus(locus);
    convNew.setStartSite(0);
    convNew.setEndSite(4000);
    convNew.setNode1(srcNode);
    convNew.setNode2(srcNodeS);
    convNew.setHeight1(convToReplace.getHeight1());
    convNew.setHeight2(t_srcNodeP);
    acg.addConversion(convNew);
    ps.println(acg);
    double newPosterior = state.robustlyCalcPosterior(mcmc.posteriorInput.get());
    System.out.println(newPosterior - oldPosterior);
// state.setStateFileName("proposal.state");
// state.storeToFile(1);
// Open state file
}
Also used : PrintStream(java.io.PrintStream) Node(beast.evolution.tree.Node) XMLParser(beast.util.XMLParser) Locus(bacter.Locus) File(java.io.File) ConversionGraph(bacter.ConversionGraph) Conversion(bacter.Conversion)

Example 33 with XMLParser

use of beast.util.XMLParser in project beast2 by CompEvol.

the class BeautiAlignmentProvider method getXMLData.

public static BEASTInterface getXMLData(File file) {
    String xml = "";
    try {
        // parse as BEAST 2 xml fragment
        XMLParser parser = new XMLParser();
        BufferedReader fin = new BufferedReader(new FileReader(file));
        while (fin.ready()) {
            xml += fin.readLine() + "\n";
        }
        fin.close();
        BEASTInterface runnable = parser.parseBareFragment(xml, false);
        BEASTInterface alignment = getAlignment(runnable);
        alignment.initAndValidate();
        return alignment;
    } catch (Exception ex) {
        // attempt to parse as BEAST 1 xml
        try {
            String ID = file.getName();
            ID = ID.substring(0, ID.lastIndexOf('.')).replaceAll("\\..*", "");
            BEASTInterface alignment = parseBeast1XML(ID, xml);
            if (alignment != null) {
                alignment.setID(file.getName().substring(0, file.getName().length() - 4).replaceAll("\\..*", ""));
            }
            return alignment;
        } catch (Exception ex2) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(null, "Loading of " + file.getName() + " failed: " + ex.getMessage() + "\n" + ex2.getMessage());
        }
        return null;
    }
}
Also used : BufferedReader(java.io.BufferedReader) FileReader(java.io.FileReader) BEASTInterface(beast.core.BEASTInterface) XMLParser(beast.util.XMLParser) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SAXException(org.xml.sax.SAXException)

Example 34 with XMLParser

use of beast.util.XMLParser in project beast2 by CompEvol.

the class BeautiConfig method initAndValidate.

@Override
public void initAndValidate() {
    parseSet(inlineInput.get(), null, inlineBEASTObject);
    parseSet(collapsedInput.get(), null, collapsedBEASTObjects);
    inlineBEASTObject.addAll(collapsedBEASTObjects);
    // parseSet(m_hidePanels.get(), "TAXON_SETS_PANEL,TIP_DATES_PANEL,PRIORS_PANEL,OPERATORS_PANEL", g_sHidePanels);
    parseSet(suppressInputs.get(), null, suppressBEASTObjects);
    parseSet(disableMenus.get(), null, disabledMenus);
    parseSet(disableButtons.get(), null, disabledButtons);
    parseMap(inputLabelMapInput.get(), inputLabelMap);
    parseMap(buttonLabelMapInput.get(), buttonLabelMap);
    // parseMap(m_editButtonStatus.get(), g_sEditButtonStatus);
    for (BeautiPanelConfig panel : panelsInput.get()) {
        panels.add(panel);
        // check for duplicates
        for (BeautiPanelConfig panel2 : panels) {
            if (panel2.nameInput.get().equals(panel.nameInput.get()) && panel2 != panel) {
                panels.remove(panels.size() - 1);
                break;
            }
        }
    }
    // InputEditor.setExpertMode(isExpertInput.get());
    subTemplates = subTemplatesInput.get();
    alignmentProvider = alignmentProviderInput.get();
    try {
        XMLParser parser = new XMLParser();
        hyperPriorTemplate = (BeautiSubTemplate) parser.parseBareFragment(HYPER_PRIOR_XML, true);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
Also used : XMLParser(beast.util.XMLParser)

Example 35 with XMLParser

use of beast.util.XMLParser in project beast2 by CompEvol.

the class BeastMCMC method parseArgs.

/**
 * parse command line arguments, and load file if specified
 * @throws IOException
 * @throws JSONException
 * @throws JSONParserException
 */
public void parseArgs(String[] args) throws IOException, XMLParserException, JSONException {
    int i = 0;
    boolean resume = false;
    boolean useStrictVersions = false;
    Map<String, String> parserDefinitions = new HashMap<>();
    File beastFile = null;
    try {
        while (i < args.length) {
            int old = i;
            if (i < args.length) {
                if (args[i].equals("")) {
                    i += 1;
                } else if (args[i].equals("-batch")) {
                    Logger.FILE_MODE = Logger.LogFileMode.only_new_or_exit;
                    i += 1;
                } else if (args[i].equals("-resume")) {
                    resume = true;
                    Logger.FILE_MODE = Logger.LogFileMode.resume;
                    System.setProperty("beast.resume", "true");
                    System.setProperty("beast.debug", "false");
                    i += 1;
                } else if (args[i].equals("-overwrite")) {
                    Logger.FILE_MODE = Logger.LogFileMode.overwrite;
                    i += 1;
                } else if (args[i].equals("-seed")) {
                    if (args[i + 1].equals("random")) {
                        m_nSeed = Randomizer.getSeed();
                    } else {
                        m_nSeed = Long.parseLong(args[i + 1]);
                    }
                    i += 2;
                } else if (args[i].equals("-threads")) {
                    m_nThreads = Integer.parseInt(args[i + 1]);
                    g_exec = Executors.newFixedThreadPool(m_nThreads);
                    i += 2;
                // use BEAST environment variable to set Beast directories as colon separated list
                // } else if (args[i].equals("-beastlib")) {
                // ClassDiscovery.setJarPath(args[i + 1]);
                // i += 2;
                } else if (args[i].equals("-prefix")) {
                    System.setProperty("file.name.prefix", args[i + 1].trim());
                    i += 2;
                } else if (args[i].equals("-D")) {
                    String[] strs = args[i + 1].split(",");
                    for (String str : strs) {
                        String[] strs2 = str.split("=");
                        if (strs2.length != 2) {
                            throw new IllegalArgumentException("Argument \"" + str + "\" is not well-formed: expecting name=value pairs");
                        }
                        String name = strs2[0];
                        String value = strs2[1];
                        parserDefinitions.put(name, value);
                    }
                    i += 2;
                } else if (args[i].equals("-strictversions")) {
                    useStrictVersions = true;
                    i += 1;
                }
                if (i == old) {
                    if (i == args.length - 1) {
                        beastFile = new File(args[i]);
                        i++;
                    } else {
                        throw new IllegalArgumentException("Wrong argument");
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new IllegalArgumentException("Error parsing command line arguments: " + Arrays.toString(args) + "\nArguments ignored\n\n" + getUsage());
    }
    if (beastFile == null) {
        // Not resuming so get starting options...
        List<String> MCMCargs = new ArrayList<>();
        Version version = new BEASTVersion2();
        String titleString = "<html><center><p>Bayesian Evolutionary Analysis Sampling Trees<br>" + "Version " + version.getVersionString() + ", " + version.getDateString() + "</p></center></html>";
        javax.swing.Icon icon = IconUtils.getIcon(BeastMain.class, "images/beast.png");
        String nameString = "BEAST " + version.getVersionString();
        BeastDialog dialog = new BeastDialog(new JFrame(), titleString, icon);
        if (!dialog.showDialog(nameString, m_nSeed)) {
            return;
        }
        switch(dialog.getLogginMode()) {
            case 0:
                /* do not ovewrite */
                break;
            case 1:
                MCMCargs.add("-overwrite");
                break;
            case 2:
                MCMCargs.add("-resume");
                break;
        }
        MCMCargs.add("-seed");
        MCMCargs.add(dialog.getSeed() + "");
        if (dialog.getThreadPoolSize() > 0) {
            MCMCargs.add("-threads");
            MCMCargs.add(dialog.getThreadPoolSize() + "");
        }
        boolean useBeagle = dialog.useBeagle();
        boolean beagleShowInfo = false;
        long beagleFlags = 0;
        if (useBeagle) {
            beagleShowInfo = dialog.showBeagleInfo();
            if (dialog.preferBeagleCPU()) {
                beagleFlags |= BeagleFlag.PROCESSOR_CPU.getMask();
            }
            if (dialog.preferBeagleSSE()) {
                beagleFlags |= BeagleFlag.VECTOR_SSE.getMask();
            }
            if (dialog.preferBeagleGPU()) {
                beagleFlags |= BeagleFlag.PROCESSOR_GPU.getMask();
            }
            if (dialog.preferBeagleDouble()) {
                beagleFlags |= BeagleFlag.PRECISION_DOUBLE.getMask();
            }
            if (dialog.preferBeagleSingle()) {
                beagleFlags |= BeagleFlag.PRECISION_SINGLE.getMask();
            }
        }
        if (beagleFlags != 0) {
            System.setProperty("beagle.preferred.flags", Long.toString(beagleFlags));
        }
        if (!useBeagle) {
            System.setProperty("java.only", "true");
        }
        File inputFile = dialog.getInputFile();
        if (!beagleShowInfo && inputFile == null) {
            System.err.println("No input file specified");
            System.exit(1);
        }
        MCMCargs.add(inputFile.getAbsolutePath());
        // BeastStartDialog dlg = new BeastStartDialog();
        // if (dlg.m_bOK) {
        // parseArgs(dlg.getArgs());
        // }
        parseArgs(MCMCargs.toArray(new String[0]));
        return;
    }
    Log.warning.println("File: " + beastFile.getName() + " seed: " + m_nSeed + " threads: " + m_nThreads);
    if (resume) {
        Log.info.println("Resuming from file");
    }
    if (useStrictVersions) {
        // grab "required" attribute from beast spec
        if (beastFile.getPath().toLowerCase().endsWith(".json")) {
            throw new IllegalArgumentException("The -strictversions flag is not implemented for JSON files yet (only XML files are supported).");
        } else {
            BufferedReader fin = new BufferedReader(new FileReader(beastFile));
            StringBuffer buf = new StringBuffer();
            String str = null;
            int lineCount = 0;
            while (fin.ready() && lineCount < 100) {
                str = fin.readLine();
                buf.append(str);
                buf.append(' ');
            }
            fin.close();
            str = buf.toString();
            int start = str.indexOf("required=");
            if (start < 0) {
                throw new IllegalArgumentException("Could not find a 'required' attribute in the XML. Add the required attribute, or run without the -strictversions flag");
            }
            char c = str.charAt(start + 9);
            start += 10;
            int end = str.indexOf(c, start);
            String packages = str.substring(start, end);
            PackageManager.loadExternalJars(packages);
        }
    } else {
        PackageManager.loadExternalJars();
    }
    // parse xml
    Randomizer.setSeed(m_nSeed);
    if (beastFile.getPath().toLowerCase().endsWith(".json")) {
        m_runnable = new JSONParser(parserDefinitions).parseFile(beastFile);
    } else {
        try {
            m_runnable = new XMLParser(parserDefinitions).parseFile(beastFile);
        } catch (SAXException | ParserConfigurationException e) {
            throw new IllegalArgumentException(e);
        }
    }
    m_runnable.setStateFile(beastFile.getName() + ".state", resume);
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) SAXException(org.xml.sax.SAXException) Version(beast.app.util.Version) JFrame(javax.swing.JFrame) FileReader(java.io.FileReader) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) XMLParser(beast.util.XMLParser) JSONException(org.json.JSONException) XMLParserException(beast.util.XMLParserException) SAXException(org.xml.sax.SAXException) JSONParserException(beast.util.JSONParserException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) BeastDialog(beast.app.beastapp.BeastDialog) BufferedReader(java.io.BufferedReader) JSONParser(beast.util.JSONParser) File(java.io.File)

Aggregations

XMLParser (beast.util.XMLParser)46 File (java.io.File)36 ArrayList (java.util.ArrayList)29 Test (org.junit.Test)27 Expectation (test.beast.beast2vs1.trace.Expectation)23 LogAnalyser (test.beast.beast2vs1.trace.LogAnalyser)23 BEASTInterface (beast.core.BEASTInterface)11 XMLProducer (beast.util.XMLProducer)5 IOException (java.io.IOException)5 FilenameFilter (java.io.FilenameFilter)4 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)4 SAXException (org.xml.sax.SAXException)4 MCMC (beast.core.MCMC)3 Alignment (beast.evolution.alignment.Alignment)3 XMLParserException (beast.util.XMLParserException)3 BufferedReader (java.io.BufferedReader)3 FileReader (java.io.FileReader)3 Input (beast.core.Input)2 StateNode (beast.core.StateNode)2 CompoundDistribution (beast.core.util.CompoundDistribution)2