format.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914
  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. MAGIC_PREFIX = b'\x93NUMPY'
  135. MAGIC_LEN = len(MAGIC_PREFIX) + 2
  136. ARRAY_ALIGN = 64 # plausible values are powers of 2 between 16 and 4096
  137. BUFFER_SIZE = 2**18 # size of buffer for reading npz files in bytes
  138. # difference between version 1.0 and 2.0 is a 4 byte (I) header length
  139. # instead of 2 bytes (H) allowing storage of large structured arrays
  140. _header_size_info = {
  141. (1, 0): ('<H', 'latin1'),
  142. (2, 0): ('<I', 'latin1'),
  143. (3, 0): ('<I', 'utf8'),
  144. }
  145. def _check_version(version):
  146. if version not in [(1, 0), (2, 0), (3, 0), None]:
  147. msg = "we only support format version (1,0), (2,0), and (3,0), not %s"
  148. raise ValueError(msg % (version,))
  149. def magic(major, minor):
  150. """ Return the magic string for the given file format version.
  151. Parameters
  152. ----------
  153. major : int in [0, 255]
  154. minor : int in [0, 255]
  155. Returns
  156. -------
  157. magic : str
  158. Raises
  159. ------
  160. ValueError if the version cannot be formatted.
  161. """
  162. if major < 0 or major > 255:
  163. raise ValueError("major version must be 0 <= major < 256")
  164. if minor < 0 or minor > 255:
  165. raise ValueError("minor version must be 0 <= minor < 256")
  166. return MAGIC_PREFIX + bytes([major, minor])
  167. def read_magic(fp):
  168. """ Read the magic string to get the version of the file format.
  169. Parameters
  170. ----------
  171. fp : filelike object
  172. Returns
  173. -------
  174. major : int
  175. minor : int
  176. """
  177. magic_str = _read_bytes(fp, MAGIC_LEN, "magic string")
  178. if magic_str[:-2] != MAGIC_PREFIX:
  179. msg = "the magic string is not correct; expected %r, got %r"
  180. raise ValueError(msg % (MAGIC_PREFIX, magic_str[:-2]))
  181. major, minor = magic_str[-2:]
  182. return major, minor
  183. def _has_metadata(dt):
  184. if dt.metadata is not None:
  185. return True
  186. elif dt.names is not None:
  187. return any(_has_metadata(dt[k]) for k in dt.names)
  188. elif dt.subdtype is not None:
  189. return _has_metadata(dt.base)
  190. else:
  191. return False
  192. def dtype_to_descr(dtype):
  193. """
  194. Get a serializable descriptor from the dtype.
  195. The .descr attribute of a dtype object cannot be round-tripped through
  196. the dtype() constructor. Simple types, like dtype('float32'), have
  197. a descr which looks like a record array with one field with '' as
  198. a name. The dtype() constructor interprets this as a request to give
  199. a default name. Instead, we construct descriptor that can be passed to
  200. dtype().
  201. Parameters
  202. ----------
  203. dtype : dtype
  204. The dtype of the array that will be written to disk.
  205. Returns
  206. -------
  207. descr : object
  208. An object that can be passed to `numpy.dtype()` in order to
  209. replicate the input dtype.
  210. """
  211. if _has_metadata(dtype):
  212. warnings.warn("metadata on a dtype may be saved or ignored, but will "
  213. "raise if saved when read. Use another form of storage.",
  214. UserWarning, stacklevel=2)
  215. if dtype.names is not None:
  216. # This is a record array. The .descr is fine. XXX: parts of the
  217. # record array with an empty name, like padding bytes, still get
  218. # fiddled with. This needs to be fixed in the C implementation of
  219. # dtype().
  220. return dtype.descr
  221. else:
  222. return dtype.str
  223. def descr_to_dtype(descr):
  224. """
  225. Returns a dtype based off the given description.
  226. This is essentially the reverse of `dtype_to_descr()`. It will remove
  227. the valueless padding fields created by, i.e. simple fields like
  228. dtype('float32'), and then convert the description to its corresponding
  229. dtype.
  230. Parameters
  231. ----------
  232. descr : object
  233. The object retreived by dtype.descr. Can be passed to
  234. `numpy.dtype()` in order to replicate the input dtype.
  235. Returns
  236. -------
  237. dtype : dtype
  238. The dtype constructed by the description.
  239. """
  240. if isinstance(descr, str):
  241. # No padding removal needed
  242. return numpy.dtype(descr)
  243. elif isinstance(descr, tuple):
  244. # subtype, will always have a shape descr[1]
  245. dt = descr_to_dtype(descr[0])
  246. return numpy.dtype((dt, descr[1]))
  247. titles = []
  248. names = []
  249. formats = []
  250. offsets = []
  251. offset = 0
  252. for field in descr:
  253. if len(field) == 2:
  254. name, descr_str = field
  255. dt = descr_to_dtype(descr_str)
  256. else:
  257. name, descr_str, shape = field
  258. dt = numpy.dtype((descr_to_dtype(descr_str), shape))
  259. # Ignore padding bytes, which will be void bytes with '' as name
  260. # Once support for blank names is removed, only "if name == ''" needed)
  261. is_pad = (name == '' and dt.type is numpy.void and dt.names is None)
  262. if not is_pad:
  263. title, name = name if isinstance(name, tuple) else (None, name)
  264. titles.append(title)
  265. names.append(name)
  266. formats.append(dt)
  267. offsets.append(offset)
  268. offset += dt.itemsize
  269. return numpy.dtype({'names': names, 'formats': formats, 'titles': titles,
  270. 'offsets': offsets, 'itemsize': offset})
  271. def header_data_from_array_1_0(array):
  272. """ Get the dictionary of header metadata from a numpy.ndarray.
  273. Parameters
  274. ----------
  275. array : numpy.ndarray
  276. Returns
  277. -------
  278. d : dict
  279. This has the appropriate entries for writing its string representation
  280. to the header of the file.
  281. """
  282. d = {'shape': array.shape}
  283. if array.flags.c_contiguous:
  284. d['fortran_order'] = False
  285. elif array.flags.f_contiguous:
  286. d['fortran_order'] = True
  287. else:
  288. # Totally non-contiguous data. We will have to make it C-contiguous
  289. # before writing. Note that we need to test for C_CONTIGUOUS first
  290. # because a 1-D array is both C_CONTIGUOUS and F_CONTIGUOUS.
  291. d['fortran_order'] = False
  292. d['descr'] = dtype_to_descr(array.dtype)
  293. return d
  294. def _wrap_header(header, version):
  295. """
  296. Takes a stringified header, and attaches the prefix and padding to it
  297. """
  298. import struct
  299. assert version is not None
  300. fmt, encoding = _header_size_info[version]
  301. if not isinstance(header, bytes): # always true on python 3
  302. header = header.encode(encoding)
  303. hlen = len(header) + 1
  304. padlen = ARRAY_ALIGN - ((MAGIC_LEN + struct.calcsize(fmt) + hlen) % ARRAY_ALIGN)
  305. try:
  306. header_prefix = magic(*version) + struct.pack(fmt, hlen + padlen)
  307. except struct.error:
  308. msg = "Header length {} too big for version={}".format(hlen, version)
  309. raise ValueError(msg)
  310. # Pad the header with spaces and a final newline such that the magic
  311. # string, the header-length short and the header are aligned on a
  312. # ARRAY_ALIGN byte boundary. This supports memory mapping of dtypes
  313. # aligned up to ARRAY_ALIGN on systems like Linux where mmap()
  314. # offset must be page-aligned (i.e. the beginning of the file).
  315. return header_prefix + header + b' '*padlen + b'\n'
  316. def _wrap_header_guess_version(header):
  317. """
  318. Like `_wrap_header`, but chooses an appropriate version given the contents
  319. """
  320. try:
  321. return _wrap_header(header, (1, 0))
  322. except ValueError:
  323. pass
  324. try:
  325. ret = _wrap_header(header, (2, 0))
  326. except UnicodeEncodeError:
  327. pass
  328. else:
  329. warnings.warn("Stored array in format 2.0. It can only be"
  330. "read by NumPy >= 1.9", UserWarning, stacklevel=2)
  331. return ret
  332. header = _wrap_header(header, (3, 0))
  333. warnings.warn("Stored array in format 3.0. It can only be "
  334. "read by NumPy >= 1.17", UserWarning, stacklevel=2)
  335. return header
  336. def _write_array_header(fp, d, version=None):
  337. """ Write the header for an array and returns the version used
  338. Parameters
  339. ----------
  340. fp : filelike object
  341. d : dict
  342. This has the appropriate entries for writing its string representation
  343. to the header of the file.
  344. version: tuple or None
  345. None means use oldest that works
  346. explicit version will raise a ValueError if the format does not
  347. allow saving this data. Default: None
  348. """
  349. header = ["{"]
  350. for key, value in sorted(d.items()):
  351. # Need to use repr here, since we eval these when reading
  352. header.append("'%s': %s, " % (key, repr(value)))
  353. header.append("}")
  354. header = "".join(header)
  355. header = _filter_header(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. header = _filter_header(header)
  484. try:
  485. d = safe_eval(header)
  486. except SyntaxError as e:
  487. msg = "Cannot parse header: {!r}\nException: {!r}"
  488. raise ValueError(msg.format(header, e))
  489. if not isinstance(d, dict):
  490. msg = "Header is not a dictionary: {!r}"
  491. raise ValueError(msg.format(d))
  492. keys = sorted(d.keys())
  493. if keys != ['descr', 'fortran_order', 'shape']:
  494. msg = "Header does not contain the correct keys: {!r}"
  495. raise ValueError(msg.format(keys))
  496. # Sanity-check the values.
  497. if (not isinstance(d['shape'], tuple) or
  498. not numpy.all([isinstance(x, int) for x in d['shape']])):
  499. msg = "shape is not valid: {!r}"
  500. raise ValueError(msg.format(d['shape']))
  501. if not isinstance(d['fortran_order'], bool):
  502. msg = "fortran_order is not a valid bool: {!r}"
  503. raise ValueError(msg.format(d['fortran_order']))
  504. try:
  505. dtype = descr_to_dtype(d['descr'])
  506. except TypeError:
  507. msg = "descr is not a valid dtype descriptor: {!r}"
  508. raise ValueError(msg.format(d['descr']))
  509. return d['shape'], d['fortran_order'], dtype
  510. def write_array(fp, array, version=None, allow_pickle=True, pickle_kwargs=None):
  511. """
  512. Write an array to an NPY file, including a header.
  513. If the array is neither C-contiguous nor Fortran-contiguous AND the
  514. file_like object is not a real file object, this function will have to
  515. copy data in memory.
  516. Parameters
  517. ----------
  518. fp : file_like object
  519. An open, writable file object, or similar object with a
  520. ``.write()`` method.
  521. array : ndarray
  522. The array to write to disk.
  523. version : (int, int) or None, optional
  524. The version number of the format. None means use the oldest
  525. supported version that is able to store the data. Default: None
  526. allow_pickle : bool, optional
  527. Whether to allow writing pickled data. Default: True
  528. pickle_kwargs : dict, optional
  529. Additional keyword arguments to pass to pickle.dump, excluding
  530. 'protocol'. These are only useful when pickling objects in object
  531. arrays on Python 3 to Python 2 compatible format.
  532. Raises
  533. ------
  534. ValueError
  535. If the array cannot be persisted. This includes the case of
  536. allow_pickle=False and array being an object array.
  537. Various other errors
  538. If the array contains Python objects as part of its dtype, the
  539. process of pickling them may raise various errors if the objects
  540. are not picklable.
  541. """
  542. _check_version(version)
  543. _write_array_header(fp, header_data_from_array_1_0(array), version)
  544. if array.itemsize == 0:
  545. buffersize = 0
  546. else:
  547. # Set buffer size to 16 MiB to hide the Python loop overhead.
  548. buffersize = max(16 * 1024 ** 2 // array.itemsize, 1)
  549. if array.dtype.hasobject:
  550. # We contain Python objects so we cannot write out the data
  551. # directly. Instead, we will pickle it out
  552. if not allow_pickle:
  553. raise ValueError("Object arrays cannot be saved when "
  554. "allow_pickle=False")
  555. if pickle_kwargs is None:
  556. pickle_kwargs = {}
  557. pickle.dump(array, fp, protocol=3, **pickle_kwargs)
  558. elif array.flags.f_contiguous and not array.flags.c_contiguous:
  559. if isfileobj(fp):
  560. array.T.tofile(fp)
  561. else:
  562. for chunk in numpy.nditer(
  563. array, flags=['external_loop', 'buffered', 'zerosize_ok'],
  564. buffersize=buffersize, order='F'):
  565. fp.write(chunk.tobytes('C'))
  566. else:
  567. if isfileobj(fp):
  568. array.tofile(fp)
  569. else:
  570. for chunk in numpy.nditer(
  571. array, flags=['external_loop', 'buffered', 'zerosize_ok'],
  572. buffersize=buffersize, order='C'):
  573. fp.write(chunk.tobytes('C'))
  574. def read_array(fp, allow_pickle=False, pickle_kwargs=None):
  575. """
  576. Read an array from an NPY file.
  577. Parameters
  578. ----------
  579. fp : file_like object
  580. If this is not a real file object, then this may take extra memory
  581. and time.
  582. allow_pickle : bool, optional
  583. Whether to allow writing pickled data. Default: False
  584. .. versionchanged:: 1.16.3
  585. Made default False in response to CVE-2019-6446.
  586. pickle_kwargs : dict
  587. Additional keyword arguments to pass to pickle.load. These are only
  588. useful when loading object arrays saved on Python 2 when using
  589. Python 3.
  590. Returns
  591. -------
  592. array : ndarray
  593. The array from the data on disk.
  594. Raises
  595. ------
  596. ValueError
  597. If the data is invalid, or allow_pickle=False and the file contains
  598. an object array.
  599. """
  600. version = read_magic(fp)
  601. _check_version(version)
  602. shape, fortran_order, dtype = _read_array_header(fp, version)
  603. if len(shape) == 0:
  604. count = 1
  605. else:
  606. count = numpy.multiply.reduce(shape, dtype=numpy.int64)
  607. # Now read the actual data.
  608. if dtype.hasobject:
  609. # The array contained Python objects. We need to unpickle the data.
  610. if not allow_pickle:
  611. raise ValueError("Object arrays cannot be loaded when "
  612. "allow_pickle=False")
  613. if pickle_kwargs is None:
  614. pickle_kwargs = {}
  615. try:
  616. array = pickle.load(fp, **pickle_kwargs)
  617. except UnicodeError as err:
  618. # Friendlier error message
  619. raise UnicodeError("Unpickling a python object failed: %r\n"
  620. "You may need to pass the encoding= option "
  621. "to numpy.load" % (err,)) from err
  622. else:
  623. if isfileobj(fp):
  624. # We can use the fast fromfile() function.
  625. array = numpy.fromfile(fp, dtype=dtype, count=count)
  626. else:
  627. # This is not a real file. We have to read it the
  628. # memory-intensive way.
  629. # crc32 module fails on reads greater than 2 ** 32 bytes,
  630. # breaking large reads from gzip streams. Chunk reads to
  631. # BUFFER_SIZE bytes to avoid issue and reduce memory overhead
  632. # of the read. In non-chunked case count < max_read_count, so
  633. # only one read is performed.
  634. # Use np.ndarray instead of np.empty since the latter does
  635. # not correctly instantiate zero-width string dtypes; see
  636. # https://github.com/numpy/numpy/pull/6430
  637. array = numpy.ndarray(count, dtype=dtype)
  638. if dtype.itemsize > 0:
  639. # If dtype.itemsize == 0 then there's nothing more to read
  640. max_read_count = BUFFER_SIZE // min(BUFFER_SIZE, dtype.itemsize)
  641. for i in range(0, count, max_read_count):
  642. read_count = min(max_read_count, count - i)
  643. read_size = int(read_count * dtype.itemsize)
  644. data = _read_bytes(fp, read_size, "array data")
  645. array[i:i+read_count] = numpy.frombuffer(data, dtype=dtype,
  646. count=read_count)
  647. if fortran_order:
  648. array.shape = shape[::-1]
  649. array = array.transpose()
  650. else:
  651. array.shape = shape
  652. return array
  653. def open_memmap(filename, mode='r+', dtype=None, shape=None,
  654. fortran_order=False, version=None):
  655. """
  656. Open a .npy file as a memory-mapped array.
  657. This may be used to read an existing file or create a new one.
  658. Parameters
  659. ----------
  660. filename : str or path-like
  661. The name of the file on disk. This may *not* be a file-like
  662. object.
  663. mode : str, optional
  664. The mode in which to open the file; the default is 'r+'. In
  665. addition to the standard file modes, 'c' is also accepted to mean
  666. "copy on write." See `memmap` for the available mode strings.
  667. dtype : data-type, optional
  668. The data type of the array if we are creating a new file in "write"
  669. mode, if not, `dtype` is ignored. The default value is None, which
  670. results in a data-type of `float64`.
  671. shape : tuple of int
  672. The shape of the array if we are creating a new file in "write"
  673. mode, in which case this parameter is required. Otherwise, this
  674. parameter is ignored and is thus optional.
  675. fortran_order : bool, optional
  676. Whether the array should be Fortran-contiguous (True) or
  677. C-contiguous (False, the default) if we are creating a new file in
  678. "write" mode.
  679. version : tuple of int (major, minor) or None
  680. If the mode is a "write" mode, then this is the version of the file
  681. format used to create the file. None means use the oldest
  682. supported version that is able to store the data. Default: None
  683. Returns
  684. -------
  685. marray : memmap
  686. The memory-mapped array.
  687. Raises
  688. ------
  689. ValueError
  690. If the data or the mode is invalid.
  691. IOError
  692. If the file is not found or cannot be opened correctly.
  693. See Also
  694. --------
  695. numpy.memmap
  696. """
  697. if isfileobj(filename):
  698. raise ValueError("Filename must be a string or a path-like object."
  699. " Memmap cannot use existing file handles.")
  700. if 'w' in mode:
  701. # We are creating the file, not reading it.
  702. # Check if we ought to create the file.
  703. _check_version(version)
  704. # Ensure that the given dtype is an authentic dtype object rather
  705. # than just something that can be interpreted as a dtype object.
  706. dtype = numpy.dtype(dtype)
  707. if dtype.hasobject:
  708. msg = "Array can't be memory-mapped: Python objects in dtype."
  709. raise ValueError(msg)
  710. d = dict(
  711. descr=dtype_to_descr(dtype),
  712. fortran_order=fortran_order,
  713. shape=shape,
  714. )
  715. # If we got here, then it should be safe to create the file.
  716. with open(os_fspath(filename), mode+'b') as fp:
  717. _write_array_header(fp, d, version)
  718. offset = fp.tell()
  719. else:
  720. # Read the header of the file first.
  721. with open(os_fspath(filename), 'rb') as fp:
  722. version = read_magic(fp)
  723. _check_version(version)
  724. shape, fortran_order, dtype = _read_array_header(fp, version)
  725. if dtype.hasobject:
  726. msg = "Array can't be memory-mapped: Python objects in dtype."
  727. raise ValueError(msg)
  728. offset = fp.tell()
  729. if fortran_order:
  730. order = 'F'
  731. else:
  732. order = 'C'
  733. # We need to change a write-only mode to a read-write mode since we've
  734. # already written data to the file.
  735. if mode == 'w+':
  736. mode = 'r+'
  737. marray = numpy.memmap(filename, dtype=dtype, shape=shape, order=order,
  738. mode=mode, offset=offset)
  739. return marray
  740. def _read_bytes(fp, size, error_template="ran out of data"):
  741. """
  742. Read from file-like object until size bytes are read.
  743. Raises ValueError if not EOF is encountered before size bytes are read.
  744. Non-blocking objects only supported if they derive from io objects.
  745. Required as e.g. ZipExtFile in python 2.6 can return less data than
  746. requested.
  747. """
  748. data = bytes()
  749. while True:
  750. # io files (default in python3) return None or raise on
  751. # would-block, python2 file will truncate, probably nothing can be
  752. # done about that. note that regular files can't be non-blocking
  753. try:
  754. r = fp.read(size - len(data))
  755. data += r
  756. if len(r) == 0 or len(data) == size:
  757. break
  758. except io.BlockingIOError:
  759. pass
  760. if len(data) != size:
  761. msg = "EOF: reading %s, expected %d bytes got %d"
  762. raise ValueError(msg % (error_template, size, len(data)))
  763. else:
  764. return data