format.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008
  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 they have been given without much
  35. documentation.
  36. - Allows memory-mapping of the data. See `open_memmap`.
  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. Format Version 3.0
  115. ------------------
  116. This version replaces the ASCII string (which in practice was latin1) with
  117. a utf8-encoded string, so supports structured types with any unicode field
  118. names.
  119. Notes
  120. -----
  121. The ``.npy`` format, including motivation for creating it and a comparison of
  122. alternatives, is described in the
  123. :doc:`"npy-format" NEP <neps:nep-0001-npy-format>`, however details have
  124. evolved with time and this document is more current.
  125. """
  126. import io
  127. import os
  128. import pickle
  129. import warnings
  130. import numpy
  131. from numpy.lib._utils_impl import drop_metadata
  132. __all__ = []
  133. drop_metadata.__module__ = "numpy.lib.format"
  134. EXPECTED_KEYS = {'descr', 'fortran_order', 'shape'}
  135. MAGIC_PREFIX = b'\x93NUMPY'
  136. MAGIC_LEN = len(MAGIC_PREFIX) + 2
  137. ARRAY_ALIGN = 64 # plausible values are powers of 2 between 16 and 4096
  138. BUFFER_SIZE = 2**18 # size of buffer for reading npz files in bytes
  139. # allow growth within the address space of a 64 bit machine along one axis
  140. GROWTH_AXIS_MAX_DIGITS = 21 # = len(str(8*2**64-1)) hypothetical int1 dtype
  141. # difference between version 1.0 and 2.0 is a 4 byte (I) header length
  142. # instead of 2 bytes (H) allowing storage of large structured arrays
  143. _header_size_info = {
  144. (1, 0): ('<H', 'latin1'),
  145. (2, 0): ('<I', 'latin1'),
  146. (3, 0): ('<I', 'utf8'),
  147. }
  148. # Python's literal_eval is not actually safe for large inputs, since parsing
  149. # may become slow or even cause interpreter crashes.
  150. # This is an arbitrary, low limit which should make it safe in practice.
  151. _MAX_HEADER_SIZE = 10000
  152. def _check_version(version):
  153. if version not in [(1, 0), (2, 0), (3, 0), None]:
  154. msg = "we only support format version (1,0), (2,0), and (3,0), not %s"
  155. raise ValueError(msg % (version,))
  156. def magic(major, minor):
  157. """ Return the magic string for the given file format version.
  158. Parameters
  159. ----------
  160. major : int in [0, 255]
  161. minor : int in [0, 255]
  162. Returns
  163. -------
  164. magic : str
  165. Raises
  166. ------
  167. ValueError if the version cannot be formatted.
  168. """
  169. if major < 0 or major > 255:
  170. raise ValueError("major version must be 0 <= major < 256")
  171. if minor < 0 or minor > 255:
  172. raise ValueError("minor version must be 0 <= minor < 256")
  173. return MAGIC_PREFIX + bytes([major, minor])
  174. def read_magic(fp):
  175. """ Read the magic string to get the version of the file format.
  176. Parameters
  177. ----------
  178. fp : filelike object
  179. Returns
  180. -------
  181. major : int
  182. minor : int
  183. """
  184. magic_str = _read_bytes(fp, MAGIC_LEN, "magic string")
  185. if magic_str[:-2] != MAGIC_PREFIX:
  186. msg = "the magic string is not correct; expected %r, got %r"
  187. raise ValueError(msg % (MAGIC_PREFIX, magic_str[:-2]))
  188. major, minor = magic_str[-2:]
  189. return major, minor
  190. def dtype_to_descr(dtype):
  191. """
  192. Get a serializable descriptor from the dtype.
  193. The .descr attribute of a dtype object cannot be round-tripped through
  194. the dtype() constructor. Simple types, like dtype('float32'), have
  195. a descr which looks like a record array with one field with '' as
  196. a name. The dtype() constructor interprets this as a request to give
  197. a default name. Instead, we construct descriptor that can be passed to
  198. dtype().
  199. Parameters
  200. ----------
  201. dtype : dtype
  202. The dtype of the array that will be written to disk.
  203. Returns
  204. -------
  205. descr : object
  206. An object that can be passed to `numpy.dtype()` in order to
  207. replicate the input dtype.
  208. """
  209. # NOTE: that drop_metadata may not return the right dtype e.g. for user
  210. # dtypes. In that case our code below would fail the same, though.
  211. new_dtype = drop_metadata(dtype)
  212. if new_dtype is not dtype:
  213. warnings.warn("metadata on a dtype is not saved to an npy/npz. "
  214. "Use another format (such as pickle) to store it.",
  215. UserWarning, stacklevel=2)
  216. dtype = new_dtype
  217. if dtype.names is not None:
  218. # This is a record array. The .descr is fine. XXX: parts of the
  219. # record array with an empty name, like padding bytes, still get
  220. # fiddled with. This needs to be fixed in the C implementation of
  221. # dtype().
  222. return dtype.descr
  223. elif not type(dtype)._legacy:
  224. # this must be a user-defined dtype since numpy does not yet expose any
  225. # non-legacy dtypes in the public API
  226. #
  227. # non-legacy dtypes don't yet have __array_interface__
  228. # support. Instead, as a hack, we use pickle to save the array, and lie
  229. # that the dtype is object. When the array is loaded, the descriptor is
  230. # unpickled with the array and the object dtype in the header is
  231. # discarded.
  232. #
  233. # a future NEP should define a way to serialize user-defined
  234. # descriptors and ideally work out the possible security implications
  235. warnings.warn("Custom dtypes are saved as python objects using the "
  236. "pickle protocol. Loading this file requires "
  237. "allow_pickle=True to be set.",
  238. UserWarning, stacklevel=2)
  239. return "|O"
  240. else:
  241. return dtype.str
  242. def descr_to_dtype(descr):
  243. """
  244. Returns a dtype based off the given description.
  245. This is essentially the reverse of `~lib.format.dtype_to_descr`. It will
  246. remove the valueless padding fields created by, i.e. simple fields like
  247. dtype('float32'), and then convert the description to its corresponding
  248. dtype.
  249. Parameters
  250. ----------
  251. descr : object
  252. The object retrieved by dtype.descr. Can be passed to
  253. `numpy.dtype` in order to replicate the input dtype.
  254. Returns
  255. -------
  256. dtype : dtype
  257. The dtype constructed by the description.
  258. """
  259. if isinstance(descr, str):
  260. # No padding removal needed
  261. return numpy.dtype(descr)
  262. elif isinstance(descr, tuple):
  263. # subtype, will always have a shape descr[1]
  264. dt = descr_to_dtype(descr[0])
  265. return numpy.dtype((dt, descr[1]))
  266. titles = []
  267. names = []
  268. formats = []
  269. offsets = []
  270. offset = 0
  271. for field in descr:
  272. if len(field) == 2:
  273. name, descr_str = field
  274. dt = descr_to_dtype(descr_str)
  275. else:
  276. name, descr_str, shape = field
  277. dt = numpy.dtype((descr_to_dtype(descr_str), shape))
  278. # Ignore padding bytes, which will be void bytes with '' as name
  279. # Once support for blank names is removed, only "if name == ''" needed)
  280. is_pad = (name == '' and dt.type is numpy.void and dt.names is None)
  281. if not is_pad:
  282. title, name = name if isinstance(name, tuple) else (None, name)
  283. titles.append(title)
  284. names.append(name)
  285. formats.append(dt)
  286. offsets.append(offset)
  287. offset += dt.itemsize
  288. return numpy.dtype({'names': names, 'formats': formats, 'titles': titles,
  289. 'offsets': offsets, 'itemsize': offset})
  290. def header_data_from_array_1_0(array):
  291. """ Get the dictionary of header metadata from a numpy.ndarray.
  292. Parameters
  293. ----------
  294. array : numpy.ndarray
  295. Returns
  296. -------
  297. d : dict
  298. This has the appropriate entries for writing its string representation
  299. to the header of the file.
  300. """
  301. d = {'shape': array.shape}
  302. if array.flags.c_contiguous:
  303. d['fortran_order'] = False
  304. elif array.flags.f_contiguous:
  305. d['fortran_order'] = True
  306. else:
  307. # Totally non-contiguous data. We will have to make it C-contiguous
  308. # before writing. Note that we need to test for C_CONTIGUOUS first
  309. # because a 1-D array is both C_CONTIGUOUS and F_CONTIGUOUS.
  310. d['fortran_order'] = False
  311. d['descr'] = dtype_to_descr(array.dtype)
  312. return d
  313. def _wrap_header(header, version):
  314. """
  315. Takes a stringified header, and attaches the prefix and padding to it
  316. """
  317. import struct
  318. assert version is not None
  319. fmt, encoding = _header_size_info[version]
  320. header = header.encode(encoding)
  321. hlen = len(header) + 1
  322. padlen = ARRAY_ALIGN - ((MAGIC_LEN + struct.calcsize(fmt) + hlen) % ARRAY_ALIGN)
  323. try:
  324. header_prefix = magic(*version) + struct.pack(fmt, hlen + padlen)
  325. except struct.error:
  326. msg = "Header length {} too big for version={}".format(hlen, version)
  327. raise ValueError(msg) from None
  328. # Pad the header with spaces and a final newline such that the magic
  329. # string, the header-length short and the header are aligned on a
  330. # ARRAY_ALIGN byte boundary. This supports memory mapping of dtypes
  331. # aligned up to ARRAY_ALIGN on systems like Linux where mmap()
  332. # offset must be page-aligned (i.e. the beginning of the file).
  333. return header_prefix + header + b' '*padlen + b'\n'
  334. def _wrap_header_guess_version(header):
  335. """
  336. Like `_wrap_header`, but chooses an appropriate version given the contents
  337. """
  338. try:
  339. return _wrap_header(header, (1, 0))
  340. except ValueError:
  341. pass
  342. try:
  343. ret = _wrap_header(header, (2, 0))
  344. except UnicodeEncodeError:
  345. pass
  346. else:
  347. warnings.warn("Stored array in format 2.0. It can only be"
  348. "read by NumPy >= 1.9", UserWarning, stacklevel=2)
  349. return ret
  350. header = _wrap_header(header, (3, 0))
  351. warnings.warn("Stored array in format 3.0. It can only be "
  352. "read by NumPy >= 1.17", UserWarning, stacklevel=2)
  353. return header
  354. def _write_array_header(fp, d, version=None):
  355. """ Write the header for an array and returns the version used
  356. Parameters
  357. ----------
  358. fp : filelike object
  359. d : dict
  360. This has the appropriate entries for writing its string representation
  361. to the header of the file.
  362. version : tuple or None
  363. None means use oldest that works. Providing an explicit version will
  364. raise a ValueError if the format does not allow saving this data.
  365. Default: None
  366. """
  367. header = ["{"]
  368. for key, value in sorted(d.items()):
  369. # Need to use repr here, since we eval these when reading
  370. header.append("'%s': %s, " % (key, repr(value)))
  371. header.append("}")
  372. header = "".join(header)
  373. # Add some spare space so that the array header can be modified in-place
  374. # when changing the array size, e.g. when growing it by appending data at
  375. # the end.
  376. shape = d['shape']
  377. header += " " * ((GROWTH_AXIS_MAX_DIGITS - len(repr(
  378. shape[-1 if d['fortran_order'] else 0]
  379. ))) if len(shape) > 0 else 0)
  380. if version is None:
  381. header = _wrap_header_guess_version(header)
  382. else:
  383. header = _wrap_header(header, version)
  384. fp.write(header)
  385. def write_array_header_1_0(fp, d):
  386. """ Write the header for an array using the 1.0 format.
  387. Parameters
  388. ----------
  389. fp : filelike object
  390. d : dict
  391. This has the appropriate entries for writing its string
  392. representation to the header of the file.
  393. """
  394. _write_array_header(fp, d, (1, 0))
  395. def write_array_header_2_0(fp, d):
  396. """ Write the header for an array using the 2.0 format.
  397. The 2.0 format allows storing very large structured arrays.
  398. Parameters
  399. ----------
  400. fp : filelike object
  401. d : dict
  402. This has the appropriate entries for writing its string
  403. representation to the header of the file.
  404. """
  405. _write_array_header(fp, d, (2, 0))
  406. def read_array_header_1_0(fp, max_header_size=_MAX_HEADER_SIZE):
  407. """
  408. Read an array header from a filelike object using the 1.0 file format
  409. version.
  410. This will leave the file object located just after the header.
  411. Parameters
  412. ----------
  413. fp : filelike object
  414. A file object or something with a `.read()` method like a file.
  415. Returns
  416. -------
  417. shape : tuple of int
  418. The shape of the array.
  419. fortran_order : bool
  420. The array data will be written out directly if it is either
  421. C-contiguous or Fortran-contiguous. Otherwise, it will be made
  422. contiguous before writing it out.
  423. dtype : dtype
  424. The dtype of the file's data.
  425. max_header_size : int, optional
  426. Maximum allowed size of the header. Large headers may not be safe
  427. to load securely and thus require explicitly passing a larger value.
  428. See :py:func:`ast.literal_eval()` for details.
  429. Raises
  430. ------
  431. ValueError
  432. If the data is invalid.
  433. """
  434. return _read_array_header(
  435. fp, version=(1, 0), max_header_size=max_header_size)
  436. def read_array_header_2_0(fp, max_header_size=_MAX_HEADER_SIZE):
  437. """
  438. Read an array header from a filelike object using the 2.0 file format
  439. version.
  440. This will leave the file object located just after the header.
  441. Parameters
  442. ----------
  443. fp : filelike object
  444. A file object or something with a `.read()` method like a file.
  445. max_header_size : int, optional
  446. Maximum allowed size of the header. Large headers may not be safe
  447. to load securely and thus require explicitly passing a larger value.
  448. See :py:func:`ast.literal_eval()` for details.
  449. Returns
  450. -------
  451. shape : tuple of int
  452. The shape of the array.
  453. fortran_order : bool
  454. The array data will be written out directly if it is either
  455. C-contiguous or Fortran-contiguous. Otherwise, it will be made
  456. contiguous before writing it out.
  457. dtype : dtype
  458. The dtype of the file's data.
  459. Raises
  460. ------
  461. ValueError
  462. If the data is invalid.
  463. """
  464. return _read_array_header(
  465. fp, version=(2, 0), max_header_size=max_header_size)
  466. def _filter_header(s):
  467. """Clean up 'L' in npz header ints.
  468. Cleans up the 'L' in strings representing integers. Needed to allow npz
  469. headers produced in Python2 to be read in Python3.
  470. Parameters
  471. ----------
  472. s : string
  473. Npy file header.
  474. Returns
  475. -------
  476. header : str
  477. Cleaned up header.
  478. """
  479. import tokenize
  480. from io import StringIO
  481. tokens = []
  482. last_token_was_number = False
  483. for token in tokenize.generate_tokens(StringIO(s).readline):
  484. token_type = token[0]
  485. token_string = token[1]
  486. if (last_token_was_number and
  487. token_type == tokenize.NAME and
  488. token_string == "L"):
  489. continue
  490. else:
  491. tokens.append(token)
  492. last_token_was_number = (token_type == tokenize.NUMBER)
  493. return tokenize.untokenize(tokens)
  494. def _read_array_header(fp, version, max_header_size=_MAX_HEADER_SIZE):
  495. """
  496. see read_array_header_1_0
  497. """
  498. # Read an unsigned, little-endian short int which has the length of the
  499. # header.
  500. import ast
  501. import struct
  502. hinfo = _header_size_info.get(version)
  503. if hinfo is None:
  504. raise ValueError("Invalid version {!r}".format(version))
  505. hlength_type, encoding = hinfo
  506. hlength_str = _read_bytes(fp, struct.calcsize(hlength_type), "array header length")
  507. header_length = struct.unpack(hlength_type, hlength_str)[0]
  508. header = _read_bytes(fp, header_length, "array header")
  509. header = header.decode(encoding)
  510. if len(header) > max_header_size:
  511. raise ValueError(
  512. f"Header info length ({len(header)}) is large and may not be safe "
  513. "to load securely.\n"
  514. "To allow loading, adjust `max_header_size` or fully trust "
  515. "the `.npy` file using `allow_pickle=True`.\n"
  516. "For safety against large resource use or crashes, sandboxing "
  517. "may be necessary.")
  518. # The header is a pretty-printed string representation of a literal
  519. # Python dictionary with trailing newlines padded to a ARRAY_ALIGN byte
  520. # boundary. The keys are strings.
  521. # "shape" : tuple of int
  522. # "fortran_order" : bool
  523. # "descr" : dtype.descr
  524. # Versions (2, 0) and (1, 0) could have been created by a Python 2
  525. # implementation before header filtering was implemented.
  526. #
  527. # For performance reasons, we try without _filter_header first though
  528. try:
  529. d = ast.literal_eval(header)
  530. except SyntaxError as e:
  531. if version <= (2, 0):
  532. header = _filter_header(header)
  533. try:
  534. d = ast.literal_eval(header)
  535. except SyntaxError as e2:
  536. msg = "Cannot parse header: {!r}"
  537. raise ValueError(msg.format(header)) from e2
  538. else:
  539. warnings.warn(
  540. "Reading `.npy` or `.npz` file required additional "
  541. "header parsing as it was created on Python 2. Save the "
  542. "file again to speed up loading and avoid this warning.",
  543. UserWarning, stacklevel=4)
  544. else:
  545. msg = "Cannot parse header: {!r}"
  546. raise ValueError(msg.format(header)) from e
  547. if not isinstance(d, dict):
  548. msg = "Header is not a dictionary: {!r}"
  549. raise ValueError(msg.format(d))
  550. if EXPECTED_KEYS != d.keys():
  551. keys = sorted(d.keys())
  552. msg = "Header does not contain the correct keys: {!r}"
  553. raise ValueError(msg.format(keys))
  554. # Sanity-check the values.
  555. if (not isinstance(d['shape'], tuple) or
  556. not all(isinstance(x, int) for x in d['shape'])):
  557. msg = "shape is not valid: {!r}"
  558. raise ValueError(msg.format(d['shape']))
  559. if not isinstance(d['fortran_order'], bool):
  560. msg = "fortran_order is not a valid bool: {!r}"
  561. raise ValueError(msg.format(d['fortran_order']))
  562. try:
  563. dtype = descr_to_dtype(d['descr'])
  564. except TypeError as e:
  565. msg = "descr is not a valid dtype descriptor: {!r}"
  566. raise ValueError(msg.format(d['descr'])) from e
  567. return d['shape'], d['fortran_order'], dtype
  568. def write_array(fp, array, version=None, allow_pickle=True, pickle_kwargs=None):
  569. """
  570. Write an array to an NPY file, including a header.
  571. If the array is neither C-contiguous nor Fortran-contiguous AND the
  572. file_like object is not a real file object, this function will have to
  573. copy data in memory.
  574. Parameters
  575. ----------
  576. fp : file_like object
  577. An open, writable file object, or similar object with a
  578. ``.write()`` method.
  579. array : ndarray
  580. The array to write to disk.
  581. version : (int, int) or None, optional
  582. The version number of the format. None means use the oldest
  583. supported version that is able to store the data. Default: None
  584. allow_pickle : bool, optional
  585. Whether to allow writing pickled data. Default: True
  586. pickle_kwargs : dict, optional
  587. Additional keyword arguments to pass to pickle.dump, excluding
  588. 'protocol'. These are only useful when pickling objects in object
  589. arrays on Python 3 to Python 2 compatible format.
  590. Raises
  591. ------
  592. ValueError
  593. If the array cannot be persisted. This includes the case of
  594. allow_pickle=False and array being an object array.
  595. Various other errors
  596. If the array contains Python objects as part of its dtype, the
  597. process of pickling them may raise various errors if the objects
  598. are not picklable.
  599. """
  600. _check_version(version)
  601. _write_array_header(fp, header_data_from_array_1_0(array), version)
  602. if array.itemsize == 0:
  603. buffersize = 0
  604. else:
  605. # Set buffer size to 16 MiB to hide the Python loop overhead.
  606. buffersize = max(16 * 1024 ** 2 // array.itemsize, 1)
  607. dtype_class = type(array.dtype)
  608. if array.dtype.hasobject or not dtype_class._legacy:
  609. # We contain Python objects so we cannot write out the data
  610. # directly. Instead, we will pickle it out
  611. if not allow_pickle:
  612. if array.dtype.hasobject:
  613. raise ValueError("Object arrays cannot be saved when "
  614. "allow_pickle=False")
  615. if not dtype_class._legacy:
  616. raise ValueError("User-defined dtypes cannot be saved "
  617. "when allow_pickle=False")
  618. if pickle_kwargs is None:
  619. pickle_kwargs = {}
  620. pickle.dump(array, fp, protocol=4, **pickle_kwargs)
  621. elif array.flags.f_contiguous and not array.flags.c_contiguous:
  622. if isfileobj(fp):
  623. array.T.tofile(fp)
  624. else:
  625. for chunk in numpy.nditer(
  626. array, flags=['external_loop', 'buffered', 'zerosize_ok'],
  627. buffersize=buffersize, order='F'):
  628. fp.write(chunk.tobytes('C'))
  629. else:
  630. if isfileobj(fp):
  631. array.tofile(fp)
  632. else:
  633. for chunk in numpy.nditer(
  634. array, flags=['external_loop', 'buffered', 'zerosize_ok'],
  635. buffersize=buffersize, order='C'):
  636. fp.write(chunk.tobytes('C'))
  637. def read_array(fp, allow_pickle=False, pickle_kwargs=None, *,
  638. max_header_size=_MAX_HEADER_SIZE):
  639. """
  640. Read an array from an NPY file.
  641. Parameters
  642. ----------
  643. fp : file_like object
  644. If this is not a real file object, then this may take extra memory
  645. and time.
  646. allow_pickle : bool, optional
  647. Whether to allow writing pickled data. Default: False
  648. pickle_kwargs : dict
  649. Additional keyword arguments to pass to pickle.load. These are only
  650. useful when loading object arrays saved on Python 2 when using
  651. Python 3.
  652. max_header_size : int, optional
  653. Maximum allowed size of the header. Large headers may not be safe
  654. to load securely and thus require explicitly passing a larger value.
  655. See :py:func:`ast.literal_eval()` for details.
  656. This option is ignored when `allow_pickle` is passed. In that case
  657. the file is by definition trusted and the limit is unnecessary.
  658. Returns
  659. -------
  660. array : ndarray
  661. The array from the data on disk.
  662. Raises
  663. ------
  664. ValueError
  665. If the data is invalid, or allow_pickle=False and the file contains
  666. an object array.
  667. """
  668. if allow_pickle:
  669. # Effectively ignore max_header_size, since `allow_pickle` indicates
  670. # that the input is fully trusted.
  671. max_header_size = 2**64
  672. version = read_magic(fp)
  673. _check_version(version)
  674. shape, fortran_order, dtype = _read_array_header(
  675. fp, version, max_header_size=max_header_size)
  676. if len(shape) == 0:
  677. count = 1
  678. else:
  679. count = numpy.multiply.reduce(shape, dtype=numpy.int64)
  680. # Now read the actual data.
  681. if dtype.hasobject:
  682. # The array contained Python objects. We need to unpickle the data.
  683. if not allow_pickle:
  684. raise ValueError("Object arrays cannot be loaded when "
  685. "allow_pickle=False")
  686. if pickle_kwargs is None:
  687. pickle_kwargs = {}
  688. try:
  689. array = pickle.load(fp, **pickle_kwargs)
  690. except UnicodeError as err:
  691. # Friendlier error message
  692. raise UnicodeError("Unpickling a python object failed: %r\n"
  693. "You may need to pass the encoding= option "
  694. "to numpy.load" % (err,)) from err
  695. else:
  696. if isfileobj(fp):
  697. # We can use the fast fromfile() function.
  698. array = numpy.fromfile(fp, dtype=dtype, count=count)
  699. else:
  700. # This is not a real file. We have to read it the
  701. # memory-intensive way.
  702. # crc32 module fails on reads greater than 2 ** 32 bytes,
  703. # breaking large reads from gzip streams. Chunk reads to
  704. # BUFFER_SIZE bytes to avoid issue and reduce memory overhead
  705. # of the read. In non-chunked case count < max_read_count, so
  706. # only one read is performed.
  707. # Use np.ndarray instead of np.empty since the latter does
  708. # not correctly instantiate zero-width string dtypes; see
  709. # https://github.com/numpy/numpy/pull/6430
  710. array = numpy.ndarray(count, dtype=dtype)
  711. if dtype.itemsize > 0:
  712. # If dtype.itemsize == 0 then there's nothing more to read
  713. max_read_count = BUFFER_SIZE // min(BUFFER_SIZE, dtype.itemsize)
  714. for i in range(0, count, max_read_count):
  715. read_count = min(max_read_count, count - i)
  716. read_size = int(read_count * dtype.itemsize)
  717. data = _read_bytes(fp, read_size, "array data")
  718. array[i:i+read_count] = numpy.frombuffer(data, dtype=dtype,
  719. count=read_count)
  720. if fortran_order:
  721. array.shape = shape[::-1]
  722. array = array.transpose()
  723. else:
  724. array.shape = shape
  725. return array
  726. def open_memmap(filename, mode='r+', dtype=None, shape=None,
  727. fortran_order=False, version=None, *,
  728. max_header_size=_MAX_HEADER_SIZE):
  729. """
  730. Open a .npy file as a memory-mapped array.
  731. This may be used to read an existing file or create a new one.
  732. Parameters
  733. ----------
  734. filename : str or path-like
  735. The name of the file on disk. This may *not* be a file-like
  736. object.
  737. mode : str, optional
  738. The mode in which to open the file; the default is 'r+'. In
  739. addition to the standard file modes, 'c' is also accepted to mean
  740. "copy on write." See `memmap` for the available mode strings.
  741. dtype : data-type, optional
  742. The data type of the array if we are creating a new file in "write"
  743. mode, if not, `dtype` is ignored. The default value is None, which
  744. results in a data-type of `float64`.
  745. shape : tuple of int
  746. The shape of the array if we are creating a new file in "write"
  747. mode, in which case this parameter is required. Otherwise, this
  748. parameter is ignored and is thus optional.
  749. fortran_order : bool, optional
  750. Whether the array should be Fortran-contiguous (True) or
  751. C-contiguous (False, the default) if we are creating a new file in
  752. "write" mode.
  753. version : tuple of int (major, minor) or None
  754. If the mode is a "write" mode, then this is the version of the file
  755. format used to create the file. None means use the oldest
  756. supported version that is able to store the data. Default: None
  757. max_header_size : int, optional
  758. Maximum allowed size of the header. Large headers may not be safe
  759. to load securely and thus require explicitly passing a larger value.
  760. See :py:func:`ast.literal_eval()` for details.
  761. Returns
  762. -------
  763. marray : memmap
  764. The memory-mapped array.
  765. Raises
  766. ------
  767. ValueError
  768. If the data or the mode is invalid.
  769. OSError
  770. If the file is not found or cannot be opened correctly.
  771. See Also
  772. --------
  773. numpy.memmap
  774. """
  775. if isfileobj(filename):
  776. raise ValueError("Filename must be a string or a path-like object."
  777. " Memmap cannot use existing file handles.")
  778. if 'w' in mode:
  779. # We are creating the file, not reading it.
  780. # Check if we ought to create the file.
  781. _check_version(version)
  782. # Ensure that the given dtype is an authentic dtype object rather
  783. # than just something that can be interpreted as a dtype object.
  784. dtype = numpy.dtype(dtype)
  785. if dtype.hasobject:
  786. msg = "Array can't be memory-mapped: Python objects in dtype."
  787. raise ValueError(msg)
  788. d = dict(
  789. descr=dtype_to_descr(dtype),
  790. fortran_order=fortran_order,
  791. shape=shape,
  792. )
  793. # If we got here, then it should be safe to create the file.
  794. with open(os.fspath(filename), mode+'b') as fp:
  795. _write_array_header(fp, d, version)
  796. offset = fp.tell()
  797. else:
  798. # Read the header of the file first.
  799. with open(os.fspath(filename), 'rb') as fp:
  800. version = read_magic(fp)
  801. _check_version(version)
  802. shape, fortran_order, dtype = _read_array_header(
  803. fp, version, max_header_size=max_header_size)
  804. if dtype.hasobject:
  805. msg = "Array can't be memory-mapped: Python objects in dtype."
  806. raise ValueError(msg)
  807. offset = fp.tell()
  808. if fortran_order:
  809. order = 'F'
  810. else:
  811. order = 'C'
  812. # We need to change a write-only mode to a read-write mode since we've
  813. # already written data to the file.
  814. if mode == 'w+':
  815. mode = 'r+'
  816. marray = numpy.memmap(filename, dtype=dtype, shape=shape, order=order,
  817. mode=mode, offset=offset)
  818. return marray
  819. def _read_bytes(fp, size, error_template="ran out of data"):
  820. """
  821. Read from file-like object until size bytes are read.
  822. Raises ValueError if not EOF is encountered before size bytes are read.
  823. Non-blocking objects only supported if they derive from io objects.
  824. Required as e.g. ZipExtFile in python 2.6 can return less data than
  825. requested.
  826. """
  827. data = bytes()
  828. while True:
  829. # io files (default in python3) return None or raise on
  830. # would-block, python2 file will truncate, probably nothing can be
  831. # done about that. note that regular files can't be non-blocking
  832. try:
  833. r = fp.read(size - len(data))
  834. data += r
  835. if len(r) == 0 or len(data) == size:
  836. break
  837. except BlockingIOError:
  838. pass
  839. if len(data) != size:
  840. msg = "EOF: reading %s, expected %d bytes got %d"
  841. raise ValueError(msg % (error_template, size, len(data)))
  842. else:
  843. return data
  844. def isfileobj(f):
  845. if not isinstance(f, (io.FileIO, io.BufferedReader, io.BufferedWriter)):
  846. return False
  847. try:
  848. # BufferedReader/Writer may raise OSError when
  849. # fetching `fileno()` (e.g. when wrapping BytesIO).
  850. f.fileno()
  851. return True
  852. except OSError:
  853. return False