
    .Ph^p                        d 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mZ ddl	m
Z
 ddlmZmZ e
 ddlmZ ddlmZ dd	lmZmZ dd
lmZ ddlmZ  G d de          Z G d de          Z G d de          Z G d de          Z G d dee          Z G d deee          Z G d dee          Z  G d de!          Z"d Z#dS )z,
Backends for embarrassingly parallel code.
    N)ABCMetaabstractmethod   )mp)*_retrieve_traceback_capturing_wrapped_call_TracebackCapturingWrapper)
ThreadPool)get_memmapping_executor)	cpu_countprocess_executor)ShutdownExecutorError)MemmappingPoolc                       e Zd ZdZdZdZdZed             Zed             Z	dZ
	 d fd	Zg dZd	Zed
             ZddZddZd ZddZ	 ddZd Zd Zd Zd Zd ZddZd Zd Zej        d             Ze d             Z! xZ"S )ParallelBackendBasezEHelper abc which defines all methods a ParallelBackend must implementr   Fc                     | j         S Nsupports_retrieve_callbackselfs    Y/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/joblib/_parallel_backends.pysupports_return_generatorz-ParallelBackendBase.supports_return_generator)       ..    c                     | j         S r   r   r   s    r   supports_timeoutz$ParallelBackendBase.supports_timeout-   r   r   Nc                 r    t                                                       || _        || _        || _        d S r   )super__init__nesting_levelinner_max_num_threadsbackend_kwargs)r   r    r!   r"   	__class__s       r   r   zParallelBackendBase.__init__3   s9     	*%:",r   )OMP_NUM_THREADSOPENBLAS_NUM_THREADSMKL_NUM_THREADSBLIS_NUM_THREADSVECLIB_MAXIMUM_THREADSNUMBA_NUM_THREADSNUMEXPR_NUM_THREADS
ENABLE_IPCc                     dS )a  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. 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.
        N r   n_jobss     r   effective_n_jobsz$ParallelBackendBase.effective_n_jobsG         r   c                      t          d          )z'Deprecated: implement `submit` instead.zImplement `submit` instead.)NotImplementedErrorr   funccallbacks      r   apply_asynczParallelBackendBase.apply_asyncY   s    !"?@@@r   c                 b    t          j        dt                     |                     ||          S )a8  Schedule a function to be run and return a future-like object.

        This method should return a future-like object that allow tracking
        the progress of the task.

        If ``supports_retrieve_callback`` is False, the return value of this
        method is passed to ``retrieve_result`` instead of calling
        ``retrieve_result_callback``.

        Parameters
        ----------
        func: callable
            The function to be run in parallel.

        callback: callable
            A callable that will be called when the task is completed. This callable
            is a wrapper around ``retrieve_result_callback``. This should be added
            to the future-like object returned by this method, so that the callback
            is called when the task is completed.

            For future-like backends, this can be achieved with something like
            ``future.add_done_callback(callback)``.

        Returns
        -------
        future: future-like
            A future-like object to track the execution of the submitted function.
        z@`apply_async` is deprecated, implement and use `submit` instead.)warningswarnDeprecationWarningr7   r4   s      r   submitzParallelBackendBase.submit]   s6    : 	N	
 	
 	
 h///r   c                     dS )a  Called within the callback function passed to `submit`.

        This method can customise how the result of the function is retrieved
        from the future-like object.

        Parameters
        ----------
        future: future-like
            The future-like object returned by the `submit` method.

        Returns
        -------
        result: object
            The result of the function executed in parallel.
        Nr-   r   outs     r   retrieve_result_callbackz,ParallelBackendBase.retrieve_result_callback   r1   r   c                 d    | j         r|                    |          S |                                S )a  Hook to retrieve the result when support_retrieve_callback=False.

        The argument `out` is the result of the `submit` call. This method
        should return the result of the computation or raise an exception if
        the computation failed.
        )timeout)r   get)r   r?   rB   s      r   retrieve_resultz#ParallelBackendBase.retrieve_result   s1       	7777+++7799r   c                 :    || _         |                     |          S )zReconfigure the backend and return the number of workers.

        This makes it possible to reuse an existing backend instance for
        successive independent calls to Parallel with different parameters.
        )parallelr0   )r   r/   rF   preferrequirer"   s         r   	configurezParallelBackendBase.configure   s     !$$V,,,r   c                     dS )z;Call-back method called at the beginning of a Parallel callNr-   r   s    r   
start_callzParallelBackendBase.start_call   r1   r   c                     dS )z5Call-back method called at the end of a Parallel callNr-   r   s    r   	stop_callzParallelBackendBase.stop_call   r1   r   c                     dS )z0Shutdown the workers and free the shared memory.Nr-   r   s    r   	terminatezParallelBackendBase.terminate   r1   r   c                     dS ) Determine the optimal batch sizer   r-   r   s    r   compute_batch_sizez&ParallelBackendBase.compute_batch_size   s    qr   c                     dS )1Callback indicate how long it took to run a batchNr-   )r   
batch_sizedurations      r   batch_completedz#ParallelBackendBase.batch_completed   r1   r   Tc                     dS )au  Abort any running tasks

        This is called when an exception has been raised when executing a task
        and all the remaining tasks will be ignored and can therefore be
        aborted to spare computation resources.

        If ensure_ready is True, the backend should be left in an operating
        state as future tasks might be re-submitted via that same backend
        instance.

        If ensure_ready is False, the implementer of this method can decide
        to leave the backend in a closed / terminated state as no new task
        are expected to be submitted to this backend.

        Setting ensure_ready to False is an optimization that can be leveraged
        when aborting tasks via killing processes from a local process pool
        managed by the backend it-self: if we expect no new tasks, there is no
        point in re-creating new workers.
        Nr-   r   ensure_readys     r   abort_everythingz$ParallelBackendBase.abort_everything   s	    , 	r   c                 ~    t          | dd          dz   }|dk    rt          |          dfS t          |          dfS )zBackend instance to be used by nested Parallel calls.

        By default a thread-based backend is used for the first level of
        nesting. Beyond, switch to sequential backend to avoid spawning too
        many threads on the host.
        r    r   r   r    N)getattrSequentialBackendThreadingBackend)r   r    s     r   get_nested_backendz&ParallelBackendBase.get_nested_backend   sQ      oq99A=1$=AAA4GG#-@@@$FFr   c                    | j         }t          t                      |z  d          }i }| j        D ]9}|!t          j                            ||          }n|}t          |          ||<   :| j        t          j        vr
d|| j        <   |S )af  Return environment variables limiting threadpools in external libs.

        This function return a dict containing environment variables to pass
        when creating a pool of process. These environment variables limit the
        number of threads to `n_threads` for OpenMP, MKL, Accelerated and
        OpenBLAS libraries in the child processes.
        r   N1)	r!   maxr   MAX_NUM_THREADS_VARSosenvironrC   strTBB_ENABLE_IPC_VAR)r   r/   explicit_n_threadsdefault_n_threadsenvvar	var_values          r   _prepare_worker_envz'ParallelBackendBase._prepare_worker_env   s     "7	v 5q99
 , 	& 	&C!)JNN30ABB		.	9~~CHH""*44 ,/C'(
r   c              #      K   dV  dS )a  Context manager to manage an execution context.

        Calls to Parallel.retrieve will be made inside this context.

        By default, this does nothing. It may be useful for subclasses to
        handle nested parallelism. In particular, it may be required to avoid
        deadlocks if a backend manages a fixed number of workers, when those
        workers may be asked to do nested Parallel calls. Without
        'retrieval_context' this could lead to deadlock, as all the workers
        managed by the backend may be "busy" waiting for the nested parallel
        calls to finish, but the backend has no free workers to execute those
        tasks.
        Nr-   r   s    r   retrieval_contextz%ParallelBackendBase.retrieval_context   s       	r   c                  X    t          t          j                    t          j                  S r   )
isinstance	threadingcurrent_thread_MainThreadr-   r   r   in_main_threadz"ParallelBackendBase.in_main_thread  s    )244i6KLLLr   )NNr   r   NNNT)#__name__
__module____qualname____doc__default_n_jobssupports_inner_max_num_threadsr   propertyr   r   r    r   re   ri   r   r0   r7   r<   r@   rD   rI   rK   rM   rO   rR   rW   r[   ra   ro   
contextlibcontextmanagerrq   staticmethodrw   __classcell__r#   s   @r   r   r      s       OON%*"
 "'/ / X/ / / X/ M 9=- - - - - -   &  ^"A A A A!0 !0 !0 !0F  "
 
 
 
 =A	- 	- 	- 	-J J JD D D? ? ?  @ @ @   0G G G  :     M M \M M M M Mr   r   )	metaclassc                   <    e Zd ZdZdZdZdZdZd Zd	dZ	d Z
d ZdS )
r_   zA ParallelBackend which will execute all batches sequentially.

    Does not use/create any threading objects, and hence has minimal
    overhead. Used when n_jobs == 1.
    TFc                 0    |dk    rt          d          dS )?Determine the number of jobs which are going to run in parallelr   &n_jobs == 0 in Parallel has no meaningr   )
ValueErrorr.   s     r   r0   z"SequentialBackend.effective_n_jobs  s    Q;;EFFFqr   Nc                      t          d          )Schedule a func to be run-Should never be called for SequentialBackend.RuntimeErrorr4   s      r   r<   zSequentialBackend.submit"  s    JKKKr   c                      t          d          )Nr   r   r>   s     r   r@   z*SequentialBackend.retrieve_result_callback&  s    JKKKr   c                 "    ddl m}  |            S )Nr   )get_active_backend)rF   r   )r   r   s     r   ra   z$SequentialBackend.get_nested_backend)  s%    000000 "!###r   r   )rz   r{   r|   r}   uses_threadsr   r   supports_sharedmemr0   r<   r@   ra   r-   r   r   r_   r_     s          L!&  L L L LL L L$ $ $ $ $r   r_   c                   >    e Zd ZdZdZd Zd Zd Zd
dZd Z	dd	Z
dS )PoolManagerMixinz,A helper class for managing pool of workers.Nc                     |dk    rt          d          t          |dS |dk     r"t          t                      dz   |z   d          }|S )r   r   r   Nr   )r   r   rd   r   r.   s     r   r0   z!PoolManagerMixin.effective_n_jobs7  sT    Q;;EFFFZ6> 1aZZq61155Fr   c                     | j         ;| j                                          | j                                          d| _         dS dS z#Shutdown the process or thread poolN)_poolcloserO   r   s    r   rO   zPoolManagerMixin.terminateC  sE    :!JJ  """DJJJ "!r   c                     | j         S )z;Used by `submit` to make it possible to implement lazy init)r   r   s    r   	_get_poolzPoolManagerMixin._get_poolJ  s
    zr   c                 r    |                                                      t          |          d||          S )r   r-   )r6   error_callback)r   r7   r   r4   s      r   r<   zPoolManagerMixin.submitN  s?    
 ~~++&t,,#	 , 
 
 	
r   c                      t          |          S )z=Mimic concurrent.futures results, raising an error if needed.)r   )r   results     r   r@   z)PoolManagerMixin.retrieve_result_callbackZ  s     :&AAAr   Tc                     |                                   |r+ | j        d| j        j        | j        d| j        j         dS dS )z@Shutdown the pool and restart a new one with the same parametersr/   rF   Nr-   )rO   rI   rF   r/   _backend_kwargsrY   s     r   r[   z!PoolManagerMixin.abort_everythingb  sj     	DN }+  -/    	 	r   r   ry   )rz   r{   r|   r}   r   r0   rO   r   r<   r@   r[   r-   r   r   r   r   2  s        66E
 
 
    

 

 

 

B B B     r   r   c                   D     e Zd ZdZdZdZdZdZ fdZd Z	d Z
d	 Z xZS )
AutoBatchingMixinz/A helper class for automagically batching jobs.皙?   r   g        c                 j     t                      j        di | | j        | _        | j        | _        d S )Nr-   )r   r   _DEFAULT_EFFECTIVE_BATCH_SIZE_effective_batch_size _DEFAULT_SMOOTHED_BATCH_DURATION_smoothed_batch_duration)r   kwargsr#   s     r   r   zAutoBatchingMixin.__init__~  s<    ""6"""%)%G"(,(M%%%r   c                 P   | j         }| j        }|dk    r|| j        k     r{t          || j        z  |z            }|dz  }t	          d|z  |          }t          |d          }|| _         | j        j        dk    r!| j                            d| d| d           ny|| j	        k    rl|dk    rft          || j        z  |z            }t          d|z  d          }|| _         | j        j        dk    r!| j                            d| d| d           n|}||k    r| j
        | _        |S )	rQ   r   r   r   
   zBatch computation too fast (zs.) Setting batch_size=.zBatch computation too slow ()r   r   MIN_IDEAL_BATCH_DURATIONintminrd   rF   verbose_printMAX_IDEAL_BATCH_DURATIONr   )r   old_batch_sizebatch_durationideal_batch_sizerU   s        r   rR   z$AutoBatchingMixin.compute_batch_size  s   36A.43P"P"P  #!>>O    ! Q/1ABBJZ++J)3D&}$**$$8> 8 8*48 8 8   d;;;RS@S@S  #!>>O    Q!11155J)3D&}$**$$8> 8 8*48 8 8   (J'' -1,QD)r   c                 n    || j         k    r)| j        }|| j        k    r|}nd|z  d|z  z   }|| _        dS dS )rT   g?r   N)r   r   r   )r   rU   rV   old_durationnew_durations        r   rW   z!AutoBatchingMixin.batch_completed  s\    333  8LtDDD  (  #\1C(NB,8D))) 43r   c                 6    | j         | _        | j        | _        dS )zgReset batch statistics to default values.

        This avoids interferences with future jobs.
        N)r   r   r   r   r   s    r   reset_batch_statsz#AutoBatchingMixin.reset_batch_stats  s     
 &*%G"(,(M%%%r   )rz   r{   r|   r}   r   r   r   r   r   rR   rW   r   r   r   s   @r   r   r   m  s        99  #  ! %&!'*$N N N N N
9 9 9v9 9 9 N N N N N N Nr   r   c                   ,    e Zd ZdZdZdZdZddZd ZdS )r`   a  A ParallelBackend which will use a thread pool to execute batches in.

    This is a low-overhead backend but it suffers from the Python Global
    Interpreter Lock if the called function relies a lot on Python objects.
    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).

    The actual thread pool is lazily initialized: the actual thread pool
    construction is delayed to the first call to apply_async.

    ThreadingBackend is used as the default backend for nested calls.
    Tr   Nc                     |                      |          }|dk    r"t          t          | j                            || _        || _        |S z?Build a process or thread pool and return the number of workersr   r]   )r0   FallbackToBackendr_   r    rF   _n_jobs)r   r/   rF   r"   s       r   rI   zThreadingBackend.configure  sN    &&v..Q;;#$5DDV$W$W$WXXX r   c                 P    | j         t          | j                  | _         | j         S )zLazily initialize the thread pool

        The actual pool of worker threads is only initialized at the first
        call to apply_async.
        )r   r	   r   r   s    r   r   zThreadingBackend._get_pool  s%     :#DL11DJzr   )r   N)	rz   r{   r|   r}   r   r   r   rI   r   r-   r   r   r`   r`     sT          "&L       r   r`   c                   D     e Zd ZdZdZdZ fdZ	 	 	 	 d	dZ fdZ xZ	S )
MultiprocessingBackenda  A ParallelBackend which will use a multiprocessing.Pool.

    Will introduce some communication and memory overhead when exchanging
    input and output data with the with the worker Python processes.
    However, does not suffer from the Python Global Interpreter Lock.
    TFc                    t           dS t          j                    j        r1|dk    r)t                      rd}nd}t	          j        |d           dS t          j        dk    r|dk    rt	          j        dd           dS |                                 s)| j	        dk    s|dk    rt	          j        d	d           dS t          t          |                               |          S )
zDetermine the number of jobs which are going to run in parallel.

        This also checks if we are attempting to create a nested parallel
        loop.
        Nr   zInside a Dask worker with daemon=True, setting n_jobs=1.
Possible work-arounds:
- dask.config.set({'distributed.worker.daemon': False})- set the environment variable DASK_DISTRIBUTED__WORKER__DAEMON=False
before creating your Dask cluster.zHMultiprocessing-backed parallel loops cannot be nested, setting n_jobs=1   
stacklevelr   zTMultiprocessing-backed parallel loops cannot be nested, below loky, setting n_jobs=1zVMultiprocessing-backed parallel loops cannot be nested below threads, setting n_jobs=1)r   current_processdaemoninside_dask_workerr9   r:   r   _CURRENT_DEPTHrw   r    r   r   r0   )r   r/   msgr#   s      r   r0   z'MultiprocessingBackend.effective_n_jobs
  s    :1& 	{{%'' = C=  ca00001*Q..{{4    
 1%%'' 	4+=+B+B{{7    
 1+T22CCFKKKr   r   Nc                     |                      |          }|dk    r"t          t          | j                            i | j        |}t          j                     t          |fi || _        || _	        |S r   )
r0   r   r_   r    r"   gccollectr   r   rF   )r   r/   rF   rG   rH   memmapping_pool_kwargss         r   rI   z MultiprocessingBackend.configure>  s     &&v..Q;;#$5DDV$W$W$WXXX"
!"
$"
 	
#FEE.DEE
 r   c                 ~    t          t          |                                            |                                  dS r   )r   r   rO   r   )r   r#   s    r   rO   z MultiprocessingBackend.terminateV  s8    $d++55777     r   rx   )
rz   r{   r|   r}   r   r   r0   rI   rO   r   r   s   @r   r   r     s          "& %2L 2L 2L 2L 2Ll    0! ! ! ! ! ! ! ! !r   r   c                   N    e Zd ZdZdZdZ	 	 	 	 	 ddZd ZddZd Z	d	 Z
dd
ZdS )LokyBackendz>Managing pool of workers with loky instead of multiprocessing.Tr   Nc                 b   |                      |          }|dk    r"t          t          | j                            i | j        |}d|v rt          d          || j                            dd          }t          |f||                     |          |j	        d	|| _
        || _        |S )
z9Build a process executor and return the number of workersr   r]   rB   ztThe 'timeout' parameter is not supported by the LokyBackend. Please use the `idle_worker_timeout` parameter instead.Nidle_worker_timeouti,  )r/   )rB   rl   
context_id)r0   r   r_   r    r"   r   rC   r
   ro   _id_workersrF   )r   r/   rF   rG   rH   r   memmapping_executor_kwargss          r   rI   zLokyBackend.configureb  s     &&v..Q;;#$5DDV$W$W$WXXX&
!&
(&
" 222J   &"&"5"9"9:OQT"U"U/
'(((77|	
 

 )
 
 !r   c                    |dk    rt          d          t          |dS t          j                    j        r1|dk    r)t	                      rd}nd}t          j        |d           dS |                                 s)| j        dk    s|dk    rt          j        d	d           dS |dk     r"t          t                      dz   |z   d          }|S )
r   r   r   Nr   zInside a Dask worker with daemon=True, setting n_jobs=1.
Possible work-arounds:
- dask.config.set({'distributed.worker.daemon': False})
- set the environment variable DASK_DISTRIBUTED__WORKER__DAEMON=False
before creating your Dask cluster.zRLoky-backed parallel loops cannot be called in a multiprocessing, setting n_jobs=1r   r   zKLoky-backed parallel loops cannot be nested below threads, setting n_jobs=1)r   r   r   r   r   r9   r:   rw   r    rd   r   )r   r/   r   s      r   r0   zLokyBackend.effective_n_jobs  s   Q;;EFFFZ6> 1!!( 	6{{%'' = C=  ca00001%%'' 
	64+=+B+B{{0    
 1aZZq61155Fr   c                 h    | j                             |          }||                    |           |S )r   )r   r<   add_done_callback)r   r5   r6   futures       r   r<   zLokyBackend.submit  s6    %%d++$$X...r   c                 f    	 |                                 S # t          $ r t          d          w xY w)z;Retrieve the result, here out is the future given by submita  The executor underlying Parallel has been shutdown. This is likely due to the garbage collection of a previous generator from a call to Parallel with return_as='generator'. Make sure the generator is not garbage collected when submitting a new job or that it is first properly exhausted.)r   r   r   )r   r   s     r   r@   z$LokyBackend.retrieve_result_callback  sH    		==??"$ 	 	 	O  	s    0c                     | j         2| j         j                            | j        j        d           d | _         |                                  d S )NF)r   force)r   _temp_folder_manager_clean_temporary_resourcesrF   r   r   r   s    r   rO   zLokyBackend.terminate  sZ    =$ M.II=,E J    !DM     r   c                     | j                             d           d| _         |r(|                     | j        j        | j                   dS dS )zCShutdown the workers and restart a new one with the same parametersT)kill_workersNr   )r   rO   rI   rF   r/   rY   s     r   r[   zLokyBackend.abort_everything  sZ    T222 	PNN$-"6NOOOOO	P 	Pr   )r   NNNNr   ry   )rz   r{   r|   r}   r   r   rI   r0   r<   r@   rO   r[   r-   r   r   r   r   \  s        HH!%%)"  % % % %N( ( (T     
! 
! 
!P P P P P Pr   r   c                       e Zd ZdZd ZdS )r   z<Raised when configuration should fallback to another backendc                     || _         d S r   )backend)r   r   s     r   r   zFallbackToBackend.__init__  s    r   N)rz   r{   r|   r}   r   r-   r   r   r   r     s)        FF    r   r   c                  p    	 ddl m}  n# t          $ r Y dS w xY w	  |              dS # t          $ r Y dS w xY w)zDCheck whether the current function is executed inside a Dask worker.r   
get_workerFT)distributedr   ImportErrorr   r   s    r   r   r     su    
*******   uu
t   uus   	 

' 
55)$r}   r   r   rf   rt   r9   abcr   r   _multiprocessing_helpersr   _utilsr   r   multiprocessing.poolr	   executorr
   externals.lokyr   r   externals.loky.process_executorr   poolr   r   r_   objectr   r   r`   r   r   	Exceptionr   r   r-   r   r   <module>r      s        				 				      ' ' ' ' ' ' ' ' ( ( ( ( ( (       
 >//////111111 <;;;;;;;FFFFFF$$$$$$pM pM pM pM pMG pM pM pM pMf$ $ $ $ $+ $ $ $D8 8 8 8 8v 8 8 8vgN gN gN gN gN gN gN gNT% % % % %')< % % %PZ! Z! Z! Z! Z!-/@BU Z! Z! Z!z}P }P }P }P }P#%8 }P }P }P@    	       r   