Skip to content
Nathan Jensen edited this page Mar 18, 2016 · 21 revisions

Since Jep 3.3

###Java primitive arrays <-> numpy.ndarrays Jep supports automatic conversion of Java primitive arrays to numpy.ndarrays. For ease and speed of copying the arrays between the two languages, the Java arrays must be one dimensional. This is to ensure a contiguous block of a known size of memory for the conversion. Conceptually the Java array can be n-dimensional with the dimensions argument, but in memory it must be one dimensional.

Sending a Java primitive array into Python as a numpy.ndarray is easy using the class jep.NDArray. For example:

try(Jep jep = new Jep(false)) {
   float[] f = new float[] { 1.0f, 2.1f, 3.3f, 4.5f, 5.6f, 6.7f };
   NDArray<float[]> nd = new NDArray<>(f, 3, 2);
   jep.set("x", nd);
}

Inside the interpreter, the variable named x will be a numpy.ndarray with shape (3,2) and dtype float32. If a Java method signature contains an NDArray, it will also be transformed when crossing between the languages. For example:

/**
 * If Python invokes this method, it will receive back a numpy.ndarray.
 */
public NDArray<?> getRawData() {
   // presuming this.rawdata is conceptually only 1-dimensional
   return new NDArray(this.rawdata, this.rawdata.length);
}
/**
 * If Python invokes this method, it should pass in a numpy.ndarray.
 */
public void setData(NDArray<?> dataFromPython) {
   // ignoring dimensions, presuming this.rawdata is conceptually only 1-dimensional
   this.rawdata = dataFromPython.getData();
}

At times Jep will convert a numpy.ndarray into a Java primitive array when the class NDArray does not fit a method signature. For example,

public void setFloatData(float[] dataFromPython) {
   // note that the dimensions are lost
   this.rawdata = dataFromPython;
}

In this scenario the information about the ndarray dimensions will not be sent along.

###Direct memory support Jep does not support direct memory sharing between numpy and Java, therefore changes in the array in one language are not reflected in the array in the other language. Currently all numpy <-> Java operations are completed with a memcpy(). (We are looking at adding direct memory support in a future release).

###Numpy gotchas Numpy currently does not support running in an embedded interpreter, though it mostly works. The following issues have been identified when using Jep. To see the issues in action, run the Java classes in the jep.test.numpy package.

All of these issues can be worked around with some minor code changes when you use Jep.

Clone this wiki locally