a
    ˜¥»aI  ã                   @   sª  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mZ d dl	Z	d dl
Z
d dlmZmZmZmZ d dlZeeejf Zeeejejf ZerÊeeeejjejjf  Zedeejjejjf d�Zzd dlmZ W n  eyú   G dd	„ d	ƒZY n0 d.d
d„Zd/dd„Z eddfdd„Z!dd„ Z"dd„ Z#eedœdd„Z$G dd„ dƒZ%dd„ Z&d0dd„Z'd1d d!„Z(ed"g d#¢ƒZ)d$d%„ Z*G d&d'„ d'ƒZ+d2d)d*„Z,ed3d,d-„ƒZ-dS )4é    )ÚcontextmanagerN)Ú
namedtuple)ÚOptionalÚUnionÚTYPE_CHECKINGÚTypeVarÚGeneratorType)Úbound)Ú	Generatorc                   @   s   e Zd ZdS )r
   N)Ú__name__Ú
__module__Ú__qualname__© r   r   úJ/home/yuhw/wc/pochoir/venv/lib/python3.9/site-packages/scipy/_lib/_util.pyr
   !   s   r
   c           	         sð   t  ˆ ¡‰ |du r,|du r$tdƒ‚q<t j}n|dur<tdƒ‚t jˆ g|¢R Ž }|d |dd…  ‰ }t‡ fdd„|D ƒƒ}t  dd	„ |D ƒ¡}t jt  |d ¡||d
�}t  	|ˆ ||Ž ¡ |durìt‡ fdd„|D ƒƒ}t  	|ˆ  ||Ž ¡ |S )aË  
    np.where(cond, x, fillvalue) always evaluates x even where cond is False.
    This one only evaluates f(arr1[cond], arr2[cond], ...).

    Examples
    --------
    >>> a, b = np.array([1, 2, 3, 4]), np.array([5, 6, 7, 8])
    >>> def f(a, b):
    ...     return a*b
    >>> _lazywhere(a > 2, (a, b), f, np.nan)
    array([ nan,  nan,  21.,  32.])

    Notice, it assumes that all `arrays` are of the same shape, or can be
    broadcasted together.

    Nz%One of (fillvalue, f2) must be given.z)Only one of (fillvalue, f2) can be given.r   é   c                 3   s   | ]}t  ˆ |¡V  qd S ©N©ÚnpÚextract©Ú.0Zarr©Úcondr   r   Ú	<genexpr>B   ó    z_lazywhere.<locals>.<genexpr>c                 S   s   g | ]}|j j‘qS r   ©ÚdtypeÚchar©r   Úar   r   r   Ú
<listcomp>C   r   z_lazywhere.<locals>.<listcomp>©Z
fill_valuer   c                 3   s   | ]}t  ˆ  |¡V  qd S r   r   r   r   r   r   r   G   r   )
r   ÚasarrayÚ
ValueErrorÚnanÚbroadcast_arraysÚtupleÚmintypecodeÚfullÚshapeÚplace)	r   ÚarraysÚfÚ	fillvalueÚf2ÚargsÚtempÚtcodeÚoutr   r   r   Ú
_lazywhere%   s"    

r3   c           
         s¬   t j|Ž }t  dd„ |D ƒ¡}t jt  |d ¡||d�}tt| ƒƒD ]b}|| | |  }‰ t  ˆ du ¡rjqDt  ˆ |d ¡\‰ }t‡ fdd„|D ƒƒ}	t  	|ˆ ||	Ž ¡ qD|S )a?  
    Mimic `np.select(condlist, choicelist)`.

    Notice, it assumes that all `arrays` are of the same shape or can be
    broadcasted together.

    All functions in `choicelist` must accept array arguments in the order
    given in `arrays` and must return an array of the same shape as broadcasted
    `arrays`.

    Examples
    --------
    >>> x = np.arange(6)
    >>> np.select([x <3, x > 3], [x**2, x**3], default=0)
    array([  0,   1,   4,   0,  64, 125])

    >>> _lazyselect([x < 3, x > 3], [lambda x: x**2, lambda x: x**3], (x,))
    array([   0.,    1.,    4.,   0.,   64.,  125.])

    >>> a = -np.ones_like(x)
    >>> _lazyselect([x < 3, x > 3],
    ...             [lambda x, a: x**2, lambda x, a: a * x**3],
    ...             (x, a), default=np.nan)
    array([   0.,    1.,    4.,   nan,  -64., -125.])

    c                 S   s   g | ]}|j j‘qS r   r   r   r   r   r   r    i   r   z_lazyselect.<locals>.<listcomp>r   r!   Fc                 3   s   | ]}t  ˆ |¡V  qd S r   r   r   r   r   r   r   p   r   z_lazyselect.<locals>.<genexpr>)
r   r%   r'   r(   r)   ÚrangeÚlenÚallr&   r*   )
ZcondlistZ
choicelistr+   Údefaultr1   r2   ÚindexÚfuncÚ_r0   r   r   r   Ú_lazyselectM   s    
r;   ÚCc                 C   s°   t  |¡}|du r|j}t| dƒs(| f} t tj| ¡|j }t  	|| d t j
¡}|jd d | }|dkrt|| }|||| d … dd… }t j| |||d�}| d¡ |S )zôAllocate a new ndarray with aligned memory.

    Primary use case for this currently is working around a f2py issue
    in NumPy 1.9.1, where dtype.alignment is such that np.zeros() does
    not necessarily create arrays aligned up to it.

    NÚ__len__r   Údatar   éÿÿÿÿ)Úorder)r   r   Ú	alignmentÚhasattrÚ	functoolsÚreduceÚoperatorÚmulÚitemsizeÚemptyZuint8Z__array_interface__ZndarrayÚfill)r)   r   r@   ZalignÚsizeÚbufÚoffsetr>   r   r   r   Ú_aligned_zerosu   s    


rM   c                 C   s(   | j dur$| j| j jd k r$|  ¡ S | S )zÅReturn an array equivalent to the input array. If the input
    array is a view of a much larger array, copy its contents to a
    newly allocated array. Otherwise, return the input unchanged.
    Né   )ÚbaserJ   Úcopy)Úarrayr   r   r   Ú_prune_array�   s    rR   c                 C   s   d}| D ]}||9 }q|S )z›
    Product of a sequence of numbers.

    Faster than np.prod for short lists like array shapes, and does
    not overflow if using Python integers.
    r   r   )ÚiterableÚproductÚxr   r   r   Úprod™   s    
rV   )ÚnÚreturnc                 C   s   | dk rt t | ¡ƒS tjS )zlCompute the factorial and return as a float

    Returns infinity when result is too large for a double
    é«   )ÚfloatÚmathÚ	factorialr   Úinf)rW   r   r   r   Úfloat_factorial¦   s    r^   c                   @   s(   e Zd ZdZdd„ Zdd„ Zdd„ ZdS )	ÚDeprecatedImporta3  
    Deprecated import with redirection and warning.

    Examples
    --------
    Suppose you previously had in some module::

        from foo import spam

    If this has to be deprecated, do::

        spam = DeprecatedImport("foo.spam", "baz")

    to redirect users to use "baz" module instead.

    c                 C   s(   || _ || _t| jƒ tj| j | _d S r   )Ú	_old_nameÚ	_new_nameÚ
__import__ÚsysÚmodulesÚ_mod)ÚselfZold_module_nameZnew_module_namer   r   r   Ú__init__À   s    
zDeprecatedImport.__init__c                 C   s
   t | jƒS r   )Údirre   ©rf   r   r   r   Ú__dir__Æ   s    zDeprecatedImport.__dir__c                 C   s$   t  d| j| jf t¡ t| j|ƒS )Nz'Module %s is deprecated, use %s instead)ÚwarningsÚwarnr`   ra   ÚDeprecationWarningÚgetattrre   )rf   Únamer   r   r   Ú__getattr__É   s    
ÿþzDeprecatedImport.__getattr__N)r   r   r   Ú__doc__rg   rj   rp   r   r   r   r   r_   ®   s   r_   c                 C   sˆ   | du s| t ju rt jjjS t| tjt jfƒr:t j | ¡S t| t jjƒrL| S zt| t jj	ƒrb| W S W n t
yv   Y n0 td|  ƒ‚dS )am  Turn `seed` into a `np.random.RandomState` instance.

    Parameters
    ----------
    seed : {None, int, `numpy.random.Generator`,
            `numpy.random.RandomState`}, optional

        If `seed` is None (or `np.random`), the `numpy.random.RandomState`
        singleton is used.
        If `seed` is an int, a new ``RandomState`` instance is used,
        seeded with `seed`.
        If `seed` is already a ``Generator`` or ``RandomState`` instance then
        that instance is used.

    Returns
    -------
    seed : {`numpy.random.Generator`, `numpy.random.RandomState`}
        Random number generator.

    Nz=%r cannot be used to seed a numpy.random.RandomState instance)r   ÚrandomÚmtrandÚ_randÚ
isinstanceÚnumbersÚIntegralÚintegerÚRandomStater
   ÚAttributeErrorr#   ©Úseedr   r   r   Úcheck_random_stateÒ   s    

ÿr}   TFc           	      C   s–   |s$ddl }|j | ¡r$d}t|ƒ‚|s<tj | ¡r<tdƒ‚|rFtjntj}|| ƒ} |sp| j	t 	d¡u rptdƒ‚|r’t 
| j	tj¡s’|| tjd�} | S )aA  
    Helper function for SciPy argument validation.

    Many SciPy linear algebra functions do support arbitrary array-like
    input arguments. Examples of commonly unsupported inputs include
    matrices containing inf/nan, sparse matrix representations, and
    matrices with complicated elements.

    Parameters
    ----------
    a : array_like
        The array-like input.
    check_finite : bool, optional
        Whether to check that the input matrices contain only finite numbers.
        Disabling may give a performance gain, but may result in problems
        (crashes, non-termination) if the inputs do contain infinities or NaNs.
        Default: True
    sparse_ok : bool, optional
        True if scipy sparse matrices are allowed.
    objects_ok : bool, optional
        True if arrays with dype('O') are allowed.
    mask_ok : bool, optional
        True if masked arrays are allowed.
    as_inexact : bool, optional
        True to convert the input array to a np.inexact dtype.

    Returns
    -------
    ret : ndarray
        The converted validated array.

    r   NzxSparse matrices are not supported by this function. Perhaps one of the scipy.sparse.linalg functions would work instead.zmasked arrays are not supportedÚOzobject arrays are not supported)r   )Zscipy.sparseÚsparseÚissparser#   r   ÚmaZisMaskedArrayZasarray_chkfiniter"   r   Z
issubdtypeZinexactZfloat_)	r   Zcheck_finiteZ	sparse_okZ
objects_okZmask_okZ
as_inexactZscipyÚmsgZtoarrayr   r   r   Ú_asarray_validated÷   s"    #rƒ   c                 C   sZ   zt  | ¡} W n" ty0   t|› d�ƒd‚Y n0 |durV| |k rVt|› d|› �ƒd‚| S )a»  
    Validate a scalar integer.

    This functon can be used to validate an argument to a function
    that expects the value to be an integer.  It uses `operator.index`
    to validate the value (so, for example, k=2.0 results in a
    TypeError).

    Parameters
    ----------
    k : int
        The value to be validated.
    name : str
        The name of the parameter.
    minimum : int, optional
        An optional lower bound.
    z must be an integer.Nz" must be an integer not less than )rE   r8   Ú	TypeErrorr#   )Úkro   Zminimumr   r   r   Ú_validate_int/  s    ÿÿr†   ÚFullArgSpec)r/   ÚvarargsÚvarkwÚdefaultsÚ
kwonlyargsÚkwonlydefaultsÚannotationsc           	      C   sÖ   t  | ¡}dd„ |j ¡ D ƒ}dd„ |j ¡ D ƒ}|r>|d nd}dd„ |j ¡ D ƒ}|rb|d nd}tdd„ |j ¡ D ƒƒp€d}d	d„ |j ¡ D ƒ}d
d„ |j ¡ D ƒ}dd„ |j ¡ D ƒ}t||||||pÐd|ƒS )as  inspect.getfullargspec replacement using inspect.signature.

    If func is a bound method, do not list the 'self' parameter.

    Parameters
    ----------
    func : callable
        A callable to inspect

    Returns
    -------
    fullargspec : FullArgSpec(args, varargs, varkw, defaults, kwonlyargs,
                              kwonlydefaults, annotations)

        NOTE: if the first argument of `func` is self, it is *not*, I repeat
        *not*, included in fullargspec.args.
        This is done for consistency between inspect.getargspec() under
        Python 2.x, and inspect.signature() under Python 3.x.

    c                 S   s(   g | ] }|j tjjtjjfv r|j‘qS r   )ÚkindÚinspectÚ	ParameterÚPOSITIONAL_OR_KEYWORDÚPOSITIONAL_ONLYro   ©r   Úpr   r   r   r    s  s
   
ÿÿz*getfullargspec_no_self.<locals>.<listcomp>c                 S   s    g | ]}|j tjjkr|j‘qS r   )rŽ   r�   r�   ÚVAR_POSITIONALro   r“   r   r   r   r    x  s   ÿr   Nc                 S   s    g | ]}|j tjjkr|j‘qS r   )rŽ   r�   r�   ÚVAR_KEYWORDro   r“   r   r   r   r    }  s   ÿc                 s   s.   | ]&}|j tjjkr|j|jur|jV  qd S r   )rŽ   r�   r�   r‘   r7   rH   r“   r   r   r   r   ‚  s   þz)getfullargspec_no_self.<locals>.<genexpr>c                 S   s    g | ]}|j tjjkr|j‘qS r   )rŽ   r�   r�   ÚKEYWORD_ONLYro   r“   r   r   r   r    ‡  s   ÿc                 S   s0   i | ](}|j tjjkr|j|jur|j|j“qS r   )rŽ   r�   r�   r—   r7   rH   ro   r“   r   r   r   Ú
<dictcomp>‹  s   þz*getfullargspec_no_self.<locals>.<dictcomp>c                 S   s"   i | ]}|j |jur|j|j “qS r   )Ú
annotationrH   ro   r“   r   r   r   r˜   Ž  s   ÿ)r�   Ú	signatureÚ
parametersÚvaluesr&   r‡   )	r9   Úsigr/   rˆ   r‰   rŠ   r‹   Ú
kwdefaultsr�   r   r   r   Úgetfullargspec_no_self]  s2    
ÿÿÿÿüÿÿrŸ   c                   @   sJ   e Zd ZdZddd„Zdd„ Zdd„ Zd	d
„ Zdd„ Zdd„ Z	dd„ Z
dS )Ú
MapWrapperav  
    Parallelisation wrapper for working with map-like callables, such as
    `multiprocessing.Pool.map`.

    Parameters
    ----------
    pool : int or map-like callable
        If `pool` is an integer, then it specifies the number of threads to
        use for parallelization. If ``int(pool) == 1``, then no parallel
        processing is used and the map builtin is used.
        If ``pool == -1``, then the pool will utilize all available CPUs.
        If `pool` is a map-like callable that follows the same
        calling sequence as the built-in map function, then this callable is
        used for parallelization.
    r   c                 C   s¤   d | _ t| _d| _t|ƒr*|| _ | j | _nvddlm} t|ƒdkr\|ƒ | _ | j j| _d| _nDt|ƒdkrjn6t|ƒdkr˜|t|ƒd�| _ | j j| _d| _ntdƒ‚d S )	NFr   )ÚPoolr?   Tr   )Z	processeszUNumber of workers specified must be -1, an int >= 1, or an object with a 'map' method)	ÚpoolÚmapÚ_mapfuncÚ	_own_poolÚcallableÚmultiprocessingr¡   ÚintÚRuntimeError)rf   r¢   r¡   r   r   r   rg   ¤  s$    


zMapWrapper.__init__c                 C   s   | S r   r   ri   r   r   r   Ú	__enter__À  s    zMapWrapper.__enter__c                 C   s   | j r| j ¡  d S r   )r¥   r¢   Ú	terminateri   r   r   r   r«   Ã  s    zMapWrapper.terminatec                 C   s   | j r| j ¡  d S r   )r¥   r¢   Újoinri   r   r   r   r¬   Ç  s    zMapWrapper.joinc                 C   s   | j r| j ¡  d S r   )r¥   r¢   Úcloseri   r   r   r   r­   Ë  s    zMapWrapper.closec                 C   s   | j r| j ¡  | j ¡  d S r   )r¥   r¢   r­   r«   )rf   Úexc_typeÚ	exc_valueÚ	tracebackr   r   r   Ú__exit__Ï  s    
zMapWrapper.__exit__c              
   C   sB   z|   ||¡W S  ty< } ztdƒ|‚W Y d }~n
d }~0 0 d S )Nz;The map-like callable must be of the form f(func, iterable))r¤   r„   )rf   r9   rS   Úer   r   r   Ú__call__Ô  s    ÿzMapWrapper.__call__N)r   )r   r   r   rq   rg   rª   r«   r¬   r­   r±   r³   r   r   r   r   r    ”  s   
r    Úint64c                 C   s„   t | tƒr| j|||||d�S | du r0tjjj} |rn|du rP| j|d ||d�S |durn| j||d ||d�S | j||||d�S dS )al  
    Return random integers from low (inclusive) to high (exclusive), or if
    endpoint=True, low (inclusive) to high (inclusive). Replaces
    `RandomState.randint` (with endpoint=False) and
    `RandomState.random_integers` (with endpoint=True).

    Return random integers from the "discrete uniform" distribution of the
    specified dtype. If high is None (the default), then results are from
    0 to low.

    Parameters
    ----------
    gen : {None, np.random.RandomState, np.random.Generator}
        Random number generator. If None, then the np.random.RandomState
        singleton is used.
    low : int or array-like of ints
        Lowest (signed) integers to be drawn from the distribution (unless
        high=None, in which case this parameter is 0 and this value is used
        for high).
    high : int or array-like of ints
        If provided, one above the largest (signed) integer to be drawn from
        the distribution (see above for behavior if high=None). If array-like,
        must contain integer values.
    size : array-like of ints, optional
        Output shape. If the given shape is, e.g., (m, n, k), then m * n * k
        samples are drawn. Default is None, in which case a single value is
        returned.
    dtype : {str, dtype}, optional
        Desired dtype of the result. All dtypes are determined by their name,
        i.e., 'int64', 'int', etc, so byteorder is not available and a specific
        precision may have different C types depending on the platform.
        The default value is np.int_.
    endpoint : bool, optional
        If True, sample from the interval [low, high] instead of the default
        [low, high) Defaults to False.

    Returns
    -------
    out: int or ndarray of ints
        size-shaped array of random integers from the appropriate distribution,
        or a single such random int if size not provided.
    )ÚhighrJ   r   ÚendpointNr   )rJ   r   )rµ   rJ   r   )ru   r
   Zintegersr   rr   rs   rt   Úrandint)ÚgenÚlowrµ   rJ   r   r¶   r   r   r   Úrng_integersÞ  s    ,
ÿ
rº   ì	   !E^Ã‹1ÝcuBän½ c                 #   s>   t jj‰ | f‡ fdd„	t j_zdV  W ˆ t j_n
ˆ t j_0 dS )z0Context with a fixed np.random.default_rng seed.c                    s   ˆ | ƒS r   r   r{   ©Zorig_funr   r   Ú<lambda>"  r   z$_fixed_default_rng.<locals>.<lambda>N)r   rr   Zdefault_rngr{   r   r¼   r   Ú_fixed_default_rng  s
    r¾   )NN)r   )TFFFF)N)NNr´   F)r»   ).Ú
contextlibr   rC   rE   rc   rk   rv   Úcollectionsr   r�   r[   Útypingr   r   r   r   Únumpyr   r¨   rx   Z	IntNumberrZ   ZfloatingZDecimalNumberrr   r
   ry   ZSeedTyper   Znumpy.randomÚImportErrorr3   r;   rM   rR   rV   r^   r_   r}   rƒ   r†   r‡   rŸ   r    rº   r¾   r   r   r   r   Ú<module>   s\   ÿÿ

(
(
$%   þ
8
)ÿ7J  ÿ
@