Equivalent of numpy.ascontiguousarray in Julia


#1

I would like to change a non-contiguous array to a contiguous one. What is the fastest way to do that in Julia?


#2

convert(Array,A) should work on objects which <:AbstractArray.


#3

Seems like it is not working. I am not sure if you can reproduce the problem I am getting, but here it is anyways.

I am trying to use the numpy_to_vtk function from vtk.numpy_support through PyCall to change a Julia array to a vtk array. This function only accepts C contiguous arrays as input. Now even when trying to call np.array through PyCall, the returned array is a Julia array, and using np.ascontiguousarray through PyCall also doesn’t do the trick as shown by the following repeating error. The error persists even when using np.ascontiguousarray(julia_array) and np.array(convert(Array, julia_array)) before passing the array to numpy_to_vtk.

ERROR: PyError (:PyObject_Call) <type 'exceptions.AssertionError'>
AssertionError('Only contiguous arrays are supported.',)
  File "C:\Program Files\VTK 7.1.1\bin\Lib\site-packages\vtk\util\numpy_support.
py", line 131, in numpy_to_vtk
    assert z.flags.contiguous, 'Only contiguous arrays are supported.'

Perhaps the question can be rephrased to how to make a C contiguous array inside Julia?


#4

Can you post a reproducible example?


#5
using PyCall
@pyimport numpy as np
@pyimport vtk.util.numpy_support as vtkns

julia_array = rand(3,3);
vtk_array = vtkns.numpy_to_vtk(np.array(julia_array))

Edited to add:

Using PyObject explicitly creates a proper numpy array with access to its fields and methods. I am interested in making a row-major or C contiguous array not an F contiguous array as shown by the flags.

julia> numpy_array = PyObject(np.array(rand(3,3)))
PyObject array([[ 0.55107837,  0.98646111,  0.80035289],
       [ 0.92075771,  0.08981173,  0.88408335],
       [ 0.50036782,  0.91732487,  0.65456648]])

julia> numpy_array[:flags]
PyObject   C_CONTIGUOUS : False
  F_CONTIGUOUS : True
  OWNDATA : False
  WRITEABLE : True
  ALIGNED : True
  UPDATEIFCOPY : False

#6

vtk_array = vtkns.numpy_to_vtk(PyReverseDims(julia_array))


#7

Perfect, thanks!

ETA: Except when I get the array back in Julia using vtk_to_numpy, it is trasposed, which is easy to work around, but worth mentioning.