o
    ƒôj[A ã                   @  s¶  d Z ddlm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
mZ 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mZ dd
lmZ ddlmZmZmZ dZ ej!dkr‡ej!dkssej"dd… dkr‡zddl#m Z  W n e$y†   dZ Y nw ej!dkr“ddlm%Z% [%dZ&g d¢Z'ej( )dd¡ dZ*ej+dkrªej,nej-Z.ej+dkrµej-nej/Z0ej!dkoÂej1 2d¡Z3G dd„ dej4ƒZ5zej6Z7W n e8yÝ   ej9Z7Y nw ed Z:dad#d$„Z;G d%d&„ d&e
ƒZ<e=ƒ Z>ed'ƒZ?eG d(d)„ d)ƒƒZ@e@ƒ ZAG d*d+„ d+e<ƒZBG d,d-„ d-eƒZCeCƒ ZDG d.d/„ d/e<ƒZEG d0d1„ d1e<ƒZFG d2d3„ d3e<ƒZGG d4d5„ d5e<ƒZHeBeEeGeHeFgZIeJd6d7„ eID ƒƒZKd8d9„ eID ƒZLeJd:d7„ eID ƒƒZMd;d9„ eID ƒZNeHjOZPd<d=„ ZQd>d?„ ZRed@dA�dBdC„ ƒZSeReJeKƒeLdD�dbdcdHdI„ƒZTe=ƒ ZUdJdK„ ZVG dLdM„ dMƒZWG dNdO„ dOeƒZXeRdP YdQdR„ eKD ƒ¡dP YeN¡dP YeP¡dS�G dTdU„ dUeWƒƒZZdVZ[G dWdX„ dXƒZ\dYdZ„ Z]da^da_eƒ Z`ddd[d\„Zaded^d_„Zbecd`k�rÙe]ƒ  dS dS )fzÓthreadpoolctl

This module provides utilities to introspect native libraries that relies on
thread pools (notably BLAS and OpenMP implementations) and dynamically set the
maximal number of threads they can use.
é    )ÚannotationsN)ÚABCÚabstractmethod)ÚCallable)ÚContextDecorator)Ú	dataclassÚfield)Ú	lru_cacheÚwraps)ÚLockÚThreadÚcurrent_thread)Úlocal)ÚLiteralÚTypeVarÚfinalZ
emscriptenÚlinuxé   ©é   é   )ÚdllistÚwin32)Úwintypesz3.8.0)ÚLibControllerÚThreadpoolControllerÚget_cached_controllerÚregisterÚreset_cached_controllerÚthreadpool_infoÚthreadpool_limitsÚKMP_DUPLICATE_LIB_OKÚTruei(
  l        z
/proc/selfc                   @  s,   e Zd ZdefdejfdejfdefgZdS )Ú_dl_phdr_infoZ	dlpi_addrÚ	dlpi_nameZ	dlpi_phdrZ
dlpi_phnumN)	Ú__name__Ú
__module__Ú__qualname__Ú_SYSTEM_UINTÚctypesÚc_char_pÚc_void_pÚ_SYSTEM_UINT_HALFÚ_fields_© r.   r.   ú`/var/www/html/academy/tools/voices/clone/cosy-venv/lib/python3.10/site-packages/threadpoolctl.pyr#   g   s    ür#   )r   ÚprocessÚunknownÚget_n_threadsúCallable[[], int]Úset_n_threadsúCallable[[int], None]ÚreturnÚ_ThreadLimitScopec              	     sø   ˆƒ }zm|dk rd‰ n|d ‰ g ‰d‡ ‡‡‡fdd„}t |d�}| ¡  | ¡  tjdd	� ˆˆ gkr@W ˆ|ƒ tjdd	� d
S ˆƒ ˆ krRW ˆ|ƒ tjdd	� dS ˆƒ |krdW ˆ|ƒ tjdd	� dS W ˆ|ƒ tjdd	� d
S ˆ|ƒ tjdd	� w )ai  
    Run some experiments to determine the scope of the given get/set API.

    This function might not work if you only have one core available.

    This function might not work if you set a limit on a library with an
    environment variable.

    The function works by changing the number of threads in loaded controllers,
    which can be a process-wide change. As such, it is not always thread-safe.
    An attempt will be made to restore all settings to their previous state,
    but the result may be subtly different, e.g. if "unset" has different
    semantics than "set to the default returned value".
    r   é   r6   ÚNonec                     s   ˆˆ ƒ ˆ  ˆƒ ¡ d S ©N)Úappendr.   ©Úexpectedr2   r4   Zthread_resultr.   r/   Úget_and_set¨   s   z2_determine_thread_limit_scope.<locals>.get_and_set)ÚtargetT)Úforcer1   r0   r   N©r6   r9   )r   ÚstartÚjoinÚOpenBLASControllerÚclear_controlling_thread)r2   r4   Úpreviousr>   Úthreadr.   r<   r/   Ú_determine_thread_limit_scope…   s8   


õ
øýÿrH   c                   @  sz   e Zd ZdZeddddœdd„ƒZddd	d
„Zdd„ Zedd„ ƒZ	e
dd„ ƒZe
dd„ ƒZe
dd„ ƒZdd„ Zdd„ ZdS )r   a  Abstract base class for the individual library controllers

    A library controller must expose the following class attributes:
        - user_api : str
            Usually the name of the library or generic specification the library
            implements, e.g. "blas" is a specification with different implementations.
        - internal_api : str
            Usually the name of the library or concrete implementation of some
            specification, e.g. "openblas" is an implementation of the "blas"
            specification.
        - filename_prefixes : tuple
            Possible prefixes of the shared library's filename that allow to
            identify the library. e.g. "libopenblas" for libopenblas.so.

    and implement the following methods: `get_num_threads`, `set_num_threads` and
    `get_version`.

    Threadpoolctl loops through all the loaded shared libraries and tries to match
    the filename of each library with the `filename_prefixes`. If a match is found, a
    controller is instantiated and a handler to the library is stored in the `dynlib`
    attribute as a `ctypes.CDLL` object. It can be used to access the necessary symbols
    of the shared library to implement the above methods.

    The following information will be exposed in the info dictionary:
      - user_api : standardized API, if any, or a copy of internal_api.
      - internal_api : implementation-specific API.
      - num_threads : the current thread limit.
      - prefix : prefix of the shared library's filename.
      - filepath : path to the loaded shared library.
      - version : version of the library (if available).

    In addition, each library controller may expose internal API specific entries. They
    must be set as attributes in the `set_additional_attributes` method.
    N©ÚfilepathÚprefixÚparentc                C  sD   || _ || _|| _t |¡| _|  ¡ \| _| _|  	¡ | _
|  ¡  dS )z0This is not meant to be overriden by subclasses.N)rL   rK   rJ   Ú_CDLL_CACHEÚget_cdllÚdynlibÚ_find_affixesÚ_symbol_prefixÚ_symbol_suffixÚget_versionÚversionÚset_additional_attributes)ÚselfrJ   rK   rL   r.   r.   r/   Ú__init__ð   s   
zLibController.__init__FÚdebugging_infoÚboolc                   sJ   d‰ | j | j| jdœ‡ fdd„t| ƒ ¡ D ƒ¥}|r#t| j| jƒ|d< |S )a  Return relevant info wrapped in a dict.

        Parameters
        ----------
        debugging_info : bool

            Include extra fields which require more intrusive actions to
            obtain, and which can't always reliably be determined.
        )rO   rL   rQ   rR   )Úuser_apiÚinternal_apiÚnum_threadsc                   s   i | ]\}}|ˆ vr||“qS r.   r.   )Ú.0ÚkÚv©Zhidden_attrsr.   r/   Ú
<dictcomp>
  s    z&LibController.info.<locals>.<dictcomp>Zthread_limit_scope)rZ   r[   r\   ÚvarsÚitemsrH   Úget_num_threadsÚset_num_threads)rV   rX   Úresultr.   r`   r/   Úinfoû   s   
ýüÿzLibController.infoc                 C  ó   dS )z>Set additional attributes meant to be exposed in the info dictNr.   ©rV   r.   r.   r/   rU     ó    z'LibController.set_additional_attributesc                 C  ó   |   ¡ S )z�Exposes the current thread limit as a dynamic property

        This is not meant to be used or overriden by subclasses.
        )rd   ri   r.   r.   r/   r\     s   zLibController.num_threadsc                 C  rh   )z5Return the maximum number of threads available to useNr.   ri   r.   r.   r/   rd     rj   zLibController.get_num_threadsc                 C  rh   )z½Set the maximum number of threads to use

        When possible, implementations of this method should choose a thread
        limiting API that only applies to the current thread.
        Nr.   )rV   r\   r.   r.   r/   re   !  rj   zLibController.set_num_threadsc                 C  rh   )z(Return the version of the shared libraryNr.   ri   r.   r.   r/   rS   )  rj   zLibController.get_versionc                 C  rh   )z8Return the affixes for the symbols of the shared library)Ú rl   r.   ri   r.   r.   r/   rP   -  ó   zLibController._find_affixesc                 C  s   t | j| j› |› | j› �dƒS )zBReturn the symbol of the shared library accounding for the affixesN)ÚgetattrrO   rQ   rR   )rV   Únamer.   r.   r/   Ú_get_symbol1  s   ÿzLibController._get_symbol©F©rX   rY   )r%   r&   r'   Ú__doc__r   rW   rg   rU   Úpropertyr\   r   rd   re   rS   rP   rp   r.   r.   r.   r/   r   Ì   s     #




r   Ú_Tc                   @  sp   e Zd ZU dZeed�Zded< eed�Zded< eed�Z	ded< ddd„Z
d dd„Zd!dd„Zd"dd„ZdS )#Ú
_CDLLCachez 
    Cache CDLL instances and their associated method results, as well as which
    ``LibController`` subclass to use for a given shared library file path.
    )Údefault_factoryz%dict[str, type[LibController] | None]Ú_controller_cachezdict[str, ctypes.CDLL]Ú_cdll_cachez:dict[tuple[type[LibController], str, ctypes.CDLL], object]Ú_method_result_cacheÚlibrary_basenameÚstrÚfilename_prefixesú	list[str]r6   ú
str | Nonec                 C  s    |D ]}|  |¡r|  S qdS )z]Return the prefix library_basename starts with

        Return None if none matches.
        N)Ú
startswith)rV   r{   r}   rK   r.   r.   r/   Ú_check_prefixP  s
   
ÿz_CDLLCache._check_prefixrJ   rL   r   úLibController | Nonec              	     s"  | j  |t¡}|tur|\}}}|du rdS ||||d�S |}t|ƒ}tj |¡ ¡ }tD ]\}|  	||j
¡}|du r;q-|dkrY| d¡rXt |t¡‰t‡fdd„|jD ƒƒsWq-nq-z	||||d�‰ W n	 tyk   Y q-w t|dƒr}t‡ fdd„|jD ƒƒr‰|||f| j |< ˆ   S q-d	| j |< dS )
z
        Create the associated controller, if there is one, relying on cached
        info for the given ``filepath``.
        NrI   Úlibblasú.dllc                 3  s   � | ]}t ˆ |ƒV  qd S r:   )Úhasattr©r]   Úfunc)rƒ   r.   r/   Ú	<genexpr>†  s
   € ÿ
ÿz/_CDLLCache.create_controller.<locals>.<genexpr>Úcheck_symbolsc                 3  s   � | ]	}t ˆ j|ƒV  qd S r:   )r…   rO   r†   ©Úlib_controllerr.   r/   rˆ   �  s
   € 
ÿ
ÿ)Nrl   rl   )rx   ÚgetÚ_MISSINGÚ	_realpathÚosÚpathÚbasenameÚlowerÚ_ALL_CONTROLLERSr�   r}   Úendswithr)   ÚCDLLÚ_RTLD_NOLOADÚanyr‰   ÚOSErrorr…   )rV   rJ   rL   rf   Zcontroller_classrK   Zoriginal_filepathÚfilenamer.   )r‹   rƒ   r/   Úcreate_controller\  sP   

þü
ÿþþ
ý÷
z_CDLLCache.create_controllerúctypes.CDLLc                 C  s2   | j  |t¡}|tu rtj|td�}|| j |< |S )z}
        Get the ``CDLL`` for a path, loading if necessary, using a cached
        version if it was already loaded.
        ©Úmode)ry   rŒ   r�   r)   r•   r–   )rV   rJ   rf   r.   r.   r/   rN   ¬  s
   
z_CDLLCache.get_cdllÚmethodúCallable[[LibController], _T]c                   s(   | j ‰ ˆj‰tˆƒ‡ ‡‡fdd„ƒ}|S )z·
        Caching decorator for idempotent read-only methods of
        ``LibController``, with the cache shared across instances that have the
        same ``CDLL`` instance.
        c                   s6   | j ˆ| jf}ˆ  |t¡}|tu rˆ| ƒ}|ˆ |< |S r:   )Ú	__class__rO   rŒ   r�   )rV   Úkeyrf   ©Úcacherž   ro   r.   r/   ÚwrapperÂ  s   z2_CDLLCache.cache_method_on_dynlib.<locals>.wrapper)rz   r%   r
   )rV   rž   r¤   r.   r¢   r/   Úcache_method_on_dynlib·  s
   z!_CDLLCache.cache_method_on_dynlibN)r{   r|   r}   r~   r6   r   )rJ   r|   rL   r   r6   r‚   )rJ   r|   r6   r›   )rž   rŸ   r6   rŸ   )r%   r&   r'   rs   r   Údictrx   Ú__annotations__ry   rz   r�   rš   rN   r¥   r.   r.   r.   r/   rv   ?  s   
 ÿ
ÿ


Prv   c                   @  s´   e Zd ZdZdZdZdZdZdZe	dd„ e
 ee¡D ƒƒZejd	d
„ ƒZdd„ Zdd„ ZG dd„ dƒZed!d"dd„ƒZdd„ Zdd„ Zejdd„ ƒZejdd„ ƒZejdd„ ƒZd S )#rD   aP  Controller class for OpenBLAS.

    When OpenBLAS uses the OpenMP threading layer, each thread that calls into
    OpenBLAS gets its own OpenBLAS thread pool, and correspondingly the limit
    set by ``threadpoolctl`` is per-thread.  Each Python thread can therefore
    set its own limit without consideration for other Python threads.

    In constrast, when the OpenMP threading layer is not used, there is a
    process-wide shared thread pool, so having multiple Python threads change
    the limit at the same time makes no sense.  Therefore:

        1. Thread pool size can only be set by a single thread, the first
           thread to call ``set_num_threads()``.  In practice this will usually
           be the main thread.

        2. Other threads silently do nothing.

        3. ``clear_controlling_thread()`` can be used to reset the thread that
           can meaningfully use the limiting API.

    ``with threadpool_limits()`` and the function decorator
    ``threadpool_limits.wrap()`` will automatically clear the controlling
    thread when they're done, including when nested.
    ÚblasÚopenblas)Zlibopenblasrƒ   Zlibscipy_openblasr©   )rl   Zscipy_)rl   Z64_Z_64c                 c  s"   � | ]\}}|› d |› �V  qdS )Úopenblas_get_num_threadsNr.   )r]   rK   Úsuffixr.   r.   r/   rˆ   ø  s
   € ÿ
ÿzOpenBLASController.<genexpr>c                 C  s@   t  | j| j¡D ]\}}t| j|› d|› �ƒr||f  S qd S )Nrª   )Ú	itertoolsÚproductÚ_symbol_prefixesÚ_symbol_suffixesr…   rO   )rV   rK   r«   r.   r.   r/   rP   ý  s   ÿÿýz OpenBLASController._find_affixesc                 C  ó   |   ¡ | _|  ¡ | _d S r:   ©Ú_get_threading_layerÚthreading_layerÚ_get_architectureÚarchitectureri   r.   r.   r/   rU     ó   
z,OpenBLASController.set_additional_attributesc                 C  s0   | j dkrd}nd}|  |¡}|d ur|ƒ S d S )NÚopenmpÚomp_get_max_threadsrª   ©r³   rp   )rV   ÚsymbolZget_num_threads_funcr.   r.   r/   rd   	  s   

z"OpenBLASController.get_num_threadsc                   @  s$   e Zd ZU dZdZded< eƒ ZdS )z OpenBLASController._SHARED_STATEzShared state across instances.NzThread | NoneÚcontrolling_thread)r%   r&   r'   rs   r»   r§   r   Úlockr.   r.   r.   r/   Ú_SHARED_STATE  s   
 
r½   Fr@   rY   c                 C  sX   | j j� |s| j jtƒ u rd| j _W d  ƒ dS W d  ƒ dS 1 s%w   Y  dS )aS  Reset which thread can set limits (on non-OpenMP threading layer).

        It's up the caller to ensure the current controlling thread is done.

        By default, only the controlling thread has an effect when calling this
        method.  You can have any thread clear the controlling thread by
        setting ``force=True``.
        N)r½   r¼   r»   r   )Úclsr@   r.   r.   r/   rE     s   


þ"ÿz+OpenBLASController.clear_controlling_threadc                 C  sš   | j dkr
|  |¡S tƒ }| jj}||u r|  |¡S |d u s"| ¡ sK| jj� | jjd u s3| jj ¡ s7|| j_W d   ƒ n1 sAw   Y  |  |¡S d S )Nr·   )r³   Ú_real_set_num_threadsr   r½   r»   Úis_aliver¼   re   )rV   r\   Zthis_threadr»   r.   r.   r/   re   (  s    




ÿ€ù

z"OpenBLASController.set_num_threadsc                 C  s2   | j dkrd}nd}|  |¡}|d ur||ƒS d S )Nr·   Úomp_set_num_threadsZopenblas_set_num_threadsr¹   )rV   r\   rº   Zset_num_threads_funcr.   r.   r/   r¿   E  s   

z(OpenBLASController._real_set_num_threadsc                 C  sF   |   d¡}|d ur!tj|_|ƒ  ¡ }|d dkr|d  d¡S d S d S )NZopenblas_get_configr   s   OpenBLASr8   úutf-8)rp   r)   r*   ÚrestypeÚsplitÚdecode)rV   Zget_version_funcÚconfigr.   r.   r/   rS   \  s   

zOpenBLASController.get_versionc                 C  s8   |   d¡}|dur|ƒ }|dkrdS |dkrdS dS dS )	z&Return the threading layer of OpenBLASZopenblas_get_parallelNr   r·   r8   ÚpthreadsÚdisabledr1   )rp   )rV   Zget_threading_layer_funcr³   r.   r.   r/   r²   i  s   
z'OpenBLASController._get_threading_layerc                 C  s*   |   d¡}|durtj|_|ƒ  d¡S dS )z,Return the architecture detected by OpenBLASZopenblas_get_corenameNrÂ   )rp   r)   r*   rÃ   rÅ   )rV   Zget_architecture_funcr.   r.   r/   r´   v  s
   
z$OpenBLASController._get_architectureNrq   )r@   rY   )r%   r&   r'   rs   rZ   r[   r}   r®   r¯   Útupler¬   r­   r‰   rM   r¥   rP   rU   rd   r½   ÚclassmethodrE   re   r¿   rS   r²   r´   r.   r.   r.   r/   rD   Ñ  s2    
þ


rD   c                   @  s$   e Zd ZdZdZdd„ Zdd„ ZdS )Ú_ControllingThreadOwnershipzãCount how many paired limit-unlimits have modified OpenBLAS.

    Clear controlling thread if it hits zero.

    In the future this could potentialy also apply to non-OpenBLAS libraries
    that have a shared process pool.
    r   c                 C  s   |  j d7  _ dS )zIncrement ownership.r8   N)Úcountri   r.   r.   r/   Ú	increment‹  s   z%_ControllingThreadOwnership.incrementc                 C  s(   |  j d8  _ | j dkrt ¡  dS dS )zDecrement ownership.r8   r   N)rÌ   rD   rE   ri   r.   r.   r/   Ú	decrement�  s   
ÿz%_ControllingThreadOwnership.decrementN)r%   r&   r'   rs   rÌ   rÍ   rÎ   r.   r.   r.   r/   rË   €  s
    rË   c                   @  sb   e Zd ZdZdZdZdZdZdd„ Zdd	„ Z	d
d„ Z
ejdd„ ƒZejdd„ ƒZejdd„ ƒZdS )ÚBLISControllerzController class for BLISr¨   Zblis)Zlibblisrƒ   )Úbli_thread_get_num_threadsÚbli_thread_set_num_threadsÚbli_info_get_version_strÚbli_info_get_enable_openmpÚbli_info_get_enable_pthreadsÚbli_arch_query_idÚbli_arch_stringc                 C  r°   r:   r±   ri   r.   r.   r/   rU   ¬  r¶   z(BLISController.set_additional_attributesc                 C  ó(   t | jddd„ ƒ}|ƒ }|dkrdS |S )NrÐ   c                   S  ó   d S r:   r.   r.   r.   r.   r/   Ú<lambda>±  rj   z0BLISController.get_num_threads.<locals>.<lambda>éÿÿÿÿr8   ©rn   rO   ©rV   Úget_funcr\   r.   r.   r/   rd   °  ó   zBLISController.get_num_threadsc                 C  ó   t | jddd„ ƒ}||ƒS )NrÑ   c                 S  rØ   r:   r.   ©r\   r.   r.   r/   rÙ   ¹  rj   z0BLISController.set_num_threads.<locals>.<lambda>rÛ   ©rV   r\   Zset_funcr.   r.   r/   re   ·  ó   ÿzBLISController.set_num_threadsc                 C  s.   t | jdd ƒ}|d u rd S tj|_|ƒ  d¡S )NrÒ   rÂ   )rn   rO   r)   r*   rÃ   rÅ   )rV   Úget_version_r.   r.   r/   rS   ½  s
   zBLISController.get_versionc                 C  s4   t | jddd„ ƒƒ rdS t | jddd„ ƒƒ rdS dS )	z"Return the threading layer of BLISrÓ   c                   S  rh   ©NFr.   r.   r.   r.   r/   rÙ   É  rj   z5BLISController._get_threading_layer.<locals>.<lambda>r·   rÔ   c                   S  rh   rä   r.   r.   r.   r.   r/   rÙ   Ë  rj   rÇ   rÈ   rÛ   ri   r.   r.   r/   r²   Æ  s
   z#BLISController._get_threading_layerc                 C  sP   t | jddƒ}t | jddƒ}|du s|du rdS tj|_tj|_||ƒ ƒ d¡S )z(Return the architecture detected by BLISrÕ   NrÖ   rÂ   )rn   rO   r)   Úc_intrÃ   r*   rÅ   )rV   rÕ   rÖ   r.   r.   r/   r´   Ï  s   z BLISController._get_architectureN)r%   r&   r'   rs   rZ   r[   r}   r‰   rU   rd   re   rM   r¥   rS   r²   r´   r.   r.   r.   r/   rÏ   ™  s    


rÏ   c                      sŒ   e Zd ZdZdZdZdZdZedd„ ƒZ	edd	„ ƒZ
dd‡ fdd„Zdd„ Zdd„ Zdd„ Zejdd„ ƒZddd„Zdd„ Zdd„ Z‡  ZS )ÚFlexiBLASControllerzController class for FlexiBLASr¨   Z	flexiblas)Zlibflexiblas)Úflexiblas_get_num_threadsÚflexiblas_set_num_threadsÚflexiblas_get_versionÚflexiblas_listZflexiblas_list_loadedÚflexiblas_current_backendc                 C  s   | j dd�S )NT©Úloaded)Ú_get_backend_listri   r.   r.   r/   Úloaded_backendsí  s   z#FlexiBLASController.loaded_backendsc                 C  rk   r:   )Ú_get_current_backendri   r.   r.   r/   Úcurrent_backendñ  s   z#FlexiBLASController.current_backendFrX   rY   c                   s&   t ƒ j|d�}| j|d< | j|d< |S )z&Return relevant info wrapped in a dict©rX   rï   rñ   )Úsuperrg   rï   rñ   )rV   rX   Zexposed_attrs©r    r.   r/   rg   õ  s   

zFlexiBLASController.infoc                 C  s   | j dd�| _d S )NFrì   )rî   Úavailable_backendsri   r.   r.   r/   rU   ÿ  s   z-FlexiBLASController.set_additional_attributesc                 C  r×   )Nrç   c                   S  rØ   r:   r.   r.   r.   r.   r/   rÙ     rj   z5FlexiBLASController.get_num_threads.<locals>.<lambda>rÚ   r8   rÛ   rÜ   r.   r.   r/   rd     rÞ   z#FlexiBLASController.get_num_threadsc                 C  rß   )Nrè   c                 S  rØ   r:   r.   rà   r.   r.   r/   rÙ     rj   z5FlexiBLASController.set_num_threads.<locals>.<lambda>rÛ   rá   r.   r.   r/   re   	  râ   z#FlexiBLASController.set_num_threadsc                 C  sj   t | jdd ƒ}|d u rd S t ¡ }t ¡ }t ¡ }|t |¡t |¡t |¡ƒ |j› d|j› d|j› �S )Nré   Ú.)rn   rO   r)   rå   ÚbyrefÚvalue)rV   rã   ÚmajorÚminorÚpatchr.   r.   r/   rS     s   zFlexiBLASController.get_versionc                 C  s†   d|rdnd› �}t | j|dƒ}|du rdS |dddƒ}g }t|ƒD ]}t d¡}||d|ƒ |j d¡dkr@| |j d¡¡ q"|S )	zêReturn the list of available backends for FlexiBLAS.

        If loaded is False, return the list of available backends from the FlexiBLAS
        configuration. If loaded is True, return the list of actually loaded backends.
        rê   Ú_loadedrl   Nr   é   rÂ   Z__FALLBACK__)rn   rO   Úranger)   Úcreate_string_bufferrø   rÅ   r;   )rV   rí   Ú	func_nameZget_backend_list_Z
n_backendsÚbackendsÚiÚbackend_namer.   r.   r/   rî     s   
€z%FlexiBLASController._get_backend_listc                 C  s@   t | jddƒ}|du rdS t d¡}||t |¡ƒ |j d¡S )zReturn the backend of FlexiBLASrë   Nrý   rÂ   )rn   rO   r)   rÿ   Úsizeofrø   rÅ   )rV   Zget_backend_Úbackendr.   r.   r/   rð   2  s   
z(FlexiBLASController._get_current_backendc                 C  sà   || j vrO|| jv rt| jddd„ ƒ}n	t| jddd„ ƒ}|t|ƒ d¡ƒ}|dkr6td|›d	| j› d
�ƒ‚t�
 daW d  ƒ n1 sEw   Y  | j	 
¡  t| jddd„ ƒ}| j  |¡}||ƒ}|dkrntd|›d�ƒ‚dS )a  Switch the backend of FlexiBLAS

        Parameters
        ----------
        backend : str
            The name or the path to the shared library of the backend to switch to. If
            the backend is not already loaded, it will be loaded first.
        Zflexiblas_load_backendc                 S  rh   ©NrÚ   r.   ©Ú_r.   r.   r/   rÙ   G  rj   z4FlexiBLASController.switch_backend.<locals>.<lambda>Zflexiblas_load_backend_libraryc                 S  rh   r  r.   r  r.   r.   r/   rÙ   J  rj   rÂ   rÚ   zFailed to load backend zS. It must either be the name of a backend available in the FlexiBLAS configuration z' or the path to a valid shared library.NZflexiblas_switchc                 S  rh   r  r.   r  r.   r.   r/   rÙ   ]  rj   zFailed to switch to backend rö   )rï   rõ   rn   rO   r|   ÚencodeÚRuntimeErrorÚ_CACHE_LOCKÚ_CACHED_CONTROLLERrL   Ú_load_librariesÚindex)rV   r  Ú	load_funcÚresZswitch_funcÚidxr.   r.   r/   Úswitch_backend<  s.   
	
ÿþÿÿ
ÿz"FlexiBLASController.switch_backendrq   rr   )r%   r&   r'   rs   rZ   r[   r}   r‰   rt   rï   rñ   rg   rU   rd   re   rM   r¥   rS   rî   rð   r  Ú__classcell__r.   r.   rô   r/   ræ   Þ  s&    	





ræ   c                   @  sT   e Zd ZdZdZdZdZdZdd„ Zdd	„ Z	d
d„ Z
ejdd„ ƒZejdd„ ƒZdS )ÚMKLControllerzController class for MKLr¨   Úmkl)Z	libmkl_rtZmkl_rtrƒ   )ÚMKL_Get_Max_ThreadsÚMKL_Set_Num_Threads_LocalÚMKL_Get_Version_StringÚMKL_Set_Threading_Layerc                 C  s   |   ¡ | _d S r:   )r²   r³   ri   r.   r.   r/   rU   u  s   z'MKLController.set_additional_attributesc                 C  ó   t | jddd„ ƒ}|ƒ S )Nr  c                   S  rØ   r:   r.   r.   r.   r.   r/   rÙ   y  rj   z/MKLController.get_num_threads.<locals>.<lambda>rÛ   ©rV   rÝ   r.   r.   r/   rd   x  ó   zMKLController.get_num_threadsc                 C  rß   )Nr  c                 S  rØ   r:   r.   rà   r.   r.   r/   rÙ   ~  rj   z/MKLController.set_num_threads.<locals>.<lambda>rÛ   rá   r.   r.   r/   re   |  râ   zMKLController.set_num_threadsc                 C  s\   t | jdƒsd S t d¡}| j |d¡ |j d¡}t d|¡}|d ur*| 	¡ d }| 
¡ S )Nr  éÈ   rÂ   zVersion ([^ ]+) r   )r…   rO   r)   rÿ   r  rø   rÅ   ÚreÚsearchÚgroupsÚstrip)rV   r  rT   Úgroupr.   r.   r/   rS   ‚  s   
zMKLController.get_versionc                 C  s0   t | jddd„ ƒ}dddddd	d
œ}||dƒ S )z!Return the threading layer of MKLr  c                 S  rh   r  r.   )Úlayerr.   r.   r/   rÙ   —  rj   z4MKLController._get_threading_layer.<locals>.<lambda>ZintelÚ
sequentialZpgiZgnuZtbbznot specified)r   r8   r   r   é   rÚ   rÚ   rÛ   )rV   Zset_threading_layerZ	layer_mapr.   r.   r/   r²   �  s   ÿúz"MKLController._get_threading_layerN)r%   r&   r'   rs   rZ   r[   r}   r‰   rU   rd   re   rM   r¥   rS   r²   r.   r.   r.   r/   r  d  s    
r  c                   @  s8   e Zd ZdZdZdZdZdZdd„ Zdd„ Z	d	d
„ Z
dS )ÚOpenMPControllerzController class for OpenMPr·   )ÚlibiompZlibgompÚlibompZvcomp)r¸   Zomp_get_num_threadsc                 C  r  )Nr¸   c                   S  rØ   r:   r.   r.   r.   r.   r/   rÙ   °  rj   z2OpenMPController.get_num_threads.<locals>.<lambda>rÛ   r  r.   r.   r/   rd   ¯  r  z OpenMPController.get_num_threadsc                 C  rß   )NrÁ   c                 S  rØ   r:   r.   rà   r.   r.   r/   rÙ   ´  rj   z2OpenMPController.set_num_threads.<locals>.<lambda>rÛ   rá   r.   r.   r/   re   ³  s   z OpenMPController.set_num_threadsc                 C  rØ   r:   r.   ri   r.   r.   r/   rS   ·  rm   zOpenMPController.get_versionN)r%   r&   r'   rs   rZ   r[   r}   r‰   rd   re   rS   r.   r.   r.   r/   r&  ¤  s    r&  c                 C  s   h | ]}|j ’qS r.   ©rZ   ©r]   Úlibr.   r.   r/   Ú	<setcomp>Ç  ó    r,  c                 C  ó   g | ]}|j ‘qS r.   ©r[   r*  r.   r.   r/   Ú
<listcomp>È  r-  r0  c                 C  s   h | ]
}|j D ]}|’qqS r.   )r}   )r]   r+  rK   r.   r.   r/   r,  Ê  s    c                 C  s   g | ]
}|j d kr|j‘qS )r¨   )rZ   r[   r*  r.   r.   r/   r0  Ì  s    c                 C  sB   t  | ¡ t | j¡ t | j¡ t | j¡ t	j
 ¡  tƒ  dS )zRegister a new controllerN)r“   r;   Ú_ALL_USER_APISrZ   Ú_ALL_INTERNAL_APISr[   Ú_ALL_PREFIXESÚextendr}   rM   rx   Úclearr   )Ú
controllerr.   r.   r/   r   Ò  s   


r   c                    s   ‡ ‡fdd„}|S )Nc                   s"   | j d ur| j jˆ i ˆ¤Ž| _ | S r:   )rs   Úformat)Úo©ÚargsÚkwargsr.   r/   Ú	decoratorÞ  s   
z$_format_docstring.<locals>.decoratorr.   )r:  r;  r<  r.   r9  r/   Ú_format_docstringÝ  s   r=  i'  )Úmaxsizec                 C  s   t j | ¡S )zCSmall caching wrapper around os.path.realpath to limit system calls)r�   r�   Úrealpath©rJ   r.   r.   r/   rŽ   æ  s   rŽ   )Ú	USER_APISZINTERNAL_APISFrX   rY   c                 C  s   t ƒ  | ¡S )aæ  Return the maximal number of threads for each detected library.

    Return a list with all the supported libraries that have been found. Each
    library is represented by a dict with the following information:

      - "user_api" : user API. Possible values are {USER_APIS}.
      - "internal_api": internal API. Possible values are {INTERNAL_APIS}.
      - "prefix" : filename prefix of the specific implementation.
      - "filepath": path to the loaded library.
      - "version": version of the library (if available).
      - "num_threads": the current thread limit.

    In addition, each library may contain internal_api specific entries.

    Parameters
    ----------
    debugging_info : bool
        Include extra fields which require more intrusive actions to obtain,
        and which can't always reliably be determined.

        - "thread_limit_scope": When setting the number of threads, what is
          affected. Possible values are "process", "current_thread", "unknown".
    )r   rg   rò   r.   r.   r/   r   ì  s   r   c                   s$  t ˆ tƒrˆ dkr|  ¡  ¡ \‰ }ˆ du st ˆ tƒrE|du r!t}n|tv r)|g}ntdt› d|› d�ƒ‚ˆ durA‡ fdd„|D ƒ‰ ˆ |fS t ˆ tƒrki }ˆ D ]}| dt	¡ }t	ur]|}n|d	 }|d
 ||< qN|‰ nt ˆ t
ƒrxdd„ ˆ jD ƒ‰ t ˆ tƒs‡tdtˆ ƒ› d�ƒ‚dd„ ˆ D ƒ}ˆ |fS )z8Suitable values for the _limits and _user_api attributesZsequential_blas_under_openmpNzuser_api must be either in z or None. Got z	 instead.c                   s   i | ]}|ˆ “qS r.   r.   ©r]   Úapi©Úlimitsr.   r/   ra      r-  z)_check_limiter_params.<locals>.<dictcomp>rJ   rK   r\   c                 S  s   i | ]}|j |j“qS r.   )rJ   r\   ©r]   r‹   r.   r.   r/   ra   2  s    ÿÿzUlimits must either be an int, a list, a dict, or 'sequential_blas_under_openmp'. Got z insteadc                 S  s   g | ]}|t v r|‘qS r.   )r1  rB  r.   r.   r/   r0  ?  s    z)_check_limiter_params.<locals>.<listcomp>)Ú
isinstancer|   Ú,_get_params_for_sequential_blas_under_openmpÚvaluesÚintr1  Ú
ValueErrorÚlistrŒ   Ú_missingr   Úlib_controllersr¦   Ú	TypeErrorÚtype)r6  rE  rZ   rf   Úlib_inforJ   r¡   r.   rD  r/   Ú_check_limiter_params  sL   
ýÿÿ!
á
þ
ÿÿrR  c                   @  s`   e Zd ZdZdddœdd„Zdd„ Zdd	„ Zedddœd
d„ƒZdd„ Z	e	Z
dd„ Zdd„ ZdS )Ú_ThreadpoolLimitera¤  The guts of ThreadpoolController.limit

    Refer to the docstring of ThreadpoolController.limit for more details.

    It will only act on the library controllers held by the provided `controller`.
    Using the default constructor sets the limits right away such that it can be used as
    a callable. Setting the limits can be delayed by using the `wrap` class method such
    that it can be used as a decorator.
    N©rE  rZ   c                C  s2   || _ t|||ƒ\| _| _| j  ¡ | _|  ¡  d S r:   )Ú_controllerrR  Ú_limitsÚ	_user_apirg   Ú_original_infoÚ_set_threadpool_limits©rV   r6  rE  rZ   r.   r.   r/   rW   O  s   ÿz_ThreadpoolLimiter.__init__c                 C  s   t  ¡  | S r:   )ÚCONTROLLING_THREAD_OWNERSHIPrÍ   ri   r.   r.   r/   Ú	__enter__W  s   z_ThreadpoolLimiter.__enter__c                 C  s   |   ¡  t ¡  d S r:   )Úrestore_original_limitsr[  rÎ   )rV   rP  rø   Ú	tracebackr.   r.   r/   Ú__exit__[  s   z_ThreadpoolLimiter.__exit__c                C  s   t |||d�S )z@Return an instance of this class that can be used as a decorator)r6  rE  rZ   )Ú_ThreadpoolLimiterDecorator)r¾   r6  rE  rZ   r.   r.   r/   Úwrap_  s   ÿz_ThreadpoolLimiter.wrapc                 C  s,   t | jj| jƒD ]\}}| |d ¡ qdS )ú,Set the limits back to their original valuesr\   N)ÚziprU  rN  rX  re   )rV   r‹   Zoriginal_infor.   r.   r/   r]  f  s
   
ÿýz*_ThreadpoolLimiter.restore_original_limitsc                   s’   i }g }| j D ]1‰ ‡ fdd„| jD ƒ}t|ƒ}t|ƒ}|dkr$| ¡ }n|dkr+d}n	t|ƒ}| ˆ ¡ ||ˆ < q|rGt dd 	|¡ d ¡ |S )	zuOriginal num_threads from before calling threadpool_limits

        Return a dict `{user_api: num_threads}`.
        c                   s    g | ]}|d  ˆ kr|d ‘qS )rZ   r\   r.   )r]   rQ  r)  r.   r/   r0  y  s
    þz?_ThreadpoolLimiter.get_original_num_threads.<locals>.<listcomp>r8   r   Nz2Multiple values possible for following user apis: ú, z. Returning the minimum.)
rW  rX  ÚsetÚlenÚpopÚminr;   ÚwarningsÚwarnrC   )rV   r\   Zwarning_apisrE  Zn_limitsÚlimitr.   r)  r/   Úget_original_num_threadsp  s0   

þ


ÿþÿz+_ThreadpoolLimiter.get_original_num_threadsc                 C  s‚   | j du rdS | jjD ]3}|j| j v r| j |j }n|j| j v r'| j |j }n|j| j v r4| j |j }nq|dur>| |¡ qdS )z>Change the maximal number of threads in selected thread pools.N)rV  rU  rN  rJ   rK   rZ   re   )rV   r‹   r\   r.   r.   r/   rY  ”  s   

€òz)_ThreadpoolLimiter._set_threadpool_limits)r%   r&   r'   rs   rW   r\  r_  rÊ   ra  r]  Ú
unregisterrl  rY  r.   r.   r.   r/   rS  D  s    
$rS  c                   @  s8   e Zd ZdZdddœdd„Zdd„ Zdd	„ Zd
d„ ZdS )r`  zSame as _ThreadpoolLimiter but to be used as a decorator.

    If ``controller`` is None, use ``get_cached_controller()``.
    NrT  c                C  s0   || _ t|  ¡ ||ƒ ||| _| _tƒ | _d S r:   )rU  rR  Ú_get_controllerrV  rW  Úthread_localÚ	_limitersrZ  r.   r.   r/   rW   °  s   z$_ThreadpoolLimiterDecorator.__init__c                 C  s   | j d ur| j S tƒ S r:   )rU  r   ri   r.   r.   r/   rn  ¶  s   
z+_ThreadpoolLimiterDecorator._get_controllerc                 C  sH   t | jdƒs
g | j_|  ¡ }t|| j| jd�}| ¡  | jj |¡ | S )NÚstackrT  )	r…   rp  rq  rn  rS  rV  rW  r\  r;   )rV   r6  Úlimiterr.   r.   r/   r\  »  s   
ÿz%_ThreadpoolLimiterDecorator.__enter__c                 C  s   | j j ¡ }| |||¡S )rb  )rp  rq  rg  r_  )rV   rP  rø   r^  rr  r.   r.   r/   r_  É  s   z$_ThreadpoolLimiterDecorator.__exit__)r%   r&   r'   rs   rW   rn  r\  r_  r.   r.   r.   r/   r`  ª  s    r`  rd  c                 c  ó   � | ]	}d |› d �V  qdS ©ú"Nr.   rB  r.   r.   r/   rˆ   Ð  ó   € rˆ   ©rA  Z	BLAS_LIBSZOPENMP_LIBSc                      s4   e Zd ZdZd‡ fdd„	Zed‡ fdd„	ƒZ‡  ZS )r    aV
  Change the maximal number of threads that can be used in thread pools.

    This object can be used either as a callable (the construction of this object
    limits the number of threads), as a context manager in a `with` block to
    automatically restore the original state of the controlled libraries when exiting
    the block, or as a decorator through its `wrap` method.

    Set the maximal number of threads that can be used in thread pools used in
    the supported libraries to `limit`. This function works for libraries that
    are already loaded in the interpreter and can be changed dynamically.

    This effect is thread-local whenever possible but this is not guaranteed
    and actual behavior can depend on the controlled libraries. Notably,
    OpenBLAS built with the "windows" or "pthreads" threading layers uses a
    process-wide thread pool instead of independently controlled thread pools
    per calling threads.

    Parameters
    ----------
    limits : int, dict, list, 'sequential_blas_under_openmp' or None (default=None)
        The maximal number of threads that can be used in thread pools

        - If int, sets the maximum number of threads to `limits` for each
          library selected by `user_api`.

        - If it is a dictionary `{{key: max_threads}}`, this function sets a
          custom maximum number of threads for each `key` which can be either a
          `filepath`, `prefix`, or `user_api` for a specific library,
          checked in that order.

        - If it is a list, it should be a list of dictionaries of the form
          `{{"filepath": "/.../", "num_threads": 12}}`. Older versions of
          threadpoolctl accepted a `"prefix"` instead of `"filepath"`,
          so for maximal compatibility set both:
          `[{{"filepath": "...", "prefix": "...", "num_threads": 7}}]`

        - If 'sequential_blas_under_openmp', it will chose the appropriate `limits`
          and `user_api` parameters for the specific use case of sequential BLAS
          calls within an OpenMP parallel region. The `user_api` parameter is
          ignored.

        - If None, this function does not do anything.

    user_api : {USER_APIS} or None (default=None)
        APIs of libraries to limit. Used only if `limits` is an int.

        - If "blas", it will only limit BLAS supported libraries ({BLAS_LIBS}).

        - If "openmp", it will only limit OpenMP supported libraries
          ({OPENMP_LIBS}). Note that it can affect the number of threads used
          by the BLAS libraries if they rely on OpenMP.

        - If None, this function will apply to all supported libraries.
    Nc                   s   t ƒ jtƒ ||d� d S )NrT  )ró   rW   r   ©rV   rE  rZ   rô   r.   r/   rW     s   zthreadpool_limits.__init__c                   s   t ƒ jd||d�S )zAWrap a function, using ``get_cached_controller()`` on every call.NrT  )ró   ra  )r¾   rE  rZ   rô   r.   r/   ra    s   zthreadpool_limits.wrap)NN)r%   r&   r'   rs   rW   rÊ   ra  r  r.   r.   rô   r/   r    Ï  s
    7r    a™  
Found Intel OpenMP ('libiomp') and LLVM OpenMP ('libomp') loaded at
the same time. Both libraries are known to be incompatible and this
can cause random crashes or deadlocks on Linux when loaded in the
same Python program.
Using threadpoolctl may cause crashes or deadlocks. For more
information and possible workarounds, please see
    https://github.com/joblib/threadpoolctl/blob/master/multiple_openmp.md
c                   @  sR  e Zd ZdZi Zdd„ Zedd„ ƒZd;d<d	d
„Zdd„ Z	dd„ Z
ed dd„ eD ƒ¡d e¡d e¡d�dddœdd„ƒZed dd„ eD ƒ¡d e¡d e¡d�dddœdd„ƒZdd„ Zdd„ Ze dej¡Zdd „ Zd!d"„ Zd#d$„ Zd%d&„ Zd'd(„ Zed)d*„ ƒZd+d,„ Zd-d.„ Zd/d0„ Z d1d2„ Z!d3d4„ Z"d5d6„ Z#ed7d8„ ƒZ$ed9d:„ ƒZ%dS )=r   zëCollection of LibController objects for all loaded supported libraries

    Attributes
    ----------
    lib_controllers : list of `LibController` objects
        The list of library controllers of all loaded supported libraries.
    c                 C  s   g | _ |  ¡  |  ¡  d S r:   )rN  r  Ú_warn_if_incompatible_openmpri   r.   r.   r/   rW   /  s   zThreadpoolController.__init__c                 C  s   |   | ¡}||_|S r:   )Ú__new__rN  )r¾   rN  Znew_controllerr.   r.   r/   Ú_from_controllers4  s   
z&ThreadpoolController._from_controllersFrX   rY   c                   s   ‡ fdd„| j D ƒS )a	  Return lib_controllers info as a list of dicts.

        Parameters
        ----------
        debugging_info : bool
            Include extra fields which require more intrusive actions to
            obtain, and which can't always reliably be determined.
        c                   s   g | ]}|j ˆ d �‘qS )rò   )rg   rF  rò   r.   r/   r0  C  s    
ÿÿz-ThreadpoolController.info.<locals>.<listcomp>)rN  )rV   rX   r.   rò   r/   rg   :  s   
	þzThreadpoolController.infoc                   sH   ˆ   ¡ D ]\}}t|tƒs|gn|ˆ |< q‡ fdd„| jD ƒ}t |¡S )a>  Return a ThreadpoolController containing a subset of its current
        library controllers

        It will select all libraries matching at least one pair (key, value) from kwargs
        where key is an entry of the library info dict (like "user_api", "internal_api",
        "prefix", ...) and value is the value or a list of acceptable values for that
        entry.

        For instance, `ThreadpoolController().select(internal_api=["blis", "openblas"])`
        will select all library controllers whose internal_api is either "blis" or
        "openblas".
        c                   s*   g | ]‰ t ‡ fd d„ˆ ¡ D ƒƒrˆ ‘qS )c                 3  s$   � | ]\}}t ˆ |d ƒ|v V  qd S r:   )rn   )r]   r¡   ÚvalsrŠ   r.   r/   rˆ   [  s
   € ÿ
ÿz9ThreadpoolController.select.<locals>.<listcomp>.<genexpr>)r—   rc   )r]   ©r;  rŠ   r/   r0  X  s    þýÿz/ThreadpoolController.select.<locals>.<listcomp>)rc   rG  rL  rN  r   r{  )rV   r;  r¡   r|  rN  r.   r}  r/   ÚselectH  s   
þ
	zThreadpoolController.selectc                 C  s*   | j dd�j dd�jrdddœS dddœS )	zÍReturn appropriate params to use for a sequential BLAS call in an OpenMP loop

        This function takes into account the unexpected behavior of OpenBLAS with the
        OpenMP threading layer.
        r©   r/  r·   )r³   NrT  r8   r¨   )r~  rN  ri   r.   r.   r/   rH  c  s   
ÿý

zAThreadpoolController._get_params_for_sequential_blas_under_openmprd  c                 c  rs  rt  r.   rB  r.   r.   r/   rˆ   v  rv  zThreadpoolController.<genexpr>rw  NrT  c                C  s   t | ||d�S )aæ
  Change the maximal number of threads that can be used in thread pools.

        This function returns an object that can be used either as a callable (the
        construction of this object limits the number of threads) or as a context
        manager, in a `with` block to automatically restore the original state of the
        controlled libraries when exiting the block.

        Set the maximal number of threads that can be used in thread pools used in
        the supported libraries to `limits`. This function works for libraries that
        are already loaded in the interpreter and can be changed dynamically.

        This effect is thread-local whenever possible but this is not guaranteed
        and actual behavior can depend on the controlled libraries. Notably,
        OpenBLAS built with the "windows" or "pthreads" threading layers uses a
        process-wide thread pool instead of independently controlled thread pools
        per calling threads.

        Parameters
        ----------
        limits : int, dict, list, 'sequential_blas_under_openmp' or None (default=None)
            The maximal number of threads that can be used in thread pools

            - If int, sets the maximum number of threads to `limits` for each
              library selected by `user_api`.

            - If it is a dictionary `{{key: max_threads}}`, this function sets a
              custom maximum number of threads for each `key` which can be either a
              `filepath`, `prefix`, or `user_api` for a specific library,
              checked in that order.

            - If it is a list, it should be a list of dictionaries of the form
              `{{"filepath": "/.../", "num_threads": 12}}`. Older versions of
              threadpoolctl accepted a `"prefix"` instead of `"filepath"`,
              so for maximal compatibility set both:
              `[{{"filepath": "...", "prefix": "...", "num_threads": 7}}]`

            - If 'sequential_blas_under_openmp', it will chose the appropriate `limits`
              and `user_api` parameters for the specific use case of sequential BLAS
              calls within an OpenMP parallel region. The `user_api` parameter is
              ignored.

            - If None, this function does not do anything.

        user_api : {USER_APIS} or None (default=None)
            APIs of libraries to limit. Used only if `limits` is an int.

            - If "blas", it will only limit BLAS supported libraries ({BLAS_LIBS}).

            - If "openmp", it will only limit OpenMP supported libraries
              ({OPENMP_LIBS}). Note that it can affect the number of threads used
              by the BLAS libraries if they rely on OpenMP.

            - If None, this function will apply to all supported libraries.
        rT  )rS  rx  r.   r.   r/   rk  u  s   <zThreadpoolController.limitc                 c  rs  rt  r.   rB  r.   r.   r/   rˆ   ´  rv  c                C  s   t j| ||d�S )a¢  Change the maximal number of threads that can be used in thread pools.

        This function returns an object that can be used as a decorator.

        Set the maximal number of threads that can be used in thread pools used in
        the supported libraries to `limits`. This function works for libraries that
        are already loaded in the interpreter and can be changed dynamically.

        Parameters
        ----------
        limits : int, dict, list, 'sequential_blas_under_openmp', or None (default=None)
            The maximal number of threads that can be used in thread pools

            - If int, sets the maximum number of threads to `limits` for each
              library selected by `user_api`.

            - If it is a dictionary `{{key: max_threads}}`, this function sets a
              custom maximum number of threads for each `key` which can be either a
              `filepath`, `prefix`, or `user_api` for a specific library,
              checked in that order.

            - If it is a list, it should be a list of dictionaries of the form
              `{{"filepath": "/.../", "num_threads": 12}}`. Older versions of
              threadpoolctl accepted a `"prefix"` instead of `"filepath"`,
              so for maximal compatibility set both:
              `[{{"filepath": "...", "prefix": "...", "num_threads": 7}}]`

            - If 'sequential_blas_under_openmp', it will chose the appropriate `limits`
              and `user_api` parameters for the specific use case of sequential BLAS
              calls within an OpenMP parallel region. The `user_api` parameter is
              ignored.

            - If None, this function does not do anything.

        user_api : {USER_APIS} or None (default=None)
            APIs of libraries to limit. Used only if `limits` is an int.

            - If "blas", it will only limit BLAS supported libraries ({BLAS_LIBS}).

            - If "openmp", it will only limit OpenMP supported libraries
              ({OPENMP_LIBS}). Note that it can affect the number of threads used
              by the BLAS libraries if they rely on OpenMP.

            - If None, this function will apply to all supported libraries.
        rT  )rS  ra  rx  r.   r.   r/   ra  ³  s   3zThreadpoolController.wrapc                 C  s
   t | jƒS r:   )rf  rN  ri   r.   r.   r/   Ú__len__è  s   
zThreadpoolController.__len__c                 C  s˜   t rtjdd… dkrttddd„ ƒƒ r|  ¡  dS tdur%|  t¡ dS tjdkr0|  ¡  dS tjdkr;|  	¡  dS d	tj
v rF|  ¡  dS |  ¡  dS )
zALoop through loaded shared libraries and store the supported onesNr   r   Z_is_gil_enabledc                   S  rh   )NTr.   r.   r.   r.   r/   rÙ     rj   z6ThreadpoolController._load_libraries.<locals>.<lambda>Údarwinr   Zpyodide)Ú_HAS_PROCFSÚsysÚversion_inforn   Ú_find_libraries_with_linuxr   Ú_find_libraries_with_pythonÚplatformÚ_find_libraries_with_dyldÚ_find_libraries_on_windowsÚmodulesÚ_find_libraries_pyodideÚ$_find_libraries_with_dl_iterate_phdrri   r.   r.   r/   r  ë  s   ÿ


z$ThreadpoolController._load_librariess    (/[^\n]+\.so[^\n^/]*)\nc                 C  sd   t ddƒ�}| ¡ }W d  ƒ n1 sw   Y  t| j |¡ƒ}|D ]}| d¡}|  |¡ q#dS )z¸Loop through loaded libraries and return binders on supported ones

        Uses a Linux-specific mechanism:
        https://man7.org/linux/man-pages/man5/proc_pid_maps.5.html
        z/proc/self/mapsÚrbNrÂ   )ÚopenÚreadre  Ú_PATH_REÚfindallrÅ   Ú_make_controller_from_path)rV   ÚfÚmapsÚ	filepathsrJ   r.   r.   r/   r„    s   
ÿ
þz/ThreadpoolController._find_libraries_with_linuxc              
   C  s€   z|ƒ }W n t y" } zt d|›d�t¡ W Y d}~dS d}~ww |r4|d dtjfv r4|dd… }|D ]}|  |¡ q6dS )z‹Loop through loaded libraries and return binders on supported ones

        Uses Python's built-in support for this functionality.
        z4ctypes.util.dllist failed to list loaded libraries (zè). Native thread pools will not be inspected for this ThreadpoolController. Please report a minimal reproducer at https://github.com/joblib/threadpoolctl/issues so it can be investigated and possibly be reported upstream to CPython.Nr   rl   r8   )r˜   ri  rj  ÚRuntimeWarningr‚  Ú
executabler‘  )rV   r   r”  ÚexcrJ   r.   r.   r/   r…  %  s"   
ÿù	€óÿz0ThreadpoolController._find_libraries_with_pythonc                   sŠ   |   ¡ }t|dƒst dt¡ g S g ‰ ‡ fdd„}t tjt t	¡tj
tj¡}||ƒ}t d¡}| ||¡ ˆ D ]
}|  | d¡¡ q8dS )an  Loop through loaded libraries and return binders on supported ones

        This function is expected to work on POSIX system only.
        This code is adapted from code by Intel developer @anton-malakhov
        available at https://github.com/IntelPython/smp

        Copyright (c) 2017, Intel Corporation published under the BSD 3-Clause
        license
        Údl_iterate_phdrz9Could not find dl_iterate_phdr in the C standard library.c                   s   | j j}|rˆ  |¡ dS )Nr   )Úcontentsr$   r;   )rg   ÚsizeÚdatarJ   ©r”  r.   r/   Úmatch_library_callbackX  s   
zYThreadpoolController._find_libraries_with_dl_iterate_phdr.<locals>.match_library_callbackó    rÂ   N)Ú	_get_libcr…   ri  rj  r•  r)   Ú	CFUNCTYPErå   ÚPOINTERr#   Úc_size_tr*   r˜  r‘  rÅ   )rV   Úlibcr�  Zc_func_signatureZc_match_library_callbackr›  rJ   r.   rœ  r/   r‹  ?  s*   

þü
þz9ThreadpoolController._find_libraries_with_dl_iterate_phdrc                 C  sj   |   ¡ }t|dƒst dt¡ g S | ¡ }tj|j_	t
|ƒD ]}t | |¡¡}| d¡}|  |¡ qdS )z‰Loop through loaded libraries and return binders on supported ones

        This function is expected to work on OSX system only
        Ú_dyld_image_countz;Could not find _dyld_image_count in the C standard library.rÂ   N)rŸ  r…   ri  rj  r•  r¤  r)   r*   Z_dyld_get_image_namerÃ   rþ   Ú	string_atrÅ   r‘  )rV   r£  Zn_dyldr  rJ   r.   r.   r/   r‡  p  s   
þ

ûz.ThreadpoolController._find_libraries_with_dyldc              	   C  sÚ   ddl m} |  d¡}|  d¡}|  ||¡ | ¡ }t}t |¡}z|  |¡}W n t	y3   d}Y nw |durb|D ]%\}}	|	rKt
|	ƒ|d k rK|	}
n| j||||||d�}
|
dur_|  |
¡ q:dS |  |||||¡ dS )a%  Loop through loaded libraries and return binders on supported ones

        This function is expected to work on windows system only.

        Used when ``ctypes.util.dllist`` is unavailable (Python < 3.14).
        Module discovery uses a snapshot-first strategy:
        ``CreateToolhelp32Snapshot`` provides an atomic list of loaded
        modules, which is more robust than ``EnumProcessModulesEx`` under
        concurrent DLL load/unload. Paths that fit in
        ``MODULEENTRY32W.szExePath`` (shorter than ``MAX_PATH``) are used as-is.
        Truncated or empty snapshot paths are resolved with
        ``GetModuleFileNameW`` and, when needed, ``GetModuleFileNameExW`` with a
        larger buffer. If snapshot creation fails, enumeration falls back to
        ``EnumProcessModulesEx``.
        r   ©ÚMAX_PATHZPsapiÚkernel32Nr8   ©Úmax_pathÚpath_buf)Úctypes.wintypesr§  Ú_get_windllÚ_setup_windows_module_apisÚGetCurrentProcessÚ _WINDOWS_MAX_LIBRARY_PATH_LENGTHr)   Úcreate_unicode_bufferÚ_snapshot_loaded_modulesr˜   rf  Ú_resolve_module_filepathr‘  Ú,_find_libraries_with_enum_process_modules_ex)rV   r§  Úps_apiÚ	kernel_32Ú	h_processrª  r«  r‰  Úh_moduleÚsnapshot_pathrJ   r.   r.   r/   rˆ  ‡  s>   


ÿú
€ó
ÿz/ThreadpoolController._find_libraries_on_windowsc                 C  sä   ddl m}m}m}m} t| ddƒrdS ||j_||g|j_	||j_|t
jg|j_	||j_|t
jg|j_	||j_|t
j|g|j_	||j_|g|j_	||j_|t
 |¡|t
 |¡|g|j_	||j_||t
j|g|j_	||j_d| _dS )z:Set ctypes signatures for Windows module enumeration APIs.r   )ÚBOOLÚDWORDÚHANDLEÚHMODULEÚ_windows_module_apis_configuredFNT)r¬  rº  r»  r¼  r½  rn   r¯  rÃ   ÚCreateToolhelp32SnapshotÚargtypesr)   r+   ÚModule32FirstWÚModule32NextWÚ	c_wchar_pÚGetModuleFileNameWÚCloseHandler¡  ÚEnumProcessModulesExÚGetModuleFileNameExWr¾  )r¾   rµ  r¶  rº  r»  r¼  r½  r.   r.   r/   r®  ¼  s8   
ûü
z/ThreadpoolController._setup_windows_module_apisc              	     s‚  ddl m‰ m‰m‰ G ‡ ‡‡fdd„dtjƒ}d}d}d}d}ˆd	ƒj}d}t|ƒD ](}	| ||B t	 
¡ ¡}
|
|kr< n%t ¡ }||krEq*t |¡ ¡ }td
|› �ƒ‚t |¡ ¡ }td
|› �ƒ‚g }zW|ƒ }t |¡|_| |
t |¡¡sˆt ¡ }t |¡ ¡ }td|› �ƒ‚	 | |j|jf¡ | |
t |¡¡s²t ¡ }||kr±t |¡ ¡ }td|› �ƒ‚nq‰W | |
¡ |S | |
¡ w )aÌ  Return loaded modules as (hModule, snapshot_path) pairs.

        Uses CreateToolhelp32Snapshot for an atomic view of loaded modules, which
        is more robust than EnumProcessModulesEx when DLLs are loaded or unloaded
        concurrently. ``ERROR_BAD_LENGTH`` is retried a bounded number of times
        (the documented transient race when the module list changes mid-snapshot)
        and then raised as ``OSError`` so the caller can fall back.
        r   ©r»  r¼  r§  c                      s`   e Zd Zd” fd” fd” fd” fd” fde ej¡fd” fd”fd	ejd
 fdej” fg
ZdS )zEThreadpoolController._snapshot_loaded_modules.<locals>.MODULEENTRY32WÚdwSizeZth32ModuleIDZth32ProcessIDZGlblcntUsageZProccntUsageZmodBaseAddrZmodBaseSizeÚhModuleZszModuleé   Ú	szExePathN)r%   r&   r'   r)   r¡  Úc_byteÚc_wcharr-   r.   rÈ  r.   r/   ÚMODULEENTRY32Wí  s    örÏ  é   é   é   é   rÚ   z!CreateToolhelp32Snapshot failed: zModule32FirstW failed: TzModule32NextW failed: )r¬  r»  r¼  r§  r)   Ú	Structurerø   rþ   r¿  r�   ÚgetpidÚget_last_errorÚFormatErrorr!  r˜   r  rÉ  rÁ  r÷   r;   rÊ  rÌ  rÂ  rÅ  )rV   r¶  rÏ  ZTH32CS_SNAPMODULEZTH32CS_SNAPMODULE32ZERROR_BAD_LENGTHZERROR_NO_MORE_FILESZINVALID_HANDLE_VALUEZmax_snapshot_retriesr  Zsnap_handleÚerrÚmsgr‰  Z	lib_entryr.   rÈ  r/   r²  â  sX   	
ÿ
ÿù
þz-ThreadpoolController._snapshot_loaded_modulesc                 C  s¢   ddl m} | |||¡}|r||d k r|jS | ||||¡}|r+||d k r+|jS |r;|j}	t d|	›�t¡ dS t 	¡ }
t 
|
¡ ¡ }t d|› �t¡ dS )zCReturn the full path for a module, or None if it should be skipped.r   r¦  r8   zÜCould not get the full path of a dynamic library (path too long). This library will be ignored and threadpoolctl might not be able to control or display information about all loaded libraries. Here's the truncated path: NzáCould not get the path of a dynamic library (GetModuleFileNameW and GetModuleFileNameExW failed). This library will be ignored and threadpoolctl might not be able to control or display information about all loaded libraries. )r¬  r§  rÄ  rø   rÇ  ri  rj  r•  r)   rÖ  r×  r!  )rV   rµ  r¶  r·  r¸  rª  r«  r§  Zn_sizerJ   rØ  rÙ  r.   r.   r/   r³  )  s2   
ýûüúz-ThreadpoolController._resolve_module_filepathc              	   C  sÂ   ddl m}m} d}d}	|ƒ }
	 ||	 ƒ }t |¡}| |||t |
¡|¡s*tdƒ‚||
jkr0n|
j||	  }	q|
j||	  }t	||d|… ƒD ]}| j
||||||d�}|dur^|  |¡ qHdS )	zÑFallback Windows module enumeration using EnumProcessModulesEx.

        This code is adapted from code by Philipp Hagemeister @phihag available
        at https://stackoverflow.com/questions/17474574
        r   )r»  r½  r   rË  TzEnumProcessModulesEx failedNr©  )r¬  r»  r½  r)   r  rÆ  r÷   r˜   rø   Úmapr³  r‘  )rV   rµ  r¶  r·  rª  r«  r»  r½  ZLIST_LIBRARIES_ALLZ	buf_countZneededÚbufÚbuf_sizerÌ   r¸  rJ   r.   r.   r/   r´  S  sB   

û
óú
€özAThreadpoolController._find_libraries_with_enum_process_modules_exc                 C  sv   zddl m} W n ty   t d¡ Y dS w t|jdƒr$|j ¡ }n|j ¡ }|D ]}t	j
 |¡r8|  |¡ q+dS )a¢  Pyodide specific implementation for finding loaded libraries.

        Adapted from suggestion in https://github.com/joblib/threadpoolctl/pull/169#issuecomment-1946696449.

        One day, we may have a simpler solution. libc dl_iterate_phdr needs to
        be implemented in Emscripten and exposed in Pyodide, see
        https://github.com/emscripten-core/emscripten/issues/21354 for more
        details.
        r   )ÚLDSOzHUnable to import LDSO from pyodide_js._module. This should never happen.NÚ
as_py_json)Zpyodide_js._modulerÝ  ÚImportErrorri  rj  r…   ZloadedLibsByNamerÞ  Zas_object_mapr�   r�   Úexistsr‘  )rV   rÝ  Z	libs_iterrJ   r.   r.   r/   rŠ    s    
ÿû

€úz,ThreadpoolController._find_libraries_pyodidec                 C  sB   t  || ¡}|dur|jdd„ | jD ƒv rdS | j |¡ dS dS )z:Store a library controller if it is supported and selectedNc                 s  s   � | ]}|j V  qd S r:   r@  r*  r.   r.   r/   rˆ   £  s   € 
ÿzBThreadpoolController._make_controller_from_path.<locals>.<genexpr>)rM   rš   rJ   rN  r;   )rV   rJ   r‹   r.   r.   r/   r‘  Ÿ  s   
ÿùz/ThreadpoolController._make_controller_from_pathc                 C  sF   t jdkrdS dd„ | jD ƒ}d|v rd|v r!t tt¡ dS dS dS )z?Raise a warning if llvm-OpenMP and intel-OpenMP are both loadedr   Nc                 S  r.  r.   )rK   rF  r.   r.   r/   r0  ´  r-  zEThreadpoolController._warn_if_incompatible_openmp.<locals>.<listcomp>r(  r'  )r‚  r†  rN  ri  rj  Ú_INCOMPATIBLE_OPENMP_MESSAGEr•  )rV   Úprefixesr.   r.   r/   ry  «  s   
ÿz1ThreadpoolController._warn_if_incompatible_openmpc                 C  s0   | j  d¡}|du rtjdtd�}|| j d< |S )z Load the lib-C for unix systems.r£  Nrœ   )Ú_system_librariesrŒ   r)   r•   r–   )r¾   r£  r.   r.   r/   rŸ  ¸  s
   
zThreadpoolController._get_libcc                 C  s6   | j  |¡}|du rtj|› d�dd�}|| j |< |S )zLoad a windows DLLNr„   T)Úuse_last_error)rã  rŒ   r)   ÚWinDLL)r¾   Zdll_nameÚdllr.   r.   r/   r­  Ç  s
   
z ThreadpoolController._get_windllrq   rr   )&r%   r&   r'   rs   rã  rW   rÊ   r{  rg   r~  rH  r=  rC   r1  Ú_ALL_BLAS_LIBRARIESÚ_ALL_OPENMP_LIBRARIESrk  ra  r  r  r  ÚcompileÚ	MULTILINEr�  r„  r…  r‹  r‡  rˆ  r®  r²  r³  r´  rŠ  r‘  ry  rŸ  r­  r.   r.   r.   r/   r      sR    
ý9ý0+15
%G*, 
r   c               	   C  sÔ   ddl } ddl}ddl}ddl}| jddd�}|jdddd	d
dd� |jdddd� | |jdd… ¡}|jD ]}z	|j	|dd� W q7 t
yS   td||jd� Y q7w |jr\t|jƒ t|jtdd�dd�ƒ dS )zBCommandline interface to display thread-pool information and exit.r   Nz5python -m threadpoolctl -i numpy scipy.linalg xgboostz)Display thread-pool information and exit.)ÚusageÚdescriptionz-iz--importr‰  Ú*r.   z;Python modules to import before introspecting thread-pools.)ÚdestÚnargsÚdefaultÚhelpz-cz	--commandz@a Python statement to execute before introspecting thread-pools.)rñ  r8   )ÚpackagezWARNING: could not import)ÚfileTrò   r   )Úindent)ÚargparseÚ	importlibÚjsonr‚  ÚArgumentParserÚadd_argumentÚ
parse_argsÚargvr‰  Úimport_modulerß  ÚprintÚstderrÚcommandÚexecÚdumpsr   )rõ  rö  r÷  r‚  ÚparserÚoptionsÚmoduler.   r.   r/   Ú_mainÑ  s>   þúý
ÿ
r  c                  C  sn   t } tttjƒkr| dur| S t� ttjƒ}t du s|tkr$tƒ a |at W  d  ƒ S 1 s0w   Y  dS )a-  Return a cached ``ThreadpoolController``, as a speed optimization.

    The cached version is regenerated if the number of imported of modules has
    changed, since this indicates the possibility that a new controllable
    library has been loaded.  Invalidation also happens if Flexiblas is in use
    and has changed its backend.

    It is possible that somehow a controllable library gets loaded without
    importing a Python module, e.g. using ``dlopen()`` on Linux, a ctypes
    ``CDLL``, and the like.  This is rare, however.  Outside of these
    situations, using ``get_cached_controller()`` will be much faster than
    creating a new ``ThreadpoolController`` instance.

    The cached controller can be explicitly invalidated by calling the
    `reset_cached_controller()` module level function.
    N)r  Ú_CACHED_SYS_MODULES_LENrf  r‚  r‰  r  r   )r6  Znum_modulesr.   r.   r/   r      s   
$ùr   r9   c                   C  s2   t � dadaW d  ƒ dS 1 sw   Y  dS )z2Clear the cached ``ThreadpoolController``, if any.Nr   )r  r  r  r.   r.   r.   r/   r   #  s   "þr   Ú__main__)r2   r3   r4   r5   r6   r7   rq   rr   )r6   r   rA   )drs   Ú
__future__r   r)   r¬   r�   r  r‚  ri  Úabcr   r   Úcollections.abcr   Ú
contextlibr   Údataclassesr   r   Ú	functoolsr	   r
   Ú	threadingr   r   r   r   ro  Útypingr   r   r   r   r†  rƒ  Úctypes.utilrß  r   Ú__version__Ú__all__ÚenvironÚ
setdefaultr°  r>  Úc_uint64Úc_uint32r(   Úc_uint16r,   r�   rà  r�  rÔ  r#   ÚRTLD_NOLOADr–   ÚAttributeErrorÚDEFAULT_MODEr7   rH   r   Úobjectr�   ru   rv   rM   rD   rË   r[  rÏ   ræ   r  r&  r“   rL  r1  r2  r3  rç  r}   rè  r   r=  rŽ   r   rM  rR  rS  r`  rC   r    rá  r   r  r  r  r  r   r   r%   r.   r.   r.   r/   Ú<module>   sÜ    

þ


ü


ÿþ
Gm  0E @û	ÿÿ	
9f%ýA     6(

#

ÿ