L iwpdZddlZddlZddlZddlZddlmZddlmZddl m Z m Z m Z m Z mZmZmZmZmZmZmZddlmZmZmZddlmZmZmZmZmZmZm Z m!Z!ed eed eed e ed eed eededZ"Gdde#Z$GddeZ%GddeZ&ddZ'ddZ(dZ)ddZ*y)zFUtilities for fast persistence of big data, with optional compression.N)Path) make_memmap) _COMPRESSORSLZ4_NOT_INSTALLED_ERRORBinaryZlibFileBZ2CompressorWrapperGzipCompressorWrapperLZ4CompressorWrapperLZMACompressorWrapperXZCompressorWrapperZlibCompressorWrapperlz4register_compressor)NDArrayWrapperZNDArrayWrapperload_compatibility) BUFFER_SIZEPickler Unpickler_ensure_native_byte_order _read_bytes _reconstruct_validate_fileobject_and_memmap_write_fileobjectzlibgzipbz2lzmaxzrc:eZdZdZdefdZdZdZdZdZ dZ y ) NumpyArrayWrapperapAn object to be persisted instead of numpy arrays. This object is used to hack into the pickle machinery and read numpy array data from our custom persistence format. More precisely, this object is used for: * carrying the information of the persisted array: subclass, shape, order, dtype. Those ndarray metadata are used to correctly reconstruct the array with low level numpy functions. * determining if memmap is allowed on the array. * reading the array bytes from a file. * reading the array using memorymap from a file. * writing the array bytes to a file. Attributes ---------- subclass: numpy.ndarray subclass Determine the subclass of the wrapped array. shape: numpy.ndarray shape Determine the shape of the wrapped array. order: {'C', 'F'} Determine the order of wrapped array data. 'C' is for C order, 'F' is for fortran order. dtype: numpy.ndarray dtype Determine the data type of the wrapped array. allow_mmap: bool Determine if memory mapping is allowed on the wrapped array. Default: False. FcX||_||_||_||_||_||_y)z4Constructor. Store the useful information for later.N)subclassshapeorderdtype allow_mmapnumpy_array_alignment_bytes)selfr%r&r'r(r)r*s Y/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/joblib/numpy_pickle.py__init__zNumpyArrayWrapper.__init__^s2!    $,G(ct|ddS)Nr*)getattr)r+s r,$safe_get_numpy_array_alignment_bytesz6NumpyArrayWrapper.safe_get_numpy_array_alignment_bytesrst:DAAr.c~td|jzd}|jjr#t j ||j dy|j}||j j}|dz}|||zz }tj|dd}|j j||dk7r d |z} |j j| |jj|gd ||j D],} |j j| jd .y) zWrite array bytes to pickler file handle. This function is an adaptation of the numpy write_array function available in version 1.10.1 in numpy/lib/format.py. irprotocolNlittle)length byteorderr) external_loopbuffered zerosize_ok)flags buffersizer'C)maxitemsizer( hasobjectpickledump file_handler1tellintto_byteswritenpnditerr'tobytes) r+arraypicklerr>r* current_pospos_after_padding_bytepadding_lengthpadding_length_bytepaddingchunks r, write_arrayzNumpyArrayWrapper.write_arrayws07; ;;  KKw22Q ?*.*S*S*U '*6%11668 )4q&!<*-HH" '*ll"1'3'###))*=>!Q&%6G''--g6 **B%jj + > ##))%--*<=  >r.ct|jdk(rd}nW|jDcgc]}|jj|}}|jjj |}|j jr!tj|j}n|j}|R|jjd}tj|d} | dk7r|jj| tt!t|j j"z} |jj%||j }t'd|| D]y} t!| || z } t| |j j"z} t)|j| d}|jj+||j | || | | z~{|j,d k(r(|jddd |_|j/}n|j|_|r t1|}|Scc}w) zRead array from unpickler file handle. This function is an adaptation of the numpy read_array function available in version 1.10.1 in numpy/lib/format.py. rrNr6r8)r(z array data)r(countF)lenr&rJint64multiplyreducer(rBrCloadrEr1readrG from_bytesrminrAemptyranger frombufferr' transposer)r+ unpicklerensure_native_byte_orderrXx shape_int64rMr* padding_byterQmax_read_counti read_count read_sizedatas r, read_arrayzNumpyArrayWrapper.read_arrays tzz?a E;?**EQ9<<--a0EKELL))00=E ::  KK 5 56E*.*S*S*U '*6(4499!< !$ !Q!Q&))..~>)C TZZ=P=P,QQNLL&&uDJJ&?E1e^4  ;  TZZ-@-@ @A "9#8#8)\R,5LL,C,C *-D-a!j.) zzS "jj2. )"jj #-e4E WFs"IcX|jj}|}|j}|:|jjd}tj |d}||dzz }|j dk(rd|_t|j|j|j|j|j |}|jj||jz|>|tzdk7r2d|d |jjd }t!j"||S) z!Read an array using numpy memmap.rr6rWzw+zr+)r(r&r'modeoffsetrzThe memmapped array z loaded from the file a is not byte aligned. This may cause segmentation faults if this memmapped array is used in some libraries like BLAS or PyTorch. To get rid of this warning, regenerate your pickle file with joblib >= 1.2.0. See https://github.com/joblib/joblib/issues/563 for more details)rErFr1r`rGra mmap_moderfilenamer(r&r'seeknbytesNUMPY_ARRAY_ALIGNMENT_BYTESnamewarningswarn) r+rgrOrtr*rkrQmarraymessages r, read_mmapzNumpyArrayWrapper.read_mmaps&++002 &*&O&O&Q# & 2$0055a8L ^^LH^MN nq( (F   $ &"&I    ******$$   ""6FMM#9: ( /99Q>'vh.D((--./##  MM' " r.ch|j'|jr|rJd|j|}n|j||}t |dr`|j |j j|j jfvr(t|j dd}|j|S|S)aRead the array corresponding to this wrapper. Use the unpickler to get all information to correctly read the array. Parameters ---------- unpickler: NumpyUnpickler ensure_native_byte_order: bool If true, coerce the array to use the native endianness of the host system. Returns ------- array: numpy.ndarray zNMemmaps cannot be coerced to a given byte order, this code path is impossible.__array_prepare__)rb) rur)rrqhasattrr%rJndarraymemmaprr)r+rgrhrM new_arrays r,r`zNumpyArrayWrapper.reads$    *t/ 0 /NN9-EOOI/GHE 5- .4== LL LL  I 4 %T]]D#>I..u5 5Lr.N) __name__ __module__ __qualname____doc__ryr-r1rUrqrr`r.r,r#r#@s3F$?G(B &>P6p*X$r.r#cXeZdZdZej j ZddZdZdZ y) NumpyPickleraA pickler to persist big data efficiently. The main features of this object are: * persistence of numpy arrays in a single file. * optional compression with a special care on avoiding memory copies. Attributes ---------- fp: file File object handle used for serializing the input object. protocol: int, optional Pickle protocol used. Default is pickle.DEFAULT_PROTOCOL. Nc||_t|jt|_|tj }t j||j| ddl}||_ y#t$r d}Y||_ ywxYw)Nr4r) rE isinstancerr;rCDEFAULT_PROTOCOLrr-numpy ImportErrorrJ)r+fpr5rJs r,r-zNumpyPickler.__init__?sw"4#3#3^D   ..Ht//(C   B sA(( A=<A=c|jjr|jjsdnd}|j xr|jj }i} |j jtt||j||jfd|i|}|S#tj$rddi}YIwxYw)z=B>c |jt||jj|jj|jjfvrt||jjur|jj |}|j |}tj|||jdk\r|jjd|j||ytj||S)aSubclass the Pickler `save` method. This is a total abuse of the Pickler class in order to use the numpy persistence function `save` instead of the default pickle implementation. The numpy array is replaced by a custom wrapper in the pickle persistence stack and the serialized array is written right after in the file. Warning: the file produced does not follow the pickle format. As such it can not be read with `pickle.load`. NT)force) rJrrmatrixr asanyarrayrrsaveprotoframer commit_framerU)r+objrs r,rzNumpyPickler.savehs 77 49 GGOO GGNN GGNN1 $ CyDGGNN*gg((-005G LLw 'zzQ ((t(4   T * ||D#&&r.N) rrrrrdispatchcopyr-rrrr.r,rr.s, $$&H"0#'r.rcveZdZdZej j ZddZdZeee jd<y)NumpyUnpickleraZA subclass of the Unpickler to unpickle our numpy pickles. Attributes ---------- mmap_mode: str The memorymap mode to use for reading numpy arrays. file_handle: file_like File object to unpickle from. ensure_native_byte_order: bool If True, coerce the array to use the native endianness of the host system. filename: str Name of the file to unpickle from. It should correspond to file_handle. This parameter is required when using mmap_mode. np: module Reference to numpy module if numpy is installed else None. Nctjj||_||_||_||_d|_||_tj||j  ddl }||_ y#t$r d}Y||_ ywxYw)NFr)ospathdirname_dirnamerurErv compat_moderhrr-rrrJ)r+rvrErhrurJs r,r-zNumpyUnpickler.__init__s1 "&   (@%4!1!12   B s)A55 B  B ctj|t|jdtt fr|j td|jj}t|trd|_ |j|}n|j||j}|jj|yy)aOCalled to set the state of a newly created object. We capture it to replace our place-holder objects, NDArrayWrapper or NumpyArrayWrapper, by the array we are interested in. We replace them directly in the stack of pickler. NDArrayWrapper is used for backward compatibility with joblib <= 0.9. rZNz@Trying to unpickle an ndarray, but numpy didn't import correctlyT) r load_buildrstackrr#rJrpoprr`rhappend)r+ array_wrapper_array_payloads r,rzNumpyUnpickler.load_builds T" djjn~7H&I Jww!V!JJNN,M-8#' !.!3!3D!9!.!3!3D$:W:W!X JJ  n - Kr.rr) rrrrrrrr-rrCBUILDrr.r,rrs;&!!&&(H$.:!+HV\\!_r.rc tt|tr t|}t|t}t|d}d}|durd}nYt|tr.t |dk7rt dj||\}}nt|tr |}d}||f}n|}|dk(rtt t|>|dur:|td vr-t d j|ttd |tvrt d j|t|s|st d |d t|d|r[t|tsKd}tjD]#\}} |j| j s"|}%|tvr|dk(rd}|dk7r5t#|||f5} t%| |j'|dddnP|r2t)|d5} t%| |j'|dddnt%||j'||ry|gS#1swYxYw#1swYxYw)aPersist an arbitrary Python object into one file. Read more in the :ref:`User Guide `. Parameters ---------- value: any Python object The object to store to disk. filename: str, pathlib.Path, or file object. The file object or path of the file in which it is to be stored. The compression method corresponding to one of the supported filename extensions ('.z', '.gz', '.bz2', '.xz' or '.lzma') will be used automatically. compress: int from 0 to 9 or bool or 2-tuple, optional Optional compression level for the data. 0 or False is no compression. Higher value means more compression, but also slower read and write times. Using a value of 3 is often a good compromise. See the notes for more details. If compress is True, the compression level used is 3. If compress is a 2-tuple, the first element must correspond to a string between supported compressors (e.g 'zlib', 'gzip', 'bz2', 'lzma' 'xz'), the second element must be an integer from 0 to 9, corresponding to the compression level. protocol: int, optional Pickle protocol, see pickle.dump documentation for more details. Returns ------- filenames: list of strings The list of file names in which the data is stored. If compress is false, each array is stored in a different file. See Also -------- joblib.load : corresponding loader Notes ----- Memmapping on load cannot be used for compressed files. Thus using compression can significantly slow down loading. In addition, compressed files take up extra memory during dump and load. NrIrTzkCompress argument tuple should contain exactly 2 elements: (compress method, compress level), you passed {}rF z=Non valid compress level given: "{}". Possible values are {}.zANon valid compression method given: "{}". Possible values are {}.z C  :h6  , 2 2 4 ' D*  !5!56"& ' l *~/B"N  @  ;  X . 3 3E : ; ;  (D ! ;Q X . 3 3E : ; ; X166u= :! ; ;  ; ;s1H-%H9-H69Ict||||}d} |j}|jrtjd|zt d|S#t $r}td}||_|d}~wwxYw)zInternal unpickling function.)ruNzjThe file '%s' has been generated with a joblib version less than 0.10. Please regenerate this pickle file.) stacklevelzyYou may be trying to read with python 3 a joblib pickle generated with python 2. This feature is not supported by joblib.) rr_rr{r|DeprecationWarningUnicodeDecodeErrorr __cause__)fobjrhrvrurgrexcnew_excs r, _unpickleres$0II Cnn  MM68@A#   J  7    s;A A2A--A2c ddlm}m}t|d5}t |||5\}}t |d||}dddddd|j j|r|||S#1swY8xYw#1swY`. WARNING: joblib.load relies on the pickle module and can therefore execute arbitrary Python code. It should therefore never be used to load files from untrusted sources. Parameters ---------- filename: str, pathlib.Path, or file object. The file object or path of the file from which to load the object mmap_mode: {None, 'r+', 'r', 'w+', 'c'}, optional If not None, the arrays are memory-mapped from the disk. This mode has no effect for compressed files. Note that in this case the reconstructed object might no longer match exactly the originally pickled object. ensure_native_byte_order: bool, or 'auto', default=='auto' If True, ensures that the byte order of the loaded arrays matches the native byte ordering (or _endianness_) of the host system. This is not compatible with memory-mapped arrays and using non-null `mmap_mode` parameter at the same time will raise an error. The default 'auto' parameter is equivalent to True if `mmap_mode` is None, else False. Returns ------- result: any Python object The object stored in the file. See Also -------- joblib.dump : function to save an object Notes ----- This function can load numpy array files saved separately during the dump. If the mmap_mode argument is given, it is passed to np.load and arrays are loaded as memmaps. As a consequence, the reconstructed object might not match the original pickled object. Note that if the file was saved with compression, the arrays cannot be memmapped. autoNzfNative byte ordering can only be enforced if 'mmap_mode' parameter is set to None, but got 'mmap_mode=z ' instead.r`rz)rhrr) rrrrrr0rrrr)rvrurhr_rrrs r,r_r_sPV 6)#,#4 I$9 22;J H   Jx6x=x 4, ,T8Y G U9DRSD;STC U0 J+(D ! Q0HiH M#dC(.d3     -E%1   * J1 U0 J)   * Js<&C- DC:9 D C:D-C7:D ?DD)rN)rN)Nr)+rrrrCr{pathlibr backportsrrrrrr r r r r rrrnumpy_pickle_compatrrrnumpy_pickle_utilsrrrrrrrrryobjectr#rrrDrrr_rr.r,rsL  "        F134F134E/12F134D-/0E/12!gg\]'7]'@E+YE+XHVD6Rr.