_fortran.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. """
  2. Module to read / write Fortran unformatted sequential files.
  3. This is in the spirit of code written by Neil Martinsen-Burrell and Joe Zuntz.
  4. """
  5. import warnings
  6. import numpy as np
  7. __all__ = ['FortranFile', 'FortranEOFError', 'FortranFormattingError']
  8. class FortranEOFError(TypeError, OSError):
  9. """Indicates that the file ended properly.
  10. This error descends from TypeError because the code used to raise
  11. TypeError (and this was the only way to know that the file had
  12. ended) so users might have ``except TypeError:``.
  13. """
  14. pass
  15. class FortranFormattingError(TypeError, OSError):
  16. """Indicates that the file ended mid-record.
  17. Descends from TypeError for backward compatibility.
  18. """
  19. pass
  20. class FortranFile:
  21. """
  22. A file object for unformatted sequential files from Fortran code.
  23. Parameters
  24. ----------
  25. filename : file or str
  26. Open file object or filename.
  27. mode : {'r', 'w'}, optional
  28. Read-write mode, default is 'r'.
  29. header_dtype : dtype, optional
  30. Data type of the header. Size and endiness must match the input/output file.
  31. Notes
  32. -----
  33. These files are broken up into records of unspecified types. The size of
  34. each record is given at the start (although the size of this header is not
  35. standard) and the data is written onto disk without any formatting. Fortran
  36. compilers supporting the BACKSPACE statement will write a second copy of
  37. the size to facilitate backwards seeking.
  38. This class only supports files written with both sizes for the record.
  39. It also does not support the subrecords used in Intel and gfortran compilers
  40. for records which are greater than 2GB with a 4-byte header.
  41. An example of an unformatted sequential file in Fortran would be written as::
  42. OPEN(1, FILE=myfilename, FORM='unformatted')
  43. WRITE(1) myvariable
  44. Since this is a non-standard file format, whose contents depend on the
  45. compiler and the endianness of the machine, caution is advised. Files from
  46. gfortran 4.8.0 and gfortran 4.1.2 on x86_64 are known to work.
  47. Consider using Fortran direct-access files or files from the newer Stream
  48. I/O, which can be easily read by `numpy.fromfile`.
  49. Examples
  50. --------
  51. To create an unformatted sequential Fortran file:
  52. >>> from scipy.io import FortranFile
  53. >>> import numpy as np
  54. >>> f = FortranFile('test.unf', 'w')
  55. >>> f.write_record(np.array([1,2,3,4,5], dtype=np.int32))
  56. >>> f.write_record(np.linspace(0,1,20).reshape((5,4)).T)
  57. >>> f.close()
  58. To read this file:
  59. >>> f = FortranFile('test.unf', 'r')
  60. >>> print(f.read_ints(np.int32))
  61. [1 2 3 4 5]
  62. >>> print(f.read_reals(float).reshape((5,4), order="F"))
  63. [[0. 0.05263158 0.10526316 0.15789474]
  64. [0.21052632 0.26315789 0.31578947 0.36842105]
  65. [0.42105263 0.47368421 0.52631579 0.57894737]
  66. [0.63157895 0.68421053 0.73684211 0.78947368]
  67. [0.84210526 0.89473684 0.94736842 1. ]]
  68. >>> f.close()
  69. Or, in Fortran::
  70. integer :: a(5), i
  71. double precision :: b(5,4)
  72. open(1, file='test.unf', form='unformatted')
  73. read(1) a
  74. read(1) b
  75. close(1)
  76. write(*,*) a
  77. do i = 1, 5
  78. write(*,*) b(i,:)
  79. end do
  80. """
  81. def __init__(self, filename, mode='r', header_dtype=np.uint32):
  82. if header_dtype is None:
  83. raise ValueError('Must specify dtype')
  84. header_dtype = np.dtype(header_dtype)
  85. if header_dtype.kind != 'u':
  86. warnings.warn("Given a dtype which is not unsigned.")
  87. if mode not in 'rw' or len(mode) != 1:
  88. raise ValueError('mode must be either r or w')
  89. if hasattr(filename, 'seek'):
  90. self._fp = filename
  91. else:
  92. self._fp = open(filename, '%sb' % mode)
  93. self._header_dtype = header_dtype
  94. def _read_size(self, eof_ok=False):
  95. n = self._header_dtype.itemsize
  96. b = self._fp.read(n)
  97. if (not b) and eof_ok:
  98. raise FortranEOFError("End of file occurred at end of record")
  99. elif len(b) < n:
  100. raise FortranFormattingError(
  101. "End of file in the middle of the record size")
  102. return int(np.frombuffer(b, dtype=self._header_dtype, count=1)[0])
  103. def write_record(self, *items):
  104. """
  105. Write a record (including sizes) to the file.
  106. Parameters
  107. ----------
  108. *items : array_like
  109. The data arrays to write.
  110. Notes
  111. -----
  112. Writes data items to a file::
  113. write_record(a.T, b.T, c.T, ...)
  114. write(1) a, b, c, ...
  115. Note that data in multidimensional arrays is written in
  116. row-major order --- to make them read correctly by Fortran
  117. programs, you need to transpose the arrays yourself when
  118. writing them.
  119. """
  120. items = tuple(np.asarray(item) for item in items)
  121. total_size = sum(item.nbytes for item in items)
  122. nb = np.array([total_size], dtype=self._header_dtype)
  123. nb.tofile(self._fp)
  124. for item in items:
  125. item.tofile(self._fp)
  126. nb.tofile(self._fp)
  127. def read_record(self, *dtypes, **kwargs):
  128. """
  129. Reads a record of a given type from the file.
  130. Parameters
  131. ----------
  132. *dtypes : dtypes, optional
  133. Data type(s) specifying the size and endiness of the data.
  134. Returns
  135. -------
  136. data : ndarray
  137. A 1-D array object.
  138. Raises
  139. ------
  140. FortranEOFError
  141. To signal that no further records are available
  142. FortranFormattingError
  143. To signal that the end of the file was encountered
  144. part-way through a record
  145. Notes
  146. -----
  147. If the record contains a multidimensional array, you can specify
  148. the size in the dtype. For example::
  149. INTEGER var(5,4)
  150. can be read with::
  151. read_record('(4,5)i4').T
  152. Note that this function does **not** assume the file data is in Fortran
  153. column major order, so you need to (i) swap the order of dimensions
  154. when reading and (ii) transpose the resulting array.
  155. Alternatively, you can read the data as a 1-D array and handle the
  156. ordering yourself. For example::
  157. read_record('i4').reshape(5, 4, order='F')
  158. For records that contain several variables or mixed types (as opposed
  159. to single scalar or array types), give them as separate arguments::
  160. double precision :: a
  161. integer :: b
  162. write(1) a, b
  163. record = f.read_record('<f4', '<i4')
  164. a = record[0] # first number
  165. b = record[1] # second number
  166. and if any of the variables are arrays, the shape can be specified as
  167. the third item in the relevant dtype::
  168. double precision :: a
  169. integer :: b(3,4)
  170. write(1) a, b
  171. record = f.read_record('<f4', np.dtype(('<i4', (4, 3))))
  172. a = record[0]
  173. b = record[1].T
  174. NumPy also supports a short syntax for this kind of type::
  175. record = f.read_record('<f4', '(3,3)<i4')
  176. See Also
  177. --------
  178. read_reals
  179. read_ints
  180. """
  181. dtype = kwargs.pop('dtype', None)
  182. if kwargs:
  183. raise ValueError("Unknown keyword arguments {}".format(tuple(kwargs.keys())))
  184. if dtype is not None:
  185. dtypes = dtypes + (dtype,)
  186. elif not dtypes:
  187. raise ValueError('Must specify at least one dtype')
  188. first_size = self._read_size(eof_ok=True)
  189. dtypes = tuple(np.dtype(dtype) for dtype in dtypes)
  190. block_size = sum(dtype.itemsize for dtype in dtypes)
  191. num_blocks, remainder = divmod(first_size, block_size)
  192. if remainder != 0:
  193. raise ValueError('Size obtained ({0}) is not a multiple of the '
  194. 'dtypes given ({1}).'.format(first_size, block_size))
  195. if len(dtypes) != 1 and first_size != block_size:
  196. # Fortran does not write mixed type array items in interleaved order,
  197. # and it's not possible to guess the sizes of the arrays that were written.
  198. # The user must specify the exact sizes of each of the arrays.
  199. raise ValueError('Size obtained ({0}) does not match with the expected '
  200. 'size ({1}) of multi-item record'.format(first_size, block_size))
  201. data = []
  202. for dtype in dtypes:
  203. r = np.fromfile(self._fp, dtype=dtype, count=num_blocks)
  204. if len(r) != num_blocks:
  205. raise FortranFormattingError(
  206. "End of file in the middle of a record")
  207. if dtype.shape != ():
  208. # Squeeze outmost block dimension for array items
  209. if num_blocks == 1:
  210. assert r.shape == (1,) + dtype.shape
  211. r = r[0]
  212. data.append(r)
  213. second_size = self._read_size()
  214. if first_size != second_size:
  215. raise ValueError('Sizes do not agree in the header and footer for '
  216. 'this record - check header dtype')
  217. # Unpack result
  218. if len(dtypes) == 1:
  219. return data[0]
  220. else:
  221. return tuple(data)
  222. def read_ints(self, dtype='i4'):
  223. """
  224. Reads a record of a given type from the file, defaulting to an integer
  225. type (``INTEGER*4`` in Fortran).
  226. Parameters
  227. ----------
  228. dtype : dtype, optional
  229. Data type specifying the size and endiness of the data.
  230. Returns
  231. -------
  232. data : ndarray
  233. A 1-D array object.
  234. See Also
  235. --------
  236. read_reals
  237. read_record
  238. """
  239. return self.read_record(dtype)
  240. def read_reals(self, dtype='f8'):
  241. """
  242. Reads a record of a given type from the file, defaulting to a floating
  243. point number (``real*8`` in Fortran).
  244. Parameters
  245. ----------
  246. dtype : dtype, optional
  247. Data type specifying the size and endiness of the data.
  248. Returns
  249. -------
  250. data : ndarray
  251. A 1-D array object.
  252. See Also
  253. --------
  254. read_ints
  255. read_record
  256. """
  257. return self.read_record(dtype)
  258. def close(self):
  259. """
  260. Closes the file. It is unsupported to call any other methods off this
  261. object after closing it. Note that this class supports the 'with'
  262. statement in modern versions of Python, to call this automatically
  263. """
  264. self._fp.close()
  265. def __enter__(self):
  266. return self
  267. def __exit__(self, type, value, tb):
  268. self.close()