
    7Th67                         S r SSKrSSKrSSKrSSKJr   \  SSK	J
r
  SSKJr  SSKJrJr  SSKJrJr  SS	KJrJr   SSKr " S
 S\5      r " S S\5      r " S S\5      r " S S\5      rg! \ a    \" S5      r Nff = f! \ a    Sr NKf = f)a  Custom implementation of multiprocessing.Pool with custom pickler.

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

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

    N)sleep)BytesIO)Pool)HIGHEST_PROTOCOLPickler   )TemporaryResourcesManagerget_memmapping_reducers)assert_spawningmpc                   ,    \ rS rSrSrS\4S jrS rSrg)CustomizablePickler.   a}  Pickler that accepts custom reducers.

TODO python2_drop : can this be simplified ?

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

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

Nc                 D   [         R                  " XUS9  Uc  0 n[        [         S5      (       a$  [         R                  R	                  5       U l        O#[
        R                  R	                  5       U l        UR                  5        H  u  pEU R                  XE5        M     g )N)protocoldispatch)	r   __init__hasattrr   copycopyregdispatch_tableitemsregister)selfwriterreducersr   typereduce_funcs         C/var/www/auris/envauris/lib/python3.13/site-packages/joblib/pool.pyr   CustomizablePickler.__init__F   s{    9H7J'' $,,113DM #*"8"8"="="?D!)!1DMM$, "2    c                 x   ^ [        [        S5      (       a  U4S jnX0R                  U'   gTU R                  U'   g)z@Attach a reducer function to a given type in the dispatch table.r   c                 :   > T" U5      nU R                   " USU06  g )Nobj)save_reduce)r   r$   reducedr   s      r   
dispatcher0CustomizablePickler.register.<locals>.dispatcherZ   s     %c*  73S3r!   N)r   r   r   r   )r   r   r   r'   s     ` r   r   CustomizablePickler.registerU   s3    7J''4 #-MM$(3D%r!   )r   r   )	__name__
__module____qualname____firstlineno____doc__r   r   r   __static_attributes__ r!   r   r   r   .   s    . )-7G -4r!   r   c                   :    \ rS rSrSrS
S jrS rS rS rS r	S	r
g)CustomizablePicklingQueuec   a  Locked Pipe implementation that uses a customizable pickler.

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

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

See the standard library documentation on pickling for more details.
Nc                     X l         UR                  SS9u  U l        U l        UR	                  5       U l        [        R                  S:X  a  S U l        OUR	                  5       U l        U R                  5         g )NF)duplexwin32)
	_reducersPipe_reader_writerLock_rlocksysplatform_wlock_make_methods)r   contextr   s      r   r   "CustomizablePicklingQueue.__init__t   sY    !%,\\\%?"dllln<<7"DK!,,.DKr!   c                     [        U 5        U R                  U R                  U R                  U R                  U R
                  4$ N)r   r9   r:   r<   r?   r7   r   s    r   __getstate__&CustomizablePicklingQueue.__getstate__~   s/    dllDKKdnnUUr!   c                 f    Uu  U l         U l        U l        U l        U l        U R                  5         g rD   )r9   r:   r<   r?   r7   r@   )r   states     r   __setstate__&CustomizablePicklingQueue.__setstate__   s(    QVNt|T[$+t~r!   c                 @    U R                   R                  5       (       + $ rD   )r9   pollrE   s    r   emptyCustomizablePicklingQueue.empty   s    <<$$&&&r!   c                   ^ ^^^^^^ T R                   R                  =T l        mT R                  R                  T R                  R
                  smmUUU4S jnUT l        T R                  (       a  U 4S jmTT l        OT R                  R                  =T l        mT R                  c  TT l        g T R                  R                  T R                  R
                  smmUUU4S jnUT l        g )Nc                  H   > T " 5          T" 5       T" 5         $ ! T" 5         f = frD   r0   )racquirerecvrreleases   r   get4CustomizablePicklingQueue._make_methods.<locals>.get   s    Jv

s    	!c                    > [        5       n[        UTR                  5      R                  U 5        TR                  R                  UR                  5       5        g rD   )r   r   r7   dumpr:   
send_bytesgetvalue)r$   bufferr   s     r   send5CustomizablePicklingQueue._make_methods.<locals>.send   s<     #FDNN;@@E''(9:r!   c                 J   > T" 5          T" U 5      T" 5         $ ! T" 5         f = frD   r0   )r$   r\   wlock_acquirewlock_releases    r   put4CustomizablePicklingQueue._make_methods.<locals>.put   s    $9!OMOs    	")r9   rS   _recvr<   acquirereleaserU   r7   _sendr:   r\   r?   ra   )	r   rU   ra   rR   rS   rT   r\   r_   r`   s	   `  @@@@@@r   r@   'CustomizablePicklingQueue._make_methods   s     LL---
T![[00$++2E2E(	 >>;
 DJ $ 1 11DJ;;DH,0KK,?,?ATAT(M=$ DHr!   )	r9   rc   r7   r<   rf   r?   r:   rU   ra   rD   )r*   r+   r,   r-   r.   r   rF   rJ   rN   r@   r/   r0   r!   r   r2   r2   c   s!     V'$r!   r2   c                   8   ^  \ rS rSrSr SU 4S jjrS rSrU =r$ )PicklingPool   a  Pool implementation with customizable pickling reducers.

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

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

c                    > Uc
  [        5       nUc
  [        5       nX l        X0l        [        US9nUR                  U5        [        [
        U ]  " S0 UD6  g )N)	processesr0   )dict_forward_reducers_backward_reducersupdatesuperri   r   )r   rl   forward_reducersbackward_reducerskwargspoolargs	__class__s         r   r   PicklingPool.__init__   sU     ##v$ $!1"3),lD*6X6r!   c                     [        U S[        5      n[        XR                  5      U l        [        XR
                  5      U l        U R                  R                  U l        U R                  R                  U l
        g )N_ctx)getattrr   r2   rn   _inqueuero   	_outqueuerf   
_quick_putrc   
_quick_get)r   rA   s     r   _setup_queuesPicklingPool._setup_queues   sV    $+1';Q;QR27<S<ST----....r!   )ro   rn   r{   r|   r~   r}   )NNN)	r*   r+   r,   r-   r.   r   r   r/   __classcell__rv   s   @r   ri   ri      s    " HL7/ /r!   ri   c                   \   ^  \ rS rSrSr        SU 4S jjrU 4S jr\S 5       rSr	U =r
$ )MemmappingPool   a2  Process pool that shares large arrays to avoid memory copy.

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

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

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

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

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

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

c	                    > [        U5      n
Xl        [        U
R                  UUUUUSUS9u  pV[	        UUUS9nUR                  U	5        [        [        U ]"  " S0 UD6  g )NF)temp_folder_resolver
max_nbytes	mmap_moderr   rs   verboseunlink_on_gc_collectprewarm)rl   rr   rs   r0   )	r	   _temp_folder_managerr
   resolve_temp_folder_namerm   rp   rq   r   r   )r   rl   temp_folderr   r   rr   rs   r   r   rt   managerru   rv   s               r   r   MemmappingPool.__init__#  sy     ,K8$+! /F!(!A!A!-/!&	/
+ -/

 	nd,8x8r!   c                 T  > Sn[        U5       H  n [        [        U ]  5           O   U R                  R                  5         g ! [         aY  n[        U[        5      (       a9  [        S5        US-   U:X  a  [        R                  " SU-  5         S nAM   S nAM   S nAM  S nAff = f)N
   g?r   z@Failed to terminate worker processes in multiprocessing pool: %r)rangerq   r   	terminateOSError
isinstanceWindowsErrorr   warningswarnr   _clean_temporary_resources)r   	n_retriesierv   s       r   r   MemmappingPool.terminateI  s    	y!And57 "  	!!<<>  	a.. #J1u	) 8:;<  *	 /	s   A
B'AB""B'c                     [        U SS 5      b  U R                  $ U R                  R                  5       U l        U R                  $ )N_cached_temp_folder)rz   r   r   r   rE   s    r   _temp_folderMemmappingPool._temp_folder]  sJ     4.5A+++ ))BBD $ +++r!   )r   r   )NNg    .ArNNr   F)r*   r+   r,   r-   r.   r   r   propertyr   r/   r   r   s   @r   r   r      sC    J\ $9L?( , ,r!   r   )r.   r   r=   r   timer   r   	NameErrorr   ior   multiprocessing.poolr   pickler   r   _memmapping_reducerr	   r
   _multiprocessing_helpersr   r   numpynpImportErrorr   objectr2   ri   r   r0   r!   r   <module>r      s   
  
    & , S 924' 24jJ JZ#/4 #/LT,\ T,  :L  	Bs"   A. B .A?>A?BB