Your IP : 216.73.216.61


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__/pool.cpython-35.pyc



�u�W�a�@s�dZddlmZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlmZye
Wnek
r�dZ
YnXddlmZy$ddlmZddlmZWn>ek
r)ddlmZddlmZddlZYnXddlmZdd	lmZdd
lmZddlmZmZdd
lmZy ddlZ ddl!m"Z"Wnek
r�dZ YnXddl#m$Z$ddl#m%Z%ddl&m'Z'dZ(ej)ej*Bej+BZ,ej)ej*BZ-dd�Z.dd�Z/dd�Z0dd�Z1dd�Z2Gdd�de3�Z4Gdd �d e�Z5Gd!d"�d"e3�Z6Gd#d$�d$e�Z7d%d&�Z8Gd'd(�d(e7�Z9dS))a�Custom implementation of multiprocessing.Pool with custom pickler.

This module provides efficient ways of working with data stored in
shared memory with numpy.memmap arrays without inducing any memory
copy between the parent and child processes.

This module should not be imported if multiprocessing is not
available as it implements subclasses of multiprocessing Pool
that uses a custom alternative to SimpleQueue.

�)�mmapN)�sleep)�whichmodule)�loads)�dumps)�Pickler)�HIGHEST_PROTOCOL)�BytesIO�)�mp�assert_spawning)�Pool)�
as_strided)�load)�dump)�hashz/dev/shmcCsCt|dd�}|dkr"dSt|t�r5|St|�SdS)z@Recursively look up the original np.memmap instance base if any.�baseN)�getattr�
isinstancer�_get_backing_memmap)�a�b�r�</opt/alt/python35/lib/python3.5/site-packages/joblib/pool.pyrOsrcCst|�dk	S)z?Return True if a is backed by some mmap buffer directly or not.N)r)rrrr�has_shareable_memory`src	Cs�|dkrd}|dkrItj|d|d|d|d|d|�Stj|d|d|d|d|d|�}t|d|d	|�SdS)
z2Reconstruct an array view on a memory mapped file.zw+zr+N�dtype�shape�mode�offset�order�strides)�np�memmapr)	�filenamerrrrrr �total_buffer_lenrrrr�_strided_from_memmapes
r%c		Cs�tj|�\}}tj|�d}||}||j7}|jdrUd}nd}|jdsu|jdr�d}d}n|j}|||j}t|j|j|j	|||j
||ffS)aPickling reduction for memmap backed arrays.

    a is expected to be an instance of np.ndarray (or np.memmap)
    m is expected to be an instance of np.memmap on the top of the ``base``
    attribute ancestry of a. ``m.base`` should be the real python mmap object.
    r�F_CONTIGUOUS�F�C�C_CONTIGUOUSN)r!�byte_boundsr�flagsr �itemsizer%r#rrr)	r�m�a_start�a_end�m_startrrr r$rrr�_reduce_memmap_backedxs


			!r1cCsKt|�}|dk	r%t||�Stttj|�dt�ffSdS)zCPickle the descriptors of a memmap instance to reopen on same file.N�protocol)rr1rrr!�asarrayr)rr-rrr�
reduce_memmap�s
r4c@s7eZdZdZddddd�Zdd�ZdS)	�ArrayMemmapReducera�Reducer callable to dump large arrays to memmap files.

    Parameters
    ----------
    max_nbytes: int
        Threshold to trigger memmaping of large arrays to files created
        a folder.
    temp_folder: str
        Path of a folder where files for backing memmaped arrays are created.
    mmap_mode: 'r', 'r+' or 'c'
        Mode for the created memmap datastructure. See the documentation of
        numpy.memmap for more details. Note: 'w+' is coerced to 'r+'
        automatically to avoid zeroing the data on unpickling.
    verbose: int, optional, 0 by default
        If verbose > 0, memmap creations are logged.
        If verbose > 1, both memmap creations, reuse and array pickling are
        logged.
    prewarm: bool, optional, False by default.
        Force a read on newly memmaped array to make sure that OS pre-cache it
        memory. This can be useful to avoid concurrent disk access when the
        same data array is passed to different worker processes.
    rNTcCsS||_||_||_t|�|_||_|dk	rOtjdt�dS)NzPcontext_id is deprecated and ignored in joblib 0.9.4 and will be removed in 0.11)	�_max_nbytes�_temp_folder�
_mmap_mode�int�verbose�_prewarm�warnings�warn�DeprecationWarning)�self�
max_nbytes�temp_folder�	mmap_moder:�
context_id�prewarmrrr�__init__�s					zArrayMemmapReducer.__init__cCst|�}|dk	r%t||�S|jjr�|jdk	r�|j|jkr�y'tj|j�tj	|jt
�Wn=tk
r�}z|jtj
kr�|�WYdd}~XnXdtj�ttj��t|�f}tjj|j|�}tjj|�s�|jdkr;td|j|j|f�x't||�D]}tj	|t�qKW|jr�t|d|j�j�n,|jdkr�td|j|j|f�t||jffS|jdkr�td|j|jf�tt |dt!�ffSdS)	Nz%d-%d-%s.pklrz-Memmaping (shape=%r, dtype=%s) to new file %srBr
z-Memmaping (shape=%s, dtype=%s) to old file %sz$Pickling array (shape=%r, dtype=%s).r2)"rr1r�	hasobjectr6�nbytes�os�makedirsr7�chmod�FOLDER_PERMISSIONS�OSError�errno�EEXIST�getpid�id�	threading�current_threadr�path�join�existsr:�printrr�FILE_PERMISSIONSr;rr8�maxrrr)r?rr-�e�basenamer#�dumped_filenamerrr�__call__�s>

(	zArrayMemmapReducer.__call__)�__name__�
__module__�__qualname__�__doc__rEr\rrrrr5�sr5c@s4eZdZdZdedd�Zdd�ZdS)�CustomizablePicklerawPickler that accepts custom reducers.

    HIGHEST_PROTOCOL is selected by default as this pickler is used
    to pickle ephemeral datastructures for interprocess communication
    hence no backward compatibility is required.

    `reducers` is expected to be a dictionary with key/values
    being `(type, callable)` pairs where `callable` is a function that
    give an instance of `type` will return a tuple `(constructor,
    tuple_of_objects)` to rebuild an instance out of the pickled
    `tuple_of_objects` as would return a `__reduce__` method. See the
    standard library documentation on pickling for more details.

    NcCs�tj||d|�|dkr(i}ttd�rLtjj�|_ntjj�|_x*|j�D]\}}|j||�qkWdS)Nr2�dispatch)	rrE�hasattrrb�copy�copyreg�dispatch_table�items�register)r?�writer�reducersr2�type�reduce_funcrrrrEszCustomizablePickler.__init__csBttd�r1�fdd�}||j|<n
�|j|<dS)z@Attach a reducer function to a given type in the dispatch table.rbcs#�|�}|j|d|�dS)N�obj)�save_reduce)r?rm�reduced)rlrr�
dispatcher3sz0CustomizablePickler.register.<locals>.dispatcherN)rcrrbrf)r?rkrlrpr)rlrrh.szCustomizablePickler.register)r]r^r_r`rrErhrrrrra	srac@sUeZdZdZddd�Zdd�Zdd�Zd	d
�Zdd�ZdS)
�CustomizablePicklingQueuea�Locked Pipe implementation that uses a customizable pickler.

    This class is an alternative to the multiprocessing implementation
    of SimpleQueue in order to make it possible to pass custom
    pickling reducers, for instance to avoid memory copy when passing
    memory mapped datastructures.

    `reducers` is expected to be a dict with key / values being
    `(type, callable)` pairs where `callable` is a function that, given an
    instance of `type`, will return a tuple `(constructor, tuple_of_objects)`
    to rebuild an instance out of the pickled `tuple_of_objects` as would
    return a `__reduce__` method.

    See the standard library documentation on pickling for more details.
    NcCsn||_|jdd�\|_|_|j�|_tjdkrQd|_n|j�|_|j	�dS)N�duplexF�win32)
�	_reducers�Pipe�_reader�_writer�Lock�_rlock�sys�platform�_wlock�
_make_methods)r?�contextrjrrrrELs	z"CustomizablePicklingQueue.__init__cCs,t|�|j|j|j|j|jfS)N)rrvrwryr|rt)r?rrr�__getstate__Vs
z&CustomizablePicklingQueue.__getstate__cCs2|\|_|_|_|_|_|j�dS)N)rvrwryr|rtr})r?�staterrr�__setstate__[s$z&CustomizablePicklingQueue.__setstate__cCs|jj�S)N)rv�poll)r?rrr�empty`szCustomizablePicklingQueue.emptycs��jj�_��jj�jj�����fdd�}|�_�jrt�fdd����_n�j	j
�_��jdkr���_n:�jj�jj�����fdd�}|�_dS)Nc
s!��z��SWd��XdS)Nrr)�racquire�recv�rreleaserr�getgsz4CustomizablePicklingQueue._make_methods.<locals>.getcs<t�}t|�j�j|��jj|j��dS)N)r	rartrrw�
send_bytes�getvalue)rm�buffer)r?rr�sendqs	z5CustomizablePicklingQueue._make_methods.<locals>.sendc
s$��z�|�SWd��XdS)Nr)rm)r��
wlock_acquire�
wlock_releaserr�putsz4CustomizablePicklingQueue._make_methods.<locals>.put)
rvr��_recvry�acquire�releaser�rt�_sendrwr�r|r�)r?r�r�r)r�r�r�r?r�r�r�rr}cs		z'CustomizablePicklingQueue._make_methods)	r]r^r_r`rErr�r�r}rrrrrq;s
rqcs=eZdZdZddd�fdd�Zdd�Z�S)�PicklingPoola�Pool implementation with customizable pickling reducers.

    This is useful to control how data is shipped between processes
    and makes it possible to use shared memory without useless
    copies induces by the default pickling methods of the original
    objects passed as arguments to dispatch.

    `forward_reducers` and `backward_reducers` are expected to be
    dictionaries with key/values being `(type, callable)` pairs where
    `callable` is a function that, given an instance of `type`, will return a
    tuple `(constructor, tuple_of_objects)` to rebuild an instance out of the
    pickled `tuple_of_objects` as would return a `__reduce__` method.
    See the standard library documentation about pickling for more details.

    Ncsr|dkrt�}|dkr*t�}||_||_td|�}|j|�tt|�j|�dS)N�	processes)�dict�_forward_reducers�_backward_reducers�update�superr�rE)r?r��forward_reducers�backward_reducers�kwargs�poolargs)�	__class__rrrE�s				
zPicklingPool.__init__cCs^t|dt�}t||j�|_t||j�|_|jj|_|jj	|_
dS)N�_ctx)rrrqr��_inqueuer��	_outqueuer��
_quick_putr��
_quick_get)r?r~rrr�
_setup_queues�szPicklingPool._setup_queues)r]r^r_r`rEr�rr)r�rr��sr�cCsMy#tjj|�r"tj|�Wn#tk
rHtjd|�YnXdS)zAUtility function to cleanup a temporary folder if still existing.z$Failed to clean temporary folder: %sN)rHrSrU�shutil�rmtree�WindowsErrorr<r=)�folder_pathrrr�
delete_folder�s

r�csUeZdZdZddddddddd�fdd�	Z�fd	d
�Z�S)�
MemmapingPoolau
Process pool that shares large arrays to avoid memory copy.

    This drop-in replacement for `multiprocessing.pool.Pool` makes
    it possible to work efficiently with shared memory in a numpy
    context.

    Existing instances of numpy.memmap are preserved: the child
    suprocesses will have access to the same shared memory in the
    original mode except for the 'w+' mode that is automatically
    transformed as 'r+' to avoid zeroing the original data upon
    instantiation.

    Furthermore large arrays from the parent process are automatically
    dumped to a temporary folder on the filesystem such as child
    processes to access their content via memmaping (file system
    backed shared memory).

    Note: it is important to call the terminate method to collect
    the temporary folder used by the pool.

    Parameters
    ----------
    processes: int, optional
        Number of worker processes running concurrently in the pool.
    initializer: callable, optional
        Callable executed on worker process creation.
    initargs: tuple, optional
        Arguments passed to the initializer callable.
    temp_folder: str, optional
        Folder to be used by the pool for memmaping large arrays
        for sharing memory with worker processes. If None, this will try in
        order:
        - a folder pointed by the JOBLIB_TEMP_FOLDER environment variable,
        - /dev/shm if the folder exists and is writable: this is a RAMdisk
          filesystem available by default on modern Linux distributions,
        - the default system temporary folder that can be overridden
          with TMP, TMPDIR or TEMP environment variables, typically /tmp
          under Unix operating systems.
    max_nbytes int or None, optional, 1e6 by default
        Threshold on the size of arrays passed to the workers that
        triggers automated memory mapping in temp_folder.
        Use None to disable memmaping of large arrays.
    mmap_mode: {'r+', 'r', 'w+', 'c'}
        Memmapping mode for numpy arrays passed to workers.
        See 'max_nbytes' parameter documentation for more details.
    forward_reducers: dictionary, optional
        Reducers used to pickle objects passed from master to worker
        processes: see below.
    backward_reducers: dictionary, optional
        Reducers used to pickle return values from workers back to the
        master process.
    verbose: int, optional
        Make it possible to monitor how the communication of numpy arrays
        with the subprocess is handled (pickling or memmaping)
    prewarm: bool or str, optional, "auto" by default.
        If True, force a read on newly memmaped array to make sure that OS pre-
        cache it in memory. This can be useful to avoid concurrent disk access
        when the same data array is passed to different worker processes.
        If "auto" (by default), prewarm is set to True, unless the Linux shared
        memory partition /dev/shm is available and used as temp_folder.

    `forward_reducers` and `backward_reducers` are expected to be
    dictionaries with key/values being `(type, callable)` pairs where
    `callable` is a function that give an instance of `type` will return
    a tuple `(constructor, tuple_of_objects)` to rebuild an instance out
    of the pickled `tuple_of_objects` as would return a `__reduce__`
    method. See the standard library documentation on pickling for more
    details.

    Ng��.A�rrFc
sP|dkrt�}|dkr*t�}|dk	rFtjdt�d}dtj�t|�f}|dkr�tjjdd�}|dkrtj	j
t�ryDt}tj	j||��tj	j
��s�tj
��d}Wntk
rd}YnX|dkrtj�}tj	jtj	j|��}tj	j||���|_ttd����fdd�}
tj|
�tdk	r|	d	kr�|}	t|�||d
|	�}||tj<t|tj<td�||�}||tj<t|tj<td|d|d
|�}|j|
�tt|�j |�dS)NzPcontext_id is deprecated and ignored in joblib 0.9.4 and will be removed in 0.11Fzjoblib_memmaping_pool_%d_%d�JOBLIB_TEMP_FOLDERTr�cs&t�ddg�j}|��dS)N�fromlistr�)�
__import__r�)r�)�pool_folder�pool_module_namerr�_cleanup/s	z(MemmapingPool.__init__.<locals>._cleanup�autorDr�r�r�)!r�r<r=r>rHrOrP�environr�rSrU�SYSTEM_SHARED_MEM_FSrTrI�IOError�tempfile�
gettempdir�abspath�
expanduserr7rr��atexitrhr!r5�ndarrayr4r"r�r�r�rE)r?r�rAr@rBr�r�r:rCrDr��use_shared_mem�pool_folder_namer��forward_reduce_ndarray�backward_reduce_ndarrayr�)r�)r�r�rrEs`			


	

	



	
zMemmapingPool.__init__cs�d}xt|�D]q}ytt|�j�PWqtk
r�}z0td�|d|krqtjd|�WYdd}~XqXqWt|j	�dS)N�
g�������?r
zAFailed to terminate worker processes in  multiprocessing pool: %r)
�ranger�r��	terminater�rr<r=r�r7)r?�	n_retries�irY)r�rrr�Zs
	zMemmapingPool.terminate)r]r^r_r`rEr�rr)r�rr��s
F		Wr�):r`rrMrH�statrzrQr�r�r�r<�timerr��	NameError�pickler�cPicklerr�ImportErrorrerr�ior	�_multiprocessing_helpersrr�multiprocessing.poolr
�numpyr!�numpy.lib.stride_tricksr�numpy_picklerr�hashingrr��S_IRUSR�S_IWUSR�S_IXUSRrKrWrrr%r1r4�objectr5rarqr�r�r�rrrr�<module>sd


$_2N'