L i\dZddlZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl Z ddlZddlZddlmZddlmZmZmZddlmZmZmZmZmZddlmZmZmZdZ d Z!Gd d e"Z#d eiZ$d Z%ddZ&dZ'ejPZ)GddeZ*Gdde+Z,Gdde+Z-Gdde-Z.GddeZ/Gdde/Z0GddeZ1 d dZ2y)!zo A context object for caching a function's return value each time it is called with the same input arguments. N)hashing) CacheWarningFileSystemStoreBackendStoreBackendBase) filter_args format_callformat_signature get_func_code get_func_name)Logger format_timepformatz # first line:c|jtrG|jd}t|dt td}dj |dd}||fSd}||fS)zUExtract the first line information from the function code text if available.  rNr) startswithFIRST_LINE_TEXTsplitintlenjoin) func_code first_lines S/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/joblib/memory.pyextract_first_liner9snO,OOD) 1c/&:&<=> IIim,  j   j  ceZdZdZy)JobLibCollisionWarningz@Warn that there might be a collision between names of functions.N)__name__ __module__ __qualname____doc__rrrrFsJrrlocalct|tstdj||t |t stdj||t |<y)aExtend available store backends. The Memory, MemorizeResult and MemorizeFunc objects are designed to be agnostic to the type of store used behind. By default, the local file system is used but this function gives the possibility to extend joblib's memory pattern with other types of storage such as cloud storage (S3, GCS, OpenStack, HadoopFS, etc) or blob DBs. Parameters ---------- backend_name: str The name identifying the store backend being registered. For example, 'local' is used with FileSystemStoreBackend. backend: StoreBackendBase subclass The name of a class that implements the StoreBackendBase interface. z3Store backend name should be a string, '{0}' given.Nz;Store backend should inherit StoreBackendBase, '{0}' given.) isinstancestr ValueErrorformat issubclassr_STORE_BACKENDS) backend_namebackends rregister_store_backendr/Msd$ lC ( A H H V  j2BC I P P   %,OL!rc|i}t|tjr t|}t|tr|St|tr}d}t j j|}tjD]\}}||k(s |}|tdj|||j||||S|=tjdj|jj t"y)z7Return the correct store object for the given location.Nz#Unknown location {0} or backend {1}verbosebackend_optionszdInstantiating a backend using a {} as a location is not supported by joblib. Returning None instead.)r'pathlibPathr(rospath expanduserr,items TypeErrorr* configurewarningswarn __class__r UserWarning)r.locationr2r3obj backend_key backend_objs r_store_backend_factoryrDms(GLL)x=(,- Hc "77%%h/)8(=(=(? $ $K+%!m $ ;5<>DfGGLL!3!3!r rQr@rPr\s r__repr__zMemorizedResult.__repr__s?B;BB NN # #T%7%7%@%@ CG==  rcD|jj}d|d<|S)NrV__dict__copyrWstates r __getstate__zMemorizedResult.__getstate__s# ""$!k r)r%NrNN) r r!r"r#rOpropertyrFr[rbrUrjrlrsr$rrrKrKsnD#0    #$5 rrKc8eZdZdZdZdZdZdZdZdZ dZ y ) NotMemorizedResultzxClass representing an arbitrary value. This class is a replacement for MemorizedResult when there is no cache. valuevalidc ||_d|_y)NTrw)rWrxs rrOzNotMemorizedResult.__init__  rcH|jr |jStd)NzNo value stored.)ryrxrer\s rrUzNotMemorizedResult.gets :::: -. .rc d|_d|_yNFryrxr\s rrjzNotMemorizedResult.clearr{rc|jr:dj|jjt |j S|jjdzS)Nz{class_name}({value})) class_namerxz with no value)ryr*r>r rrxr\s rrlzNotMemorizedResult.__repr__!sQ ::*11>>22'$**:M2 >>**-== =rc4|j|jdS)Nrrr\s rrszNotMemorizedResult.__getstate__*sdjj99rc,|d|_|d|_y)Nryrxrrqs r __setstate__zNotMemorizedResult.__setstate__-s7^ 7^ rN) r r!r"r# __slots__rOrUrjrlrsrr$rrrvrv s, #I/ >:$rrvc<eZdZdZdZdZdZdZd dZdZ dZ y ) NotMemorizedFuncaNo-op object decorating a function. This class replaces MemorizedFunc when there is no cache. It provides an identical API but does not write anything on disk. Attributes ---------- func: callable Original undecorated function. c||_yrZrF)rWrFs rrOzNotMemorizedFunc.__init__Bs  rc&|j|i|SrZrrWargskwargss r__call__zNotMemorizedFunc.__call__Estyy$)&))rc8t|j|i|SrZrvrFrs rcall_and_shelvez NotMemorizedFunc.call_and_shelveHs!)$))T"r rFr\s rrlzNotMemorizedFunc.__repr__Ks#%%dnn&=&=tyyIIrcyrZr$rWr=s rrjzNotMemorizedFunc.clearNs rc*|j|i|ifSrZrrs rcallzNotMemorizedFunc.callRstyy$)&)2--rcyr~r$rs rcheck_call_in_cachez$NotMemorizedFunc.check_call_in_cacheUsrNT) r r!r"r#rOrrrlrjrrr$rrrr5s+ *>J .rrceZdZdZy)AsyncNotMemorizedFunccTKt|j|i|d{S7wrZrrs rrz%AsyncNotMemorizedFunc.call_and_shelve]s'!  4(B6(B"BCC"Bs (& (N)r r!r"rr$rrrr\sDrrceZdZdZ ddZdZdZedZdZ dZ d Z d Z d Z d Zd ZddZddZdZddZdZdZddZddZddZddZdZy) MemorizedFuncajCallable object decorating a function for caching its return value each time it is called. Methods are provided to inspect the cache or clean it. Attributes ---------- func: callable The original, undecorated, function. location: string The location of joblib cache. Depends on the store backend used. backend: str Type of store backend for reading/writing cache files. Default is 'local', in which case the location is the path to a disk storage. ignore: list or None List of variable names to ignore when choosing whether to recompute. mmap_mode: {None, 'r+', 'r', 'w+', 'c'} The memmapping mode used when loading from cache numpy arrays. See numpy.load for the meaning of the different values. compress: boolean, or integer Whether to zip the stored data on disk. If an integer is given, it should be between 1 and 9, and sets the amount of compression. Note that compressed arrays cannot be read by memmapping. verbose: int, optional The verbosity flag, controls messages that are issued as the function is evaluated. cache_validation_callback: callable, optional Callable to check if a result in cache is valid or is to be recomputed. When the function is called with arguments for which a cache exists, the callback is called with the cache entry's metadata as its sole argument. If it returns True, the cached result is returned, else the cache for these arguments is cleared and the result is recomputed. Nc tj|||_||_||_| |_t ||_||ng|_||_ t|||t|||_ |j&|jj|jg||ntj|_ t!j"||t'j(|rNt+j,j/|} | j1ddd} t3j4dd| } n |j6} d| z|_d|_d|_y#t$$rYwxYw) NcompressrRr1rz rz.zMemoized version of %s)r rOrRrrFcache_validation_callbackrIr[ignore_verboserDdictrQstore_cached_func_codetimerV functoolsupdate_wrapper Exceptioninspect isfunctionpydocTextDocdocumentreplaceresubr#_func_code_info _func_code_id) rWrFr@r.rrRrr2rVrdocs rrOzMemorizedFunc.__init__sF "   )B&-d3 & 2f  4   (iH      )    5 5t||n E&/&;   $ $T4 0   d #--/**40C++dFA.C&&"c*C,,C/#5 #!   sE!! E-,E-c |jdsy|jj|sy|jj|}|j-|j |s|jj |yy)aCheck if the function call is cached and valid for given arguments. - Compare the function code with the one from the cached function, asserting if it has changed. - Check if the function call is present in the cache. - Call `cache_validation_callback` for user define cache validation. Returns True if the function call is in cache and can be used, and returns False otherwise.  stacklevelFT)_check_previous_func_coderQ contains_itemrTrrirWrXrSs r_is_in_cache_and_validz$MemorizedFunc._is_in_cache_and_valids}---;!!//8%%227;  * * 6228<    ) )' 2rc  |j|i|}|j|f}t|j\}}|jj |jg}|d} |j dk\rqtjtjt|jg|i|\}} |jtjd|d| d|d| d |j|rv|r|j|ifS t!j } |j#|} |j d kDr(|j%t!j | z d | ifS|j d kDr|j)d|d|d| |j1||||S#t&$rRt|jg|i|\}} |j)d j+| t-j.YwxYw)aCall wrapped function and cache result, or read cache if available. This function returns the wrapped function output or a reference to the cached result. Arguments: ---------- args, kwargs: list and dict input arguments for wrapped function shelving: bool True when called via the call_and_shelve function. Returns ------- output: Output of the wrapped function if shelving is false, or a MemorizedResult reference to the value if shelving is true. metadata: dict containing the metadata associated with the call. r@)levelz" Querying z( with signature z*. (argument hash z1) The store location is z. rz cache loaded )contextz*Exception while loading results for {} {} zComputing func z, argument hash z in location ) _get_args_idr[r rFrQget_cached_func_inforlogging basicConfigINFOr infotextwrapdedentr_get_memorized_resultr _load_item_print_durationrr=r* traceback format_exc_call) rWrrshelvingrbrX_ func_name func_infor@ signature start_timeoutputs r _cached_callzMemorizedFunc._cached_calls ,$$##T4V4<<)$TYY/ 9&&;;T\\NK Z( ==B    gll 3+DIIGGGLAy II""+-" $((/y1//7j9     & &w /11':B>> !YY[ 1==1$(( j0/)rz! ==2  II!),qAArcf|j}|jj}d|d<d|d<|S)NrVr)rrorp)rWrrrs rrszMemorizedFunc.__getstate__as>    ""$!k"&o rc`|j|j|i|f}|j|S)aACheck if the function call is cached and valid for given arguments. Does not call the function or do any work besides function inspection and argument hashing. - Compare the function code with the one from the cached function, asserting if it has changed. - Check if the function call is present in the cache. - Call `cache_validation_callback` for user define cache validation. Returns ------- is_call_in_cache: bool Whether or not the function call is in cache and can be used. )r[rrrWrrrXs rrz!MemorizedFunc.check_call_in_cacheqs6 <N) rrQrr[rrFr r_FUNCTION_HASHESr:)rWrris_named_callable func_hashs r_write_func_codezMemorizedFunc._write_func_codes ?J "JJ  114<<.)L DIIz * Otyy/A/AZ/O  )I .7 +    s8B BBc Z |jtvr'|j}|t|jk(ry|j\}}} t |j j|jg\}}||k(ryt|jdd\}} ||cxk(rdk(sn| dk(rJ|dk(sdj| ||} n| } tjt!dj| |||k(s|t"j$j'|rt|jd \}} t)|j+d } t-j.|5} | j1|d z |d z | zd z } d d d d j3 } | j5|j5k(}n|j7d}|r)tjt!d| ||| ||fz||j8dkDrEt|jd \}} |jdj| |j|j;dy#t$rY:wxYw#ttf$r|j||YywxYw#1swYxYw)zx stacklevel is the depth a which this function is called, to issue useful warnings to the user. TF) resolv_aliaswin_charactersrrz {0} ({1}:{2})z0Cannot detect name collisions for function '{0}'rN)rrrrz ""77G- )M> I % % IIE% 9 Z -2 -j1H##2#9#9{J$ $- MM&FMM( &  + 0Gww~~k*,TYYUK 9  56 ]];/1() &*^a-?)-Ka-O)%%'GG,=$>!%,,.-2F2F2HH#&1%;%;K%H"! *8&'*%'&    *$ ==2 (GLAy II?FFt||   m   !   ! !)Z 8 Js/8I) 2I9+ J ) I65I69!JJ J*c|j}|jdkDr|r|jd|z|jj |g|j \}}}|j ||y)zEmpty the function's cache.rz(Clearing function cache identified by %sN)r[rr=rQ clear_pathrr)rWr=r[rrrs rrjzMemorizedFunc.clearsk,, ==1  II@7J K %%  $(#6#6 1j i4rcd|j|j|i|f}|j|||S)aForce the execution of the function with the given arguments. The output values will be persisted, i.e., the cache will be updated with any new values. Parameters ---------- *args: arguments The arguments. **kwargs: keyword arguments Keyword arguments. Returns ------- output : object The output of the function call. metadata : dict The metadata associated with the call. )r[rrrs rrzMemorizedFunc.call#s:(<> %__Wh7Fxrcbtj}t|j|j||}t d|j D}|||d} |j j|| tj|z } | |kDrtjd| zd| S)aSave a small summary of the call using json format in the output directory. output_dir: string directory where to write metadata. duration: float time taken by hashing input arguments, calling the wrapped function and persisting its output. args, kwargs: list and dict input arguments for wrapped function this_duration_limit: float Max execution time for this function before issuing a warning. c3<K|]\}}|t|fywrZ)repr).0kvs r z/MemorizedFunc._persist_input..jsI41a1d1g,Is)rN input_argsrzPersisting input arguments took %.2fs to run.If this happens often in your code, it can cause performance problems (results will be correct in all cases). The reason for this is probably some large input arguments for a wrapped function.r) rrrFrrr9rQstore_metadatar<r=) rWrNrXrrthis_duration_limitr argument_dict input_reprrS this_durations rrzMemorizedFunc._persist_inputVs"YY[ #DIIt{{D&I I=3F3F3HII !$  ))'8< j0 . . MM4 7D D  rcdt|j|||j|jdz S)NrrSrVr2)rKrQrVrrs rrz#MemorizedFunc._get_memorized_results1    nnMMA%   rch|jj|||j|jS)Nr#)rQrdrVrrs rrzMemorizedFunc._load_items1!!++ h$..$--,  rc t|j\}}|d|dt|}tt ddt |z dz|zy)N z- rPr)r rFrrmaxr)rWrNrrnamemsgs rrzMemorizedFunc._print_durationsQ *4ay;x#8"9: c!b3s8m%+c12rcdj|jj|j|jj S)Nz.{class_name}(func={func}, location={location}))rrFr@)r*r>r rFrQr@r\s rrlzMemorizedFunc.__repr__s>?FF~~..''00G  r)r%NNFrNN)rF)g?rZ)r)r r!r"r#rOrrrtrrrrsrrrrrrjrrr r rrrrrlr$rrrrds+j"&1"fs rrzAsyncMemorizedFunc.calls6glD+F+#//4Sy=#=ys *646cK|j||tj}|j|i|d{}|j||||||S7wrZr rs rrzAsyncMemorizedFunc._callsY $'YY[  tyy$1&11vxTT2ss@rr/r/s  >Urr/cXeZdZdZ d dZ d dZd dZd dZdZdZ d Z y)MemoryaA context object for caching a function's return value each time it is called with the same input arguments. All values are cached on the filesystem, in a deep directory structure. Read more in the :ref:`User Guide `. Parameters ---------- location: str, pathlib.Path or None The path of the base directory to use as a data store or None. If None is given, no caching is done and the Memory object is completely transparent. This option replaces cachedir since version 0.12. backend: str, optional, default='local' Type of store backend for reading/writing cache files. The 'local' backend is using regular filesystem operations to manipulate data (open, mv, etc) in the backend. mmap_mode: {None, 'r+', 'r', 'w+', 'c'}, optional The memmapping mode used when loading from cache numpy arrays. See numpy.load for the meaning of the arguments. compress: boolean, or integer, optional Whether to zip the stored data on disk. If an integer is given, it should be between 1 and 9, and sets the amount of compression. Note that compressed arrays cannot be read by memmapping. verbose: int, optional Verbosity flag, controls the debug messages that are issued as functions are evaluated. backend_options: dict, optional Contains a dictionary of named parameters used to configure the store backend. Nc tj|||_||_t j|_||_||_|i}||_|r|tjdd||_ t|tr tjj!|d}t#|||jt%d||d||_y)Nz&Compressed results cannot be memmappedr,rjoblibrr1r$)r rOrrRrrVr.rr3r<r=r@r'r(r6r7rrDrrQ)rWr@r.rRrr2r3s rrOzMemory.__init__s  "    " O.  - MMBq Q  h $ww||Hh7H3  MM !Y:I  rc |t|std|d|$tj|j||||S|j )t j|rtnt}||S| |j}|dur |j}t|tr |j}t j|rtnt}|||j |j |||j"||j$| S)aDecorates the given function func to only compute its return value for input arguments not cached on disk. Parameters ---------- func: callable, optional The function to be decorated ignore: list of strings A list of arguments name to ignore in the hashing verbose: integer, optional The verbosity mode of the function. By default that of the memory object is used. mmap_mode: {None, 'r+', 'r', 'w+', 'c'}, optional The memmapping mode used when loading from cache numpy arrays. See numpy.load for the meaning of the arguments. By default that of the memory object is used. cache_validation_callback: callable, optional Callable to validate whether or not the cache is valid. When the cached function is called with arguments for which a cache exists, this callable is called with the metadata of the cached result as its sole argument. If it returns True, then the cached result is returned, else the cache for these arguments is cleared and recomputed. Returns ------- decorated_func: MemorizedFunc object The returned object is a MemorizedFunc object, that is callable (behaves like a function), but offers extra methods for cache lookup and management. See the documentation for :class:`joblib.memory.MemorizedFunc`. z4cache_validation_callback needs to be callable. Got .)rrRr2rF)r@r.rrRrr2rVr)callabler)rpartialcacherQriscoroutinefunctionrrrrRr'rrFr/r.rrV)rWrFrr2rRrclss rrDz Memory.cachesP % 0 %: 014  <$$ #*C      %..t4&%  t9  ?mmG  I dM *99D$+$?$?$E = ''LL]]nn&?  rc|r|jd|j/|jjtjyy)z#Erase the complete cache directory.zFlushing completely the cacheN)r=rQrjrrs rrjz Memory.cleargsC  II5 6    )    $ $ &  " " $ *rcf|jy|||y|jj|||y)aORemove cache elements to make the cache fit its limits. The limitation can impose that the cache size fits in ``bytes_limit``, that the number of cache items is no more than ``items_limit``, and that all files in cache are not older than ``age_limit``. Parameters ---------- bytes_limit: int | str, optional Limit in bytes of the size of the cache. By default, the size of the cache is unlimited. When reducing the size of the cache, ``joblib`` keeps the most recently accessed items first. If a str is passed, it is converted to a number of bytes using units { K | M | G} for kilo, mega, giga. items_limit: int, optional Number of items to limit the cache to. By default, the number of items in the cache is unlimited. When reducing the size of the cache, ``joblib`` keeps the most recently accessed items first. age_limit: datetime.timedelta, optional Maximum age of items to limit the cache to. When reducing the size of the cache, any items last accessed more than the given length of time ago are deleted. Example: to remove files older than 5 days, use datetime.timedelta(days=5). Negative timedelta are not accepted. N)rQenforce_store_limits)rW bytes_limit items_limit age_limits r reduce_sizezMemory.reduce_sizets@8    %   ;#69;L  // [)TrcX|j||i|S|j||i|S)zEval function func with arguments `*args` and `**kwargs`, in the context of the memory. This method works similarly to the builtin `apply`, except that the function is called only if the cache is not up to date. )rQrD)rWrFrrs revalz Memory.evals;    %(( (tzz$000rcdj|jj|jdS|jjS)Nz!{class_name}(location={location}))rr@)r*r>r rQr@r\s rrlzMemory.__repr__sU299~~..**2:  9=8J8J8S8S:  rcD|jj}d|d<|S)zaWe don't store the timestamp when pickling, to avoid the hash depending from it. NrVrnrqs rrszMemory.__getstate__s% ""$!k r)Nr%NFrN)NNNFNr)NNN) r r!r"r#rOrDrjrMrOrlrsr$rrr=r=sU'^! J"& Q f %%UN 1" rr=c Jtj|||||||fd}|S)zHelper cache_validation_callback to force recompute after a duration. Parameters ---------- days, seconds, microseconds, milliseconds, minutes, hours, weeks: numbers argument passed to a timedelta. )daysseconds microseconds millisecondsminuteshoursweeksc^tj|dz }|jkS)Nr)r total_seconds)rScomputation_agedeltas rrz0expires_after..cache_validation_callbacks,))+(88!4!4!666r)datetime timedelta) rSrTrUrVrWrXrYrr]s @r expires_afterr`s7    !! E7 %$r)rN)rrrrrrr)3r#r2r^rrrr6r4rrrrrrr<weakrefrr_store_backendsrrr func_inspectrr r r r loggerr rrrrr?rr,r/rDrIWeakKeyDictionaryrrKobjectrvrrrr/r=r`r$rrrgs    10! !K[K23,@(V,-7,,. afaH$$$$T!v!ND,D@  F@  LUU2wVw@RS%r