
    .Pho                     `   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ZddlZddlZddl	Z	ddl
m
Z
 ddlmZ ddlmZmZmZmZmZ ddlmZ 	 e n# e$ r  ed          ZY nw xY w	 ddlZddlmZ n# e$ r dZY nw xY wdd	lmZ dd
lm Z  ddl!m"Z" ddl#m$Z$m%Z%m&Z& dZ' e(d          Z)ej*        ej+        z  ej,        z  Z-ej*        ej+        z  Z. e/            Z0d Z1d Z2d Z3e3e"j4        d<    G d d          Z5d Z6d$dZ7d Z8d Z9d Z:d Z; G d de<          Z=	 	 	 	 	 	 	 	 d%d!Z> G d" d#e<          Z?dS )&z/
Reducer using memory mapping for numpy arrays
    N)mmap)util)HIGHEST_PROTOCOLPicklingErrordumpsloadswhichmodule)uuid4)
as_strided   )make_memmap)delete_folder)resource_tracker)dumploadload_temporary_memmapz/dev/shmg    eAc                     ddl m} t          j        d                    t
          j                            |           t          j                                         |	                    | d           d S )Nr   )_resource_trackerzj[FINALIZER CALL] object mapping to {} about to be deleted, decrementing the refcount of the file (pid: {})file)
'externals.loky.backend.resource_trackerr   r   debugformatospathbasenamegetpidmaybe_unlink)filenamer   s     Z/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/joblib/_memmapping_reducer.py_log_and_unlinkr    ;   su    JJJJJJJ	;;A6GX&&	<
 <
   ""8V44444    c           	      4   t          j        d                    t          |           t	          |           t
          j                            | j                  t          j	                                         t          j        | t          | j                   d S )NzD[FINALIZER ADD] adding finalizer to {} (id {}, filename {}, pid  {}))r   r   r   typeidr   r   r   r   r   weakreffinalizer    )memmaps    r   add_maybe_unlink_finalizerr(   G   su    JNUULL"V**bg&6&6v&G&G	
 	
  
 V_fo>>>>>r!   c                    d}t          d|dz             D ]v}	 t          j        |             dS # t          $ rE t	          j        d                    |                      ||k    r t          j        d           Y ht          $ r Y sw xY wdS )a=  Wrapper around os.unlink with a retry mechanism.

    The retry mechanism has been implemented primarily to overcome a race
    condition happening during the finalizer of a np.memmap: when a process
    holding the last reference to a mmap-backed np.memmap/np.array is about to
    delete this array (and close the reference), it sends a maybe_unlink
    request to the resource_tracker. This request can be processed faster than
    it takes for the last reference of the memmap to be closed, yielding (on
    Windows) a PermissionError in the resource_tracker loop.
    
   r   z9[ResourceTracker] tried to unlink {}, got PermissionErrorg?N)
ranger   unlinkPermissionErrorr   r   r   timesleepFileNotFoundError)r   NUM_RETRIESretry_nos      r   unlink_filer3   P   s     K![1_--  	IhEE 		  		  		 JKRR   
 ;&&
3  	 	 	 D	 s   0AB
>	B
	B
r   c                   *    e Zd ZdZd Zd Zd Zd ZdS )_WeakArrayKeyMapa  A variant of weakref.WeakKeyDictionary for unhashable numpy arrays.

    This datastructure will be used with numpy arrays as obj keys, therefore we
    do not use the __get__ / __set__ methods to avoid any conflict with the
    numpy fancy indexing syntax.
    c                     i | _         d S N_dataselfs    r   __init__z_WeakArrayKeyMap.__init__{   s    


r!   c                 v    | j         t          |                   \  }} |            |urt          |          |S r7   )r9   r$   KeyError)r;   objrefvals       r   getz_WeakArrayKeyMap.get~   s<    :bgg&S355 3--
r!   c                      t          |          	  j                 \  }} |            |urt          |          n+# t          $ r  fd}t          j        ||          }Y nw xY w||f j        <   d S )Nc                     j         = d S r7   r8   )_keyr;   s    r   
on_destroyz(_WeakArrayKeyMap.set.<locals>.on_destroy   s    JsOOOr!   )r$   r9   r>   r%   r@   )r;   r?   valuer@   rE   rG   rF   s   `     @r   setz_WeakArrayKeyMap.set   s    gg	/Z_FCsuuC smm#    	/ 	/ 	/$ $ $ $ $ $ +c:..CCC	/ u*
3s   +? %A'&A'c                      t          d          )Nz"_WeakArrayKeyMap is not pickleable)r   r:   s    r   __getstate__z_WeakArrayKeyMap.__getstate__   s    @AAAr!   N)__name__
__module____qualname____doc__r<   rB   rI   rK    r!   r   r5   r5   s   s_             % % %$B B B B Br!   r5   c                 x    t          | dd          }|dS t          |t                    r| S t          |          S )z@Recursively look up the original np.memmap instance base if any.baseN)getattr
isinstancer   _get_backing_memmap)abs     r   rU   rU      sF    64  Ay t	At		 & #1%%%r!   c                    d}| t           j                            dd          }|t           j                            t
                    rt          t           d          r	 t          j        t
                    }|j        |j	        z  }|t          k    r\t
          }t           j                            ||           }t           j                            |          st          j        |           d}n# t          t          f$ r d}Y nw xY w|t          j                    }t           j                            t           j                            |                    }t           j                            ||           }||fS )a  Get the full path to a subfolder inside the temporary folder.

    Parameters
    ----------
    pool_folder_name : str
        Sub-folder name used for the serialization of a pool instance.

    temp_folder: str, optional
        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.

    Returns
    -------
    pool_folder : str
       full path to the temporary folder
    use_shared_mem : bool
       whether the temporary folder is written to the system shared memory
       folder or some other temporary folder.
    FNJOBLIB_TEMP_FOLDERstatvfsT)r   environrB   r   existsSYSTEM_SHARED_MEM_FShasattrrZ   f_bsizef_bavailSYSTEM_SHARED_MEM_FS_MIN_SIZEjoinmakedirsIOErrorOSErrortempfile
gettempdirabspath
expanduser)pool_folder_nametemp_folderuse_shared_mem	shm_statsavailable_nbytespool_folders         r   _get_temp_dirrp      sS   < Njnn%94@@7>>.// 	#GB	4J4J 	##J';<<	#,#4y7I#I #&CCC #7K"$',,{<L"M"MK7>>+66 1K000%)NW% # # # ## )++'//"'"4"4["A"ABBK',,{,<==K&&s   !BC1 1DDc                 $    t          |           duS )z?Return True if a is backed by some mmap buffer directly or not.N)rU   )rV   s    r   has_shareable_memoryrr      s    q!!--r!   c	           	          |dk    rd}|t          | ||||||          S t          | ||||||          }	t          |	||          S )z2Reconstruct an array view on a memory mapped file.zw+zr+N)dtypeshapemodeoffsetorderunlink_on_gc_collect)rt   ru   rw   rv   rx   ry   )ru   strides)r   r   )
r   rt   rv   rw   rx   ru   rz   total_buffer_lenry   rR   s
             r   _strided_from_memmapr|      s     t||!5
 
 
 	
 "!5
 
 
 $eW====r!   c           
         t          j        d                    | j        t	          j                                         	 ddlm} n# t          t          f$ r	 ddl
m} Y nw xY w ||           \  }} ||          d         }||z
  }||j        z  }|j        dk    r|j        d         rd}nd}| j        d         s| j        d         rd	}d	}	n| j        }||z
  | j        z  }	t           |j        | j        |j        ||| j        ||	d
f	fS )a  Pickling reduction for memmap backed arrays.

    a is expected to be an instance of np.ndarray (or np.memmap)
    m is expected to be an instance of np.memmap on the top of the ``base``
    attribute ancestry of a. ``m.base`` should be the real python mmap object.
    zC[MEMMAP REDUCE] reducing a memmap-backed array (shape, {}, pid: {})r   )byte_boundsr   F_CONTIGUOUSFCC_CONTIGUOUSNF)r   r   r   ru   r   r   numpy.lib.array_utilsr~   ModuleNotFoundErrorImportErrornumpyrw   ndimflagsrz   itemsizer|   r   rt   rv   )
rV   mr~   a_starta_endm_startrw   rx   rz   r{   s
             r   _reduce_memmap_backedr     si    	JMTTGRY[[	
 	
  
&5555555- & & &%%%%%%%%& ![^^NGUk!nnQGwF ahF 	vzzagn-z w~ ;!'."9 ; )!GO
: 	JGFG
	
 s    A A! A!c                     t          |           }t          |t          j                  r|j        t
          vrt          | |          S t          t          t          j	        |           t                    ffS )z5reduce a np.array or a np.memmap from a child processprotocol)rU   rT   npr'   r   JOBLIB_MMAPSr   r   r   asarrayr   )rV   r   s     r   reduce_array_memmap_backwardr   W  sh    AA!RY KAJl$B$B %Q*** bjmm6FGGGIJJr!   c                   @    e Zd ZdZ	 	 d	dZed             Zd Zd ZdS )
ArrayMemmapForwardReducera#  Reducer callable to dump large arrays to memmap files.

    Parameters
    ----------
    max_nbytes: int
        Threshold to trigger memmapping of large arrays to files created
        a folder.
    temp_folder_resolver: callable
        An callable in charge of resolving a temporary folder name where files
        for backing memmapped arrays are created.
    mmap_mode: 'r', 'r+' or 'c'
        Mode for the created memmap datastructure. See the documentation of
        numpy.memmap for more details. Note: 'w+' is coerced to 'r+'
        automatically to avoid zeroing the data on unpickling.
    verbose: int, optional, 0 by default
        If verbose > 0, memmap creations are logged.
        If verbose > 1, both memmap creations, reuse and array pickling are
        logged.
    prewarm: bool, optional, False by default.
        Force a read on newly memmapped array to make sure that OS pre-cache it
        memory. This can be useful to avoid concurrent disk access when the
        same data array is passed to different worker processes.
    r   Tc                 &   || _         || _        || _        t          |          | _        |dk    r&| j                            t                     | _        n|| _        || _        t                      | _
        t                      | _        || _        d S )Nauto)_max_nbytes_temp_folder_resolver
_mmap_modeintverbose_temp_folder
startswithr]   _prewarmr5   _memmaped_arraysrI   _temporary_memmaped_filenames_unlink_on_gc_collect)r;   
max_nbytestemp_folder_resolver	mmap_modery   r   prewarms          r   r<   z"ArrayMemmapForwardReducer.__init__  s     &%9"#7||f $ 1 < <=Q R RRDMM#DM 0 2 2-0UU*%9"""r!   c                 *    |                                  S r7   )r   r:   s    r   r   z&ArrayMemmapForwardReducer._temp_folder  s    ))+++r!   c                 ^    | j         d | j        | j        f}| j        | j        d}t
          ||fS )N)r   r   )r   r   r   r   r   r   )r;   argskwargss      r   
__reduce__z$ArrayMemmapForwardReducer.__reduce__  s?      $9ST|}
 
 )$66r!   c           	         t          |          }|*t          |t          j                  rt	          ||          S |j        j        s| j        |j        | j        k    r	 t          j
        | j                   t          j        | j        t                     n.# t          $ r!}|j        t          j        k    r|Y d }~nd }~ww xY w	 | j                            |          }n# t&          $ ru d                    t          j                    t-          t/          j                              t3                      j                  }| j                            ||           Y nw xY wt          j                            | j        |          }|| j        v}| j                            |           | j         rtC          j"        |d           |rtC          j"        |d           t          j        #                    |          stI          j%        d                    |j&        |j        |                     tO          ||          D ]}t          j        |tP                     | j)        r(tU          || j+                  ,                                 nPtI          j%        d                    |j&        |j        t          j        -                    |                               t\          || j+        | j         ffS tI          j%        d                    |j&        |j                             t^          ta          |tb                    ffS )Nz{}-{}-{}.pklr   zP[ARRAY DUMP] Pickling new array (shape={}, dtype={}) creating a new memmap at {})r   zN[ARRAY DUMP] Pickling known array (shape={}, dtype={}) reusing memmap file: {}zB[ARRAY DUMP] Pickling array (NO MEMMAPPING) (shape={},  dtype={}).r   )2rU   rT   r   r'   r   rt   	hasobjectr   nbytesr   rc   r   chmodFOLDER_PERMISSIONSre   errnoEEXISTr   rB   r>   r   r   r$   	threadingcurrent_threadr
   hexrI   r   rb   r   addr   r   registerr\   r   r   ru   r   FILE_PERMISSIONSr   r   r   maxr   r   r   r   r   )r;   rV   r   er   r   is_new_memmapdumped_filenames           r   __call__z"ArrayMemmapForwardReducer.__call__  s;   ""=Z2955=(A... !^	C ,4+++D-...*,>????   7el**G +****
7044Q77 7 7 7
 *00IKKI$<$>$>!?!?  %))!X666667 w||D$5x@@H
 %D,NNM .228<<<) < !)(F;;; < !)(F;;;7>>(++ 
228&!'82T2T   (,Ax'8'8 @ @OH_.>????= D T_===AACCC 
..4f"'*:*:8*D*D/ /   &4?D,FG  J$fQWag66   E!.>???ABBs+   #8B 
C&CCC& &A<E%$E%N)r   T)	rL   rM   rN   rO   r<   propertyr   r   r   rP   r!   r   r   r   h  s}         < : : : :, , , X,7 7 7"dC dC dC dC dCr!   r       .ArFTc                    | t                      } |t                      }t          [t          ||||||          }	|	| t          j        <   |	| t          j        <   t
          |t          j        <   t
          |t          j        <   | |fS )a	  Construct a pair of memmapping reducer linked to a tmpdir.

    This function manage the creation and the clean up of the temporary folders
    underlying the memory maps and should be use to get the reducers necessary
    to construct joblib pool or executor.
    N)r   )dictr   r   ndarrayr'   r   )
forward_reducersbackward_reducersr   r   r   r   r   ry   r   forward_reduce_ndarrays
             r   get_memmapping_reducersr     s    " 66  FF	~ ";  "
 "
 "
 (>$&<# )E"*%'C")$...r!   c                   <    e Zd ZdZd
dZd Zd Zd Zd Z	 dd	Z	dS )TemporaryResourcesManagera9  Stateful object able to manage temporary folder and pickles

    It exposes:
    - a per-context folder name resolving API that memmap-based reducers will
      rely on to know where to pickle the temporary memmaps
    - a temporary file/folder management API that internally uses the
      resource_tracker.
    Nc                     d | _         || _        d | _        t                      | _        t                      j        | _        i | _        |t                      j        }| 	                    |           d S r7   )
_current_temp_folder_temp_folder_root_use_shared_memr   _cached_temp_foldersr
   r   _id_finalizersset_current_context)r;   temp_folder_root
context_ids      r   r<   z"TemporaryResourcesManager.__init__L  sh    $(!!1#$(FF!77;
 J  ,,,,,r!   c                 >    || _         |                     |           d S r7   )_current_context_idregister_new_context)r;   r   s     r   r   z-TemporaryResourcesManager.set_current_context[  s$    #- !!*-----r!   c                     || j         v rd S d                    t          j                    | j        |          }t          || j                  \  }}|                     ||           || j         |<   d S )Nz!joblib_memmapping_folder_{}_{}_{})r   r   r   r   r   rp   r   register_folder_finalizer)r;   r   new_folder_namenew_folder_pathrE   s        r   r   z.TemporaryResourcesManager.register_new_context_  s     222F BHH	TXz O "/@V!W!WOQ**?JGGG4CD%j111r!   c                 &    | j         | j                 S )z@Return a folder name specific to the currently activated context)r   r   r:   s    r   resolve_temp_folder_namez2TemporaryResourcesManager.resolve_temp_folder_namev  s    ()ABBr!   c                     t          t          d          t          j        d           fd}t	          j        |          | j        |<   d S )Nr   folderc                      t          dg          j        } 	  | d           t          j        d           d S # t          $ r+ t          j        d                                         Y d S w xY w)Nr   )fromlistTallow_non_emptyr   z%Failed to delete temporary folder: {})
__import__r   r   
unregisterre   warningswarnr   )r   pool_module_namepool_subfolders    r   _cleanupzETemporaryResourcesManager.register_folder_finalizer.<locals>._cleanup  s     ' O+<   ndCCCC +NHEEEEE   ;BB>RR     s   "> 1A32A3)r	   r   r   r   atexitr   )r;   r   r   r   r   s    `  @r   r   z3TemporaryResourcesManager.register_folder_finalizer|  sf     '}oFF!.(;;;	 	 	 	 	 	( (.x'@'@$$$r!   Fc                    |1t          | j                  D ]}|                     |||           dS | j                            |          }|r-t          j                            |          rt	          j        |          D ]k}|r4t          j	        t          j        
                    ||          d           8t          j        t          j        
                    ||          d           l||z  }	 t          ||           | j                            |d           t          j	        |d           | j                            |d          }|t          j	        |           dS dS # t           $ r Y dS w xY wdS dS )z9Clean temporary resources created by a process-based poolN)forcer   r   r   r   )listr   _clean_temporary_resourcesrB   r   r   r\   listdirr   r   rb   r   r   popr   r   re   )r;   r   r   r   rk   r   	finalizers          r   r   z4TemporaryResourcesManager._clean_temporary_resources  s     #4#<==  
//e_ 0     
 377
CCK #rw~~k:: # "
; 7 7  H 
 )3GLLh??    )5GLLh??     5(!+OOOO-11*dCCC$/XFFF !% 0 4 4Z F FI ,))44444 -,     DD	?# # # #s   7A2E- -
E;:E;)NN)NFF)
rL   rM   rN   rO   r<   r   r   r   r   r   rP   r!   r   r   r   B  s         - - - -. . .D D D.C C CA A A@ =B0 0 0 0 0 0r!   r   r7   )NNNr   r   r   FT)@rO   r   r   r   statrf   r   r.   r   r%   r   multiprocessingr   pickler   r   r   r   r	   uuidr
   WindowsError	NameErrorr#   r   r   numpy.lib.stride_tricksr   r   	backportsr   diskr   externals.loky.backendr   numpy_pickler   r   r   r]   r   ra   S_IRUSRS_IWUSRS_IXUSRr   r   rI   r   r    r(   r3   _CLEANUP_FUNCSr5   rU   rp   rr   r|   r   r   objectr   r   r   rP   r!   r   <module>r     se      				                            M M M M M M M M M M M M M M      LL   4::LLL2222222   	BBB # " " " " "       4 4 4 4 4 4 ; ; ; ; ; ; ; ; ; ; "  !$C 
 \DL04<? <$,.  suu	5 	5 	5? ? ?  @ +6   '&B &B &B &B &B &B &B &BZ& & &"8' 8' 8' 8'v. . .
'> '> '>T9 9 9xK K K"hC hC hC hC hC hC hC hCX ,/ ,/ ,/ ,/^I I I I I I I I I Is$   A AA"
A- -A76A7