How to export data from R script within Java using Rserve? - java

I am using Rserve to access an R script through my Java project. The java code asks for a user input to enter the file location and stores in a String variable. This variable is then passes through to the R function which should read the file location perform some processes and then create a new folder and write the processed data in individual files and then print out on the console that all the files have been generated. I initially checked the R connection with a smaller version of the program and it worked. But, when I include the steps to write data to files, it shows the following error:
Enter the file path:
/home/workspace/TestR/test_file
Exception in thread "main" org.rosuda.REngine.Rserve.RserveException: eval failed, request status: error code: 127
at org.rosuda.REngine.Rserve.RConnection.eval(RConnection.java:234)
at testMain.main(testMain.java:23)
Moreover, the code also does not print any statements on the console which have to be printed via R from the Rscript. Here is the Java code:
import java.util.Scanner;
import org.rosuda.REngine.REXP;
import org.rosuda.REngine.REXPMismatchException;
import org.rosuda.REngine.REngineException;
import org.rosuda.REngine.Rserve.RConnection;
import org.rosuda.REngine.Rserve.RserveException;
public class testMain {
static String dirPath;
public static void main(String[] args) throws REXPMismatchException, REngineException {
// For user input
Scanner scanner = new Scanner(System.in );
System.out.println("Enter the file path: ");
dirPath = scanner.nextLine();
RConnection c = new RConnection();
// source the Palindrome function
c.eval("source('/home/workspace/TestR/Main.R')");
REXP valueReturned = c.eval("Main(\""+dirPath+"\")");
//c.eval("Main(\""+dirPath+"\")");
System.out.println(valueReturned.length());
}
}
And, here is the R script:
Main <- function(FILE_PATH)
{
## load libraries
library(MALDIquant)
library(MALDIquantForeign)
library(dcemriS4)
require(gridExtra) # also loads grid
library(lattice)
library(fields)
library(matlab)
library(rJava)
#Call the source files of the function which this script will use
source('/home/workspace/TestR/importAnalyzeFormat.R', echo=TRUE)
source('/home/workspace/TestR/exportFile.R', echo=TRUE)
source('/home/workspace/TestR/readRecalibratedSpectra.R', echo=TRUE)
spectralDataObjects <- importAnalyzeFormat(FILE_PATH)
p <- detectPeaks(spectralDataObjects, method="MAD", halfWindowSize=1, SNR=1)
# Assign the p to preprocessedDataObjects
preprocessedDataObjects<-p
dir.create("PreprocessedSpectra", showWarnings = FALSE)
setwd("PreprocessedSpectra")
for(i in 1:length(preprocessedDataObjects))
{
coordinateValue<-metaData(preprocessedDataObjects[[i]])
coordinates<-coordinateValue$imaging$pos
mzValues<-mass(preprocessedDataObjects[[i]])
intensityValues<-intensity(preprocessedDataObjects[[i]])
exportFile(coordinates,mzValues,intensityValues)
}
print("Files exported. Program will now terminate")
print("############################################################")
return(preprocessedDataObjects)
}
Can someone please help me?

You have an error in your script, a 127 means that there is a parse exception.
If you use something like this it will print out the error in the script.
c is the rserve connection in this case.
c.assign(".tmp.", myCode);
REXP r = c.parseAndEval("try(eval(parse(text=.tmp.)),silent=TRUE)");
if (r.inherits("try-error")) System.err.println("Error: "+r.toString())
else { // success .. }

Error code 127 means parsing exception.
Change your line:
c.eval("source('/home/workspace/TestR/Main.R')");
to
c.eval("source(\"/home/workspace/TestR/Main.R\")");
Now it is suppose to work.

Related

How to delete java.util.prefs storage on a Mac?

I'm using the java.util.prefs package to store some information entered by users. My understanding, based on documentation and this question is that the actual (user node) preferences are stored in ~/Library/Preferences/, in a file named after the package. So far, this all checks out: Whenever I store some data in the node, a file in this directory is created and using the command line tool plutil, I can inspect it and find the stored data.
However: When I delete the file, and restart my program, the data is still there. I couldn't find anything about that in the documentation or source code. Any help appreciated.
The following code demonstrates the behaviour, see command line session below:
package de.unistuttgart.ims.PreferencesTest;
import java.io.IOException;
import java.util.prefs.Preferences;
public class Main {
Preferences preferences = Preferences.userNodeForPackage(Main.class);
static Main app;
static String KEY = "KEY";
static String DEFAULTVALUE = "DEFAULTVALUE";
public static void main(String[] args) throws IOException {
app = new Main();
app.doStuff();
}
public void doStuff() throws IOException {
System.err.println("Retrieving value:");
System.err.println(preferences.get(KEY, DEFAULTVALUE));
System.err.println("Setting value:");
char ch = (char) System.in.read();
preferences.put(KEY, String.valueOf(ch));
}
}
Command line session:
$ java de.unistuttgart.ims.PreferencesTest.Main
Retrieving value:
DEFAULTVALUE
Setting value:
5
$ rm ~/Library/Preferences/de.unistuttgart.ims.plist
$ java de.unistuttgart.ims.PreferencesTest.Main
Retrieving value:
5
Setting value:
4
How can this be? Or: Where else are preferences stored?

Nothing happening when a R file is called from my Java code

I have a java code which has R programming steps in it which is running perfectly fine. But the same R programming steps are extracted into a R file (MyScript.r) and I tried to call this file from my java code. When I run my java code nothing seems to be happening. I may look dumb with what I'm trying to achieve, may be it's true as I don't have knowledge on R. So required your help on this.
My Java code with R programming steps inside it.
package com.rtest;
import java.io.IOException;
import org.rosuda.JRI.Rengine;
public class RWithJavaTest {
public static void main(String a[]) {
// Create an R vector in the form of a string.
String javaVector = "c(1,2,3,4,5)";
// System.out.println("System.getProperty(\"java.library.path\")>>"+System.getProperty("java.library.path")); //Prints path in env var
// Start Rengine.
Rengine engine = new Rengine(new String[] { "--no-save" }, false, null);
// The vector that was created in JAVA context is stored in 'rVector'
// which is a variable in R context.
engine.eval("rVector=" + javaVector);
// Calculate MEAN of vector using R syntax.
engine.eval("meanVal=mean(rVector)");
// Retrieve MEAN value
double mean = engine.eval("meanVal").asDouble();
// Print output values
System.out.println("Mean of given vector is=" + mean);
}
}
The above program when run, successfully giving me the output: 3.0
Java code with R programming steps included in R file and calling the R file from the java code.
package com.rtest;
import java.io.IOException;
public class RWithJavaTest {
public static void main(String a[]) {
try {
System.out.println("before..");
Runtime.getRuntime().exec("Rscript D:\\MyScript.R");
System.out.println("after..");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
R script:
// Create an R vector in the form of a string.
String javaVector = "c(1,2,3,4,5)";
// System.out.println("System.getProperty(\"java.library.path\")>>"+System.getProperty("java.library.path")); //Prints path in env var
// Start Rengine.
Rengine engine = new Rengine(new String[] { "--no-save" }, false, null);
// The vector that was created in JAVA context is stored in 'rVector'
// which is a variable in R context.
engine.eval("rVector=" + javaVector);
// Calculate MEAN of vector using R syntax.
engine.eval("meanVal=mean(rVector)");
// Retrieve MEAN value
double mean = engine.eval("meanVal").asDouble();
// Print output values
System.out.println("Mean of given vector is=" + mean);
I know what I did here is something completely wrong but seeking help on 2 things here.
1) How to correct my R Script so that it runs with out any issues
2) Java code to call the R Script, so I can see the output 3.0 once I run the code.
Below lines of code obviously worked for me and it calls the R file successfully.
ProcessBuilder pb = new ProcessBuilder("C:/Program Files/R/R-3.4.3/bin/Rscript.exe" ,"D:/RTest/MyScript.R");
pb.start();

Basic Java Runtime program cannot find python

Hello working on a small program that just needs to run a python script I have. This python script will play a given .wav file, and draw a shape on the turtle screen. As such, I'm not looking for an output to be returned to java. Here is my java code:
public class Driver {
public static void main(String[] args){
try {
Process p = Runtime.getRuntime().exec("python " +
" D:/Coding Files/Python/MusicColors.py" +" teenagers.wav");
}
catch (Exception e){
System.out.println(e);
}
}
}
The exception I get is:
java.io.IOException: Cannot run program "python":
CreateProcess error=2, The system cannot find the file specified
I probably am making a very stupid mistake as I have limited knowledge in the subject of processes and such. I added python to my system path, so whenever I put "python" into command line, it returns with
Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
And makes it the python shell.
Here is the exact line I added to my environment path:
C:\Users\Joe\AppData\Local\Programs\Python\Python35-32
If anyone can figure out where I went wrong I'd really appreciate it!
The $PATH variable you've set is not inherited in Java's execution context. Try passing the Python's bin path to exec()'s execution environment.
To do this, the code below first retrieve all the environment variables and create an array of ENV_KEY=ENV_VALUE pairs.
Then, the path to your Python's bin is appended to the PATH value.
Finally, we pass the array of all environment variables to exec() (via the second parameter).
import java.util.HashMap;
import java.util.Map;
public class Driver {
public static void main(String[] args){
try {
String[] commands = {"python D:/Coding Files/Python/MusicColors.py teenagers.wav"};
// Get a list of all environment variables
final Map<String, String> envMap = new HashMap<String, String>(System.getenv());
// Append Python bin path to Path
envMap.put("Path", envMap.get("Path") + ";C:/Users/Joe/AppData/Local/Programs/Python/Python35-32");
// Convert to an array of ENV_KEY=ENV_VALUE format strings
final String[] envs = new String[envMap.size()];
int i = 0;
for (Map.Entry<String, String> e : envMap.entrySet()) {
envs[i] = e.getKey() + '=' + e.getValue();
i++;
}
// Exec with the environment variables
Process p = Runtime.getRuntime().exec(commands, envs);
}
catch (Exception e){
System.out.println(e);
}
}
}

How To Use Rcaller with Java Servlet and read CSV file

I'm using R programing to analysis FFT . now I want to make Java web application/ java servlet and calling R to use Rcaller/Rcode for it . I have some reference about Calling Rcode in java application. http://code.google.com/p/rcaller/wiki/Examples
I have CSV File
for example A.csv
time Amplitude
1 0.00000 -0.021
2 0.00001 -0.024
3 0.00003 -0.013
4 0.00004 -0.023
5 0.00005 0.019
6 0.00007 -0.002
7 0.00008 -0.013
then I want to upload this file and use R Code for analysis FFT and Plot it.
Help is much appreciated! Thanks in advance, Maria
You start creating an instance of RCaller and set the current location of install Rscript.exe file. You can start with
RCaller caller = new RCaller();
Globals.detect_current_rscript();
caller.setRscriptExecutable(Globals.Rscript_current);
RCode code = new RCode();
or you can give the exact location
RCaller caller = new RCaller();
caller.setRscriptExecutable("c:\\path\\to\\Rscript.exe");
RCode code = new RCode();
Suppose your data is saved in a file mydata.csv.
code.addRCode("dat <- read.cvs(\"mydata.csv\", header=T, sep=\",\"");
then we are plotting the Amplitude
File file = code.startPlot();
code.addRCode("plot.ts(dat$Amplitude)");
code.endPlot();
and sending our code to R:
caller.setRCode(code);
caller.runOnly();
And now, the file variable holds the image data. It can be shown on screen using the code
code.showPlot(file);
For further reading, follow the blog entries on stdioe blog
When I execute this code is running but didn't show anything !!!!!!!
package test2;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import javax.swing.ImageIcon;
import rcaller.RCaller;
import rcaller.RCode;
import rcaller.exception.RCallerExecutionException;
import rcaller.exception.RCallerParseException;
public class Test2 {
public static void main(String[] args) {
Test2 test2=new Test2();
}
private int span;
#SuppressWarnings("empty-statement")
public void test2()throws IOException{
try {
RCaller caller = new RCaller();
caller.setRscriptExecutable("C:\\Program Files\\R\\R-3.0.3\\bin\\Rscript.exe");
RCode code = new RCode();
code.addRCode("dat<-read.csv(\"NetBeansProjects\"test2\"A.csv\",header=T,sep=\",\"");
File file=code.startPlot();
code.addRCode("plot.ts(dat$Amplitude)");
code.endPlot();
caller.setRCode(code);
caller.runOnly();
ImageIcon i=code.getPlot(file);
code.showPlot(file);
} catch (RCallerExecutionException | RCallerParseException e) {
System.out.println(e.toString());
}
}
}

passing files from R to Java

I m passing multiple tab delim files into R via Java.The R programm merges those tab delim files as single file and sends back to java and it is captured in the variable "name".Now I want to rename and save that file stored in "name" as tab delim using save dialog box in windows.Any help highly appreciated.Here is the java code:
import org.rosuda.REngine.*;
public class rjava {
// Before this run Rserve() command in R
public String ana(String filenames)
{
String name = "";
try{
System.out.println("INFO: Trying to connect to R ");
RConnection c = new RConnection();
System.out.println("INFO: Connected to R");
System.out.println("INFO: The Server version is "+ c.getServerVersion());
// c.voidEval("source('D:/combine/combining_files.r')");
c.voidEval("source('D:/combine/merge.r')");
c.assign("file",filenames);
// name = (c.eval("fn(file)").asString());
name = (c.eval("combine (file)").asString());
c.close();
}
catch(Exception e)
{
System.out.println("ERROR: In Connection to R");
System.out.println("The Exception is "+ e.getMessage());
e.printStackTrace();
}
return name;
}
}
I find passing complex objects between R and Java to be a pain the ass. I would not pass the full data, but rather would pass only file names as a string. Either have Java tell R to write out the new file (my pref) or have Java read in the file and then write out with a new name.
Can you modify the R program, so that it outputs files in the same path with a given file name, such as [path]/filename.out?
Otherwise, you can modify the execte string so that the R program outputs in a given location.
See http://cran.r-project.org/doc/manuals/R-intro.html#Invoking-R-from-the-command-line
When working at a command line on UNIX or Windows, the command ‘R’ can be used both for starting the main R program in the form R [options] [<infile] [>outfile]
-- EDIT
I just saw that you are using an RConnection. According to the R docs, you can define where to pipe stdout
The function sink, sink("record.lis") will divert all subsequent output from the console to an external file, record.lis.

Categories

Resources