
    7Th^p                     \   S r SSKrSSKrSSKrSSKrSSKrSSKJrJr  SSK	J
r
  SSKJrJr  \
b   SSKJr  SSKJr  SS	KJrJr  SS
KJr  SSKJr   " S S\S9r " S S\5      r " S S\5      r " S S\5      r " S S\\5      r " S S\\\5      r " S S\\5      r  " S S\!5      r"S r#g)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                     ^  \ rS rSrSrSrSrSr\S 5       r	\S 5       r
Sr SU 4S jjr/ S	QrS
r\S 5       rSS jrSS jrS rSS jr SS jrS rS rS rS rS rSS jrS rS r\R>                  S 5       r \!S 5       r"Sr#U =r$$ ) ParallelBackendBase   zEHelper abc which defines all methods a ParallelBackend must implementr   Fc                     U R                   $ Nsupports_retrieve_callbackselfs    Q/var/www/auris/envauris/lib/python3.13/site-packages/joblib/_parallel_backends.pysupports_return_generator-ParallelBackendBase.supports_return_generator)       ...    c                     U R                   $ r   r   r   s    r   supports_timeout$ParallelBackendBase.supports_timeout-   r   r   Nc                 F   > [         TU ]  5         Xl        X l        X0l        g r   )super__init__nesting_levelinner_max_num_threadsbackend_kwargs)r   r#   r$   r%   	__class__s       r   r"   ParallelBackendBase.__init__3   s"     	*%:",r   )OMP_NUM_THREADSOPENBLAS_NUM_THREADSMKL_NUM_THREADSBLIS_NUM_THREADSVECLIB_MAXIMUM_THREADSNUMBA_NUM_THREADSNUMEXPR_NUM_THREADS
ENABLE_IPCc                     g)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_jobs$ParallelBackendBase.effective_n_jobsG       r   c                     [        S5      e)z'Deprecated: implement `submit` instead.zImplement `submit` instead.)NotImplementedErrorr   funccallbacks      r   apply_asyncParallelBackendBase.apply_asyncY   s    !"?@@r   c                 Z    [         R                  " S[        5        U R                  X5      $ )a  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DeprecationWarningr<   r9   s      r   submitParallelBackendBase.submit]   s)    : 	N	
 //r   c                     g)aX  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.
Nr1   r   outs     r   retrieve_result_callback,ParallelBackendBase.retrieve_result_callback   r6   r   c                 b    U R                   (       a  UR                  US9$ UR                  5       $ )zHook 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   rF   rJ   s      r   retrieve_result#ParallelBackendBase.retrieve_result   s*       7777++779r   c                 0    X l         U R                  U5      $ )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.
)parallelr4   )r   r3   rO   preferrequirer%   s         r   	configureParallelBackendBase.configure   s     !$$V,,r   c                     g)z;Call-back method called at the beginning of a Parallel callNr1   r   s    r   
start_callParallelBackendBase.start_call   r6   r   c                     g)z5Call-back method called at the end of a Parallel callNr1   r   s    r   	stop_callParallelBackendBase.stop_call   r6   r   c                     g)z0Shutdown the workers and free the shared memory.Nr1   r   s    r   	terminateParallelBackendBase.terminate   r6   r   c                     g) Determine the optimal batch sizer   r1   r   s    r   compute_batch_size&ParallelBackendBase.compute_batch_size   s    r   c                     g)1Callback indicate how long it took to run a batchNr1   )r   
batch_sizedurations      r   batch_completed#ParallelBackendBase.batch_completed   r6   r   c                     g)a  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.
Nr1   r   ensure_readys     r   abort_everything$ParallelBackendBase.abort_everything   s    , 	r   c                 Z    [        U SS5      S-   nUS:  a  [        US9S4$ [        US9S4$ )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_backend&ParallelBackendBase.get_nested_backend   s?      oq9A=1$=A4GG#-@$FFr   c                 2   U R                   n[        [        5       U-  S5      n0 nU R                   H5  nUc   [        R
                  R                  XS5      nOUn[        U5      XE'   M7     U R                  [        R
                  ;  a  SX@R                  '   U$ )a>  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   1)	r$   maxr   MAX_NUM_THREADS_VARSosenvironrK   strTBB_ENABLE_IPC_VAR)r   r3   explicit_n_threadsdefault_n_threadsenvvar	var_values          r   _prepare_worker_env'ParallelBackendBase._prepare_worker_env   s     "77	v 5q9
 ,,C!)JJNN3B	.	9~CH - """**4 ,/C''(
r   c              #      #    Sv   g7f)aL  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.
Nr1   r   s    r   retrieval_context%ParallelBackendBase.retrieval_context   s
      	s   c                  \    [        [        R                  " 5       [        R                  5      $ r   )
isinstance	threadingcurrent_thread_MainThreadr1   r   r   in_main_thread"ParallelBackendBase.in_main_thread  s    )224i6K6KLLr   )r%   r$   r#   rO   )NNr   r   NNNT)%__name__
__module____qualname____firstlineno____doc__default_n_jobssupports_inner_max_num_threadsr   propertyr   r   r#   r"   rv   rz   r   r4   r<   rB   rG   rL   rR   rU   rX   r[   r_   re   rj   rq   r   
contextlibcontextmanagerr   staticmethodr   __static_attributes____classcell__r&   s   @r   r   r      s    ON%*"
 "'/ / / / M 9=- & "A!0F"
 =A	-JD?@0G:    M Mr   r   )	metaclassc                   D    \ rS rSrSrSrSrSrSrS r	SS jr
S rS	 rS
rg)ro   i  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                 &    US:X  a  [        S5      eg?Determine the number of jobs which are going to run in parallelr   &n_jobs == 0 in Parallel has no meaningr   )
ValueErrorr2   s     r   r4   "SequentialBackend.effective_n_jobs  s    Q;EFFr   Nc                     [        S5      e)Schedule a func to be run-Should never be called for SequentialBackend.RuntimeErrorr9   s      r   rB   SequentialBackend.submit"  s    JKKr   c                     [        S5      e)Nr   r   rE   s     r   rG   *SequentialBackend.retrieve_result_callback&  s    JKKr   c                     SSK Jn  U" 5       $ )Nr   )get_active_backend)rO   r   )r   r   s     r   rq   $SequentialBackend.get_nested_backend)  s    0 "##r   r1   r   )r   r   r   r   r   uses_threadsr   r   supports_sharedmemr4   rB   rG   rq   r   r1   r   r   ro   ro     s6     L!&LL$r   ro   c                   H    \ rS rSrSrSrS rS rS rSS jr	S r
SS	 jrS
rg)PoolManagerMixini2  z,A helper class for managing pool of workers.Nc                 ~    US:X  a  [        S5      e[        b  Uc  gUS:  a  [        [        5       S-   U-   S5      nU$ r   )r   r   ru   r   r2   s     r   r4   !PoolManagerMixin.effective_n_jobs7  sF    Q;EFFZ6> aZq6115Fr   c                     U R                   b<  U R                   R                  5         U R                   R                  5         SU l         ggz#Shutdown the process or thread poolN)_poolcloser[   r   s    r   r[   PoolManagerMixin.terminateC  s8    ::!JJJJ  "DJ "r   c                     U R                   $ )z;Used by `submit` to make it possible to implement lazy initr   r   s    r   	_get_poolPoolManagerMixin._get_poolJ  s    zzr   c                 T    U R                  5       R                  [        U5      SUUS9$ )r   r1   )r;   error_callback)r   r<   r   r9   s      r   rB   PoolManagerMixin.submitN  s4    
 ~~++&t,#	 , 
 	
r   c                     [        U5      $ )z=Mimic concurrent.futures results, raising an error if needed.)r   )r   results     r   rG   )PoolManagerMixin.retrieve_result_callbackZ  s     :&AAr   c                     U R                  5         U(       aH  U R                  " SU R                  R                  U R                  S.U R                  R                  D6  gg)z@Shutdown the pool and restart a new one with the same parametersr3   rO   Nr1   )r[   rR   rO   r3   _backend_kwargsrh   s     r   rj   !PoolManagerMixin.abort_everythingb  sM    NN }}++ --// r   r   r   r   )r   r   r   r   r   r   r4   r[   r   rB   rG   rj   r   r1   r   r   r   r   2  s)    6E


Br   r   c                   N   ^  \ rS rSrSrSrSrSrSrU 4S jr	S r
S	 rS
 rSrU =r$ )AutoBatchingMixinim  z/A helper class for automagically batching jobs.皙?   r   g        c                 j   > [         TU ]  " S0 UD6  U R                  U l        U R                  U l        g )Nr1   )r!   r"   _DEFAULT_EFFECTIVE_BATCH_SIZE_effective_batch_size _DEFAULT_SMOOTHED_BATCH_DURATION_smoothed_batch_duration)r   kwargsr&   s     r   r"   AutoBatchingMixin.__init__~  s/    "6"%)%G%G"(,(M(M%r   c                    U R                   nU R                  nUS:  a  X R                  :  a}  [        XR                  -  U-  5      nUS-  n[	        SU-  U5      n[        US5      nX@l         U R                  R                  S:  a"  U R                  R                  SU SU S35        OX R                  :  ar  US:  al  [        XR                  -  U-  5      n[        SU-  S5      nX@l         U R                  R                  S:  a"  U R                  R                  SU SU S35        OUnXA:w  a  U R                  U l        U$ )	r^   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minru   rO   verbose_printMAX_IDEAL_BATCH_DURATIONr   )r   old_batch_sizebatch_durationideal_batch_sizerc   s        r   r_   $AutoBatchingMixin.compute_batch_size  sk   3366A.3P3P"P  #!>!>>O  ! Q/1ABJZ+J)3&}}$$*$$2>2B C**4Q8 ;;;RS@S  #!>!>>O  Q!1115J)3&}}$$*$$2>2B C**4Q8 (J' -1,Q,QD)r   c                     XR                   :X  a0  U R                  nX0R                  :X  a  UnOSU-  SU-  -   nX@l        gg)rb   g?r   N)r   r   r   )r   rc   rd   old_durationnew_durations        r   re   !AutoBatchingMixin.batch_completed  sN    333  88LDDD  (  #\1C(NB,8) 4r   c                 H    U R                   U l        U R                  U l        g)zWReset batch statistics to default values.

This avoids interferences with future jobs.
N)r   r   r   r   r   s    r   reset_batch_stats#AutoBatchingMixin.reset_batch_stats  s     
 &*%G%G"(,(M(M%r   )r   r   )r   r   r   r   r   r   r   r   r   r"   r_   re   r   r   r   r   s   @r   r   r   m  sA    9  #  ! %&!'*$N
9v9 N Nr   r   c                   4    \ rS rSrSrSrSrSrSS jrS r	Sr
g)	rp   i  aj  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.
TNc                     U R                  U5      nUS:X  a  [        [        U R                  S95      eX l        Xl        U$ z?Build a process or thread pool and return the number of workersr   rm   )r4   FallbackToBackendro   r#   rO   _n_jobs)r   r3   rO   r%   s       r   rR   ThreadingBackend.configure  s?    &&v.Q;#$5DDVDV$WXX r   c                 h    U R                   c  [        U R                  5      U l         U R                   $ )z{Lazily 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   ThreadingBackend._get_pool  s(     ::#DLL1DJzzr   )r   r   rO   )r   N)r   r   r   r   r   r   r   r   rR   r   r   r1   r   r   rp   rp     s$     "&Lr   rp   c                   R   ^  \ rS rSrSrSrSrU 4S jr    S	S jrU 4S jr	Sr
U =r$ )
MultiprocessingBackendi  a  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                   > [         c  g[         R                  " 5       R                  (       a0  US:w  a)  [        5       (       a  SnOSn[        R
                  " USS9  g[        R                  S:  a  US:w  a  [        R
                  " SSS9  gU R                  5       (       d,  U R                  S:X  d  US:w  a  [        R
                  " SSS9  g[        [        U ]3  U5      $ )	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.
r   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_workerr?   r@   r   _CURRENT_DEPTHr   r#   r!   r   r4   )r   r3   msgr&   s      r   r4   'MultiprocessingBackend.effective_n_jobs
  s     :&&{%''= =  ca0**Q.{4 
 %%''4+=+=+B{7 
 +TCFKKr   c                     U R                  U5      nUS:X  a  [        [        U R                  S95      e0 U R                  EUEn[
        R                  " 5         [        U40 UD6U l        X l	        U$ r   )
r4   r   ro   r#   r%   gccollectr   r   rO   )r   r3   rO   rP   rQ   memmapping_pool_kwargss         r   rR    MultiprocessingBackend.configure>  sw     &&v.Q;#$5DDVDV$WXX"
!!"
$"
 	

#FE.DE
 r   c                 J   > [         [        U ]  5         U R                  5         gr   )r!   r   r[   r   )r   r&   s    r   r[    MultiprocessingBackend.terminateV  s    $d57 r   )r   rO   r   )r   r   r   r   r   r   r   r4   rR   r[   r   r   r   s   @r   r   r     s:     "& %2Ll 0! !r   r   c                   Z    \ rS rSrSrSrSr     SS jrS rSS jr	S r
S	 rSS
 jrSrg)LokyBackendi\  z>Managing pool of workers with loky instead of multiprocessing.TNc                 P   U R                  U5      nUS:X  a  [        [        U R                  S95      e0 U R                  EUEnSU;   a  [        S5      eUc  U R                  R                  SS5      n[        U4UU R                  US9UR                  S.UD6U l
        X l        U$ )	z9Build a process executor and return the number of workersr   rm   rJ   ztThe 'timeout' parameter is not supported by the LokyBackend. Please use the `idle_worker_timeout` parameter instead.idle_worker_timeouti,  )r3   )rJ   r}   
context_id)r4   r   ro   r#   r%   r   rK   r
   r   _id_workersrO   )r   r3   rO   rP   rQ   r  memmapping_executor_kwargss          r   rR   LokyBackend.configureb  s     &&v.Q;#$5DDVDV$WXX&
!!&
(&
" 22J  &"&"5"5"9"9:OQT"U/
'(((7||	

 )
 !r   c                    US:X  a  [        S5      e[        b  Uc  g[        R                  " 5       R                  (       a0  US:w  a)  [	        5       (       a  SnOSn[
        R                  " USS9  gU R                  5       (       d,  U R                  S:X  d  US:w  a  [
        R                  " SSS9  gUS:  a  [        [        5       S-   U-   S5      nU$ )	r   r   r   r   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   r?   r@   r   r#   ru   r   )r   r3   r   s      r   r4   LokyBackend.effective_n_jobs  s    Q;EFFZ6> !(({%''= =  ca0%%''4+=+=+B{0 
 aZq6115Fr   c                 d    U R                   R                  U5      nUb  UR                  U5        U$ )r   )r  rB   add_done_callback)r   r:   r;   futures       r   rB   LokyBackend.submit  s/    %%d+$$X.r   c                 V     UR                  5       $ ! [         a    [        S5      ef = f)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   rG   $LokyBackend.retrieve_result_callback  s5    		==?"$ 	O 	s    (c                     U R                   b?  U R                   R                  R                  U R                  R                  SS9  S U l         U R                  5         g )NF)r  force)r  _temp_folder_manager_clean_temporary_resourcesrO   r  r   r   s    r   r[   LokyBackend.terminate  sP    ==$ MM..II==,,E J  !DM r   c                     U R                   R                  SS9  SU l         U(       a/  U R                  U R                  R                  U R                  S9  gg)zCShutdown the workers and restart a new one with the same parametersT)kill_workersNr   )r  r[   rR   rO   r3   rh   s     r   rj   LokyBackend.abort_everything  sD    T2NN$--"6"6NO r   )r  rO   )r   NNNNr   r   )r   r   r   r   r   r   r   rR   r4   rB   rG   r[   rj   r   r1   r   r   r  r  \  sC    H!%%)"  %N(T
!Pr   r  c                       \ rS rSrSrS rSrg)r   i  z<Raised when configuration should fallback to another backendc                     Xl         g r   backend)r   r  s     r   r"   FallbackToBackend.__init__  s    r   r  N)r   r   r   r   r   r"   r   r1   r   r   r   r     s
    Fr   r   c                  b     SSK Jn    U " 5         g! [         a     gf = f! [         a     gf = f)zDCheck whether the current function is executed inside a Dask worker.r   
get_workerFT)distributedr"  ImportErrorr   r!  s    r   r   r     s>    
*    s    ! 

..)$r   r   r   rw   r   r?   abcr   r   _multiprocessing_helpersr   _utilsr   r   multiprocessing.poolr	   executorr
   externals.lokyr   r   externals.loky.process_executorr   poolr   r   ro   objectr   r   rp   r   r  	Exceptionr   r   r1   r   r   <module>r/     s     	 	   ' (
 >/1 <F$pMG pMf$+ $D8v 8vgN gNT%')< %PZ!-/@BU Z!z}P#%8 }P@	 r   