org.rosuda.REngine.REXP Java Examples

The following examples show how to use org.rosuda.REngine.REXP. 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 vote down vote up
/**
 * @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 #2
Source File: Rsession.java    From mzmine3 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 #3
Source File: Rsession.java    From mzmine2 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 #4
Source File: Rsession.java    From mzmine2 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 
 * @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 #5
Source File: Rsession.java    From mzmine3 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Launch R command and return value.
 * 
 * @param expression R expresison to evaluate
 * @param tryEval encapsulate command in try() to cacth errors
 * @return REXP R expression
 */
public REXP eval(String expression, boolean tryEval) {
  // GLG HACK: Less verbosity when no error.
  // log(HEAD_EVAL + (tryEval ? HEAD_TRY : "") + expression, Level.INFO);

  REXP e = silentlyEval(expression, tryEval);

  for (UpdateObjectsListener b : updateObjects) {
    b.update();
  }

  // GLG HACK: Less verbosity when no error.
  // if (e != null) {
  // log(__ + e.toDebugString(), Level.INFO);
  // }

  return e;
}
 
Example #6
Source File: Rsession.java    From mzmine2 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Launch R command and return value.
 * 
 * @param expression R expresison to evaluate
 * @param tryEval encapsulate command in try() to cacth errors
 * @return REXP R expression
 */
public REXP eval(String expression, boolean tryEval) {
  // GLG HACK: Less verbosity when no error.
  // log(HEAD_EVAL + (tryEval ? HEAD_TRY : "") + expression, Level.INFO);

  REXP e = silentlyEval(expression, tryEval);

  for (UpdateObjectsListener b : updateObjects) {
    b.update();
  }

  // GLG HACK: Less verbosity when no error.
  // if (e != null) {
  // log(__ + e.toDebugString(), Level.INFO);
  // }

  return e;
}
 
Example #7
Source File: Rsession.java    From mzmine3 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 
 * @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 mzmine3 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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: Rsession.java    From mzmine2 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 #10
Source File: Rsession.java    From mzmine2 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * @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 #11
Source File: Rsession.java    From mzmine2 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * cast to java String representation of object
 * 
 * @param eval REXP R object
 * @return String representation
 */
public static String castToString(REXP eval) {
  if (eval == null) {
    return "";
  }
  return eval.toString();
}
 
Example #12
Source File: RObjectsPanel.java    From mzmine2 with GNU General Public License v2.0 5 votes vote down vote up
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 #13
Source File: RScriptExecutor.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
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 #14
Source File: Rsession.java    From mzmine3 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * cast to java String representation of object
 * 
 * @param eval REXP R object
 * @return String representation
 */
public static String castToString(REXP eval) {
  if (eval == null) {
    return "";
  }
  return eval.toString();
}
 
Example #15
Source File: RScriptExecutor.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
protected void evalScript(DataMiningCommand command, Boolean rerun, HashMap params) throws Exception {
	logger.debug("IN");

	if (re == null) {
		logger.error("No R instance found");
		return;
	}
	// checks whether executed before
	if (rerun || command.getExecuted() == null || !command.getExecuted()) {
		logger.debug("rerun or first execution");
		// load libraries from local dir (if needed)
		DataMiningScript script = getScript(command);
		loadLibrariesFromRLocal(script.getLibraries());
		logger.debug("loaded libraries from local dir (if needed)");
		// command-->script name --> execute script without output
		String scriptToExecute = getScriptCodeToEval(command, params);
		logger.debug("loaded script to execute: " + scriptToExecute);
		// loading libraries, preprocessing, functions definition in main
		// "auto"
		// script
		logger.info("creating temporary script...");

		String ret = createTemporarySourceScript(scriptToExecute);
		logger.info("created temporary script: " + ret);

		logger.info("executing temporary script...");
		REXP rexp = re.parseAndEval("source(\"" + ret + "\")");
		logger.info("temporary script execution completed");

		logger.debug("detects action to execute from command --> used to call functions");
		// detects action to execute from command --> used to call functions
		String action = command.getAction();
		if (action != null) {
			logger.info("evaluating action..");
			System.out.println("evaluating action..");
			re.parseAndEval(action);
			System.out.println("evaluated action");
			logger.info("evaluated action");
		}

		command.setExecuted(true);
		logger.debug("delete temporary scripts");
		deleteTemporarySourceScript(ret);
		logger.debug("deleted temporary scripts");
	} else {
		// everithing in user workspace
		logger.debug("Command " + command.getName() + " script " + command.getScriptName() + " already executed");
	}
	logger.debug("OUT");
}
 
Example #16
Source File: ROutputExecutor.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
private CreateDatasetResult createAndPersistDatasetProductByFunction(IEngUserProfile profile, String outVal, Output out, String function, String userId,
		String documentLabel) throws Exception {
	logger.debug("IN");
	CreateDatasetResult creationResult = new CreateDatasetResult();
	REXP rexp = null;
	DataMiningResult res = new DataMiningResult();

	FileDataSet dataSet = new FileDataSet();
	String path = getDatasetsDirectoryPath();
	String resourcePath = DAOConfig.getResourcePath();
	dataSet.setResourcePath(resourcePath);

	String spagoBiDatasetname = userId + "_" + documentLabel + "_" + out.getOuputLabel();
	JSONObject configurationObj = new JSONObject();

	configurationObj.put(DataSetConstants.FILE_TYPE, "CSV");
	configurationObj.put(DataSetConstants.CSV_FILE_DELIMITER_CHARACTER, ",");
	configurationObj.put(DataSetConstants.CSV_FILE_QUOTE_CHARACTER, "'");
	configurationObj.put(DataSetConstants.FILE_NAME, spagoBiDatasetname + ".csv");
	configurationObj.put("encoding", "UTF-8");
	configurationObj.put(DataSetConstants.XSL_FILE_SKIP_ROWS, DataSetConstants.XSL_FILE_SKIP_ROWS);
	configurationObj.put(DataSetConstants.XSL_FILE_LIMIT_ROWS, DataSetConstants.XSL_FILE_LIMIT_ROWS);
	configurationObj.put(DataSetConstants.XSL_FILE_SHEET_NUMBER, DataSetConstants.XSL_FILE_SHEET_NUMBER);

	String confString = configurationObj.toString();
	dataSet.setConfiguration(confString);

	String rExecution = "write.csv(" + outVal + ",file=" + path + spagoBiDatasetname + ",row.names=FALSE,na='')";
	rexp = re.parseAndEval("try(" + rExecution + ")");
	if (rexp.inherits("try-error")) {
		logger.debug("Script contains error(s)");
		creationResult.setRExecutionError(rexp.asString());
	}

	dataSet.setFileName(spagoBiDatasetname + ".csv");
	dataSet.setFileType("CSV");
	dataSet.setDsType(DataSetConstants.DS_FILE);

	String label = out.getOuputLabel();
	dataSet.setLabel(spagoBiDatasetname);
	dataSet.setName(spagoBiDatasetname);
	dataSet.setDescription("Dataset created from execution of document " + documentLabel + " by user " + userId);
	dataSet.setOwner(((UserProfile) profile).getUserId().toString());

	// ------------Metadata setting------------

	dataSet.loadData();
	IDataStore dataStore = dataSet.getDataStore();
	JSONArray metadataArray = new JSONArray();

	IMetaData metaData = dataStore.getMetaData();
	for (int i = 0; i < metaData.getFieldCount(); i++) {
		IFieldMetaData ifmd = metaData.getFieldMeta(i);
		for (int j = 0; j < metadataArray.length(); j++) {
			if (ifmd.getName().equals((metadataArray.getJSONObject(j)).getString("name"))) {
				if ("MEASURE".equals((metadataArray.getJSONObject(j)).getString("fieldType"))) {
					ifmd.setFieldType(IFieldMetaData.FieldType.MEASURE);
				} else {
					ifmd.setFieldType(IFieldMetaData.FieldType.ATTRIBUTE);
				}
				break;
			}
		}
	}
	IMetaData currentMetadata = dataStore.getMetaData();
	DatasetMetadataParser dsp = new DatasetMetadataParser();
	String dsMetadata = dsp.metadataToXML(currentMetadata);
	dataSet.setDsMetadata(dsMetadata);

	// ----------------------------------------

	IDataSetDAO dataSetDAO = DAOFactory.getDataSetDAO();
	dataSetDAO.setUserProfile(profile);

	logger.debug("check if dataset with label " + spagoBiDatasetname + " is already present");

	// check label is already present; insert or modify dependengly
	IDataSet iDataSet = dataSetDAO.loadDataSetByLabel(spagoBiDatasetname);

	// loadActiveDataSetByLabel(label);
	if (iDataSet != null) {
		logger.debug("a dataset with label " + spagoBiDatasetname + " is already present: modify it");
		dataSet.setId(iDataSet.getId());
		dataSetDAO.modifyDataSet(dataSet);
	} else {
		logger.debug("No dataset with label " + spagoBiDatasetname + " is already present: insert it");
		dataSetDAO.insertDataSet(dataSet);

	}
	creationResult.setDatasetlabel(spagoBiDatasetname);
	return creationResult;

}
 
Example #17
Source File: RSessionWrapper.java    From mzmine2 with GNU General Public License v2.0 4 votes vote down vote up
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 #18
Source File: ROutputExecutor.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
private CreateDatasetResult createAndPersistDataset(IEngUserProfile profile, String outVal, Output out, String userId, String documentLabel)
		throws Exception {
	logger.debug("IN");

	REXP rexp = null;
	CreateDatasetResult creationResult = new CreateDatasetResult();

	String spagoBiDatasetname = userId + "_" + documentLabel + "_" + out.getOuputLabel();

	FileDataSet dataSet = new FileDataSet();
	String path = getDatasetsDirectoryPath();
	String resourcePath = DAOConfig.getResourcePath();
	dataSet.setResourcePath(resourcePath);

	JSONObject configurationObj = new JSONObject();

	configurationObj.put(DataSetConstants.FILE_TYPE, "CSV");
	configurationObj.put(DataSetConstants.CSV_FILE_DELIMITER_CHARACTER, ",");
	configurationObj.put(DataSetConstants.CSV_FILE_QUOTE_CHARACTER, "\"");
	configurationObj.put(DataSetConstants.FILE_NAME, spagoBiDatasetname + ".csv");
	configurationObj.put(DataSetConstants.CSV_FILE_ENCODING, "UTF-8");
	configurationObj.put(DataSetConstants.XSL_FILE_SKIP_ROWS, DataSetConstants.XSL_FILE_SKIP_ROWS);
	configurationObj.put(DataSetConstants.XSL_FILE_LIMIT_ROWS, DataSetConstants.XSL_FILE_LIMIT_ROWS);
	configurationObj.put(DataSetConstants.XSL_FILE_SHEET_NUMBER, DataSetConstants.XSL_FILE_SHEET_NUMBER);

	String confString = configurationObj.toString();
	dataSet.setConfiguration(confString);

	String rExecution = "write.csv(" + outVal + ",file='" + path + "/" + spagoBiDatasetname + ".csv',row.names=FALSE,na='')";
	rexp = re.parseAndEval("try(" + rExecution + ")");
	if (rexp.inherits("try-error")) {
		logger.debug("Script contains error(s)");
		creationResult.setRExecutionError(rexp.asString());
	}

	dataSet.setFileName(spagoBiDatasetname + ".csv");
	dataSet.setFileType("CSV");
	dataSet.setDsType(DataSetConstants.DS_FILE);

	dataSet.setLabel(spagoBiDatasetname);
	dataSet.setName(spagoBiDatasetname);
	dataSet.setDescription("Dataset created from execution of document " + documentLabel + " by user " + userId);
	dataSet.setOwner(((UserProfile) profile).getUserId().toString());

	// ------------Metadata setting------------

	dataSet.loadData();
	IDataStore dataStore = dataSet.getDataStore();
	JSONArray metadataArray = new JSONArray();

	IMetaData metaData = dataStore.getMetaData();
	for (int i = 0; i < metaData.getFieldCount(); i++) {
		IFieldMetaData ifmd = metaData.getFieldMeta(i);
		for (int j = 0; j < metadataArray.length(); j++) {
			if (ifmd.getName().equals((metadataArray.getJSONObject(j)).getString("name"))) {
				if ("MEASURE".equals((metadataArray.getJSONObject(j)).getString("fieldType"))) {
					ifmd.setFieldType(IFieldMetaData.FieldType.MEASURE);
				} else {
					ifmd.setFieldType(IFieldMetaData.FieldType.ATTRIBUTE);
				}
				break;
			}
		}
	}
	IMetaData currentMetadata = dataStore.getMetaData();
	DatasetMetadataParser dsp = new DatasetMetadataParser();
	String dsMetadata = dsp.metadataToXML(currentMetadata);
	dataSet.setDsMetadata(dsMetadata);

	// ----------------------------------------

	IDataSetDAO dataSetDAO = DAOFactory.getDataSetDAO();
	dataSetDAO.setUserProfile(profile);

	logger.debug("check if dataset with label " + spagoBiDatasetname + " is already present");

	// check label is already present; insert or modify dependengly
	IDataSet iDataSet = dataSetDAO.loadDataSetByLabel(spagoBiDatasetname);

	// loadActiveDataSetByLabel(label);
	if (iDataSet != null) {
		logger.debug("a dataset with label " + spagoBiDatasetname + " is already present: modify it");
		dataSet.setId(iDataSet.getId());
		dataSetDAO.modifyDataSet(dataSet);
	} else {
		logger.debug("No dataset with label " + spagoBiDatasetname + " is already present: insert it");
		dataSetDAO.insertDataSet(dataSet);

	}
	creationResult.setDatasetlabel(spagoBiDatasetname);
	return creationResult;

}
 
Example #19
Source File: Rsession.java    From mzmine3 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * 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 #20
Source File: Rsession.java    From mzmine2 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Silently (ie no log) launch R command and return value.
 * 
 * @param expression R expression to evaluate
 * @param tryEval encapsulate command in try() to cacth errors
 * @return REXP R expression
 */
public REXP silentlyEval(String expression, boolean tryEval) {
  assert connected : "R environment not initialized.";
  if (expression == null) {
    return null;
  }
  if (expression.trim().length() == 0) {
    return null;
  }
  for (EvalListener b : eval) {
    b.eval(expression);
  }
  REXP e = null;
  try {
    synchronized (connection) {
      if (SINK_OUTPUT) {
        connection.parseAndEval("sink('" + SINK_FILE + "',type='output')");
      }
      if (tryEval) {
        e = connection.parseAndEval(
            "try(eval(parse(text='" + expression.replace("'", "\\'") + "')),silent=FALSE)");
      } else {
        e = connection.parseAndEval(expression);
      }
      if (SINK_OUTPUT) {
        connection.parseAndEval("sink(type='output')");
        try {
          lastOuput = connection
              .parseAndEval("paste(collapse='\n',readLines('" + SINK_FILE + "'))").asString();
          log(lastOuput, Level.OUTPUT);
        } catch (Exception ex) {
          lastOuput = ex.getMessage();
          log(lastOuput, Level.WARNING);
        }
        connection.parseAndEval("unlink('" + SINK_FILE + "')");
      }
    }
  } catch (Exception ex) {
    log(HEAD_EXCEPTION + ex.getMessage() + "\n  " + expression, Level.ERROR);
  }

  if (tryEval && e != null) {
    try {
      if (e.inherits("try-error")/*
                                  * e.isString() && e.asStrings().length > 0 && e.asString
                                  * ().toLowerCase().startsWith ("error")
                                  */) {
        log(HEAD_EXCEPTION + e.asString() + "\n  " + expression, Level.WARNING);
        e = null;
      }
    } catch (REXPMismatchException ex) {
      log(HEAD_ERROR + ex.getMessage() + "\n  " + expression, Level.ERROR);
      return null;
    }
  }
  return e;
}
 
Example #21
Source File: Rsession.java    From mzmine3 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Silently (ie no log) launch R command and return value.
 * 
 * @param expression R expression to evaluate
 * @param tryEval encapsulate command in try() to cacth errors
 * @return REXP R expression
 */
public REXP silentlyEval(String expression, boolean tryEval) {
  assert connected : "R environment not initialized.";
  if (expression == null) {
    return null;
  }
  if (expression.trim().length() == 0) {
    return null;
  }
  for (EvalListener b : eval) {
    b.eval(expression);
  }
  REXP e = null;
  try {
    synchronized (connection) {
      if (SINK_OUTPUT) {
        connection.parseAndEval("sink('" + SINK_FILE + "',type='output')");
      }
      if (tryEval) {
        e = connection.parseAndEval(
            "try(eval(parse(text='" + expression.replace("'", "\\'") + "')),silent=FALSE)");
      } else {
        e = connection.parseAndEval(expression);
      }
      if (SINK_OUTPUT) {
        connection.parseAndEval("sink(type='output')");
        try {
          lastOuput = connection
              .parseAndEval("paste(collapse='\n',readLines('" + SINK_FILE + "'))").asString();
          log(lastOuput, Level.OUTPUT);
        } catch (Exception ex) {
          lastOuput = ex.getMessage();
          log(lastOuput, Level.WARNING);
        }
        connection.parseAndEval("unlink('" + SINK_FILE + "')");
      }
    }
  } catch (Exception ex) {
    log(HEAD_EXCEPTION + ex.getMessage() + "\n  " + expression, Level.ERROR);
  }

  if (tryEval && e != null) {
    try {
      if (e.inherits("try-error")/*
                                  * e.isString() && e.asStrings().length > 0 && e.asString
                                  * ().toLowerCase().startsWith ("error")
                                  */) {
        log(HEAD_EXCEPTION + e.asString() + "\n  " + expression, Level.WARNING);
        e = null;
      }
    } catch (REXPMismatchException ex) {
      log(HEAD_ERROR + ex.getMessage() + "\n  " + expression, Level.ERROR);
      return null;
    }
  }
  return e;
}
 
Example #22
Source File: Rsession.java    From mzmine2 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * 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 #23
Source File: RSessionWrapper.java    From mzmine3 with GNU General Public License v2.0 4 votes vote down vote up
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 #24
Source File: Rsession.java    From mzmine2 with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Silently (ie no log) launch R command and return value. Encapsulate command in try() to cacth
 * errors.
 * 
 * @param expression R expresison to evaluate
 * @return REXP R expression
 */
public REXP silentlyEval(String expression) {
  return silentlyEval(expression, TRY_MODE_DEFAULT);
}
 
Example #25
Source File: Rsession.java    From mzmine3 with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Launch R command and return value. Encapsulate command in try() to cacth errors.
 * 
 * @param expression R expresison to evaluate
 * @return REXP R expression
 */
public REXP eval(String expression) {
  return eval(expression, TRY_MODE_DEFAULT);
}
 
Example #26
Source File: Rsession.java    From mzmine2 with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Launch R command and return value. Encapsulate command in try() to cacth errors.
 * 
 * @param expression R expresison to evaluate
 * @return REXP R expression
 */
public REXP eval(String expression) {
  return eval(expression, TRY_MODE_DEFAULT);
}
 
Example #27
Source File: Rsession.java    From mzmine3 with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Silently (ie no log) launch R command and return value. Encapsulate command in try() to cacth
 * errors.
 * 
 * @param expression R expresison to evaluate
 * @return REXP R expression
 */
public REXP silentlyEval(String expression) {
  return silentlyEval(expression, TRY_MODE_DEFAULT);
}