3
QfX                 @   s  d Z ddlm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yddl	Z
W n ek
rh   ddl
Z
Y nX 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mZmZ ddlmZmZ ddlmZ dd	lmZmZm Z  dd
lm!Z! ddl"m#Z#m$Z$ ddl%m&Z& dZ'dd Z(G dd de)Z*dd Z+dd Z,d"ddZ-ej. Z/G dd deZ0G dd de1Z2G dd de1Z3G dd deZ4G d d! d!eZ5dS )#zo
A context object for caching a function's return value each time it
is called with the same input arguments.

    )with_statementN   )hashing)get_func_codeget_func_namefilter_args)format_signatureformat_call)open_py_source)Loggerformat_timepformat)numpy_pickle)mkdirp
rm_subdirs)_basestringz# first line:c             C   sL   | j tr@| jd} t| d ttd }dj| dd } nd}| |fS )zZ Extract the first line information from the function code
        text if available.
    
r   Nr   )
startswithFIRST_LINE_TEXTsplitintlenjoin)	func_code
first_line r   T/home/psgendb/BIRCHDEV/pkg/SPAdes-3.15.4/linux-x86_64/share/spades/joblib3/memory.pyextract_first_line8   s    

r   c               @   s   e Zd ZdZdS )JobLibCollisionWarningzF Warn that there might be a collision between names of functions.
    N)__name__
__module____qualname____doc__r   r   r   r   r   E   s   r   c             C   s"   t | \}}|j| tjj| S )ziCompute the part of part associated with a function.

    See code of_cache_key_to_dir() for details
    )r   appendospathr   )funcmodulesfuncnamer   r   r   _get_func_fullnameJ   s    
r*   c             C   sH   | g}t |tr|j| n|jt| |dk	r<|j| tjj| S )zCompute directory associated with a given cache key.

    func can be a function or a string as returned by _get_func_fullname().
    N)
isinstancer   r$   r*   r%   r&   r   )cachedirr'   argument_hashpartsr   r   r   _cache_key_to_dirT   s    

r/   c       
      C   s   |dkrd}yJ|dk	rHdj dd |d j D }dtjj||f }ntjj|}W n tk
rj   Y nX |dk	rd	ttj |  }nd}|d
k rtd|t	|f  ntd|t	|| f  tjj | d}	tjj
|	std|	 tj|	|dS )zLoad output of a computation.r    Nz, c             S   s   g | ]\}}d ||f qS )z%s=%sr   ).0namevaluer   r   r   
<listcomp>k   s   z _load_output.<locals>.<listcomp>
input_argsz%s(%s)z% 16s
   z[Memory]%s: Loading %s...z[Memory]%s: Loading %s from %sz
output.pklzHNon-existing cache value (may have been cleared).
File %s does not exist)	mmap_mode)r   itemsr%   r&   basenameKeyErrorr   timeprintstrisfiler   load)

output_dir	func_name	timestampmetadatar7   verboseZ	signatureargstfilenamer   r   r   _load_outputd   s0    

rH   c               @   s:   e Zd ZdZdddZdd Zdd	 Zd
d Zdd ZdS )MemorizedResulta  Object representing a cached value.

    Attributes
    ----------
    cachedir: string
        path to root of joblib cache

    func: function or string
        function whose output is cached. The string case is intended only for
        instanciation based on the output of repr() on another instance.
        (namely eval(repr(memorized_instance)) works).

    argument_hash: string
        hash of the function arguments

    mmap_mode: {None, 'r+', 'r', 'w+', 'c'}
        The memmapping mode used when loading from cache numpy arrays. See
        numpy.load for the meaning of the different values.

    verbose: int
        verbosity level (0 means no message)

    timestamp, metadata: string
        for internal use only
    Nr   c       	      C   s   t j|  t|tr|| _n
t|| _|| _|| _|| _t	|| j|| _
|d k	rX|| _nFi | _y2ttjj| j
dd}tj|| _W d Q R X W n   Y nX | jjdd | _|| _|| _d S )Nzmetadata.jsonrbduration)r   __init__r+   r   r'   r*   r-   r,   r7   r/   _output_dirrC   openr%   r&   r   jsonr?   getrK   rD   rB   )	selfr,   r'   r-   r7   rD   rB   rC   fr   r   r   rL      s*    


zMemorizedResult.__init__c             C   s$   t | jt| j| j| j| j| jdS )z$Read value from cache and return it.)rB   rC   r7   rD   )rH   rM   r*   r'   rB   rC   r7   rD   )rQ   r   r   r   rP      s    zMemorizedResult.getc             C   s   t j| jdd dS )zClear value from cacheT)ignore_errorsN)shutilrmtreerM   )rQ   r   r   r   clear   s    zMemorizedResult.clearc             C   s   dj | jj| j| j| jdS )NzS{class_name}(cachedir="{cachedir}", func="{func}", argument_hash="{argument_hash}"))
class_namer,   r'   r-   )format	__class__r    r,   r'   r-   )rQ   r   r   r   __repr__   s
    zMemorizedResult.__repr__c             C   s   | j | j| j| jfd| jifS )Nr7   )rY   r,   r'   r-   r7   )rQ   r   r   r   
__reduce__   s    zMemorizedResult.__reduce__)Nr   NN)	r    r!   r"   r#   rL   rP   rV   rZ   r[   r   r   r   r   rI      s   
	rI   c               @   sD   e Zd ZdZdZdd Zdd Zdd	 Zd
d Zdd Z	dd Z
dS )NotMemorizedResultzxClass representing an arbitrary value.

    This class is a replacement for MemorizedResult when there is no cache.
    r3   validc             C   s   || _ d| _d S )NT)r3   r]   )rQ   r3   r   r   r   rL      s    zNotMemorizedResult.__init__c             C   s   | j r| jS tdd S )NzNo value stored.)r]   r3   r:   )rQ   r   r   r   rP      s    zNotMemorizedResult.getc             C   s   d| _ d | _d S )NF)r]   r3   )rQ   r   r   r   rV      s    zNotMemorizedResult.clearc             C   s.   | j rdj| jjt| jdS | jjd S d S )Nz{class_name}({value}))rW   r3   z with no value)r]   rX   rY   r    r   r3   )rQ   r   r   r   rZ      s
    zNotMemorizedResult.__repr__c             C   s   | j | jdS )N)r]   r3   )r]   r3   )rQ   r   r   r   __getstate__   s    zNotMemorizedResult.__getstate__c             C   s   |d | _ |d | _d S )Nr]   r3   )r]   r3   )rQ   stater   r   r   __setstate__  s    
zNotMemorizedResult.__setstate__N)r3   r]   )r    r!   r"   r#   	__slots__rL   rP   rV   rZ   r^   r`   r   r   r   r   r\      s   
r\   c               @   sB   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d ZdddZ	dS )NotMemorizedFunca  No-op object decorating a function.

    This class replaces MemorizedFunc when there is no cache. It provides an
    identical API but does not write anything on disk.

    Attributes
    ----------
    func: callable
        Original undecorated function.
    c             C   s
   || _ d S )N)r'   )rQ   r'   r   r   r   rL     s    zNotMemorizedFunc.__init__c             O   s   | j ||S )N)r'   )rQ   rE   kwargsr   r   r   __call__  s    zNotMemorizedFunc.__call__c             O   s   t | j||S )N)r\   r'   )rQ   rE   rc   r   r   r   call_and_shelve  s    z NotMemorizedFunc.call_and_shelvec             C   s   | j | jffS )N)rY   r'   )rQ   r   r   r   r[      s    zNotMemorizedFunc.__reduce__c             C   s   d| j j| jf S )Nz%s(func=%s))rY   r    r'   )rQ   r   r   r   rZ   #  s    zNotMemorizedFunc.__repr__Tc             C   s   d S )Nr   )rQ   warnr   r   r   rV   )  s    zNotMemorizedFunc.clearN)T)
r    r!   r"   r#   rL   rd   re   r[   rZ   rV   r   r   r   r   rb     s   
rb   c               @   s   e Zd ZdZd.ddZdd Zd	d
 Zdd Zdd Zdd Z	dd Z
dd Zdd ZeZd/ddZdd Zdd Zd0dd Zd1d!d"Zd#d$ Zd%d& Zd2d(d)Zd*d+ Zd,d- ZdS )3MemorizedFunca   Callable object decorating a function for caching its return value
        each time it is called.

        All values are cached on the filesystem, in a deep directory
        structure. Methods are provided to inspect the cache or clean it.

        Attributes
        ----------
        func: callable
            The original, undecorated, function.

        cachedir: string
            Path to the base cache directory of the memory context.

        ignore: list or None
            List of variable names to ignore when choosing whether to
            recompute.

        mmap_mode: {None, 'r+', 'r', 'w+', 'c'}
            The memmapping mode used when loading from cache
            numpy arrays. See numpy.load for the meaning of the different
            values.

        compress: boolean, or integer
            Whether to zip the stored data on disk. If an integer is
            given, it should be between 1 and 9, and sets the amount
            of compression. Note that compressed arrays cannot be
            read by memmapping.

        verbose: int, optional
            The verbosity flag, controls messages that are issued as
            the function is evaluated.
    NFr   c       	   
   C   s   t j|  || _|| _|dkr"g }|| _|| _|| _|| _|rV| jdk	rVtj	ddd |dkrft
j
 }|| _t| j ytj| | W n   Y nX tj|rtj j|}|jddd}tjdd	|}n|j}d
| | _dS )a{  
            Parameters
            ----------
            func: callable
                The function to decorate
            cachedir: string
                The path of the base directory to use as a data store
            ignore: list or None
                List of variable names to ignore.
            mmap_mode: {None, 'r+', 'r', 'w+', 'c'}, optional
                The memmapping mode used when loading from cache
                numpy arrays. See numpy.load for the meaning of the
                arguments.
            compress : boolean, or integer
                Whether to zip the stored data on disk. If an integer is
                given, it should be between 1 and 9, and sets the amount
                of compression. Note that compressed arrays cannot be
                read by memmapping.
            verbose: int, optional
                Verbosity flag, controls the debug messages that are issued
                as functions are evaluated. The higher, the more verbose
            timestamp: float, optional
                The reference time from which times in tracing messages
                are reported.
        Nz&Compressed results cannot be memmapped   )
stacklevelr   z

r   z.r0   zMemoized version of %s)r   rL   r7   r'   ignore_verboser,   compresswarningsrf   r;   rB   r   	functoolsupdate_wrapperinspectZ
isfunctionpydocZTextDocdocumentreplaceresubr#   )	rQ   r'   r,   rj   r7   rl   rD   rB   docr   r   r   rL   W  s4    


zMemorizedFunc.__init__c             C   sn  | j ||\}}d}| jddo*tjj|s| jdkrXt| j\}}| jd|||f  | j	||\}}| j
dk	rt|t| j| j| j
| jd}nytj }	t|t| j| j|| j
| jd}| jdkrtj |	 }
t| j\}}d|t|
f }ttd	d
t| d |  W nP tk
rb   | jd||tj f  tj|dd | j	||\}}d}Y nX |||fS )a  Call wrapped function and cache result, or read cache if available.

        This function returns the wrapped function output and some metadata.

        Returns
        -------
        output: value or tuple
            what is returned by wrapped function

        argument_hash: string
            hash of function arguments

        metadata: dict
            some metadata about wrapped function call (see _persist_input())
        N   )ri   r6   z3Computing func %s, argument hash %s in directory %s)rB   r7   rD   )rB   rC   r7   rD   z%s cache loaded - %sr   P   _z<Exception while loading results for (args=%s, kwargs=%s)
 %sT)rS   )_get_output_dir_check_previous_func_coder%   r&   existsrk   r   r'   rf   callr7   rH   r*   rB   r;   r   r<   maxr   	Exception	traceback
format_excrT   rU   )rQ   rE   rc   r@   r-   rC   ry   r2   outt0rF   msgr   r   r   _cached_call  s@    


"
zMemorizedFunc._cached_callc             O   s2   | j ||\}}}t| j| j||| jd | jdS )a\  Call wrapped function, cache result and return a reference.

        This method returns a reference to the cached result instead of the
        result itself. The reference object is small and pickeable, allowing
        to send or store it easily. Call .get() on reference object to get
        result.

        Returns
        -------
        cached_result: MemorizedResult or NotMemorizedResult
            reference to the value returned by the wrapped function. The
            class "NotMemorizedResult" is used when there is no cache
            activated (e.g. cachedir=None in Memory).
        r   )rC   rD   rB   )r   rI   r,   r'   rk   rB   )rQ   rE   rc   ry   r-   rC   r   r   r   re     s    
zMemorizedFunc.call_and_shelvec             O   s   | j ||d S )Nr   )r   )rQ   rE   rc   r   r   r   rd     s    zMemorizedFunc.__call__c             C   s"   | j | j| j| j| j| j| jffS )z We don't store the timestamp when pickling, to avoid the hash
            depending from it.
            In addition, when unpickling, we run the __init__
        )rY   r'   r,   rj   r7   rl   rk   )rQ   r   r   r   r[     s    zMemorizedFunc.__reduce__c             O   s   t jdt t| jf||S )NzMMemorizedFunc.format_signature will be removed in a future version of joblib.)rm   rf   DeprecationWarningr   r'   )rQ   rE   rc   r   r   r   r     s    zMemorizedFunc.format_signaturec             O   s   t jdt t| j||S )NzHMemorizedFunc.format_call will be removed in a future version of joblib.)rm   rf   r   r	   r'   )rQ   rE   rc   r   r   r   r	     s    zMemorizedFunc.format_callc             O   s"   t jt| j| j||| jd k	dS )N)Zcoerce_mmap)r   hashr   r'   rj   r7   )rQ   rE   rc   r   r   r   _get_argument_hash  s    z MemorizedFunc._get_argument_hashc             O   s*   | j ||}tjj| j| j|}||fS )z} Return the directory in which are persisted the result
            of the function called with the given arguments.
        )r   r%   r&   r   _get_func_dirr'   )rQ   rE   rc   r-   r@   r   r   r   rz      s    zMemorizedFunc._get_output_dirTc             C   s    t | j| jd}|rt| |S )zT Get the directory corresponding to the cache for the
            function.
        N)r/   r,   r'   r   )rQ   mkdirfunc_dirr   r   r   r     s    zMemorizedFunc._get_func_dirc             C   s(   t t| jdd}t| jt | j|fS )z'Hash a function to key the online cache__code__N)r   getattrr'   id)rQ   Zfunc_code_hr   r   r   
_hash_func  s    zMemorizedFunc._hash_funcc             C   s   dt ||f }tj|ddd}|j| W dQ R X d}tjd dkr`t| jd	o\| jjd
k}nt| jdov| jj	d
k}|r| j
 }y|t| j< W n tk
r   Y nX dS )z= Write the function code and the filename to a file.
        z%s %i
%swzUTF-8)encodingNFr   rh   r    z<lambda>rA   )r   iorN   writesysversion_infohasattrr'   r    rA   r   _FUNCTION_HASHES	TypeError)rQ   rG   r   r   r   Zis_named_callable	func_hashr   r   r   _write_func_code  s    zMemorizedFunc._write_func_coderh   c          %   C   s6  y(| j tkr&| j }|t| j  kr&dS W n tk
r<   Y nX t| j \}}}| j }tjj|d}y.t	j
|dd}t|j \}	}
W dQ R X W n" tk
r   | j||| dS X |	|krdS t| j ddd\}}|
|  kodkn  s|d	kr,|dksd
|||f }n|}tjtd| |d |
|k r|dk	rd}tjj|rt| j dd\}}t|jd}t|&}|j |
d |
d | d  }W dQ R X dj|}|j |	j k}n
|jd}|rtjtd|||
|||f |d | jdkr&t| j dd\}}| jd||f  | jdd dS )z
            stacklevel is the depth a which this function is called, to
            issue useful warnings to the user.
        Tzfunc_code.pyzUTF-8)r   NF)resolv_aliasZwin_charactersr   z<lambda>z
%s (%s:%i)z/Cannot detect name collisions for function '%s')ri   )r   r   r0   z	<doctest zHPossible name collisions between functions '%s' (%s:%i) and '%s' (%s:%i)r6   z'Function %s (stored in %s) has changed.)rf   r   r   )r'   r   r   r   r   r   r%   r&   r   r   rN   r   readIOErrorr   r   rm   rf   r   r|   r   r   r
   	readlinesrstripr   rk   rV   )rQ   ri   r   r   Zsource_filer   r   func_code_fileZinfileZold_func_codeZold_first_linery   rA   Zfunc_descriptionZpossible_collisionZ	num_linesrR   Zon_disk_func_coder   r   r   r{   9  sh    	
"

$

z'MemorizedFunc._check_previous_func_codec             C   sz   | j dd}| jdkr(|r(| jd|  tjj|rBtj|dd t| t	| j
\}}}tjj|d}| j||| dS )	z% Empty the function's cache.
        F)r   r   zClearing cache %sT)rS   zfunc_code.pyN)r   rk   rf   r%   r&   r|   rT   rU   r   r   r'   r   r   )rQ   rf   r   r   ry   r   r   r   r   r   rV     s    zMemorizedFunc.clearc             O   s   t j  }| j||\}}| jdkr4tt| j|| | j||}| j|| t j  | }| j||||}| jdkrt| j\}}	d|	t	|f }
tt
ddt|
 d |
  ||fS )zq Force the execution of the function with the given arguments and
            persist the output values.
        r   z%s - %srx   ry   )r;   rz   rk   r<   r	   r'   _persist_output_persist_inputr   r   r~   r   )rQ   rE   rc   
start_timer@   ry   outputrK   rC   r2   r   r   r   r   r}     s    

zMemorizedFunc.callc             C   s\   yBt | tjj|d}tj||| jd | jdkr@td|  W n t	k
rV   Y nX dS )z: Persist the given output tuple in the directory.
        z
output.pkl)rl   r6   zPersisting in %sN)
r   r%   r&   r   r   dumprl   rk   r<   OSError)rQ   r   dirrG   r   r   r   r     s    
zMemorizedFunc._persist_output      ?c             C   s   t j  }t| j| j||}tdd |j D }||d}	y8t| ttj	j
|dd}
tj|	|
 W dQ R X W n   Y nX t j  | }||krtjd| dd	 |	S )
a%   Save a small summary of the call using json format in the
            output directory.

            output_dir: string
                directory where to write metadata.

            duration: float
                time taken by hashing input arguments, calling the wrapped
                function and persisting its output.

            args, kwargs: list and dict
                input arguments for wrapped function

            this_duration_limit: float
                Max execution time for this function before issuing a warning.
        c             s   s   | ]\}}|t |fV  qd S )N)repr)r1   kvr   r   r   	<genexpr>  s    z/MemorizedFunc._persist_input.<locals>.<genexpr>)rK   r5   zmetadata.jsonr   Na~  Persisting input arguments took %.2fs to run.
If this happens often in your code, it can cause performance problems 
(results will be correct in all cases). 
The reason for this is probably some large input arguments for a wrapped
 function (e.g. large strings).
THIS IS A JOBLIB ISSUE. If you can, kindly provide the joblib's team with an
 example so that they can fix the problem.   )ri   )r;   r   r'   rj   dictr8   r   rN   r%   r&   r   rO   r   rm   rf   )rQ   r@   rK   rE   rc   Zthis_duration_limitr   Zargument_dictZ
input_reprrC   rR   Zthis_durationr   r   r   r     s     


zMemorizedFunc._persist_inputc             C   s*   t jdt t|t| j| j| j| jdS )ze Read the results of a previous calculation from the directory
            it was cached in.
        zMemorizedFunc.load_output is deprecated and will be removed in a future version
of joblib. A MemorizedResult provides similar features)rB   r7   rD   )	rm   rf   r   rH   r*   r'   rB   r7   rk   )rQ   r@   r   r   r   load_output  s
    zMemorizedFunc.load_outputc             C   s   d| j j| jt| jf S )Nz%s(func=%s, cachedir=%s))rY   r    r'   r   r,   )rQ   r   r   r   rZ     s    zMemorizedFunc.__repr__)NNFr   N)T)rh   )T)r   )r    r!   r"   r#   rL   r   re   rd   r[   r   r	   r   rz   Zget_output_dirr   r   r   r{   rV   r}   r   r   r   rZ   r   r   r   r   rg   1  s,   ! 
:;		
	 
X

5rg   c               @   sF   e Zd ZdZdddZdddZdd
dZdd Zdd Zdd Z	dS )Memoryz A context object for caching a function's return value each time it
        is called with the same input arguments.

        All values are cached on the filesystem, in a deep directory
        structure.

        see :ref:`memory_reference`
    NFr   c             C   sn   t j|  || _|| _tj | _|| _|r@|dk	r@tjddd |dkrPd| _	nt
jj|d| _	t| j	 dS )a  
            Parameters
            ----------
            cachedir: string or None
                The path of the base directory to use as a data store
                or None. If None is given, no caching is done and
                the Memory object is completely transparent.
            mmap_mode: {None, 'r+', 'r', 'w+', 'c'}, optional
                The memmapping mode used when loading from cache
                numpy arrays. See numpy.load for the meaning of the
                arguments.
            compress: boolean, or integer
                Whether to zip the stored data on disk. If an integer is
                given, it should be between 1 and 9, and sets the amount
                of compression. Note that compressed arrays cannot be
                read by memmapping.
            verbose: int, optional
                Verbosity flag, controls the debug messages that are issued
                as functions are evaluated.
        Nz&Compressed results cannot be memmappedrh   )ri   Zjoblib)r   rL   rk   r7   r;   rB   rl   rm   rf   r,   r%   r&   r   r   )rQ   r,   r7   rl   rD   r   r   r   rL     s    

zMemory.__init__c          	   C   sv   |dkrt j| j|||dS | jdkr.t|S |dkr<| j}|dkrJ| j}t|trZ|j	}t|| j||| j
|| jdS )a{   Decorates the given function func to only compute its return
            value for input arguments not cached on disk.

            Parameters
            ----------
            func: callable, optional
                The function to be decorated
            ignore: list of strings
                A list of arguments name to ignore in the hashing
            verbose: integer, optional
                The verbosity mode of the function. By default that
                of the memory object is used.
            mmap_mode: {None, 'r+', 'r', 'w+', 'c'}, optional
                The memmapping mode used when loading from cache
                numpy arrays. See numpy.load for the meaning of the
                arguments. By default that of the memory object is used.

            Returns
            -------
            decorated_func: MemorizedFunc object
                The returned object is a MemorizedFunc object, that is
                callable (behaves like a function), but offers extra
                methods for cache lookup and management. See the
                documentation for :class:`joblib.memory.MemorizedFunc`.
        N)rj   rD   r7   F)r,   r7   rj   rl   rD   rB   )rn   partialcacher,   rb   rk   r7   r+   rg   r'   rl   rB   )rQ   r'   rj   rD   r7   r   r   r   r   C  s"    



zMemory.cacheTc             C   s&   |r| j d | jdk	r"t| j dS )z- Erase the complete cache directory.
        zFlushing completely the cacheN)rf   r,   r   )rQ   rf   r   r   r   rV   r  s    

zMemory.clearc             O   s$   | j dkr|||S | j|||S )a   Eval function func with arguments `*args` and `**kwargs`,
            in the context of the memory.

            This method works similarly to the builtin `apply`, except
            that the function is called only if the cache is not
            up to date.

        N)r,   r   )rQ   r'   rE   rc   r   r   r   evalz  s    	

zMemory.evalc             C   s   d| j jt| jf S )Nz%s(cachedir=%s))rY   r    r   r,   )rQ   r   r   r   rZ     s    zMemory.__repr__c             C   s4   | j dk	r| j dd nd}| j|| j| j| jffS )z We don't store the timestamp when pickling, to avoid the hash
            depending from it.
            In addition, when unpickling, we run the __init__
        N   i)r,   rY   r7   rl   rk   )rQ   r,   r   r   r   r[     s    zMemory.__reduce__)NFr   )NNNF)T)
r    r!   r"   r#   rL   r   rV   r   rZ   r[   r   r   r   r   r     s   
$ 
.
r   )NNNr   )6r#   Z
__future__r   r%   rT   r;   rq   rt   r   ZcPicklepickleImportErrorrn   r   rm   rp   rO   weakrefr   r0   r   Zfunc_inspectr   r   r   r   r	   Z_memory_helpersr
   loggerr   r   r   r   Zdiskr   r   Z_compatr   r   r   UserWarningr   r*   r/   rH   WeakKeyDictionaryr   rI   objectr\   rb   rg   r   r   r   r   r   <module>   sT   
 
%Q*&   d