Tejas Shetty
Tejas Shetty

Reputation: 715

Can one save Fortran arrays in .npy format?

I am using Fortran for my numerical computations. The common standard in Fortran is to save the array as a .dat file. I want to occasionally transfer the array to Python for further manipulations. Ways to do this thing

.dat file script reader would need to be customised t0 the way the arrays are stored. Would need to store probably one array per file for ease of use. My arrays are not that big so, I am not fond of using HDF5. But do let me know if there is no other option.

This is the opposite of Reading arrays from .npy files into Fortran 90

Upvotes: 2

Views: 441

Answers (1)

Tejas Shetty
Tejas Shetty

Reputation: 715

I have not MRedies NPY-for-Fortran used enough yet, but it seems to be what you are looking for.

From the README

NPY for Fortran

This Fortran module allows to save numerical Fortran arrays in Numpy's .npy or .npz format. Currently supported are:

1. integer(1), integer(2), integer(4), integer(8)
2. real(4), real(8)
3. complex(4), complex(8)

*.npy files Saving an array into a .npy-file is simply done by calling:

call save_npy("filename.npy", array) 

Also, keep an eye out for this pull request on the fortran standard library

Another option, not tested by me

Not my idea See first CAZT's comment on CAZT's stackoverflow answer

libnpy seems to be a library that provides simple routines for saving a C or Fortran array to a data file using NumPy's binary format.

The following is an excerpt from https://scipy-cookbook.readthedocs.io/items/InputOutput.html

program fex
    use fnpy
    use iso_c_binding
    implicit none

    integer  :: i
    real(C_DOUBLE) :: a(2,4) = reshape([(i, i=1,8)], [2,4])

    call save_double("fa.npy", shape(a), a)
end program fe

The program creates a file fa.npy that you can load into python in the usual way.

But the entries of the NumPy array now follow the Fortran (column-major) ordering.

>>> fa = np.load('fa.npy')
>>> print fa
[[ 1.  3.  5.  7.]
 [ 2.  4.  6.  8.]] 

You can build the executable with npy.mod and libnpy.a in the same directory as fex.f95 with the command.

gfortran -o fex fex.f95 libnpy.a

Just for info, I stumbled upon a newer version of libnpy at https://github.com/kovalp/libnpy

Probable bug

from Matthias Redies If you save some array slice call save_npy(a(:,1,:)) with libnpy you are not going to be happy.

Upvotes: 1

Related Questions