oracle / fastr

A high-performance implementation of the R programming language, built on GraalVM.
Other
623 stars 64 forks source link

Java interop - Calling R functions from Java code #96

Open mardukbp opened 5 years ago

mardukbp commented 5 years ago

The Java Parallel Optimization Package provides a pure-Java implementation of the UNCMIN algorithms used by the nlm function of the R package stats. In particular, JPOP enables the parallel evaluation of analytical functions, gradients, and Hessians, with multi-core optimization of computationally expensive functions.

I want to write an R function parnlm that provides a FastR interface to this package. Since the function to be optimized is defined in R, I would like to know how to pass an R function as an argument to a Java function. Maybe it involves compiling the function to Java bytecode?

steve-s commented 5 years ago

Hello Marduk,

the infrastructure can convert R functions to Java functional interfaces and vice versa. So for example:

public class MyJavaClass {
  public int sumRFunction(java.util.function.Function<Integer,Integer> lambda) {
    int res = 0;
    for (int i = 0; i < 10; ++i) {
      res += lambda.apply(i);
    }
    return res;
  }
}

and in R

> testObject <- new("MyJavaClass")
> testObject$sumRFunction(function(i) i*2L)
[1] 90

we should add this to our documentation. In case you weren't aware of the sources of the documentation for Java interop: this example may be useful and there is documentation at graalvm.org and in our repo.

steve-s commented 5 years ago

Btw. this looks like a very neat use-case for FastR: the interaction with Java should be both simpler and much much faster. If you can, let us know how this went.

mardukbp commented 5 years ago

Thank you Stepan! I have been thinking that FastR can provide an interactive interface to the hundreds of Java packages developed in academia in the last 20 years. I will experiment with JPOP and SSJ and report back.

steve-s commented 5 years ago

Sounds really interesting! Btw. if you need your Java Function to take/return something that cannot be expresses as Java type or is dynamic (sometimes this type, sometimes another), then you can always use java.util.function.Function<Object, Object>.

mardukbp commented 5 years ago

Yes, thanks. For reference, here is the documentation for the built-in functional interfaces. This issue should be discussed in Java interoperability. Until this is done, I would suggest reopening the issue just to remember that something is pending.

steve-s commented 5 years ago

I would suggest reopening the issue just to remember that something is pending.

indeed, good idea.