fastr icon indicating copy to clipboard operation
fastr copied to clipboard

Java interop - Calling R functions from Java code

Open mardukbp opened this issue 6 years ago • 6 comments

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?

mardukbp avatar Sep 14 '19 18:09 mardukbp

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 avatar Sep 15 '19 16:09 steve-s

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.

steve-s avatar Sep 15 '19 16:09 steve-s

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.

mardukbp avatar Sep 17 '19 08:09 mardukbp

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>.

steve-s avatar Sep 17 '19 14:09 steve-s

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.

mardukbp avatar Sep 17 '19 17:09 mardukbp

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

indeed, good idea.

steve-s avatar Sep 18 '19 00:09 steve-s