B
    0d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reeeejjejjf  Zedeejjejjf dZyd dlmZ W n" ek
r   G dd	 d	ZY nX d4d
dZd5d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&d6ddZ'd7d d!Z(ed"d#d$d%d&d'd(d)gZ)d*d+ Z*G d,d- d-Z+d8d/d0Z,ed9d2d3Z-dS ):    )contextmanagerN)
namedtuple)OptionalUnionTYPE_CHECKINGTypeVarGeneratorType)bound)	Generatorc               @   s   e Zd ZdS )r
   N)__name__
__module____qualname__ r   r   B/var/www/html/venv/lib/python3.7/site-packages/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
    --------
    >>> 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).0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>)
fill_valuer   c             3   s   | ]}t   |V  qd S )N)r   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"    

r-   c       
         s   t j| }t dd |D }t jt |d ||d}xrtt| D ]b}|| | |  } t  dkrlqFt  |d \ }t fdd|D }	t 	| ||	  qFW |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   r   r   i   s    z_lazyselect.<locals>.<listcomp>r   )r   r   Fc             3   s   | ]}t  |V  qd S )N)r   r   )r   r   )r   r   r   r   p   s    z_lazyselect.<locals>.<genexpr>)
r   r   r!   r"   r#   rangelenallr    r$   )
ZcondlistZ
choicelistr%   defaultr+   r,   indexfunc_r*   r   )r   r   _lazyselectM   s    
r5   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   Z	alignmenthasattr	functoolsreduceoperatormulitemsizeemptyZuint8Z__array_interface__Zndarrayfill)r#   r   r:   alignsizebufoffsetr8   r   r   r   _aligned_zerosu   s    


rG   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   )baserD   copy)arrayr   r   r   _prune_array   s    rL   c             C   s   d}x| D ]}||9 }q
W |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    
rP   )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)rQ   r   r   r   float_factorial   s    rX   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 )N)	_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 )N)dirr_   )r`   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warnrZ   r[   DeprecationWarninggetattrr_   )r`   namer   r   r   __getattr__   s    zDeprecatedImport.__getattr__N)r   r   r   __doc__ra   rc   ri   r   r   r   r   rY      s   rY   c             C   s   | 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rL| S yt| t jj	r`| S W n t
k
rv   Y nX 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    
ru   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   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   s\   y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 )r>   r2   	TypeErrorr   )krh   minimumr   r   r   _validate_int/  s    r   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gkr|jqS r   )kindinspect	ParameterPOSITIONAL_OR_KEYWORDPOSITIONAL_ONLYrh   )r   pr   r   r   r   t  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_POSITIONALrh   )r   r   r   r   r   r   y  s    r   Nc             S   s    g | ]}|j tjjkr|jqS r   )r   r   r   VAR_KEYWORDrh   )r   r   r   r   r   r   ~  s    c             s   s.   | ]&}|j tjjkr|j|jk	r|jV  qd S )N)r   r   r   r   r1   rA   )r   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_ONLYrh   )r   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   r1   rA   rh   )r   r   r   r   r   
<dictcomp>  s    z*getfullargspec_no_self.<locals>.<dictcomp>c             S   s"   i | ]}|j |jk	r|j |jqS r   )
annotationrA   rh   )r   r   r   r   r   r     s    )r   	signature
parametersvaluesr    r   )	r3   sigr)   r   r   r   r   
kwdefaultsr   r   r   r   getfullargspec_no_self]  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   )Poolr9   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   ra     s$    


zMapWrapper.__init__c             C   s   | S )Nr   )r`   r   r   r   	__enter__  s    zMapWrapper.__enter__c             C   s   | j r| j  d S )N)r   r   	terminate)r`   r   r   r   r     s    zMapWrapper.terminatec             C   s   | j r| j  d S )N)r   r   join)r`   r   r   r   r     s    zMapWrapper.joinc             C   s   | j r| j  d S )N)r   r   close)r`   r   r   r   r     s    zMapWrapper.closec             C   s   | j r| j  | j  d S )N)r   r   r   r   )r`   exc_type	exc_value	tracebackr   r   r   __exit__  s    
zMapWrapper.__exit__c          
   C   s>   y|  ||S  tk
r8 } ztd|W d d }~X Y nX d S )Nz;The map-like callable must be of the form f(func, iterable))r   r|   )r`   r3   rM   er   r   r   __call__  s
    zMapWrapper.__call__N)r   )r   r   r   rj   ra   r   r   r   r   r   r   r   r   r   r   r     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.
    )highrD   r   endpointNr   )rD   r   )r   rD   r   )rn   r
   Zintegersr   rk   rl   rm   randint)genlowr   rD   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 d t j_X dS )z0Context with a fixed np.random.default_rng seed.c                s    | S )Nr   )rt   )orig_funr   r   <lambda>"      z$_fixed_default_rng.<locals>.<lambda>N)r   rk   Zdefault_rng)rt   r   )r   r   _fixed_default_rng  s
    
r   )NN)r   )TFFFF)N)NNr   F)r   ).
contextlibr   r<   r>   r]   rd   ro   collectionsr   r   rU   typingr   r   r   r   numpyr   r   rq   Z	IntNumberrT   ZfloatingZDecimalNumberrk   r
   rr   ZSeedTyper   Znumpy.randomImportErrorr-   r5   rG   rL   rP   rX   rY   ru   r{   r   r   r   r   r   r   r   r   r   r   <module>   sT   
(
(
$%  
6
)7J 
?