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



ש�W~�@s�dZddlmZddlZddlZddlmZddlZddlZddl	Z	ddl
Z
ddlmZddl
mZyddlZWnddlZYnXddlmZdd	lmZdd
lmZmZddlmZmZddlmZdd
lmZmZm Z m!Z!ddl"m#Z#ddl$m%Z%ddlm&Z&ddlm'Z'dede de!iZ(da)dZ*e	j+�Z,dd�Z-ed/dd��Z.e/ed�r	ej0j1dd�j2�p�dZ3ej4de3�Z5ndZ5Gdd�de6�Z7dd �Z8d!d"�Z9d#d$d%�Z:Gd&d'�d'e6�Z;d(d)d*�Z<d0d+d,�Z=Gd-d.�d.e�Z>dS)1z+
Helpers for embarrassingly parallel code.
�)�divisionN)�sqrt)�Integral)�contextmanager�)�mp)�format_outer_frames)�Logger�short_format_time)�TransportableException�
_mk_exception)�memstr_to_bytes)�FallbackToBackend�MultiprocessingBackend�ThreadingBackend�SequentialBackend)�_basestring)�getfullargspec)�AutoBatchingMixin)�ParallelBackendBase�multiprocessing�	threading�
sequentialcCs9ttdd�}|dk	r"|Stt�}|tfS)z!Return the active default backend�backend_and_jobsN)�getattr�_backend�BACKENDS�DEFAULT_BACKEND�DEFAULT_N_JOBS)�active_backend_and_jobs�active_backend�r!�@/opt/alt/python35/lib/python3.5/site-packages/joblib/parallel.py�get_active_backend8s

r#c
ks�t|t�rt||�}ttdd�}z||ft_||fVWd|dkrttdd�dk	r�t`n	|t_XdS)a�Change the default backend used by Parallel inside a with block.

    If ``backend`` is a string it must match a previously registered
    implementation using the ``register_parallel_backend`` function.

    Alternatively backend can be passed directly as an instance.

    By default all available workers will be used (``n_jobs=-1``) unless the
    caller passes an explicit value for the ``n_jobs`` parameter.

    This is an alternative to passing a ``backend='backend_name'`` argument to
    the ``Parallel`` class constructor. It is particularly useful when calling
    into library code that uses joblib internally but does not expose the
    backend argument in its own API.

    >>> from operator import neg
    >>> with parallel_backend('threading'):
    ...     print(Parallel()(delayed(neg)(i + 1) for i in range(5)))
    ...
    [-1, -2, -3, -4, -5]

    Warning: this function is experimental and subject to change in a future
    version of joblib.

    .. versionadded:: 0.10

    rN)�
isinstancerrrrr)�backend�n_jobs�backend_params�old_backend_and_jobsr!r!r"�parallel_backendCs	r)�get_contextZJOBLIB_START_METHOD��methodc@s:eZdZdZdd�Zdd�Zdd�ZdS)	�BatchedCallszCWrap a sequence of (func, args, kwargs) tuples as a single callablecCs%t|�|_t|j�|_dS)N)�list�items�len�_size)�self�iterator_slicer!r!r"�__init__~szBatchedCalls.__init__cCsdd�|jD�S)NcSs(g|]\}}}|||��qSr!r!)�.0�func�args�kwargsr!r!r"�
<listcomp>�s	z)BatchedCalls.__call__.<locals>.<listcomp>)r/)r2r!r!r"�__call__�szBatchedCalls.__call__cCs|jS)N)r1)r2r!r!r"�__len__�szBatchedCalls.__len__N)�__name__�
__module__�__qualname__�__doc__r4r:r;r!r!r!r"r-{sr-cCstdkrdStj�S)zReturn the number of CPUs.Nr)r�	cpu_countr!r!r!r"r@�sr@cCsv|s
dS|dkrdS|dkr*dSdd|d}t||�}t|d|�}t|�t|�kS)	z� Returns False for indices increasingly apart, the distance
        depending on the value of verbose.

        We use a lag increasing as the square of index
    T�
Frg�?��r)r�int)�index�verbose�scale�
next_scaler!r!r"�_verbosity_filter�srITcsW|rtj���fdd�}ytj��|�}Wntk
rRYnX|S)a!Decorator used to capture the arguments of a function.

    Pass `check_pickle=False` when:

    - performing a possibly repeated check is too costly and has been done
      already once outside of the call to delayed.

    - when used in conjunction `Parallel(backend='threading')`.

    cs
�||fS)Nr!)r7r8)�functionr!r"�delayed_function�sz!delayed.<locals>.delayed_function)�pickle�dumps�	functools�wraps�AttributeError)rJ�check_picklerKr!)rJr"�delayed�s


rRc@s.eZdZdZdd�Zdd�ZdS)�BatchCompletionCallBacka_Callback used by joblib.Parallel's multiprocessing backend.

    This callable is executed by the parent process whenever a worker process
    has returned the results of a batch of tasks.

    It is used for progress reporting, to update estimate of the batch
    processing duration and to schedule the next batch of tasks to be
    processed.

    cCs||_||_||_dS)N)�dispatch_timestamp�
batch_size�parallel)r2rTrUrVr!r!r"r4�s		z BatchCompletionCallBack.__init__cCsq|jj|j7_tj�|j}|jjj|j|�|jj�|jjdk	rm|jj	�dS)N)
rV�n_completed_tasksrU�timerTr�batch_completed�print_progress�_original_iterator�
dispatch_next)r2�out�this_batch_durationr!r!r"r:�s
z BatchCompletionCallBack.__call__N)r<r=r>r?r4r:r!r!r!r"rS�s
rSFcCs|t|<|r|adS)a�Register a new Parallel backend factory.

    The new backend can then be selected by passing its name as the backend
    argument to the Parallel class. Moreover, the default backend can be
    overwritten globally by setting make_default=True.

    The factory can be any callable that takes no argument and return an
    instance of ``ParallelBackendBase``.

    Warning: this function is experimental and subject to change in a future
    version of joblib.

    .. versionadded:: 0.10

    N)rr)�name�factory�make_defaultr!r!r"�register_parallel_backend�s
rbcCst�\}}|jd|�S)amDetermine the number of jobs that can actually run in parallel

    n_jobs is the is the number of workers requested by the callers.
    Passing n_jobs=-1 means requesting all available workers for instance
    matching the number of CPU cores on the worker host(s).

    This method should return a guesstimate of the number of workers that can
    actually perform work concurrently with the currently enabled default
    backend. The primary use case is to make it possible for the caller to know
    in how many chunks to slice the work.

    In general working on larger data chunks is more efficient (less
    scheduling overhead and better use of CPU cache prefetching heuristics)
    as long as all the workers have enough work to do.

    Warning: this function is experimental and subject to change in a future
    version of joblib.

    .. versionadded:: 0.10

    r&)r#�effective_n_jobs)r&r%�_r!r!r"rc�srcc@s�eZdZdZdddddddddd	d
�	Zdd�Zd
d�Zdd�Zdd�Zdd�Z	dd�Z
dd�Zdd�Zdd�Z
dd�Zdd �Zd!d"�Zd#d$�ZdS)%�Parallela<' Helper class for readable parallel mapping.

        Parameters
        -----------
        n_jobs: int, default: 1
            The maximum number of concurrently running jobs, such as the number
            of Python worker processes when backend="multiprocessing"
            or the size of the thread-pool when backend="threading".
            If -1 all CPUs are used. If 1 is given, no parallel computing code
            is used at all, which is useful for debugging. For n_jobs below -1,
            (n_cpus + 1 + n_jobs) are used. Thus for n_jobs = -2, all
            CPUs but one are used.
        backend: str or None, default: 'multiprocessing'
            Specify the parallelization backend implementation.
            Supported backends are:
              - "multiprocessing" used by default, can induce some
                communication and memory overhead when exchanging input and
                output data with the worker Python processes.
              - "threading" is a very low-overhead backend but it suffers
                from the Python Global Interpreter Lock if the called function
                relies a lot on Python objects. "threading" is mostly useful
                when the execution bottleneck is a compiled extension that
                explicitly releases the GIL (for instance a Cython loop wrapped
                in a "with nogil" block or an expensive call to a library such
                as NumPy).
              - finally, you can register backends by calling
                register_parallel_backend. This will allow you to implement
                a backend of your liking.
        verbose: int, optional
            The verbosity level: if non zero, progress messages are
            printed. Above 50, the output is sent to stdout.
            The frequency of the messages increases with the verbosity level.
            If it more than 10, all iterations are reported.
        timeout: float, optional
            Timeout limit for each task to complete.  If any task takes longer
            a TimeOutError will be raised. Only applied when n_jobs != 1
        pre_dispatch: {'all', integer, or expression, as in '3*n_jobs'}
            The number of batches (of tasks) to be pre-dispatched.
            Default is '2*n_jobs'. When batch_size="auto" this is reasonable
            default and the multiprocessing workers should never starve.
        batch_size: int or 'auto', default: 'auto'
            The number of atomic tasks to dispatch at once to each
            worker. When individual evaluations are very fast, multiprocessing
            can be slower than sequential computation because of the overhead.
            Batching fast computations together can mitigate this.
            The ``'auto'`` strategy keeps track of the time it takes for a batch
            to complete, and dynamically adjusts the batch size to keep the time
            on the order of half a second, using a heuristic. The initial batch
            size is 1.
            ``batch_size="auto"`` with ``backend="threading"`` will dispatch
            batches of a single task at a time as the threading backend has
            very little overhead and using larger batch size has not proved to
            bring any gain in that case.
        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.
            Only active when backend="multiprocessing".
        max_nbytes int, str, or None, optional, 1M by default
            Threshold on the size of arrays passed to the workers that
            triggers automated memory mapping in temp_folder. Can be an int
            in Bytes, or a human-readable string, e.g., '1M' for 1 megabyte.
            Use None to disable memmaping of large arrays.
            Only active when backend="multiprocessing".
        mmap_mode: {None, 'r+', 'r', 'w+', 'c'}
            Memmapping mode for numpy arrays passed to workers.
            See 'max_nbytes' parameter documentation for more details.

        Notes
        -----

        This object uses the multiprocessing module to compute in
        parallel the application of a function to many different
        arguments. The main functionality it brings in addition to
        using the raw multiprocessing API are (see examples for details):

            * More readable code, in particular since it avoids
              constructing list of arguments.

            * Easier debugging:
                - informative tracebacks even when the error happens on
                  the client side
                - using 'n_jobs=1' enables to turn off parallel computing
                  for debugging without changing the codepath
                - early capture of pickling errors

            * An optional progress meter.

            * Interruption of multiprocesses jobs with 'Ctrl-C'

            * Flexible pickling control for the communication to and from
              the worker processes.

            * Ability to use shared memory efficiently with worker
              processes for large numpy-based datastructures.

        Examples
        --------

        A simple example:

        >>> from math import sqrt
        >>> from joblib import Parallel, delayed
        >>> Parallel(n_jobs=1)(delayed(sqrt)(i**2) for i in range(10))
        [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]

        Reshaping the output when the function has several return
        values:

        >>> from math import modf
        >>> from joblib import Parallel, delayed
        >>> r = Parallel(n_jobs=1)(delayed(modf)(i/2.) for i in range(10))
        >>> res, i = zip(*r)
        >>> res
        (0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5)
        >>> i
        (0.0, 0.0, 1.0, 1.0, 2.0, 2.0, 3.0, 3.0, 4.0, 4.0)

        The progress meter: the higher the value of `verbose`, the more
        messages::

            >>> from time import sleep
            >>> from joblib import Parallel, delayed
            >>> r = Parallel(n_jobs=2, verbose=5)(delayed(sleep)(.1) for _ in range(10)) #doctest: +SKIP
            [Parallel(n_jobs=2)]: Done   1 out of  10 | elapsed:    0.1s remaining:    0.9s
            [Parallel(n_jobs=2)]: Done   3 out of  10 | elapsed:    0.2s remaining:    0.5s
            [Parallel(n_jobs=2)]: Done   6 out of  10 | elapsed:    0.3s remaining:    0.2s
            [Parallel(n_jobs=2)]: Done   9 out of  10 | elapsed:    0.5s remaining:    0.1s
            [Parallel(n_jobs=2)]: Done  10 out of  10 | elapsed:    0.5s finished

        Traceback example, note how the line of the error is indicated
        as well as the values of the parameter passed to the function that
        triggered the exception, even though the traceback happens in the
        child process::

         >>> from heapq import nlargest
         >>> from joblib import Parallel, delayed
         >>> Parallel(n_jobs=2)(delayed(nlargest)(2, n) for n in (range(4), 'abcde', 3)) #doctest: +SKIP
         #...
         ---------------------------------------------------------------------------
         Sub-process traceback:
         ---------------------------------------------------------------------------
         TypeError                                          Mon Nov 12 11:37:46 2012
         PID: 12934                                    Python 2.7.3: /usr/bin/python
         ...........................................................................
         /usr/lib/python2.7/heapq.pyc in nlargest(n=2, iterable=3, key=None)
             419         if n >= size:
             420             return sorted(iterable, key=key, reverse=True)[:n]
             421
             422     # When key is none, use simpler decoration
             423     if key is None:
         --> 424         it = izip(iterable, count(0,-1))                    # decorate
             425         result = _nlargest(n, it)
             426         return map(itemgetter(0), result)                   # undecorate
             427
             428     # General case, slowest method

         TypeError: izip argument #1 must support iteration
         ___________________________________________________________________________


        Using pre_dispatch in a producer/consumer situation, where the
        data is generated on the fly. Note how the producer is first
        called a 3 times before the parallel loop is initiated, and then
        called to generate new data on the fly. In this case the total
        number of iterations cannot be reported in the progress messages::

         >>> from math import sqrt
         >>> from joblib import Parallel, delayed

         >>> def producer():
         ...     for i in range(6):
         ...         print('Produced %s' % i)
         ...         yield i

         >>> out = Parallel(n_jobs=2, verbose=100, pre_dispatch='1.5*n_jobs')(
         ...                         delayed(sqrt)(i) for i in producer()) #doctest: +SKIP
         Produced 0
         Produced 1
         Produced 2
         [Parallel(n_jobs=2)]: Done 1 jobs     | elapsed:  0.0s
         Produced 3
         [Parallel(n_jobs=2)]: Done 2 jobs     | elapsed:  0.0s
         Produced 4
         [Parallel(n_jobs=2)]: Done 3 jobs     | elapsed:  0.0s
         Produced 5
         [Parallel(n_jobs=2)]: Done 4 jobs     | elapsed:  0.0s
         [Parallel(n_jobs=2)]: Done 5 out of 6 | elapsed:  0.0s remaining: 0.0s
         [Parallel(n_jobs=2)]: Done 6 out of 6 | elapsed:  0.0s finished
    rNrz
2 * n_jobs�auto�1M�rc

Cs�t�\}
}|dkr-|dkr-|}||_||_||_||_t|t�rlt|�}td|d|	d|dt	d|jd��|_
tdk	r�t|j
d<|dkr�|
}n�t|d	�rt|d
�r||j
d<t
�}nNyt|}Wn4tk
rItd|ttj��f��YnX|�}|dkszt|t�r�|dkr�||_ntd
|��||_d|_t�|_d|_tj�|_dS)Nr�
max_nbytes�	mmap_mode�temp_folderrFr�2�context�Pool�Lockz'Invalid backend: %s, expected one of %rrfz8batch_size must be 'auto' or a positive integer, got: %rF)r#r&rF�timeout�pre_dispatchr$rr
�dict�max�
_backend_args�DEFAULT_MP_CONTEXT�hasattrrr�KeyError�
ValueError�sorted�keysrrUr�_outputr.�_jobs�_managed_backendrro�_lock)
r2r&r%rFrprqrUrkrirjr �default_n_jobs�backend_factoryr!r!r"r4�sL				
	

!	
			zParallel.__init__cCsd|_|j�|S)NT)r}�_initialize_backend)r2r!r!r"�	__enter__s	
zParallel.__enter__cCs|j�d|_dS)NF)�_terminate_backendr})r2�exc_type�	exc_value�	tracebackr!r!r"�__exit__s
zParallel.__exit__cCshy&|jjd|jd||j�SWn;tk
rc}z|j|_|j�SWYdd}~XnXdS)z?Build a process or thread pool and return the number of workersr&rVN)r�	configurer&rtrr%r�)r2�er!r!r"r�szParallel._initialize_backendcCs |jr|jj|j�SdS)Nr)rrcr&)r2r!r!r"�_effective_n_jobs"s	zParallel._effective_n_jobscCs |jdk	r|jj�dS)N)r�	terminate)r2r!r!r"r�'szParallel._terminate_backendcCs�|jr
dS|jt|�7_|jd7_tj�}t|t|�|�}|jj|d|�}|jj	|�dS)z�Queue the batch for computing, with or without multiprocessing

        WARNING: this method is not thread-safe: it should be only called
        indirectly via dispatch_one_batch.

        Nr�callback)
�	_aborting�n_dispatched_tasksr0�n_dispatched_batchesrXrSr�apply_asyncr|�append)r2�batchrT�cb�jobr!r!r"�	_dispatch+s	zParallel._dispatchcCs(|j|j�s$d|_d|_dS)aDispatch more data for parallel processing

        This method is meant to be called concurrently by the multiprocessing
        callback. We rely on the thread-safety of dispatch_one_batch to protect
        against concurrent consumption of the unprotected iterator.

        FN)�dispatch_one_batchr[�
_iterating)r2r!r!r"r\>s	zParallel.dispatch_nextcCs~|jdkr!|jj�}n	|j}|j�Dttj||��}t|�dkrbdS|j|�dSWdQRXdS)aTPrefetch the tasks for the next batch and dispatch them.

        The effective size of the batch is computed here.
        If there are no more jobs to dispatch, return False, else return True.

        The iterator consumption and dispatching is protected by the same
        lock so calling this function should be thread safe.

        rfrFTN)	rUr�compute_batch_sizer~r-�	itertools�islicer0r�)r2�iteratorrU�tasksr!r!r"r�Js
	

zParallel.dispatch_one_batchcCsY|js
dS|jdkr+tjj}ntjj}||}|d||f�dS)z=Display the message on stout or stderr depending on verbosityNrlz	[%s]: %s
)rF�sys�stderr�write�stdout)r2�msg�msg_args�writerr!r!r"�_printcs	
zParallel._printcCs|js
dStj�|j}|jdk	rjt|j|j�rHdS|jd|jt|�f�n�|j}|j	}|dks�||d|j
}||jd}|d|k}|s�||r�dS|||j	|d}|jd||t|�t|�f�dS)zvDisplay the process of the parallel execution only a fraction
           of time, controlled by self.verbose.
        Nz!Done %3i tasks      | elapsed: %srrg�?z/Done %3i out of %3i | elapsed: %s remaining: %s)rFrX�_start_timer[rIr�r�rWr
r��_pre_dispatch_amount)r2�elapsed_timerE�total_tasks�cursor�	frequency�is_last_item�remaining_timer!r!r"rZps2				
		zParallel.print_progresscCs�t�|_x�|js-t|j�dkr�t|j�dkrRtjd�q|j�|jjd�}WdQRXyTdt	|j
�jkr�|jj|j
d|j
��n|jj|j
��Wqtk
r�}z�d|_t|t�r=tdddd�}d	||jf}t|j�d}||�}|j}|dk	rzt|d
�rz|j}|jd|�|�WYdd}~XqXqWdS)Nrg{�G�z�?rpTrmrA�stack_startrz�Multiprocessing exception:
%s
---------------------------------------------------------------------------
Sub-process traceback:
---------------------------------------------------------------------------
%s�abort_everything�ensure_ready)r.r{r�r0r|rX�sleepr~�popr�getr7�extendrp�
BaseExceptionr�r$rr�messager�etyperrvr}r�)r2r��	exception�this_report�report�exception_typer%r�r!r!r"�retrieve�s2!

"				zParallel.retrievecCs�|jrtd��d|_|js6|j�}n|j�}t|�}|j}|dkso|dkr�d|_d|_	nI||_t
|d�r�t|�}t|�|_	}t
j||�}tj�|_d|_d|_d|_z�x%|j|�rd|_q�Wd|_|dks:|dkrCd|_|j�tj�|j}|jdt|j�t|j�t|�f�Wd|js�|j�t�|_X|j}d|_|S)	Nz)This Parallel instance is already runningF�allrr�endswithTz*Done %3i out of %3i | elapsed: %s finished)r|rxr�r}r�r��iterrqr[r�rv�evalrDr�r�rXr�r�r�rWr�r�r�r�r0r{r
r�r.)r2�iterabler&r�rqr��outputr!r!r"r:�sJ									
		
		

		zParallel.__call__cCsd|jj|jfS)Nz
%s(n_jobs=%s))�	__class__r<r&)r2r!r!r"�__repr__szParallel.__repr__)r<r=r>r?r4r�r�r�r�r�r�r\r�r�rZr�r:r�r!r!r!r"res"�8

+6=re���r�)?r?�
__future__r�osr��mathrrNrXrr��numbersr�
contextlibr�cPicklerL�_multiprocessing_helpersr�format_stackr�loggerr	r
�
my_exceptionsrr�diskr
�_parallel_backendsrrrr�_compatr�func_inspectrrrrrr�localrr#r)rv�environr��stripr,r*ru�objectr-r@rIrRrSrbrcrer!r!r!r"�<module>sZ"0!