zmc
2023-10-12 ed135d79df12a2466b52dae1a82326941211dcc9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
U
P±dk‰ã@s4dZddlZddlZddlmZddlmZmZmZgZ    dddhZ
dZ e e ƒd    Z d
Zd Zd Zd dddœZdZdd„Zdd„Zdd„Zdd„Zdd„Zdd„Zdd„Zd d!„Zd"d#„Zd?d$d%„Zd&d'„Zd(d)„Zefd*d+„Zefd,d-„Z d.d/„Z!efd0d1„Z"d@d3d4„Z#dAed6œd7d8„Z$dBed6œd:d;„Z%dCd=d>„Z&dS)Daþ
Binary serialization
 
NPY format
==========
 
A simple format for saving numpy arrays to disk with the full
information about them.
 
The ``.npy`` format is the standard binary file format in NumPy for
persisting a *single* arbitrary NumPy array on disk. The format stores all
of the shape and dtype information necessary to reconstruct the array
correctly even on another machine with a different architecture.
The format is designed to be as simple as possible while achieving
its limited goals.
 
The ``.npz`` format is the standard format for persisting *multiple* NumPy
arrays on disk. A ``.npz`` file is a zip file containing multiple ``.npy``
files, one for each array.
 
Capabilities
------------
 
- Can represent all NumPy arrays including nested record arrays and
  object arrays.
 
- Represents the data in its native binary form.
 
- Supports Fortran-contiguous arrays directly.
 
- Stores all of the necessary information to reconstruct the array
  including shape and dtype on a machine of a different
  architecture.  Both little-endian and big-endian arrays are
  supported, and a file with little-endian numbers will yield
  a little-endian array on any machine reading the file. The
  types are described in terms of their actual sizes. For example,
  if a machine with a 64-bit C "long int" writes out an array with
  "long ints", a reading machine with 32-bit C "long ints" will yield
  an array with 64-bit integers.
 
- Is straightforward to reverse engineer. Datasets often live longer than
  the programs that created them. A competent developer should be
  able to create a solution in their preferred programming language to
  read most ``.npy`` files that they have been given without much
  documentation.
 
- Allows memory-mapping of the data. See `open_memmap`.
 
- Can be read from a filelike stream object instead of an actual file.
 
- Stores object arrays, i.e. arrays containing elements that are arbitrary
  Python objects. Files with object arrays are not to be mmapable, but
  can be read and written to disk.
 
Limitations
-----------
 
- Arbitrary subclasses of numpy.ndarray are not completely preserved.
  Subclasses will be accepted for writing, but only the array data will
  be written out. A regular numpy.ndarray object will be created
  upon reading the file.
 
.. warning::
 
  Due to limitations in the interpretation of structured dtypes, dtypes
  with fields with empty names will have the names replaced by 'f0', 'f1',
  etc. Such arrays will not round-trip through the format entirely
  accurately. The data is intact; only the field names will differ. We are
  working on a fix for this. This fix will not require a change in the
  file format. The arrays with such structures can still be saved and
  restored, and the correct dtype may be restored by using the
  ``loadedarray.view(correct_dtype)`` method.
 
File extensions
---------------
 
We recommend using the ``.npy`` and ``.npz`` extensions for files saved
in this format. This is by no means a requirement; applications may wish
to use these file formats but use an extension specific to the
application. In the absence of an obvious alternative, however,
we suggest using ``.npy`` and ``.npz``.
 
Version numbering
-----------------
 
The version numbering of these formats is independent of NumPy version
numbering. If the format is upgraded, the code in `numpy.io` will still
be able to read and write Version 1.0 files.
 
Format Version 1.0
------------------
 
The first 6 bytes are a magic string: exactly ``\x93NUMPY``.
 
The next 1 byte is an unsigned byte: the major version number of the file
format, e.g. ``\x01``.
 
The next 1 byte is an unsigned byte: the minor version number of the file
format, e.g. ``\x00``. Note: the version of the file format is not tied
to the version of the numpy package.
 
The next 2 bytes form a little-endian unsigned short int: the length of
the header data HEADER_LEN.
 
The next HEADER_LEN bytes form the header data describing the array's
format. It is an ASCII string which contains a Python literal expression
of a dictionary. It is terminated by a newline (``\n``) and padded with
spaces (``\x20``) to make the total of
``len(magic string) + 2 + len(length) + HEADER_LEN`` be evenly divisible
by 64 for alignment purposes.
 
The dictionary contains three keys:
 
    "descr" : dtype.descr
      An object that can be passed as an argument to the `numpy.dtype`
      constructor to create the array's dtype.
    "fortran_order" : bool
      Whether the array data is Fortran-contiguous or not. Since
      Fortran-contiguous arrays are a common form of non-C-contiguity,
      we allow them to be written directly to disk for efficiency.
    "shape" : tuple of int
      The shape of the array.
 
For repeatability and readability, the dictionary keys are sorted in
alphabetic order. This is for convenience only. A writer SHOULD implement
this if possible. A reader MUST NOT depend on this.
 
Following the header comes the array data. If the dtype contains Python
objects (i.e. ``dtype.hasobject is True``), then the data is a Python
pickle of the array. Otherwise the data is the contiguous (either C-
or Fortran-, depending on ``fortran_order``) bytes of the array.
Consumers can figure out the number of bytes by multiplying the number
of elements given by the shape (noting that ``shape=()`` means there is
1 element) by ``dtype.itemsize``.
 
Format Version 2.0
------------------
 
The version 1.0 format only allowed the array header to have a total size of
65535 bytes.  This can be exceeded by structured arrays with a large number of
columns.  The version 2.0 format extends the header size to 4 GiB.
`numpy.save` will automatically save in 2.0 format if the data requires it,
else it will always use the more compatible 1.0 format.
 
The description of the fourth element of the header therefore has become:
"The next 4 bytes form a little-endian unsigned int: the length of the header
data HEADER_LEN."
 
Format Version 3.0
------------------
 
This version replaces the ASCII string (which in practice was latin1) with
a utf8-encoded string, so supports structured types with any unicode field
names.
 
Notes
-----
The ``.npy`` format, including motivation for creating it and a comparison of
alternatives, is described in the
:doc:`"npy-format" NEP <neps:nep-0001-npy-format>`, however details have
evolved with time and this document is more current.
 
éN)Ú    safe_eval)Ú    isfileobjÚ    os_fspathÚpickleÚdescrÚ fortran_orderÚshapes“NUMPYéé@ié)z<HÚlatin1)ú<Ir )r Úutf8)©ér©r    r©éri'cCs|dkrd}t||fƒ‚dS)N)rrrNz>we only support format version (1,0), (2,0), and (3,0), not %s)Ú
ValueError)ÚversionÚmsg©rúGd:\z\workplace\vscode\pyvenv\venv\Lib\site-packages\numpy/lib/format.pyÚ_check_versionÄsrcCs@|dks|dkrtdƒ‚|dks(|dkr0tdƒ‚tt||gƒS)a
 Return the magic string for the given file format version.
 
    Parameters
    ----------
    major : int in [0, 255]
    minor : int in [0, 255]
 
    Returns
    -------
    magic : str
 
    Raises
    ------
    ValueError if the version cannot be formatted.
    réÿz&major version must be 0 <= major < 256z&minor version must be 0 <= minor < 256)rÚ MAGIC_PREFIXÚbytes)ÚmajorÚminorrrrÚmagicÉs
rcCsPt|tdƒ}|dd…tkr8d}t|t|dd…fƒ‚|dd…\}}||fS)z³ Read the magic string to get the version of the file format.
 
    Parameters
    ----------
    fp : filelike object
 
    Returns
    -------
    major : int
    minor : int
    z magic stringNéþÿÿÿz4the magic string is not correct; expected %r, got %r)Ú _read_bytesÚ    MAGIC_LENrr)ÚfpZ    magic_strrrrrrrÚ
read_magicßs r$csLˆjdk    rdSˆjdk    r0t‡fdd„ˆjDƒƒSˆjdk    rDtˆjƒSdSdS)NTc3s|]}tˆ|ƒVqdS©N)Ú _has_metadata)Ú.0Úk©ÚdtrrÚ    <genexpr>ösz _has_metadata.<locals>.<genexpr>F)ÚmetadataÚnamesÚanyZsubdtyper&Úbaser)rr)rr&òs
 
 
 
r&cCs2t|ƒrtjdtdd|jdk    r(|jS|jSdS)a´
    Get a serializable descriptor from the dtype.
 
    The .descr attribute of a dtype object cannot be round-tripped through
    the dtype() constructor. Simple types, like dtype('float32'), have
    a descr which looks like a record array with one field with '' as
    a name. The dtype() constructor interprets this as a request to give
    a default name.  Instead, we construct descriptor that can be passed to
    dtype().
 
    Parameters
    ----------
    dtype : dtype
        The dtype of the array that will be written to disk.
 
    Returns
    -------
    descr : object
        An object that can be passed to `numpy.dtype()` in order to
        replicate the input dtype.
 
    zlmetadata on a dtype may be saved or ignored, but will raise if saved when read. Use another form of storage.r    ©Ú
stacklevelN)r&ÚwarningsÚwarnÚ UserWarningr-rÚstr©ÚdtyperrrÚdtype_to_descrüsþ
r8c Cst|tƒrt |¡St|tƒr<t|dƒ}t ||df¡Sg}g}g}g}d}|D]¬}t|ƒdkrv|\}}    t|    ƒ}n|\}}    }
t t|    ƒ|
f¡}|dko®|jtjko®|j    dk} | söt|tƒrÂ|nd|f\} }| 
| ¡| 
|¡| 
|¡| 
|¡||j 7}qTt |||||dœ¡S)a.
    Returns a dtype based off the given description.
 
    This is essentially the reverse of `dtype_to_descr()`. It will remove
    the valueless padding fields created by, i.e. simple fields like
    dtype('float32'), and then convert the description to its corresponding
    dtype.
 
    Parameters
    ----------
    descr : object
        The object retrieved by dtype.descr. Can be passed to
        `numpy.dtype()` in order to replicate the input dtype.
 
    Returns
    -------
    dtype : dtype
        The dtype constructed by the description.
 
    rrr    ÚN)r-ÚformatsÚtitlesÚoffsetsÚitemsize) Ú
isinstancer5Únumpyr7ÚtupleÚdescr_to_dtypeÚlenÚtypeZvoidr-Úappendr=) rr*r;r-r:r<ÚoffsetÚfieldÚnameZ    descr_strrZis_padÚtitlerrrrA s8
 
 
 
 
 
 
 
 
 
ÿrAcCsHd|ji}|jjrd|d<n|jjr.d|d<nd|d<t|jƒ|d<|S)a Get the dictionary of header metadata from a numpy.ndarray.
 
    Parameters
    ----------
    array : numpy.ndarray
 
    Returns
    -------
    d : dict
        This has the appropriate entries for writing its string representation
        to the header of the file.
    rFrTr)rÚflagsÚ c_contiguousÚ f_contiguousr8r7)ÚarrayÚdrrrÚheader_data_from_array_1_0Xs
 
 
rNc    Cs®ddl}|dk    st‚t|\}}| |¡}t|ƒd}tt| |¡|t}zt|Ž|     |||¡}Wn,|j
k
r˜d  ||¡}t |ƒd‚YnX||d|dS)zO
    Takes a stringified header, and attaches the prefix and padding to it
    rNrz'Header length {} too big for version={}ó ó
) ÚstructÚAssertionErrorÚ_header_size_infoÚencoderBÚ ARRAY_ALIGNr"ÚcalcsizerÚpackÚerrorÚformatr)    ÚheaderrrQÚfmtÚencodingZhlenZpadlenZ header_prefixrrrrÚ _wrap_headerts  
  r]cCsxz t|dƒWStk
r YnXzt|dƒ}Wntk
rDYnXtjdtdd|St|dƒ}tjdtdd|S)zT
    Like `_wrap_header`, but chooses an appropriate version given the contents
    rrz>Stored array in format 2.0. It can only beread by NumPy >= 1.9r    r0rz@Stored array in format 3.0. It can only be read by NumPy >= 1.17)r]rÚUnicodeEncodeErrorr2r3r4)rZÚretrrrÚ_wrap_header_guess_versionŒs& ÿ
ÿr`cCs°dg}t| ¡ƒD]\}}| d|t|ƒf¡q| d¡d |¡}|d}|dt|ƒdkr~ttt||drrd    ndƒƒnd7}|d
kr˜t|ƒ}n
t||ƒ}|     |¡d
S) aÀ Write the header for an array and returns the version used
 
    Parameters
    ----------
    fp : filelike object
    d : dict
        This has the appropriate entries for writing its string representation
        to the header of the file.
    version : tuple or None
        None means use oldest that works. Providing an explicit version will
        raise a ValueError if the format does not allow saving this data.
        Default: None
    Ú{z
'%s': %s, Ú}r9rú rréÿÿÿÿN)
ÚsortedÚitemsrDÚreprÚjoinrBÚGROWTH_AXIS_MAX_DIGITSr`r]Úwrite)r#rMrrZÚkeyÚvaluerrrrÚ_write_array_header¤s"
 
 
þÿþ
 
rmcCst||dƒdS)zð Write the header for an array using the 1.0 format.
 
    Parameters
    ----------
    fp : filelike object
    d : dict
        This has the appropriate entries for writing its string
        representation to the header of the file.
    rN©rm©r#rMrrrÚwrite_array_header_1_0Çs
rpcCst||dƒdS)aQ Write the header for an array using the 2.0 format.
        The 2.0 format allows storing very large structured arrays.
 
    .. versionadded:: 1.9.0
 
    Parameters
    ----------
    fp : filelike object
    d : dict
        This has the appropriate entries for writing its string
        representation to the header of the file.
    rNrnrorrrÚwrite_array_header_2_0Ôs rqcCst|d|dS)a²
    Read an array header from a filelike object using the 1.0 file format
    version.
 
    This will leave the file object located just after the header.
 
    Parameters
    ----------
    fp : filelike object
        A file object or something with a `.read()` method like a file.
 
    Returns
    -------
    shape : tuple of int
        The shape of the array.
    fortran_order : bool
        The array data will be written out directly if it is either
        C-contiguous or Fortran-contiguous. Otherwise, it will be made
        contiguous before writing it out.
    dtype : dtype
        The dtype of the file's data.
    max_header_size : int, optional
        Maximum allowed size of the header.  Large headers may not be safe
        to load securely and thus require explicitly passing a larger value.
        See :py:meth:`ast.literal_eval()` for details.
 
    Raises
    ------
    ValueError
        If the data is invalid.
 
    r©rÚmax_header_size©Ú_read_array_header©r#rsrrrÚread_array_header_1_0ãs
!ÿrwcCst|d|dS)aÏ
    Read an array header from a filelike object using the 2.0 file format
    version.
 
    This will leave the file object located just after the header.
 
    .. versionadded:: 1.9.0
 
    Parameters
    ----------
    fp : filelike object
        A file object or something with a `.read()` method like a file.
    max_header_size : int, optional
        Maximum allowed size of the header.  Large headers may not be safe
        to load securely and thus require explicitly passing a larger value.
        See :py:meth:`ast.literal_eval()` for details.
 
    Returns
    -------
    shape : tuple of int
        The shape of the array.
    fortran_order : bool
        The array data will be written out directly if it is either
        C-contiguous or Fortran-contiguous. Otherwise, it will be made
        contiguous before writing it out.
    dtype : dtype
        The dtype of the file's data.
 
    Raises
    ------
    ValueError
        If the data is invalid.
 
    rrrrtrvrrrÚread_array_header_2_0s
#ÿrxcCszddl}ddlm}g}d}| ||ƒj¡D]B}|d}|d}|rZ||jkrZ|dkrZq,n
| |¡||jk}q,| |¡S)a6Clean up 'L' in npz header ints.
 
    Cleans up the 'L' in strings representing integers. Needed to allow npz
    headers produced in Python2 to be read in Python3.
 
    Parameters
    ----------
    s : string
        Npy file header.
 
    Returns
    -------
    header : str
        Cleaned up header.
 
    rN)ÚStringIOFrÚL)    ÚtokenizeÚioryÚgenerate_tokensÚreadlineÚNAMErDÚNUMBERÚ
untokenize)Úsr{ryÚtokensZlast_token_was_numberÚtokenÚ
token_typeZ token_stringrrrÚ_filter_header.s  ÿþ
 r†c
Csèddl}t |¡}|dkr(td |¡ƒ‚|\}}t|| |¡dƒ}| ||¡d}t||dƒ}    |     |¡}    t    |    ƒ|krˆtdt    |    ƒ›dƒ‚|dkr˜t
|    ƒ}    z t |    ƒ}
Wn6t k
rÚ} zd    } t|  |    ¡ƒ| ‚W5d} ~ XYnXt |
tƒsød
} t|  |
¡ƒ‚t|
 ¡kr$t|
 ¡ƒ} d } t|  | ¡ƒ‚t |
d tƒrLtd d„|
d Dƒƒsbd} t|  |
d ¡ƒ‚t |
dtƒsˆd} t|  |
d¡ƒ‚zt|
dƒ}Wn<tk
rÔ} zd} t|  |
d¡ƒ| ‚W5d} ~ XYnX|
d |
d|fS)z#
    see read_array_header_1_0
    rNzInvalid version {!r}zarray header lengthz array headerzHeader info length (zä) is large and may not be safe to load securely.
To allow loading, adjust `max_header_size` or fully trust the `.npy` file using `allow_pickle=True`.
For safety against large resource use or crashes, sandboxing may be necessary.rzCannot parse header: {!r}z Header is not a dictionary: {!r}z.Header does not contain the correct keys: {!r}rcss|]}t|tƒVqdSr%)r>Úint)r'Úxrrrr+„sz%_read_array_header.<locals>.<genexpr>zshape is not valid: {!r}rz'fortran_order is not a valid bool: {!r}rz+descr is not a valid dtype descriptor: {!r})rQrSÚgetrrYr!rVÚunpackÚdecoderBr†rÚ SyntaxErrorr>ÚdictÚ EXPECTED_KEYSÚkeysrer@ÚallÚboolrAÚ    TypeError)r#rrsrQZhinfoZ hlength_typer\Z hlength_strÚ header_lengthrZrMÚerrr7rrrruQsR
 
 ÿ "
 ÿ&ruTcCst|ƒt|t|ƒ|ƒ|jdkr(d}ntd|jdƒ}|jjrr|sLtdƒ‚|dkrXi}tj    ||fddi|—Žn˜|j
j rÈ|j
j sÈt |ƒr˜|j |¡n.tj|dd    d
g|d d D]}| | d ¡¡q°nBt |ƒrÜ| |¡n.tj|dd    d
g|d d D]}| | d ¡¡qôdS)a'
    Write an array to an NPY file, including a header.
 
    If the array is neither C-contiguous nor Fortran-contiguous AND the
    file_like object is not a real file object, this function will have to
    copy data in memory.
 
    Parameters
    ----------
    fp : file_like object
        An open, writable file object, or similar object with a
        ``.write()`` method.
    array : ndarray
        The array to write to disk.
    version : (int, int) or None, optional
        The version number of the format. None means use the oldest
        supported version that is able to store the data.  Default: None
    allow_pickle : bool, optional
        Whether to allow writing pickled data. Default: True
    pickle_kwargs : dict, optional
        Additional keyword arguments to pass to pickle.dump, excluding
        'protocol'. These are only useful when pickling objects in object
        arrays on Python 3 to Python 2 compatible format.
 
    Raises
    ------
    ValueError
        If the array cannot be persisted. This includes the case of
        allow_pickle=False and array being an object array.
    Various other errors
        If the array contains Python objects as part of its dtype, the
        process of pickling them may raise various errors if the objects
        are not picklable.
 
    rirz5Object arrays cannot be saved when allow_pickle=FalseNÚprotocolrZ external_loopZbufferedZ zerosize_okÚF)rIÚ
buffersizeÚorderÚC)rrmrNr=Úmaxr7Ú    hasobjectrrÚdumprIrKrJrÚTZtofiler?ZnditerrjÚtobytes)r#rLrÚ allow_pickleÚ pickle_kwargsr—ÚchunkrrrÚ write_array’s<$
þ
 þ
r¢F©rsc
Cs||rd}t|ƒ}t|ƒt|||d\}}}t|ƒdkr>d}ntjj|tjd}|jr¶|sbt    dƒ‚|dkrni}zt
j |f|Ž}    Wn2t k
r²}
zt d|
fƒ|
‚W5d}
~
XYnXnÂt |ƒrÐtj|||d    }    n‚tj||d}    |jdkrRttt|jƒ} td|| ƒD]J} t| || ƒ} t| |jƒ}t||d
ƒ}tj||| d    |    | | | …<q|rr|ddd …|    _|     ¡}    n||    _|    S) a¨
    Read an array from an NPY file.
 
    Parameters
    ----------
    fp : file_like object
        If this is not a real file object, then this may take extra memory
        and time.
    allow_pickle : bool, optional
        Whether to allow writing pickled data. Default: False
 
        .. versionchanged:: 1.16.3
            Made default False in response to CVE-2019-6446.
 
    pickle_kwargs : dict
        Additional keyword arguments to pass to pickle.load. These are only
        useful when loading object arrays saved on Python 2 when using
        Python 3.
    max_header_size : int, optional
        Maximum allowed size of the header.  Large headers may not be safe
        to load securely and thus require explicitly passing a larger value.
        See :py:meth:`ast.literal_eval()` for details.
        This option is ignored when `allow_pickle` is passed.  In that case
        the file is by definition trusted and the limit is unnecessary.
 
    Returns
    -------
    array : ndarray
        The array from the data on disk.
 
    Raises
    ------
    ValueError
        If the data is invalid, or allow_pickle=False and the file contains
        an object array.
 
    lr£rrr6z6Object arrays cannot be loaded when allow_pickle=FalseNz]Unpickling a python object failed: %r
You may need to pass the encoding= option to numpy.load)r7Úcountz
array datard)r$rrurBr?ÚmultiplyÚreduceÚint64r›rrÚloadÚ UnicodeErrorrZfromfileZndarrayr=Ú BUFFER_SIZEÚminÚranger‡r!Z
frombufferrZ    transpose)r#rŸr rsrrrr7r¤rLÚerrZmax_read_countÚiZ
read_countÚ    read_sizeÚdatarrrÚ
read_arrayÚsT'ÿ  þþ   ÿ
r±úr+c     Cst|ƒrtdƒ‚d|kr‚t|ƒt |¡}|jr<d}t|ƒ‚tt|ƒ||d}tt    |ƒ|dƒ}    t
|    ||ƒ|      ¡}
W5QRXnXtt    |ƒdƒD}    t |    ƒ}t|ƒt |    ||d\}}}|jrÈd}t|ƒ‚|      ¡}
W5QRX|räd} nd    } |d
krôd }tj|||| ||
d } | S) a˜
    Open a .npy file as a memory-mapped array.
 
    This may be used to read an existing file or create a new one.
 
    Parameters
    ----------
    filename : str or path-like
        The name of the file on disk.  This may *not* be a file-like
        object.
    mode : str, optional
        The mode in which to open the file; the default is 'r+'.  In
        addition to the standard file modes, 'c' is also accepted to mean
        "copy on write."  See `memmap` for the available mode strings.
    dtype : data-type, optional
        The data type of the array if we are creating a new file in "write"
        mode, if not, `dtype` is ignored.  The default value is None, which
        results in a data-type of `float64`.
    shape : tuple of int
        The shape of the array if we are creating a new file in "write"
        mode, in which case this parameter is required.  Otherwise, this
        parameter is ignored and is thus optional.
    fortran_order : bool, optional
        Whether the array should be Fortran-contiguous (True) or
        C-contiguous (False, the default) if we are creating a new file in
        "write" mode.
    version : tuple of int (major, minor) or None
        If the mode is a "write" mode, then this is the version of the file
        format used to create the file.  None means use the oldest
        supported version that is able to store the data.  Default: None
    max_header_size : int, optional
        Maximum allowed size of the header.  Large headers may not be safe
        to load securely and thus require explicitly passing a larger value.
        See :py:meth:`ast.literal_eval()` for details.
 
    Returns
    -------
    marray : memmap
        The memory-mapped array.
 
    Raises
    ------
    ValueError
        If the data or the mode is invalid.
    OSError
        If the file is not found or cannot be opened correctly.
 
    See Also
    --------
    numpy.memmap
 
    zZFilename must be a string or a path-like object.  Memmap cannot use existing file handles.Úwz6Array can't be memory-mapped: Python objects in dtype.)rrrÚbÚrbr£r–r™zw+r²)r7rr˜ÚmoderE)rrrr?r7r›rr8ÚopenrrmÚtellr$ruZmemmap) Úfilenamer¶r7rrrrsrrMr#rEr˜ZmarrayrrrÚ open_memmapDsL7
ý ÿ  ÿrºúran out of datacCsˆtƒ}z:| |t|ƒ¡}||7}t|ƒdks:t|ƒ|kr>WqXWqtk
rTYqXqt|ƒ|kr€d}t|||t|ƒfƒ‚n|SdS)a+
    Read from file-like object until size bytes are read.
    Raises ValueError if not EOF is encountered before size bytes are read.
    Non-blocking objects only supported if they derive from io objects.
 
    Required as e.g. ZipExtFile in python 2.6 can return less data than
    requested.
    rz)EOF: reading %s, expected %d bytes got %dN)rÚreadrBÚBlockingIOErrorr)r#ÚsizeÚerror_templater°Úrrrrrr!¯s     r!)N)NTN)FN)r²NNFN)r»)'Ú__doc__r?r2Znumpy.lib.utilsrZ numpy.compatrrrÚ__all__rŽrrBr"rUrªrirSZ_MAX_HEADER_SIZErrr$r&r8rArNr]r`rmrprqrwrxr†rur¢r±rºr!rrrrÚ<module>sX$ 
 ý    
$8
#  $ '# A
Hÿ jÿþ k