Your IP : 216.73.216.85


Current Path : /opt/alt/python35/lib/python3.5/site-packages/joblib/__pycache__/
Upload File :
Current File : //opt/alt/python35/lib/python3.5/site-packages/joblib/__pycache__/memory.cpython-35.opt-1.pyc



��X��@scdZddlmZddlZddlZddlZddlZddlZddlZyddl	Z
Wnek
r�ddl
Z
YnXddlZddl
Z
ddlZddlZddlZddlZddlZddlmZddlmZmZmZddlmZmZddlmZdd	lmZmZm Z dd
lm!Z!ddl"m#Z#m$Z$ddl%m&Z&m'Z'd
Z(dd�Z)Gdd�de*�Z+dd�Z,dd�Z-dddddd�Z.ej/�Z0Gdd�de�Z1Gdd�de2�Z3Gdd�de2�Z4Gdd�de�Z5Gd d!�d!e�Z6dS)"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)�_basestring�PY3_OR_LATERz
# first line:cCsj|jt�rZ|jd�}t|dtt�d��}dj|dd��}nd}||fS)zZ Extract the first line information from the function code
        text if available.
    �
rNr���)�
startswith�FIRST_LINE_TEXT�split�int�len�join)�	func_code�
first_line�r�>/opt/alt/python35/lib/python3.5/site-packages/joblib/memory.py�extract_first_line8s rc@seZdZdZdS)�JobLibCollisionWarningzF Warn that there might be a collision between names of functions.
    N)�__name__�
__module__�__qualname__�__doc__rrrrr Esr cCs/t|�\}}|j|�tjj|�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�funcnamerrr�_get_func_fullnameJs
r+cCsd|g}t|t�r(|j|�n|jt|��|dk	rT|j|�tjj|�S)z�Compute directory associated with a given cache key.

    func can be a function or a string as returned by _get_func_fullname().
    N)�
isinstancerr%r+r&r'r)�cachedirr(�
argument_hash�partsrrr�_cache_key_to_dirTs	
r0c

CsM|dkrd}yg|dk	rfdjdd�|dj�D��}dtjj|�|f}ntjj|�}Wntk
r�YnX|dk	r�d	ttj�|�}nd}|d
kr�td|t	|�f�ntd|t	|�|f�tjj|d
�}	tjj
|	�s:td|	��tj|	d|�S)zLoad output of a computation.r�Nz, cSs&g|]\}}d||f�qS)z%s=%sr)�.0�name�valuerrr�
<listcomp>ks	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�metadatar8�verboseZ	signature�args�t�filenamerrr�_load_outputds0


rIc@s^eZdZdZdddddd�Zdd�Zdd	�Zd
d�Zdd
�ZdS)�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
    Nrc	Cstj|�t|t�r(||_nt|�|_||_||_||_t	||j|�|_
|dk	r�||_nUi|_yAtt
jj|j
d�d��}tj|�|_WdQRXWnYnX|jjdd�|_||_||_dS)Nz
metadata.json�rb�duration)r�__init__r,rr(r+r.r-r8r0�_output_dirrD�openr&r'r�jsonr@�getrLrErC)	�selfr-r(r.r8rErCrD�frrrrM�s*
					zMemorizedResult.__init__cCs=t|jt|j�d|jd|jd|jd|j�S)z$Read value from cache and return it.rCrDr8rE)rIrNr+r(rCrDr8rE)rRrrrrQ�s	zMemorizedResult.getcCstj|jdd�dS)zClear value from cache�
ignore_errorsTN)�shutil�rmtreerN)rRrrr�clear�szMemorizedResult.clearc	Cs1djd|jjd|jd|jd|j�S)NzS{class_name}(cachedir="{cachedir}", func="{func}", argument_hash="{argument_hash}")�
class_namer-r(r.)�format�	__class__r!r-r(r.)rRrrr�__repr__�s
			zMemorizedResult.__repr__cCs+|j|j|j|jfd|jifS)Nr8)rZr-r(r.r8)rRrrr�
__reduce__�szMemorizedResult.__reduce__)	r!r"r#r$rMrQrWr[r\rrrrrJ�s	rJc@sdeZdZdZdZdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dS)�NotMemorizedResultzxClass representing an arbitrary value.

    This class is a replacement for MemorizedResult when there is no cache.
    r4�validcCs||_d|_dS)NT)r4r^)rRr4rrrrM�s	zNotMemorizedResult.__init__cCs |jr|jStd��dS)NzNo value stored.)r^r4r;)rRrrrrQ�s	zNotMemorizedResult.getcCsd|_d|_dS)NF)r^r4)rRrrrrW�s	zNotMemorizedResult.clearcCs@|jr.djd|jjdt|j��S|jjdSdS)Nz{class_name}({value})rXr4z with no value)r^rYrZr!r
r4)rRrrrr[�s
		zNotMemorizedResult.__repr__cCsd|jd|jiS)Nr^r4)r^r4)rRrrr�__getstate__szNotMemorizedResult.__getstate__cCs|d|_|d|_dS)Nr^r4)r^r4)rR�staterrr�__setstate__s
zNotMemorizedResult.__setstate__N)r4r^)r!r"r#r$�	__slots__rMrQrWr[r_rarrrrr]�s
r]c@saeZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
d�Z	dS)�NotMemorizedFuncaNo-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.
    cCs
||_dS)N)r()rRr(rrrrMszNotMemorizedFunc.__init__cOs|j||�S)N)r()rRrF�kwargsrrr�__call__szNotMemorizedFunc.__call__cOst|j||��S)N)r]r()rRrFrdrrr�call_and_shelvesz NotMemorizedFunc.call_and_shelvecCs|j|jffS)N)rZr()rRrrrr\ szNotMemorizedFunc.__reduce__cCsd|jj|jfS)Nz%s(func=%s))rZr!r()rRrrrr[#s	zNotMemorizedFunc.__repr__TcCsdS)Nr)rR�warnrrrrW)szNotMemorizedFunc.clearN)
r!r"r#r$rMrerfr\r[rWrrrrrcs
rcc@seZdZdZddddddd�Zdd�Zd	d
�Zdd�Zd
d�Zdd�Z	dd�Z
dd�Zdd�ZeZ
ddd�Zdd�Zdd�Zddd �Zdd!d"�Zd#d$�Zd%d&�Zd'd(d)�Zd*d+�Zd,d-�ZdS).�
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.
    NFrc	
Cs5tj|�||_||_|dkr1g}||_||_||_||_|r}|jdk	r}tj	ddd�|dkr�t
j
�}||_t|j�yt
j||�WnYnXtj|�rtj�j|�}|jddd�}tjdd	|�}n	|j}d
||_dS)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�
stacklevel�rz

rz.r1zMemoized version of %s)rrMr8r(�ignore�_verboser-�compress�warningsrgr<rCr�	functools�update_wrapper�inspectZ
isfunction�pydocZTextDocZdocument�replace�re�subr$)	rRr(r-rkr8rmrErC�docrrrrMWs4
							
	zMemorizedFunc.__init__cCs|j||�\}}d}|jdd�o?tjj|�s�|jdkr�t|j�\}}|jd|||f�|j	||�\}}|j
dk	r�t|t|j�d|j
d|j
d|j�}ny�tj�}	t|t|j�d|j
d	|d|j
d|j�}|jdkr�tj�|	}
t|j�\}}d
|t|
�f}ttddt|��d
|�Wnctk
r�|jd||tj�f�tj|dd�|j	||�\}}d}YnX|||fS)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())
        Nri�r7z3Computing func %s, argument hash %s in directory %srCr8rErDz%s cache loaded - %sr�P�_z<Exception while loading results for (args=%s, kwargs=%s)
 %srTT)�_get_output_dir�_check_previous_func_coder&r'�existsrlrr(rg�callr8rIr+rCr<rr=�maxr�	Exception�	traceback�
format_excrUrV)rRrFrdrAr.rDryr3�outZt0rG�msgrrr�_cached_call�s@				)
	zMemorizedFunc._cached_callc
OsM|j||�\}}}t|j|j|d|d|jdd|j�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).
        rDrErrC)r�rJr-r(rlrC)rRrFrdryr.rDrrrrf�szMemorizedFunc.call_and_shelvecOs|j||�dS)Nr)r�)rRrFrdrrrre�szMemorizedFunc.__call__cCs1|j|j|j|j|j|j|jffS)z� We don't store the timestamp when pickling, to avoid the hash
            depending from it.
            In addition, when unpickling, we run the __init__
        )rZr(r-rkr8rmrl)rRrrrr\�szMemorizedFunc.__reduce__cOs#tjdt�t|j||�S)NzMMemorizedFunc.format_signature will be removed in a future version of joblib.)rnrg�DeprecationWarningrr()rRrFrdrrrr�s	zMemorizedFunc.format_signaturecOs#tjdt�t|j||�S)NzHMemorizedFunc.format_call will be removed in a future version of joblib.)rnrgr�r	r()rRrFrdrrrr	�s	zMemorizedFunc.format_callcOs1tjt|j|j||�d|jdk	�S)NZcoerce_mmap)r�hashrr(rkr8)rRrFrdrrr�_get_argument_hash�sz MemorizedFunc._get_argument_hashcOs=|j||�}tjj|j|j�|�}||fS)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()rRrFrdr.rArrrrzs	zMemorizedFunc._get_output_dirTcCs,t|j|jd�}|r(t|�|S)zT Get the directory corresponding to the cache for the
            function.
        N)r0r-r(r)rR�mkdir�func_dirrrrr�s
zMemorizedFunc._get_func_dircCs:tt|jdd��}t|j�t|j�|fS)z'Hash a function to key the online cache�__code__N)r��getattrr(�id)rRZfunc_code_hrrr�
_hash_funcszMemorizedFunc._hash_funccCs�dt||f}tj|ddd��}|j|�WdQRXd}trut|jd�oo|jjdk}n$t|jd	�o�|jjdk}|r�|j	�}y|t
|j<Wntk
r�YnXdS)
z= Write the function code and the filename to a file.
        z%s %i
%s�w�encodingzUTF-8NFr!z<lambda>rB)r�iorO�writer�hasattrr(r!rBr��_FUNCTION_HASHES�	TypeError)rRrHrrr�Zis_named_callable�	func_hashrrr�_write_func_codes
zMemorizedFunc._write_func_coderjc%Cs�y6|jtkr5|j�}|t|jkr5dSWntk
rJYnXt|j�\}}}|j�}tjj|d�}y;t	j
|dd��}t|j��\}	}
WdQRXWn)t
k
r�|j|||�dSYnX|	|kr�dSt|jdddd�\}}|
|ko3dknsD|d
kr�|dksfd|||f}
n|}
tjtd|
�d
|�|
|kr�|dk	r�d}tjj|�rPt|jdd�\}}t|jd��}t|��-}|j�|
d	|
d	|d	�}WdQRXdj|�}|j�|	j�k}n|jd�}|r�tjtd|||
|||f�d
|�|jdkr�t|jdd�\}}|jd||f�|jdd�dS)z�
            stacklevel is the depth a which this function is called, to
            issue useful warnings to the user.
        Tzfunc_code.pyr�zUTF-8NFZresolv_aliasZwin_charactersrz<lambda>z
%s (%s:%i)z/Cannot detect name collisions for function '%s'rirr1z	<doctest zHPossible name collisions between functions '%s' (%s:%i) and '%s' (%s:%i)r7z'Function %s (stored in %s) has changed.rgrr)r(r�r�r�rr�r&r'rr�rOr�read�IOErrorr�rrnrgr r|rrr
�	readlines�rstriprrlrW)rRrir�rZsource_filerr��func_code_fileZinfileZ
old_func_codeZold_first_lineryrBZfunc_descriptionZpossible_collisionZ	num_linesrSZon_disk_func_coderrrr{6sh	
#
	(		$				z'MemorizedFunc._check_previous_func_codecCs�|jdd�}|jdkr8|r8|jd|�tjj|�r]tj|dd�t|�t	|j
�\}}}tjj|d�}|j|||�dS)	z% Empty the function's cache.
        r�FrzClearing cache %srTTzfunc_code.pyN)
r�rlrgr&r'r|rUrVrrr(rr�)rRrgr�rryrr�rrrrW�s
zMemorizedFunc.clearcOs�tj�}|j||�\}}|jdkrLtt|j||��|j||�}|j||�tj�|}|j||||�}|jdkr�t|j�\}}	d|	t	|�f}
tt
ddt|
��d|
�||fS)zq Force the execution of the function with the given arguments and
            persist the output values.
        rz%s - %srxry)r<rzrlr=r	r(�_persist_output�_persist_inputrrr~r)rRrFrd�
start_timerAry�outputrLrDr3r�rrrr}�s%zMemorizedFunc.callcCsryYt|�tjj|d�}tj||d|j�|jdkrXtd|�Wnt	k
rmYnXdS)z: Persist the given output tuple in the directory.
        z
output.pklrmr7zPersisting in %sN)
rr&r'rr�dumprmrlr=�OSError)rRr��dirrHrrrr��s

zMemorizedFunc._persist_outputg�?cCs�tj�}t|j|j||�}tdd�|j�D��}d|d|i}	yFt|�ttj	j
|d�d��}
tj|	|
�WdQRXWnYnXtj�|}||kr�t
jd|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.
        css'|]\}}|t|�fVqdS)N)�repr)r2�k�vrrr�	<genexpr>�sz/MemorizedFunc._persist_input.<locals>.<genexpr>rLr6z
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<rr(rk�dictr9rrOr&r'rrPr�rnrg)rRrArLrFrdZthis_duration_limitr�Z
argument_dictZ
input_reprrDrSZ
this_durationrrrr��s 
!	
zMemorizedFunc._persist_inputc	CsAtjdt�t|t|j�d|jd|jd|j�S)ze Read the results of a previous calculation from the directory
            it was cached in.
        z�MemorizedFunc.load_output is deprecated and will be removed in a future version
of joblib. A MemorizedResult provides similar featuresrCr8rE)	rnrgr�rIr+r(rCr8rl)rRrArrr�load_output�s
		zMemorizedFunc.load_outputcCs#d|jj|jt|j�fS)Nz%s(func=%s, cachedir=%s))rZr!r(r�r-)rRrrrr[s	zMemorizedFunc.__repr__)r!r"r#r$rMr�rfrer\rr	r�rzZget_output_dirr�r�r�r{rWr}r�r�r�r[rrrrrh1s,!:;			X

5rhc@sveZdZdZddddd�Zdddddd�Zd	d
d�Zdd
�Zdd�Zdd�Z	dS)�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`
    NFrcCs�tj|�||_||_tj�|_||_|r\|dk	r\tjddd�|dkrtd|_	n%t
jj|d�|_	t
|j	�dS)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 memmappedrirjZjoblib)rrMrlr8r<rCrmrnrgr-r&r'rr)rRr-r8rmrErrrrMs
			zMemory.__init__cCs�|dkr.tj|jd|d|d|�S|jdkrGt|�S|dkr\|j}|dkrq|j}t|t�r�|j	}t|d|jd|d|d|j
d|d|j�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`.
        NrkrEr8Fr-rmrC)ro�partial�cacher-rcrlr8r,rhr(rmrC)rRr(rkrEr8rrrr�@s"

				zMemory.cacheTcCs3|r|jd�|jdk	r/t|j�dS)z- Erase the complete cache directory.
        zFlushing completely the cacheN)rgr-r)rRrgrrrrWos
zMemory.clearcOs2|jdkr|||�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�)rRr(rFrdrrr�evalws	
zMemory.evalcCsd|jjt|j�fS)Nz%s(cachedir=%s))rZr!r�r-)rRrrrr[�s	zMemory.__repr__cCsJ|jdk	r"|jdd�nd}|j||j|j|jffS)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-rZr8rmrl)rRr-rrrr\�s(	zMemory.__reduce__)
r!r"r#r$rMr�rWr�r[r\rrrrr�s$	.r�)7r$Z
__future__rr&rUr<rrrt�sysZcPickle�pickle�ImportErrorror�rnrqrP�weakrefr�r1rZfunc_inspectrrrrr	Z_memory_helpersr
Zloggerrrr
rZdiskrrZ_compatrrrr�UserWarningr r+r0rI�WeakKeyDictionaryr�rJ�objectr]rcrhr�rrrr�<module>sP


%Q*&��