U
    Gvf_                  	   @   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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re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k
r   G dd	 d	ZY nX dAd
dZdBddZeddfddZ dd Z!dd Z"eedddZ#dd Z$dCddZ%dDddZ&ed d!d"d#d$d%d&d'gZ'd(d) Z(G d*d+ d+Z)G d,d- d-Z*dEd/d0Z+edFd2d3Z,dGd4d5Z-d6d7 Z.dHd8d9Z/dId;d<Z0dJd=d>Z1d?d@ Z2dS )K    )contextmanagerN)
namedtuple)OptionalUnionTYPE_CHECKINGTypeVarGeneratorType)bound)	Generatorc                   @   s   e Zd ZdS )r
   N)__name__
__module____qualname__ r   r   4/tmp/pip-unpacked-wheel-96ln3f52/scipy/_lib/_util.pyr
       s   r
   c           	         s   t   |dkr,|dkr$tdq<t j}n|dk	r<tdt j f| }|d |dd   }t fdd|D }t dd	 |D }t jt |d ||d
}t 	| ||  |dk	rt 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
    --------
    >>> import numpy as np
    >>> 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   s     z_lazywhere.<locals>.<genexpr>c                 S   s   g | ]}|j jqS r   dtypecharr   ar   r   r   
<listcomp>C   s     z_lazywhere.<locals>.<listcomp>Z
fill_valuer   c                 3   s   | ]}t   |V  qd S r   r   r   r   r   r   r   G   s     )
r   asarray
ValueErrornanbroadcast_arraystuplemintypecodefullshapeplace)	r   arraysf	fillvaluef2argstemptcodeoutr   r   r   
_lazywhere$   s"    

r2   c           	         s   t j| }t dd |D }t jt |d ||d}t|| D ]T\} t  dkrZqBt  |d \ }t fdd|D }t | ||  qB|S )aZ  
    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
    --------
    >>> import numpy as np
    >>> 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   j   s     z_lazyselect.<locals>.<listcomp>r   r    Fc                 3   s   | ]}t  |V  qd S r   r   r   r   r   r   r   p   s     z_lazyselect.<locals>.<genexpr>)	r   r$   r&   r'   r(   zipallr%   r)   )	ZcondlistZ
choicelistr*   defaultr0   r1   func_r/   r   r   r   _lazyselectM   s    
r8   Cc                 C   s   t |}|dk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 )zAllocate 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__ndarrayfill)r(   r   r=   Zalignsizebufoffsetr;   r   r   r   _aligned_zerosu   s    


rK   c                 C   s(   | j dk	r$| j| j jd k r$|  S | S )zReturn 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   )baserH   copy)arrayr   r   r   _prune_array   s    rP   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    
rT   )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)rU   r   r   r   float_factorial   s    r\   c                 C   sd   | dks| t jkrt jjjS t| tjt jfr:t j| S t| t jjt jj	frT| S t
d|  dS )a`  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
   r"   seedr   r   r   check_random_state   s    
rg   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krptd|rt
| 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   
issubdtypeinexactZfloat_)	r   Zcheck_finiteZ	sparse_okZ
objects_okZmask_okZ
as_inexactZscipymsgZtoarrayr   r   r   _asarray_validated   s"    #ro   c                 C   s\   zt | } W n$ tk
r2   t| ddY nX |dk	rX| |k rXt| 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 )rB   index	TypeErrorr"   )knameZminimumr   r   r   _validate_int  s    rt   FullArgSpecr.   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 pd}d	d |j D }d
d |j D }dd |j D }t||||||pd|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kr|jqS r   )kindinspect	ParameterPOSITIONAL_OR_KEYWORDPOSITIONAL_ONLYrs   r   pr   r   r   r   J  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_POSITIONALrs   r   r   r   r   r   O  s   r   Nc                 S   s    g | ]}|j tjjkr|jqS r   )r|   r}   r~   VAR_KEYWORDrs   r   r   r   r   r   T  s   c                 s   s.   | ]&}|j tjjkr|j|jk	r|jV  qd S r   )r|   r}   r~   r   r5   rE   r   r   r   r   r   Y  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_ONLYrs   r   r   r   r   r   ^  s   c                 S   s0   i | ](}|j tjjkr|j|jk	r|j|jqS r   )r|   r}   r~   r   r5   rE   rs   r   r   r   r   
<dictcomp>b  s
     z*getfullargspec_no_self.<locals>.<dictcomp>c                 S   s"   i | ]}|j |jk	r|j|j qS r   )
annotationrE   rs   r   r   r   r   r   e  s     )r}   	signature
parametersvaluesr%   ru   )	r6   sigr.   rv   rw   rx   ry   
kwdefaultsr{   r   r   r   getfullargspec_no_self4  s4    
 r   c                   @   s    e Zd ZdZdd Zdd ZdS )_FunctionWrapperz?
    Object to wrap user's function, allowing picklability
    c                 C   s   || _ |d krg n|| _d S r   r+   r.   )selfr+   r.   r   r   r   __init__o  s    z_FunctionWrapper.__init__c                 C   s   | j |f| j S r   r   )r   rS   r   r   r   __call__s  s    z_FunctionWrapper.__call__N)r   r   r   __doc__r   r   r   r   r   r   r   k  s   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)r   r   r   r   r   r   r     s$    


zMapWrapper.__init__c                 C   s   | S r   r   r   r   r   r   	__enter__  s    zMapWrapper.__enter__c                 C   s   | j r| j  d S r   )r   r   	terminater   r   r   r   r     s    zMapWrapper.terminatec                 C   s   | j r| j  d S r   )r   r   joinr   r   r   r   r     s    zMapWrapper.joinc                 C   s   | j r| j  d S r   )r   r   closer   r   r   r   r     s    zMapWrapper.closec                 C   s   | j r| j  | j  d S r   )r   r   r   r   )r   exc_type	exc_value	tracebackr   r   r   __exit__  s    
zMapWrapper.__exit__c              
   C   s@   z|  ||W S  tk
r: } ztd|W 5 d }~X Y nX d S )Nz;The map-like callable must be of the form f(func, iterable))r   rq   )r   r6   rQ   er   r   r   r     s    zMapWrapper.__call__N)r   )r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   w  s   
r   int64c                 C   s   t | tr| j|||||dS | dkr0tjjj} |rn|dkrP| j|d ||dS |dk	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.
    )highrH   r   endpointNr   )rH   r   )r   rH   r   )r`   r
   Zintegersr   r]   r^   r_   randint)genlowr   rH   r   r   r   r   r   rng_integers  s    ,

r   	   !E^1cuBn c                 #   s6   t jj | f fdd	t j_z
dV  W 5  t j_X dS )z0Context with a fixed np.random.default_rng seed.c                    s    | S r   r   re   Zorig_funr   r   <lambda>      z$_fixed_default_rng.<locals>.<lambda>N)r   r]   Zdefault_rngre   r   r   r   _fixed_default_rng  s
    
r   c                 C   s,   t j| |d}|r(|dk	r(t j||d}|S )z
    argmin with a `keepdims` parameter.

    See https://github.com/numpy/numpy/issues/8710

    If axis is not None, a.shape[axis] must be greater than 0.
    axisN)r   ZargminZexpand_dims)r   keepdimsr   resr   r   r   _argmin  s    r   c                 C   s$   t t| |dd}tj| ||dS )a  
    Return the first non-nan value along the given axis.

    If a slice is all nan, nan is returned for that slice.

    The shape of the return value corresponds to ``keepdims=True``.

    Examples
    --------
    >>> import numpy as np
    >>> nan = np.nan
    >>> a = np.array([[ 3.,  3., nan,  3.],
                      [ 1., nan,  2.,  4.],
                      [nan, nan,  9., -1.],
                      [nan,  5.,  4.,  3.],
                      [ 2.,  2.,  2.,  2.],
                      [nan, nan, nan, nan]])
    >>> _first_nonnan(a, axis=0)
    array([[3., 3., 2., 3.]])
    >>> _first_nonnan(a, axis=1)
    array([[ 3.],
           [ 1.],
           [ 9.],
           [ 5.],
           [ 2.],
           [nan]])
    Tr   r   r   )r   r   isnanZtake_along_axis)r   r   rr   r   r   r   _first_nonnan  s    r   c                 C   s   |dkr$| j dkrdS |  } d}nF| j}|| dkrj|d| d|  ||d d  }tj|dtdS t| |d}|| kt| B j||dS )	a  
    Determine if the values along an axis are all the same.

    nan values are ignored.

    `a` must be a numpy array.

    `axis` is assumed to be normalized; that is, 0 <= axis < a.ndim.

    For an axis of length 0, the result is True.  That is, we adopt the
    convention that ``allsame([])`` is True. (There are no values in the
    input that are different.)

    `True` is returned for slices that are all nan--not because all the
    values are the same, but because this is equivalent to ``allsame([])``.

    Examples
    --------
    >>> import numpy as np
    >>> a = np.array([[ 3.,  3., nan,  3.],
                      [ 1., nan,  2.,  4.],
                      [nan, nan,  9., -1.],
                      [nan,  5.,  4.,  3.],
                      [ 2.,  2.,  2.,  2.],
                      [nan, nan, nan, nan]])
    >>> _nan_allsame(a, axis=1, keepdims=True)
    array([[ True],
           [False],
           [False],
           [False],
           [ True],
           [ True]])
    Nr   T)r   r   r    r   r   )	rH   ravelr(   r   r'   boolr   r   r4   )r   r   r   ZshpZa0r   r   r   _nan_allsame:  s    "
$r   	propagatec              	   C   s   t | tjsd}dddg}||kr>tdddd |D  t| jtjr|r~tjd	d	d
 t	t
| }W 5 Q R X qt	|  }nJt| jtrd}|  D ](}tt|tjrt	|rd} qqnd}|r|dkrtd||fS )NFr   raiseZomitznan_policy must be one of {%s}z, c                 s   s   | ]}d | V  qdS )z'%s'Nr   )r   sr   r   r   r   p  s     z _contains_nan.<locals>.<genexpr>ignore)invalidZoverTzThe input contains nan values)r`   r   rF   r"   r   rl   r   rm   Zerrstater   sumanyobjectr   typenumber)r   Z
nan_policyZuse_summationZpoliciesZcontains_nanelr   r   r   _contains_nanj  s,    
r   c                    s    fdd}|S )a  
    Generate decorator for backward-compatible keyword renaming.

    Apply the decorator generated by `_rename_parameter` to functions with a
    recently renamed parameter to maintain backward-compatibility.

    After decoration, the function behaves as follows:
    If only the new parameter is passed into the function, behave as usual.
    If only the old parameter is passed into the function (as a keyword), raise
    a DeprecationWarning if `dep_version` is provided, and behave as usual
    otherwise.
    If both old and new parameters are passed into the function, raise a
    DeprecationWarning if `dep_version` is provided, and raise the appropriate
    TypeError (function got multiple values for argument).

    Parameters
    ----------
    old_name : str
        Old name of parameter
    new_name : str
        New name of parameter
    dep_version : str, optional
        Version of SciPy in which old parameter was deprecated in the format
        'X.Y.Z'. If supplied, the deprecation message will indicate that
        support for the old parameter will be removed in version 'X.Y+2.Z'

    Notes
    -----
    Untested with functions that accept *args. Probably won't work as written.

    c                    s    t   fdd}|S )Nc               	      s   |kr rf  d}tt|d d |d< d|}d d d d| d	}tj|tdd |krj d	 d
}t||	|< | |S )N.r   rL   zUse of keyword argument `z!` is deprecated and replaced by `z`.  Support for `z` will be removed in SciPy )
stacklevelz2() got multiple values for argument now known as ``)
splitstrr   r   warningswarnDeprecationWarningr   rq   pop)r.   kwargsZend_versionmessage)dep_versionfunnew_nameold_namer   r   wrapper  s    

z5_rename_parameter.<locals>.decorator.<locals>.wrapper)r@   wraps)r   r   r   r   r   )r   r   	decorator  s    z$_rename_parameter.<locals>.decoratorr   )r   r   r   r   r   r   r   _rename_parameter  s     r   c                    s(   | j   j} fdd||D }|S )Nc                    s    g | ]}t jt |qS r   )r   r]   r
   r   )r   Zchild_ssbgr   r   r     s   z_rng_spawn.<locals>.<listcomp>)Z_bit_generatorZ	_seed_seqspawn)rngZ
n_childrenssZ
child_rngsr   r   r   
_rng_spawn  s    
r   )NN)r   )TFFFF)N)NNr   F)r   )FN)F)r   T)N)3
contextlibr   r@   rB   r   ra   collectionsr   r}   rY   typingr   r   r   r   Znumpyr   r   rc   Z	IntNumberrX   ZfloatingZDecimalNumberr]   r
   rd   ZSeedTyper   Znumpy.randomImportErrorr2   r8   rK   rP   rT   r\   rg   ro   rt   ru   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   <module>   sr   

)
(

       
8
)  7J  
@

 
0
 
7