user3032683
user3032683

Reputation:

Creating nd JArray with jcc from numpy array

I have some java classes (not written by me) that I'm trying to access from python. I have succesfully compiled them with JCC and can access the methods without any problem. I can call a method requiring a numpy 1D array (or a list, which are the same), but I can't figure out how to create a 2D, or 3D, JArray to feed to the code.

It seems that since numpy arrays are embedded list, they can't be converted straightforwardly to JArrays. The JCC doc tries to explain how to do it, but it's completely obscure.

http://lucene.apache.org/pylucene/jcc/readme.html

cast obj to an array of Document

       JArray('object').cast_(obj, Document)

In both cases, the java type of obj must be compatible with the array type it is being >cast to.

using nested array:

       d = JArray('object')(1, Document) d[0] = Document() d JArray<object>[<Document: Document<>>] d[0] <Document: Document<>> a = JArray('object')(2) a[0] = d a[1] = JArray('int')([0, 1, 2]) a JArray<object>[<Object: [Lorg.apache.lucene.document.Document;@694f12>, <Object: [I@234265>] a[0] <Object: [Lorg.apache.lucene.document.Document;@694f12> a[1] <Object: [I@234265> JArray('object').cast_(a[0])[0] <Object: Document<>> JArray('object').cast_(a[0], Document)[0] <Document: Document<>> JArray('int').cast_(a[1]) JArray<int>[0, 1, 2] JArray('int').cast_(a[1])[0] 0

Here's some code, but since this needs also need a compiled java class to work,I only want to make JArrays work in more than 1d.

import my_java_class
import numpy as np
my_java_class.initVM()

arr = np.ones(10)
# This makes a 1d JArray that can be later used by the java classes in my_java_class
j_arr = my_java_class.JArray('float')(arr) 
arr_2d = np.ones((10,10))
# This fails since the nested lists can't be converted to a 2d JArray.
j_arr2d = my_java_class.JArray('float')(arr_2d) 

I also tried re-embedding JArrays inside JArrays like the jcc docs seems to do, but that doesn't seem to work either.

Upvotes: 1

Views: 566

Answers (1)

marscher
marscher

Reputation: 830

at least for double arrays you can do this via:

a = JArray('double')(np.ones(3))
b = JArray('double')(np.ones(3))

ab = JArray('object')((a, b))

This creates a two-dimensional array (haven’t figured out howto do it with tensors)

Upvotes: 0

Related Questions