_format_impl.py 36 KB

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