Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force numpy array order to fortran style?

I am using quite a lot of fortran libraries to do some mathematical computation. So all the arrays in numpy need to be Fortran-contiguous.
Currently I accomplish this with numpy.asfortranarray().

My questions are:

  1. Is this a fast way of telling numpy that the array should be stored in fortran style or is there a faster one?
  2. Is there the possibility to set some numpy flag, so that every array that is created is in fortran style?
like image 913
Woltan Avatar asked Oct 07 '11 13:10

Woltan


People also ask

What is Fortran order in NumPy?

Fortran order/ array is a special case in which all elements of an array are stored in column-major order. Sometimes we need to display array in fortran order, for this numpy has a function known as numpy. nditer().

Is NumPy based on Fortran?

Various NumPy modules use FORTRAN 77 libraries, so you'll also need a FORTRAN 77 compiler installed. Note that NumPy is developed mainly using GNU compilers.

How do I arrange in NumPy?

arrange() It creates an array by using the evenly spaced values over the given interval. The interval mentioned is half opened i.e. [Start, Stop]).

What is NumPy order?

Ordered sequence is any sequence that has an order corresponding to elements, like numeric or alphabetical, ascending or descending. The NumPy ndarray object has a function called sort() , that will sort a specified array.


2 Answers

Use optional argument order='F' (default 'C'), when generating numpy.array objects. This is the way I do it, probably does the same thing that you are doing. About number 2, I am not aware of setting default order, but it's easy enough to just include order optional argument when generating arrays.

like image 70
milancurcic Avatar answered Oct 14 '22 19:10

milancurcic


Regarding question 2: you may be concerned about retaining Fortran ordering after performing array transformations and operations. I had a similar issue with endianness. I loaded a big-endian raw array from file, but when I applied a log transformation, the resultant array would be little-endian. I got around the problem by first allocating a second big-endian array, then performing an in-place log:

b=np.zeros(a.shape,dtype=a.dtype)
np.log10(1+100*a,b)

In your case you would allocate b with Fortran ordering.

like image 24
bdforbes Avatar answered Oct 14 '22 19:10

bdforbes