
    .Ph67                     @   d Z ddlZddlZddlZddlmZ 	 e n# e$ r  ed          ZY nw xY wddl	m
Z
 ddlmZ ddlmZmZ ddlmZmZ dd	lmZmZ 	 ddlZn# e$ r dZY nw xY w G d
 de          Z G d de          Z G d de          Z G d de          ZdS )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                   $    e Zd ZdZdefdZd ZdS )CustomizablePicklera  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                 T   t          j        | ||           |i }t          t           d          r$t           j                                        | _        n#t
          j                                        | _        |                                D ]\  }}|                     ||           d S )N)protocoldispatch)	r   __init__hasattrr   copycopyregdispatch_tableitemsregister)selfwriterreducersr   typereduce_funcs         K/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/joblib/pool.pyr   zCustomizablePickler.__init__F   s    v9999H7J'' 	@ $,1133DMM #*"8"="="?"?D!)!1!1 	- 	-D+MM$,,,,	- 	-    c                 h    t          t          d          rfd}|| j        |<   dS | j        |<   dS )z@Attach a reducer function to a given type in the dispatch table.r   c                 8     |          } | j         |d|i d S )Nobj)save_reduce)r   r"   reducedr   s      r   
dispatcherz0CustomizablePickler.register.<locals>.dispatcherZ   s0    %+c**  73S33333r   N)r   r   r   r   )r   r   r   r%   s     ` r   r   zCustomizablePickler.registerU   sU    7J'' 		44 4 4 4 4 #-DM$(3D%%%r   )__name__
__module____qualname____doc__r   r   r    r   r   r   r   .   sI         . )-7G - - - -4 4 4 4 4r   r   c                   2    e Zd ZdZddZd Zd Zd Zd ZdS )	CustomizablePicklingQueuea  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                    || _         |                    d          \  | _        | _        |                                | _        t          j        dk    rd | _        n|                                | _        | 	                                 d S )NF)duplexwin32)
	_reducersPipe_reader_writerLock_rlocksysplatform_wlock_make_methods)r   contextr   s      r   r   z"CustomizablePicklingQueue.__init__t   sq    !%,\\\%?%?"dlllnn<7""DKK!,,..DKr   c                 `    t          |            | j        | j        | j        | j        | j        fS N)r   r2   r3   r5   r8   r0   r   s    r   __getstate__z&CustomizablePicklingQueue.__getstate__~   s+    dlDKdnUUr   c                 p    |\  | _         | _        | _        | _        | _        |                                  d S r<   )r2   r3   r5   r8   r0   r9   )r   states     r   __setstate__z&CustomizablePicklingQueue.__setstate__   s4    QVNt|T[$+t~r   c                 6    | j                                          S r<   )r2   pollr=   s    r   emptyzCustomizablePicklingQueue.empty   s    <$$&&&&r   c                 D     j         j        x _         j        j         j        j        cfd}| _         j        r fd _        n j	        j
        x _         j        	 _        d S  j        j         j        j        cfd}| _        d S )Nc                  `                   	                            S #               w xY wr<   r*   )racquirerecvrreleases   r   getz4CustomizablePicklingQueue._make_methods.<locals>.get   s9    HJJJtvv







s   	! -c                     t                      }t          |j                                      |            j                            |                                           d S r<   )r   r   r0   dumpr3   
send_bytesgetvalue)r"   bufferr   s     r   sendz5CustomizablePicklingQueue._make_methods.<locals>.send   sR     #FDN;;@@EEE''(9(9:::::r   c                 b                  	  |                         S #               w xY wr<   r*   )r"   rP   wlock_acquirewlock_releases    r   putz4CustomizablePicklingQueue._make_methods.<locals>.put   s;    $499!MOOOOMMOOOOs   
" .)r2   rH   _recvr5   acquirereleaserJ   r0   _sendr3   rP   r8   rT   )	r   rJ   rT   rG   rH   rI   rP   rR   rS   s	   `  @@@@@@r   r9   z'CustomizablePicklingQueue._make_methods   s     L--
T![0$+2E(	 	 	 	 	 	 	 > 		2; ; ; ; ;
 DJJ $ 11DJ;DHHH,0K,?AT(M=$ $ $ $ $ $ $ DHHHr   r<   )	r&   r'   r(   r)   r   r>   rA   rD   r9   r*   r   r   r,   r,   c   sq             V V V  ' ' '$ $ $ $ $r   r,   c                   ,     e Zd ZdZ	 d fd	Zd Z xZS )PicklingPoola  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.

    Nc                     |t                      }|t                      }|| _        || _        t          |          }|                    |            t	          t
          |           j        di | d S )N)	processesr*   )dict_forward_reducers_backward_reducersupdatesuperrZ   r   )r   r\   forward_reducersbackward_reducerskwargspoolargs	__class__s         r   r   zPicklingPool.__init__   s     ##vv$ $!1"3),,,*lD!!*66X66666r   c                     t          | dt                    }t          || j                  | _        t          || j                  | _        | j        j        | _        | j        j	        | _
        d S )N_ctx)getattrr   r,   r^   _inqueuer_   	_outqueuerX   
_quick_putrU   
_quick_get)r   r:   s     r   _setup_queueszPicklingPool._setup_queues   sW    $++1'4;QRR27D<STT--..r   )NNN)r&   r'   r(   r)   r   rn   __classcell__rf   s   @r   rZ   rZ      s]         " HL7 7 7 7 7 7/ / / / / / /r   rZ   c                   T     e Zd ZdZ	 	 	 	 	 	 	 	 d
 fd	Z fdZed	             Z xZS )MemmappingPoola>  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.

    N    .Arr   Fc	           
          t          |          }
|
| _        t          |
j        |||||d|          \  }}t	          |||          }|                    |	            t          t          |           j        di | d S )NF)temp_folder_resolver
max_nbytes	mmap_moderb   rc   verboseunlink_on_gc_collectprewarm)r\   rb   rc   r*   )	r	   _temp_folder_managerr
   resolve_temp_folder_namer]   r`   ra   rr   r   )r   r\   temp_folderrw   rx   rb   rc   ry   r{   rd   managerre   rf   s               r   r   zMemmappingPool.__init__#  s     ,K88$+! /F!(!A!-/!&	/
 	/
 	/
++ -/
 
 

 	,nd##,88x88888r   c                 j   d}t          |          D ]}	 t          t          |                                             n[# t          $ rN}t          |t                    r/t          d           |dz   |k    rt          j	        d|z             Y d }~d }~ww xY w| j
                                         d S )N
   g?r   z@Failed to terminate worker processes in multiprocessing pool: %r)rangera   rr   	terminateOSError
isinstanceWindowsErrorr   warningswarnr|   _clean_temporary_resources)r   	n_retriesierf   s       r   r   zMemmappingPool.terminateI  s    	y!! 	 	And++55777 	 	 	a..  #JJJ1u	)) 8:;<  	 	!<<>>>>>s   '?
B	ABBc                 |    t          | dd           | j        S | j                                        | _        | j        S )N_cached_temp_folder)ri   r   r|   r}   r=   s    r   _temp_folderzMemmappingPool._temp_folder]  sG     4.55A++ )BBDD $ ++r   )NNrs   rt   NNr   F)	r&   r'   r(   r)   r   r   propertyr   ro   rp   s   @r   rr   rr      s        J J\ $9 $9 $9 $9 $9 $9L? ? ? ? ?( , , X, , , , ,r   rr   )r)   r   r6   r   timer   r   	NameErrorr   ior   multiprocessing.poolr   pickler   r   _memmapping_reducerr	   r
   _multiprocessing_helpersr   r   numpynpImportErrorr   objectr,   rZ   rr   r*   r   r   <module>r      s  
 
  



       LL   4::LLL       & % % % % % , , , , , , , , S S S S S S S S 9 9 9 9 9 9 9 9   	BBB24 24 24 24 24' 24 24 24jJ J J J J J J JZ#/ #/ #/ #/ #/4 #/ #/ #/LT, T, T, T, T,\ T, T, T, T, T,s    ,,A A#"A#