format.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883
  1. """
  2. Binary serialization
  3. NPY format
  4. ==========
  5. A simple format for saving numpy arrays to disk with the full
  6. information about them.
  7. The ``.npy`` format is the standard binary file format in NumPy for
  8. persisting a *single* arbitrary NumPy array on disk. The format stores all
  9. of the shape and dtype information necessary to reconstruct the array
  10. correctly even on another machine with a different architecture.
  11. The format is designed to be as simple as possible while achieving
  12. its limited goals.
  13. The ``.npz`` format is the standard format for persisting *multiple* NumPy
  14. arrays on disk. A ``.npz`` file is a zip file containing multiple ``.npy``
  15. files, one for each array.
  16. Capabilities
  17. ------------
  18. - Can represent all NumPy arrays including nested record arrays and
  19. object arrays.
  20. - Represents the data in its native binary form.
  21. - Supports Fortran-contiguous arrays directly.
  22. - Stores all of the necessary information to reconstruct the array
  23. including shape and dtype on a machine of a different
  24. architecture. Both little-endian and big-endian arrays are
  25. supported, and a file with little-endian numbers will yield
  26. a little-endian array on any machine reading the file. The
  27. types are described in terms of their actual sizes. For example,
  28. if a machine with a 64-bit C "long int" writes out an array with
  29. "long ints", a reading machine with 32-bit C "long ints" will yield
  30. an array with 64-bit integers.
  31. - Is straightforward to reverse engineer. Datasets often live longer than
  32. the programs that created them. A competent developer should be
  33. able to create a solution in their preferred programming language to
  34. read most ``.npy`` files that he has been given without much
  35. documentation.
  36. - Allows memory-mapping of the data. See `open_memmep`.
  37. - Can be read from a filelike stream object instead of an actual file.
  38. - Stores object arrays, i.e. arrays containing elements that are arbitrary
  39. Python objects. Files with object arrays are not to be mmapable, but
  40. can be read and written to disk.
  41. Limitations
  42. -----------
  43. - Arbitrary subclasses of numpy.ndarray are not completely preserved.
  44. Subclasses will be accepted for writing, but only the array data will
  45. be written out. A regular numpy.ndarray object will be created
  46. upon reading the file.
  47. .. warning::
  48. Due to limitations in the interpretation of structured dtypes, dtypes
  49. with fields with empty names will have the names replaced by 'f0', 'f1',
  50. etc. Such arrays will not round-trip through the format entirely
  51. accurately. The data is intact; only the field names will differ. We are
  52. working on a fix for this. This fix will not require a change in the
  53. file format. The arrays with such structures can still be saved and
  54. restored, and the correct dtype may be restored by using the
  55. ``loadedarray.view(correct_dtype)`` method.
  56. File extensions
  57. ---------------
  58. We recommend using the ``.npy`` and ``.npz`` extensions for files saved
  59. in this format. This is by no means a requirement; applications may wish
  60. to use these file formats but use an extension specific to the
  61. application. In the absence of an obvious alternative, however,
  62. we suggest using ``.npy`` and ``.npz``.
  63. Version numbering
  64. -----------------
  65. The version numbering of these formats is independent of NumPy version
  66. numbering. If the format is upgraded, the code in `numpy.io` will still
  67. be able to read and write Version 1.0 files.
  68. Format Version 1.0
  69. ------------------
  70. The first 6 bytes are a magic string: exactly ``\\x93NUMPY``.
  71. The next 1 byte is an unsigned byte: the major version number of the file
  72. format, e.g. ``\\x01``.
  73. The next 1 byte is an unsigned byte: the minor version number of the file
  74. format, e.g. ``\\x00``. Note: the version of the file format is not tied
  75. to the version of the numpy package.
  76. The next 2 bytes form a little-endian unsigned short int: the length of
  77. the header data HEADER_LEN.
  78. The next HEADER_LEN bytes form the header data describing the array's
  79. format. It is an ASCII string which contains a Python literal expression
  80. of a dictionary. It is terminated by a newline (``\\n``) and padded with
  81. spaces (``\\x20``) to make the total of
  82. ``len(magic string) + 2 + len(length) + HEADER_LEN`` be evenly divisible
  83. by 64 for alignment purposes.
  84. The dictionary contains three keys:
  85. "descr" : dtype.descr
  86. An object that can be passed as an argument to the `numpy.dtype`
  87. constructor to create the array's dtype.
  88. "fortran_order" : bool
  89. Whether the array data is Fortran-contiguous or not. Since
  90. Fortran-contiguous arrays are a common form of non-C-contiguity,
  91. we allow them to be written directly to disk for efficiency.
  92. "shape" : tuple of int
  93. The shape of the array.
  94. For repeatability and readability, the dictionary keys are sorted in
  95. alphabetic order. This is for convenience only. A writer SHOULD implement
  96. this if possible. A reader MUST NOT depend on this.
  97. Following the header comes the array data. If the dtype contains Python
  98. objects (i.e. ``dtype.hasobject is True``), then the data is a Python
  99. pickle of the array. Otherwise the data is the contiguous (either C-
  100. or Fortran-, depending on ``fortran_order``) bytes of the array.
  101. Consumers can figure out the number of bytes by multiplying the number
  102. of elements given by the shape (noting that ``shape=()`` means there is
  103. 1 element) by ``dtype.itemsize``.
  104. Format Version 2.0
  105. ------------------
  106. The version 1.0 format only allowed the array header to have a total size of
  107. 65535 bytes. This can be exceeded by structured arrays with a large number of
  108. columns. The version 2.0 format extends the header size to 4 GiB.
  109. `numpy.save` will automatically save in 2.0 format if the data requires it,
  110. else it will always use the more compatible 1.0 format.
  111. The description of the fourth element of the header therefore has become:
  112. "The next 4 bytes form a little-endian unsigned int: the length of the header
  113. data HEADER_LEN."
  114. Notes
  115. -----
  116. The ``.npy`` format, including motivation for creating it and a comparison of
  117. alternatives, is described in the `"npy-format" NEP
  118. <https://www.numpy.org/neps/nep-0001-npy-format.html>`_, however details have
  119. evolved with time and this document is more current.
  120. """
  121. from __future__ import division, absolute_import, print_function
  122. import numpy
  123. import sys
  124. import io
  125. import warnings
  126. from numpy.lib.utils import safe_eval
  127. from numpy.compat import (
  128. asbytes, asstr, isfileobj, long, os_fspath
  129. )
  130. from numpy.core.numeric import pickle
  131. MAGIC_PREFIX = b'\x93NUMPY'
  132. MAGIC_LEN = len(MAGIC_PREFIX) + 2
  133. ARRAY_ALIGN = 64 # plausible values are powers of 2 between 16 and 4096
  134. BUFFER_SIZE = 2**18 # size of buffer for reading npz files in bytes
  135. # difference between version 1.0 and 2.0 is a 4 byte (I) header length
  136. # instead of 2 bytes (H) allowing storage of large structured arrays
  137. def _check_version(version):
  138. if version not in [(1, 0), (2, 0), None]:
  139. msg = "we only support format version (1,0) and (2, 0), not %s"
  140. raise ValueError(msg % (version,))
  141. def magic(major, minor):
  142. """ Return the magic string for the given file format version.
  143. Parameters
  144. ----------
  145. major : int in [0, 255]
  146. minor : int in [0, 255]
  147. Returns
  148. -------
  149. magic : str
  150. Raises
  151. ------
  152. ValueError if the version cannot be formatted.
  153. """
  154. if major < 0 or major > 255:
  155. raise ValueError("major version must be 0 <= major < 256")
  156. if minor < 0 or minor > 255:
  157. raise ValueError("minor version must be 0 <= minor < 256")
  158. if sys.version_info[0] < 3:
  159. return MAGIC_PREFIX + chr(major) + chr(minor)
  160. else:
  161. return MAGIC_PREFIX + bytes([major, minor])
  162. def read_magic(fp):
  163. """ Read the magic string to get the version of the file format.
  164. Parameters
  165. ----------
  166. fp : filelike object
  167. Returns
  168. -------
  169. major : int
  170. minor : int
  171. """
  172. magic_str = _read_bytes(fp, MAGIC_LEN, "magic string")
  173. if magic_str[:-2] != MAGIC_PREFIX:
  174. msg = "the magic string is not correct; expected %r, got %r"
  175. raise ValueError(msg % (MAGIC_PREFIX, magic_str[:-2]))
  176. if sys.version_info[0] < 3:
  177. major, minor = map(ord, magic_str[-2:])
  178. else:
  179. major, minor = magic_str[-2:]
  180. return major, minor
  181. def dtype_to_descr(dtype):
  182. """
  183. Get a serializable descriptor from the dtype.
  184. The .descr attribute of a dtype object cannot be round-tripped through
  185. the dtype() constructor. Simple types, like dtype('float32'), have
  186. a descr which looks like a record array with one field with '' as
  187. a name. The dtype() constructor interprets this as a request to give
  188. a default name. Instead, we construct descriptor that can be passed to
  189. dtype().
  190. Parameters
  191. ----------
  192. dtype : dtype
  193. The dtype of the array that will be written to disk.
  194. Returns
  195. -------
  196. descr : object
  197. An object that can be passed to `numpy.dtype()` in order to
  198. replicate the input dtype.
  199. """
  200. if dtype.names is not None:
  201. # This is a record array. The .descr is fine. XXX: parts of the
  202. # record array with an empty name, like padding bytes, still get
  203. # fiddled with. This needs to be fixed in the C implementation of
  204. # dtype().
  205. return dtype.descr
  206. else:
  207. return dtype.str
  208. def descr_to_dtype(descr):
  209. '''
  210. descr may be stored as dtype.descr, which is a list of
  211. (name, format, [shape]) tuples where format may be a str or a tuple.
  212. Offsets are not explicitly saved, rather empty fields with
  213. name, format == '', '|Vn' are added as padding.
  214. This function reverses the process, eliminating the empty padding fields.
  215. '''
  216. if isinstance(descr, str):
  217. # No padding removal needed
  218. return numpy.dtype(descr)
  219. elif isinstance(descr, tuple):
  220. # subtype, will always have a shape descr[1]
  221. dt = descr_to_dtype(descr[0])
  222. return numpy.dtype((dt, descr[1]))
  223. fields = []
  224. offset = 0
  225. for field in descr:
  226. if len(field) == 2:
  227. name, descr_str = field
  228. dt = descr_to_dtype(descr_str)
  229. else:
  230. name, descr_str, shape = field
  231. dt = numpy.dtype((descr_to_dtype(descr_str), shape))
  232. # Ignore padding bytes, which will be void bytes with '' as name
  233. # Once support for blank names is removed, only "if name == ''" needed)
  234. is_pad = (name == '' and dt.type is numpy.void and dt.names is None)
  235. if not is_pad:
  236. fields.append((name, dt, offset))
  237. offset += dt.itemsize
  238. names, formats, offsets = zip(*fields)
  239. # names may be (title, names) tuples
  240. nametups = (n if isinstance(n, tuple) else (None, n) for n in names)
  241. titles, names = zip(*nametups)
  242. return numpy.dtype({'names': names, 'formats': formats, 'titles': titles,
  243. 'offsets': offsets, 'itemsize': offset})
  244. def header_data_from_array_1_0(array):
  245. """ Get the dictionary of header metadata from a numpy.ndarray.
  246. Parameters
  247. ----------
  248. array : numpy.ndarray
  249. Returns
  250. -------
  251. d : dict
  252. This has the appropriate entries for writing its string representation
  253. to the header of the file.
  254. """
  255. d = {'shape': array.shape}
  256. if array.flags.c_contiguous:
  257. d['fortran_order'] = False
  258. elif array.flags.f_contiguous:
  259. d['fortran_order'] = True
  260. else:
  261. # Totally non-contiguous data. We will have to make it C-contiguous
  262. # before writing. Note that we need to test for C_CONTIGUOUS first
  263. # because a 1-D array is both C_CONTIGUOUS and F_CONTIGUOUS.
  264. d['fortran_order'] = False
  265. d['descr'] = dtype_to_descr(array.dtype)
  266. return d
  267. def _write_array_header(fp, d, version=None):
  268. """ Write the header for an array and returns the version used
  269. Parameters
  270. ----------
  271. fp : filelike object
  272. d : dict
  273. This has the appropriate entries for writing its string representation
  274. to the header of the file.
  275. version: tuple or None
  276. None means use oldest that works
  277. explicit version will raise a ValueError if the format does not
  278. allow saving this data. Default: None
  279. Returns
  280. -------
  281. version : tuple of int
  282. the file version which needs to be used to store the data
  283. """
  284. import struct
  285. header = ["{"]
  286. for key, value in sorted(d.items()):
  287. # Need to use repr here, since we eval these when reading
  288. header.append("'%s': %s, " % (key, repr(value)))
  289. header.append("}")
  290. header = "".join(header)
  291. header = asbytes(_filter_header(header))
  292. hlen = len(header) + 1 # 1 for newline
  293. padlen_v1 = ARRAY_ALIGN - ((MAGIC_LEN + struct.calcsize('<H') + hlen) % ARRAY_ALIGN)
  294. padlen_v2 = ARRAY_ALIGN - ((MAGIC_LEN + struct.calcsize('<I') + hlen) % ARRAY_ALIGN)
  295. # Which version(s) we write depends on the total header size; v1 has a max of 65535
  296. if hlen + padlen_v1 < 2**16 and version in (None, (1, 0)):
  297. version = (1, 0)
  298. header_prefix = magic(1, 0) + struct.pack('<H', hlen + padlen_v1)
  299. topad = padlen_v1
  300. elif hlen + padlen_v2 < 2**32 and version in (None, (2, 0)):
  301. version = (2, 0)
  302. header_prefix = magic(2, 0) + struct.pack('<I', hlen + padlen_v2)
  303. topad = padlen_v2
  304. else:
  305. msg = "Header length %s too big for version=%s"
  306. msg %= (hlen, version)
  307. raise ValueError(msg)
  308. # Pad the header with spaces and a final newline such that the magic
  309. # string, the header-length short and the header are aligned on a
  310. # ARRAY_ALIGN byte boundary. This supports memory mapping of dtypes
  311. # aligned up to ARRAY_ALIGN on systems like Linux where mmap()
  312. # offset must be page-aligned (i.e. the beginning of the file).
  313. header = header + b' '*topad + b'\n'
  314. fp.write(header_prefix)
  315. fp.write(header)
  316. return version
  317. def write_array_header_1_0(fp, d):
  318. """ Write the header for an array using the 1.0 format.
  319. Parameters
  320. ----------
  321. fp : filelike object
  322. d : dict
  323. This has the appropriate entries for writing its string
  324. representation to the header of the file.
  325. """
  326. _write_array_header(fp, d, (1, 0))
  327. def write_array_header_2_0(fp, d):
  328. """ Write the header for an array using the 2.0 format.
  329. The 2.0 format allows storing very large structured arrays.
  330. .. versionadded:: 1.9.0
  331. Parameters
  332. ----------
  333. fp : filelike object
  334. d : dict
  335. This has the appropriate entries for writing its string
  336. representation to the header of the file.
  337. """
  338. _write_array_header(fp, d, (2, 0))
  339. def read_array_header_1_0(fp):
  340. """
  341. Read an array header from a filelike object using the 1.0 file format
  342. version.
  343. This will leave the file object located just after the header.
  344. Parameters
  345. ----------
  346. fp : filelike object
  347. A file object or something with a `.read()` method like a file.
  348. Returns
  349. -------
  350. shape : tuple of int
  351. The shape of the array.
  352. fortran_order : bool
  353. The array data will be written out directly if it is either
  354. C-contiguous or Fortran-contiguous. Otherwise, it will be made
  355. contiguous before writing it out.
  356. dtype : dtype
  357. The dtype of the file's data.
  358. Raises
  359. ------
  360. ValueError
  361. If the data is invalid.
  362. """
  363. return _read_array_header(fp, version=(1, 0))
  364. def read_array_header_2_0(fp):
  365. """
  366. Read an array header from a filelike object using the 2.0 file format
  367. version.
  368. This will leave the file object located just after the header.
  369. .. versionadded:: 1.9.0
  370. Parameters
  371. ----------
  372. fp : filelike object
  373. A file object or something with a `.read()` method like a file.
  374. Returns
  375. -------
  376. shape : tuple of int
  377. The shape of the array.
  378. fortran_order : bool
  379. The array data will be written out directly if it is either
  380. C-contiguous or Fortran-contiguous. Otherwise, it will be made
  381. contiguous before writing it out.
  382. dtype : dtype
  383. The dtype of the file's data.
  384. Raises
  385. ------
  386. ValueError
  387. If the data is invalid.
  388. """
  389. return _read_array_header(fp, version=(2, 0))
  390. def _filter_header(s):
  391. """Clean up 'L' in npz header ints.
  392. Cleans up the 'L' in strings representing integers. Needed to allow npz
  393. headers produced in Python2 to be read in Python3.
  394. Parameters
  395. ----------
  396. s : byte string
  397. Npy file header.
  398. Returns
  399. -------
  400. header : str
  401. Cleaned up header.
  402. """
  403. import tokenize
  404. if sys.version_info[0] >= 3:
  405. from io import StringIO
  406. else:
  407. from StringIO import StringIO
  408. tokens = []
  409. last_token_was_number = False
  410. # adding newline as python 2.7.5 workaround
  411. string = asstr(s) + "\n"
  412. for token in tokenize.generate_tokens(StringIO(string).readline):
  413. token_type = token[0]
  414. token_string = token[1]
  415. if (last_token_was_number and
  416. token_type == tokenize.NAME and
  417. token_string == "L"):
  418. continue
  419. else:
  420. tokens.append(token)
  421. last_token_was_number = (token_type == tokenize.NUMBER)
  422. # removing newline (see above) as python 2.7.5 workaround
  423. return tokenize.untokenize(tokens)[:-1]
  424. def _read_array_header(fp, version):
  425. """
  426. see read_array_header_1_0
  427. """
  428. # Read an unsigned, little-endian short int which has the length of the
  429. # header.
  430. import struct
  431. if version == (1, 0):
  432. hlength_type = '<H'
  433. elif version == (2, 0):
  434. hlength_type = '<I'
  435. else:
  436. raise ValueError("Invalid version {!r}".format(version))
  437. hlength_str = _read_bytes(fp, struct.calcsize(hlength_type), "array header length")
  438. header_length = struct.unpack(hlength_type, hlength_str)[0]
  439. header = _read_bytes(fp, header_length, "array header")
  440. # The header is a pretty-printed string representation of a literal
  441. # Python dictionary with trailing newlines padded to a ARRAY_ALIGN byte
  442. # boundary. The keys are strings.
  443. # "shape" : tuple of int
  444. # "fortran_order" : bool
  445. # "descr" : dtype.descr
  446. header = _filter_header(header)
  447. try:
  448. d = safe_eval(header)
  449. except SyntaxError as e:
  450. msg = "Cannot parse header: {!r}\nException: {!r}"
  451. raise ValueError(msg.format(header, e))
  452. if not isinstance(d, dict):
  453. msg = "Header is not a dictionary: {!r}"
  454. raise ValueError(msg.format(d))
  455. keys = sorted(d.keys())
  456. if keys != ['descr', 'fortran_order', 'shape']:
  457. msg = "Header does not contain the correct keys: {!r}"
  458. raise ValueError(msg.format(keys))
  459. # Sanity-check the values.
  460. if (not isinstance(d['shape'], tuple) or
  461. not numpy.all([isinstance(x, (int, long)) for x in d['shape']])):
  462. msg = "shape is not valid: {!r}"
  463. raise ValueError(msg.format(d['shape']))
  464. if not isinstance(d['fortran_order'], bool):
  465. msg = "fortran_order is not a valid bool: {!r}"
  466. raise ValueError(msg.format(d['fortran_order']))
  467. try:
  468. dtype = descr_to_dtype(d['descr'])
  469. except TypeError as e:
  470. msg = "descr is not a valid dtype descriptor: {!r}"
  471. raise ValueError(msg.format(d['descr']))
  472. return d['shape'], d['fortran_order'], dtype
  473. def write_array(fp, array, version=None, allow_pickle=True, pickle_kwargs=None):
  474. """
  475. Write an array to an NPY file, including a header.
  476. If the array is neither C-contiguous nor Fortran-contiguous AND the
  477. file_like object is not a real file object, this function will have to
  478. copy data in memory.
  479. Parameters
  480. ----------
  481. fp : file_like object
  482. An open, writable file object, or similar object with a
  483. ``.write()`` method.
  484. array : ndarray
  485. The array to write to disk.
  486. version : (int, int) or None, optional
  487. The version number of the format. None means use the oldest
  488. supported version that is able to store the data. Default: None
  489. allow_pickle : bool, optional
  490. Whether to allow writing pickled data. Default: True
  491. pickle_kwargs : dict, optional
  492. Additional keyword arguments to pass to pickle.dump, excluding
  493. 'protocol'. These are only useful when pickling objects in object
  494. arrays on Python 3 to Python 2 compatible format.
  495. Raises
  496. ------
  497. ValueError
  498. If the array cannot be persisted. This includes the case of
  499. allow_pickle=False and array being an object array.
  500. Various other errors
  501. If the array contains Python objects as part of its dtype, the
  502. process of pickling them may raise various errors if the objects
  503. are not picklable.
  504. """
  505. _check_version(version)
  506. used_ver = _write_array_header(fp, header_data_from_array_1_0(array),
  507. version)
  508. # this warning can be removed when 1.9 has aged enough
  509. if version != (2, 0) and used_ver == (2, 0):
  510. warnings.warn("Stored array in format 2.0. It can only be"
  511. "read by NumPy >= 1.9", UserWarning, stacklevel=2)
  512. if array.itemsize == 0:
  513. buffersize = 0
  514. else:
  515. # Set buffer size to 16 MiB to hide the Python loop overhead.
  516. buffersize = max(16 * 1024 ** 2 // array.itemsize, 1)
  517. if array.dtype.hasobject:
  518. # We contain Python objects so we cannot write out the data
  519. # directly. Instead, we will pickle it out with version 2 of the
  520. # pickle protocol.
  521. if not allow_pickle:
  522. raise ValueError("Object arrays cannot be saved when "
  523. "allow_pickle=False")
  524. if pickle_kwargs is None:
  525. pickle_kwargs = {}
  526. pickle.dump(array, fp, protocol=2, **pickle_kwargs)
  527. elif array.flags.f_contiguous and not array.flags.c_contiguous:
  528. if isfileobj(fp):
  529. array.T.tofile(fp)
  530. else:
  531. for chunk in numpy.nditer(
  532. array, flags=['external_loop', 'buffered', 'zerosize_ok'],
  533. buffersize=buffersize, order='F'):
  534. fp.write(chunk.tobytes('C'))
  535. else:
  536. if isfileobj(fp):
  537. array.tofile(fp)
  538. else:
  539. for chunk in numpy.nditer(
  540. array, flags=['external_loop', 'buffered', 'zerosize_ok'],
  541. buffersize=buffersize, order='C'):
  542. fp.write(chunk.tobytes('C'))
  543. def read_array(fp, allow_pickle=False, pickle_kwargs=None):
  544. """
  545. Read an array from an NPY file.
  546. Parameters
  547. ----------
  548. fp : file_like object
  549. If this is not a real file object, then this may take extra memory
  550. and time.
  551. allow_pickle : bool, optional
  552. Whether to allow writing pickled data. Default: False
  553. .. versionchanged:: 1.16.3
  554. Made default False in response to CVE-2019-6446.
  555. pickle_kwargs : dict
  556. Additional keyword arguments to pass to pickle.load. These are only
  557. useful when loading object arrays saved on Python 2 when using
  558. Python 3.
  559. Returns
  560. -------
  561. array : ndarray
  562. The array from the data on disk.
  563. Raises
  564. ------
  565. ValueError
  566. If the data is invalid, or allow_pickle=False and the file contains
  567. an object array.
  568. """
  569. version = read_magic(fp)
  570. _check_version(version)
  571. shape, fortran_order, dtype = _read_array_header(fp, version)
  572. if len(shape) == 0:
  573. count = 1
  574. else:
  575. count = numpy.multiply.reduce(shape, dtype=numpy.int64)
  576. # Now read the actual data.
  577. if dtype.hasobject:
  578. # The array contained Python objects. We need to unpickle the data.
  579. if not allow_pickle:
  580. raise ValueError("Object arrays cannot be loaded when "
  581. "allow_pickle=False")
  582. if pickle_kwargs is None:
  583. pickle_kwargs = {}
  584. try:
  585. array = pickle.load(fp, **pickle_kwargs)
  586. except UnicodeError as err:
  587. if sys.version_info[0] >= 3:
  588. # Friendlier error message
  589. raise UnicodeError("Unpickling a python object failed: %r\n"
  590. "You may need to pass the encoding= option "
  591. "to numpy.load" % (err,))
  592. raise
  593. else:
  594. if isfileobj(fp):
  595. # We can use the fast fromfile() function.
  596. array = numpy.fromfile(fp, dtype=dtype, count=count)
  597. else:
  598. # This is not a real file. We have to read it the
  599. # memory-intensive way.
  600. # crc32 module fails on reads greater than 2 ** 32 bytes,
  601. # breaking large reads from gzip streams. Chunk reads to
  602. # BUFFER_SIZE bytes to avoid issue and reduce memory overhead
  603. # of the read. In non-chunked case count < max_read_count, so
  604. # only one read is performed.
  605. # Use np.ndarray instead of np.empty since the latter does
  606. # not correctly instantiate zero-width string dtypes; see
  607. # https://github.com/numpy/numpy/pull/6430
  608. array = numpy.ndarray(count, dtype=dtype)
  609. if dtype.itemsize > 0:
  610. # If dtype.itemsize == 0 then there's nothing more to read
  611. max_read_count = BUFFER_SIZE // min(BUFFER_SIZE, dtype.itemsize)
  612. for i in range(0, count, max_read_count):
  613. read_count = min(max_read_count, count - i)
  614. read_size = int(read_count * dtype.itemsize)
  615. data = _read_bytes(fp, read_size, "array data")
  616. array[i:i+read_count] = numpy.frombuffer(data, dtype=dtype,
  617. count=read_count)
  618. if fortran_order:
  619. array.shape = shape[::-1]
  620. array = array.transpose()
  621. else:
  622. array.shape = shape
  623. return array
  624. def open_memmap(filename, mode='r+', dtype=None, shape=None,
  625. fortran_order=False, version=None):
  626. """
  627. Open a .npy file as a memory-mapped array.
  628. This may be used to read an existing file or create a new one.
  629. Parameters
  630. ----------
  631. filename : str or path-like
  632. The name of the file on disk. This may *not* be a file-like
  633. object.
  634. mode : str, optional
  635. The mode in which to open the file; the default is 'r+'. In
  636. addition to the standard file modes, 'c' is also accepted to mean
  637. "copy on write." See `memmap` for the available mode strings.
  638. dtype : data-type, optional
  639. The data type of the array if we are creating a new file in "write"
  640. mode, if not, `dtype` is ignored. The default value is None, which
  641. results in a data-type of `float64`.
  642. shape : tuple of int
  643. The shape of the array if we are creating a new file in "write"
  644. mode, in which case this parameter is required. Otherwise, this
  645. parameter is ignored and is thus optional.
  646. fortran_order : bool, optional
  647. Whether the array should be Fortran-contiguous (True) or
  648. C-contiguous (False, the default) if we are creating a new file in
  649. "write" mode.
  650. version : tuple of int (major, minor) or None
  651. If the mode is a "write" mode, then this is the version of the file
  652. format used to create the file. None means use the oldest
  653. supported version that is able to store the data. Default: None
  654. Returns
  655. -------
  656. marray : memmap
  657. The memory-mapped array.
  658. Raises
  659. ------
  660. ValueError
  661. If the data or the mode is invalid.
  662. IOError
  663. If the file is not found or cannot be opened correctly.
  664. See Also
  665. --------
  666. memmap
  667. """
  668. if isfileobj(filename):
  669. raise ValueError("Filename must be a string or a path-like object."
  670. " Memmap cannot use existing file handles.")
  671. if 'w' in mode:
  672. # We are creating the file, not reading it.
  673. # Check if we ought to create the file.
  674. _check_version(version)
  675. # Ensure that the given dtype is an authentic dtype object rather
  676. # than just something that can be interpreted as a dtype object.
  677. dtype = numpy.dtype(dtype)
  678. if dtype.hasobject:
  679. msg = "Array can't be memory-mapped: Python objects in dtype."
  680. raise ValueError(msg)
  681. d = dict(
  682. descr=dtype_to_descr(dtype),
  683. fortran_order=fortran_order,
  684. shape=shape,
  685. )
  686. # If we got here, then it should be safe to create the file.
  687. fp = open(os_fspath(filename), mode+'b')
  688. try:
  689. used_ver = _write_array_header(fp, d, version)
  690. # this warning can be removed when 1.9 has aged enough
  691. if version != (2, 0) and used_ver == (2, 0):
  692. warnings.warn("Stored array in format 2.0. It can only be"
  693. "read by NumPy >= 1.9", UserWarning, stacklevel=2)
  694. offset = fp.tell()
  695. finally:
  696. fp.close()
  697. else:
  698. # Read the header of the file first.
  699. fp = open(os_fspath(filename), 'rb')
  700. try:
  701. version = read_magic(fp)
  702. _check_version(version)
  703. shape, fortran_order, dtype = _read_array_header(fp, version)
  704. if dtype.hasobject:
  705. msg = "Array can't be memory-mapped: Python objects in dtype."
  706. raise ValueError(msg)
  707. offset = fp.tell()
  708. finally:
  709. fp.close()
  710. if fortran_order:
  711. order = 'F'
  712. else:
  713. order = 'C'
  714. # We need to change a write-only mode to a read-write mode since we've
  715. # already written data to the file.
  716. if mode == 'w+':
  717. mode = 'r+'
  718. marray = numpy.memmap(filename, dtype=dtype, shape=shape, order=order,
  719. mode=mode, offset=offset)
  720. return marray
  721. def _read_bytes(fp, size, error_template="ran out of data"):
  722. """
  723. Read from file-like object until size bytes are read.
  724. Raises ValueError if not EOF is encountered before size bytes are read.
  725. Non-blocking objects only supported if they derive from io objects.
  726. Required as e.g. ZipExtFile in python 2.6 can return less data than
  727. requested.
  728. """
  729. data = bytes()
  730. while True:
  731. # io files (default in python3) return None or raise on
  732. # would-block, python2 file will truncate, probably nothing can be
  733. # done about that. note that regular files can't be non-blocking
  734. try:
  735. r = fp.read(size - len(data))
  736. data += r
  737. if len(r) == 0 or len(data) == size:
  738. break
  739. except io.BlockingIOError:
  740. pass
  741. if len(data) != size:
  742. msg = "EOF: reading %s, expected %d bytes got %d"
  743. raise ValueError(msg % (error_template, size, len(data)))
  744. else:
  745. return data