
    .PhS             
          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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 ddlmZ ddlmZ d	d
lmZ d	dlmZmZmZmZ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* e"e!dZ+da,dZ-dZ.ddhZ/eee+d<   d	dl0m1Z1 ee+d<   da,dZ. e	j2                    Z3d Z4de4iZ5 e$d           e$d           e$d           e$d           e$d           e$d           e$d           e$d          dZ6dZ7dZ8d Z9e6d         e6d         e6d         fd Z:e6d         e6d         e6d         fd!Z; G d" d#          Z< G d$ d%e<          Z=dZ> e?ed&          rBej@        A                    d'd(          B                                pdZCeC ejD        eC)          Z> G d* d+eE          ZFd,ZGd-ZHd.ZId:d0ZJd1 ZKd2 ZL G d3 d4eE          ZMd:d5ZNd;d7ZO G d8 d9e)          ZPdS )<z+
Helpers for embarrassingly parallel code.
    )divisionN)nullcontext)floorlog10sqrt)TimeoutError)Integral)uuid4   )mp)AutoBatchingMixinFallbackToBackendLokyBackendMultiprocessingBackendParallelBackendBaseSequentialBackendThreadingBackend)	_Sentinel	eval_expr)memstr_to_bytes)Loggershort_format_time)	threading
sequentialr   multiprocessingloky)r   c                  |    	 ddl m}  t          d|            dS # t          $ r}d}t          |          |d}~ww xY w)zDRegister Dask Backend if called with parallel_config(backend="dask")r   )DaskDistributedBackenddaskzTo use the dask.distributed backend you must install both the `dask` and distributed modules.

See https://dask.pydata.org/en/latest/install.html for more information.N)_daskr   register_parallel_backendImportError)r   emsgs      O/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/joblib/parallel.py_register_daskr&   H   sk    &111111!&*@AAAAA & & & 	 #A%&s    
;6;r   )default_value1Mr)backendn_jobsverbosetemp_folder
max_nbytes	mmap_modepreferrequire)	processesthreadsN)	sharedmemNc                 l    | t           |         ur| S ||         t           |         ur||         S | j        S )zReturn the value of a parallel config parameter

    Explicitly setting it in Parallel has priority over setting in a
    parallel_(config/backend) context manager.
    )default_parallel_configr'   )paramcontext_configkeys      r%   _get_config_paramr:   o   sF     +C000c"9#">>>c""     r0   r1   r,   c                 j    t          | ||          \  }}t          t          d         |d          }||fS )!Return the active default backendr+   )_get_active_backendr:   r6   )r0   r1   r,   r*   configr+   s         r%   get_active_backendr@      s:     *&'7CCOGV6x@&(SSFF?r;   c                    t          t          dt                    }t          t          d         |d          }t          | |d          } t          ||d          }t          ||d          }| t          vrt          d|  dt                     |t          vrt          d| d	t                     | d
k    r|dk    rt          d          d}|t          t                   d          }d}|j	        }t          |dd          }t          |dd          }|dk    r| p| o| dk    o| }	| o| d
k    o|}
|	rjt          t                   |          }|dk    r,|r*t          d|j        j         d|j        j         d           |                                }d|d<   ||fS |
r1t          t                   |          }||                                fS ||fS )r=   r?   r*   r0   r1   r,   zprefer=z. is not a valid backend hint, expected one of zrequire=z4 is not a valid backend constraint, expected one of r2   r4   zJprefer == 'processes' and require == 'sharedmem' are inconsistent settingsTNr   nesting_levelFuses_threadssupports_sharedmemr3   
   zUsing z as joblib backend instead of z8 as the latter does not provide shared memory semantics.r   r+   )getattr_backendr6   r:   VALID_BACKEND_HINTS
ValueErrorVALID_BACKEND_CONSTRAINTSBACKENDSDEFAULT_BACKENDrC   DEFAULT_THREAD_BACKENDprint	__class____name__copyDEFAULT_PROCESS_BACKEND)r0   r1   r,   backend_configr*   explicit_backendrC   rD   rE   force_threadsforce_processessharedmem_backendthread_configprocess_backends                 r%   r>   r>      s    Xx1HIIN	*NI G v~x@@FCCGCCG(((5f 5 525 5
 
 	
 ///;w ; ;8; ;
 
 	
 K!7!7X
 
 	
  ?+!<<<  )M7NE::L *>FF +F4F0F I9!4I\9I  +*Uv/DUO 0 %%;<'
 
 

 b==-=J*4= J J-4->-GJ J J   '++--"#h -// 6 ##:;-XXX 3 3 5 555N""r;   c            
           e Zd ZdZed         fed         ed         ed         ed         ed         ed         ed	         d
ddZd Zd Zd Zd Z	d
S )parallel_configa  Set the default backend or configuration for :class:`~joblib.Parallel`.

    This is an alternative to directly passing keyword arguments to the
    :class:`~joblib.Parallel` class constructor. It is particularly useful when
    calling into library code that uses joblib internally but does not expose
    the various parallel configuration arguments in its own API.

    Parameters
    ----------
    backend: str or ParallelBackendBase instance, default=None
        If ``backend`` is a string it must match a previously registered
        implementation using the :func:`~register_parallel_backend` function.

        By default the following backends are available:

        - 'loky': single-host, process-based parallelism (used by default),
        - 'threading': single-host, thread-based parallelism,
        - 'multiprocessing': legacy single-host, process-based parallelism.

        'loky' is recommended to run functions that manipulate Python objects.
        'threading' is a low-overhead alternative that is most efficient for
        functions that release the Global Interpreter Lock: e.g. I/O-bound
        code or CPU-bound code in a few calls to native code that explicitly
        releases the GIL. Note that on some rare systems (such as pyodide),
        multiprocessing and loky may not be available, in which case joblib
        defaults to threading.

        In addition, if the ``dask`` and ``distributed`` Python packages are
        installed, it is possible to use the 'dask' backend for better
        scheduling of nested parallel calls without over-subscription and
        potentially distribute parallel calls over a networked cluster of
        several hosts.

        It is also possible to use the distributed 'ray' backend for
        distributing the workload to a cluster of nodes. See more details
        in the Examples section below.

        Alternatively the backend can be passed directly as an instance.

    n_jobs: int, default=None
        The maximum number of concurrently running jobs, such as the number
        of Python worker processes when ``backend="loky"`` or the size of the
        thread-pool when ``backend="threading"``.
        This argument is converted to an integer, rounded below for float.
        If -1 is given, `joblib` tries to use all CPUs. The number of CPUs
        ``n_cpus`` is obtained with :func:`~cpu_count`.
        For n_jobs below -1, (n_cpus + 1 + n_jobs) are used. For instance,
        using ``n_jobs=-2`` will result in all CPUs but one being used.
        This argument can also go above ``n_cpus``, which will cause
        oversubscription. In some cases, slight oversubscription can be
        beneficial, e.g., for tasks with large I/O operations.
        If 1 is given, no parallel computing code is used at all, and the
        behavior amounts to a simple python `for` loop. This mode is not
        compatible with `timeout`.
        None is a marker for 'unset' that will be interpreted as n_jobs=1
        unless the call is performed under a :func:`~parallel_config`
        context manager that sets another value for ``n_jobs``.
        If n_jobs = 0 then a ValueError is raised.

    verbose: int, default=0
        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.

    temp_folder: str or None, default=None
        Folder to be used by the pool for memmapping 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
          RAM disk 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, str, or None, optional, default='1M'
        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 memmapping of large arrays.

    mmap_mode: {None, 'r+', 'r', 'w+', 'c'}, default='r'
        Memmapping mode for numpy arrays passed to workers. None will
        disable memmapping, other modes defined in the numpy.memmap doc:
        https://numpy.org/doc/stable/reference/generated/numpy.memmap.html
        Also, see 'max_nbytes' parameter documentation for more details.

    prefer: str in {'processes', 'threads'} or None, default=None
        Soft hint to choose the default backend.
        The default process-based backend is 'loky' and the default
        thread-based backend is 'threading'. Ignored if the ``backend``
        parameter is specified.

    require: 'sharedmem' or None, default=None
        Hard constraint to select the backend. If set to 'sharedmem',
        the selected backend will be single-host and thread-based.

    inner_max_num_threads: int, default=None
        If not None, overwrites the limit set on the number of threads
        usable in some third-party library threadpools like OpenBLAS,
        MKL or OpenMP. This is only used with the ``loky`` backend.

    backend_params: dict
        Additional parameters to pass to the backend constructor when
        backend is a string.

    Notes
    -----
    Joblib tries to limit the oversubscription by limiting the number of
    threads usable in some third-party library threadpools like OpenBLAS, MKL
    or OpenMP. The default limit in each worker is set to
    ``max(cpu_count() // effective_n_jobs, 1)`` but this limit can be
    overwritten with the ``inner_max_num_threads`` argument which will be used
    to set this limit in the child processes.

    .. versionadded:: 1.3

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

    To use the 'ray' joblib backend add the following lines:

    >>> from ray.util.joblib import register_ray  # doctest: +SKIP
    >>> register_ray()  # doctest: +SKIP
    >>> with parallel_config(backend="ray"):  # doctest: +SKIP
    ...     print(Parallel()(delayed(neg)(i + 1) for i in range(5)))
    [-1, -2, -3, -4, -5]

    r*   r+   r,   r-   r.   r/   r0   r1   N)r+   r,   r-   r.   r/   r0   r1   inner_max_num_threadsc          	      X   t          t          dt                    | _         | j        ||	fi |
}||||||||d}| j                                        | _        | j                            d |                                D                        t          t          d| j                   d S )Nr?   )r+   r,   r-   r.   r/   r0   r1   r*   c                 D    i | ]\  }}t          |t                    ||S  )
isinstancer   ).0kvs      r%   
<dictcomp>z,parallel_config.__init__.<locals>.<dictcomp>  s-    QQQda
1i8P8PQQQQQr;   )
rG   rH   r6   old_parallel_config_check_backendrR   r\   updateitemssetattr)selfr*   r+   r,   r-   r.   r/   r0   r1   r]   backend_params
new_configs               r%   __init__zparallel_config.__init__k  s     $+8X?V#W#W %$%g/DWWWW &$"	
 	

  $7<<>>##QQj..00QQQ	
 	
 	
 	(D$899999r;   c           	         |t           d         u r&|t          |          dk    rt          d          |S t          |t                    r|t
          vr|t          v rt          |         } |             n|t          v rCt          j	        d| dt           dt          d           t
          t                   t
          |<   n9t          d	| d
t          t
                                                               t          |         di |}n"t          |          dk    rt          d          |'|j        j         d}|j        s
J |            ||_        |j        -| j        d         }|t           d         u rd}n|j        }||_        |S )Nr*   r   zrinner_max_num_threads and other constructor parameters backend_params are only supported when backend is not None.joblib backend '3' is not available on your system, falling back to .   
stacklevelInvalid backend: , expected one of zRConstructor parameters backend_params are only supported when backend is a string.z< does not accept setting the inner_max_num_threads argument.r`   )r6   lenrJ   ra   strrL   EXTERNAL_BACKENDSMAYBE_AVAILABLE_BACKENDSwarningswarnrM   UserWarningsortedkeysrP   rQ   supports_inner_max_num_threadsr]   rC   rf   )rk   r*   r]   rl   registerr$   parent_backendrC   s           r%   rg   zparallel_config._check_backend  s   -i888$0C4G4G!4K4K 0  
 Ngs## 	h&&///09HHJJJJ 888MK7 K K8GK K K##$	    )1(AHW%%$5G 5 5!(--//225 5  
 w'99.99GG>""Q&& :  
 !,$- 2 2 2  9>>3>>>,AG)  (!5i@N!8!CCC ! . <$1G!r;   c                     | j         S N)r\   rk   s    r%   	__enter__zparallel_config.__enter__  s    ##r;   c                 .    |                                   d S r   )
unregister)rk   typevalue	tracebacks       r%   __exit__zparallel_config.__exit__  s    r;   c                 <    t          t          d| j                   d S )Nr?   )rj   rH   rf   r   s    r%   r   zparallel_config.unregister  s    (D$<=====r;   )
rQ   
__module____qualname____doc__r6   rn   rg   r   r   r   r`   r;   r%   r\   r\      s        I IZ (	2": 'x0'	2+M:*<8)+6&x0'	2"": ": ": ": ":H8 8 8t$ $ $  > > > > >r;   r\   c                   ,     e Zd ZdZ	 d fd	Zd Z xZS )parallel_backenda  Change the default backend used by Parallel inside a with block.

    .. warning::
        It is advised to use the :class:`~joblib.parallel_config` context
        manager instead, which allows more fine-grained control over the
        backend configuration.

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

    By default the following backends are available:

    - 'loky': single-host, process-based parallelism (used by default),
    - 'threading': single-host, thread-based parallelism,
    - 'multiprocessing': legacy single-host, process-based parallelism.

    'loky' is recommended to run functions that manipulate Python objects.
    'threading' is a low-overhead alternative that is most efficient for
    functions that release the Global Interpreter Lock: e.g. I/O-bound code or
    CPU-bound code in a few calls to native code that explicitly releases the
    GIL. Note that on some rare systems (such as Pyodide),
    multiprocessing and loky may not be available, in which case joblib
    defaults to threading.

    You can also use the `Dask <https://docs.dask.org/en/stable/>`_ joblib
    backend to distribute work across machines. This works well with
    scikit-learn estimators with the ``n_jobs`` parameter, for example::

    >>> import joblib  # doctest: +SKIP
    >>> from sklearn.model_selection import GridSearchCV  # doctest: +SKIP
    >>> from dask.distributed import Client, LocalCluster # doctest: +SKIP

    >>> # create a local Dask cluster
    >>> cluster = LocalCluster()  # doctest: +SKIP
    >>> client = Client(cluster)  # doctest: +SKIP
    >>> grid_search = GridSearchCV(estimator, param_grid, n_jobs=-1)
    ... # doctest: +SKIP
    >>> with joblib.parallel_backend("dask", scatter=[X, y]):  # doctest: +SKIP
    ...     grid_search.fit(X, y)

    It is also possible to use the distributed 'ray' backend for distributing
    the workload to a cluster of nodes. To use the 'ray' joblib backend add
    the following lines::

     >>> from ray.util.joblib import register_ray  # doctest: +SKIP
     >>> register_ray()  # doctest: +SKIP
     >>> with parallel_backend("ray"):  # doctest: +SKIP
     ...     print(Parallel()(delayed(neg)(i + 1) for i in range(5)))
     [-1, -2, -3, -4, -5]

    Alternatively the 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 :class:`~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]

    Joblib also tries to limit the oversubscription by limiting the number of
    threads usable in some third-party library threadpools like OpenBLAS, MKL
    or OpenMP. The default limit in each worker is set to
    ``max(cpu_count() // effective_n_jobs, 1)`` but this limit can be
    overwritten with the ``inner_max_num_threads`` argument which will be used
    to set this limit in the child processes.

    .. versionadded:: 0.10

    See Also
    --------
    joblib.parallel_config: context manager to change the backend configuration.
    Nc                      t                      j        d|||d| | j        d | _        n| j        d         | j        d         f| _        | j        d         | j        d         f| _        d S )N)r*   r+   r]   r*   r+   r`   )superrn   rf   old_backend_and_jobsr\   new_backend_and_jobs)rk   r*   r+   r]   rl   rP   s        r%   rn   zparallel_backend.__init__$  s     	 	
"7	
 	
 		
 	
 	
 #+(,D%% (3(2)D%
  + *%
!!!r;   c                     | j         S r   )r   r   s    r%   r   zparallel_backend.__enter__:  s    ((r;   )r   N)rQ   r   r   r   rn   r   __classcell__rP   s   @r%   r   r     s^        N Nb 9=
 
 
 
 
 
,) ) ) ) ) ) )r;   r   get_contextJOBLIB_START_METHOD )methodc                   .    e Zd ZdZ	 ddZd Zd Zd ZdS )BatchedCallszCWrap a sequence of (func, args, kwargs) tuples as a single callableNc                     t          |          | _        t          | j                  | _        || _        t          |t                    r|\  | _        | _        n|d c| _        | _        ||ni | _	        d S r   )
listri   rx   _size_reducer_callbackra   tuplerH   _n_jobs_pickle_cache)rk   iterator_slicebackend_and_jobsreducer_callbackpickle_caches        r%   rn   zBatchedCalls.__init__M  sw     .))
__
!1&.. 	A*:'DM4<< +;D'DM4<-9-E\\2r;   c                     t          | j        | j                  5  d | j        D             cd d d            S # 1 swxY w Y   d S )N)r*   r+   c                 &    g | ]\  }}} ||i |S r`   r`   )rb   funcargskwargss       r%   
<listcomp>z)BatchedCalls.__call__.<locals>.<listcomp>_  s.    OOO.@dD&DD$)&))OOOr;   )r\   rH   r   ri   r   s    r%   __call__zBatchedCalls.__call__[  s     T]4<HHH 	P 	POODJOOO	P 	P 	P 	P 	P 	P 	P 	P 	P 	P 	P 	P 	P 	P 	P 	P 	P 	Ps   :>>c                 ~    | j         |                                   t          | j        | j        | j        fd | j        ffS r   )r   r   ri   rH   r   r   r   s    r%   
__reduce__zBatchedCalls.__reduce__a  sF    !-""$$$ Z$-6d>PQ
 	
r;   c                     | j         S r   )r   r   s    r%   __len__zBatchedCalls.__len__j  s
    zr;   )NN)rQ   r   r   r   rn   r   r   r   r`   r;   r%   r   r   J  si        MM UYN N N NP P P
 
 
    r;   r   DoneErrorPendingFc                 >    t           dS t          j        |           S )a  Return the number of CPUs.

    This delegates to loky.cpu_count that takes into account additional
    constraints such as Linux CFS scheduler quotas (typically set by container
    runtimes such as docker) and CPU affinity (for instance using the taskset
    command on Linux).

    Parameters
    ----------
    only_physical_cores : boolean, default=False
        If True, does not take hyperthreading / SMT logical cores into account.

    Nr   only_physical_cores)r   r   	cpu_countr   s    r%   r   r   w  s"     
zq>.ABBBBr;   c                     |sdS |dk    rdS | dk    rdS dd|z
  dz  z  }t          | |z            }t          | dz   |z            }t          |          t          |          k    S )	zReturns False for indices increasingly apart, the distance
    depending on the value of verbose.

    We use a lag increasing as the square of index
    TrF   Fr   g      ?   rs   r   )r   int)indexr,   scale
next_scales       r%   _verbosity_filterr     s~      t	2uzzuR'\a''G!!EuqyG+,,Jz??c%jj((r;   c                 p      fd}	  t          j                   |          }n# t          $ r Y nw xY w|S )z6Decorator used to capture the arguments of a function.c                      | |fS r   r`   )r   r   functions     r%   delayed_functionz!delayed.<locals>.delayed_function  s    v%%r;   )	functoolswrapsAttributeError)r   r   s   ` r%   delayedr     sf    & & & & &;49?8445EFF ; ; ;::;s   & 
33c                   H    e Zd ZdZd Zd Zd Zd Zd Zd Z	d Z
d	 Zd
 ZdS )BatchCompletionCallBacka  Callback to keep track of completed results and schedule the next tasks.

    This callable is executed by the parent process whenever a worker process
    has completed 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.

    It is assumed that this callback will always be triggered by the backend
    right after the end of a task, in case of success as well as in case of
    failure.
    c                     || _         || _        || _        |j        | _        d | _        d | _        |j        j        s	d | _	        d S t          | _	        d S r   )dispatch_timestamp
batch_sizeparallel_call_idparallel_call_id_completion_timeout_counterjobrH   supports_retrieve_callbackstatusTASK_PENDING)rk   r   r   r   s       r%   rn   z BatchCompletionCallBack.__init__  s\    "4$  ( 1+/(  ; 	' DKKK 'DKKKr;   c                     || _         dS )z)Register the object returned by `submit`.N)r   )rk   r   s     r%   register_jobz$BatchCompletionCallBack.register_job  s    r;   c                 d   | j         j        }|j        r|                                 S 	 |                    | j        |          }t          |t                    }n-# t          $ r }t          |t                    }Y d}~nd}~ww xY w| 
                    |           |                                 S )aH  Returns the raw result of the task that was submitted.

        If the task raised an exception rather than returning, this same
        exception will be raised instead.

        If the backend supports the retrieval callback, it is assumed that this
        method is only called after the result has been registered. It is
        ensured by checking that `self.status(timeout)` does not return
        TASK_PENDING. In this case, `get_result` directly returns the
        registered result (or raise the registered exception).

        For other backends, there are no such assumptions, but `get_result`
        still needs to synchronously retrieve the result before it can
        return it or raise. It will block at most `self.timeout` seconds
        waiting for retrieval to complete, after that it raises a TimeoutError.
        timeoutresultr   N)r   rH   r   _return_or_raiseretrieve_resultr   dict	TASK_DONEBaseException
TASK_ERROR_register_outcome)rk   r   r*   r   outcomer#   s         r%   
get_resultz"BatchCompletionCallBack.get_result  s    $ -(- 	+ ((***	8,,TXw,GGF&;;;GG 	8 	8 	8!J777GGGGGG	8w'''$$&&&s   2A 
B&BBc                 R    	 | j         t          k    r| j        | j        | `S # | `w xY wr   )r   r   _resultr   s    r%   r   z(BatchCompletionCallBack._return_or_raise  s9    	{j((l"<s   " &c                    || j         t          k    r| j         S t          j                    }| j        || _        || j        z
  |k    r7t	          t                      t                    }|                     |           | j         S )zGet the status of the task.

        This function also checks if the timeout has been reached and register
        the TimeoutError outcome when it is the case.
        Nr   )r   r   timer   r   r   r   r   )rk   r   nowr   s       r%   
get_statusz"BatchCompletionCallBack.get_status
  s     ?dk\99; ikk+3/2D,$22g==,..DDDG""7+++{r;   c                 `   | j         j        j        s|                                  dS | j         j        5  | j         j        | j        k    r	 ddd           dS | j         j        r	 ddd           dS  | j        |i |}ddd           n# 1 swxY w Y   |r|                                  dS dS )z@Function called by the callback thread after a job is completed.N)	r   rH   r   _dispatch_new_lockr   r   	_aborting_retrieve_result)rk   r   r   job_succeededs       r%   r   z BatchCompletionCallBack.__call__"  sm    }%@ 	   F
 ]  	C 	C
 }%)>>>	C 	C 	C 	C 	C 	C 	C 	C }& 	C 	C 	C 	C 	C 	C 	C 	C 2D14B6BBM	C 	C 	C 	C 	C 	C 	C 	C 	C 	C 	C 	C 	C 	C 	C"  	!     	! 	!s   BB2BBBc                    t          j                     | j        z
  }| j        j                            | j        |           | j        j        5  | j        xj        | j        z  c_        | j                                         | j        j	        | j        
                                 ddd           dS # 1 swxY w Y   dS )z1Schedule the next batch of tasks to be processed.N)r   r   r   rH   batch_completedr   r   n_completed_tasksprint_progress_original_iteratordispatch_next)rk   this_batch_durations     r%   r   z%BatchCompletionCallBack._dispatch_newC  s     #ikkD,CC..t@STTT ]  	. 	.M++t>++M((***}/;++---		. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	. 	.s   AB33B7:B7c                 $   	 | j         j                            |          }t          t          |          }n4# t
          $ r'}d|_        t          |t                    }Y d}~nd}~ww xY w|                     |           |d         t          k    S )zFetch and register the outcome of a task.

        Return True if the task succeeded, False otherwise.
        This function is only called by backends that support retrieving
        the task result in the callback thread.
        )r   r   Nr   r   )	r   rH   retrieve_result_callbackr   r   r   __traceback__r   r   )rk   outr   r   r#   s        r%   r   z(BatchCompletionCallBack._retrieve_resultQ  s    	8]+DDSIIF)F;;;GG 	8 	8 	8"AO!J777GGGGGG	8
 	w'''x J..s   58 
A)A$$A)c                    | j         j        5  | j        t          dfvr	 ddd           dS |d         | _        ddd           n# 1 swxY w Y   |d         | _        d| _        | j        t          k    rd| j         _        d| j         _        | j         j	        rdS | j         j        5  | j         j
                            |            ddd           dS # 1 swxY w Y   dS )ztRegister the outcome of a task.

        This method can be called only once, future calls will be ignored.
        Nr   r   T)r   r   r   r   r   r   r   
_exceptionr   return_ordered_jobsappend)rk   r   s     r%   r   z)BatchCompletionCallBack._register_outcomeg  s    ]  	, 	,{<"666	, 	, 	, 	, 	, 	, 	, 	, "(+DK	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	,
 x(  ;*$$'+DM$&*DM#=' 	F]  	- 	- M&&t,,,	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	- 	-s(   AAA	A	& CCCN)rQ   r   r   r   rn   r   r   r   r   r   r   r   r   r`   r;   r%   r   r     s         "' ' '0  "' "' "'H    0! ! !B. . ./ / /,- - - - -r;   r   c                 &    |t           | <   |r| adS dS )a  Register a new Parallel backend factory.

    The new backend can then be selected by passing its name as the backend
    argument to the :class:`~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)rL   rM   )namefactorymake_defaults      r%   r!   r!     s(     HTN  r;   r   c                 h    | dk    rdS t                      \  }}| |} |                    |           S )ae  Determine the number of jobs that can actually run in parallel

    n_jobs 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   N)r+   )r@   effective_n_jobs)r+   r*   backend_n_jobss      r%   r  r    sC    * {{q022G^~##6#222r;   c                   ,    e Zd ZdZed         ed         ded         ddded	         ed
         ed         ed         ed         f fd	Zd Zd Zd Zd Z	d Z
d Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd  Zd! Zd" Zd# Zd$ Zd% Zd& Z xZS )'Parallela/  Helper class for readable parallel mapping.

    Read more in the :ref:`User Guide <parallel>`.

    Parameters
    ----------
    n_jobs: int, default=None
        The maximum number of concurrently running jobs, such as the number
        of Python worker processes when ``backend="loky"`` or the size of
        the thread-pool when ``backend="threading"``.
        This argument is converted to an integer, rounded below for float.
        If -1 is given, `joblib` tries to use all CPUs. The number of CPUs
        ``n_cpus`` is obtained with :func:`~cpu_count`.
        For n_jobs below -1, (n_cpus + 1 + n_jobs) are used. For instance,
        using ``n_jobs=-2`` will result in all CPUs but one being used.
        This argument can also go above ``n_cpus``, which will cause
        oversubscription. In some cases, slight oversubscription can be
        beneficial, e.g., for tasks with large I/O operations.
        If 1 is given, no parallel computing code is used at all, and the
        behavior amounts to a simple python `for` loop. This mode is not
        compatible with ``timeout``.
        None is a marker for 'unset' that will be interpreted as n_jobs=1
        unless the call is performed under a :func:`~parallel_config`
        context manager that sets another value for ``n_jobs``.
        If n_jobs = 0 then a ValueError is raised.
    backend: str, ParallelBackendBase instance or None, default='loky'
        Specify the parallelization backend implementation.
        Supported backends are:

        - "loky" used by default, can induce some
          communication and memory overhead when exchanging input and
          output data with the worker Python processes. On some rare
          systems (such as Pyiodide), the loky backend may not be
          available.
        - "multiprocessing" previous process-based backend based on
          `multiprocessing.Pool`. Less robust than `loky`.
        - "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
          :func:`~register_parallel_backend`. This will allow you to
          implement a backend of your liking.

        It is not recommended to hard-code the backend name in a call to
        :class:`~Parallel` in a library. Instead it is recommended to set
        soft hints (prefer) or hard constraints (require) so as to make it
        possible for library users to change the backend from the outside
        using the :func:`~parallel_config` context manager.
    return_as: str in {'list', 'generator', 'generator_unordered'}, default='list'
        If 'list', calls to this instance will return a list, only when
        all results have been processed and retrieved.
        If 'generator', it will return a generator that yields the results
        as soon as they are available, in the order the tasks have been
        submitted with.
        If 'generator_unordered', the generator will immediately yield
        available results independently of the submission order. The output
        order is not deterministic in this case because it depends on the
        concurrency of the workers.
    prefer: str in {'processes', 'threads'} or None, default=None
        Soft hint to choose the default backend if no specific backend
        was selected with the :func:`~parallel_config` context manager.
        The default process-based backend is 'loky' and the default
        thread-based backend is 'threading'. Ignored if the ``backend``
        parameter is specified.
    require: 'sharedmem' or None, default=None
        Hard constraint to select the backend. If set to 'sharedmem',
        the selected backend will be single-host and thread-based even
        if the user asked for a non-thread based backend with
        :func:`~joblib.parallel_config`.
    verbose: int, default=0
        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 or None, default=None
        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'}, default='2*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 workers should never starve. Note that only basic
        arithmetic are allowed here and no modules can be used in this
        expression.
    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, dispatching
        calls to workers 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 or None, default=None
        Folder to be used by the pool for memmapping 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
          RAM disk 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="loky"`` or ``"multiprocessing"``.
    max_nbytes int, str, or None, optional, default='1M'
        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 memmapping of large arrays.
        Only active when ``backend="loky"`` or ``"multiprocessing"``.
    mmap_mode: {None, 'r+', 'r', 'w+', 'c'}, default='r'
        Memmapping mode for numpy arrays passed to workers. None will
        disable memmapping, other modes defined in the numpy.memmap doc:
        https://numpy.org/doc/stable/reference/generated/numpy.memmap.html
        Also, see 'max_nbytes' parameter documentation for more details.
    backend_kwargs: dict, optional
        Additional parameters to pass to the backend `configure` method.

    Notes
    -----

    This object uses workers 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 or concurrent.futures 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.

    Note that the intended usage is to run one call at a time. Multiple
    calls to the same Parallel object will result in a ``RuntimeError``

    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=10)(
    ...     delayed(sleep)(.2) for _ in range(10)) #doctest: +SKIP
    [Parallel(n_jobs=2)]: Done   1 tasks      | elapsed:    0.6s
    [Parallel(n_jobs=2)]: Done   4 tasks      | elapsed:    0.8s
    [Parallel(n_jobs=2)]: Done  10 out of  10 | elapsed:    1.4s 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 3 times before the parallel loop is initiated, and then
    called to generate new data on the fly:

    >>> 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 6 out of 6 | elapsed:  0.0s remaining: 0.0s
    [Parallel(n_jobs=2)]: Done 6 out of 6 | elapsed:  0.0s finished

    r+   r*   r   r,   Nz
2 * n_jobsautor-   r.   r/   r0   r1   c           
         t                                                       |t          d         }t          |||          \  }|j        }t          |d          | _        || _        || _        |dvrt          d| d          || _
        |dk    | _        |dk    | _        i |fd	|	d
f|df|
df|df|df|dffD             | _        t          | j        d
         t                    r"t!          | j        d
                   | j        d
<   t#          d| j        d         dz
            | j        d<   t$          t$          | j        d<   n0t'          t(          d          rt)          j                    | j        d<   |t          d         u s||}n7t          |t,                    r|j        ||_        nt'          |d          r+t'          |d          r|| j        d<   t/          |          }n|t0          vrg|t2          v r^t5          j        d| dt8           dt:          d           t0          t8                   t0          |<   t1          t8                   |          }ng	 t0          |         }nL# t<          $ r?}t          d|dt?          t0                                                               |d }~ww xY w ||          }t          |d          }||j!        }	 tE          |          }n# t          $ r t          d          w xY w|| _#        |dk    r#tI          |d d!          st          d"|z            |d#k    st          |tJ                    r|dk    r|| _&        nt          d$|z            t          |tN                    s| j        r*|j(        s#t          d%)                    ||                    tU          j+                    | _,        t[          j.                    | _/        ta                      | _1        te                      | _3        ti          j5                    | _6        d | _7        || _8        d!| _9        d!| _:        tw                      j<        | _=        d | _>        d S )&Nr+   )r0   r1   r,   r,   >   r   	generatorgenerator_unorderedzlExpected `return_as` parameter to be a string equal to "list","generator" or "generator_unordered", but got z	 instead.r   r  c                 :    i | ]\  }}|t          ||          S r`   )r:   )rb   r7   rc   r8   s      r%   re   z%Parallel.__init__.<locals>.<dictcomp>  s<     
 
 
E1 $UNA>>
 
 
r;   r.   r-   r/   r0   r1   r   2   contextr   r*   PoolLockrB   rp   rq   rr   rs   rt   rv   rw   z$n_jobs could not be converted to intr4   rE   Fz)Backend %s does not support shared memoryr  z8batch_size must be 'auto' or a positive integer, got: %rz(Backend {} does not support return_as={})?r   rn   r6   r>   rC   r:   r,   r   pre_dispatchrJ   	return_asreturn_generatorr  _backend_kwargsra   ry   r   maxDEFAULT_MP_CONTEXThasattrr   r   r   r   rL   r{   r|   r}   rM   r~   KeyErrorr   r   default_n_jobsr   r+   rG   r	   r   r   supports_return_generatorformatr   RLockr   collectionsdequer  set	_jobs_setr   _pending_outputsqueueQueue_ready_batchesr   rH   _running_managed_backendr
   hex_id	_call_ref)rk   r+   r*   r  r,   r   r  r   r-   r.   r/   r0   r1   backend_kwargsactive_backendrC   backend_factoryr#   r8   rP   s                     @r%   rn   zParallel.__init__  s%   " 	 >,X6F)<7G*
 *
 *
& '4(.)LL(HHHBK    
 # )V 3'+@@
 
 

 
 
 
  . -0,X&i(i(!
 
 
 
 d*<8#>> 	1@$\22 2D . +.a1Ei1PSU1U*V*VY').@D ++R'' 	?.0n.>.>D +-i888GO$GG!455 	C $,(5%Wf%% 	C''6*B*B 	C /6D +,=IIIGGH$$4L)L)LMC7 C C0?C C C	    !) 9HW/mLLLGG"*7"3    jwwx}} 7 7 79  
 &oMBBBG"6>8DD> +F	E[[FF 	E 	E 	ECDDD	Ek!!'';OQV*W*W!H7RSSS:j(#C#C
UV(DOOJZW   '#455 	*$ W-N  >EE    #**DJ$*,,DJ UUDN$(FFD!"'+--D%)D"   %77;s$   $I2 2
J;<:J66J;%K5 5Lc                 J    d| _         d| _        |                                  | S )NTF)r.  _calling_initialize_backendr   s    r%   r   zParallel.__enter__T  s(     $  """r;   c                     d| _         | j        r| j        r|                                  |                                  d S )NF)r.  r  r6  _abort_terminate_and_reset)rk   exc_type	exc_valuer   s       r%   r   zParallel.__exit__Z  sC     %  	T] 	KKMMM!!#####r;   c                 T   	  | j         j        d| j        | d| j        }| j        H| j         j        s<t          j        d                    | j         j	        j
        | j                             n7# t          $ r*}|j        | _         |                                 }Y d}~nd}~ww xY w|S )z?Build a process or thread pool and return the number of workers)r+   r   NzThe backend class {!r} does not support timeout. You have set 'timeout={}' in Parallel but the 'timeout' parameter will not be used.r`   )rH   	configurer+   r  r   supports_timeoutr|   r}   r#  rP   rQ   r   r*   r7  )rk   r+   r#   s      r%   r7  zParallel._initialize_backend`  s    	0,T], {T 595I F |'0N'@@F/8$,A A   ! 	0 	0 	0IDM--//FFFFFF	0
 s   A.A1 1
B%; B  B%c                 R    | j         r| j                             | j                  S dS )Nr   )rH   r  r+   r   s    r%   _effective_n_jobszParallel._effective_n_jobsv  s)    = 	?=11$+>>>qr;   c                     t          | j        d          r | j        r| j                                         d| _        | j        s| j                                         d S d S )N	stop_callF)r  rH   r6  rC  r.  	terminater   s    r%   r:  zParallel._terminate_and_reset{  si    4=+.. 	&4= 	&M##%%%$ 	&M##%%%%%	& 	&r;   c                 J   | j         rdS t          |          }| xj        |z  c_        | xj        dz  c_        t	          j                    }t          |||           }|                     |           | j                            ||          }|	                    |           dS )zQueue 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)
r   rx   n_dispatched_tasksn_dispatched_batchesr   r   _register_new_jobrH   submitr   )rk   batchr   r   batch_trackerr   s         r%   	_dispatchzParallel._dispatch  s     > 	FZZ
:-!!Q&!!!Y[[/0BJPTUU}--- m""5="AA""3'''''r;   c                     | j         r| j                            |           d S | j                            |           d S r   )r  r  r  r(  add)rk   rL  s     r%   rI  zParallel._register_new_job  sE     	.Jm,,,,,N}-----r;   c                 Z    |                      | j                  sd| _        d| _        dS dS )a  Dispatch 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   
_iteratingr   s    r%   r   zParallel.dispatch_next  s<     &&t'>?? 	+#DO&*D###	+ 	+r;   c           	         | j         rdS |                                 }| j        5  	 | j                            d          }n# t
          j        $ r | j        }||z  }	 t          t          j
        ||                    }n# t          $ r}t          |j        t
          j                  rd|_        t          d||           }|                     |           |                    t%          |t&                               Y d}~Y ddd           dS d}~ww xY wt)          |          dk    rY ddd           dS || j        u r7t)          |          |k     r$t-          dt)          |          d|z  z            }	n t-          dt)          |          |z            }	t/          dt)          |          |	          D ]Z}
t1          ||
|
|	z            | j                                        | j        | j                  }| j                            |           [| j                            d          }Y nw xY wt)          |          dk    r	 ddd           dS |                     |           	 ddd           dS # 1 swxY w Y   dS )	aT  Prefetch 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.

        F)blockNr   r   Tr   rF   )r   _get_batch_sizer   r,  getr*  Empty_cached_effective_n_jobsr   	itertoolsislice	Exceptionra   __context__	__cause__r   rI  r   r   r   rx   r   r  ranger   rH   get_nested_backendr   r   putrM  )rk   iteratorr   tasksr+   big_batch_sizerZ  r#   rL  final_batch_sizeis              r%   rQ  zParallel.dispatch_one_batch  s}    > 	5))++
Z D	 D	7=+//e/<<; 5= 5= 5= 6!+f!4 !)"28^"L"LMMFF       
 "!-== +
 '+$;Az4$P$PM**=999!33D*4U4U4UVVV4444GD	 D	 D	 D	 D	 D	 D	 D	*   v;;!## MD	 D	 D	 D	 D	 D	 D	 D	P  777CKK.<X<X (+1c&kkb6k.J'K'K$$'*1c&kkV.C'D'D$ q#f++/?@@ 3 3A(q1'7#77888::.*	 E '++E2222 +//e/<<k5=l 5zzQCD	 D	 D	 D	 D	 D	 D	 D	F u%%%ID	 D	 D	 D	 D	 D	 D	 D	 D	 D	 D	 D	 D	 D	 D	 D	 D	 D	sx   I<AI<H5!"BH5
DA5DH5I<DH50I<>C4H52I<4H55I<I<<J J c                 X    | j         dk    r| j                                        S | j         S )z-Returns the effective batch size for dispatchr  )r   rH   compute_batch_sizer   s    r%   rU  zParallel._get_batch_size  s-    ?f$$=33555 ?"r;   c                     | j         sdS | j         dk     rt          j        j        }nt          j        j        } |d|  d| d           dS )z=Display the message on stout or stderr depending on verbosityNr  [z]: 
)r,   sysstderrwritestdout)rk   r$   writers      r%   _printzParallel._print  s`     | 	F<"Z%FFZ%F#4##C###$$$$$r;   c                 @    | j         | j        k    o| j        p| j         S )z&Check if all tasks have been completed)r   rG  rR  r   r   s    r%   _is_completedzParallel._is_completed  s,    %)@@ 
O-t~F
 	
r;   c                     | j         sdS | j        0| j        dk    r%t          t          | j                            dz   }nd}t	          j                    | j        z
  }|                                 r@|                     d| j        | dd| j        | ddt          |           d	           dS | j
        t          | j        | j                   rdS d
t          |           }| j        }| j        -|                     d|| dd| j        | dd|            dS dt          d          |z   t          d          z
  z  }|                     d|| dd| |            dS | j        }| j        }|dk    r/||z
  dz   | j        z
  }|| j         z  dz   }|dz   |k    }	|	s||z  rdS |t!          |d          z  | j        |z
  z  }
|                     d|| dd|| ddt          |           dt          |
                      dS )zsDisplay the process of the parallel execution only a fraction
        of time, controlled by self.verbose.
        Nr   r      zDone dz out of z | elapsed: z	 finishedz| elapsed:  zout of rb  z tasks z remaining: )r,   n_tasksr   r   r   _start_timerr  rp  r   r   r   r   rH  rx   rG  _pre_dispatch_amountr  )rk   widthelapsed_timefmt_timer   padtotal_taskscursor	frequencyis_last_itemremaining_times              r%   r   zParallel.print_progress!  s   
 | 	F<#q(8(8%--..2EEEy{{T%55 /	KK>. >AA > >)5>@@> >$\22> > >  
 F $0 !:DLII F%6|%D%DFFH*E|'VE5VVVVVDL%VVVVVHVV     S^^e3c'llBCJE5JJJJJ3JJJKKKKK*E1Kzz %u,q043LL(DL8A=	$qyK7 6I#5 F*S]]:'%/N KK7u 7GG 7 7U 7GG 7 7/==7 7$^447 7    r;   c                     d| _         | j        }| j        s-t          |d          r| j        }|                    |           d| _        d S )NTabort_everything)ensure_ready)r   rH   _abortedr  r.  r  )rk   r*   r  s      r%   r9  zParallel._abort`  s\     -} 	@2D!E!E 	@  0L$$,$???r;   c                     d| _         |                     |          r| j        d u| _         |                     |          r	 |                     |          |dk    r	d| _         d S d S )NFall)rR  rQ  r   )rk   ra  r  s      r%   _startzParallel._startq  s      ""8,, 	B"5TADO%%h// 	 %%h// 	 5   $DOOO	 ! r;   c              #     	K   t          j                    }d}	 |                     ||           dV  | j                                        5  |                                 E d{V  ddd           n# 1 swxY w Y   n.# t          $ r d| _        |t          j                    k    rt          j	        d           d}| 	 G 	fddt           j
                  } |d                                           Y | j        rg n| j        }t          j                    | _        t                      | _        d| _        |s|                                  dS dS |                                  | j        r|                                   t,          $ r d| _        |                                   w xY w| j        rg n| j        }t          j                    | _        t                      | _        d| _        |s|                                  n^# | j        rg n| j        }t          j                    | _        t                      | _        d| _        |s|                                  w w xY wt/          |          d	k    rL|                                }|                    | j                  }|D ]}|V  t/          |          d	k    JdS dS )
z?Iterator returning the tasks' output as soon as they are ready.FNTa  A generator produced by joblib.Parallel has been gc'ed in an unexpected thread. This behavior should not cause major -issues but to make sure, please report this warning and your use case at https://github.com/joblib/joblib/issues so it can be investigated.c                       e Zd Z fdZdS )3Parallel._get_outputs.<locals>._GeneratorExitThreadc                                                       j        r                                                                  d S r   )r9  r  _warn_exit_earlyr:  )rk   	_parallels    r%   runz7Parallel._get_outputs.<locals>._GeneratorExitThread.run  sJ    !((***$5 9%66888!6688888r;   N)rQ   r   r   r  )r  s   r%   _GeneratorExitThreadr    s.        9 9 9 9 9 9 9r;   r  GeneratorExitThread)r  r   )r   	get_identr  rH   retrieval_context	_retrieveGeneratorExitr  r|   r}   Threadstartr  r%  r&  r'  r(  r-  r:  r9  r  r  r   rx   popleftr   r   )
rk   ra  r  dispatch_thread_iddetach_generator_exitr  _remaining_outputsbatched_resultsr   r  s
            @r%   _get_outputszParallel._get_outputs  sn     &022 %C	,KK,/// EEE0022 , ,>>+++++++++, , , , , , , , , , , , , , ,  *	 *	 *	 #DO "Y%8%:%:::'   )-% 	9 9 9 9 9 9 99+; 9 9 9 %$*?@@@FFHHH$ (,!FDJ$*,,DJ UUDN!DM( ,))+++++, ,% KKMMM$ (%%'''  	 	 	"DOKKMMM	 (,!FDJ$*,,DJ UUDN!DM( ,))+++ (,!FDJ$*,,DJ UUDN!DM( ,))++++, $%%))088::O-88FFO)  	 $%%))))))sP   3B A4(B 4A88B ;A8<B ?H A8F,9H AF,,H AI#c                     | j         rdS | j        | j        k     rdS | j        j        st          | j                  dk    rdS dS )z9Return True if we need to continue retrieving some tasks.Tr   F)rR  r   rG  rH   r   rx   r  r   s    r%   _wait_retrievalzParallel._wait_retrieval  sW     ? 	4 !D$;;;4 }7 	4:""tur;   c              #   R  K   d }|                                  r| j        r|                                  d S t          | j                  }| j        rK|dk    s/| j        d                             | j                  t          k    rt          j
        d           ng|dk    rV|"t          t          | j                  d           }||                    | j                   t          j
        d           |	d |_        d }| j        5  | j                                        }| j        s| j                            |           d d d            n# 1 swxY w Y   |                    | j                  }|D ]}| xj        dz  c_        |V  |                                  d S d S )Nr   r   g{Gz?r   )r  r   _raise_error_fastrx   r  r  r   r   r   r   sleepnextiterr(  r   r   r  remover   _nb_consumed)rk   timeout_control_jobnb_jobsr  r   s        r%   r  zParallel._retrieve  s&     """$$ B	
 ~ &&((($*ooG" )+ qLLJqM,,T\,BBlRRJt$$$ S
 A '.*.tDN/C/CT*J*J' '2'224<2HHH
4   $0 CG#?&*#
  ; ;"&*"4"4"6"6* ;N))/:::; ; ; ; ; ; ; ; ; ; ; ; ; ; ; .88FFO)  !!Q&!!E ""$$ B	 B	 B	 B	 B	s   ;EEEc                     | j         5  t          d | j        D             d          }ddd           n# 1 swxY w Y   ||                    | j                   dS dS )z3If we are aborting, raise if a job caused an error.c              3   :   K   | ]}|j         t          k    |V  d S r   )r   r   )rb   r   s     r%   	<genexpr>z-Parallel._raise_error_fast.<locals>.<genexpr><  s.      GGcjJ.F.F.F.F.F.FGGr;   N)r   r  r  r   r   )rk   	error_jobs     r%   r  zParallel._raise_error_fast6  s     Z 	 	GG
GGG I	 	 	 	 	 	 	 	 	 	 	 	 	 	 	    ..... ! s    488c                     | j         | j        z
  }|                                 }d}|r|| dz  }|s|dz  }|s|| j        | j         z
   dz  }|r|dz  }t	          j        |           dS dS )z?Warn the user if the generator is gc'ed before being consumned.r   z5 tasks have been successfully executed  but not used.z Additionally, zK tasks which were still being processed by the workers have been cancelled.z` You could benefit from adjusting the input task iterator to limit unnecessary computation time.N)r   r  rr  rG  r|   r}   )rk   ready_outputsis_completedr$   s       r%   r  zParallel._warn_exit_earlyE  s    .1BB))++ 	) WWWC   )(( 	*T-CC   C  	BC
 M#	 	r;   c              #     K   	 d| _         || _        |                                 dk    r/t          |          t          fdd          }d |D             }dV  |D ]f\  }}}| xj        dz  c_        | xj        dz  c_         ||i |}| xj        dz  c_        |                                  |V  | xj        dz  c_        gn$# t          $ r d| _
        d| _        d| _         w xY w	 d| _        d| _         d| _        |                                  dS # d| _        d| _         d| _        |                                  w xY w)zSeparate loop for sequential output.

        This simplifies the traceback in case of errors and reduces the
        overhead of calling sequential tasks with `joblib`.
        Tr   c                  H    t          t          j                             S r   )r   rY  rZ  )r   its   r%   <lambda>z1Parallel._get_sequential_output.<locals>.<lambda>n  s    E)"22z"B"BCC r;   r`   c              3   $   K   | ]}|D ]}|V  d S r   r`   )rb   rK  tasks      r%   r  z2Parallel._get_sequential_output.<locals>.<genexpr>p  s/      QQU5QQ4DQQQQQQQr;   NF)rR  r   rU  r  rH  rG  r   r   r  r   r  r   r  r-  )	rk   iterableiterable_batchedr   r   r   resr   r  s	          @@r%   _get_sequential_outputzParallel._get_sequential_output`  s     "	""DO&.D#--//JQ(^^#'CCCCCR$ $  RQ.>QQQ JJJ '/ ' '"dF))Q.))''1,''dD+F++&&!+&&##%%%			!!Q&!!!'  	 	 	"DO!DN DM		' "DM#DO&*D#!!!!! "DM#DO&*D#!!!!s   CC 
D !C,,D +Ec                 ,   t          | dt                                5  | j        rd}| j        du r|dz  }t	          |          d| _        ddd           n# 1 swxY w Y   d| _        d| _        d| _        d| _        d| _	        d| _
        d| _        dS )z9Reset the counters and flags used to track the execution.r   z+This Parallel instance is already running !Tz Before submitting new tasks, you must wait for the completion of all the previous tasks, or clean all references to the output generator.Nr   F)rG   r   r-  r  RuntimeErrorrH  rG  r   r  r  r   r  )rk   r$   s     r%   _reset_run_trackingzParallel._reset_run_tracking  s    
 T7KMM22 
	! 
	!} (C(D00>C
 #3''' DM
	! 
	! 
	! 
	! 
	! 
	! 
	! 
	! 
	! 
	! 
	! 
	! 
	! 
	! 
	! %&!"#!"   s   .AAAc                 l                                       t          |d          rt          |          nd _        t	          j                     _         j        s                                 }n                                 }|dk    r< 	                    |          }t          |            j        r|nt          |          S  j        5  t                      j         _        ddd           n# 1 swxY w Y   | _        t%           j        t(                    r fd}| _        | _         j        j        j        }|dk    rt1          d|z                                 d| d| d	           t           j        d
          r j                                         d _        t9          |          } j        }|dk    rd _        d _        nw| _        t          |d          r0tA          |!                    dtE          |                              }tG          |          x _        }tI          j%        | j                  }tM                       _'         (                    ||          }tS          j*        |           _+        t          |            j        r|nt          |          S )z)Main function to dispatch parallel tasks.r   Nr   c                  Z     j         j        j                             j                   d S r   )rH   _workers_temp_folder_managerset_current_contextr0  r   s   r%   _batched_calls_reducer_callbackz:Parallel.__call__.<locals>._batched_calls_reducer_callback  s4     &;OOH    r;   r   z%s has no active worker.zUsing backend z with z concurrent workers.
start_callTr  endswithr+   ),r  r  rx   rw  r   rx  r.  r7  rA  r  r  r  r   r   r
   r/  r   rX  ra   rH   r   r   rP   rQ   r  rp  r  r6  r  r  r   ry  r   replacery   r   rY  rZ  r   r   r  weakrefrefr1  )rk   r  r+   outputr  backend_namera  r  s   `       r%   r   zParallel.__call__  s    	  """(/)(D(DNs8}}}$9;;$ 	.--//FF++--FQ;; 00::FLLL!2D66VD Z 	( 	(!GGKDM	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	( 	(
 )/%dm[11 	E
 
 
 
 
 &ED" )/%}.7Q;;9LHIIIU\UUUUUVVV4=,// 	'M$$&&& >>(5  &*D#()D%%&.D#|Z00 V()=)=hF)T)TUU7:<7H7HHD% !'$2KLLH "VV""8\:: V,, 	V.@vvDLL@s   C22C69C6c                 0    | j         j        d| j        dS )Nz(n_jobs=))rP   rQ   r+   r   s    r%   __repr__zParallel.__repr__  s    "&."9"9"94;;;GGr;   )rQ   r   r   r   r6   rn   r   r   r7  rA  r:  rM  rI  r   rQ  rU  rp  rr  r   r9  r  r  r  r  r  r  r  r  r   r  r   r   s   @r%   r  r    s$       { {~ 'x0'	2'	2!+M:*<8)+6&x0'	2V V V V V Vp  $ $ $  ,  
& & &( ( (<. . .	+ 	+ 	+T T Tl# # #
% 
% 
%
 
 
= = =~  "$ $ $*M M M^  6D D DL/ / /  6(" (" ("T% % %NgA gA gARH H H H H H Hr;   r  )F)r   )Qr   
__future__r   r%  r   rY  osr*  rk  r   r   r|   r  
contextlibr   mathr   r   r   r   r   numbersr	   uuidr
   _multiprocessing_helpersr   _parallel_backendsr   r   r   r   r   r   r   _utilsr   r   diskr   loggerr   r   rL   rM   rN   rS   r{   	externalsr   localrH   r&   rz   r6   rI   rK   r:   r@   r>   r\   r   r  r  environrV  stripr   r   objectr   r   r   r   r   r   r   r   r!   r  r  r`   r;   r%   <module>r     s                       				  



        " " " " " " # # # # # # # # # # ( ( ( ( ( (             ( ( ( ( ( (                  ) ( ( ( ( ( ( ( ! ! ! ! ! ! - - - - - - - - "#  $ % -v6  >"8H"HVO$ 9?& & &" N  yt,,,id+++yq)))94000)$///---id+++yt,,,	 	  5 /   ( #8,#I.#I.    #8,#I.#I.O# O# O# O#dq> q> q> q> q> q> q> q>hh) h) h) h) h) h) h) h)`  
72} ;Z^^1266<<>>F$F+R^6:::! ! ! ! !6 ! ! !J 	
C C C C0) ) )&
 
 
V- V- V- V- V-f V- V- V-t   *3 3 3 3>]H ]H ]H ]H ]Hv ]H ]H ]H ]H ]Hr;   