org.rosuda.REngine.REXPMismatchException Java Examples
The following examples show how to use
org.rosuda.REngine.REXPMismatchException.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Rsession.java From mzmine3 with GNU General Public License v2.0 | 6 votes |
/** * Get R command text output * * @param command R command returning text * @return String */ public String asString(String command) { try { String s = silentlyEval("paste(capture.output(print(" + command + ")),collapse='\\n')").asString(); return s; } catch (REXPMismatchException ex) { return ex.getMessage(); } /* * String[] lines = null; try { lines = silentlyEval("capture.output( " + command + * ")").asStrings(); } catch (REXPMismatchException e) { return e.getMessage(); } if (lines == * null) { return ""; } StringBuffer sb = new StringBuffer(); for (String l : lines) { * sb.append(l); sb.append("\n"); } return sb.toString(); */ }
Example #2
Source File: Rsession.java From mzmine2 with GNU General Public License v2.0 | 6 votes |
public static String cat(RList list) { try { StringBuffer sb = new StringBuffer("\t"); double[][] data = new double[list.names.size()][]; for (int i = 0; i < list.size(); i++) { String n = list.keyAt(i); sb.append(n + "\t"); data[i] = list.at(n).asDoubles(); } sb.append("\n"); for (int i = 0; i < data[0].length; i++) { sb.append((i + 1) + "\t"); for (int j = 0; j < data.length; j++) { sb.append(data[j][i] + "\t"); } sb.append("\n"); } return sb.toString(); } catch (REXPMismatchException r) { return "(Not a numeric dataframe)\n" + new REXPList(list).toDebugString(); } }
Example #3
Source File: Rsession.java From mzmine2 with GNU General Public License v2.0 | 6 votes |
/** * @return available R commands */ public String[] listCommands() { silentlyEval( ".keyWords <- function() {n <- length(search());result <- c();for (i in 1:n) {result <- c(result,ls(pos=i,all.names=TRUE))}; result}"); REXP rexp = silentlyEval(".keyWords()"); String as[] = null; try { if (rexp != null && (as = rexp.asStrings()) != null) { return as; } else { return null; } } catch (REXPMismatchException ex) { log(HEAD_ERROR + ex.getMessage() + "\n listCommands()", Level.ERROR); return null; } }
Example #4
Source File: Rsession.java From mzmine2 with GNU General Public License v2.0 | 6 votes |
/** * Check for package loaded in R environment. * * @param pack R package name * @return package loading status */ public boolean isPackageLoaded(String pack) { silentlyVoidEval(loadedpacks + "<-.packages()", false); boolean isloaded = false; try { REXP i = silentlyEval("is.element(set=" + loadedpacks + ",el='" + pack + "')"); if (i != null) { isloaded = i.asInteger() == 1; } } catch (REXPMismatchException ex) { log(HEAD_ERROR + ex.getMessage() + "\n isPackageLoaded(String pack=" + pack + ")", Level.ERROR); } if (isloaded) { log(_PACKAGE_ + pack + " is loaded.", Level.INFO); } else { log(_PACKAGE_ + pack + " is not loaded.", Level.INFO); } // silentlyEval("rm(" + loadedpacks + ")"); return isloaded; }
Example #5
Source File: DataMiningRExecutor.java From Knowage-Server with GNU Affero General Public License v3.0 | 6 votes |
/** * Prepare REngine and user workspace environmet * * @param dataminingInstance * @param userProfile * @throws IOException * @throws REXPMismatchException * @throws REngineException * @throws NamingException */ private void setupEnvonmentForExternal() throws IOException, REngineException, REXPMismatchException, NamingException { logger.debug("IN"); // new R-engine re = createREngineInstanceWithWork(); if (re == null) { logger.error("Cannot load R"); return; } re.parseAndEval("setwd(\"" + DataMiningUtils.UPLOADED_FILE_PATH + DataMiningConstants.DATA_MINING_EXTERNAL_CODE_PATH + "\")"); logger.debug("Set working directory"); // commandsExecutor.setRe(re); datasetsExecutor.setRe(re); outputExecutor.setRe(re); scriptExecutor.setRe(re); fileExecutor.setRe(re); logger.debug("OUT"); }
Example #6
Source File: RDatasetsExecutor.java From Knowage-Server with GNU Affero General Public License v3.0 | 6 votes |
protected void updateDataset(DataMiningDataset ds) throws IOException, REngineException, REXPMismatchException { logger.debug("IN"); File fileDSDir = new File(DataMiningUtils.getUserResourcesPath(profile) + ds.getName()); // /find file in dir File[] dsfiles = fileDSDir.listFiles(); if (dsfiles != null) { String fileDSPath = dsfiles[0].getPath(); fileDSPath = fileDSPath.replaceAll("\\\\", "/"); logger.debug("File ds path " + fileDSPath); String stringToEval = null; if (ds.getSubstituteLabel() != null && ds.getSubstituteLabel() != "") // functionsCatalog executeWithNewData { stringToEval = ds.getSubstituteLabel() + "<-read." + ds.getReadType() + "(\"" + fileDSPath + "\"," + ds.getOptions() + ");"; } else // dataminingEngine e functionsCatalog executeDemo { stringToEval = ds.getName() + "<-read." + ds.getReadType() + "(\"" + fileDSPath + "\"," + ds.getOptions() + ");"; } logger.debug("R code to eval " + stringToEval); re.parseAndEval(stringToEval); } logger.debug("OUT"); }
Example #7
Source File: Rsession.java From mzmine2 with GNU General Public License v2.0 | 6 votes |
/** * * @param robject R object name * @return R type of object */ public String typeOf(String robject) { if (robject == null) { return "NULL"; } for (String t : types) { REXP is = silentlyEval("is." + t + "(" + robject + ")"); try { if (is != null && is.asInteger() == 1) { return t; } } catch (REXPMismatchException ex) { log(HEAD_ERROR + "[typeOf] " + robject + " type unknown.", Level.ERROR); return null; } } return "unknown"; }
Example #8
Source File: Rsession.java From mzmine2 with GNU General Public License v2.0 | 6 votes |
/** * Set R list in R env. * * @param varname R list name * @param data numeric data in list * @param names names of columns */ public boolean set(String varname, double[][] data, String... names) { RList list = buildRList(data, names); log(HEAD_SET + varname + " <- " + toString(list), Level.INFO); try { synchronized (connection) { connection.assign(varname, REXP.createDataFrame(list)); } } catch (REXPMismatchException re) { log(HEAD_ERROR + " RList " + list.toString() + " not convertible as dataframe.", Level.ERROR); return false; } catch (RserveException ex) { log(HEAD_EXCEPTION + ex.getMessage() + "\n set(String varname=" + varname + ",double[][] data, String... names)", Level.ERROR); return false; } return true; }
Example #9
Source File: RFilesExecutor.java From Knowage-Server with GNU Affero General Public License v3.0 | 6 votes |
protected String evalFilesNeeded(HashMap paramsFilled) throws IOException, REngineException, REXPMismatchException { logger.debug("IN"); if (re != null && dataminingInstance.getFiles() != null && !dataminingInstance.getFiles().isEmpty()) { for (Iterator fIt = dataminingInstance.getFiles().iterator(); fIt.hasNext();) { DataMiningFile f = (DataMiningFile) fIt.next(); // Save file String strPathUploadedFile = DataMiningUtils.getUserResourcesPath(profile) + f.getFileName(); File file = new File(strPathUploadedFile); BufferedOutputStream writer = new BufferedOutputStream(new FileOutputStream(file)); writer.write(f.getContent()); writer.flush(); writer.close(); // put file path into variable String stringToEval = f.getAlias() + "='" + strPathUploadedFile + "'\n"; re.parseAndEval(stringToEval); } } logger.debug("OUT"); return ""; }
Example #10
Source File: Rsession.java From mzmine2 with GNU General Public License v2.0 | 6 votes |
/** * Get R command text output * * @param command R command returning text * @return String */ public String asString(String command) { try { String s = silentlyEval("paste(capture.output(print(" + command + ")),collapse='\\n')").asString(); return s; } catch (REXPMismatchException ex) { return ex.getMessage(); } /* * String[] lines = null; try { lines = silentlyEval("capture.output( " + command + * ")").asStrings(); } catch (REXPMismatchException e) { return e.getMessage(); } if (lines == * null) { return ""; } StringBuffer sb = new StringBuffer(); for (String l : lines) { * sb.append(l); sb.append("\n"); } return sb.toString(); */ }
Example #11
Source File: Rsession.java From mzmine3 with GNU General Public License v2.0 | 6 votes |
/** * Set R list in R env. * * @param varname R list name * @param data numeric data in list * @param names names of columns */ public boolean set(String varname, double[][] data, String... names) { RList list = buildRList(data, names); log(HEAD_SET + varname + " <- " + toString(list), Level.INFO); try { synchronized (connection) { connection.assign(varname, REXP.createDataFrame(list)); } } catch (REXPMismatchException re) { log(HEAD_ERROR + " RList " + list.toString() + " not convertible as dataframe.", Level.ERROR); return false; } catch (RserveException ex) { log(HEAD_EXCEPTION + ex.getMessage() + "\n set(String varname=" + varname + ",double[][] data, String... names)", Level.ERROR); return false; } return true; }
Example #12
Source File: Rsession.java From mzmine3 with GNU General Public License v2.0 | 6 votes |
/** * * @param robject R object name * @return R type of object */ public String typeOf(String robject) { if (robject == null) { return "NULL"; } for (String t : types) { REXP is = silentlyEval("is." + t + "(" + robject + ")"); try { if (is != null && is.asInteger() == 1) { return t; } } catch (REXPMismatchException ex) { log(HEAD_ERROR + "[typeOf] " + robject + " type unknown.", Level.ERROR); return null; } } return "unknown"; }
Example #13
Source File: RBridgeControl.java From kieker with Apache License 2.0 | 6 votes |
/** * Wraps the execution of an arbitrary R expression. Both errors and results are logged. * * @param input * The R expression to evaluate. * * @return The result or the error of the evaluation of the given R expression. The method tries to convert it into a string, if possible. */ public Object evalWithR(final String input) throws InvalidREvaluationResultException { Object out = null; try { out = this.rCon.eval(input); Object output = null; if (out instanceof REXPString) { output = ((REXPString) out).asString(); } else if (out instanceof REXPLogical) { output = ((REXPLogical) out).toDebugString(); } else if (out != null) { output = out; } else { throw new InvalidREvaluationResultException("Got a null result for evaluation input: \"" + input + "\""); } RBridgeControl.LOGGER.trace("> REXP: {} return: {}", input, output); } catch (final REXPMismatchException exc) { RBridgeControl.LOGGER.error("Error R expr.: {} Cause: {}", input, exc.getMessage(), exc); } return out; }
Example #14
Source File: Rsession.java From mzmine3 with GNU General Public License v2.0 | 6 votes |
/** * Check for package loaded in R environment. * * @param pack R package name * @return package loading status */ public boolean isPackageLoaded(String pack) { silentlyVoidEval(loadedpacks + "<-.packages()", false); boolean isloaded = false; try { REXP i = silentlyEval("is.element(set=" + loadedpacks + ",el='" + pack + "')"); if (i != null) { isloaded = i.asInteger() == 1; } } catch (REXPMismatchException ex) { log(HEAD_ERROR + ex.getMessage() + "\n isPackageLoaded(String pack=" + pack + ")", Level.ERROR); } if (isloaded) { log(_PACKAGE_ + pack + " is loaded.", Level.INFO); } else { log(_PACKAGE_ + pack + " is not loaded.", Level.INFO); } // silentlyEval("rm(" + loadedpacks + ")"); return isloaded; }
Example #15
Source File: Rsession.java From mzmine3 with GNU General Public License v2.0 | 6 votes |
/** * @return available R commands */ public String[] listCommands() { silentlyEval( ".keyWords <- function() {n <- length(search());result <- c();for (i in 1:n) {result <- c(result,ls(pos=i,all.names=TRUE))}; result}"); REXP rexp = silentlyEval(".keyWords()"); String as[] = null; try { if (rexp != null && (as = rexp.asStrings()) != null) { return as; } else { return null; } } catch (REXPMismatchException ex) { log(HEAD_ERROR + ex.getMessage() + "\n listCommands()", Level.ERROR); return null; } }
Example #16
Source File: Rsession.java From mzmine3 with GNU General Public License v2.0 | 6 votes |
public static String cat(RList list) { try { StringBuffer sb = new StringBuffer("\t"); double[][] data = new double[list.names.size()][]; for (int i = 0; i < list.size(); i++) { String n = list.keyAt(i); sb.append(n + "\t"); data[i] = list.at(n).asDoubles(); } sb.append("\n"); for (int i = 0; i < data[0].length; i++) { sb.append((i + 1) + "\t"); for (int j = 0; j < data.length; j++) { sb.append(data[j][i] + "\t"); } sb.append("\n"); } return sb.toString(); } catch (REXPMismatchException r) { return "(Not a numeric dataframe)\n" + new REXPList(list).toDebugString(); } }
Example #17
Source File: RserveMeanIntegrationTest.java From tutorials with MIT License | 5 votes |
/** * Test for {@link RserveMeanIntegrationTest#mean(int[])}. * * @throws REXPMismatchException if an error occurs * @throws REngineException if an error occurs */ @Test public void givenValues_whenMean_thenCorrect() throws REngineException, REXPMismatchException { int[] input = { 1, 2, 3, 4, 5 }; double result = rserveMean.mean(input); Assert.assertEquals(3.0, result, 0.000001); }
Example #18
Source File: Rsession.java From mzmine2 with GNU General Public License v2.0 | 5 votes |
/** * Get R command text output in HTML format * * @param command R command returning text * @return HTML string */ public String asR2HTML(String command) { String ret = installPackage("R2HTML", true); if (!ret.equals(PACKAGEINSTALLED)) { return ret; } int h = Math.abs(command.hashCode()); silentlyEval("HTML(file=\"htmlfile_" + h + "\", " + command + ")"); String[] lines = null; try { lines = silentlyEval("readLines(\"htmlfile_" + h + "\")").asStrings(); } catch (REXPMismatchException e) { return e.getMessage(); } removeFile("htmlfile_" + h); if (lines == null) { return ""; } StringBuffer sb = new StringBuffer(); for (String l : lines) { sb.append(l); sb.append("\n"); } String str = sb.toString(); str = str.replace("align= center ", "align='center'"); str = str.replace("cellspacing=0", "cellspacing='0'"); str = str.replace("border=1", "border='1'"); str = str.replace("align=bottom", "align='bottom'"); str = str.replace("class=dataframe", "class='dataframe'"); str = str.replace("class= firstline ", "class='firstline'"); str = str.replace("class=firstcolumn", "class='firstcolumn'"); str = str.replace("class=cellinside", "class='cellinside'"); str = str.replace("border=0", "border='0'"); str = str.replace("class=captiondataframe", "class='captiondataframe'"); str = str.replace("</td></table>", "</td></tr></table>"); return str; }
Example #19
Source File: Rsession.java From mzmine2 with GNU General Public License v2.0 | 5 votes |
public String getRServeOS() { try { return eval("Sys.info()['sysname']", TRY_MODE).asString(); } catch (REXPMismatchException re) { return "unknown"; } }
Example #20
Source File: RObjectsPanel.java From mzmine2 with GNU General Public License v2.0 | 5 votes |
public void update() { try { if (R == null) { ls = new String[0]; } else { REXP rls = R.silentlyEval("ls()"); if (rls != null) { ls = rls.asStrings(); } else { ls = new String[0]; } } if (ls != null && ls.length > 0) { for (String l : ls) { try { // System.err.println("print(" + l + ")"+" -> "); String print = R.asHTML(l);// toHTML(R.silentlyEval("paste(capture.output(print(" // + l + // ")),collapse='\\n')").asString()); // String print = Rsession.cat(R.silentlyEval("print(" + // l + ")").asStrings()); // System.err.println(" "+print); prints.put(l, print); } catch (Exception re) { prints.put(l, "?:" + re.getMessage()); } } } EventQueue.invokeLater(new Runnable() { public void run() { _model.fireTableDataChanged(); } }); } catch (REXPMismatchException ex) { ex.printStackTrace(); } }
Example #21
Source File: RScriptExecutor.java From Knowage-Server with GNU Affero General Public License v3.0 | 5 votes |
private void loadLibrariesFromRLocal(String libraryNames) throws REngineException, REXPMismatchException { logger.debug("IN"); if (this.re != null) { re.parseAndEval("installed_packages = rownames(installed.packages())"); REXP rHome = re.parseAndEval("try(libdir<-paste(R.home(),\"library\", sep=\"/\"))"); if (!rHome.inherits("try-error") && !rHome.isNull()) { if (libraryNames != null && !libraryNames.isEmpty()) { setRProxy(); String[] libs = libraryNames.split(","); for (int i = 0; i < libs.length; i++) { String lib = libs[i].trim(); if (!lib.isEmpty()) { // check if the library is present in the workspace, if not try to install that package REXP libIsPresent = re.parseAndEval("\"" + lib + "\" %in% installed_packages"); if (libIsPresent.isNull() || libIsPresent.asString().equalsIgnoreCase("false")) { // re.parseAndEval("try(install.packages(\"" + lib + "\",destdir=libdir))"); logger.error("Libray '" + lib + "' is not present. Please, install the library in R before"); } REXP rLibrary = re.parseAndEval("library(" + lib + ",lib.loc=libdir)"); if (rLibrary.inherits("try-error")) { logger.error("Impossible to load library: " + lib); } } } } } } logger.debug("OUT"); }
Example #22
Source File: RDatasetsExecutor.java From Knowage-Server with GNU Affero General Public License v3.0 | 5 votes |
protected boolean getAndEvalDefaultDataset(DataMiningDataset ds) throws IOException, REngineException, REXPMismatchException { logger.debug("IN"); // checks relative path String relPathToDefDS = ds.getDefaultDS(); if (relPathToDefDS == null || relPathToDefDS.equals("")) { return false; } if (relPathToDefDS.startsWith("/") || relPathToDefDS.startsWith("\\\\")) { relPathToDefDS = relPathToDefDS.substring(1); } String defDSRelPath = DataMiningUtils.UPLOADED_FILE_PATH + relPathToDefDS; defDSRelPath = defDSRelPath.replaceAll("\\\\", "/"); logger.debug("Default path " + defDSRelPath); File fileDSDefault = new File(defDSRelPath); if (!fileDSDefault.exists()) { logger.debug("Default file doesn't exist"); return false; } String stringToEval = ds.getName() + "<-read." + ds.getReadType() + "(\"" + defDSRelPath + "\"," + ds.getOptions() + ");"; logger.debug("R code to eval " + stringToEval); re.parseAndEval(stringToEval); logger.debug("OUT"); return true; }
Example #23
Source File: DataMiningPythonExecutor.java From Knowage-Server with GNU Affero General Public License v3.0 | 5 votes |
private void setupEnvonmentForExternal() throws IOException, REngineException, REXPMismatchException, NamingException { logger.debug("IN"); String str = "" + DataMiningUtils.UPLOADED_FILE_PATH + DataMiningConstants.DATA_MINING_EXTERNAL_CODE_PATH; if (!PyLib.isPythonRunning()) { PyLib.startPython(); } PyLib.execScript("import os\n" + "os.chdir(r'" + str + "')\n"); logger.debug("Set working directory"); logger.debug("OUT"); }
Example #24
Source File: Rsession.java From mzmine3 with GNU General Public License v2.0 | 5 votes |
/** * Get R command text output in HTML format * * @param command R command returning text * @return HTML string */ public String asR2HTML(String command) { String ret = installPackage("R2HTML", true); if (!ret.equals(PACKAGEINSTALLED)) { return ret; } int h = Math.abs(command.hashCode()); silentlyEval("HTML(file=\"htmlfile_" + h + "\", " + command + ")"); String[] lines = null; try { lines = silentlyEval("readLines(\"htmlfile_" + h + "\")").asStrings(); } catch (REXPMismatchException e) { return e.getMessage(); } removeFile("htmlfile_" + h); if (lines == null) { return ""; } StringBuffer sb = new StringBuffer(); for (String l : lines) { sb.append(l); sb.append("\n"); } String str = sb.toString(); str = str.replace("align= center ", "align='center'"); str = str.replace("cellspacing=0", "cellspacing='0'"); str = str.replace("border=1", "border='1'"); str = str.replace("align=bottom", "align='bottom'"); str = str.replace("class=dataframe", "class='dataframe'"); str = str.replace("class= firstline ", "class='firstline'"); str = str.replace("class=firstcolumn", "class='firstcolumn'"); str = str.replace("class=cellinside", "class='cellinside'"); str = str.replace("border=0", "border='0'"); str = str.replace("class=captiondataframe", "class='captiondataframe'"); str = str.replace("</td></table>", "</td></tr></table>"); return str; }
Example #25
Source File: Rsession.java From mzmine3 with GNU General Public License v2.0 | 5 votes |
public String getRServeOS() { try { return eval("Sys.info()['sysname']", TRY_MODE).asString(); } catch (REXPMismatchException re) { return "unknown"; } }
Example #26
Source File: RSessionWrapper.java From mzmine2 with GNU General Public License v2.0 | 4 votes |
public void loadPackage(String packageName) throws RSessionWrapperException { String loadCode = "library(" + packageName + ", logical.return = TRUE)"; if (TRY_MODE) loadCode = "try(" + loadCode + ", silent=TRUE)"; String errorMsg = "The \"" + this.callerFeatureName + "\" requires " + "the \"" + packageName + "\" R package, which couldn't be loaded - is it installed in R?"; if (this.rEngineType == REngineType.RSERVE) { if (this.session != null && !this.userCanceled) { LOG.log(logLvl, "Loading package '" + packageName + "'..."); int loaded = 0; try { REXP r = ((RConnection) this.rEngine).eval(loadCode); if (r.inherits("try-error")) { LOG.severe("R Error [0]: " + r.asString()); LOG.severe("R eval attempt [0]: " + loadCode); } loaded = r.asInteger(); LOG.log(logLvl, "Load status: '" + (loaded != 0) + "'."); } catch (RserveException | REXPMismatchException e) { LOG.log(logLvl, "Loaded package KO: '" + e.getMessage() + "'."); // Remain silent if eval KO ("server down"). loaded = Integer.MIN_VALUE; } // Throw loading failure only if eval OK, but return FALSE // (package not loaded). // ("server down" case will be handled soon enough). if (loaded == 0) if (!this.userCanceled) throw new RSessionWrapperException(errorMsg); LOG.log(logLvl, "Loaded package: '" + packageName + "'."); } } else { // RCaller ((RCaller) rEngine).getRCode().addRCode(loadCode); // try { // // ((RCallerScriptEngine2) rEngine).eval(loadCode); // } catch (ScriptException e) { // // if (!this.userCanceled) // throw new RSessionWrapperException(errorMsg); // } } }
Example #27
Source File: Rsession.java From mzmine2 with GNU General Public License v2.0 | 4 votes |
/** * cast R object in java object * * @param eval REXP R object * @return java object * @throws org.rosuda.REngine.REXPMismatchException */ public static Object cast(REXP eval) throws REXPMismatchException { if (eval == null) { return null; } /* * int[] dim = eval.dim(); String dims = "["; if (dim == null) { dims = "NULL"; } else { for * (int i : dim) { dims += (i + " "); } dims += "]"; } * * System.out.println(eval.toString() + "\n isComplex= " + (eval.isComplex() ? "TRUE" : * " false") + "\n isEnvironment= " + (eval.isEnvironment() ? "TRUE" : " false") + * "\n isExpression= " + (eval.isExpression() ? "TRUE" : " false") + "\n isFactor= " * + (eval.isFactor() ? "TRUE" : " false") + "\n isFactor= " + (eval.isFactor() ? * "TRUE" : " false") + "\n isInteger= " + (eval.isInteger() ? "TRUE" : " false") + * "\n isLanguage= " + (eval.isLanguage() ? "TRUE" : " false") + "\n isList= " + * (eval.isList() ? "TRUE" : " false") + "\n isLogical= " + (eval.isLogical() ? "TRUE" : * " false") + "\n isNull= " + (eval.isNull() ? "TRUE" : " false") + * "\n isNumeric= " + (eval.isNumeric() ? "TRUE" : " false") + "\n isRaw= " + * (eval.isRaw() ? "TRUE" : " false") + "\n isRecursive= " + (eval.isRecursive() ? "TRUE" * : " false") + "\n isString= " + (eval.isString() ? "TRUE" : " false") + * "\n isSymbol= " + (eval.isSymbol() ? "TRUE" : " false") + "\n isVector= " + * (eval.isVector() ? "TRUE" : " false") + "\n length= " + (eval.length()) + "\n dim= " + * dims); */ if (eval.isNumeric()) { if (eval.dim() == null || eval.dim().length == 1) { double[] array = eval.asDoubles(); if (array.length == 0) { return null; } if (array.length == 1) { return array[0]; } return array; } else { // System.err.println("eval.dim()="+eval.dim()+"="+cat(eval.dim())); double[][] mat = eval.asDoubleMatrix(); if (mat.length == 0) { return null; } else if (mat.length == 1) { if (mat[0].length == 0) { return null; } else if (mat[0].length == 1) { return mat[0][0]; } else { return mat[0]; } } else { if (mat[0].length == 0) { return null; } else if (mat[0].length == 1) { double[] dmat = new double[mat.length]; for (int i = 0; i < dmat.length; i++) { dmat[i] = mat[i][0]; } return dmat; } else { return mat; } } } } if (eval.isString()) { String[] s = eval.asStrings(); if (s.length == 1) { return s[0]; } else { return s; } } if (eval.isLogical()) { return eval.asInteger() == 1; } if (eval.isList()) { return eval.asList(); } if (eval.isNull()) { return null; } else { System.err.println("Unsupported type: " + eval.toDebugString()); } return eval.toString(); }
Example #28
Source File: Rsession.java From mzmine3 with GNU General Public License v2.0 | 4 votes |
/** * cast R object in java object * * @param eval REXP R object * @return java object * @throws org.rosuda.REngine.REXPMismatchException */ public static Object cast(REXP eval) throws REXPMismatchException { if (eval == null) { return null; } /* * int[] dim = eval.dim(); String dims = "["; if (dim == null) { dims = "NULL"; } else { for * (int i : dim) { dims += (i + " "); } dims += "]"; } * * System.out.println(eval.toString() + "\n isComplex= " + (eval.isComplex() ? "TRUE" : * " false") + "\n isEnvironment= " + (eval.isEnvironment() ? "TRUE" : " false") + * "\n isExpression= " + (eval.isExpression() ? "TRUE" : " false") + "\n isFactor= " * + (eval.isFactor() ? "TRUE" : " false") + "\n isFactor= " + (eval.isFactor() ? * "TRUE" : " false") + "\n isInteger= " + (eval.isInteger() ? "TRUE" : " false") + * "\n isLanguage= " + (eval.isLanguage() ? "TRUE" : " false") + "\n isList= " + * (eval.isList() ? "TRUE" : " false") + "\n isLogical= " + (eval.isLogical() ? "TRUE" : * " false") + "\n isNull= " + (eval.isNull() ? "TRUE" : " false") + * "\n isNumeric= " + (eval.isNumeric() ? "TRUE" : " false") + "\n isRaw= " + * (eval.isRaw() ? "TRUE" : " false") + "\n isRecursive= " + (eval.isRecursive() ? "TRUE" * : " false") + "\n isString= " + (eval.isString() ? "TRUE" : " false") + * "\n isSymbol= " + (eval.isSymbol() ? "TRUE" : " false") + "\n isVector= " + * (eval.isVector() ? "TRUE" : " false") + "\n length= " + (eval.length()) + "\n dim= " + * dims); */ if (eval.isNumeric()) { if (eval.dim() == null || eval.dim().length == 1) { double[] array = eval.asDoubles(); if (array.length == 0) { return null; } if (array.length == 1) { return array[0]; } return array; } else { // System.err.println("eval.dim()="+eval.dim()+"="+cat(eval.dim())); double[][] mat = eval.asDoubleMatrix(); if (mat.length == 0) { return null; } else if (mat.length == 1) { if (mat[0].length == 0) { return null; } else if (mat[0].length == 1) { return mat[0][0]; } else { return mat[0]; } } else { if (mat[0].length == 0) { return null; } else if (mat[0].length == 1) { double[] dmat = new double[mat.length]; for (int i = 0; i < dmat.length; i++) { dmat[i] = mat[i][0]; } return dmat; } else { return mat; } } } } if (eval.isString()) { String[] s = eval.asStrings(); if (s.length == 1) { return s[0]; } else { return s; } } if (eval.isLogical()) { return eval.asInteger() == 1; } if (eval.isList()) { return eval.asList(); } if (eval.isNull()) { return null; } else { System.err.println("Unsupported type: " + eval.toDebugString()); } return eval.toString(); }
Example #29
Source File: RSessionWrapper.java From mzmine3 with GNU General Public License v2.0 | 4 votes |
public void loadPackage(String packageName) throws RSessionWrapperException { String loadCode = "library(" + packageName + ", logical.return = TRUE)"; if (TRY_MODE) loadCode = "try(" + loadCode + ", silent=TRUE)"; String errorMsg = "The \"" + this.callerFeatureName + "\" requires " + "the \"" + packageName + "\" R package, which couldn't be loaded - is it installed in R?"; if (this.rEngineType == REngineType.RSERVE) { if (this.session != null && !this.userCanceled) { logger.log(logLvl, "Loading package '" + packageName + "'..."); int loaded = 0; try { REXP r = ((RConnection) this.rEngine).eval(loadCode); if (r.inherits("try-error")) { logger.severe("R Error [0]: " + r.asString()); logger.severe("R eval attempt [0]: " + loadCode); } loaded = r.asInteger(); logger.log(logLvl, "Load status: '" + (loaded != 0) + "'."); } catch (RserveException | REXPMismatchException e) { logger.log(logLvl, "Loaded package KO: '" + e.getMessage() + "'."); // Remain silent if eval KO ("server down"). loaded = Integer.MIN_VALUE; } // Throw loading failure only if eval OK, but return FALSE // (package not loaded). // ("server down" case will be handled soon enough). if (loaded == 0) if (!this.userCanceled) throw new RSessionWrapperException(errorMsg); logger.log(logLvl, "Loaded package: '" + packageName + "'."); } } else { // RCaller ((RCaller) rEngine).getRCode().addRCode(loadCode); // try { // // ((RCallerScriptEngine2) rEngine).eval(loadCode); // } catch (ScriptException e) { // // if (!this.userCanceled) // throw new RSessionWrapperException(errorMsg); // } } }
Example #30
Source File: RserveMean.java From tutorials with MIT License | 3 votes |
/** * Connects to the Rserve istance listening on 127.0.0.1:6311 and invokes the * customMean R function passing the given values as arguments. * * @param values the input to the mean script * @return the result of the R script * @throws REngineException if any error occurs * @throws REXPMismatchException if any error occurs */ public double mean(int[] values) throws REngineException, REXPMismatchException { RConnection c = new RConnection(); c.assign("input", values); return c.eval("customMean(input)") .asDouble(); }