format.py 33 KB

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