Java Code Examples for org.rosuda.REngine.REXP#inherits()

The following examples show how to use org.rosuda.REngine.REXP#inherits() . 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: 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 2
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 3
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 4
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 5
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);
      // }

    }
  }