format.py 31 KB

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