3
QfXD                 @   s6  d Z ddlZddlZddlZddlZddlZddlZddlZddlZddl	m
Z
 ddlmZ ejd dkZerejZejZdd ZnejZejZeZd	d
 Zd$ZedZeed%Zdd Zdd Zd&ddZG dd deZG dd deZG dd deZ G dd deZ!G dd de!Z"d'd d!Z#d(d"d#Z$dS ))zH
Utilities for fast persistence of big data, with optional compression.
    N   )_basestring)BytesIO   c             C   s   t | tr| S | jdS )Nlatin1)
isinstancebytesencode)s r   Z/home/psgendb/BIRCHDEV/pkg/SPAdes-3.15.4/linux-x86_64/share/spades/joblib3/numpy_pickle.pyasbytes   s    
r   c             C   s
   dj | S )z-Converts an int to an hexadecimal string
    z{0:#x})format)Zan_intr   r   r   hex_str&   s    r         ZZF@   c             C   s   | j tt}| jd |S )zV Utility to check the magic signature of a file identifying it as a
        Zfile
    r   )readlen_ZFILE_PREFIXseek)file_handlemagicr   r   r   _read_magic8   s    
r   c             C   s   | j d t| tkstdttt }| j|}|ttd }t|d}| jd}|dkrj| j | tj	| j d|}t||kstd|  |S )	zRead the z-file and return the content as a string

    Z-files are raw data compressed with zlib used internally by joblib
    for persistence. Backward compatibility is not guaranteed. Do not
    use for external purposes.
    r   z"File does not have the right magicN   r          zIIncorrect data length while decompressing %s.The file could be corrupted.)
r   r   r   AssertionErrorr   _MAX_LENr   intzlib
decompress)r   Zheader_lengthlengthZ	next_bytedatar   r   r   
read_zfileB   s    




r$   c             C   sD   | j t tt|}| j t|jt | j tjt|| dS )zWrite the data in the given file as a Z-file.

    Z-files are raw data compressed with zlib used internally by joblib
    for persistence. Backward compatibility is not guarantied. Do not
    use for external purposes.
    N)	writer   r   r   r   ljustr   r    compress)r   r#   r'   r"   r   r   r   write_zfilee   s    
r(   c               @   s"   e Zd ZdZdddZdd ZdS )	NDArrayWrapperz An object to be persisted instead of numpy arrays.

        The only thing this object does, is to carry the filename in which
        the array has been persisted, and the array subclass.
    Tc             C   s   || _ || _|| _dS )z&Store the useful information for laterN)filenamesubclass
allow_mmap)selfr*   r+   r,   r   r   r   __init__|   s    zNDArrayWrapper.__init__c             C   s   t jj|j| j}dd |jjjdddd D }t| dd}|sHi nd|j	i}|jj
|f|}t|d	r| j|jj|jjfkr|jjjj| jdd}|j| |}|S )zReconstruct the arrayc             S   s   g | ]}t |qS r   )r   ).0xr   r   r   
<listcomp>   s    z'NDArrayWrapper.read.<locals>.<listcomp>.r   Nr,   T	mmap_mode__array_prepare__r   b)r   )ospathjoin_dirnamer*   np__version__splitgetattrr3   loadhasattrr+   ndarraymemmapcore
multiarray_reconstructr4   )r-   	unpicklerr*   Znp_verr,   Zmemmap_kwargsarrayZ	new_arrayr   r   r   r      s    "




zNDArrayWrapper.readN)T)__name__
__module____qualname____doc__r.   r   r   r   r   r   r)   v   s   
r)   c               @   s    e Zd ZdZdd Zdd ZdS )ZNDArrayWrapperaV  An object to be persisted instead of numpy arrays.

    This object store the Zfile filename in which
    the data array has been persisted, and the meta information to
    retrieve it.

    The reason that we store the raw buffer data of the array and
    the meta information, rather than array representation routine
    (tostring) is that it enables us to use completely the strided
    model to avoid memory copies (a and a.T store as fast). In
    addition saving the heavy information separately can avoid
    creating large temporary buffers when unpickling data with
    large arrays.
    c             C   s   || _ || _|| _dS )z&Store the useful information for laterN)r*   state	init_args)r-   r*   rM   rL   r   r   r   r.      s    zZNDArrayWrapper.__init__c          	   C   s\   t jj|j| j}|jjjj| j	 }t
|d}t|}W dQ R X | j|f }|j| |S )z>Reconstruct the array from the meta-information and the z-filerbN)r6   r7   r8   r9   r*   r:   rB   rC   rD   rM   openr$   rL   __setstate__)r-   rE   r*   rF   fr#   rL   r   r   r   r      s    
zZNDArrayWrapper.readN)rG   rH   rI   rJ   r.   r   r   r   r   r   rK      s   rK   c               @   s<   e Zd ZdZejj ZdddZdd Zd	d
 Z	dd Z
dS )NumpyPicklera%  A pickler to persist of big data efficiently.

        The main features of this object are:

         * persistence of numpy arrays in separate .npy files, for which
           I/O is fast.

         * optional compression using Zlib, with a special care on avoid
           temporaries.
    r   
   Nc             C   s   || _ |g| _|| _|| _| js.t|d| _nt | _d| _|d krTtrNt	j
nt	j}tj| | j|d ydd l}W n tk
r   d }Y nX || _d S )Nwbr   )protocol)	_filename
_filenames
cache_sizer'   rO   filer   _npy_counterPY3pickleDEFAULT_PROTOCOLHIGHEST_PROTOCOLPicklerr.   numpyImportErrorr:   )r-   r*   r'   rX   rU   r:   r   r   r   r.      s$    


zNumpyPickler.__init__c       	      C   s   | j s:| jj|| |jj }ttjj|t	||d}n`|d7 }|j
 \}}}t|d}t||d | j d W d Q R X |d d }ttjj|||}||fS )N)r,   z.zrT   r   )r'   rb   )r'   r:   savedtype	hasobjectr)   r6   r7   basenametype
__reduce__rO   r(   rK   )	r-   rF   r*   r,   	container_rM   rL   zfiler   r   r   _write_array   s    

zNumpyPickler._write_arrayc          
   C   s   | j dk	rt|| j j| j j| j jfkr|j|j }| jrp|| jt	 k rpt|| j jkrd| j j
|}tj| |S |  jd7  _y0d| j| jf }| j||\}}| jj| W n2   |  jd8  _tdt|tj f  Y nX tj| |S )z Subclass the save method, to save ndarray subclasses in npy
            files, rather than pickling them. Of course, this is a
            total abuse of the Pickler class.
        Nr   z%s_%02i.npyz"Failed to save %s to .npy file:
%s)r:   rg   r@   ZmatrixrA   sizeitemsizer'   rX   _MEGAZasarrayr_   rc   rZ   rV   rl   rW   appendprint	traceback
format_exc)r-   objrm   r*   r   r   r   rc      s&    
zNumpyPickler.savec             C   s6   | j r2t| jd}t|| jj | j  W d Q R X d S )NrT   )r'   rO   rV   r(   rY   getvalue)r-   rk   r   r   r   close  s    zNumpyPickler.close)r   rS   N)rG   rH   rI   rJ   r_   dispatchcopyr.   rl   rc   rv   r   r   r   r   rR      s   


rR   c               @   sR   e Zd ZdZejj Zd
ddZdd Zdd Z	e
rDe	eejd	 < n
e	eej< dS )NumpyUnpicklerz?A subclass of the Unpickler to unpickle our numpy pickles.
    Nc             C   sl   t jj|| _t jj|| _|| _| j|| _t	j
| | j ydd l}W n tk
r`   d }Y nX || _d S )Nr   )r6   r7   rf   rV   dirnamer9   r3   _open_pickler   	Unpicklerr.   r`   ra   r:   )r-   r*   r   r3   r:   r   r   r   r.   (  s    
zNumpyUnpickler.__init__c             C   s   |S )Nr   )r-   r   r   r   r   r{   4  s    zNumpyUnpickler._open_picklec             C   sP   t j|  t| jd trL| jdkr,td| jj }|j| }| jj	| dS )a   This method is called to set the state of a newly created
            object.

            We capture it to replace our place-holder objects,
            NDArrayWrapper, by the array we are interested in. We
            replace them directly in the stack of pickler.
        r   Nz@Trying to unpickle an ndarray, but numpy didn't import correctlyrb   )
r|   
load_buildr   stackr)   r:   ra   popr   rp   )r-   Znd_array_wrapperrF   r   r   r   r}   7  s    



zNumpyUnpickler.load_buildr   )N)rG   rH   rI   rJ   r|   rw   rx   r.   r{   r}   r[   r\   BUILDr   r   r   r   ry   #  s   

ry   c               @   s    e Zd ZdZdd Zdd ZdS )ZipNumpyUnpicklerzOA subclass of our Unpickler to unpickle on the fly from
    compressed storage.c             C   s   t j| ||d d d S )N)r3   )ry   r.   )r-   r*   r   r   r   r   r.   S  s    zZipNumpyUnpickler.__init__c             C   s   t t|S )N)r   r$   )r-   r   r   r   r   r{   X  s    zZipNumpyUnpickler._open_pickleN)rG   rH   rI   rJ   r.   r{   r   r   r   r   r   O  s   r   d   c             C   s   |dkrd}t |ts*td|t|f z&t||||d}|j|  |j  W ddt krzt|drz|j	j
  |j	j  X |jS )a  Fast persistence of an arbitrary Python object into one or multiple
    files, with dedicated storage for numpy arrays.

    Parameters
    -----------
    value: any Python object
        The object to store to disk
    filename: string
        The name of the file in which it is to be stored
    compress: integer for 0 to 9, optional
        Optional compression level for the data. 0 is no compression.
        Higher 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.
    cache_size: positive number, optional
        Fixes the order of magnitude (in megabytes) of the cache used
        for in-memory compression. Note that this is just an order of
        magnitude estimate and that for big arrays, the code will go
        over this value at dump and at load time.
    protocol: positive int
        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 extra extra memory during
    dump and load.
    Tr   z<Second argument should be a filename, %s (type %s) was given)r'   rX   rU   NpicklerrY   )r   r   
ValueErrorrg   rR   dumprv   localsr?   rY   flushrW   )valuer*   r'   rX   rU   r   r   r   r   r   _  s    (



r   c             C   s   t | d}t|tkrD|dk	r6tjdt  tdd t| |d}nt| ||d}zJy|j	 }W n8 t
k
r } ztrtd}||_|W Y dd}~X nX W dt|d	r|jj  X |S Q R X dS )
a  Reconstruct a Python object from a file persisted with joblib.dump.

    Parameters
    -----------
    filename: string
        The name 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 not longer match exactly
        the originally pickled object.

    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 memmaped.
    rN   NzWfile "%(filename)s" appears to be a zip, ignoring mmap_mode "%(mmap_mode)s" flag passedr   )
stacklevel)r   )r   r3   zyYou may be trying to read with python 3 a joblib pickle generated with python 2. This feature is not supported by joblib.r   )rO   r   r   warningswarnr   Warningr   ry   r>   UnicodeDecodeErrorr[   r   	__cause__r?   r   rv   )r*   r3   r   rE   rt   excnew_excr   r   r   r>     s&    
r>   i   l            )r   )r   r   N)N)%rJ   r\   rr   sysr6   r    r   structcodecs_compatr   ior   version_infor[   
_Unpicklerr|   _Picklerr_   r   strr   ro   r   r   r   r   r$   r(   objectr)   rK   rR   ry   r   r   r>   r   r   r   r   <module>   s@   

#
(%`,
@