0

I am trying to do simple math operations on every element of a Jython array in the following manner:

import math

for i in xrange (x*y*z):
    medfiltArray[i] = 2 * math.sqrt(medfiltArray[i] + (3.0/8.0)  )
    InputImgArray[i] = 2 * math.sqrt(InputImgArray[i] + (3.0/8.0)  )

The problem is that my array is large (8388608 elements) and the process takes a little more than 12 seconds. Is there a more efficient way to do this whole process? I found a slightly more faster way (about 7 seconds):

medfiltArray = map(lambda x: 2 * math.sqrt(x + (3.0/8.0)  ) ,  medfiltArray)    

The advantage of the for loop over this method is that I can modify several arrays of the same size simultaneously and therefore save up on net time. But despite all this, this is still very slow. In MATLAB modifying a matrix would take less than a second:

img = 2 * sqrt(img + (3/8));

Any tips on modifying arrays in Jython would be very appreciated. Thanks !!!

Haider
  • 341
  • 3
  • 18

2 Answers2

1

Python comes with batteries included but no good matrix batteries. Fortunately NumPy fixes that but unfortunately I don't know of the Jython alternatives from personal experience, only what a couple searches reveal: jnumeric (seems outdated), http://acs.lbl.gov/ACSSoftware/colt/ (outdated as well?), http://mail.scipy.org/pipermail/numpy-discussion/2012-August/063751.html and its SO link: Using NumPy and Cpython with Jython ..

In any case a simple CPython/NumpPy example could look like this:

import numpy as np

# dummy init values:
x = 800
y = 100
z = 100
length = x*y*z
medfiltArray = np.arange(length, dtype='f')
InputImgArray = np.arange(length, dtype='f')

# m is a constant, no reason to recalculate it 8million times
m = (3.0/8.0)
medfiltArray = 2 * np.sqrt(medfiltArray + m)
InputImgArray = 2 * np.sqrt(InputImgArray + m)

# timed, it runs in:
# real  0m0.161s
# user  0m0.131s
# sys   0m0.032s

Good luck finding your Jython alternative, I hope this sets you onto the right path.

Community
  • 1
  • 1
smassey
  • 5,875
  • 24
  • 37
  • Thanks for this. My life would be so much easier if Jython allowed the use of the numpy package. Going to try to find something equivalent to this in Java. – Haider Aug 21 '14 at 18:42
1

There is a fast vector and matrix java library called Vectorz. Vectorz can be imported in Jython and does the computation described in my question in about 200 ms. The user will have to switch over from the python (or java) arrays in Jython and use Vectorz arrays. There is also another solution, if you are doing image processing (like me), there is a program called ImageJ and it has extensive functionality. I am working on an ImageJ plugin and to do these math operations you can also use internal ImageJ math commands:

IJ.run(InputImg, "32-bit", ""); 
IJ.run(InputImg, "Add...", "value=0.375 stack"); 
IJ.run(InputImg, "Square Root", "stack"); 
IJ.run(InputImg, "Multiply...", "value=2 stack"); 

This takes only .1 sec.

Haider
  • 341
  • 3
  • 18