2

I'm generating a binary data using a Fortran code. How can I read this data, convert it to float and plot it in Python?

I have the following code in Fortran90 that outputs the vector u data in a binary file.

program test
implicit none
  integer :: i, n
  real, allocatable :: u(:)

  n = 720
  allocate(u(0:n))

  !Set the data
  do i = 0, n
    u(i) =  exp(-(i-360.0)**2/200.0)
  end do

  !Save the data in a binary file
  open(3,file='exp.dat',form='unformatted',access='sequential')
  write(3) u
  close(3)

  deallocate(u)  
end program test

Then I ran this program and got a binary file called 'exp.dat'. I wrote the following script in Python3 to read the data from 'exp.dat' and convert it to float.

import numpy as np
filename = 'exp.dat'
data = np.fromfile(filename, 'float32')
print(np.shape(data))

However, when I run this script I get

(723,)

I would expect (721,) since we wrote the values of a vector of length 721 in 'exp.dat'. After looking at the values in the variable data, I realized that the convertion from bytes to float is not working properly. I also tried to see how this script works for a different set of datas and I got the same thing.

How can I fix it? Is there an easy way to read and convert this binary data to float?

Santos
  • 133
  • 3
  • An easy check is the length of the file in the filesystem... presumably it should be 721*4 bytes, if floats take 4 bytes. – Mark Setchell Aug 21 '19 at 21:29
  • If I create a 2884 byte file like this `dd if=/dev/zero bs=721 count=4 > exp.dat` and run your code, I get a shape of (721,) so I suspect your Fortran... – Mark Setchell Aug 21 '19 at 22:07
  • Please use tye generic tags for languages like [tag:fortran] and [tag:python]. Many more people will see your question and they will be the right people (Fortran or other tag followers). Add a version tag if the question is version-specific. – Vladimir F Героям слава Aug 22 '19 at 07:05
  • Fortran sequential files contain record markers. Use stream or direct files to store data without markers, we have duplicates. – Vladimir F Героям слава Aug 22 '19 at 07:07
  • 1
    Possible duplicate of [Fortran unformatted file format](https://stackoverflow.com/questions/8751185/fortran-unformatted-file-format) and https://stackoverflow.com/questions/48312718/why-is-fortran-producing-a-12-byte-binary-file-containing-an-integer-and-16-byte?noredirect=1&lq=1 – Vladimir F Героям слава Aug 22 '19 at 07:09

0 Answers0