format.py 34 KB

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