Giter VIP home page Giter VIP logo

rcaller's Introduction

Overview

Join the chat at https://gitter.im/jbytecode/rcaller Build Status Test Status Maven Central status DOI

RCaller is a software library which is developed to simplify calling R from Java. Despite it is not the most efficient way of calling R codes from Java, it is very simple to use and its learning curve is steep. It successfully simplifies and wraps type conversations and makes variables in each languages accessible between platforms. With the calling sequential commands facility, the performance is not lost through a single external process. Although R is single-threaded, multiple R processes can be created and handled by multiple RCaller instances in Java. A Servlet based application can instantiate many RCaller objects as well as it can use a single object by using sequential command invocation ability. The former use multiple environments which do not share the same variable pool, whereas, the latter shares a mutual variable pool and clients can communicate as well. RCaller is written purely in Java and it does not depend on any external libraries, that is, it is ready to run in any machines that Java and R installed. Simulation studies show that the other libraries such as Rserve and rJava outperform the RCaller by means of interaction times. As a result of this, RCaller is not suitable for the projects which have many clients that request relatively single and small computations. [RCaller: A Software Library for Calling R from Java - M. Hakan Satman]

Official publication

Official publication in JOSS

RCaller3 Documentation

Who uses RCaller?

RCaller is a production ready library for calling R functions from within Java. If you are developing Java software that needs enhanced statistical calculations, RCaller is a practical solution to integrate these languages. R has many well-tested and matured packages for automatic time series model selection, clustering, segmentation and classification, non-linear and robust regression estimations, data and text mining, linear and non-linear programming, generating plots, function optimization besides other research tools. RCaller brings all of the functionality that R serves in Java. Easy installation and integration steps and steep learning curve make RCaller a suitable solution. RCaller's computation overhead is generating XML files in R side and parsing XML to Java objects in Java side.

Dependencies

RCaller compiled jar library requires JRE (v11 or higher) and R installed in the runtime environment. If you want to compile from source, JDK (v11 or higher) and Maven (or Gradle) are also required for building process. Maven is responsible for downloading and install additional Java dependencies defined in pom file. RCaller does not use any version specific property of R.

Usage

It is recommended to take a look at the existing tests and examples

Here is a set of selected examples:

Performance details

RCaller uses XML for reading R output by default. This is lightweight but not very fast way. For speeding up the IO, install R arrow package and add dependencies org.apache.arrow:arrow-vector and org.apache.arrow:arrow-memory-netty to your Java project. RCaller will use Arrow format automatically if it is available both in R and Java.

Errors handling can impact performance in online mode and is disabled by default. Use RCaller.runAndReturnResultOnline(String var, boolean addTryCatch) method with addTryCatch = true for throwing R exceptions to Java.

API Docs

Here is the auto-generated Javadocs.

Building and Installing RCaller

There are many options to integrate RCaller with a Java Project. First option is to download pre-compiled jar file and add it to the classpath or pom.xml. pre-compiled jar files are here.

The second option is to compile from source. R should be installed to run tests. After building process, if everything is okay, a jar file is located in the target directory.

$ git clone https://github.com/jbytecode/rcaller.git
$ cd RCaller
$ mvn package

The last option is to use maven dependency:

<dependency>
  <groupId>com.github.jbytecode</groupId>
  <artifactId>RCaller</artifactId>
  <version>4.0.2</version>
</dependency>

The RCaller is located in the Maven Central Repository.

Benchmarks

You can test the performance of the library using the benchmark tool hosted here. This file tests costs of passing vectors and matrices from Java to R and vice versa.

Join us

If you want to join us, please follow the community guidelines here. We look forward to seeing your contributions.

Citation

Please refer to citation information given in file bibtex in your publications.

rcaller's People

Contributors

dependabot[bot] avatar dieresys avatar edineipiovesan avatar gitter-badger avatar jbytecode avatar kopilov avatar ksfx avatar marecabo avatar mbatchkarov avatar stevensotelo avatar vboerchers avatar waffle-iron avatar wongjoel avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

rcaller's Issues

problem with parse in utf-8

Your code has problems when a temp file "Routput" has special character with accents. I found this error and I want to contribute to fix it. can you invite me to contribute to this repository?

NullPointerException on Windows if R not installed in C:\Program Files

When running a 64-bit JVM on Windows, with only a 32-bit version of R installed, the R version detection code in Globals.java returns a null pointer exception in line 65. The following code seems to be the problem:

...
static {
        if (isWindows()) {
            String programFiles = System.getenv("ProgramFiles");
            if (programFiles == null) {
                programFiles = "C:\\Program Files";
            }
            File rBase = new File(programFiles, "R");
            File[] rVersions = rBase.listFiles(new FileFilter() {
                @Override
                public boolean accept(File pathname) {
                    return pathname.isDirectory() && pathname.getName().startsWith("R-");
                }
            });
Arrays.sort(rVersions);
...

When called from a 64-bit JVM, System.getenv("ProgramFiles"); returns "C:\Program Files", which is a problem when R is not installed under "C:\Program Files" (e.g. if R was installed under "C:\Program Files (x86)" instead).

I'm not too sure of the best way of fixing this - short term, maybe adding a check for null on rVersions before calling Arrays.sort could at least avoid the nullPointerException being thrown?

runAndReturnResultOnline doesn't detect when R has exited

I was running some R code that makes R to halt and exit. Since my runner was instantiated with default values, maxWaitTime was equal to Long.MAX_VALUE. Therefore runAndReturnResultOnline never returned.

Example R code:

RCaller rcaller = RCaller.create(RCallerOptions.create());
RCode code = RCode.create();
code.addRCode("dev.off();dev.off();a<-1:100000;");
rcaller.setRCode(code);
rcaller.runAndReturnResultOnline("a");

My proposal is to detect if the process has ended in the runAndReturnResultOnline loop.

[JOSS REVIEW] Suggestion for Software paper

This is a part of the JOSS review (openjournals/joss-reviews#2722)

  1. For the title, I suggest the authors add the version into the title as their manual, i.e. RCaller 3.0: A Java package for interfacing R
  2. I feel the Summary section is more like a state of the field or introduction. I suggest the authors change this section to a state of the field, as the review checklist suggests.
  3. I suggest the authors write a new summary, for example, the abstract in the manual may be a good summary for the paper.
  4. The target audience is not clear in the statement of need, I suggest the author make it clear as the review checklist suggests.

How to set path to R manually using script engine?

As far as I understand, when trying to use RCallerScriptEngine, the location to the R executable is controlled by the value of Globals.R_current. I suggest that perhaps there could be a way to pass in the location of the R executable with a parameter instead of modifying the value of Globals.R_current directly to avoid the problem I describe below?

I am attempting to call an old version of R, which is not being detected automatically, so I've been trying to set the path to R manually. I've worked out how to do it with RCaller by using

RCallerOptions options = RCallerOptions.create("C:\\Program Files (x86)\\R\\R-2.11.1\\bin\\Rscript.exe", "C:\\Program Files (x86)\\R\\R-2.11.1\\bin\\R.exe", FailurePolicy.RETRY_5, Long.MAX_VALUE, 100, RProcessStartUpOptions.create());
RCode code = RCode.create();
RCaller caller = RCaller.create(code, options);

but when I attempt to use RCallerScriptEngine, I can't work out the equivalent set up.

I tried to follow RCallerScriptEngineExample1, but upon attempting to access a field of the Globals class, I get an ExceptionInInitializerError.

In other words, when running the following line:

Globals.R_Current = "C:\\Program Files (x86)\\R\\R-2.11.1\\bin\\R.exe";

I get the following stack trace

java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.codehaus.mojo.exec.ExecJavaMojo$1.run(ExecJavaMojo.java:294)
        at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ExceptionInInitializerError
        at examples.RCallerScriptEngineExample1.<init>(RCallerScriptEngineExample1.java:18)
        at examples.RCallerScriptEngineExample1.main(RCallerScriptEngineExample1.java:11)
        at Main.main(Main.java:10)
        ... 6 more
Caused by: java.lang.NullPointerException
        at java.util.Arrays.sort(Arrays.java:1246)
        at com.github.rcaller.util.Globals.<clinit>(Globals.java:65)
        ... 9 more

As can be seen in the stack trace, I'm using Maven, but I don't think that's the reason for the Null Pointer Exception.

Anyway, all that to ask if modifying Globals.R_current is the intended way to manually set the location of the R executable, and if it would be difficult to make it a parameter that can be passed into a constructor instead.

Thanks again,

Problems with detection of R and with StopRCallerOnline()

Hi,

my problem seems to be that my R installation, which is not located in C:\Program Files, is not recognized properly. I found a way to make RCaller work, defining the location of R via RCallerOptions, but now i can't terminate my R process anymore, as StopRCallerOnline() throws an exception.
So here are the details:

When I try to recreate an example the line
RCaller caller = RCaller.create();
throws the following exception:

Exception in thread "main" java.lang.ExceptionInInitializerError
	at com.github.rcaller.rstuff.RCallerOptions.create(RCallerOptions.java:32)
	at com.github.rcaller.rstuff.RCaller.create(RCaller.java:83)
	at OnlineTest.main(OnlineTest.java:24)
Caused by: java.lang.NullPointerException
	at java.base/java.util.Arrays.sort(Arrays.java:1249)
	at com.github.rcaller.util.Globals.<clinit>(Globals.java:65)
	... 3 more

When I used RCaller like 2 years ago, the function
Globals.setRPaths(String,String)
helped, but this seems to exist no more.
So I found the following solution that works

String pathToRScript = "E:\\R\\R-3.5.1\\bin\\Rscript.exe";
String pathToR = "E:\\R\\R-3.5.1\\bin\\R.exe";
RCallerOptions options = RCallerOptions.create(pathToRScript, pathToR, FailurePolicy.RETRY_1, 3000l, 100l, RProcessStartUpOptions.create());
RCaller caller = RCaller.create(options);

This makes the examples work, but when I use runAndReturnResultOnline(), I can't terminate the R process, as StopRCallerOnline() throws the following similar exception:

Exception in thread "main" java.lang.ExceptionInInitializerError
	at com.github.rcaller.rstuff.RCaller.StopRCallerOnline(RCaller.java:324)
	at OnlineTest.main(OnlineTest.java:42)
Caused by: java.lang.NullPointerException
	at java.base/java.util.Arrays.sort(Arrays.java:1249)
	at com.github.rcaller.util.Globals.<clinit>(Globals.java:65)
	... 2 more

Also everything I try to do with Globals produces a similar ExceptionInInitializerError, caused by an NullPointerException at the same location:

Globals.detect_current_rscript();
System.out.println("R_current:" + Globals.R_current);
System.out.println("R_Win:" + Globals.R_Windows);
System.out.println("RScript_Win:" + Globals.RScript_Windows);
Globals.R_current = "E:\\R\\R-3.5.1\\bin\\R.exe";
Globals.Rscript_current= "E:\\R\\R-3.5.1\\bin\\Rscript.exe";

Any help is appreciated.

getting values as double matrix doesn't return correctly

For example, 83:2 matrix from ets$states that had variables like

l b
4000 -48
4000 -48
... ...

83 rows
returns like this if I use getAsDoubleMatrix, which is not right.

4000 4000
4000 4000
4000 4000

.......

-48 -48
-48 -48

I can get around this by doing this manually:
` double[]k = rc.getParser().getAsDoubleArray("states");
System.out.println(k.length);
int nrow = 83;
for(int i = 0; i<nrow;i++) {
for (int j = 0; j < k.length/nrow; j++)
System.out.print(k[i+j*nrow] + " ");

        System.out.println();
    }`

but ideally this should be the behavior of the double matrix function.

passing R objects of linear model

My problem is Rcaller doesn't pass some R objects of linear model
Assume simple linear model : Stay ~ Diet + Smoke + Diet:Smoke
The problem is to pass the dimension names in the matrix of coefficients (borders).

skrypt R: (syntaks.txt)

BaseFrame=read.csv("DietSmoke.txt")
modd<-glm(Stay ~ Diet + Smoke + Diet:Smoke , BaseFrame , family = gaussian)
coeff=summary(modd)$coef
lista<-list(r1=coeff,r2=dimnames(coeff))

results on RGui console:

lista
$r1
Estimate Std. Error t value Pr(>|t|)
(Intercept) 3.666667e+00 2.441159 1.502019e+00 0.1538496
DietB 1.833333e+00 2.989797 6.131965e-01 0.5489321
DietC 2.666667e+00 3.452321 7.724273e-01 0.4518611
SmokeY 5.333333e+00 3.452321 1.544855e+00 0.1432147
DietB:SmokeY -5.166667e+00 4.566991 -1.131306e+00 0.2756896
DietC:SmokeY 2.756121e-15 4.882319 5.645107e-16 1.0000000

$r2
$r2[[1]]
[1] "(Intercept)" "DietB" "DietC" "SmokeY" "DietB:SmokeY"
[6] "DietC:SmokeY"

$r2[[2]]
[1] "Estimate" "Std. Error" "t value" "Pr(>|t|)"

On the RGui console objects (r1, r2) are seen. Object r2 is string array of dimension names.When'll put R syntax to Rcaller object r2 is not passed to the java. When instead of a list I put alone the object dimnames(coeff) is the same .

Java code:

RCaller caller = new RCaller();
caller.setRscriptExecutable("C:\R\R-3.1.2\bin\Rscript.exe");
RCode code = new RCode();
code.addRCode(syntaks);
caller.setRCode(code);
caller.runAndReturnResult("lista");
System.out.println(caller.getParser().getNames());

Eclipse console shows " []"

I can add another examples when from list of objects only some objects are seen.
Is the another way to pass correlation matrix with labels (names of factors)?
I will be gratefull for the request.

RCaller DataFrame fails when passing data to R in Windows OS

Running the test class in https://github.com/jbytecode/rcaller/blob/master/RCaller/src/test/java/com/github/rcaller/datatypes/DataFrameTest.java in windows 10 fails in two tests as shown below. My best guess is the way that the data frame data is transferred to R according to the manual (https://github.com/jbytecode/rcaller/blob/master/doc/rcaller3/rcaller3.pdf, page 6). There it mentions that "In order to obtain the best performance and avoid any data loss, RCaller exports the data contained in the DataFrame object as a csv file. The path of the file will be transferred to R and it will be imported using the function read.csv on the R side.". Maybe in the path that is transferred backslashes are not escaped properly for windows OS?
Tests in error:
writeBigDataFrame(usertests.DataFrameTest): R command failed with error. Reason: Error: '\d' is an unrecognized escape in character string starting ""c:\d"
writeDataFrameToRAndGetMean(usertests.DataFrameTest): R command failed with error. Reason: Error: '\d' is an unrecognized escape in character string starting ""c:\d"

Tests run: 13, Failures: 0, Errors: 2, Skipped: 0

What happen with a syntactically wrong R command ?

I am new to RCaller, which seems very powerful. When I run the MultipleCalls example, I have no problem. But if I change the syntax of a wrong command (resulting in an R error) for example : code.addRCode("result <- sdds(x)"), then the program seems to loop for a while, not taking account of the R generated error.

Thank you very much.

auto-detection of rscript/r should not override user settings

This code looks valid to me but fails to run

    Globals.R_current = "/usr/local/bin/R"
    Globals.Rscript_current= "/usr/local/bin/RScript"

    val code = RCode.create()
    val rCaller = RCaller.create(code, RCallerOptions.create())

    code.addRCode("1+1")
    rCaller.runOnly()

The error is

Exception in thread "main" com.github.rcaller.exception.ExecutionException: Can not run /usr/bin/Rscript. Reason: java.io.IOException: Cannot run program "/usr/bin/Rscript": error=2, No such file or directory
	at com.github.rcaller.rstuff.RCaller.runRCode(RCaller.java:212)
	at com.github.rcaller.rstuff.RCaller.runOnly(RCaller.java:190)
	at com.r4intellij.RCallerDemoKt.main(RCallerDemo.kt:34)

The reasons seems that com.github.rcaller.rstuff.RCallerOptions#create() is overriding my custom settings by calling Globals.detect_current_rscript(); internally. The latter should check if the user has set own defaults before detecting R (which also lacks support for macos)

Manuscript submission

Hi friends,

I have prepared a manuscript and submitted to Journal of Open Source Software that presents RCaller. Since you all have valuable contributions, the dear editor @mikldk kindly asked me to ask if you would like to participate in this article. Here is the pre-review link: openjournals/joss-reviews#2600

If your answer is yes, please add your contributions and your name to the paper hosted in our RCaller repository (the paper directory). If your answer is no, please make an explanation.

Best wishes.

@paulcurcean
@mbatchkarov
@Kopilov
@dieresys
@wongjoel
@ksfx
@waffle-iron
@stevensotelo
@gitter-badger
@edineipiovesan
@sjcetx

R can be called without using the path to R

On Linux and Mac we can use R and Rscript from the commandline. No need to specify the path like /usr/bin/R
This way changing between OS does not affect the application.

Checking that the files exists breaks this functionality. Because java does not see executables as files.

this breaks switching between mac and linux:

    File file = new File(RExecutable);
    if (!file.exists()) {
        throw new RExecutableNotFoundException("R Executable " + RExecutable + " not found");
    }

Restore Thread interrupt flag after wait

rcaller code makes the Thread to wait/sleep at some points (which is fine). The problem is that, if the Thread was interrupted, these methods throw an InterruptedException, which is caught and rethrown by rcaller without restoring the interrupted thread flag.

Example in rcaller 2.8: https://github.com/jbytecode/rcaller/blob/c586cb7c74d2e570d6b3ef242c8f3c1561cac49d/RCaller/src/main/java/com/github/rcaller/rstuff/RCaller.java

The method runRCode uses the method Process.waitFor, which throws an InterruptedException if the Thread was interrupted, and reinit the interrupted flag of the Thread. A good practice is to catch the InterruptedException and to restore the interrupted flag. For instance:

try {
    //this Process object is local to this method. Do not use the public one.
    process = exec(RscriptExecutable + " " + rSourceFile.toString());
    startStreamConsumers(process);
    returnCode = process.waitFor();
} catch (Exception e) {
    if (e instanceof InterruptedException) {
        //restore the interrupt flag so that applications don't loose this information
        Thread.currentThread().interrupt();
    }
    throw new ExecutionException("Can not run " + RscriptExecutable + ". Reason: " + e.toString());
}

does not import R packages correctly

I have been trying to use the 'semPlot' package within RCaller's functionality but I am receiving an error that there is no package called 'semPlot', leading to the error that 'semPaths' is an unknown function since 'semPlot' is not imported. I already have the package installed in R and functioning in RStudio. I transferred the code into RCaller to be used. Here is the code I came up with. I happen to be attempting to plot something in this case because that is my ultimate goal but without trying to plot anything, my packages are still not being found:

   `RCode code = RCode.create();

    code.addRCode("x1 <- rnorm(50)");

    code.addRCode("x2 <- rnorm(50)");

    code.addRCode("x3 <- rnorm(50)");

    code.addRCode("x4 <- 2*x1+.3+rnorm(50,sd=.2)");

    code.addRCode("x5 <- 2*x2+.3+rnorm(50,sd=.1)");

    code.addRCode("x6 <- 2*x3+.3+rnorm(50,sd=.3)");

    code.addRCode("data <- data.frame(x1,x2,x3, x4,x5,x6)");

    code.addRCode("data.fact <- factanal(data,3,methods=\"MLE\")");

    File file = code.startPlot();

    System.out.println("Plot will be saved to : " + file);

    code.addRCode("library(semPlot)");

    code.addRCode("semPaths(data.fact, \"est\")");

    code.endPlot();

    rCaller.setRCode(code);

    rCaller.runOnly();

    code.showPlot(file);`

How do you import R packages into RCaller? Also, if there is any difference in procedure for importing into use with RCaller plots, how does that work?

JVM languages

I created a folder and started to give some examples on using RCaller in other JVM languages (The first example is in Clojure). We can add some usage examples and code snippets about the other JVM languages including Scala and Kotlin.

I also added a link in README.md section to this documentation.

Here is the example: RCaller and Clojure

Best.

@Kopilov

How to run "runAndReturnResult" multiple times in Java ?

Screenshot from 2021-06-10 11-59-44

Above is my java code as I am getting values from dataframe to a variable and getting it's values.So,I need to use the command "runAndReturnResult" multiple times. While doing this I am getting below error.

0 = 2356040.74911315
1 = 2506554.65816997
2 = 2313497.11496627
3 = 2399868.1618223
Exception in thread "main" com.github.rcaller.exception.ExecutionException: Can not run /usr/local/bin/Rscript. Reason: java.lang.IllegalThreadStateException
at com.github.rcaller.rstuff.RCaller.runRCode(RCaller.java:261)
at com.github.rcaller.rstuff.RCaller.runAndReturnResult(RCaller.java:540)
at estimate.hello.rCall(hello.java:88)
at estimate.hello.main(hello.java:110)


For first time it's running fine but for second time getting error.Please anyone helpme out to solve it.Thank you.

maven in Actions and submitting new version in the maven repo

Hi all,

We have already CI integration so after each single commit we show up an image that indicates whether RCaller successfully compiles or not, in the README.md file.

Now, we need these:

  • Can somebody setup a maven action in Actions section with all tests are passed?
  • Can somebody submit the latest release into Maven repos?
  • Can somebody setup a release tagger in Actions, so we can serve compiled jars with diff's compared to the previous release?

Thank you in advance.

[JOSS REVIEW] Suggestion for Documentation

This is a part of the JOSS review (openjournals/joss-reviews#2722)

  1. It is not clear that who is the target audience, I suggest the authors make it clear as the review checklist suggests.
  2. For the installation, the version of RCaller in the Maven dependency code in the manual is 3.0, whereas it is 2.8 in the README.md. This makes me confused which version I should use. I also feel that the instruction for installation in the manual is better than that in the README.md. It tells readers more clearly that there are two approaches to install RCaller, one is through Maven, the other is by downloading the jar file and add it into the classpath. I suggest the authors also replace the instruction for installation in the README.md by the instruction in the manual.
  3. It is not clear that what are the dependencies for RCaller, at least, the authors should state which version of Java is required for RCaller. Or does RCaller support all the versions of Java? Based on my simple test, it looks like RCaller does not support Java 1.5. Besides, RCaller is an interface between R and Java, therefore, another dependency should be R at least. Does RCaller support all the versions of R? In Page 3 of the manual, the second paragraph of the Setup and Installation section, it says that all the dependencies including the libraries that RCaller imports are downloaded. What are the dependencies that RCaller imports and downloads? I suggest the authors make the versions of Java and R as well as the dependencies clear in the documentation. Also, I suggest the authors list the dependencies in the README.md for the RCaller repo, so that users do not need to search for them in the long manual.
  4. The authors provide a lot of examples, but it is not clear that what the purpose for each example is. For example, the authors only named the examples such as Example2.java, Example3.java and so on. It is difficult for users to figure out what the example is used for by themselves. I suggest the authors rename the example files and add annotation into the examples for users to have a better understanding. Also, I suggest the authors list their examples in the README.md, so that users can quickly find out the examples they need instead of searching examples one by one.
    The authors also provided several code examples in the manual, e.g., Listing 3. However, after copying these codes and pasting them into the IDE, these codes became weird and I have to reformat them. Therefore, I suggest the authors use more simple style, e.g. remove the line number and use plain text, for their code examples in the manual, so that users can copy and test the codes more easily.
  5. API method documents are missing. The authors should add them into the repo as the review checklist suggests.
  6. The community guidelines are missing. The authors should add them into the README.md as the review checklist suggests.

Closing plot window closes parent application too.

Hello.
I generate plots using RCaller. The plots looks fine. But when user close plot window, parent window also getting close.
It seems to me, that parent window should not be close in the case.

I suppose that the reason of the behavior is

public RPlotViewer(ImageIcon img) {
this.img = img;
this.setSize(img.getIconWidth() + 20, img.getIconHeight() + 60);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("RCaller 2.0 - Generated Plot");
repaint();
}

I think to close plot window, without closing all application JFrame.DISPOSE_ON_CLOSE
should be used.

RCaller, parser and R version 4

I am using RCaller and get results as a xml file with parser.getXMLFile. It was used to work fine. I have updated RCaller version 4.0.2 and it is still working. For one of my colleagues using R version 4, it appears that instruction parser.getXMLFile() returns null. I have noticed that this command is deprecated. I would like to know if this this issue has been noticed? And if there is is an example where rcaller.parsXMLFile is replaced with rcaller.getIPCResource?

Many thanks

Exception when variable names contains '&' character

When a variable name contains an R character and must be returned by runAndReturnResult(), the following exception occours:

Exception in thread "main" com.github.rcaller.exception.ParseException: Can not handle R results due to : Can not parse the R output: org.xml.sax.SAXParseException; lineNumber: 4; columnNumber: 3078; The reference to entity "b" must end with the ';' delimiter.
    at com.github.rcaller.rStuff.RCaller.runAndReturnResult(RCaller.java:412)

Example: suppose I have a CSV file named candidates.csv containing a row like:

ID,Feature1,Feature2,Feature3
a&b,1,0.01,0.65

And a variable named model in a file called model.RData to be used with R's predict function. If I run the following code inside RCaller:

require("nnet")
load("/tmp/model.RData")
predictions <- read.csv("/tmp/candidates.csv",stringsAsFactors = FALSE)
predictions$score <- predict(model,newdata = predictions,type="raw")

And try to get the value of predictions with runAndReturnResult("predictions");, the aforementioned exception occours.

Rcaller and concurrency

I am trying to control the RCallerRunOnLine calls to rcaller and search the way to interrupt them when they result in too long computations. I am using the Java concurrent framework, which I don't know very well.

With the following program,

import`_`` com.github.rcaller.rstuff.*;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import java.util.List;
import java.util.concurrent.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class CallerApplication extends Application {

    public static void main(String[] args) { launch(args); }

    static RCaller caller;
    RCode code;
    ExecutorService executor;
    RunRCommand runRCommand;

    @Override
    public void start(Stage primaryStage) {
        // -----------------------------
        GridPane gridPane = new GridPane();
        Button stop = new Button("Stop");
        stop.setOnAction(e -> {
            caller.StopRCallerOnline();
            executor.shutdownNow();
        });
        gridPane.add(stop,0,0);
        Scene scene = new Scene(gridPane, 300, 300);
        primaryStage.setScene(scene);
        // -----------------------------
        executor = Executors.newFixedThreadPool(10);
        runRCommand = new RunRCommand();
        executor.execute(runRCommand);
        // -----------------------------
        primaryStage.show();
        // -----------------------------
    }

    void initR(){
        code = RCode.create();
        RCallerOptions rCallerOptions = RCallerOptions.create(
                "/usr/local/bin/Rscript",
                "/usr/local/bin/R", FailurePolicy.RETRY_5,
                9223372036854775807L,
                100L,
                RProcessStartUpOptions.create());
        caller = RCaller.create(code, rCallerOptions);
        code.clear();
        String  n = "10000"; 
        StringBuilder sb = new StringBuilder("");
        sb.append("for(j in 1:"+n+") { \n");
        sb.append("for(i in 1:"+n+") { u <- cos( (i+j) *pi/180) } \n");
        sb.append("} \n");
        sb.append("resultR <- 'ok'");
        code.addRCode(sb.toString());
    }

    public  class RunRCommand implements Runnable {
        @Override
        public void run(){
            initR();
            caller.runAndReturnResultOnline("resultR");
            String result = "No result";
            try {
                ROutputParser parser = caller.getParser();
                result = RCallerDecodeResult.decodeParser(parser);
            } catch (Exception e) {
                Logger.getLogger(RCallerStuff.class.getName()).log(Level.SEVERE, e.getMessage());
                e.printStackTrace();
            }
        }
    }
}

When I stop the R call, I get errors such as :
java.lang.InterruptedException: sleep interrupted,
can not send the source code to R file due to: java.io.IOException: Stream Closed Maximum number of retries exceeded.

I am not certain that the R process has been cleanly interrupted.

I would be happy to know if there is a simpler and more adequate way to interrupt a RCallerRunOnLine call.
.

DataFrame with path error in Windows

in rcaller/RCaller/src/main/java/com/github/rcaller/rstuff/RCaller.java
L198
process = exec(rCallerOptions.getrScriptExecutable() + " " + rSourceFile.toString());

which generate temp csv file, and make R use read.csv to read csv file
windows's file path in R script should be transfered
I got temp R script like
D1 <- read.csv("C:\Users\Luke\AppData\Local\Temp\dataFrame1341473091585654957.csv")

maybe this code can be changed like this
String csv_path = com.github.rcaller.util.Globals.isWindows()? rSourceFile.toString().replace("\\","/"): rSourceFile.toString() ; process = exec(rCallerOptions.getrScriptExecutable() + " " + csv_path);

New NullPointerException whith R installed on E:

Hi,
I followed the discussion in NullPointerException on Windows if R not installed in C:\Program Files #22 closely as I had the same problem, and was very happy to see the fast presentation of a solution.
So I got the updated version, but unfortunately RCaller is still not working for me.
The simple code

import com.github.rcaller.rstuff.RCaller;
import com.github.rcaller.util.Globals;

public class Test{
	public static void main( String[] args ){
		Globals.setRPaths( "E:\\R\\R-3.1.1\\bin\\Rscript.exe" , "E:\\R\\R-3.1.1\\bin\\R.exe" );
		RCaller caller = RCaller.create();
	}
}

gives the following Exception:

Exception in thread "main" java.lang.NullPointerException
	at java.io.Reader.<init>(Unknown Source)
	at java.io.InputStreamReader.<init>(Unknown Source)
	at com.github.rcaller.rstuff.RCode.clear(RCode.java:77)
	at com.github.rcaller.rstuff.RCode.create(RCode.java:52)
	at com.github.rcaller.rstuff.RCaller.create(RCaller.java:83)
	at Test.main(Test.java:7)

Interestingly, when I delete the Globals.setRPaths(...) line, the Exception stays the same.
I also tried to install a new version of R in C:\Program Files, but still got the same problem.
As lines 76 and 77 of RCode.class are

InputStream is = this.getClass().getClassLoader().getResourceAsStream("runiversal.r");
InputStreamReader inputStreamReader = new InputStreamReader(is);

i double checked the installation of Runiversal and it is in E:\R\R-3.1.1\library\Runiversal as I guess it should be.
Thanks for reading this, any hint would be appreciated.

Error in runiversal.r when running some code in Scala

What steps will reproduce the problem?

  1. Run the following code in Scala's REPL:
import com.github.rcaller.rstuff.{RCaller, RCode}
val rCaller = RCaller.create()
val rCode = RCode.create()
rCode.addRCode("result <- vector('list', 2)")
rCode.addRCode("result[[1]] <- 'c(1,3)'")
rCode.addRCode("result[[2]] <- 'c(1,3)'")
rCaller.setRCode(rCode)
var a = rCaller.runAndReturnResult("result")

What is the expected output?
A vector containing two strings.

What do you see instead?
The following error:

com.github.rcaller.exception.ExecutionException: R command failed with error. Reason: Error in strsplit(names, "\\.") : non-character argument
Calls: cat ... makevectorxml -> cleanNames -> paste -> unlist -> strsplit
Execution halted

  at com.github.rcaller.rstuff.RCaller.runRCode(RCaller.java:217)
  at com.github.rcaller.rstuff.RCaller.runAndReturnResult(RCaller.java:379)
  ... 42 elided

What version of the product are you using? On what operating system?

  • RCaller-3.1-SNAPSHOT-jar-with-dependencies.jar
  • Ubuntu 14.04.
  • Scala version 2.11.7 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_101)

Please provide any additional information below.

The problem is located in runiversal.r. names(result) returns NULL, and then strsplit fails.

(originally created here by mistake)

Faster Data Transfer

The current Data Transfer over Files is very slow and error prone. Especially when there is no efficient signaling mechanism used.
XML as a dataformat is also not ideal for big data due to size overhead and the De-/Serialization time needed.

One of the fastet or maybe the fastet way to do local IPC is over Shared Memory.
It should be very easy to understand because RAM is much faster than a hard disk or even an SSD.

Why not reengineering this part of RCaller to support Shared Memory?

Errors when running example code

I'm trying to integrate RCaller into a project but get an exception whenever calling "caller.getParser()".

For example, running the "Example2" code from https://github.com/jbytecode/rcaller/blob/master/RCaller/src/main/java/examples/Example2.java gives the following exception:

Exception in thread "main" java.lang.AbstractMethodError: gnu.xml.dom.DomElement.getTextContent()Ljava/lang/String;
    at com.github.rcaller.rstuff.ROutputParser.getAsStringArray(ROutputParser.java:175)
    at com.github.rcaller.rstuff.ROutputParser.getAsDoubleArray(ROutputParser.java:186)
    at examples.Example2.<init>(Example2.java:96)
    at examples.Example2.main(Example2.java:43)

I have RCaller 3.1 and R 3.3.1 installed. What am I missing?

publish to sonatype or bintray

Please, publish to either sonatype or bintray so people will be able to use your lib as dependency in sbt/maven/gradle

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.