Examples of RConnection


Examples of org.rosuda.REngine.Rserve.RConnection

    ROutputHandler handler = new ROutputHandler(rServe.getInputStream(),
                                                BEGIN_MAGIC, END_MAGIC);
    handler.start();

    RConnection rconn = new RConnection("127.0.0.1", port);
    rconn.login("beaker", password);
    int pid = rconn.eval("Sys.getpid()").asInteger();
    return new RServer(rconn, handler, errorGobbler, port, password, pid);
  }
View Full Code Here

Examples of org.rosuda.REngine.Rserve.RConnection

    throws InterruptedException, REXPMismatchException, IOException
  {
    SimpleEvaluationObject obj = new SimpleEvaluationObject(code);
    obj.started();
    RServer server = getEvaluator(shellID);
    RConnection con = server.connection;
    boolean init = initString != null && initString.equals("true");

    String file = windows() ? "rplot.svg" : makeTemp("rplot", ".svg");
    try {
      java.nio.file.Path p = java.nio.file.Paths.get(file);
      java.nio.file.Files.deleteIfExists(p);
    } catch (IOException e) {
      // ignore
    }

    try {
      // direct graphical output
      String tryCode;
      if (init) {
        tryCode = code;
      } else {
        con.eval("do.call(svg,c(list('" + file + "'), beaker::saved_svg_options))");
        tryCode = "beaker_eval_=withVisible(try({" + code + "\n},silent=TRUE))";
      }
      REXP result = con.eval(tryCode);
      if (init) {
        obj.finished(result.asString());
        return obj;
      }

      if (false) {
        if (null != result)
          System.out.println("result class = " + result.getClass().getName());
        else
          System.out.println("result = null");
      }

      if (null == result) {
        obj.finished("");
      } else if (isError(result, obj)) {
      } else if (!isVisible(result, obj)) {
        obj.finished("");
      } else if (isDataFrame(result, obj)) {
        // nothing
      } else {
        server.outputHandler.reset(obj);
        String finish = "print(\"" + BEGIN_MAGIC + "\")\n" +
          "print(beaker_eval_$value)\n" +
          "print(\"" + END_MAGIC + "\")\n";
        con.eval(finish);
      }
    } catch (RserveException e) {
      if (127 == e.getRequestReturnCode()) {
        obj.error("Interrupted");
      } else {
        obj.error(e.getMessage());
      }
    }

    // flush graphical output
    try {
      con.eval("dev.off()");
    } catch (RserveException e) {
      obj.error("from dev.off(): " + e.getMessage());
    }

    addSvgResults(file, obj);
View Full Code Here

Examples of org.rosuda.REngine.Rserve.RConnection

      newRs = startRserve();
    } else {
      if (null == rServer) {
        rServer = startRserve();
      }
      RConnection rconn = new RConnection("127.0.0.1", rServer.port);
      rconn.login("beaker", rServer.password);
      int pid = rconn.eval("Sys.getpid()").asInteger();
      newRs = new RServer(rconn, rServer.outputHandler, rServer.errorGobbler,
                          rServer.port, rServer.password, pid);
    }
   
    this.shells.put(id, newRs);
View Full Code Here

Examples of org.rosuda.REngine.Rserve.RConnection

        // We do this by creating a new RConnection object which
        // searches for the already running process
        // We then check to see if it is connected. If not, start RServe
        // and try again.
        // If that doesn't work give up.
        rConnection = new RConnection(); // Throws an exception if it
        // doesn't connect
        return true;
      }
      else
      {
        return true;
      }
     
    }
    catch (Exception e)
    {
      // If we get here it means a previous RServer process was not open
      // and we should open one now
      try
      {
        ScriptRepository.startRServe();
        rConnection = new RConnection();
        return (R.isConnected());
      }
      catch (Exception e2)
      {
        // If we are here we should give up because we tries to start a
View Full Code Here

Examples of org.rosuda.REngine.Rserve.RConnection

  private static String rFolderName = "R_output";
 
  protected static RConnection getRConnection() throws RemoteException
  {
    RConnection rConnection = null; // establishing R connection   
    try
    {
      rConnection = new RConnection();
    }
    catch (RserveException e)
    {
      //e.printStackTrace();
      throw new RserveConnectionException(e);
View Full Code Here

Examples of org.rosuda.REngine.Rserve.RConnection

   
  }
 
  public static RResult[] runScript( String docrootPath, String[] inputNames, Object[] inputValues, String[] outputNames, String script, String plotScript, boolean showIntermediateResults, boolean showWarnings) throws RemoteException
  {
    RConnection rConnection = null;
    Vector<RResult> resultVector = new Vector<RResult>();
    try
    {
      rConnection = getRConnection()
      requestScriptAccess(rConnection); // important to run this before allowing end-user scripting
     
      // ASSIGNS inputNames to respective Vector in R "like x<-c(1,2,3,4)"     
      assignNamesToVector(rConnection,inputNames,inputValues);
      evaluateInputScript(rConnection, script, resultVector, showIntermediateResults, showWarnings);
      if (plotScript != "")
      {
        // R Script to EVALUATE plotScript
        String plotEvalValue = plotEvalScript(rConnection,docrootPath, plotScript, showWarnings);
        resultVector.add(new RResult("Plot Results", plotEvalValue));
      }
      for (int i = 0; i < outputNames.length; i++){// R Script to EVALUATE output Script
        String name = outputNames[i];           
        REXP evalValue = evalScript(rConnection, name, showWarnings)
        resultVector.add(new RResult(name, rexp2javaObj(evalValue)));         
      }
      // clear R objects
      evalScript(rConnection, "rm(list=ls())", false);
     
    }
    catch (Exception e)
    {
      e.printStackTrace();
      throw new RemoteException("Unable to run R script", e);
    }
    finally
    {
      if (rConnection != null)
        rConnection.close();
    }
    return resultVector.toArray(new RResult[resultVector.size()]);
  }
View Full Code Here

Examples of org.rosuda.REngine.Rserve.RConnection

    return rexp;
  }
 
  public static double[][] normalize(String docrootPath, Object[][] data) throws RemoteException
  {
    RConnection rConnection = null;
    double[][] result;
    try
    {
      rConnection = getRConnection();
      rConnection.assign("data", getREXP(data));
     
      String script = "normalized <- t(as.matrix(sapply(data, function(x) {(x - min(x, na.rm=TRUE))/(max(x, na.rm=TRUE)- min(x, na.rm=TRUE))})))";
     
      rConnection.eval(script);
     
      REXP evalValue = rConnection.eval("normalized");
      result = evalValue.asDoubleMatrix();
    }

    catch (Exception e)
    {
      e.printStackTrace();
      throw new RemoteException("Unable to run R normalize script", e);
    }
    finally
    {
      if (rConnection != null)
        rConnection.close();
    }
    return result;
  }
View Full Code Here

Examples of org.rosuda.REngine.Rserve.RConnection

    return result;
  }
 
  public static ClassDiscriminationResult doClassDiscrimination(String docrootPath, double[] dataX, double[] dataY, boolean flag) throws RemoteException
  {
    RConnection rConnection = null;
   
    ClassDiscriminationResult result = new ClassDiscriminationResult();
   
    try
    {
      rConnection = getRConnection();
     
      String script = "";
     
      rConnection.assign("x", dataX);
      rConnection.assign("y", dataY);
      if(flag)
      {
        script = "obj <- try(t.test(x, y, var.equal = TRUE, na.rm = TRUE), silent=TRUE)\n" +
            "if(is(obj, \"try-error\")) { statistic <- 0 \n  pvalue <- 0} else { cdoutput <- obj\n" +
            "statistic <- cdoutput$statistic\n" +
            "pvalue <- cdoutput$p.value}";
      } else {
        script = "obj <- try(t.test(x, y, var.equal = FALSE, na.rm = TRUE), silent=TRUE)\n" +
            "if(is(obj, \"try-error\")) { statistic <- 0 \n  pvalue <- 0} else { cdoutput <- obj\n" +
            "statistic <- cdoutput$statistic\n" +
            "pvalue <- cdoutput$p.value}";
      }
     
      rConnection.eval(script);
      result.pvalue = rConnection.eval("pvalue").asDouble();
      result.statistic = rConnection.eval("statistic").asDouble();
     
    }
   
    catch (Exception e)
    {
      e.printStackTrace();
      throw new RemoteException("Unable to run Class Discrimination Layout", e);
    }
    finally
    {
      if (rConnection != null)
        rConnection.close();
    }
   
    return result;
   
  }
View Full Code Here

Examples of org.rosuda.REngine.Rserve.RConnection

          "Unable to run computation on two arrays with different lengths (%s != %s).",
          dataX.length,
          dataY.length
        ));
   
    RConnection rConnection = null;
    LinearRegressionResult result = new LinearRegressionResult();
    try
    {
      rConnection = getRConnection();
     
      String equation = (String)MapUtils.fromPairs(
          "Linear", "y~x",
          "Polynomial", "y ~ poly(x, deg, raw = TRUE)",
          "Logarithmic", "y ~ log(x)",
          "Exponential", "log(y) ~ x",
          "Power", "log(y) ~ log(x)"
        ).get(method);
     
      String script = String.format(
        "fit <- lm(%s)\n"
        + "coef <- coefficients(fit)\n"
        + "rSquared <- summary(fit)$r.squared\n",
        equation
      );
     
      // Push the data to R
      rConnection.assign("x", dataX);
      rConnection.assign("y", dataY);
      rConnection.assign("deg", new int[]{polynomialDegree});

      // Perform the calculation
      rConnection.eval(script);

      // option to draw the plot, regression line and store the image
      /*
      rConnection.assign(".tmp.", docrootPath + rFolderName + "/Linear_Regression.jpg");
      rConnection.eval("jpeg(.tmp.)");
      rConnection.eval("plot(x,y)");
      rConnection.eval("abline(fit)");
      rConnection.eval("dev.off()");
       */

      // Get the data from R
      result.coefficients = rConnection.eval("coef").asDoubles();
      result.rSquared = rConnection.eval("rSquared").asDouble();
    }
    catch (Exception e)
    {
      e.printStackTrace();
      throw new RemoteException("Unable to run R regression script", e);
    }
    finally
    {
      if (rConnection != null)
        rConnection.close();
    }
    return result;
  }
View Full Code Here

Examples of org.rosuda.REngine.Rserve.RConnection

 
  public static RResult[] kMeansClustering( String[] inputNames, Object[][] inputValues, boolean showWarnings, int numberOfClusters, int iterations)throws RemoteException
  {
    RResult [] kClusteringResult = null;
    RConnection rConnection = null;
    try
    {
      rConnection = getRConnection()
      requestScriptAccess(rConnection); // doing this because the eval() call below is not safe
 
      int []noOfClusters = new int [1];
      noOfClusters[0] = numberOfClusters;
     
      int[]iterationNumber = new int[1];
      iterationNumber[0] = iterations;
     
      rConnection.assign("clusternumber", noOfClusters);
     
      //storing column length
      int columnLength = inputValues[0].length;
     
      //to check if columns are not empty and if all columns are of the same length
      for (int j = 1; j < inputValues.length; j++)
      {
        if (columnLength == 0 || inputValues[j].length == 0)
        throw new RemoteException("Unable to run computation on zero-length arrays.");
        if (inputValues[j].length != columnLength)
        throw new RemoteException("Unable to run computation on two arrays with different lengths (" + columnLength
          + " != " + inputValues[j].length + ").");
       
      }
     
      REXP evalValue; 
      String names = "";
     
//      We have to send columns to R and receive them back to be sent once again to R
      //enables 'n' number of columns to be sent
      for (int i = 0; i < inputNames.length; i++)
      {
        String name = inputNames[i];
        if(names.length() != 0){
          names = names + "," + name;}
        else{
          names = name;
        }
        double[] value = ListUtils.copyDoubleArray(inputValues[i], new double[inputValues[i].length]);
        rConnection.assign(name, value)
   
      }
      evalValue = rConnection.eval("data.frame(" + names + ")"); // NOT SAFE - script was built using user-specified strings
   
      rConnection.assign("frame",evalValue);
      rConnection.assign("clusternumber", noOfClusters);
      rConnection.assign("iterations",iterationNumber);

     
      //String script = "Clus <- kmeans(frame, "+numberOfClusters+","+iterations+")";
     
//    String clusteringScript = "Clustering <- function(dframe, clusternumber, iterations)\n" +
//                    "{result1 <- kmeans(dframe, clusternumber, iterations)\n " +
//                    "result2 <- kmeans(dframe, clusternumber, (iterations - 1))\n " +
//                    "while(result1$totss != result2$totss)\n"+
//                    "{iterations <- iterations + 1 \n " +
//                    "result1 <- kmeans(dframe, clusternumber, iterations)\n " +
//                    "result2 <- kmeans(dframe, clusternumber, (iterations - 1))\n }" +
//                    "print(result1)" +
//                    "print(result2)" +
//                    "}" +
//                    "KCluResult <- Clustering(frame,clusternumber, iterations)";
 
      String clusteringScript = "KClusResult <- kmeans(frame, clusternumber,iterations)";
     
      int i = 0;
      String[] outputNames = {"KClusResult$cluster", "KClusResult$centers"};
      evalScript(rConnection, clusteringScript, showWarnings);
     
      int iterationTimes = outputNames.length;
   
      kClusteringResult = new RResult[outputNames.length];
      for (; i < iterationTimes; i++)
      {
        String name;
        // Boolean addedTolist = false;
        if (iterationTimes == outputNames.length + 1){
          name = outputNames[i - 1];
        }
        else{
          name = outputNames[i];
        }
        // Script to get R - output
        evalValue = evalScript(rConnection, name, showWarnings);       
//        System.out.println(evalValue);
        if (evalValue.isVector()){
          if (evalValue instanceof REXPString)
            kClusteringResult[i] = new RResult(name, evalValue.asStrings());
          else if (evalValue instanceof REXPInteger)
            kClusteringResult[i] = new RResult(name, evalValue.asIntegers());
          else if (evalValue instanceof REXPDouble){
            if (evalValue.dim() == null)
              kClusteringResult[i] = new RResult(name, evalValue.asDoubles());
            else
              kClusteringResult[i] = new RResult(name, evalValue.asDoubleMatrix());
          }
          else{
            // if no previous cases were true, return debug String
            kClusteringResult[i] = new RResult(name, evalValue.toDebugString());
          }
        }
        else{
          kClusteringResult[i] = new RResult(name, evalValue.toDebugString());
        }
      }
    }
    catch (Exception e)
    {
      e.printStackTrace();
      throw new RemoteException("Unable to run R K-Means Clustering script", e);
    }
    finally
    {
      if (rConnection != null)
        rConnection.close();
    }
   
    return kClusteringResult;
  }
View Full Code Here
TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.