com.github.rcaller.rstuff.RCaller Java Examples

The following examples show how to use com.github.rcaller.rstuff.RCaller. 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: RSessionWrapper.java    From mzmine3 with GNU General Public License v2.0 5 votes vote down vote up
private void initNewRCaller() {

    this.rEngine = RCaller.create();
    RCode code = RCode.create();
    ((RCaller) this.rEngine).setRCode(code);

    this.wasRunAndReturned = false;
  }
 
Example #2
Source File: RSessionWrapper.java    From mzmine3 with GNU General Public License v2.0 5 votes vote down vote up
public void runOnlyOnline() {

    if (this.rEngineType == REngineType.RCALLER) {
      // Cannot 'runOnly()', all the stuff being run 'online'
      ((RCaller) this.rEngine).runAndReturnResultOnline("TRUE");
      // ((RCaller) this.rEngine).runOnly();
    }
  }
 
Example #3
Source File: RSessionWrapper.java    From mzmine2 with GNU General Public License v2.0 5 votes vote down vote up
private void initNewRCaller() {

    this.rEngine = RCaller.create();
    RCode code = RCode.create();
    ((RCaller) this.rEngine).setRCode(code);

    this.wasRunAndReturned = false;
  }
 
Example #4
Source File: RSessionWrapper.java    From mzmine2 with GNU General Public License v2.0 5 votes vote down vote up
public void runOnlyOnline() {

    if (this.rEngineType == REngineType.RCALLER) {
      // Cannot 'runOnly()', all the stuff being run 'online'
      ((RCaller) this.rEngine).runAndReturnResultOnline("TRUE");
      // ((RCaller) this.rEngine).runOnly();
    }
  }
 
Example #5
Source File: RCallerMean.java    From tutorials with MIT License 5 votes vote down vote up
/**
 * 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 IOException        if any error occurs
 * @throws URISyntaxException if any error occurs
 */
public double mean(int[] values) throws IOException, URISyntaxException {
    String fileContent = RUtils.getMeanScriptContent();
    RCode code = RCode.create();
    code.addRCode(fileContent);
    code.addIntArray("input", values);
    code.addRCode("result <- customMean(input)");
    RCaller caller = RCaller.create(code, RCallerOptions.create());
    caller.runAndReturnResult("result");
    return caller.getParser()
        .getAsDoubleArray("result")[0];
}
 
Example #6
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 #7
Source File: RSessionWrapper.java    From mzmine3 with GNU General Public License v2.0 4 votes vote down vote up
public boolean eval(String rCode, boolean stopOnError) throws RSessionWrapperException {

    // if (TRY_MODE) rCode = "try(" + rCode + ",silent=TRUE)";

    if (this.rEngineType == REngineType.RSERVE) {

      boolean ok = false;
      if (this.session != null && !this.userCanceled) {
        String msg = "Rserve error: couldn't eval R code '" + rCode + "' (instance '"
            + this.getPID() + "').";
        // try {
        // ////((RConnection) this.rEngine).eval(rCode);
        // REXP r = ((RConnection) this.rEngine).eval(rCode);
        // if (r2.inherits("try-error")) {
        // logger.severe("R Error [1]: " + r.asString());
        // logger.severe("R eval attempt [1]: " + rCode);
        // logger.severe("Debug string" + r.toDebugString());
        // }
        // //else { /* success ... */ }
        // logger.severe("R error [3]: " + ((RConnection)
        // this.rEngine).getLastError());
        // }
        // catch (RserveException e) {
        // logger.severe("R error [2]: " + getErrMessage());
        // throw new RSessionWrapperException(msg);
        // } catch (Exception e) {
        // throw new RSessionWrapperException(e.getMessage());
        // }

        ok = this.session.voidEval(rCode, true); // TRY_MODE);
        if (!ok) {
          if (stopOnError)
            throw new RSessionWrapperException(msg);
          else
            checkConnectivity();
        }
      }
      return ok;
    } else { // RCaller

      try {

        ((RCaller) this.rEngine).getRCode().addRCode(rCode);
        // ((RCallerScriptEngine2) this.rEngine).eval(rCode);

      } catch (ExecutionException /* | ScriptException */ ee) { // RCaller
                                                                // exception
        if (stopOnError)
          throw new RSessionWrapperException(ee.getMessage());
        else
          return false;
      }
      return true;
    }

  }
 
Example #8
Source File: RSessionWrapper.java    From mzmine3 with GNU General Public License v2.0 4 votes vote down vote up
public void clearCode() {

    if (this.rEngineType == REngineType.RCALLER) {
      ((RCaller) this.rEngine).getRCode().clearOnline();
    }
  }
 
Example #9
Source File: RSessionWrapper.java    From mzmine3 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * This can be necessary to call 'close()' from a different thread than the one which called
 * 'open()', sometimes, with Rserve (if the related instance is busy).
 * 
 * @param userCanceled Tell the application the closure came from a user action rather than from
 *        an unknown source error.
 * @throws RSessionWrapperException
 */
public void close(boolean userCanceled) throws RSessionWrapperException {

  this.userCanceled = userCanceled;

  if (this.rEngineType == REngineType.RSERVE) {

    if (this.session != null) {

      try {

        logger.log(logLvl,
            "Rserve: try terminate " + ((this.rServePid == -1) ? "pending" : "") + " session"
                + ((this.rServePid == -1) ? "..."
                    : " (pid: '" + this.rServePid + "' | port: '" + this.session.rServeConf.port
                        + "')..."));

        // Avoid 'Rsession' to 'printStackTrace' while catching
        // 'SocketException'
        // (since we are about to brute force kill the Rserve
        // instance,
        // such that
        // the session won't end properly).
        RSessionWrapper.muteStdOutErr();
        {
          RSessionWrapper.killRserveInstance(this);
          this.session.end();
        }
        RSessionWrapper.unMuteStdOutErr();

        logger.log(logLvl,
            "Rserve: terminated " + ((this.rServePid == -1) ? "pending" : "") + " session"
                + ((this.rServePid == -1) ? "..."
                    : " (pid: '" + this.rServePid + "' | port: '" + this.session.rServeConf.port
                        + "')..."));

        // Release session (prevents from calling close again on a
        // closed instance).
        this.session = null;

      } catch (Throwable t) {
        // Adapt/refactor message accordingly to the way the
        // termination
        // was provoked:
        // User requested or unexpectedly...
        String msg;
        if (userCanceled) {
          msg = "Rserve error: couldn't terminate instance with pid '" + this.rServePid
              + "'. Details:\n";
        } else {
          msg = "Rserve error: something when wrong with instance of pid '" + this.rServePid
              + "'. Details:\n";
        }
        throw new RSessionWrapperException(msg + TextUtils.wrapText(t.getMessage(), 80));

      } finally {
        // Make sure to restore standard outputs.
        System.setOut(System.out);
        System.setErr(System.err);
      }
    }

    this.unRegister();

  } else { // RCaller

    // if (this.wasRunAndReturned) {
    // TODO: do nothing for now, see if a special treatment is required
    // when 'user canceling' a task or else !!!
    ((RCaller) this.rEngine).StopRCallerOnline();
    // } else {
    // this.runOnlyOnline();
    // }
    // ((RCallerScriptEngine2) this.rEngine).close();
  }
}
 
Example #10
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 #11
Source File: RSessionWrapper.java    From mzmine2 with GNU General Public License v2.0 4 votes vote down vote up
public boolean eval(String rCode, boolean stopOnError) throws RSessionWrapperException {

    // if (TRY_MODE) rCode = "try(" + rCode + ",silent=TRUE)";

    if (this.rEngineType == REngineType.RSERVE) {

      boolean ok = false;
      if (this.session != null && !this.userCanceled) {
        String msg = "Rserve error: couldn't eval R code '" + rCode + "' (instance '"
            + this.getPID() + "').";
        // try {
        // ////((RConnection) this.rEngine).eval(rCode);
        // REXP r = ((RConnection) this.rEngine).eval(rCode);
        // if (r2.inherits("try-error")) {
        // LOG.severe("R Error [1]: " + r.asString());
        // LOG.severe("R eval attempt [1]: " + rCode);
        // LOG.severe("Debug string" + r.toDebugString());
        // }
        // //else { /* success ... */ }
        // LOG.severe("R error [3]: " + ((RConnection)
        // this.rEngine).getLastError());
        // }
        // catch (RserveException e) {
        // LOG.severe("R error [2]: " + getErrMessage());
        // throw new RSessionWrapperException(msg);
        // } catch (Exception e) {
        // throw new RSessionWrapperException(e.getMessage());
        // }

        ok = this.session.voidEval(rCode, true); // TRY_MODE);
        if (!ok) {
          if (stopOnError)
            throw new RSessionWrapperException(msg);
          else
            checkConnectivity();
        }
      }
      return ok;
    } else { // RCaller

      try {

        ((RCaller) this.rEngine).getRCode().addRCode(rCode);
        // ((RCallerScriptEngine2) this.rEngine).eval(rCode);

      } catch (ExecutionException /* | ScriptException */ ee) { // RCaller exception
        if (stopOnError)
          throw new RSessionWrapperException(ee.getMessage());
        else
          return false;
      }
      return true;
    }

  }
 
Example #12
Source File: RSessionWrapper.java    From mzmine2 with GNU General Public License v2.0 4 votes vote down vote up
public void clearCode() {

    if (this.rEngineType == REngineType.RCALLER) {
      ((RCaller) this.rEngine).getRCode().clearOnline();
    }
  }
 
Example #13
Source File: RSessionWrapper.java    From mzmine2 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * This can be necessary to call 'close()' from a different thread than the one which called
 * 'open()', sometimes, with Rserve (if the related instance is busy).
 * 
 * @param userCanceled Tell the application the closure came from a user action rather than from
 *        an unknown source error.
 * @throws RSessionWrapperException
 */
public void close(boolean userCanceled) throws RSessionWrapperException {

  this.userCanceled = userCanceled;

  if (this.rEngineType == REngineType.RSERVE) {


    if (this.session != null) {

      try {

        LOG.log(logLvl,
            "Rserve: try terminate " + ((this.rServePid == -1) ? "pending" : "") + " session"
                + ((this.rServePid == -1) ? "..."
                    : " (pid: '" + this.rServePid + "' | port: '" + this.session.rServeConf.port
                        + "')..."));

        // Avoid 'Rsession' to 'printStackTrace' while catching
        // 'SocketException'
        // (since we are about to brute force kill the Rserve instance,
        // such that
        // the session won't end properly).
        RSessionWrapper.muteStdOutErr();
        {
          RSessionWrapper.killRserveInstance(this);
          this.session.end();
        }
        RSessionWrapper.unMuteStdOutErr();

        LOG.log(logLvl,
            "Rserve: terminated " + ((this.rServePid == -1) ? "pending" : "") + " session"
                + ((this.rServePid == -1) ? "..."
                    : " (pid: '" + this.rServePid + "' | port: '" + this.session.rServeConf.port
                        + "')..."));

        // Release session (prevents from calling close again on a
        // closed instance).
        this.session = null;

      } catch (Throwable t) {
        // Adapt/refactor message accordingly to the way the termination
        // was provoked:
        // User requested or unexpectedly...
        String msg;
        if (userCanceled) {
          msg = "Rserve error: couldn't terminate instance with pid '" + this.rServePid
              + "'. Details:\n";
        } else {
          msg = "Rserve error: something when wrong with instance of pid '" + this.rServePid
              + "'. Details:\n";
        }
        throw new RSessionWrapperException(msg + TextUtils.wrapText(t.getMessage(), 80));

      } finally {
        // Make sure to restore standard outputs.
        System.setOut(System.out);
        System.setErr(System.err);
      }
    }

    this.unRegister();

  } else { // RCaller

    // if (this.wasRunAndReturned) {
    // TODO: do nothing for now, see if a special treatment is required
    // when 'user canceling' a task or else !!!
    ((RCaller) this.rEngine).StopRCallerOnline();
    // } else {
    // this.runOnlyOnline();
    // }
    // ((RCallerScriptEngine2) this.rEngine).close();
  }
}