/ lib / numpy / lib / function_base.pyc
function_base.pyc
   1  o

   2  [��c#��@s�ddlZddlZddlZddlZddlZddlZddlm	m
   3  Zddlm
Z
ddlmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZddlmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*ddl+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1ddl2m3Z3ddl4m5Z5ddlm6Z6dd	l7m8Z8dd
   4  l9m:Z:ddl;m<Z<m=Z=m>Z>m?Z?m@Z@mAZBmCZDddlmEZFddlGZGdd
lHmIZImJZJejKe6jLdd�ZLgd�ZMeNeNdd�dd�d�eNdd�dd�d�eNdd�dd�d�eNdd�dd�d�eNdd�dd�d�eNdd�dd�d�eNdd�d d�d�eNd!d�d"d�d�eNd#d�d$d�d�eNd%d�d&d�d�eNd'd�d(d�d�eNd)d�d*d�d�eNd+d�d,d�d�d-�
ZO�dd.d/�ZPeLeP��dd2d3��ZQ�dd4d5�ZReLeR��dd6d7��ZSe5d�d8d9��ZT�ddd:�d;d<�ZUeLeU��dejVd:�d>d?��ZWe5d��dd@dA��ZXdBdC�ZYeLeY�dDdE��ZZ�ddFdG�Z[eLe[��ddHdI��Z\�ddJdK�Z]eLe]��d	dMdN��Z^dddO�dPdQ�Z_eLe_�dd0dO�dRdS��Z`�d
   5  dTdU�ZaeLea�d0dVejVejVfdWdX��Zb�ddYdZ�ZceLec��dd[d\��ZA�dd]d^�ZdeLed��dd_d`��Ze�ddda�dbdc�ZfeLef��dddeda�dedf��Zgdgdh�ZheLeh�didj��Zi�ddkdl�ZjeLej��d
dndo��Zkdpdq�ZleLel�drds��Zmdtdu�ZneLen�dvdw��Zo�ddydz�Zpd{Zqd|�req�Zsd}�res�Ztd~�ret�Zud�reu�Zvd�d��Zwd�d��Zxd�d��Zyd�d��Zz	�dd�d��Z{e5d�Gd�d��d���Z|		�ddd��d�d��Z}eLe}�		�ddd��d�d���Z~�d
   6  dd��d�d��ZeLe�ddxejVejVfdd��d�d���Z�e5d�d�d���Z�e5d�d�d���Z�e5d�d�d���Z�e5d�d�d���Z�gd��Z�gd��Z�d�d��Z�d�d��Z�d�d��Z�d�d��Z�eLe��d�d���Z�e5d�d�d���Z�d�d��Z�eLe��d�d���Z�d�d��Z�eLe��d�d���Z��dd�d��Z�	�d
   7  d�d��Z�eLe���dd�d���Z��dd�d��Z�		�ddd��d�d��Z�eLe��			=	�	=�ddd��d�d���Z�		�ddd��d�d„Z�eLe��			=	�	=�ddd��d�dĄ�Z�			=	�	=�dd�dƄZ�d�dȄZ�d�dʄZ�d�e�d�e�fd�d΄Z�d�dЄZ��dd�d҄Z�d�dԄZ�d�dքZ�d�d؄Z�d�dڄZ�			=	��dd�ejd�ejd�e�d�e�d�ejf
   8  d�d�Z�d�d�Z�	V	�	�dd�ejd�ejd�e�fd�d�Z��dd�d�Z�eLe���dd�d��Z�dddd�d�d�Z�eLe��dxd=d�d�d�d��Z��dd�d�Z�eLe���dd�d���Z��dd�d��Z�eLe���dd�d���Z��dd�d��Z�eLe���dd�d���Z��dd��d�Z�eLe���d�d�d��Z�dS(�N)�	transpose)�ones�
   9  zeros_like�arange�concatenate�array�asarray�
  10  asanyarray�empty�ndarray�take�dot�where�intp�integer�isscalar�absolute)�pi�add�arctan2�
  11  frompyfunc�cos�
  12  less_equal�sqrt�sin�mod�exp�	not_equal�subtract)�ravel�nonzero�	partition�mean�any�sum)�	typecodes)�
  13  set_module)�	overrides)�
  14  add_newdoc)�diag)�_insert�
add_docstring�bincount�normalize_axis_index�
_monotonicity�interp�interp_complex)�_add_newdoc_ufunc)�	histogram�histogramdd�numpy)�module)*�select�	piecewise�
  15  trim_zeros�copy�iterable�
  16  percentile�diff�gradient�angle�unwrap�sort_complex�disp�flip�rot90�extract�place�	vectorize�asarray_chkfinite�averager,�digitize�cov�corrcoef�msort�median�sinc�hamming�hanning�bartlett�blackman�kaiser�trapz�i0r(r+�meshgrid�delete�insert�appendr/�add_newdoc_ufunc�quantilecC�
  17  t||�S�N)�
_inverted_cdf��n�	quantiles�rb��C:\Users\Jacks.GUTTSPC\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\numpy\lib\function_base.py�<lambda>Is
  18  rdcC�|Sr]rb��gamma�_rbrbrcrdJ�)�get_virtual_index�	fix_gammacCs||dS�N�rbr_rbrbrcrdM�cCst|jdd|dkd�S)N��?��?r��shape�
default_value�conditioned_valuer��_get_gamma_maskrrrfrbrbrcrdNs�cCr\r])�_closest_observationr_rbrbrcrdUs�cCrer]rbrfrbrbrcrdWricCst||dd�S)Nrrm��_compute_virtual_indexr_rbrbrcrd[�cCrer]rbrfrbrbrcrd]ricC�t||dd�S)Nrprxr_rbrbrcrd`rzcCrer]rbrfrbrbrcrdbricCr{�Nrrxr_rbrbrcrderzcCrer]rbrfrbrbrcrdgricCs|d|Srlrbr_rbrbrcrdnrncCrer]rbrfrbrbrcrdoricCr{)NgUUUUUU�?rxr_rbrbrcrdrrzcCrer]rbrfrbrbrcrdtricCr{)Ng�?rxr_rbrbrcrdwrzcCrer]rbrfrbrbrcrdyricC�t�|d|��tj�Srl)�np�floor�astyperr_rbrbrcrd}�
  19  �
  20  cCrer]rbrfrbrbrcrdricCr}rl)r~�ceilr�rr_rbrbrcrd�r�cCrer]rbrfrbrbrcrd�ricCs(dt�|d|�t�|d|�S)Nrprm)r~rr�r_rbrbrcrd�s
  21  ��cCst|jdd|ddkd�S)Nrp�rmrrqru�rg�indexrbrbrcrd�s
  22  �cCr}rl)r~�aroundr�rr_rbrbrcrd�r�cCrer]rbrfrbrbrcrd�ri)
�inverted_cdf�averaged_inverted_cdf�closest_observation�interpolated_inverted_cdf�hazen�weibull�linear�median_unbiased�normal_unbiased�lower�higher�midpoint�nearestcC�|fSr]rb)�m�k�axesrbrbrc�_rot90_dispatcher��r�rm�rrmcCsFt|�}t|�dkrtd��t|�}|d|dks't|d|d�|jkr+td��|d|jksI|d|jksI|d|jksI|d|jkrRtd�||j���|d;}|dkr`|dd�S|dkrptt||d�|d�Std|j�}||d||d||d<||d<|dkr�t	t||d�|�Stt	||�|d�S)	a
  23      Rotate an array by 90 degrees in the plane specified by axes.
  24  
  25      Rotation direction is from the first towards the second axis.
  26  
  27      Parameters
  28      ----------
  29      m : array_like
  30          Array of two or more dimensions.
  31      k : integer
  32          Number of times the array is rotated by 90 degrees.
  33      axes : (2,) array_like
  34          The array is rotated in the plane defined by the axes.
  35          Axes must be different.
  36  
  37          .. versionadded:: 1.12.0
  38  
  39      Returns
  40      -------
  41      y : ndarray
  42          A rotated view of `m`.
  43  
  44      See Also
  45      --------
  46      flip : Reverse the order of elements in an array along the given axis.
  47      fliplr : Flip an array horizontally.
  48      flipud : Flip an array vertically.
  49  
  50      Notes
  51      -----
  52      ``rot90(m, k=1, axes=(1,0))``  is the reverse of
  53      ``rot90(m, k=1, axes=(0,1))``
  54  
  55      ``rot90(m, k=1, axes=(1,0))`` is equivalent to
  56      ``rot90(m, k=-1, axes=(0,1))``
  57  
  58      Examples
  59      --------
  60      >>> m = np.array([[1,2],[3,4]], int)
  61      >>> m
  62      array([[1, 2],
  63             [3, 4]])
  64      >>> np.rot90(m)
  65      array([[2, 4],
  66             [1, 3]])
  67      >>> np.rot90(m, 2)
  68      array([[4, 3],
  69             [2, 1]])
  70      >>> m = np.arange(8).reshape((2,2,2))
  71      >>> np.rot90(m, 1, (1,2))
  72      array([[[1, 3],
  73              [0, 2]],
  74             [[5, 7],
  75              [4, 6]]])
  76  
  77      �zlen(axes) must be 2.rrmzAxes must be different.z*Axes={} out of range for array of ndim={}.�N)
  78  �tuple�len�
  79  ValueErrorr	r�ndim�formatrBrr)r�r�r�Z	axes_listrbrbrcrC�s.:*
  80  �
  81  
  82  �rCcCr�r]rb)r��axisrbrbrc�_flip_dispatcher�r�r�cCs�t|d�s	t|�}|durtjddd�f|j}||St�||j�}tjdd�g|j}|D]}tjddd�||<q1t|�}||S)a
  83      Reverse the order of elements in an array along the given axis.
  84  
  85      The shape of the array is preserved, but the elements are reordered.
  86  
  87      .. versionadded:: 1.12.0
  88  
  89      Parameters
  90      ----------
  91      m : array_like
  92          Input array.
  93      axis : None or int or tuple of ints, optional
  94           Axis or axes along which to flip over. The default,
  95           axis=None, will flip over all of the axes of the input array.
  96           If axis is negative it counts from the last to the first axis.
  97  
  98           If axis is a tuple of ints, flipping is performed on all of the axes
  99           specified in the tuple.
 100  
 101           .. versionchanged:: 1.15.0
 102              None and tuples of axes are supported
 103  
 104      Returns
 105      -------
 106      out : array_like
 107          A view of `m` with the entries of axis reversed.  Since a view is
 108          returned, this operation is done in constant time.
 109  
 110      See Also
 111      --------
 112      flipud : Flip an array vertically (axis=0).
 113      fliplr : Flip an array horizontally (axis=1).
 114  
 115      Notes
 116      -----
 117      flip(m, 0) is equivalent to flipud(m).
 118  
 119      flip(m, 1) is equivalent to fliplr(m).
 120  
 121      flip(m, n) corresponds to ``m[...,::-1,...]`` with ``::-1`` at position n.
 122  
 123      flip(m) corresponds to ``m[::-1,::-1,...,::-1]`` with ``::-1`` at all
 124      positions.
 125  
 126      flip(m, (0, 1)) corresponds to ``m[::-1,::-1,...]`` with ``::-1`` at
 127      position 0 and position 1.
 128  
 129      Examples
 130      --------
 131      >>> A = np.arange(8).reshape((2,2,2))
 132      >>> A
 133      array([[[0, 1],
 134              [2, 3]],
 135             [[4, 5],
 136              [6, 7]]])
 137      >>> np.flip(A, 0)
 138      array([[[4, 5],
 139              [6, 7]],
 140             [[0, 1],
 141              [2, 3]]])
 142      >>> np.flip(A, 1)
 143      array([[[2, 3],
 144              [0, 1]],
 145             [[6, 7],
 146              [4, 5]]])
 147      >>> np.flip(A)
 148      array([[[7, 6],
 149              [5, 4]],
 150             [[3, 2],
 151              [1, 0]]])
 152      >>> np.flip(A, (0, 2))
 153      array([[[5, 4],
 154              [7, 6]],
 155             [[1, 0],
 156              [3, 2]]])
 157      >>> A = np.random.randn(3,4,5)
 158      >>> np.all(np.flip(A,2) == A[:,:,::-1,...])
 159      True
 160      r�N�����)�hasattrrr~�s_r��_nx�normalize_axis_tupler�)r�r��indexer�axrbrbrcrB�s
 161  Q�rBcCs$zt|�WdStyYdSw)a
 162      Check whether or not an object can be iterated over.
 163  
 164      Parameters
 165      ----------
 166      y : object
 167        Input object.
 168  
 169      Returns
 170      -------
 171      b : bool
 172        Return ``True`` if the object has an iterator method or is a
 173        sequence and ``False`` otherwise.
 174  
 175  
 176      Examples
 177      --------
 178      >>> np.iterable([1, 2, 3])
 179      True
 180      >>> np.iterable(2)
 181      False
 182  
 183      Notes
 184      -----
 185      In most cases, the results of ``np.iterable(obj)`` are consistent with
 186      ``isinstance(obj, collections.abc.Iterable)``. One notable exception is
 187      the treatment of 0-dimensional arrays::
 188  
 189          >>> from collections.abc import Iterable
 190          >>> a = np.array(1.0)  # 0-dimensional numpy array
 191          >>> isinstance(a, Iterable)
 192          True
 193          >>> np.iterable(a)
 194          False
 195  
 196      FT)�iter�	TypeError)�yrbrbrcr:Zs&
 197  ��r:)�keepdimscC�||fSr]rb)�ar��weights�returnedr�rbrbrc�_average_dispatcher��r�FcCs�t�|�}|tjur
i}nd|i}|dur.|j|fi|��}t�|�}|j�|j|j�}n�t�|�}	t|jjtjtj	f�rHt�
 198  |j|	jd�}
 199  nt�
 200  |j|	j�}
 201  |j|	jkr�|dur^td��|	j
dkrgtd��|	jd|j|krutd��t�|	|j
dd	|	j�}	|	�d
 202  |�}	|	jd||
 203  d�|��}t�|dk�r�td
��tj||	|
 204  d�j|fi|��|}}|r�|j|jkr�t�||j���}||fS|S)a�
 205      Compute the weighted average along the specified axis.
 206  
 207      Parameters
 208      ----------
 209      a : array_like
 210          Array containing data to be averaged. If `a` is not an array, a
 211          conversion is attempted.
 212      axis : None or int or tuple of ints, optional
 213          Axis or axes along which to average `a`.  The default,
 214          axis=None, will average over all of the elements of the input array.
 215          If axis is negative it counts from the last to the first axis.
 216  
 217          .. versionadded:: 1.7.0
 218  
 219          If axis is a tuple of ints, averaging is performed on all of the axes
 220          specified in the tuple instead of a single axis or all the axes as
 221          before.
 222      weights : array_like, optional
 223          An array of weights associated with the values in `a`. Each value in
 224          `a` contributes to the average according to its associated weight.
 225          The weights array can either be 1-D (in which case its length must be
 226          the size of `a` along the given axis) or of the same shape as `a`.
 227          If `weights=None`, then all data in `a` are assumed to have a
 228          weight equal to one.  The 1-D calculation is::
 229  
 230              avg = sum(a * weights) / sum(weights)
 231  
 232          The only constraint on `weights` is that `sum(weights)` must not be 0.
 233      returned : bool, optional
 234          Default is `False`. If `True`, the tuple (`average`, `sum_of_weights`)
 235          is returned, otherwise only the average is returned.
 236          If `weights=None`, `sum_of_weights` is equivalent to the number of
 237          elements over which the average is taken.
 238      keepdims : bool, optional
 239          If this is set to True, the axes which are reduced are left
 240          in the result as dimensions with size one. With this option,
 241          the result will broadcast correctly against the original `a`.
 242          *Note:* `keepdims` will not work with instances of `numpy.matrix`
 243          or other classes whose methods do not support `keepdims`.
 244  
 245          .. versionadded:: 1.23.0
 246  
 247      Returns
 248      -------
 249      retval, [sum_of_weights] : array_type or double
 250          Return the average along the specified axis. When `returned` is `True`,
 251          return a tuple with the average as the first element and the sum
 252          of the weights as the second element. `sum_of_weights` is of the
 253          same type as `retval`. The result dtype follows a genereal pattern.
 254          If `weights` is None, the result dtype will be that of `a` , or ``float64``
 255          if `a` is integral. Otherwise, if `weights` is not None and `a` is non-
 256          integral, the result type will be the type of lowest precision capable of
 257          representing values of both `a` and `weights`. If `a` happens to be
 258          integral, the previous rules still applies but the result dtype will
 259          at least be ``float64``.
 260  
 261      Raises
 262      ------
 263      ZeroDivisionError
 264          When all weights along axis are zero. See `numpy.ma.average` for a
 265          version robust to this type of error.
 266      TypeError
 267          When the length of 1D `weights` is not the same as the shape of `a`
 268          along axis.
 269  
 270      See Also
 271      --------
 272      mean
 273  
 274      ma.average : average for masked arrays -- useful if your data contains
 275                   "missing" values
 276      numpy.result_type : Returns the type that results from applying the
 277                          numpy type promotion rules to the arguments.
 278  
 279      Examples
 280      --------
 281      >>> data = np.arange(1, 5)
 282      >>> data
 283      array([1, 2, 3, 4])
 284      >>> np.average(data)
 285      2.5
 286      >>> np.average(np.arange(1, 11), weights=np.arange(10, 0, -1))
 287      4.0
 288  
 289      >>> data = np.arange(6).reshape((3, 2))
 290      >>> data
 291      array([[0, 1],
 292             [2, 3],
 293             [4, 5]])
 294      >>> np.average(data, axis=1, weights=[1./4, 3./4])
 295      array([0.75, 2.75, 4.75])
 296      >>> np.average(data, weights=[1./4, 3./4])
 297      Traceback (most recent call last):
 298          ...
 299      TypeError: Axis must be specified when shapes of a and weights differ.
 300  
 301      >>> a = np.ones(5, dtype=np.float128)
 302      >>> w = np.ones(5, dtype=np.complex64)
 303      >>> avg = np.average(a, weights=w)
 304      >>> print(avg.dtype)
 305      complex256
 306  
 307      With ``keepdims=True``, the following result has shape (3, 1).
 308  
 309      >>> np.average(data, axis=1, keepdims=True)
 310      array([[0.5],
 311             [2.5],
 312             [4.5]])
 313      r�N�f8z;Axis must be specified when shapes of a and weights differ.rmz81D weights expected when shapes of a and weights differ.rz5Length of weights not compatible with specified axis.�rmr�)r��dtyper�z(Weights sum to zero, can't be normalized�r�rb)r~r	�_NoValuer"r��type�size�
 314  issubclassr�bool_�result_typerrr�r�r��broadcast_to�swapaxesr$r#�ZeroDivisionError�multiplyr9)r�r�r�r�r��keepdims_kw�avgZavg_as_array�scl�wgt�result_dtyperbrbrcrH�s\
 315  q
 316  
 317  
 318  �
 319  �������rHcCs8t|||d�}|jjtdvrt�|���std��|S)aConvert the input to an array, checking for NaNs or Infs.
 320  
 321      Parameters
 322      ----------
 323      a : array_like
 324          Input data, in any form that can be converted to an array.  This
 325          includes lists, lists of tuples, tuples, tuples of tuples, tuples
 326          of lists and ndarrays.  Success requires no NaNs or Infs.
 327      dtype : data-type, optional
 328          By default, the data-type is inferred from the input data.
 329      order : {'C', 'F', 'A', 'K'}, optional
 330          Memory layout.  'A' and 'K' depend on the order of input array a.
 331          'C' row-major (C-style),
 332          'F' column-major (Fortran-style) memory representation.
 333          'A' (any) means 'F' if `a` is Fortran contiguous, 'C' otherwise
 334          'K' (keep) preserve input order
 335          Defaults to 'C'.
 336  
 337      Returns
 338      -------
 339      out : ndarray
 340          Array interpretation of `a`.  No copy is performed if the input
 341          is already an ndarray.  If `a` is a subclass of ndarray, a base
 342          class ndarray is returned.
 343  
 344      Raises
 345      ------
 346      ValueError
 347          Raises ValueError if `a` contains NaN (Not a Number) or Inf (Infinity).
 348  
 349      See Also
 350      --------
 351      asarray : Create and array.
 352      asanyarray : Similar function which passes through subclasses.
 353      ascontiguousarray : Convert input to a contiguous array.
 354      asfarray : Convert input to a floating point ndarray.
 355      asfortranarray : Convert input to an ndarray with column-major
 356                       memory order.
 357      fromiter : Create an array from an iterator.
 358      fromfunction : Construct an array by executing a function on grid
 359                     positions.
 360  
 361      Examples
 362      --------
 363      Convert a list into an array.  If all elements are finite
 364      ``asarray_chkfinite`` is identical to ``asarray``.
 365  
 366      >>> a = [1, 2]
 367      >>> np.asarray_chkfinite(a, dtype=float)
 368      array([1., 2.])
 369  
 370      Raises ValueError if array_like contains Nans or Infs.
 371  
 372      >>> a = [1, 2, np.inf]
 373      >>> try:
 374      ...     np.asarray_chkfinite(a)
 375      ... except ValueError:
 376      ...     print('ValueError')
 377      ...
 378      ValueError
 379  
 380      )r��order�AllFloatz#array must not contain infs or NaNs)rr��charr%r~�isfinite�allr�)r�r�r�rbrbrcrG2s@�rGcos$�|Vt�|�r|EdHdSdSr])r~r:)�x�condlist�funclist�args�kwrbrbrc�_piecewise_dispatcherys
 381  �
 382  �r�cOs
 383  t|�}t|�}t|�st|dttf�s|jdkr|g}t|td�}t|�}||dkrDt	j
 384  |ddd�}t	j||gdd�}|d7}n||krStd�
|||d���t|�}t||�D]&\}	}
 385  t|
 386  tjj�sl|
 387  ||	<q\||	}|jdkr�|
 388  |g|�Ri|��||	<q\|S)a
 389      Evaluate a piecewise-defined function.
 390  
 391      Given a set of conditions and corresponding functions, evaluate each
 392      function on the input data wherever its condition is true.
 393  
 394      Parameters
 395      ----------
 396      x : ndarray or scalar
 397          The input domain.
 398      condlist : list of bool arrays or bool scalars
 399          Each boolean array corresponds to a function in `funclist`.  Wherever
 400          `condlist[i]` is True, `funclist[i](x)` is used as the output value.
 401  
 402          Each boolean array in `condlist` selects a piece of `x`,
 403          and should therefore be of the same shape as `x`.
 404  
 405          The length of `condlist` must correspond to that of `funclist`.
 406          If one extra function is given, i.e. if
 407          ``len(funclist) == len(condlist) + 1``, then that extra function
 408          is the default value, used wherever all conditions are false.
 409      funclist : list of callables, f(x,*args,**kw), or scalars
 410          Each function is evaluated over `x` wherever its corresponding
 411          condition is True.  It should take a 1d array as input and give an 1d
 412          array or a scalar value as output.  If, instead of a callable,
 413          a scalar is provided then a constant function (``lambda x: scalar``) is
 414          assumed.
 415      args : tuple, optional
 416          Any further arguments given to `piecewise` are passed to the functions
 417          upon execution, i.e., if called ``piecewise(..., ..., 1, 'a')``, then
 418          each function is called as ``f(x, 1, 'a')``.
 419      kw : dict, optional
 420          Keyword arguments used in calling `piecewise` are passed to the
 421          functions upon execution, i.e., if called
 422          ``piecewise(..., ..., alpha=1)``, then each function is called as
 423          ``f(x, alpha=1)``.
 424  
 425      Returns
 426      -------
 427      out : ndarray
 428          The output is the same shape and type as x and is found by
 429          calling the functions in `funclist` on the appropriate portions of `x`,
 430          as defined by the boolean arrays in `condlist`.  Portions not covered
 431          by any condition have a default value of 0.
 432  
 433  
 434      See Also
 435      --------
 436      choose, select, where
 437  
 438      Notes
 439      -----
 440      This is similar to choose or select, except that functions are
 441      evaluated on elements of `x` that satisfy the corresponding condition from
 442      `condlist`.
 443  
 444      The result is::
 445  
 446              |--
 447              |funclist[0](x[condlist[0]])
 448        out = |funclist[1](x[condlist[1]])
 449              |...
 450              |funclist[n2](x[condlist[n2]])
 451              |--
 452  
 453      Examples
 454      --------
 455      Define the sigma function, which is -1 for ``x < 0`` and +1 for ``x >= 0``.
 456  
 457      >>> x = np.linspace(-2.5, 2.5, 6)
 458      >>> np.piecewise(x, [x < 0, x >= 0], [-1, 1])
 459      array([-1., -1., -1.,  1.,  1.,  1.])
 460  
 461      Define the absolute value, which is ``-x`` for ``x <0`` and ``x`` for
 462      ``x >= 0``.
 463  
 464      >>> np.piecewise(x, [x < 0, x >= 0], [lambda x: -x, lambda x: x])
 465      array([2.5,  1.5,  0.5,  0.5,  1.5,  2.5])
 466  
 467      Apply the same function to a scalar value.
 468  
 469      >>> y = -2
 470      >>> np.piecewise(y, [y < 0, y >= 0], [lambda x: -x, lambda x: x])
 471      array(2)
 472  
 473      rr�rmT)r�r��r�z<with {} condition(s), either {} or {} functions are expected)r	r�r�
 474  isinstance�listrr�r�boolr~r#rr�r�r�zip�collections�abc�Callabler�)r�r�r�r�r��n2r`Zcondelser��cond�func�valsrbrbrcr7�s6X�
 475  
 476  �
 477  
 478  �r7ccs�|EdH|EdHdSr]rb)r��
 479  choicelist�defaultrbrbrc�_select_dispatcher�s�
 480  r�c

 481  Cs�t|�t|�krtd��t|�dkrtd��dd�|D�}ztj|�}Wnty:}z
 482  d|��}t|�d�d}~wwt�|�}|�|�zt�||�}Wntyc}z
 483  d|��}t|�d�d}~wwtj|�}tj|�}t|�D]\}}	|	j	j
 484  tjur�td	�|���qr|dj
dkr�|dj}
 485  n
t�|d|d�dj}
 486  t�|
 487  |d
 488  |�}|ddd
 489  �}|ddd
 490  �}t||�D]\}}	tj|||	d�q�|S)
a9
 491      Return an array drawn from elements in choicelist, depending on conditions.
 492  
 493      Parameters
 494      ----------
 495      condlist : list of bool ndarrays
 496          The list of conditions which determine from which array in `choicelist`
 497          the output elements are taken. When multiple conditions are satisfied,
 498          the first one encountered in `condlist` is used.
 499      choicelist : list of ndarrays
 500          The list of arrays from which the output elements are taken. It has
 501          to be of the same length as `condlist`.
 502      default : scalar, optional
 503          The element inserted in `output` when all conditions evaluate to False.
 504  
 505      Returns
 506      -------
 507      output : ndarray
 508          The output at position m is the m-th element of the array in
 509          `choicelist` where the m-th element of the corresponding array in
 510          `condlist` is True.
 511  
 512      See Also
 513      --------
 514      where : Return elements from one of two arrays depending on condition.
 515      take, choose, compress, diag, diagonal
 516  
 517      Examples
 518      --------
 519      >>> x = np.arange(6)
 520      >>> condlist = [x<3, x>3]
 521      >>> choicelist = [x, x**2]
 522      >>> np.select(condlist, choicelist, 42)
 523      array([ 0,  1,  2, 42, 16, 25])
 524  
 525      >>> condlist = [x<=4, x>3]
 526      >>> choicelist = [x, x**2]
 527      >>> np.select(condlist, choicelist, 55)
 528      array([ 0,  1,  2,  3,  4, 25])
 529  
 530      z7list of cases must be same length as list of conditionsrz3select with an empty condition list is not possiblecSsg|]}t�|��qSrb)r~r)�.0�choicerbrbrc�
 531  <listcomp>2�zselect.<locals>.<listcomp>z0Choicelist elements do not have a common dtype: Nz:Choicelists and default value do not have a common dtype: z7invalid entry {} in condlist: should be boolean ndarrayr�������r)r�r�r~r�r�rrY�broadcast_arrays�	enumerater�r�r�r�r�rr�fullr��copyto)
r�r�r�Zintermediate_dtype�e�msgZ
default_arrayr��ir��result_shape�resultr�rbrbrcr6�sP,�
 532  
 533  ��
 534  
 535  
 536  
 537  ��
 538  
 539  ��r6cCr�r]rb�r�r��subokrbrbrc�_copy_dispatchercr�r��KcCst|||dd�S)a-	
 540      Return an array copy of the given object.
 541  
 542      Parameters
 543      ----------
 544      a : array_like
 545          Input data.
 546      order : {'C', 'F', 'A', 'K'}, optional
 547          Controls the memory layout of the copy. 'C' means C-order,
 548          'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
 549          'C' otherwise. 'K' means match the layout of `a` as closely
 550          as possible. (Note that this function and :meth:`ndarray.copy` are very
 551          similar, but have different default values for their order=
 552          arguments.)
 553      subok : bool, optional
 554          If True, then sub-classes will be passed-through, otherwise the
 555          returned array will be forced to be a base-class array (defaults to False).
 556  
 557          .. versionadded:: 1.19.0
 558  
 559      Returns
 560      -------
 561      arr : ndarray
 562          Array interpretation of `a`.
 563  
 564      See Also
 565      --------
 566      ndarray.copy : Preferred method for creating an array copy
 567  
 568      Notes
 569      -----
 570      This is equivalent to:
 571  
 572      >>> np.array(a, copy=True)  #doctest: +SKIP
 573  
 574      Examples
 575      --------
 576      Create an array x, with a reference y and a copy z:
 577  
 578      >>> x = np.array([1, 2, 3])
 579      >>> y = x
 580      >>> z = np.copy(x)
 581  
 582      Note that, when we modify x, y changes, but not z:
 583  
 584      >>> x[0] = 10
 585      >>> x[0] == y[0]
 586      True
 587      >>> x[0] == z[0]
 588      False
 589  
 590      Note that, np.copy clears previously set WRITEABLE=False flag.
 591  
 592      >>> a = np.array([1, 2, 3])
 593      >>> a.flags["WRITEABLE"] = False
 594      >>> b = np.copy(a)
 595      >>> b.flags["WRITEABLE"]
 596      True
 597      >>> b[0] = 3
 598      >>> b
 599      array([3, 2, 3])
 600  
 601      Note that np.copy is a shallow copy and will not copy object
 602      elements within arrays. This is mainly important for arrays
 603      containing Python objects. The new array will contain the
 604      same object which may lead to surprises if that object can
 605      be modified (is mutable):
 606  
 607      >>> a = np.array([1, 'm', [2, 3, 4]], dtype=object)
 608      >>> b = np.copy(a)
 609      >>> b[2][0] = 10
 610      >>> a
 611      array([1, 'm', list([10, 3, 4])], dtype=object)
 612  
 613      To ensure all elements within an ``object`` array are copied,
 614      use `copy.deepcopy`:
 615  
 616      >>> import copy
 617      >>> a = np.array([1, 'm', [2, 3, 4]], dtype=object)
 618      >>> c = copy.deepcopy(a)
 619      >>> c[2][0] = 10
 620      >>> c
 621      array([1, 'm', list([10, 3, 4])], dtype=object)
 622      >>> a
 623      array([1, 'm', list([2, 3, 4])], dtype=object)
 624  
 625      T)r�r�r9)rr�rbrbrcr9gsYr9)r��
 626  edge_ordercgs�|V|EdHdSr]rb)�fr�r��varargsrbrbrc�_gradient_dispatcher�s�r�cGs�t�|�}|j}|durtt|��}nt�||�}t|�}t|�}|dkr+dg|}nn|dkr=t�|d�dkr=||}n\||kr�t|�}t	|�D]J\}	}
 627  t�|
 628  �}
 629  |
 630  jdkrXqI|
 631  jdkrat
 632  d��t|
 633  �|j||	krpt
 634  d��t�|
 635  j
tj�r~|
 636  �tj�}
 637  t�|
 638  �}||dk��r�|d}|||	<qIntd��|dkr�t
 639  d	��g}td�g|}
td�g|}td�g|}td�g|}|j
}|jtjur�t�
|j�d
 640  d��}|�|�}n|jtjur�nt�|tj�r�nt�|tj�r�|�tj�}tj}t||�D�]�\}}|j||dk�rt
 641  d��tj||d
�}t�|�dk}tdd�|
|<tdd�||<tdd�||<tdd�||<|�rQ|t|�|t|�d||t|
�<nU|dd�}|dd�}||||}||||}||||}tj|td
�}d||<||_|_|_||t|�||t|�||t|�|t|
�<|dk�r�d|
|<d||<d||<|�r�|n|d}|t|�|t|�||t|
�<d|
|<d||<d||<|�r�|n|d}|t|�|t|�||t|
�<n�d|
|<d||<d||<d||<|�rd|}d|}d|}n&|d}|d}d|||||}||||}||||}||t|�||t|�||t|�|t|
�<d|
|<d||<d||<d||<|�r|d|}d|}d|}n%|d}|d}||||}||||}d|||||}||t|�||t|�||t|�|t|
�<|� |�td�|
|<td�||<td�||<td�||<q�|dk�r�|dS|S)a
 642      Return the gradient of an N-dimensional array.
 643  
 644      The gradient is computed using second order accurate central differences
 645      in the interior points and either first or second order accurate one-sides
 646      (forward or backwards) differences at the boundaries.
 647      The returned gradient hence has the same shape as the input array.
 648  
 649      Parameters
 650      ----------
 651      f : array_like
 652          An N-dimensional array containing samples of a scalar function.
 653      varargs : list of scalar or array, optional
 654          Spacing between f values. Default unitary spacing for all dimensions.
 655          Spacing can be specified using:
 656  
 657          1. single scalar to specify a sample distance for all dimensions.
 658          2. N scalars to specify a constant sample distance for each dimension.
 659             i.e. `dx`, `dy`, `dz`, ...
 660          3. N arrays to specify the coordinates of the values along each
 661             dimension of F. The length of the array must match the size of
 662             the corresponding dimension
 663          4. Any combination of N scalars/arrays with the meaning of 2. and 3.
 664  
 665          If `axis` is given, the number of varargs must equal the number of axes.
 666          Default: 1.
 667  
 668      edge_order : {1, 2}, optional
 669          Gradient is calculated using N-th order accurate differences
 670          at the boundaries. Default: 1.
 671  
 672          .. versionadded:: 1.9.1
 673  
 674      axis : None or int or tuple of ints, optional
 675          Gradient is calculated only along the given axis or axes
 676          The default (axis = None) is to calculate the gradient for all the axes
 677          of the input array. axis may be negative, in which case it counts from
 678          the last to the first axis.
 679  
 680          .. versionadded:: 1.11.0
 681  
 682      Returns
 683      -------
 684      gradient : ndarray or list of ndarray
 685          A list of ndarrays (or a single ndarray if there is only one dimension)
 686          corresponding to the derivatives of f with respect to each dimension.
 687          Each derivative has the same shape as f.
 688  
 689      Examples
 690      --------
 691      >>> f = np.array([1, 2, 4, 7, 11, 16], dtype=float)
 692      >>> np.gradient(f)
 693      array([1. , 1.5, 2.5, 3.5, 4.5, 5. ])
 694      >>> np.gradient(f, 2)
 695      array([0.5 ,  0.75,  1.25,  1.75,  2.25,  2.5 ])
 696  
 697      Spacing can be also specified with an array that represents the coordinates
 698      of the values F along the dimensions.
 699      For instance a uniform spacing:
 700  
 701      >>> x = np.arange(f.size)
 702      >>> np.gradient(f, x)
 703      array([1. ,  1.5,  2.5,  3.5,  4.5,  5. ])
 704  
 705      Or a non uniform one:
 706  
 707      >>> x = np.array([0., 1., 1.5, 3.5, 4., 6.], dtype=float)
 708      >>> np.gradient(f, x)
 709      array([1. ,  3. ,  3.5,  6.7,  6.9,  2.5])
 710  
 711      For two dimensional arrays, the return will be two arrays ordered by
 712      axis. In this example the first array stands for the gradient in
 713      rows and the second one in columns direction:
 714  
 715      >>> np.gradient(np.array([[1, 2, 6], [3, 4, 5]], dtype=float))
 716      [array([[ 2.,  2., -1.],
 717             [ 2.,  2., -1.]]), array([[1. , 2.5, 4. ],
 718             [1. , 1. , 1. ]])]
 719  
 720      In this example the spacing is also specified:
 721      uniform for axis=0 and non uniform for axis=1
 722  
 723      >>> dx = 2.
 724      >>> y = [1., 1.5, 3.5]
 725      >>> np.gradient(np.array([[1, 2, 6], [3, 4, 5]], dtype=float), dx, y)
 726      [array([[ 1. ,  1. , -0.5],
 727             [ 1. ,  1. , -0.5]]), array([[2. , 2. , 2. ],
 728             [2. , 1.7, 0.5]])]
 729  
 730      It is possible to specify how boundaries are treated using `edge_order`
 731  
 732      >>> x = np.array([0, 1, 2, 3, 4])
 733      >>> f = x**2
 734      >>> np.gradient(f, edge_order=1)
 735      array([1.,  2.,  4.,  6.,  7.])
 736      >>> np.gradient(f, edge_order=2)
 737      array([0., 2., 4., 6., 8.])
 738  
 739      The `axis` keyword can be used to specify a subset of axes of which the
 740      gradient is calculated
 741  
 742      >>> np.gradient(np.array([[1, 2, 6], [3, 4, 5]], dtype=float), axis=0)
 743      array([[ 2.,  2., -1.],
 744             [ 2.,  2., -1.]])
 745  
 746      Notes
 747      -----
 748      Assuming that :math:`f\in C^{3}` (i.e., :math:`f` has at least 3 continuous
 749      derivatives) and let :math:`h_{*}` be a non-homogeneous stepsize, we
 750      minimize the "consistency error" :math:`\eta_{i}` between the true gradient
 751      and its estimate from a linear combination of the neighboring grid-points:
 752  
 753      .. math::
 754  
 755          \eta_{i} = f_{i}^{\left(1\right)} -
 756                      \left[ \alpha f\left(x_{i}\right) +
 757                              \beta f\left(x_{i} + h_{d}\right) +
 758                              \gamma f\left(x_{i}-h_{s}\right)
 759                      \right]
 760  
 761      By substituting :math:`f(x_{i} + h_{d})` and :math:`f(x_{i} - h_{s})`
 762      with their Taylor series expansion, this translates into solving
 763      the following the linear system:
 764  
 765      .. math::
 766  
 767          \left\{
 768              \begin{array}{r}
 769                  \alpha+\beta+\gamma=0 \\
 770                  \beta h_{d}-\gamma h_{s}=1 \\
 771                  \beta h_{d}^{2}+\gamma h_{s}^{2}=0
 772              \end{array}
 773          \right.
 774  
 775      The resulting approximation of :math:`f_{i}^{(1)}` is the following:
 776  
 777      .. math::
 778  
 779          \hat f_{i}^{(1)} =
 780              \frac{
 781                  h_{s}^{2}f\left(x_{i} + h_{d}\right)
 782                  + \left(h_{d}^{2} - h_{s}^{2}\right)f\left(x_{i}\right)
 783                  - h_{d}^{2}f\left(x_{i}-h_{s}\right)}
 784                  { h_{s}h_{d}\left(h_{d} + h_{s}\right)}
 785              + \mathcal{O}\left(\frac{h_{d}h_{s}^{2}
 786                                  + h_{s}h_{d}^{2}}{h_{d}
 787                                  + h_{s}}\right)
 788  
 789      It is worth noting that if :math:`h_{s}=h_{d}`
 790      (i.e., data are evenly spaced)
 791      we find the standard second order approximation:
 792  
 793      .. math::
 794  
 795          \hat f_{i}^{(1)}=
 796              \frac{f\left(x_{i+1}\right) - f\left(x_{i-1}\right)}{2h}
 797              + \mathcal{O}\left(h^{2}\right)
 798  
 799      With a similar procedure the forward/backward approximations used for
 800      boundaries can be derived.
 801  
 802      References
 803      ----------
 804      .. [1]  Quarteroni A., Sacco R., Saleri F. (2007) Numerical Mathematics
 805              (Texts in Applied Mathematics). New York: Springer.
 806      .. [2]  Durran D. R. (1999) Numerical Methods for Wave Equations
 807              in Geophysical Fluid Dynamics. New York: Springer.
 808      .. [3]  Fornberg B. (1988) Generation of Finite Difference Formulas on
 809              Arbitrarily Spaced Grids,
 810              Mathematics of Computation 51, no. 184 : 699-706.
 811              `PDF <http://www.ams.org/journals/mcom/1988-51-184/
 812              S0025-5718-1988-0935077-0/S0025-5718-1988-0935077-0.pdf>`_.
 813      Nrrormz&distances must be either scalars or 1dzGwhen 1d, distances must match the length of the corresponding dimensionzinvalid number of argumentsr�z)'edge_order' greater than 2 not supported�datetime�	timedeltazlShape of array too small to calculate a numerical gradient, at least (edge_order + 1) elements are required.r�r�r��@g��g������rpg�g�?)!r~r	r�r��ranger�r�r�r�r�r�rr�
 814  issubdtyper�rr��float64r<r�r��slicer��
 815  datetime64�name�replace�view�timedelta64�inexactr��
 816  empty_liker�intrY)r�r�r�r��Nr�Zlen_axesr`�dxr��	distancesZdiffxZoutvals�slice1�slice2Zslice3Zslice4ZotypeZax_dx�outZuniform_spacingZdx1Zdx2r��b�crrZdx_0Zdx_nrbrbrcr=�s�
 817  0
 818  
 819  
 820  
 821  
 822  
 823  ��*8
 824  $&
 825  8
 826  8
 827  
 828  r=cCs
 829  |||fSr]rb)r�r`r��prependrYrbrbrc�_diff_dispatcher$�
 830  rr�cCs�|dkr|S|dkrtdt|���t|�}|j}|dkr!td��t||�}g}|tjurMt�|�}|jdkrHt|j�}d||<t�	|t
 831  |��}|�|�|�|�|tjurwt�|�}|jdkrrt|j�}d||<t�	|t
 832  |��}|�|�t|�dkr�t�
||�}td�g|}td�g|}	tdd�||<tdd�|	|<t
 833  |�}t
 834  |	�}	|jtjkr�tnt}
 835  t|�D]}|
 836  ||||	�}q�|S)a0
 837  
 838      Calculate the n-th discrete difference along the given axis.
 839  
 840      The first difference is given by ``out[i] = a[i+1] - a[i]`` along
 841      the given axis, higher differences are calculated by using `diff`
 842      recursively.
 843  
 844      Parameters
 845      ----------
 846      a : array_like
 847          Input array
 848      n : int, optional
 849          The number of times values are differenced. If zero, the input
 850          is returned as-is.
 851      axis : int, optional
 852          The axis along which the difference is taken, default is the
 853          last axis.
 854      prepend, append : array_like, optional
 855          Values to prepend or append to `a` along axis prior to
 856          performing the difference.  Scalar values are expanded to
 857          arrays with length 1 in the direction of axis and the shape
 858          of the input array in along all other axes.  Otherwise the
 859          dimension and shape must match `a` except along axis.
 860  
 861          .. versionadded:: 1.16.0
 862  
 863      Returns
 864      -------
 865      diff : ndarray
 866          The n-th differences. The shape of the output is the same as `a`
 867          except along `axis` where the dimension is smaller by `n`. The
 868          type of the output is the same as the type of the difference
 869          between any two elements of `a`. This is the same as the type of
 870          `a` in most cases. A notable exception is `datetime64`, which
 871          results in a `timedelta64` output array.
 872  
 873      See Also
 874      --------
 875      gradient, ediff1d, cumsum
 876  
 877      Notes
 878      -----
 879      Type is preserved for boolean arrays, so the result will contain
 880      `False` when consecutive elements are the same and `True` when they
 881      differ.
 882  
 883      For unsigned integer arrays, the results will also be unsigned. This
 884      should not be surprising, as the result is consistent with
 885      calculating the difference directly:
 886  
 887      >>> u8_arr = np.array([1, 0], dtype=np.uint8)
 888      >>> np.diff(u8_arr)
 889      array([255], dtype=uint8)
 890      >>> u8_arr[1,...] - u8_arr[0,...]
 891      255
 892  
 893      If this is not desirable, then the array should be cast to a larger
 894      integer type first:
 895  
 896      >>> i16_arr = u8_arr.astype(np.int16)
 897      >>> np.diff(i16_arr)
 898      array([-1], dtype=int16)
 899  
 900      Examples
 901      --------
 902      >>> x = np.array([1, 2, 4, 7, 0])
 903      >>> np.diff(x)
 904      array([ 1,  2,  3, -7])
 905      >>> np.diff(x, n=2)
 906      array([  1,   1, -10])
 907  
 908      >>> x = np.array([[1, 3, 6, 10], [0, 5, 6, 8]])
 909      >>> np.diff(x)
 910      array([[2, 3, 4],
 911             [5, 1, 2]])
 912      >>> np.diff(x, axis=0)
 913      array([[-1,  2,  0, -2]])
 914  
 915      >>> x = np.arange('1066-10-13', '1066-10-16', dtype=np.datetime64)
 916      >>> np.diff(x)
 917      array([1, 1], dtype='timedelta64[D]')
 918  
 919      rz#order must be non-negative but got z4diff requires input that is at least one dimensionalrmNr�)r��reprr	r�r-r~r�r�rrr�r�rYr�rrr�r�rrr�)r�r`r�rrY�nd�combinedrrrr
�oprhrbrbrcr<(sNU
 920  �
 921  
 922  
 923  
 924  
 925  
 926  
 927  
 928  
 929  
 930  
 931  
 932  r<cC�
 933  |||fSr]rb)r��xp�fp�left�right�periodrbrbrc�_interp_dispatcher�rrc	Cs:t�|�}t�|�rt}tj}nt}tj}|dur�|dkr!td��t|�}d}d}tj|tjd�}tj|tjd�}tj||d�}|j	dksJ|j	dkrNtd��|j
 934  d|j
 935  dkr\td��||}||}t�|�}||}||}t�|dd�|||dd�|f�}t�|dd�||dd�f�}||||||�S)	a
 936      One-dimensional linear interpolation for monotonically increasing sample points.
 937  
 938      Returns the one-dimensional piecewise linear interpolant to a function
 939      with given discrete data points (`xp`, `fp`), evaluated at `x`.
 940  
 941      Parameters
 942      ----------
 943      x : array_like
 944          The x-coordinates at which to evaluate the interpolated values.
 945  
 946      xp : 1-D sequence of floats
 947          The x-coordinates of the data points, must be increasing if argument
 948          `period` is not specified. Otherwise, `xp` is internally sorted after
 949          normalizing the periodic boundaries with ``xp = xp % period``.
 950  
 951      fp : 1-D sequence of float or complex
 952          The y-coordinates of the data points, same length as `xp`.
 953  
 954      left : optional float or complex corresponding to fp
 955          Value to return for `x < xp[0]`, default is `fp[0]`.
 956  
 957      right : optional float or complex corresponding to fp
 958          Value to return for `x > xp[-1]`, default is `fp[-1]`.
 959  
 960      period : None or float, optional
 961          A period for the x-coordinates. This parameter allows the proper
 962          interpolation of angular x-coordinates. Parameters `left` and `right`
 963          are ignored if `period` is specified.
 964  
 965          .. versionadded:: 1.10.0
 966  
 967      Returns
 968      -------
 969      y : float or complex (corresponding to fp) or ndarray
 970          The interpolated values, same shape as `x`.
 971  
 972      Raises
 973      ------
 974      ValueError
 975          If `xp` and `fp` have different length
 976          If `xp` or `fp` are not 1-D sequences
 977          If `period == 0`
 978  
 979      See Also
 980      --------
 981      scipy.interpolate
 982  
 983      Warnings
 984      --------
 985      The x-coordinate sequence is expected to be increasing, but this is not
 986      explicitly enforced.  However, if the sequence `xp` is non-increasing,
 987      interpolation results are meaningless.
 988  
 989      Note that, since NaN is unsortable, `xp` also cannot contain NaNs.
 990  
 991      A simple check for `xp` being strictly increasing is::
 992  
 993          np.all(np.diff(xp) > 0)
 994  
 995      Examples
 996      --------
 997      >>> xp = [1, 2, 3]
 998      >>> fp = [3, 2, 0]
 999      >>> np.interp(2.5, xp, fp)
1000      1.0
1001      >>> np.interp([0, 1, 1.5, 2.72, 3.14], xp, fp)
1002      array([3.  , 3.  , 2.5 , 0.56, 0.  ])
1003      >>> UNDEF = -99.0
1004      >>> np.interp(3.14, xp, fp, right=UNDEF)
1005      -99.0
1006  
1007      Plot an interpolant to the sine function:
1008  
1009      >>> x = np.linspace(0, 2*np.pi, 10)
1010      >>> y = np.sin(x)
1011      >>> xvals = np.linspace(0, 2*np.pi, 50)
1012      >>> yinterp = np.interp(xvals, x, y)
1013      >>> import matplotlib.pyplot as plt
1014      >>> plt.plot(x, y, 'o')
1015      [<matplotlib.lines.Line2D object at 0x...>]
1016      >>> plt.plot(xvals, yinterp, '-x')
1017      [<matplotlib.lines.Line2D object at 0x...>]
1018      >>> plt.show()
1019  
1020      Interpolation with periodic x-coordinates:
1021  
1022      >>> x = [-180, -170, -185, 185, -10, -5, 0, 365]
1023      >>> xp = [190, -190, 350, -350]
1024      >>> fp = [5, 10, 3, 4]
1025      >>> np.interp(x, xp, fp, period=360)
1026      array([7.5 , 5.  , 8.75, 6.25, 3.  , 3.25, 3.5 , 3.75])
1027  
1028      Complex interpolation:
1029  
1030      >>> x = [1.5, 4.0]
1031      >>> xp = [2,3,5]
1032      >>> fp = [1.0j, 0, 2+3j]
1033      >>> np.interp(x, xp, fp)
1034      array([0.+1.j , 1.+1.5j])
1035  
1036      Nrzperiod must be a non-zero valuer�rmz!Data points must be 1-D sequencesz$fp and xp are not of the same lengthr�)
r~r�iscomplexobj�compiled_interp_complex�
1037  complex128�compiled_interpr�r��absr�rr�argsortr)	r�rrrrrZinterp_func�input_dtypeZasort_xprbrbrcr/�s6
1038  i
1039  
1040  ( r/cCr�r]rb)�z�degrbrbrc�_angle_dispatcher>r�r(cCsLt|�}t|jjtj�r|j}|j}nd}|}t||�}|r$|dt	9}|S)a�
1041      Return the angle of the complex argument.
1042  
1043      Parameters
1044      ----------
1045      z : array_like
1046          A complex number or sequence of complex numbers.
1047      deg : bool, optional
1048          Return angle in degrees if True, radians if False (default).
1049  
1050      Returns
1051      -------
1052      angle : ndarray or scalar
1053          The counterclockwise angle from the positive real axis on the complex
1054          plane in the range ``(-pi, pi]``, with dtype as numpy.float64.
1055  
1056          .. versionchanged:: 1.16.0
1057              This function works on subclasses of ndarray like `ma.array`.
1058  
1059      See Also
1060      --------
1061      arctan2
1062      absolute
1063  
1064      Notes
1065      -----
1066      Although the angle of the complex number 0 is undefined, ``numpy.angle(0)``
1067      returns the value 0.
1068  
1069      Examples
1070      --------
1071      >>> np.angle([1.0, 1.0j, 1+1j])               # in radians
1072      array([ 0.        ,  1.57079633,  0.78539816]) # may vary
1073      >>> np.angle(1+1j, deg=True)                  # in degrees
1074      45.0
1075  
1076      r�)
1077  r	r�r�r�r��complexfloating�imag�realrr)r&r'ZzimagZzrealr�rbrbrcr>Bs'
1078  r>)rcCr�r]rb)�p�discontr�rrbrbrc�_unwrap_dispatcherwr�r/r�cCst|�}|j}t||d�}|dur|d}tdd�g|}tdd�||<t|�}t�||�}t�|tj	�rAt
1079  |d�\}}	|	dk}
1080  n|d}d}
1081  |}t|||�|}|
1082  rctj||||k|dk@d�||}
tj|
dt
|�|kd�t|d|d�}|||
�|�||<|S)	a	
1083      Unwrap by taking the complement of large deltas with respect to the period.
1084  
1085      This unwraps a signal `p` by changing elements which have an absolute
1086      difference from their predecessor of more than ``max(discont, period/2)``
1087      to their `period`-complementary values.
1088  
1089      For the default case where `period` is :math:`2\pi` and `discont` is
1090      :math:`\pi`, this unwraps a radian phase `p` such that adjacent differences
1091      are never greater than :math:`\pi` by adding :math:`2k\pi` for some
1092      integer :math:`k`.
1093  
1094      Parameters
1095      ----------
1096      p : array_like
1097          Input array.
1098      discont : float, optional
1099          Maximum discontinuity between values, default is ``period/2``.
1100          Values below ``period/2`` are treated as if they were ``period/2``.
1101          To have an effect different from the default, `discont` should be
1102          larger than ``period/2``.
1103      axis : int, optional
1104          Axis along which unwrap will operate, default is the last axis.
1105      period : float, optional
1106          Size of the range over which the input wraps. By default, it is
1107          ``2 pi``.
1108  
1109          .. versionadded:: 1.21.0
1110  
1111      Returns
1112      -------
1113      out : ndarray
1114          Output array.
1115  
1116      See Also
1117      --------
1118      rad2deg, deg2rad
1119  
1120      Notes
1121      -----
1122      If the discontinuity in `p` is smaller than ``period/2``,
1123      but larger than `discont`, no unwrapping is done because taking
1124      the complement would only make the discontinuity larger.
1125  
1126      Examples
1127      --------
1128      >>> phase = np.linspace(0, np.pi, num=5)
1129      >>> phase[3:] += np.pi
1130      >>> phase
1131      array([ 0.        ,  0.78539816,  1.57079633,  5.49778714,  6.28318531]) # may vary
1132      >>> np.unwrap(phase)
1133      array([ 0.        ,  0.78539816,  1.57079633, -0.78539816,  0.        ]) # may vary
1134      >>> np.unwrap([0, 1, 2, -1, 0], period=4)
1135      array([0, 1, 2, 3, 4])
1136      >>> np.unwrap([ 1, 2, 3, 4, 5, 6, 1, 2, 3], period=6)
1137      array([1, 2, 3, 4, 5, 6, 7, 8, 9])
1138      >>> np.unwrap([2, 3, 4, 5, 2, 3, 4, 5], period=4)
1139      array([2, 3, 4, 5, 6, 7, 8, 9])
1140      >>> phase_deg = np.mod(np.linspace(0 ,720, 19), 360) - 180
1141      >>> np.unwrap(phase_deg, period=360)
1142      array([-180., -140., -100.,  -60.,  -20.,   20.,   60.,  100.,  140.,
1143              180.,  220.,  260.,  300.,  340.,  380.,  420.,  460.,  500.,
1144              540.])
1145      r�Nr�rmrTr�)r9r�)rr�r<rr�r~r�r�r�r�divmodrr�r#r�cumsum)r-r.r�rr�ddrr�Z
interval_high�remZboundary_ambiguousZinterval_lowZddmodZ
1146  ph_correct�uprbrbrcr?{s2B
1147  �r?cCr�r]rb�r�rbrbrc�
_sort_complex�r�r6cCs^t|dd�}|��t|jjtj�s-|jjdvr|�d�S|jjdkr(|�d�S|�d�S|S)a�
1148      Sort a complex array using the real part first, then the imaginary part.
1149  
1150      Parameters
1151      ----------
1152      a : array_like
1153          Input array
1154  
1155      Returns
1156      -------
1157      out : complex ndarray
1158          Always returns a sorted complex array.
1159  
1160      Examples
1161      --------
1162      >>> np.sort_complex([5, 3, 6, 2, 1])
1163      array([1.+0.j, 2.+0.j, 3.+0.j, 5.+0.j, 6.+0.j])
1164  
1165      >>> np.sort_complex([1 + 2j, 2 - 1j, 3 - 2j, 3 - 3j, 3 + 5j])
1166      array([1.+2.j,  2.-1.j,  3.-3.j,  3.-2.j,  3.+5.j])
1167  
1168      T�r9ZbhBH�F�g�G�D)	r�sortr�r�r�r�r*r�r��r�rrbrbrcr@�s
1169  
1170  
1171  r@cCr�r]rb)�filt�trimrbrbrc�_trim_zerosr�r@�fbcCsvd}|��}d|vr|D]}|dkrn|d}qt|�}d|vr5|ddd�D]}|dkr0n|d}q(|||�S)a/
1172      Trim the leading and/or trailing zeros from a 1-D array or sequence.
1173  
1174      Parameters
1175      ----------
1176      filt : 1-D array or sequence
1177          Input array.
1178      trim : str, optional
1179          A string with 'f' representing trim from front and 'b' to trim from
1180          back. Default is 'fb', trim zeros from both front and back of the
1181          array.
1182  
1183      Returns
1184      -------
1185      trimmed : 1-D array or sequence
1186          The result of trimming the input. The input data type is preserved.
1187  
1188      Examples
1189      --------
1190      >>> a = np.array((0, 0, 0, 1, 2, 3, 0, 2, 1, 0))
1191      >>> np.trim_zeros(a)
1192      array([1, 2, 3, 0, 2, 1])
1193  
1194      >>> np.trim_zeros(a, 'b')
1195      array([0, 0, 0, ..., 0, 2, 1])
1196  
1197      The input data type is preserved, list/tuple in means list/tuple out.
1198  
1199      >>> np.trim_zeros([0, 1, 2, 0])
1200      [1, 2]
1201  
1202      rr8r�rm�BNr�)�upperr�)r>r?�firstr��lastrbrbrcr8s#
1203  
1204  r8cC�||fSr]rb��	condition�arrrbrbrc�_extract_dispatcher=�rJcCst�t|�tt|��d�S)a�
1205      Return the elements of an array that satisfy some condition.
1206  
1207      This is equivalent to ``np.compress(ravel(condition), ravel(arr))``.  If
1208      `condition` is boolean ``np.extract`` is equivalent to ``arr[condition]``.
1209  
1210      Note that `place` does the exact opposite of `extract`.
1211  
1212      Parameters
1213      ----------
1214      condition : array_like
1215          An array whose nonzero or True entries indicate the elements of `arr`
1216          to extract.
1217      arr : array_like
1218          Input array of the same size as `condition`.
1219  
1220      Returns
1221      -------
1222      extract : ndarray
1223          Rank 1 array of values from `arr` where `condition` is True.
1224  
1225      See Also
1226      --------
1227      take, put, copyto, compress, place
1228  
1229      Examples
1230      --------
1231      >>> arr = np.arange(12).reshape((3, 4))
1232      >>> arr
1233      array([[ 0,  1,  2,  3],
1234             [ 4,  5,  6,  7],
1235             [ 8,  9, 10, 11]])
1236      >>> condition = np.mod(arr, 3)==0
1237      >>> condition
1238      array([[ True, False, False,  True],
1239             [False, False,  True, False],
1240             [False,  True, False, False]])
1241      >>> np.extract(condition, arr)
1242      array([0, 3, 6, 9])
1243  
1244  
1245      If `condition` is boolean:
1246  
1247      >>> arr[condition]
1248      array([0, 3, 6, 9])
1249  
1250      r)r�rrr rGrbrbrcrDAs1rDcCrr]rb�rI�maskr�rbrbrc�_place_dispatcherurrNcCs.t|tj�stdjt|�jd���t|||�S)a
1251      Change elements of an array based on conditional and input values.
1252  
1253      Similar to ``np.copyto(arr, vals, where=mask)``, the difference is that
1254      `place` uses the first N elements of `vals`, where N is the number of
1255      True values in `mask`, while `copyto` uses the elements where `mask`
1256      is True.
1257  
1258      Note that `extract` does the exact opposite of `place`.
1259  
1260      Parameters
1261      ----------
1262      arr : ndarray
1263          Array to put data into.
1264      mask : array_like
1265          Boolean mask array. Must have the same size as `a`.
1266      vals : 1-D sequence
1267          Values to put into `a`. Only the first N elements are used, where
1268          N is the number of True values in `mask`. If `vals` is smaller
1269          than N, it will be repeated, and if elements of `a` are to be masked,
1270          this sequence must be non-empty.
1271  
1272      See Also
1273      --------
1274      copyto, put, take, extract
1275  
1276      Examples
1277      --------
1278      >>> arr = np.arange(6).reshape(2, 3)
1279      >>> np.place(arr, arr>2, [44, 55])
1280      >>> arr
1281      array([[ 0,  1,  2],
1282             [44, 55, 44]])
1283  
1284      z,argument 1 must be numpy.ndarray, not {name})r)r�r~rr�r�r��__name__r*rLrbrbrcrEys
1285  %
1286  �rETcCs<|durtj}|r|�d|�n|�d|�|��dS)a2
1287      Display a message on a device.
1288  
1289      Parameters
1290      ----------
1291      mesg : str
1292          Message to display.
1293      device : object
1294          Device to write message. If None, defaults to ``sys.stdout`` which is
1295          very similar to ``print``. `device` needs to have ``write()`` and
1296          ``flush()`` methods.
1297      linefeed : bool, optional
1298          Option whether to print a line feed or not. Defaults to True.
1299  
1300      Raises
1301      ------
1302      AttributeError
1303          If `device` does not have a ``write()`` or ``flush()`` method.
1304  
1305      Examples
1306      --------
1307      Besides ``sys.stdout``, a file-like object can also be used as it has
1308      both required methods:
1309  
1310      >>> from io import StringIO
1311      >>> buf = StringIO()
1312      >>> np.disp(u'"Display" in a file', device=buf)
1313      >>> buf.getvalue()
1314      '"Display" in a file\n'
1315  
1316      Nz%s
1317  z%s)�sys�stdout�write�flush)�mesg�device�linefeedrbrbrcrA�s rAz\w+z(?:{0:}(?:,{0:})*)?z\({}\)z{0:}(?:,{0:})*z^{0:}->{0:}$cCs@t�dd|�}t�t|�std�|���tdd�|�d�D��S)as
1318      Parse string signatures for a generalized universal function.
1319  
1320      Arguments
1321      ---------
1322      signature : string
1323          Generalized universal function signature, e.g., ``(m,n),(n,p)->(m,p)``
1324          for ``np.matmul``.
1325  
1326      Returns
1327      -------
1328      Tuple of input and output core dimensions parsed from the signature, each
1329      of the form List[Tuple[str, ...]].
1330      z\s+�z not a valid gufunc signature: {}css&�|]}dd�t�t|�D�VqdS)cSsg|]
1331  }tt�t|���qSrb)r��re�findall�_DIMENSION_NAME�r��argrbrbrcr����z5_parse_gufunc_signature.<locals>.<genexpr>.<listcomp>N)rXrY�	_ARGUMENT)r��arg_listrbrbrc�	<genexpr>�s��
1332  �z*_parse_gufunc_signature.<locals>.<genexpr>z->)rX�sub�match�
1333  _SIGNATUREr�r�r��split)�	signaturerbrbrc�_parse_gufunc_signature�s��rfcCs�|sdSt|�}|j|krtd|j|f��|j|d�}t||�D]\}}||vr=|||kr<td||||f��q#|||<q#dS)aO
1334      Incrementally check and update core dimension sizes for a single argument.
1335  
1336      Arguments
1337      ---------
1338      dim_sizes : Dict[str, int]
1339          Sizes of existing core dimensions. Will be updated in-place.
1340      arg : ndarray
1341          Argument to examine.
1342      core_dims : Tuple[str, ...]
1343          Core dimensions for this argument.
1344      NzR%d-dimensional argument does not have enough dimensions for all core dimensions %rz1inconsistent size for core dimension %r: %r vs %r)r�r�r�rrr�)�	dim_sizesr\�	core_dimsZ
num_core_dimsZ
1345  core_shape�dimr�rbrbrc�_update_dim_sizes�s*

1346  �����
1347  �rjc	Cspg}i}t||�D]#\}}t|||�|jt|�}tjj�d|jd|��}|�	|�q	tjjj
1348  |�}||fS)a�
1349      Parse broadcast and core dimensions for vectorize with a signature.
1350  
1351      Arguments
1352      ---------
1353      args : Tuple[ndarray, ...]
1354          Tuple of input arguments to examine.
1355      input_core_dims : List[Tuple[str, ...]]
1356          List of core dimensions corresponding to each input.
1357  
1358      Returns
1359      -------
1360      broadcast_shape : Tuple[int, ...]
1361          Common shape to broadcast all non-core dimensions to.
1362      dim_sizes : Dict[str, int]
1363          Common sizes for named core dimensions.
1364      rN)r�rjr�r�r~�lib�
stride_tricks�
1365  as_stridedrrrY�_broadcast_shape)	r��input_core_dimsZbroadcast_argsrgr\rhr�Zdummy_array�broadcast_shaperbrbrc�_parse_input_dimensionssrqcs��fdd�|D�S)z=Helper for calculating broadcast shapes with core dimensions.cs&g|]}�t�fdd�|D���qS)c3s�|]}�|VqdSr]rb)r�ri�rgrbrcr`1��z/_calculate_shapes.<locals>.<listcomp>.<genexpr>)r�)r�rh�rprgrbrcr�1s�z%_calculate_shapes.<locals>.<listcomp>rb)rprg�list_of_core_dimsrbrtrc�_calculate_shapes/s�rvcCsdt|||�}|durdgt|�}|dur#tdd�t||�D��}|Stdd�t|||�D��}|S)z/Helper for creating output arrays in vectorize.Ncss"�|]\}}tj||d�VqdS�)rrr�N)r~r
1366  )r�rrr�rbrbrcr`<s��z!_create_arrays.<locals>.<genexpr>css&�|]\}}}tj|||d�VqdSrw)r~r)r�r�rrr�rbrbrcr`?s��)rvr�r�r�)rprgru�dtypes�results�shapes�arraysrbrbrc�_create_arrays5s��
1367  �r|c@s>eZdZdZ		ddd�Zdd�Zdd	�Zd
1368  d�Zdd
�ZdS)rFa�
1369      vectorize(pyfunc, otypes=None, doc=None, excluded=None, cache=False,
1370                signature=None)
1371  
1372      Generalized function class.
1373  
1374      Define a vectorized function which takes a nested sequence of objects or
1375      numpy arrays as inputs and returns a single numpy array or a tuple of numpy
1376      arrays. The vectorized function evaluates `pyfunc` over successive tuples
1377      of the input arrays like the python map function, except it uses the
1378      broadcasting rules of numpy.
1379  
1380      The data type of the output of `vectorized` is determined by calling
1381      the function with the first element of the input.  This can be avoided
1382      by specifying the `otypes` argument.
1383  
1384      Parameters
1385      ----------
1386      pyfunc : callable
1387          A python function or method.
1388      otypes : str or list of dtypes, optional
1389          The output data type. It must be specified as either a string of
1390          typecode characters or a list of data type specifiers. There should
1391          be one data type specifier for each output.
1392      doc : str, optional
1393          The docstring for the function. If None, the docstring will be the
1394          ``pyfunc.__doc__``.
1395      excluded : set, optional
1396          Set of strings or integers representing the positional or keyword
1397          arguments for which the function will not be vectorized.  These will be
1398          passed directly to `pyfunc` unmodified.
1399  
1400          .. versionadded:: 1.7.0
1401  
1402      cache : bool, optional
1403          If `True`, then cache the first function call that determines the number
1404          of outputs if `otypes` is not provided.
1405  
1406          .. versionadded:: 1.7.0
1407  
1408      signature : string, optional
1409          Generalized universal function signature, e.g., ``(m,n),(n)->(m)`` for
1410          vectorized matrix-vector multiplication. If provided, ``pyfunc`` will
1411          be called with (and expected to return) arrays with shapes given by the
1412          size of corresponding core dimensions. By default, ``pyfunc`` is
1413          assumed to take scalars as input and output.
1414  
1415          .. versionadded:: 1.12.0
1416  
1417      Returns
1418      -------
1419      vectorized : callable
1420          Vectorized function.
1421  
1422      See Also
1423      --------
1424      frompyfunc : Takes an arbitrary Python function and returns a ufunc
1425  
1426      Notes
1427      -----
1428      The `vectorize` function is provided primarily for convenience, not for
1429      performance. The implementation is essentially a for loop.
1430  
1431      If `otypes` is not specified, then a call to the function with the
1432      first argument will be used to determine the number of outputs.  The
1433      results of this call will be cached if `cache` is `True` to prevent
1434      calling the function twice.  However, to implement the cache, the
1435      original function must be wrapped which will slow down subsequent
1436      calls, so only do this if your function is expensive.
1437  
1438      The new keyword argument interface and `excluded` argument support
1439      further degrades performance.
1440  
1441      References
1442      ----------
1443      .. [1] :doc:`/reference/c-api/generalized-ufuncs`
1444  
1445      Examples
1446      --------
1447      >>> def myfunc(a, b):
1448      ...     "Return a-b if a>b, otherwise return a+b"
1449      ...     if a > b:
1450      ...         return a - b
1451      ...     else:
1452      ...         return a + b
1453  
1454      >>> vfunc = np.vectorize(myfunc)
1455      >>> vfunc([1, 2, 3, 4], 2)
1456      array([3, 4, 1, 2])
1457  
1458      The docstring is taken from the input function to `vectorize` unless it
1459      is specified:
1460  
1461      >>> vfunc.__doc__
1462      'Return a-b if a>b, otherwise return a+b'
1463      >>> vfunc = np.vectorize(myfunc, doc='Vectorized `myfunc`')
1464      >>> vfunc.__doc__
1465      'Vectorized `myfunc`'
1466  
1467      The output type is determined by evaluating the first element of the input,
1468      unless it is specified:
1469  
1470      >>> out = vfunc([1, 2, 3, 4], 2)
1471      >>> type(out[0])
1472      <class 'numpy.int64'>
1473      >>> vfunc = np.vectorize(myfunc, otypes=[float])
1474      >>> out = vfunc([1, 2, 3, 4], 2)
1475      >>> type(out[0])
1476      <class 'numpy.float64'>
1477  
1478      The `excluded` argument can be used to prevent vectorizing over certain
1479      arguments.  This can be useful for array-like arguments of a fixed length
1480      such as the coefficients for a polynomial as in `polyval`:
1481  
1482      >>> def mypolyval(p, x):
1483      ...     _p = list(p)
1484      ...     res = _p.pop(0)
1485      ...     while _p:
1486      ...         res = res*x + _p.pop(0)
1487      ...     return res
1488      >>> vpolyval = np.vectorize(mypolyval, excluded=['p'])
1489      >>> vpolyval(p=[1, 2, 3], x=[0, 1])
1490      array([3, 6])
1491  
1492      Positional arguments may also be excluded by specifying their position:
1493  
1494      >>> vpolyval.excluded.add(0)
1495      >>> vpolyval([1, 2, 3], x=[0, 1])
1496      array([3, 6])
1497  
1498      The `signature` argument allows for vectorizing functions that act on
1499      non-scalar arrays of fixed length. For example, you can use it for a
1500      vectorized calculation of Pearson correlation coefficient and its p-value:
1501  
1502      >>> import scipy.stats
1503      >>> pearsonr = np.vectorize(scipy.stats.pearsonr,
1504      ...                 signature='(n),(n)->(),()')
1505      >>> pearsonr([[0, 1, 2, 3]], [[1, 2, 3, 4], [4, 3, 2, 1]])
1506      (array([ 1., -1.]), array([ 0.,  0.]))
1507  
1508      Or for a vectorized convolution:
1509  
1510      >>> convolve = np.vectorize(np.convolve, signature='(n),(m)->(k)')
1511      >>> convolve(np.eye(4), [1, 2, 1])
1512      array([[1., 2., 1., 0., 0., 0.],
1513             [0., 1., 2., 1., 0., 0.],
1514             [0., 0., 1., 2., 1., 0.],
1515             [0., 0., 0., 1., 2., 1.]])
1516  
1517      NFcCs�||_||_||_i|_|dur|j|_n||_t|t�r0|D]}|tdvr.td|f��qnt	|�r?d�
1518  dd�|D��}n|durGtd��||_|durQt�}t|�|_
|durat|�|_dSd|_dS)N�AllzInvalid otype specified: %srWcSsg|]}t�|�j�qSrb)r�r�r��r�r�rbrbrcr���z&vectorize.__init__.<locals>.<listcomp>zInvalid otype specification)�pyfunc�cachere�_ufunc�__doc__r��strr%r�r:�join�otypes�set�excludedrf�_in_and_out_core_dims)�selfr�r��docr�r�rer�rbrbrc�__init__�s0
1519  
1520  ��
1521  
1522  zvectorize.__init__cs��j��s
�s
�j}�}n;t��}�fdd��D���fdd�t|�D��t��������fdd�}�fdd��D�}|��fdd��D���j||d�S)	z�
1523          Return arrays with the results of `pyfunc` broadcast (vectorized) over
1524          `args` and `kwargs` not in `excluded`.
1525          c�g|]}|�vr|�qSrbrb�r��_n�r�rbrcr�	rz&vectorize.__call__.<locals>.<listcomp>cr�rbrb�r��_ir�rbrcr�
	rcsJt��D]
1526  \}}||�|<q��t�|t��d����j�i���Sr])r��updater�r�r�)�vargsr�r�)�inds�kwargs�namesr��the_argsrbrcr�	sz vectorize.__call__.<locals>.funcc�g|]}�|�qSrbrbr�)r�rbrcr�	�cr�rbrbr�)r�rbrcr�	r��r�r�)r�r�r�r�r��extend�_vectorize_call)r�r�r�r�r��nargsrb)r�r�r�r�r�r�r�rc�__call__�szvectorize.__call__c	s&|std��|jdur:|j}t|�}t|j�}�|jus!||jvr(t�||�}nd}�|jur6|j�||�}||fSdd�|D�}t�dd�|D��rOtd��dd�|D�}�|��|j	rh�g���fd	d
1527  �}n�}t
1528  �t�rtt��}nd}�f�d��fd
d�t
|�D��}t|t|�|�}||fS)zReturn (ufunc, otypes).zargs can not be emptyNcSsg|]}t|��qSrb)rr[rbrbrcr�9	r�z3vectorize._get_ufunc_and_otypes.<locals>.<listcomp>css�|]}|jdkVqdS�rN)r�r[rbrbrcr`:	s�z2vectorize._get_ufunc_and_otypes.<locals>.<genexpr>�?cannot call `vectorize` on size 0 inputs unless `otypes` is setcSsg|]}|jd�qS�r)�flatr[rbrbrcr�>	r�cs�r���S�|�Sr])�pop)r�)�_cacher�rbrc�_funcH	sz.vectorize._get_ufunc_and_otypes.<locals>._funcrmrWcsg|]
1529  }t�|�jj�qSrb)rr�r�)r��_k)�outputsrbrcr�V	r])r�r�r�r�r�r�
1530  setdefault�builtinsr#r�r�r�r�r�)	r�r�r�r��nin�nout�ufunc�inputsr�rb)r�r�r�rc�_get_ufunc_and_otypes	s<
1531  	
1532  
1533  ,�
1534  
1535  �zvectorize._get_ufunc_and_otypescCs�|jdur
|�||�}|S|s|�}|S|j||d�\}}dd�|D�}||�}|jdkr7t||dd�}|Stdd�t||�D��}|S)	z1Vectorized call to `func` over positional `args`.Nr�cSsg|]}t|td��qS�r�)r	�object)r�r�rbrbrcr�j	rz-vectorize._vectorize_call.<locals>.<listcomp>rmrr�cSsg|]
1536  \}}t||d��qSr��r	)r�r��trbrbrcr�q	s�)re�_vectorize_call_with_signaturer�r�r	r�r�)r�r�r��resr�r�r�r�rbrbrcr�`	s 
1537  ��
1538  ��zvectorize._vectorize_callcs�|j\}}t|�t|�krtdt|�t|�f��tdd�|D��}t||�\}�t|�|�}dd�t||�D�}d}|j}t|�}	tj	|�D]U�|�fdd�|D��}
1539  t
1540  |
1541  t�r]t|
1542  �nd}|	|krktd	|	|f��|	dkrr|
1543  f}
1544  |dur�t|
1545  |�D]
1546  \}}
t�||
�q{t
|�|||
1547  �}t||
1548  �D]\}}||�<q�qG|dur�|dur�td
1549  ��t��fdd�|D��r�td��t
|�||�}|	dkr�|d
S|S)z;Vectorized call over positional arguments with a signature.z9wrong number of positional arguments: expected %r, got %rcss�|]}t|�VqdSr]r�r[rbrbrcr`}	rsz;vectorize._vectorize_call_with_signature.<locals>.<genexpr>cSs g|]\}}tj||dd��qS)T)r�)r~r�)r�r\rrrbrbrcr��	s�z<vectorize._vectorize_call_with_signature.<locals>.<listcomp>Nc3s�|]}|�VqdSr]rbr[)r�rbrcr`�	rsrmz8wrong number of outputs from pyfunc: expected %r, got %rr�c3s"�|]}|D]}|�vVqqdSr]rb)r��dimsrirrrbrcr`�	s���zYcannot call `vectorize` with a signature including new output dimensions on size 0 inputsr)r�r�r�r�rqrvr�r�r~�ndindexr�r�rjr|r�r#)r�r�r�roZoutput_core_dimsrp�input_shapesr�r�r�ryZ	n_resultsr�rh�outputrb)rgr�rcr�u	sb
1550  �������
1551  ���z(vectorize._vectorize_call_with_signature)NNNFN)	rO�
1552  __module__�__qualname__r�r�r�r�r�r�rbrbrbrcrFEs
1553  � ErFr�cCs||||fSr]rb)r�r��rowvar�bias�ddof�fweights�aweightsr�rbrbrc�_cov_dispatcher�	sr�cCs|dur|t|�krtd��t�|�}|jdkrtd��|dur.t�|�}|jdkr.td��|durF|dur>t�|tj�}nt�||tj�}t|d|d�}|sY|jddkrY|j	}|jddkrit�g��
1554  dd�S|dur�t|d	d|d
1555  �}|s�|jddkr�|j	}tj||fdd�}|dur�|dkr�d}nd}d}	|dur�tj|td�}t�
|t�|�k�s�td
��|jdkr�td��|jd|jdkr�td��t|dk�r�td��|}	|du�rtj|td�}|jdkr�td��|jd|jdkr�td��t|dk��rtd��|	du�r|}	n|	|9}	t|d|	dd�\}
1556  }|d}|	du�r*|jd|}n|dk�r2|}n|du�r<||}n||t|	|�|}|dk�rWtjdtdd�d}||
1557  dd�df8}|	du�rj|j	}
n||	j	}
t||
���}|t�d|�9}|��S)a'
1558      Estimate a covariance matrix, given data and weights.
1559  
1560      Covariance indicates the level to which two variables vary together.
1561      If we examine N-dimensional samples, :math:`X = [x_1, x_2, ... x_N]^T`,
1562      then the covariance matrix element :math:`C_{ij}` is the covariance of
1563      :math:`x_i` and :math:`x_j`. The element :math:`C_{ii}` is the variance
1564      of :math:`x_i`.
1565  
1566      See the notes for an outline of the algorithm.
1567  
1568      Parameters
1569      ----------
1570      m : array_like
1571          A 1-D or 2-D array containing multiple variables and observations.
1572          Each row of `m` represents a variable, and each column a single
1573          observation of all those variables. Also see `rowvar` below.
1574      y : array_like, optional
1575          An additional set of variables and observations. `y` has the same form
1576          as that of `m`.
1577      rowvar : bool, optional
1578          If `rowvar` is True (default), then each row represents a
1579          variable, with observations in the columns. Otherwise, the relationship
1580          is transposed: each column represents a variable, while the rows
1581          contain observations.
1582      bias : bool, optional
1583          Default normalization (False) is by ``(N - 1)``, where ``N`` is the
1584          number of observations given (unbiased estimate). If `bias` is True,
1585          then normalization is by ``N``. These values can be overridden by using
1586          the keyword ``ddof`` in numpy versions >= 1.5.
1587      ddof : int, optional
1588          If not ``None`` the default value implied by `bias` is overridden.
1589          Note that ``ddof=1`` will return the unbiased estimate, even if both
1590          `fweights` and `aweights` are specified, and ``ddof=0`` will return
1591          the simple average. See the notes for the details. The default value
1592          is ``None``.
1593  
1594          .. versionadded:: 1.5
1595      fweights : array_like, int, optional
1596          1-D array of integer frequency weights; the number of times each
1597          observation vector should be repeated.
1598  
1599          .. versionadded:: 1.10
1600      aweights : array_like, optional
1601          1-D array of observation vector weights. These relative weights are
1602          typically large for observations considered "important" and smaller for
1603          observations considered less "important". If ``ddof=0`` the array of
1604          weights can be used to assign probabilities to observation vectors.
1605  
1606          .. versionadded:: 1.10
1607      dtype : data-type, optional
1608          Data-type of the result. By default, the return data-type will have
1609          at least `numpy.float64` precision.
1610  
1611          .. versionadded:: 1.20
1612  
1613      Returns
1614      -------
1615      out : ndarray
1616          The covariance matrix of the variables.
1617  
1618      See Also
1619      --------
1620      corrcoef : Normalized covariance matrix
1621  
1622      Notes
1623      -----
1624      Assume that the observations are in the columns of the observation
1625      array `m` and let ``f = fweights`` and ``a = aweights`` for brevity. The
1626      steps to compute the weighted covariance are as follows::
1627  
1628          >>> m = np.arange(10, dtype=np.float64)
1629          >>> f = np.arange(10) * 2
1630          >>> a = np.arange(10) ** 2.
1631          >>> ddof = 1
1632          >>> w = f * a
1633          >>> v1 = np.sum(w)
1634          >>> v2 = np.sum(w * a)
1635          >>> m -= np.sum(m * w, axis=None, keepdims=True) / v1
1636          >>> cov = np.dot(m * w, m.T) * v1 / (v1**2 - ddof * v2)
1637  
1638      Note that when ``a == 1``, the normalization factor
1639      ``v1 / (v1**2 - ddof * v2)`` goes over to ``1 / (np.sum(f) - ddof)``
1640      as it should.
1641  
1642      Examples
1643      --------
1644      Consider two variables, :math:`x_0` and :math:`x_1`, which
1645      correlate perfectly, but in opposite directions:
1646  
1647      >>> x = np.array([[0, 2], [1, 1], [2, 0]]).T
1648      >>> x
1649      array([[0, 1, 2],
1650             [2, 1, 0]])
1651  
1652      Note how :math:`x_0` increases while :math:`x_1` decreases. The covariance
1653      matrix shows this clearly:
1654  
1655      >>> np.cov(x)
1656      array([[ 1., -1.],
1657             [-1.,  1.]])
1658  
1659      Note that element :math:`C_{0,1}`, which shows the correlation between
1660      :math:`x_0` and :math:`x_1`, is negative.
1661  
1662      Further, note how `x` and `y` are combined:
1663  
1664      >>> x = [-2.1, -1,  4.3]
1665      >>> y = [3,  1.1,  0.12]
1666      >>> X = np.stack((x, y), axis=0)
1667      >>> np.cov(X)
1668      array([[11.71      , -4.286     ], # may vary
1669             [-4.286     ,  2.144133]])
1670      >>> np.cov(x, y)
1671      array([[11.71      , -4.286     ], # may vary
1672             [-4.286     ,  2.144133]])
1673      >>> np.cov(x)
1674      array(11.71)
1675  
1676      Nzddof must be integerr�zm has more than 2 dimensionszy has more than 2 dimensions)�ndminr�rrmF�r9r�r�r�r�zfweights must be integerz'cannot handle multidimensional fweightsz,incompatible numbers of samples and fweightszfweights cannot be negativez'cannot handle multidimensional aweightsz,incompatible numbers of samples and aweightszaweights cannot be negativeT)r�r�r�z!Degrees of freedom <= 0 for slice���
1677  stacklevelr�)rr�r~rr�r�r�rrr�T�reshaper�floatr�r�r��RuntimeErrorr#rHr$�warnings�warn�RuntimeWarningr
�conj�true_divide�squeeze)r�r�r�r�r�r�r�r��X�wr�Zw_sum�factZX_TrrbrbrcrJ�	s�|�
1678  
1679  
1680  
1681  �
1682  ���
1683  
1684  ���
1685  
1686  
1687  
1688  
1689  
1690  �
1691  
1692  rJcCrFr]rb)r�r�r�r�r�r�rbrbrc�_corrcoef_dispatcher�
1693  r�r�c	Cs�|tjus
1694  |tjurtjdtdd�t||||d�}zt|�}Wn
ty-||YSwt|j	�}||dd�df}||ddd�f}tj
1695  |j	dd|j	d�t�|�rbtj
1696  |jdd|jd�|S)	ai
1697      Return Pearson product-moment correlation coefficients.
1698  
1699      Please refer to the documentation for `cov` for more detail.  The
1700      relationship between the correlation coefficient matrix, `R`, and the
1701      covariance matrix, `C`, is
1702  
1703      .. math:: R_{ij} = \frac{ C_{ij} } { \sqrt{ C_{ii} C_{jj} } }
1704  
1705      The values of `R` are between -1 and 1, inclusive.
1706  
1707      Parameters
1708      ----------
1709      x : array_like
1710          A 1-D or 2-D array containing multiple variables and observations.
1711          Each row of `x` represents a variable, and each column a single
1712          observation of all those variables. Also see `rowvar` below.
1713      y : array_like, optional
1714          An additional set of variables and observations. `y` has the same
1715          shape as `x`.
1716      rowvar : bool, optional
1717          If `rowvar` is True (default), then each row represents a
1718          variable, with observations in the columns. Otherwise, the relationship
1719          is transposed: each column represents a variable, while the rows
1720          contain observations.
1721      bias : _NoValue, optional
1722          Has no effect, do not use.
1723  
1724          .. deprecated:: 1.10.0
1725      ddof : _NoValue, optional
1726          Has no effect, do not use.
1727  
1728          .. deprecated:: 1.10.0
1729      dtype : data-type, optional
1730          Data-type of the result. By default, the return data-type will have
1731          at least `numpy.float64` precision.
1732  
1733          .. versionadded:: 1.20
1734  
1735      Returns
1736      -------
1737      R : ndarray
1738          The correlation coefficient matrix of the variables.
1739  
1740      See Also
1741      --------
1742      cov : Covariance matrix
1743  
1744      Notes
1745      -----
1746      Due to floating point rounding the resulting array may not be Hermitian,
1747      the diagonal elements may not be 1, and the elements may not satisfy the
1748      inequality abs(a) <= 1. The real and imaginary parts are clipped to the
1749      interval [-1,  1] in an attempt to improve on that situation but is not
1750      much help in the complex case.
1751  
1752      This function accepts but discards arguments `bias` and `ddof`.  This is
1753      for backwards compatibility with previous versions of this function.  These
1754      arguments had no effect on the return values of the function and can be
1755      safely ignored in this and previous versions of numpy.
1756  
1757      Examples
1758      --------
1759      In this example we generate two random arrays, ``xarr`` and ``yarr``, and
1760      compute the row-wise and column-wise Pearson correlation coefficients,
1761      ``R``. Since ``rowvar`` is  true by  default, we first find the row-wise
1762      Pearson correlation coefficients between the variables of ``xarr``.
1763  
1764      >>> import numpy as np
1765      >>> rng = np.random.default_rng(seed=42)
1766      >>> xarr = rng.random((3, 3))
1767      >>> xarr
1768      array([[0.77395605, 0.43887844, 0.85859792],
1769             [0.69736803, 0.09417735, 0.97562235],
1770             [0.7611397 , 0.78606431, 0.12811363]])
1771      >>> R1 = np.corrcoef(xarr)
1772      >>> R1
1773      array([[ 1.        ,  0.99256089, -0.68080986],
1774             [ 0.99256089,  1.        , -0.76492172],
1775             [-0.68080986, -0.76492172,  1.        ]])
1776  
1777      If we add another set of variables and observations ``yarr``, we can
1778      compute the row-wise Pearson correlation coefficients between the
1779      variables in ``xarr`` and ``yarr``.
1780  
1781      >>> yarr = rng.random((3, 3))
1782      >>> yarr
1783      array([[0.45038594, 0.37079802, 0.92676499],
1784             [0.64386512, 0.82276161, 0.4434142 ],
1785             [0.22723872, 0.55458479, 0.06381726]])
1786      >>> R2 = np.corrcoef(xarr, yarr)
1787      >>> R2
1788      array([[ 1.        ,  0.99256089, -0.68080986,  0.75008178, -0.934284  ,
1789              -0.99004057],
1790             [ 0.99256089,  1.        , -0.76492172,  0.82502011, -0.97074098,
1791              -0.99981569],
1792             [-0.68080986, -0.76492172,  1.        , -0.99507202,  0.89721355,
1793               0.77714685],
1794             [ 0.75008178,  0.82502011, -0.99507202,  1.        , -0.93657855,
1795              -0.83571711],
1796             [-0.934284  , -0.97074098,  0.89721355, -0.93657855,  1.        ,
1797               0.97517215],
1798             [-0.99004057, -0.99981569,  0.77714685, -0.83571711,  0.97517215,
1799               1.        ]])
1800  
1801      Finally if we use the option ``rowvar=False``, the columns are now
1802      being treated as the variables and we will find the column-wise Pearson
1803      correlation coefficients between variables in ``xarr`` and ``yarr``.
1804  
1805      >>> R3 = np.corrcoef(xarr, yarr, rowvar=False)
1806      >>> R3
1807      array([[ 1.        ,  0.77598074, -0.47458546, -0.75078643, -0.9665554 ,
1808               0.22423734],
1809             [ 0.77598074,  1.        , -0.92346708, -0.99923895, -0.58826587,
1810              -0.44069024],
1811             [-0.47458546, -0.92346708,  1.        ,  0.93773029,  0.23297648,
1812               0.75137473],
1813             [-0.75078643, -0.99923895,  0.93773029,  1.        ,  0.55627469,
1814               0.47536961],
1815             [-0.9665554 , -0.58826587,  0.23297648,  0.55627469,  1.        ,
1816              -0.46666491],
1817             [ 0.22423734, -0.44069024,  0.75137473,  0.47536961, -0.46666491,
1818               1.        ]])
1819  
1820      z/bias and ddof have no effect and are deprecatedr�r�r�Nr�rm�r)
r~r�r�r��DeprecationWarningrJr)r�rr,�cliprr+)	r�r�r�r�r�r�r�d�stddevrbrbrcrK�
1821  s$��
1822  
1823  rKcCs�|dkrtgt�|d�d�S|dkrtdt�|d�d�Std||d�}ddtt||d�dtdt||d�S)	a
1824      Return the Blackman window.
1825  
1826      The Blackman window is a taper formed by using the first three
1827      terms of a summation of cosines. It was designed to have close to the
1828      minimal leakage possible.  It is close to optimal, only slightly worse
1829      than a Kaiser window.
1830  
1831      Parameters
1832      ----------
1833      M : int
1834          Number of points in the output window. If zero or less, an empty
1835          array is returned.
1836  
1837      Returns
1838      -------
1839      out : ndarray
1840          The window, with the maximum value normalized to one (the value one
1841          appears only if the number of samples is odd).
1842  
1843      See Also
1844      --------
1845      bartlett, hamming, hanning, kaiser
1846  
1847      Notes
1848      -----
1849      The Blackman window is defined as
1850  
1851      .. math::  w(n) = 0.42 - 0.5 \cos(2\pi n/M) + 0.08 \cos(4\pi n/M)
1852  
1853      Most references to the Blackman window come from the signal processing
1854      literature, where it is used as one of many windowing functions for
1855      smoothing values.  It is also known as an apodization (which means
1856      "removing the foot", i.e. smoothing discontinuities at the beginning
1857      and end of the sampled signal) or tapering function. It is known as a
1858      "near optimal" tapering function, almost as good (by some measures)
1859      as the kaiser window.
1860  
1861      References
1862      ----------
1863      Blackman, R.B. and Tukey, J.W., (1958) The measurement of power spectra,
1864      Dover Publications, New York.
1865  
1866      Oppenheim, A.V., and R.W. Schafer. Discrete-Time Signal Processing.
1867      Upper Saddle River, NJ: Prentice-Hall, 1999, pp. 468-471.
1868  
1869      Examples
1870      --------
1871      >>> import matplotlib.pyplot as plt
1872      >>> np.blackman(12)
1873      array([-1.38777878e-17,   3.26064346e-02,   1.59903635e-01, # may vary
1874              4.14397981e-01,   7.36045180e-01,   9.67046769e-01,
1875              9.67046769e-01,   7.36045180e-01,   4.14397981e-01,
1876              1.59903635e-01,   3.26064346e-02,  -1.38777878e-17])
1877  
1878      Plot the window and the frequency response:
1879  
1880      >>> from numpy.fft import fft, fftshift
1881      >>> window = np.blackman(51)
1882      >>> plt.plot(window)
1883      [<matplotlib.lines.Line2D object at 0x...>]
1884      >>> plt.title("Blackman window")
1885      Text(0.5, 1.0, 'Blackman window')
1886      >>> plt.ylabel("Amplitude")
1887      Text(0, 0.5, 'Amplitude')
1888      >>> plt.xlabel("Sample")
1889      Text(0.5, 0, 'Sample')
1890      >>> plt.show()
1891  
1892      >>> plt.figure()
1893      <Figure size 640x480 with 0 Axes>
1894      >>> A = fft(window, 2048) / 25.5
1895      >>> mag = np.abs(fftshift(A))
1896      >>> freq = np.linspace(-0.5, 0.5, len(A))
1897      >>> with np.errstate(divide='ignore', invalid='ignore'):
1898      ...     response = 20 * np.log10(mag)
1899      ...
1900      >>> response = np.clip(response, -100, 100)
1901      >>> plt.plot(freq, response)
1902      [<matplotlib.lines.Line2D object at 0x...>]
1903      >>> plt.title("Frequency response of Blackman window")
1904      Text(0.5, 1.0, 'Frequency response of Blackman window')
1905      >>> plt.ylabel("Magnitude [dB]")
1906      Text(0, 0.5, 'Magnitude [dB]')
1907      >>> plt.xlabel("Normalized frequency [cycles per sample]")
1908      Text(0.5, 0, 'Normalized frequency [cycles per sample]')
1909      >>> _ = plt.axis('tight')
1910      >>> plt.show()
1911  
1912      rmr�r�r�g�z�G��?rpg{�G�z�?r��rr~r�rrrr��Mr`rbrbrcrR3s\8rRcCsr|dkrtgt�|d�d�S|dkrtdt�|d�d�Std||d�}tt|d�d||dd||d�S)a6
1913      Return the Bartlett window.
1914  
1915      The Bartlett window is very similar to a triangular window, except
1916      that the end points are at zero.  It is often used in signal
1917      processing for tapering a signal, without generating too much
1918      ripple in the frequency domain.
1919  
1920      Parameters
1921      ----------
1922      M : int
1923          Number of points in the output window. If zero or less, an
1924          empty array is returned.
1925  
1926      Returns
1927      -------
1928      out : array
1929          The triangular window, with the maximum value normalized to one
1930          (the value one appears only if the number of samples is odd), with
1931          the first and last samples equal to zero.
1932  
1933      See Also
1934      --------
1935      blackman, hamming, hanning, kaiser
1936  
1937      Notes
1938      -----
1939      The Bartlett window is defined as
1940  
1941      .. math:: w(n) = \frac{2}{M-1} \left(
1942                \frac{M-1}{2} - \left|n - \frac{M-1}{2}\right|
1943                \right)
1944  
1945      Most references to the Bartlett window come from the signal processing
1946      literature, where it is used as one of many windowing functions for
1947      smoothing values.  Note that convolution with this window produces linear
1948      interpolation.  It is also known as an apodization (which means "removing
1949      the foot", i.e. smoothing discontinuities at the beginning and end of the
1950      sampled signal) or tapering function. The Fourier transform of the
1951      Bartlett window is the product of two sinc functions. Note the excellent
1952      discussion in Kanasewich [2]_.
1953  
1954      References
1955      ----------
1956      .. [1] M.S. Bartlett, "Periodogram Analysis and Continuous Spectra",
1957             Biometrika 37, 1-16, 1950.
1958      .. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics",
1959             The University of Alberta Press, 1975, pp. 109-110.
1960      .. [3] A.V. Oppenheim and R.W. Schafer, "Discrete-Time Signal
1961             Processing", Prentice-Hall, 1999, pp. 468-471.
1962      .. [4] Wikipedia, "Window function",
1963             https://en.wikipedia.org/wiki/Window_function
1964      .. [5] W.H. Press,  B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling,
1965             "Numerical Recipes", Cambridge University Press, 1986, page 429.
1966  
1967      Examples
1968      --------
1969      >>> import matplotlib.pyplot as plt
1970      >>> np.bartlett(12)
1971      array([ 0.        ,  0.18181818,  0.36363636,  0.54545455,  0.72727273, # may vary
1972              0.90909091,  0.90909091,  0.72727273,  0.54545455,  0.36363636,
1973              0.18181818,  0.        ])
1974  
1975      Plot the window and its frequency response (requires SciPy and matplotlib):
1976  
1977      >>> from numpy.fft import fft, fftshift
1978      >>> window = np.bartlett(51)
1979      >>> plt.plot(window)
1980      [<matplotlib.lines.Line2D object at 0x...>]
1981      >>> plt.title("Bartlett window")
1982      Text(0.5, 1.0, 'Bartlett window')
1983      >>> plt.ylabel("Amplitude")
1984      Text(0, 0.5, 'Amplitude')
1985      >>> plt.xlabel("Sample")
1986      Text(0.5, 0, 'Sample')
1987      >>> plt.show()
1988  
1989      >>> plt.figure()
1990      <Figure size 640x480 with 0 Axes>
1991      >>> A = fft(window, 2048) / 25.5
1992      >>> mag = np.abs(fftshift(A))
1993      >>> freq = np.linspace(-0.5, 0.5, len(A))
1994      >>> with np.errstate(divide='ignore', invalid='ignore'):
1995      ...     response = 20 * np.log10(mag)
1996      ...
1997      >>> response = np.clip(response, -100, 100)
1998      >>> plt.plot(freq, response)
1999      [<matplotlib.lines.Line2D object at 0x...>]
2000      >>> plt.title("Frequency response of Bartlett window")
2001      Text(0.5, 1.0, 'Frequency response of Bartlett window')
2002      >>> plt.ylabel("Magnitude [dB]")
2003      Text(0, 0.5, 'Magnitude [dB]')
2004      >>> plt.xlabel("Normalized frequency [cycles per sample]")
2005      Text(0.5, 0, 'Normalized frequency [cycles per sample]')
2006      >>> _ = plt.axis('tight')
2007      >>> plt.show()
2008  
2009      rmr�r�r�r)rr~r�rrrrr�rbrbrcrQ�sd*rQcCsd|dkrtgt�|d�d�S|dkrtdt�|d�d�Std||d�}ddtt||d�S)a�
2010      Return the Hanning window.
2011  
2012      The Hanning window is a taper formed by using a weighted cosine.
2013  
2014      Parameters
2015      ----------
2016      M : int
2017          Number of points in the output window. If zero or less, an
2018          empty array is returned.
2019  
2020      Returns
2021      -------
2022      out : ndarray, shape(M,)
2023          The window, with the maximum value normalized to one (the value
2024          one appears only if `M` is odd).
2025  
2026      See Also
2027      --------
2028      bartlett, blackman, hamming, kaiser
2029  
2030      Notes
2031      -----
2032      The Hanning window is defined as
2033  
2034      .. math::  w(n) = 0.5 - 0.5\cos\left(\frac{2\pi{n}}{M-1}\right)
2035                 \qquad 0 \leq n \leq M-1
2036  
2037      The Hanning was named for Julius von Hann, an Austrian meteorologist.
2038      It is also known as the Cosine Bell. Some authors prefer that it be
2039      called a Hann window, to help avoid confusion with the very similar
2040      Hamming window.
2041  
2042      Most references to the Hanning window come from the signal processing
2043      literature, where it is used as one of many windowing functions for
2044      smoothing values.  It is also known as an apodization (which means
2045      "removing the foot", i.e. smoothing discontinuities at the beginning
2046      and end of the sampled signal) or tapering function.
2047  
2048      References
2049      ----------
2050      .. [1] Blackman, R.B. and Tukey, J.W., (1958) The measurement of power
2051             spectra, Dover Publications, New York.
2052      .. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics",
2053             The University of Alberta Press, 1975, pp. 106-108.
2054      .. [3] Wikipedia, "Window function",
2055             https://en.wikipedia.org/wiki/Window_function
2056      .. [4] W.H. Press,  B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling,
2057             "Numerical Recipes", Cambridge University Press, 1986, page 425.
2058  
2059      Examples
2060      --------
2061      >>> np.hanning(12)
2062      array([0.        , 0.07937323, 0.29229249, 0.57115742, 0.82743037,
2063             0.97974649, 0.97974649, 0.82743037, 0.57115742, 0.29229249,
2064             0.07937323, 0.        ])
2065  
2066      Plot the window and its frequency response:
2067  
2068      >>> import matplotlib.pyplot as plt
2069      >>> from numpy.fft import fft, fftshift
2070      >>> window = np.hanning(51)
2071      >>> plt.plot(window)
2072      [<matplotlib.lines.Line2D object at 0x...>]
2073      >>> plt.title("Hann window")
2074      Text(0.5, 1.0, 'Hann window')
2075      >>> plt.ylabel("Amplitude")
2076      Text(0, 0.5, 'Amplitude')
2077      >>> plt.xlabel("Sample")
2078      Text(0.5, 0, 'Sample')
2079      >>> plt.show()
2080  
2081      >>> plt.figure()
2082      <Figure size 640x480 with 0 Axes>
2083      >>> A = fft(window, 2048) / 25.5
2084      >>> mag = np.abs(fftshift(A))
2085      >>> freq = np.linspace(-0.5, 0.5, len(A))
2086      >>> with np.errstate(divide='ignore', invalid='ignore'):
2087      ...     response = 20 * np.log10(mag)
2088      ...
2089      >>> response = np.clip(response, -100, 100)
2090      >>> plt.plot(freq, response)
2091      [<matplotlib.lines.Line2D object at 0x...>]
2092      >>> plt.title("Frequency response of the Hann window")
2093      Text(0.5, 1.0, 'Frequency response of the Hann window')
2094      >>> plt.ylabel("Magnitude [dB]")
2095      Text(0, 0.5, 'Magnitude [dB]')
2096      >>> plt.xlabel("Normalized frequency [cycles per sample]")
2097      Text(0.5, 0, 'Normalized frequency [cycles per sample]')
2098      >>> plt.axis('tight')
2099      ...
2100      >>> plt.show()
2101  
2102      rmr�r�r�rpr�r�rbrbrcrPs`rPcCsd|dkrtgt�|d�d�S|dkrtdt�|d�d�Std||d�}ddtt||d�S)a_
2103      Return the Hamming window.
2104  
2105      The Hamming window is a taper formed by using a weighted cosine.
2106  
2107      Parameters
2108      ----------
2109      M : int
2110          Number of points in the output window. If zero or less, an
2111          empty array is returned.
2112  
2113      Returns
2114      -------
2115      out : ndarray
2116          The window, with the maximum value normalized to one (the value
2117          one appears only if the number of samples is odd).
2118  
2119      See Also
2120      --------
2121      bartlett, blackman, hanning, kaiser
2122  
2123      Notes
2124      -----
2125      The Hamming window is defined as
2126  
2127      .. math::  w(n) = 0.54 - 0.46\cos\left(\frac{2\pi{n}}{M-1}\right)
2128                 \qquad 0 \leq n \leq M-1
2129  
2130      The Hamming was named for R. W. Hamming, an associate of J. W. Tukey
2131      and is described in Blackman and Tukey. It was recommended for
2132      smoothing the truncated autocovariance function in the time domain.
2133      Most references to the Hamming window come from the signal processing
2134      literature, where it is used as one of many windowing functions for
2135      smoothing values.  It is also known as an apodization (which means
2136      "removing the foot", i.e. smoothing discontinuities at the beginning
2137      and end of the sampled signal) or tapering function.
2138  
2139      References
2140      ----------
2141      .. [1] Blackman, R.B. and Tukey, J.W., (1958) The measurement of power
2142             spectra, Dover Publications, New York.
2143      .. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics", The
2144             University of Alberta Press, 1975, pp. 109-110.
2145      .. [3] Wikipedia, "Window function",
2146             https://en.wikipedia.org/wiki/Window_function
2147      .. [4] W.H. Press,  B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling,
2148             "Numerical Recipes", Cambridge University Press, 1986, page 425.
2149  
2150      Examples
2151      --------
2152      >>> np.hamming(12)
2153      array([ 0.08      ,  0.15302337,  0.34890909,  0.60546483,  0.84123594, # may vary
2154              0.98136677,  0.98136677,  0.84123594,  0.60546483,  0.34890909,
2155              0.15302337,  0.08      ])
2156  
2157      Plot the window and the frequency response:
2158  
2159      >>> import matplotlib.pyplot as plt
2160      >>> from numpy.fft import fft, fftshift
2161      >>> window = np.hamming(51)
2162      >>> plt.plot(window)
2163      [<matplotlib.lines.Line2D object at 0x...>]
2164      >>> plt.title("Hamming window")
2165      Text(0.5, 1.0, 'Hamming window')
2166      >>> plt.ylabel("Amplitude")
2167      Text(0, 0.5, 'Amplitude')
2168      >>> plt.xlabel("Sample")
2169      Text(0.5, 0, 'Sample')
2170      >>> plt.show()
2171  
2172      >>> plt.figure()
2173      <Figure size 640x480 with 0 Axes>
2174      >>> A = fft(window, 2048) / 25.5
2175      >>> mag = np.abs(fftshift(A))
2176      >>> freq = np.linspace(-0.5, 0.5, len(A))
2177      >>> response = 20 * np.log10(mag)
2178      >>> response = np.clip(response, -100, 100)
2179      >>> plt.plot(freq, response)
2180      [<matplotlib.lines.Line2D object at 0x...>]
2181      >>> plt.title("Frequency response of Hamming window")
2182      Text(0.5, 1.0, 'Frequency response of Hamming window')
2183      >>> plt.ylabel("Magnitude [dB]")
2184      Text(0, 0.5, 'Magnitude [dB]')
2185      >>> plt.xlabel("Normalized frequency [cycles per sample]")
2186      Text(0.5, 0, 'Normalized frequency [cycles per sample]')
2187      >>> plt.axis('tight')
2188      ...
2189      >>> plt.show()
2190  
2191      rmr�r�r�gH�z�G�?gq=
2192  ףp�?r�r�rbrbrcrOks\rO)g��4!�\T�g��}�b3�<g��r넱�g�^�����<g����"P
2193  �g'&&KF�5=g��bLa�g$ӛ�/��=g�j�z����g<t̾��=gV�����g4�T��&>g�0���K�g5dM�v;p>g�"�c쑾g��$��>g'd��o�ҾgY(��X?�>gZ�Y&+�g�|t�(?gR���B�g�u�Z?gI� ^�q�g����a��?g�!�N��g-��Ί>�?g�-4pK��g���w���?g��W��ӿg*�5�N��?)g��T��`�g0�f�FV�g!����<g�A`��<g�ҫ`��g8��箸�g��}��<g�攐�*�<g�be~���g2�hϙ]'�gE�_
�V=gs��k�[=g�&�GCi=gf�C��g�{~5���g%t9Q��gO��$�=guo����>g�["�d,->gm�ր�VX>gna����>g���+A�>gR��x�?gI�墌�k?g�	��b��?cCsH|d}d}tdt|��D]}|}|}|||||}q
d||S)Nrr�rmrp)r�r�)r�r��b0�b1r��b2rbrbrc�_chbevl
sr�cCst|�t|ddt�S)Nr�r�)rr��_i0A�r�rbrbrc�_i0_1
sr�cCs"t|�td|dt�t|�S)Ng@@r�)rr��_i0Brr�rbrbrc�_i0_2
s"r�cCr�r]rbr�rbrbrc�_i0_dispatcher#
r�r�cCsTt�|�}|jjdkrtd��|jjdkr|�t�}t�|�}t||dkgt	t
2194  g�S)a�
2195      Modified Bessel function of the first kind, order 0.
2196  
2197      Usually denoted :math:`I_0`.
2198  
2199      Parameters
2200      ----------
2201      x : array_like of float
2202          Argument of the Bessel function.
2203  
2204      Returns
2205      -------
2206      out : ndarray, shape = x.shape, dtype = float
2207          The modified Bessel function evaluated at each of the elements of `x`.
2208  
2209      See Also
2210      --------
2211      scipy.special.i0, scipy.special.iv, scipy.special.ive
2212  
2213      Notes
2214      -----
2215      The scipy implementation is recommended over this function: it is a
2216      proper ufunc written in C, and more than an order of magnitude faster.
2217  
2218      We use the algorithm published by Clenshaw [1]_ and referenced by
2219      Abramowitz and Stegun [2]_, for which the function domain is
2220      partitioned into the two intervals [0,8] and (8,inf), and Chebyshev
2221      polynomial expansions are employed in each interval. Relative error on
2222      the domain [0,30] using IEEE arithmetic is documented [3]_ as having a
2223      peak of 5.8e-16 with an rms of 1.4e-16 (n = 30000).
2224  
2225      References
2226      ----------
2227      .. [1] C. W. Clenshaw, "Chebyshev series for mathematical functions", in
2228             *National Physical Laboratory Mathematical Tables*, vol. 5, London:
2229             Her Majesty's Stationery Office, 1962.
2230      .. [2] M. Abramowitz and I. A. Stegun, *Handbook of Mathematical
2231             Functions*, 10th printing, New York: Dover, 1964, pp. 379.
2232             https://personal.math.ubc.ca/~cbm/aands/page_379.htm
2233      .. [3] https://metacpan.org/pod/distribution/Math-Cephes/lib/Math/Cephes.pod#i0:-Modified-Bessel-function-of-order-zero
2234  
2235      Examples
2236      --------
2237      >>> np.i0(0.)
2238      array(1.0)
2239      >>> np.i0([0, 1, 2, 3])
2240      array([1.        , 1.26606588, 2.2795853 , 4.88079259])
2241  
2242      rz#i0 not supported for complex valuesr�g @)r~r	r��kindr�r�r�r#r7r�r�r�rbrbrcrU'
s
2243  3
2244  
2245  rUcCs`|dkrtjdt�|d�d�Std|�}|dd}t|td|||d��tt|��S)a�
2246      Return the Kaiser window.
2247  
2248      The Kaiser window is a taper formed by using a Bessel function.
2249  
2250      Parameters
2251      ----------
2252      M : int
2253          Number of points in the output window. If zero or less, an
2254          empty array is returned.
2255      beta : float
2256          Shape parameter for window.
2257  
2258      Returns
2259      -------
2260      out : array
2261          The window, with the maximum value normalized to one (the value
2262          one appears only if the number of samples is odd).
2263  
2264      See Also
2265      --------
2266      bartlett, blackman, hamming, hanning
2267  
2268      Notes
2269      -----
2270      The Kaiser window is defined as
2271  
2272      .. math::  w(n) = I_0\left( \beta \sqrt{1-\frac{4n^2}{(M-1)^2}}
2273                 \right)/I_0(\beta)
2274  
2275      with
2276  
2277      .. math:: \quad -\frac{M-1}{2} \leq n \leq \frac{M-1}{2},
2278  
2279      where :math:`I_0` is the modified zeroth-order Bessel function.
2280  
2281      The Kaiser was named for Jim Kaiser, who discovered a simple
2282      approximation to the DPSS window based on Bessel functions.  The Kaiser
2283      window is a very good approximation to the Digital Prolate Spheroidal
2284      Sequence, or Slepian window, which is the transform which maximizes the
2285      energy in the main lobe of the window relative to total energy.
2286  
2287      The Kaiser can approximate many other windows by varying the beta
2288      parameter.
2289  
2290      ====  =======================
2291      beta  Window shape
2292      ====  =======================
2293      0     Rectangular
2294      5     Similar to a Hamming
2295      6     Similar to a Hanning
2296      8.6   Similar to a Blackman
2297      ====  =======================
2298  
2299      A beta value of 14 is probably a good starting point. Note that as beta
2300      gets large, the window narrows, and so the number of samples needs to be
2301      large enough to sample the increasingly narrow spike, otherwise NaNs will
2302      get returned.
2303  
2304      Most references to the Kaiser window come from the signal processing
2305      literature, where it is used as one of many windowing functions for
2306      smoothing values.  It is also known as an apodization (which means
2307      "removing the foot", i.e. smoothing discontinuities at the beginning
2308      and end of the sampled signal) or tapering function.
2309  
2310      References
2311      ----------
2312      .. [1] J. F. Kaiser, "Digital Filters" - Ch 7 in "Systems analysis by
2313             digital computer", Editors: F.F. Kuo and J.F. Kaiser, p 218-285.
2314             John Wiley and Sons, New York, (1966).
2315      .. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics", The
2316             University of Alberta Press, 1975, pp. 177-178.
2317      .. [3] Wikipedia, "Window function",
2318             https://en.wikipedia.org/wiki/Window_function
2319  
2320      Examples
2321      --------
2322      >>> import matplotlib.pyplot as plt
2323      >>> np.kaiser(12, 14)
2324       array([7.72686684e-06, 3.46009194e-03, 4.65200189e-02, # may vary
2325              2.29737120e-01, 5.99885316e-01, 9.45674898e-01,
2326              9.45674898e-01, 5.99885316e-01, 2.29737120e-01,
2327              4.65200189e-02, 3.46009194e-03, 7.72686684e-06])
2328  
2329  
2330      Plot the window and the frequency response:
2331  
2332      >>> from numpy.fft import fft, fftshift
2333      >>> window = np.kaiser(51, 14)
2334      >>> plt.plot(window)
2335      [<matplotlib.lines.Line2D object at 0x...>]
2336      >>> plt.title("Kaiser window")
2337      Text(0.5, 1.0, 'Kaiser window')
2338      >>> plt.ylabel("Amplitude")
2339      Text(0, 0.5, 'Amplitude')
2340      >>> plt.xlabel("Sample")
2341      Text(0.5, 0, 'Sample')
2342      >>> plt.show()
2343  
2344      >>> plt.figure()
2345      <Figure size 640x480 with 0 Axes>
2346      >>> A = fft(window, 2048) / 25.5
2347      >>> mag = np.abs(fftshift(A))
2348      >>> freq = np.linspace(-0.5, 0.5, len(A))
2349      >>> response = 20 * np.log10(mag)
2350      >>> response = np.clip(response, -100, 100)
2351      >>> plt.plot(freq, response)
2352      [<matplotlib.lines.Line2D object at 0x...>]
2353      >>> plt.title("Frequency response of Kaiser window")
2354      Text(0.5, 1.0, 'Frequency response of Kaiser window')
2355      >>> plt.ylabel("Magnitude [dB]")
2356      Text(0, 0.5, 'Magnitude [dB]')
2357      >>> plt.xlabel("Normalized frequency [cycles per sample]")
2358      Text(0.5, 0, 'Normalized frequency [cycles per sample]')
2359      >>> plt.axis('tight')
2360      (-0.5, 0.5, -100.0, ...) # may vary
2361      >>> plt.show()
2362  
2363      rmr�r�rr�)r~rr�rrUrr�)r��betar`�alpharbrbrcrSe
s
2364  y
2365  ,rScCr�r]rbr�rbrbrc�_sinc_dispatcher�
r�r�cCs*t�|�}tt|dkd|�}t|�|S)a�
2366  
2367      Return the normalized sinc function.
2368  
2369      The sinc function is equal to :math:`\sin(\pi x)/(\pi x)` for any argument
2370      :math:`x\ne 0`. ``sinc(0)`` takes the limit value 1, making ``sinc`` not
2371      only everywhere continuous but also infinitely differentiable.
2372  
2373      .. note::
2374  
2375          Note the normalization factor of ``pi`` used in the definition.
2376          This is the most commonly used definition in signal processing.
2377          Use ``sinc(x / np.pi)`` to obtain the unnormalized sinc function
2378          :math:`\sin(x)/x` that is more common in mathematics.
2379  
2380      Parameters
2381      ----------
2382      x : ndarray
2383          Array (possibly multi-dimensional) of values for which to calculate
2384          ``sinc(x)``.
2385  
2386      Returns
2387      -------
2388      out : ndarray
2389          ``sinc(x)``, which has the same shape as the input.
2390  
2391      Notes
2392      -----
2393      The name sinc is short for "sine cardinal" or "sinus cardinalis".
2394  
2395      The sinc function is used in various signal processing applications,
2396      including in anti-aliasing, in the construction of a Lanczos resampling
2397      filter, and in interpolation.
2398  
2399      For bandlimited interpolation of discrete-time signals, the ideal
2400      interpolation kernel is proportional to the sinc function.
2401  
2402      References
2403      ----------
2404      .. [1] Weisstein, Eric W. "Sinc Function." From MathWorld--A Wolfram Web
2405             Resource. http://mathworld.wolfram.com/SincFunction.html
2406      .. [2] Wikipedia, "Sinc function",
2407             https://en.wikipedia.org/wiki/Sinc_function
2408  
2409      Examples
2410      --------
2411      >>> import matplotlib.pyplot as plt
2412      >>> x = np.linspace(-4, 4, 41)
2413      >>> np.sinc(x)
2414       array([-3.89804309e-17,  -4.92362781e-02,  -8.40918587e-02, # may vary
2415              -8.90384387e-02,  -5.84680802e-02,   3.89804309e-17,
2416              6.68206631e-02,   1.16434881e-01,   1.26137788e-01,
2417              8.50444803e-02,  -3.89804309e-17,  -1.03943254e-01,
2418              -1.89206682e-01,  -2.16236208e-01,  -1.55914881e-01,
2419              3.89804309e-17,   2.33872321e-01,   5.04551152e-01,
2420              7.56826729e-01,   9.35489284e-01,   1.00000000e+00,
2421              9.35489284e-01,   7.56826729e-01,   5.04551152e-01,
2422              2.33872321e-01,   3.89804309e-17,  -1.55914881e-01,
2423             -2.16236208e-01,  -1.89206682e-01,  -1.03943254e-01,
2424             -3.89804309e-17,   8.50444803e-02,   1.26137788e-01,
2425              1.16434881e-01,   6.68206631e-02,   3.89804309e-17,
2426              -5.84680802e-02,  -8.90384387e-02,  -8.40918587e-02,
2427              -4.92362781e-02,  -3.89804309e-17])
2428  
2429      >>> plt.plot(x, np.sinc(x))
2430      [<matplotlib.lines.Line2D object at 0x...>]
2431      >>> plt.title("Sinc Function")
2432      Text(0.5, 1.0, 'Sinc Function')
2433      >>> plt.ylabel("Amplitude")
2434      Text(0, 0.5, 'Amplitude')
2435      >>> plt.xlabel("X")
2436      Text(0.5, 0, 'X')
2437      >>> plt.show()
2438  
2439      rg#B����;)r~r	rrr)r�r�rbrbrcrN�
s
2440  LrNcCr�r]rbr5rbrbrc�_msort_dispatcher:r�r�cCs,tjdtdd�t|ddd�}|�d�|S)a`
2441      Return a copy of an array sorted along the first axis.
2442  
2443      .. deprecated:: 1.24
2444  
2445         msort is deprecated, use ``np.sort(a, axis=0)`` instead.
2446  
2447      Parameters
2448      ----------
2449      a : array_like
2450          Array to be sorted.
2451  
2452      Returns
2453      -------
2454      sorted_array : ndarray
2455          Array of the same type and shape as `a`.
2456  
2457      See Also
2458      --------
2459      sort
2460  
2461      Notes
2462      -----
2463      ``np.msort(a)`` is equivalent to  ``np.sort(a, axis=0)``.
2464  
2465      Examples
2466      --------
2467      >>> a = np.array([[1, 4], [3, 1]])
2468      >>> np.msort(a)  # sort along the first axis
2469      array([[1, 1],
2470             [3, 4]])
2471  
2472      z3msort is deprecated, use np.sort(a, axis=0) insteadr�r�T)r�r9r)r�r�r�rr<r=rbrbrcrL>s$�
2473  rLc
s�t�|�}|�dd��|�dd�}|tjurd}|j}�dur~t��|��|rA|durAt�fdd�t|�D��}|t	f||d<t
2474  ��dkrN�d|d<nCtt|��t��}t
2475  |�}tt
|��D]
2476  \}	}
2477  |�|	|
2478  �}qb|�|jd|�d	�}d
2479  |d<n|r�|dur�d|}|t	f||d<||fi|��}|dur�|S|r��dur�tjf|}n
t�fdd�t|�D��}|t	f|}|S)
a-
2480      Internal Function.
2481      Call `func` with `a` as first argument swapping the axes to use extended
2482      axis on functions that don't support it natively.
2483  
2484      Returns result and a.shape with axis dims set to 1.
2485  
2486      Parameters
2487      ----------
2488      a : array_like
2489          Input array or object that can be converted to an array.
2490      func : callable
2491          Reduction function capable of receiving a single axis argument.
2492          It is called with `a` as first argument followed by `kwargs`.
2493      kwargs : keyword arguments
2494          additional keyword arguments to pass to `func`.
2495  
2496      Returns
2497      -------
2498      result : tuple
2499          Result of func(a, **kwargs) and a.shape with axis dims set to 1
2500          which can be used to reshape the result to the same shape a ufunc with
2501          keepdims=True would produce.
2502  
2503      r�NrFc3s$�|]
}|�vr
2504  dntd�VqdSr�)r�r�r�r�rbrcr`�s�
2505  �z_ureduce.<locals>.<genexpr>rmr�r�r�r�c3s&�|]}|�vrtjntd�VqdSr])r~�newaxisrr�r�rbrcr`�s
2506  ��
2507  �)r~r	�getr�r�r�r�r�r��Ellipsisr�r�r��sortedr�r�rrr�)
r�r�r�r�rrZ	index_out�keepZnkeepr��s�rZindex_rrbr�rc�_ureducelsJ
2508  
2509  �
2510  �r�cCr�r]rb�r�r�r�overwrite_inputr�rbrbrc�_median_dispatcher�r�r�cCst|t||||d�S)a
2511      Compute the median along the specified axis.
2512  
2513      Returns the median of the array elements.
2514  
2515      Parameters
2516      ----------
2517      a : array_like
2518          Input array or object that can be converted to an array.
2519      axis : {int, sequence of int, None}, optional
2520          Axis or axes along which the medians are computed. The default
2521          is to compute the median along a flattened version of the array.
2522          A sequence of axes is supported since version 1.9.0.
2523      out : ndarray, optional
2524          Alternative output array in which to place the result. It must
2525          have the same shape and buffer length as the expected output,
2526          but the type (of the output) will be cast if necessary.
2527      overwrite_input : bool, optional
2528         If True, then allow use of memory of input array `a` for
2529         calculations. The input array will be modified by the call to
2530         `median`. This will save memory when you do not need to preserve
2531         the contents of the input array. Treat the input as undefined,
2532         but it will probably be fully or partially sorted. Default is
2533         False. If `overwrite_input` is ``True`` and `a` is not already an
2534         `ndarray`, an error will be raised.
2535      keepdims : bool, optional
2536          If this is set to True, the axes which are reduced are left
2537          in the result as dimensions with size one. With this option,
2538          the result will broadcast correctly against the original `arr`.
2539  
2540          .. versionadded:: 1.9.0
2541  
2542      Returns
2543      -------
2544      median : ndarray
2545          A new array holding the result. If the input contains integers
2546          or floats smaller than ``float64``, then the output data-type is
2547          ``np.float64``.  Otherwise, the data-type of the output is the
2548          same as that of the input. If `out` is specified, that array is
2549          returned instead.
2550  
2551      See Also
2552      --------
2553      mean, percentile
2554  
2555      Notes
2556      -----
2557      Given a vector ``V`` of length ``N``, the median of ``V`` is the
2558      middle value of a sorted copy of ``V``, ``V_sorted`` - i
2559      e., ``V_sorted[(N-1)/2]``, when ``N`` is odd, and the average of the
2560      two middle values of ``V_sorted`` when ``N`` is even.
2561  
2562      Examples
2563      --------
2564      >>> a = np.array([[10, 7, 4], [3, 2, 1]])
2565      >>> a
2566      array([[10,  7,  4],
2567             [ 3,  2,  1]])
2568      >>> np.median(a)
2569      3.5
2570      >>> np.median(a, axis=0)
2571      array([6.5, 4.5, 2.5])
2572      >>> np.median(a, axis=1)
2573      array([7.,  2.])
2574      >>> m = np.median(a, axis=0)
2575      >>> out = np.zeros_like(m)
2576      >>> np.median(a, axis=0, out=m)
2577      array([6.5,  4.5,  2.5])
2578      >>> m
2579      array([6.5,  4.5,  2.5])
2580      >>> b = a.copy()
2581      >>> np.median(b, axis=1, overwrite_input=True)
2582      array([7.,  2.])
2583      >>> assert not np.all(a==b)
2584      >>> b = a.copy()
2585      >>> np.median(b, axis=None, overwrite_input=True)
2586      3.5
2587      >>> assert not np.all(a==b)
2588  
2589      )r�r�r�rr�)r��_medianr�rbrbrcrM�sR�rMcCspt�|�}|dur
|j}n|j|}|ddkr#|d}|d|g}n|ddg}t�|jtj�r7|�d�|rQ|durG|��}|�	|�n|j	||d�|}nt	|||d�}|jdkra|�
2590  �S|durgd}td�g|j}|j|d}	|j|ddkr�t|	|	d�||<nt|	d|	d�||<t
|�}t||||d�}
2591  t�|jtj�r�|dkr�tjj�||
2592  |�}
2593  |
2594  S)Nr�rrmr�r�rb�r�r)r~r	r�rrr�r�rrYrr!�itemrr�r�r"rk�utils�_median_nancheck)r�r�rr��szZszh�kth�partr�r��routrbrbrcr�s>
2595  
2596  
2597  
2598  r�)�
interpolationcC�
2599  |||fSr]rb�r��qr�rr��methodr�rrbrbrc�_percentile_dispatcherK�
2600  rr�cCsL|dur
2601  t||d�}t�|d�}t|�}t|�std��t|||||||�S)a�"
2602      Compute the q-th percentile of the data along the specified axis.
2603  
2604      Returns the q-th percentile(s) of the array elements.
2605  
2606      Parameters
2607      ----------
2608      a : array_like
2609          Input array or object that can be converted to an array.
2610      q : array_like of float
2611          Percentile or sequence of percentiles to compute, which must be between
2612          0 and 100 inclusive.
2613      axis : {int, tuple of int, None}, optional
2614          Axis or axes along which the percentiles are computed. The
2615          default is to compute the percentile(s) along a flattened
2616          version of the array.
2617  
2618          .. versionchanged:: 1.9.0
2619              A tuple of axes is supported
2620      out : ndarray, optional
2621          Alternative output array in which to place the result. It must
2622          have the same shape and buffer length as the expected output,
2623          but the type (of the output) will be cast if necessary.
2624      overwrite_input : bool, optional
2625          If True, then allow the input array `a` to be modified by intermediate
2626          calculations, to save memory. In this case, the contents of the input
2627          `a` after this function completes is undefined.
2628      method : str, optional
2629          This parameter specifies the method to use for estimating the
2630          percentile.  There are many different methods, some unique to NumPy.
2631          See the notes for explanation.  The options sorted by their R type
2632          as summarized in the H&F paper [1]_ are:
2633  
2634          1. 'inverted_cdf'
2635          2. 'averaged_inverted_cdf'
2636          3. 'closest_observation'
2637          4. 'interpolated_inverted_cdf'
2638          5. 'hazen'
2639          6. 'weibull'
2640          7. 'linear'  (default)
2641          8. 'median_unbiased'
2642          9. 'normal_unbiased'
2643  
2644          The first three methods are discontinuous.  NumPy further defines the
2645          following discontinuous variations of the default 'linear' (7.) option:
2646  
2647          * 'lower'
2648          * 'higher',
2649          * 'midpoint'
2650          * 'nearest'
2651  
2652          .. versionchanged:: 1.22.0
2653              This argument was previously called "interpolation" and only
2654              offered the "linear" default and last four options.
2655  
2656      keepdims : bool, optional
2657          If this is set to True, the axes which are reduced are left in
2658          the result as dimensions with size one. With this option, the
2659          result will broadcast correctly against the original array `a`.
2660  
2661          .. versionadded:: 1.9.0
2662  
2663      interpolation : str, optional
2664          Deprecated name for the method keyword argument.
2665  
2666          .. deprecated:: 1.22.0
2667  
2668      Returns
2669      -------
2670      percentile : scalar or ndarray
2671          If `q` is a single percentile and `axis=None`, then the result
2672          is a scalar. If multiple percentiles are given, first axis of
2673          the result corresponds to the percentiles. The other axes are
2674          the axes that remain after the reduction of `a`. If the input
2675          contains integers or floats smaller than ``float64``, the output
2676          data-type is ``float64``. Otherwise, the output data-type is the
2677          same as that of the input. If `out` is specified, that array is
2678          returned instead.
2679  
2680      See Also
2681      --------
2682      mean
2683      median : equivalent to ``percentile(..., 50)``
2684      nanpercentile
2685      quantile : equivalent to percentile, except q in the range [0, 1].
2686  
2687      Notes
2688      -----
2689      Given a vector ``V`` of length ``n``, the q-th percentile of ``V`` is
2690      the value ``q/100`` of the way from the minimum to the maximum in a
2691      sorted copy of ``V``. The values and distances of the two nearest
2692      neighbors as well as the `method` parameter will determine the
2693      percentile if the normalized ranking does not match the location of
2694      ``q`` exactly. This function is the same as the median if ``q=50``, the
2695      same as the minimum if ``q=0`` and the same as the maximum if
2696      ``q=100``.
2697  
2698      The optional `method` parameter specifies the method to use when the
2699      desired percentile lies between two indexes ``i`` and ``j = i + 1``.
2700      In that case, we first determine ``i + g``, a virtual index that lies
2701      between ``i`` and ``j``, where  ``i`` is the floor and ``g`` is the
2702      fractional part of the index. The final result is, then, an interpolation
2703      of ``a[i]`` and ``a[j]`` based on ``g``. During the computation of ``g``,
2704      ``i`` and ``j`` are modified using correction constants ``alpha`` and
2705      ``beta`` whose choices depend on the ``method`` used. Finally, note that
2706      since Python uses 0-based indexing, the code subtracts another 1 from the
2707      index internally.
2708  
2709      The following formula determines the virtual index ``i + g``, the location 
2710      of the percentile in the sorted sample:
2711  
2712      .. math::
2713          i + g = (q / 100) * ( n - alpha - beta + 1 ) + alpha
2714  
2715      The different methods then work as follows
2716  
2717      inverted_cdf:
2718          method 1 of H&F [1]_.
2719          This method gives discontinuous results:
2720  
2721          * if g > 0 ; then take j
2722          * if g = 0 ; then take i
2723  
2724      averaged_inverted_cdf:
2725          method 2 of H&F [1]_.
2726          This method give discontinuous results:
2727  
2728          * if g > 0 ; then take j
2729          * if g = 0 ; then average between bounds
2730  
2731      closest_observation:
2732          method 3 of H&F [1]_.
2733          This method give discontinuous results:
2734  
2735          * if g > 0 ; then take j
2736          * if g = 0 and index is odd ; then take j
2737          * if g = 0 and index is even ; then take i
2738  
2739      interpolated_inverted_cdf:
2740          method 4 of H&F [1]_.
2741          This method give continuous results using:
2742  
2743          * alpha = 0
2744          * beta = 1
2745  
2746      hazen:
2747          method 5 of H&F [1]_.
2748          This method give continuous results using:
2749  
2750          * alpha = 1/2
2751          * beta = 1/2
2752  
2753      weibull:
2754          method 6 of H&F [1]_.
2755          This method give continuous results using:
2756  
2757          * alpha = 0
2758          * beta = 0
2759  
2760      linear:
2761          method 7 of H&F [1]_.
2762          This method give continuous results using:
2763  
2764          * alpha = 1
2765          * beta = 1
2766  
2767      median_unbiased:
2768          method 8 of H&F [1]_.
2769          This method is probably the best method if the sample
2770          distribution function is unknown (see reference).
2771          This method give continuous results using:
2772  
2773          * alpha = 1/3
2774          * beta = 1/3
2775  
2776      normal_unbiased:
2777          method 9 of H&F [1]_.
2778          This method is probably the best method if the sample
2779          distribution function is known to be normal.
2780          This method give continuous results using:
2781  
2782          * alpha = 3/8
2783          * beta = 3/8
2784  
2785      lower:
2786          NumPy method kept for backwards compatibility.
2787          Takes ``i`` as the interpolation point.
2788  
2789      higher:
2790          NumPy method kept for backwards compatibility.
2791          Takes ``j`` as the interpolation point.
2792  
2793      nearest:
2794          NumPy method kept for backwards compatibility.
2795          Takes ``i`` or ``j``, whichever is nearest.
2796  
2797      midpoint:
2798          NumPy method kept for backwards compatibility.
2799          Uses ``(i + j) / 2``.
2800  
2801      Examples
2802      --------
2803      >>> a = np.array([[10, 7, 4], [3, 2, 1]])
2804      >>> a
2805      array([[10,  7,  4],
2806             [ 3,  2,  1]])
2807      >>> np.percentile(a, 50)
2808      3.5
2809      >>> np.percentile(a, 50, axis=0)
2810      array([6.5, 4.5, 2.5])
2811      >>> np.percentile(a, 50, axis=1)
2812      array([7.,  2.])
2813      >>> np.percentile(a, 50, axis=1, keepdims=True)
2814      array([[7.],
2815             [2.]])
2816  
2817      >>> m = np.percentile(a, 50, axis=0)
2818      >>> out = np.zeros_like(m)
2819      >>> np.percentile(a, 50, axis=0, out=out)
2820      array([6.5, 4.5, 2.5])
2821      >>> m
2822      array([6.5, 4.5, 2.5])
2823  
2824      >>> b = a.copy()
2825      >>> np.percentile(b, 50, axis=1, overwrite_input=True)
2826      array([7.,  2.])
2827      >>> assert not np.all(a == b)
2828  
2829      The different methods can be visualized graphically:
2830  
2831      .. plot::
2832  
2833          import matplotlib.pyplot as plt
2834  
2835          a = np.arange(4)
2836          p = np.linspace(0, 100, 6001)
2837          ax = plt.gca()
2838          lines = [
2839              ('linear', '-', 'C0'),
2840              ('inverted_cdf', ':', 'C1'),
2841              # Almost the same as `inverted_cdf`:
2842              ('averaged_inverted_cdf', '-.', 'C1'),
2843              ('closest_observation', ':', 'C2'),
2844              ('interpolated_inverted_cdf', '--', 'C1'),
2845              ('hazen', '--', 'C3'),
2846              ('weibull', '-.', 'C4'),
2847              ('median_unbiased', '--', 'C5'),
2848              ('normal_unbiased', '-.', 'C6'),
2849              ]
2850          for method, style, color in lines:
2851              ax.plot(
2852                  p, np.percentile(a, p, method=method),
2853                  label=method, linestyle=style, color=color)
2854          ax.set(
2855              title='Percentiles for different methods and data: ' + str(a),
2856              xlabel='Percentile',
2857              ylabel='Estimated percentile value',
2858              yticks=a)
2859          ax.legend()
2860          plt.show()
2861  
2862      References
2863      ----------
2864      .. [1] R. J. Hyndman and Y. Fan,
2865         "Sample quantiles in statistical packages,"
2866         The American Statistician, 50(4), pp. 361-365, 1996
2867  
2868      Nr;�dz)Percentiles must be in the range [0, 100])�_check_interpolation_as_methodr~r�r	�_quantile_is_validr��_quantile_uncheckedrrbrbrcr;Ps��r;cCrr]rbrrbrbrc�_quantile_dispatcherqrr
cCsB|dur
2869  t||d�}t�|�}t|�std��t|||||||�S)a�
2870      Compute the q-th quantile of the data along the specified axis.
2871  
2872      .. versionadded:: 1.15.0
2873  
2874      Parameters
2875      ----------
2876      a : array_like
2877          Input array or object that can be converted to an array.
2878      q : array_like of float
2879          Quantile or sequence of quantiles to compute, which must be between
2880          0 and 1 inclusive.
2881      axis : {int, tuple of int, None}, optional
2882          Axis or axes along which the quantiles are computed. The default is
2883          to compute the quantile(s) along a flattened version of the array.
2884      out : ndarray, optional
2885          Alternative output array in which to place the result. It must have
2886          the same shape and buffer length as the expected output, but the
2887          type (of the output) will be cast if necessary.
2888      overwrite_input : bool, optional
2889          If True, then allow the input array `a` to be modified by
2890          intermediate calculations, to save memory. In this case, the
2891          contents of the input `a` after this function completes is
2892          undefined.
2893      method : str, optional
2894          This parameter specifies the method to use for estimating the
2895          quantile.  There are many different methods, some unique to NumPy.
2896          See the notes for explanation.  The options sorted by their R type
2897          as summarized in the H&F paper [1]_ are:
2898  
2899          1. 'inverted_cdf'
2900          2. 'averaged_inverted_cdf'
2901          3. 'closest_observation'
2902          4. 'interpolated_inverted_cdf'
2903          5. 'hazen'
2904          6. 'weibull'
2905          7. 'linear'  (default)
2906          8. 'median_unbiased'
2907          9. 'normal_unbiased'
2908  
2909          The first three methods are discontinuous.  NumPy further defines the
2910          following discontinuous variations of the default 'linear' (7.) option:
2911  
2912          * 'lower'
2913          * 'higher',
2914          * 'midpoint'
2915          * 'nearest'
2916  
2917          .. versionchanged:: 1.22.0
2918              This argument was previously called "interpolation" and only
2919              offered the "linear" default and last four options.
2920  
2921      keepdims : bool, optional
2922          If this is set to True, the axes which are reduced are left in
2923          the result as dimensions with size one. With this option, the
2924          result will broadcast correctly against the original array `a`.
2925  
2926      interpolation : str, optional
2927          Deprecated name for the method keyword argument.
2928  
2929          .. deprecated:: 1.22.0
2930  
2931      Returns
2932      -------
2933      quantile : scalar or ndarray
2934          If `q` is a single quantile and `axis=None`, then the result
2935          is a scalar. If multiple quantiles are given, first axis of
2936          the result corresponds to the quantiles. The other axes are
2937          the axes that remain after the reduction of `a`. If the input
2938          contains integers or floats smaller than ``float64``, the output
2939          data-type is ``float64``. Otherwise, the output data-type is the
2940          same as that of the input. If `out` is specified, that array is
2941          returned instead.
2942  
2943      See Also
2944      --------
2945      mean
2946      percentile : equivalent to quantile, but with q in the range [0, 100].
2947      median : equivalent to ``quantile(..., 0.5)``
2948      nanquantile
2949  
2950      Notes
2951      -----
2952      Given a vector ``V`` of length ``n``, the q-th quantile of ``V`` is
2953      the value ``q`` of the way from the minimum to the maximum in a
2954      sorted copy of ``V``. The values and distances of the two nearest
2955      neighbors as well as the `method` parameter will determine the
2956      quantile if the normalized ranking does not match the location of
2957      ``q`` exactly. This function is the same as the median if ``q=0.5``, the
2958      same as the minimum if ``q=0.0`` and the same as the maximum if
2959      ``q=1.0``.
2960  
2961      The optional `method` parameter specifies the method to use when the
2962      desired quantile lies between two indexes ``i`` and ``j = i + 1``.
2963      In that case, we first determine ``i + g``, a virtual index that lies
2964      between ``i`` and ``j``, where  ``i`` is the floor and ``g`` is the
2965      fractional part of the index. The final result is, then, an interpolation
2966      of ``a[i]`` and ``a[j]`` based on ``g``. During the computation of ``g``,
2967      ``i`` and ``j`` are modified using correction constants ``alpha`` and
2968      ``beta`` whose choices depend on the ``method`` used. Finally, note that
2969      since Python uses 0-based indexing, the code subtracts another 1 from the
2970      index internally.
2971  
2972      The following formula determines the virtual index ``i + g``, the location 
2973      of the quantile in the sorted sample:
2974  
2975      .. math::
2976          i + g = q * ( n - alpha - beta + 1 ) + alpha
2977  
2978      The different methods then work as follows
2979  
2980      inverted_cdf:
2981          method 1 of H&F [1]_.
2982          This method gives discontinuous results:
2983  
2984          * if g > 0 ; then take j
2985          * if g = 0 ; then take i
2986  
2987      averaged_inverted_cdf:
2988          method 2 of H&F [1]_.
2989          This method gives discontinuous results:
2990  
2991          * if g > 0 ; then take j
2992          * if g = 0 ; then average between bounds
2993  
2994      closest_observation:
2995          method 3 of H&F [1]_.
2996          This method gives discontinuous results:
2997  
2998          * if g > 0 ; then take j
2999          * if g = 0 and index is odd ; then take j
3000          * if g = 0 and index is even ; then take i
3001  
3002      interpolated_inverted_cdf:
3003          method 4 of H&F [1]_.
3004          This method gives continuous results using:
3005  
3006          * alpha = 0
3007          * beta = 1
3008  
3009      hazen:
3010          method 5 of H&F [1]_.
3011          This method gives continuous results using:
3012  
3013          * alpha = 1/2
3014          * beta = 1/2
3015  
3016      weibull:
3017          method 6 of H&F [1]_.
3018          This method gives continuous results using:
3019  
3020          * alpha = 0
3021          * beta = 0
3022  
3023      linear:
3024          method 7 of H&F [1]_.
3025          This method gives continuous results using:
3026  
3027          * alpha = 1
3028          * beta = 1
3029  
3030      median_unbiased:
3031          method 8 of H&F [1]_.
3032          This method is probably the best method if the sample
3033          distribution function is unknown (see reference).
3034          This method gives continuous results using:
3035  
3036          * alpha = 1/3
3037          * beta = 1/3
3038  
3039      normal_unbiased:
3040          method 9 of H&F [1]_.
3041          This method is probably the best method if the sample
3042          distribution function is known to be normal.
3043          This method gives continuous results using:
3044  
3045          * alpha = 3/8
3046          * beta = 3/8
3047  
3048      lower:
3049          NumPy method kept for backwards compatibility.
3050          Takes ``i`` as the interpolation point.
3051  
3052      higher:
3053          NumPy method kept for backwards compatibility.
3054          Takes ``j`` as the interpolation point.
3055  
3056      nearest:
3057          NumPy method kept for backwards compatibility.
3058          Takes ``i`` or ``j``, whichever is nearest.
3059  
3060      midpoint:
3061          NumPy method kept for backwards compatibility.
3062          Uses ``(i + j) / 2``.
3063  
3064      Examples
3065      --------
3066      >>> a = np.array([[10, 7, 4], [3, 2, 1]])
3067      >>> a
3068      array([[10,  7,  4],
3069             [ 3,  2,  1]])
3070      >>> np.quantile(a, 0.5)
3071      3.5
3072      >>> np.quantile(a, 0.5, axis=0)
3073      array([6.5, 4.5, 2.5])
3074      >>> np.quantile(a, 0.5, axis=1)
3075      array([7.,  2.])
3076      >>> np.quantile(a, 0.5, axis=1, keepdims=True)
3077      array([[7.],
3078             [2.]])
3079      >>> m = np.quantile(a, 0.5, axis=0)
3080      >>> out = np.zeros_like(m)
3081      >>> np.quantile(a, 0.5, axis=0, out=out)
3082      array([6.5, 4.5, 2.5])
3083      >>> m
3084      array([6.5, 4.5, 2.5])
3085      >>> b = a.copy()
3086      >>> np.quantile(b, 0.5, axis=1, overwrite_input=True)
3087      array([7.,  2.])
3088      >>> assert not np.all(a == b)
3089  
3090      See also `numpy.percentile` for a visualization of most methods.
3091  
3092      References
3093      ----------
3094      .. [1] R. J. Hyndman and Y. Fan,
3095         "Sample quantiles in statistical packages,"
3096         The American Statistician, 50(4), pp. 361-365, 1996
3097  
3098      Nr[z%Quantiles must be in the range [0, 1])r
3099  r~r	rr�rrrbrbrcr[vsq�
3100  �r[c
3101  Cst|t||||||d�S)z.Assumes that q is in [0, 1], and is an ndarray)r�rr�r�rr�r)r��_quantile_ureduce_func)r�rr�rr�rr�rbrbrcrqs�rcCsp|jdkr&|jdkr&t|j�D]}d||krdks#dSdSqdSt�d|k�r4t�|dk�s6dSdS)Nrm�
3102  r�roFrT)r�r�r�r~r�)rr�rbrbrcr�s���rcCs,tjd|�d�tdd�|dkrtd��|S)Nz!the `interpolation=` argument to z� was renamed to `method=`, which has additional options.
3103  Users of the modes 'nearest', 'lower', 'higher', or 'midpoint' are encouraged to review the method they used. (Deprecated NumPy 1.22)r�r�r�zjYou shall not pass both `method` and `interpolation`!
3104  (`interpolation` is Deprecated in favor of `method`))r�r�r�r�)rr�fnamerbrbrcr
3105  �s
3106  ��r
3107  r�r�cCs ||||d||dS)a0
3108      Compute the floating point indexes of an array for the linear
3109      interpolation of quantiles.
3110      n : array_like
3111          The sample sizes.
3112      quantiles : array_like
3113          The quantiles values.
3114      alpha : float
3115          A constant used to correct the index computed.
3116      beta : float
3117          A constant used to correct the index computed.
3118  
3119      alpha and beta values depend on the chosen method
3120      (see quantile documentation)
3121  
3122      Reference:
3123      Hyndman&Fan paper "Sample Quantiles in Statistical Packages",
3124      DOI: 10.1080/00031305.1996.10473566
3125      rmrb)r`rar�r�rbrbrcry�s
3126  ��rycCs&t�||�}|d||�}t�|�S)a
3127      Compute gamma (a.k.a 'm' or 'weight') for the linear interpolation
3128      of quantiles.
3129  
3130      virtual_indexes : array_like
3131          The indexes where the percentile is supposed to be found in the sorted
3132          sample.
3133      previous_indexes : array_like
3134          The floor values of virtual_indexes.
3135      interpolation : dict
3136          The interpolation method chosen, which may have a specific rule
3137          modifying gamma.
3138  
3139      gamma is usually the fractional part of virtual_indexes but can be modified
3140      by the interpolation method.
3141      rk)r~r	)�virtual_indexes�previous_indexesrrgrbrbrc�
3142  _get_gamma�s
3143  rcCsZt||�}tt||||d��}t||d|||dkd�|jdkr+|dur+|d}|S)a
3144      Compute the linear interpolation weighted by gamma on each point of
3145      two same shape array.
3146  
3147      a : array_like
3148          Left bound.
3149      b : array_like
3150          Right bound.
3151      t : array_like
3152          The interpolation weight.
3153      out : array_like
3154          Output array.
3155      r�rmrp)rrrNrb)rr	rr�)r�rr�rZdiff_b_aZlerp_interpolationrbrbrc�_lerp�s
3156  rcCs"t�||�}tj|||dd�|S)N�unsafe)r�casting)r~r�r�)rrrsrtrrrbrbrcrv�srvcCsJt�|�}|d}||}t|j|||||�d��tj�}d||dk<|S)Nrmrqr)r~rrvrrr�r)r�Zgamma_condition_fun�previous�nextrgr�rbrbrc�$_discret_interpolation_to_boundaries�s
3157  ��rcCsdd�}t||dd|�S)NcSs|dkt�|�ddk@S)Nrr�)r~rr�rbrbrcrd�sz&_closest_observation.<locals>.<lambda>rmrp�r�r`raZ	gamma_funrbrbrcrw�s�rwcCsdd�}t||d|�S)NcSs|dkSr|rbrfrbrbrcrdsz_inverted_cdf.<locals>.<lambda>rmrrrbrbrcr^s�r^r�rr�r��returncCsf|jdkr	td��|r|durd}|��}n|}n|dur$d}|��}n|��}t|||||d�}|S)Nr�zq must be a scalar or 1dr)rar�rr)r�r�r�flattenr9�	_quantile)r�rr�rr�rrIr�rbrbrcrs$
3158  
3159  
3160  �rcCs�t�t�|��}t�|d�}||dk}|��r!d||<d||<|dk}|��r1d||<d||<t�|jtj�rJt�|�}|��rJd||<d||<|�tj	�}|�tj	�}||fS)a
3161      Get the valid indexes of arr neighbouring virtual_indexes.
3162      Note
3163      This is a companion function to linear interpolation of
3164      Quantiles
3165  
3166      Returns
3167      -------
3168      (previous_indexes, next_indexes): Tuple
3169          A Tuple of virtual_indexes neighbouring indexes
3170      rmr�r)
3171  r~r	rr#r�r�r�isnanr�r)rIrZvalid_values_countr�next_indexesZindexes_above_boundsZindexes_below_boundsZvirtual_indexes_nansrbrbrc�_get_indexes's$
3172  r!rIrac	Cs�t�|�}|j|}d}||krtj|||d�}zt|}Wnty1t|�dt�����d�w|d||�}t�|�}t�|j	tj
3173  �r}t�|j	tj�rd|jt
|��dgf�dd�t�|d�}n|j|��dd�tjdtd	�}t||d|d
3174  �}	n`t|||�\}
3175  }|jt�t�
ddg|
3176  ��|��f��|d�t�|j	tj�r�t�t|d|d��}nd}tj||
3177  |d�}tj|||d�}
t||
3178  |�}|jd|jd
}|�|�}t||
||d�}	t�|�r�|	jdkr�|dur�|j	�tj�}	|	Stj|	d|f<|	S)a
3179  
3180      Private function that doesn't support extended axis or keepdims.
3181      These methods are extended to this function using _ureduce
3182      See nanpercentile for parameter usage
3183      It computes the quantiles of the array for the given axis.
3184      A linear interpolation is performed based on the `interpolation`.
3185  
3186      By default, the method is "linear" where alpha == beta == 1 which
3187      performs the 7th method of Hyndman&Fan.
3188      With "median_unbiased" we get alpha == beta == 1/3
3189      thus the 8th method of Hyndman&Fan.
3190      r)�destinationz$ is not a valid method. Use one of: Nrjr�r�Fr�r�)�indicesr�r�rmr�.)r~r	rr�moveaxis�_QuantileMethods�KeyErrorr��keysr�r�rrr!rrrrr�rr!�uniquerr�r�rr#r��nan)rIrar�rrZvalues_countZ	DATA_AXISrZslices_having_nansr�rr rrrgr�rbrbrcrJsr
3191  
3192  ����
3193  ����
3194  �
3195  �rcCrFr]rb)r�r�r
3196  r�rbrbrc�_trapz_dispatcher�rKr*roc
3197  
3198  Cst|�}|dur|}n&t|�}|jdkr+t|�}dg|j}|jd||<|�|�}nt||d�}|j}td�g|}td�g|}tdd�||<tdd�||<z||t|�|t|�d�|�}	W|	Sty�t	�
3199  |�}t	�
3200  |�}t�||t|�|t|�d|�}	Y|	Sw)a+
3201  
3202      Integrate along the given axis using the composite trapezoidal rule.
3203  
3204      If `x` is provided, the integration happens in sequence along its
3205      elements - they are not sorted.
3206  
3207      Integrate `y` (`x`) along each 1d slice on the given axis, compute
3208      :math:`\int y(x) dx`.
3209      When `x` is specified, this integrates along the parametric curve,
3210      computing :math:`\int_t y(t) dt =
3211      \int_t y(t) \left.\frac{dx}{dt}\right|_{x=x(t)} dt`.
3212  
3213      Parameters
3214      ----------
3215      y : array_like
3216          Input array to integrate.
3217      x : array_like, optional
3218          The sample points corresponding to the `y` values. If `x` is None,
3219          the sample points are assumed to be evenly spaced `dx` apart. The
3220          default is None.
3221      dx : scalar, optional
3222          The spacing between sample points when `x` is None. The default is 1.
3223      axis : int, optional
3224          The axis along which to integrate.
3225  
3226      Returns
3227      -------
3228      trapz : float or ndarray
3229          Definite integral of `y` = n-dimensional array as approximated along
3230          a single axis by the trapezoidal rule. If `y` is a 1-dimensional array,
3231          then the result is a float. If `n` is greater than 1, then the result
3232          is an `n`-1 dimensional array.
3233  
3234      See Also
3235      --------
3236      sum, cumsum
3237  
3238      Notes
3239      -----
3240      Image [2]_ illustrates trapezoidal rule -- y-axis locations of points
3241      will be taken from `y` array, by default x-axis distances between
3242      points will be 1.0, alternatively they can be provided with `x` array
3243      or with `dx` scalar.  Return value will be equal to combined area under
3244      the red lines.
3245  
3246  
3247      References
3248      ----------
3249      .. [1] Wikipedia page: https://en.wikipedia.org/wiki/Trapezoidal_rule
3250  
3251      .. [2] Illustration image:
3252             https://en.wikipedia.org/wiki/File:Composite_trapezoidal_rule_illustration.png
3253  
3254      Examples
3255      --------
3256      >>> np.trapz([1,2,3])
3257      4.0
3258      >>> np.trapz([1,2,3], x=[4,6,8])
3259      8.0
3260      >>> np.trapz([1,2,3], dx=2)
3261      8.0
3262  
3263      Using a decreasing `x` corresponds to integrating in reverse:
3264  
3265      >>> np.trapz([1,2,3], x=[8,6,4])
3266      -8.0
3267  
3268      More generally `x` is used to integrate along a parametric curve.
3269      This finds the area of a circle, noting we repeat the sample which closes
3270      the curve:
3271  
3272      >>> theta = np.linspace(0, 2 * np.pi, num=1000, endpoint=True)
3273      >>> np.trapz(np.cos(theta), x=np.sin(theta))
3274      3.141571941375841
3275  
3276      >>> a = np.arange(6).reshape(2, 3)
3277      >>> a
3278      array([[0, 1, 2],
3279             [3, 4, 5]])
3280      >>> np.trapz(a, axis=0)
3281      array([1.5, 2.5, 3.5])
3282      >>> np.trapz(a, axis=1)
3283      array([2.,  8.])
3284      Nrmrr�r�r�)
r	r�r<rrr�rr�r$r�r~rr�reduce)
3285  r�r�r
3286  r�r�rrrrr
�retrbrbrcrT�s0V
3287  (�
3288  
3289  *�rT)r9�sparse�indexingcGs|Sr]rb)r9r-r.�xirbrbrc�_meshgrid_dispatchersr0�xycs�t|�}|dvrtd��d|��fdd�t|�D�}|dkr9|dkr9d�d	d
3290  �|d_d�d	d
3291  �|d_|sCtj|d
di�}|rLdd�|D�}|S)a�
3292      Return coordinate matrices from coordinate vectors.
3293  
3294      Make N-D coordinate arrays for vectorized evaluations of
3295      N-D scalar/vector fields over N-D grids, given
3296      one-dimensional coordinate arrays x1, x2,..., xn.
3297  
3298      .. versionchanged:: 1.9
3299         1-D and 0-D cases are allowed.
3300  
3301      Parameters
3302      ----------
3303      x1, x2,..., xn : array_like
3304          1-D arrays representing the coordinates of a grid.
3305      indexing : {'xy', 'ij'}, optional
3306          Cartesian ('xy', default) or matrix ('ij') indexing of output.
3307          See Notes for more details.
3308  
3309          .. versionadded:: 1.7.0
3310      sparse : bool, optional
3311          If True the shape of the returned coordinate array for dimension *i*
3312          is reduced from ``(N1, ..., Ni, ... Nn)`` to
3313          ``(1, ..., 1, Ni, 1, ..., 1)``.  These sparse coordinate grids are
3314          intended to be use with :ref:`basics.broadcasting`.  When all
3315          coordinates are used in an expression, broadcasting still leads to a
3316          fully-dimensonal result array.
3317  
3318          Default is False.
3319  
3320          .. versionadded:: 1.7.0
3321      copy : bool, optional
3322          If False, a view into the original arrays are returned in order to
3323          conserve memory.  Default is True.  Please note that
3324          ``sparse=False, copy=False`` will likely return non-contiguous
3325          arrays.  Furthermore, more than one element of a broadcast array
3326          may refer to a single memory location.  If you need to write to the
3327          arrays, make copies first.
3328  
3329          .. versionadded:: 1.7.0
3330  
3331      Returns
3332      -------
3333      X1, X2,..., XN : ndarray
3334          For vectors `x1`, `x2`,..., `xn` with lengths ``Ni=len(xi)``,
3335          returns ``(N1, N2, N3,..., Nn)`` shaped arrays if indexing='ij'
3336          or ``(N2, N1, N3,..., Nn)`` shaped arrays if indexing='xy'
3337          with the elements of `xi` repeated to fill the matrix along
3338          the first dimension for `x1`, the second for `x2` and so on.
3339  
3340      Notes
3341      -----
3342      This function supports both indexing conventions through the indexing
3343      keyword argument.  Giving the string 'ij' returns a meshgrid with
3344      matrix indexing, while 'xy' returns a meshgrid with Cartesian indexing.
3345      In the 2-D case with inputs of length M and N, the outputs are of shape
3346      (N, M) for 'xy' indexing and (M, N) for 'ij' indexing.  In the 3-D case
3347      with inputs of length M, N and P, outputs are of shape (N, M, P) for
3348      'xy' indexing and (M, N, P) for 'ij' indexing.  The difference is
3349      illustrated by the following code snippet::
3350  
3351          xv, yv = np.meshgrid(x, y, indexing='ij')
3352          for i in range(nx):
3353              for j in range(ny):
3354                  # treat xv[i,j], yv[i,j]
3355  
3356          xv, yv = np.meshgrid(x, y, indexing='xy')
3357          for i in range(nx):
3358              for j in range(ny):
3359                  # treat xv[j,i], yv[j,i]
3360  
3361      In the 1-D and 0-D case, the indexing and sparse keywords have no effect.
3362  
3363      See Also
3364      --------
3365      mgrid : Construct a multi-dimensional "meshgrid" using indexing notation.
3366      ogrid : Construct an open multi-dimensional "meshgrid" using indexing
3367              notation.
3368      how-to-index
3369  
3370      Examples
3371      --------
3372      >>> nx, ny = (3, 2)
3373      >>> x = np.linspace(0, 1, nx)
3374      >>> y = np.linspace(0, 1, ny)
3375      >>> xv, yv = np.meshgrid(x, y)
3376      >>> xv
3377      array([[0. , 0.5, 1. ],
3378             [0. , 0.5, 1. ]])
3379      >>> yv
3380      array([[0.,  0.,  0.],
3381             [1.,  1.,  1.]])
3382  
3383      The result of `meshgrid` is a coordinate grid:
3384  
3385      >>> import matplotlib.pyplot as plt
3386      >>> plt.plot(xv, yv, marker='o', color='k', linestyle='none')
3387      >>> plt.show()
3388  
3389      You can create sparse output arrays to save memory and computation time.
3390  
3391      >>> xv, yv = np.meshgrid(x, y, sparse=True)
3392      >>> xv
3393      array([[0. ,  0.5,  1. ]])
3394      >>> yv
3395      array([[0.],
3396             [1.]])
3397  
3398      `meshgrid` is very useful to evaluate functions on a grid. If the
3399      function depends on all coordinates, both dense and sparse outputs can be
3400      used.
3401  
3402      >>> x = np.linspace(-5, 5, 101)
3403      >>> y = np.linspace(-5, 5, 101)
3404      >>> # full coordinate arrays
3405      >>> xx, yy = np.meshgrid(x, y)
3406      >>> zz = np.sqrt(xx**2 + yy**2)
3407      >>> xx.shape, yy.shape, zz.shape
3408      ((101, 101), (101, 101), (101, 101))
3409      >>> # sparse coordinate arrays
3410      >>> xs, ys = np.meshgrid(x, y, sparse=True)
3411      >>> zs = np.sqrt(xs**2 + ys**2)
3412      >>> xs.shape, ys.shape, zs.shape
3413      ((1, 101), (101, 1), (101, 101))
3414      >>> np.array_equal(zz, zs)
3415      True
3416  
3417      >>> h = plt.contourf(x, y, zs)
3418      >>> plt.axis('scaled')
3419      >>> plt.colorbar()
3420      >>> plt.show()
3421      )r1�ijz.Valid values for `indexing` are 'xy' and 'ij'.r�cs<g|]\}}t�|���d|�d�|dd���qS)Nr�rm)r~r	r�)r�r�r���s0rbrcr��s0�zmeshgrid.<locals>.<listcomp>r1rm)rmr�r�Nr)r�rmr�TcSsg|]}|���qSrbr7r~rbrbrcr��r�)r�r�r�rrr~r�)r9r-r.r/r�r�rbr3rcrVs$�
3422  �rVcCrFr]rb)rI�objr�rbrbrc�_delete_dispatcher�rKr6cCs�d}t|�turz|j}Wn	tyYnwt|�}|j}|jjr$dnd}|dur:|dkr2|��}|j}|d}nt	||�}t
3423  d�g|}|j|}t|j�}t
|t
3424  ��r"|�|�\}	}
3425  }t|	|
3426  |�}t|�}
|
dkr||rv||j|d��S|j|d�S|dkr�|}|d}	|dd}
3427  |||
8<t||j|�}|	dkr�nt
3428  d|	�||<|t|�|t|�<|
3429  |kr�n!t
3430  |
3431  |
d�||<t
3432  d�g|}t
3433  |
3434  d�||<|t|�|t|�<|dkr�n<t|
3435  |	td�}d	|d|
3436  |	|�<t
3437  |	|
3438  |
�||<t
3439  d�g|}t
3440  |	|
3441  �||<|t|�}|||<|t|�|t|�<|�r ||�S|St
|ttf��r3t
|t��s3d
3442  }n/d	}|}t�|�}|jdk�rOt
|tj��sO|�t�}n|jdk�rb|jjdv�rb|��}d
3443  }|�r�||k�sp||k�rytd|||f��|dk�r�||7}||d8<t||j|�}t
3444  d|�||<|t|�|t|�<t
3445  |d�||<t
3446  d�g|}t
3447  |dd�||<|t|�|t|�<n-|jtk�r�|j|fk�r�t d
�!|���|}nt|td�}d	||f<|||<|t|�}|�r�||�S|S)a
3448      Return a new array with sub-arrays along an axis deleted. For a one
3449      dimensional array, this returns those entries not returned by
3450      `arr[obj]`.
3451  
3452      Parameters
3453      ----------
3454      arr : array_like
3455          Input array.
3456      obj : slice, int or array of ints
3457          Indicate indices of sub-arrays to remove along the specified axis.
3458  
3459          .. versionchanged:: 1.19.0
3460              Boolean indices are now treated as a mask of elements to remove,
3461              rather than being cast to the integers 0 and 1.
3462  
3463      axis : int, optional
3464          The axis along which to delete the subarray defined by `obj`.
3465          If `axis` is None, `obj` is applied to the flattened array.
3466  
3467      Returns
3468      -------
3469      out : ndarray
3470          A copy of `arr` with the elements specified by `obj` removed. Note
3471          that `delete` does not occur in-place. If `axis` is None, `out` is
3472          a flattened array.
3473  
3474      See Also
3475      --------
3476      insert : Insert elements into an array.
3477      append : Append elements at the end of an array.
3478  
3479      Notes
3480      -----
3481      Often it is preferable to use a boolean mask. For example:
3482  
3483      >>> arr = np.arange(12) + 1
3484      >>> mask = np.ones(len(arr), dtype=bool)
3485      >>> mask[[0,2,4]] = False
3486      >>> result = arr[mask,...]
3487  
3488      Is equivalent to ``np.delete(arr, [0,2,4], axis=0)``, but allows further
3489      use of `mask`.
3490  
3491      Examples
3492      --------
3493      >>> arr = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
3494      >>> arr
3495      array([[ 1,  2,  3,  4],
3496             [ 5,  6,  7,  8],
3497             [ 9, 10, 11, 12]])
3498      >>> np.delete(arr, 1, 0)
3499      array([[ 1,  2,  3,  4],
3500             [ 9, 10, 11, 12]])
3501  
3502      >>> np.delete(arr, np.s_[::2], 1)
3503      array([[ 2,  4],
3504             [ 6,  8],
3505             [10, 12]])
3506      >>> np.delete(arr, [1,3,5], None)
3507      array([ 1,  3,  5,  7,  8,  9, 10, 11, 12])
3508  
3509      Nr8�Crmr)r�r�r�FT�uiz2index %i is out of bounds for axis %i with size %iz\boolean array argument obj to delete must be one dimensional and match the axis length of {})"r�r�__array_wrap__�AttributeErrorrr��flags�fncrr-rrrr�r�r#r�r�r9r
3510  r�r�rr�rrr~r�r�rr�r��
3511  IndexErrorr�r�)rIr5r��wrapr��arrorder�slobjr	�newshape�start�stop�step�xrZnumtodel�new�slobj2r�Zsingle_value�_objrbrbrcrW�s�A
3512  �
3513  
3514  
3515  
3516  
3517  ��
3518  �
3519  rWcCrr]rb)rIr5�valuesr�rbrbrc�_insert_dispatcher~rrJcCsd}t|�turz|j}Wn	tyYnwt|�}|j}|jjr$dnd}|dur:|dkr2|��}|j}|d}nt	||�}t
3520  d�g|}|j|}t|j�}	t
|t
3521  �r`t|�|�dti�}
3522  n!t�|�}
3523  |
3524  jtkrxtjdtdd�|
3525  �t�}
3526  n	|
3527  jdkr�td	��|
3528  jdk�r|
3529  ��}||ks�||kr�td
3530  |�d|�d|����|d
kr�||7}t|d|j|jd�}|
3531  jd
kr�t�|d
|�}|j|}|	||7<t|	|j|�}
t
3532  d|�||<|t|�|
t|�<t
3533  |||�||<||
t|�<t
3534  ||d�||<t
3535  d�g|}t
3536  |d�||<|t|�|
t|�<|�r||
�S|
S|
3537  jd
k�r/t
|tj��s/|
3538  �t�}
3539  |
3540  |
3541  d
k|7<t |
3542  �}|
3543  j!dd�}|
3544  |t�|�7<|	||7<t"|	|td�}d||
3545  <t|	|j|�}
t
3546  d�g|}|
3547  ||<|||<||
t|�<||
t|�<|�r�||
�S|
S)a
3548  
3549      Insert values along the given axis before the given indices.
3550  
3551      Parameters
3552      ----------
3553      arr : array_like
3554          Input array.
3555      obj : int, slice or sequence of ints
3556          Object that defines the index or indices before which `values` is
3557          inserted.
3558  
3559          .. versionadded:: 1.8.0
3560  
3561          Support for multiple insertions when `obj` is a single scalar or a
3562          sequence with one element (similar to calling insert multiple
3563          times).
3564      values : array_like
3565          Values to insert into `arr`. If the type of `values` is different
3566          from that of `arr`, `values` is converted to the type of `arr`.
3567          `values` should be shaped so that ``arr[...,obj,...] = values``
3568          is legal.
3569      axis : int, optional
3570          Axis along which to insert `values`.  If `axis` is None then `arr`
3571          is flattened first.
3572  
3573      Returns
3574      -------
3575      out : ndarray
3576          A copy of `arr` with `values` inserted.  Note that `insert`
3577          does not occur in-place: a new array is returned. If
3578          `axis` is None, `out` is a flattened array.
3579  
3580      See Also
3581      --------
3582      append : Append elements at the end of an array.
3583      concatenate : Join a sequence of arrays along an existing axis.
3584      delete : Delete elements from an array.
3585  
3586      Notes
3587      -----
3588      Note that for higher dimensional inserts ``obj=0`` behaves very different
3589      from ``obj=[0]`` just like ``arr[:,0,:] = values`` is different from
3590      ``arr[:,[0],:] = values``.
3591  
3592      Examples
3593      --------
3594      >>> a = np.array([[1, 1], [2, 2], [3, 3]])
3595      >>> a
3596      array([[1, 1],
3597             [2, 2],
3598             [3, 3]])
3599      >>> np.insert(a, 1, 5)
3600      array([1, 5, 1, ..., 2, 3, 3])
3601      >>> np.insert(a, 1, 5, axis=1)
3602      array([[1, 5, 1],
3603             [2, 5, 2],
3604             [3, 5, 3]])
3605  
3606      Difference between sequence and scalars:
3607  
3608      >>> np.insert(a, [1], [[1],[2],[3]], axis=1)
3609      array([[1, 1, 1],
3610             [2, 2, 2],
3611             [3, 3, 3]])
3612      >>> np.array_equal(np.insert(a, 1, [1, 2, 3], axis=1),
3613      ...                np.insert(a, [1], [[1],[2],[3]], axis=1))
3614      True
3615  
3616      >>> b = a.flatten()
3617      >>> b
3618      array([1, 1, 2, 2, 3, 3])
3619      >>> np.insert(b, [2, 2], [5, 6])
3620      array([1, 1, 5, ..., 2, 3, 3])
3621  
3622      >>> np.insert(b, slice(2, 4), [5, 6])
3623      array([1, 1, 5, ..., 2, 3, 3])
3624  
3625      >>> np.insert(b, [2, 2], [7.13, False]) # type casting
3626      array([1, 1, 7, ..., 2, 3, 3])
3627  
3628      >>> x = np.arange(8).reshape(2, 4)
3629      >>> idx = (1, 3)
3630      >>> np.insert(x, idx, 999, axis=1)
3631      array([[  0, 999,   1,   2, 999,   3],
3632             [  4, 999,   5,   6, 999,   7]])
3633  
3634      Nr8r7rmr�zrin the future insert will treat boolean arrays and array-likes as a boolean index instead of casting it to integerr�r�zDindex array argument obj to insert must be one dimensional or scalarzindex z is out of bounds for axis z with size rFr��	mergesort)r�r�)#r�rr9r:rr�r;r<rr-rrrr�r�rr#rr~rr�r�r�r��
FutureWarningr�r�r�r�r=r$r
3635  r�r�r$r)rIr5rIr�r>r�r?r@r	rAr#r�ZnumnewrFrGr�Zold_maskrbrbrcrX�s�Y
3636  �
3637  
3638  
3639  
3640  
3641  
3642  
3643  �
3644  ��
3645  
3646  
3647  rXcCrFr]rb�rIrIr�rbrbrc�_append_dispatcher@rKrNcCsDt|�}|dur|jdkr|��}t|�}|jd}t||f|d�S)a
3648      Append values to the end of an array.
3649  
3650      Parameters
3651      ----------
3652      arr : array_like
3653          Values are appended to a copy of this array.
3654      values : array_like
3655          These values are appended to a copy of `arr`.  It must be of the
3656          correct shape (the same shape as `arr`, excluding `axis`).  If
3657          `axis` is not specified, `values` can be any shape and will be
3658          flattened before use.
3659      axis : int, optional
3660          The axis along which `values` are appended.  If `axis` is not
3661          given, both `arr` and `values` are flattened before use.
3662  
3663      Returns
3664      -------
3665      append : ndarray
3666          A copy of `arr` with `values` appended to `axis`.  Note that
3667          `append` does not occur in-place: a new array is allocated and
3668          filled.  If `axis` is None, `out` is a flattened array.
3669  
3670      See Also
3671      --------
3672      insert : Insert elements into an array.
3673      delete : Delete elements from an array.
3674  
3675      Examples
3676      --------
3677      >>> np.append([1, 2, 3], [[4, 5, 6], [7, 8, 9]])
3678      array([1, 2, 3, ..., 7, 8, 9])
3679  
3680      When `axis` is specified, `values` must have the correct shape.
3681  
3682      >>> np.append([[1, 2, 3], [4, 5, 6]], [[7, 8, 9]], axis=0)
3683      array([[1, 2, 3],
3684             [4, 5, 6],
3685             [7, 8, 9]])
3686      >>> np.append([[1, 2, 3], [4, 5, 6]], [7, 8, 9], axis=0)
3687      Traceback (most recent call last):
3688          ...
3689      ValueError: all the input arrays must have same number of dimensions, but
3690      the array at index 0 has 2 dimension(s) and the array at index 1 has 1
3691      dimension(s)
3692  
3693      Nrmr�)r	r�rrrMrbrbrcrYDs1
3694  
3695  rYcCrFr]rb)r��binsrrbrbrc�_digitize_dispatcher~rKrPcCs�t�|�}t�|�}t�|jtj�rtd��t|�}|dkr"td��|r&dnd}|dkr=t	|�tj
3696  |ddd�||d�Stj
3697  |||d�S)	a?
3698      Return the indices of the bins to which each value in input array belongs.
3699  
3700      =========  =============  ============================
3701      `right`    order of bins  returned index `i` satisfies
3702      =========  =============  ============================
3703      ``False``  increasing     ``bins[i-1] <= x < bins[i]``
3704      ``True``   increasing     ``bins[i-1] < x <= bins[i]``
3705      ``False``  decreasing     ``bins[i-1] > x >= bins[i]``
3706      ``True``   decreasing     ``bins[i-1] >= x > bins[i]``
3707      =========  =============  ============================
3708  
3709      If values in `x` are beyond the bounds of `bins`, 0 or ``len(bins)`` is
3710      returned as appropriate.
3711  
3712      Parameters
3713      ----------
3714      x : array_like
3715          Input array to be binned. Prior to NumPy 1.10.0, this array had to
3716          be 1-dimensional, but can now have any shape.
3717      bins : array_like
3718          Array of bins. It has to be 1-dimensional and monotonic.
3719      right : bool, optional
3720          Indicating whether the intervals include the right or the left bin
3721          edge. Default behavior is (right==False) indicating that the interval
3722          does not include the right edge. The left bin end is open in this
3723          case, i.e., bins[i-1] <= x < bins[i] is the default behavior for
3724          monotonically increasing bins.
3725  
3726      Returns
3727      -------
3728      indices : ndarray of ints
3729          Output array of indices, of same shape as `x`.
3730  
3731      Raises
3732      ------
3733      ValueError
3734          If `bins` is not monotonic.
3735      TypeError
3736          If the type of the input is complex.
3737  
3738      See Also
3739      --------
3740      bincount, histogram, unique, searchsorted
3741  
3742      Notes
3743      -----
3744      If values in `x` are such that they fall outside the bin range,
3745      attempting to index `bins` with the indices that `digitize` returns
3746      will result in an IndexError.
3747  
3748      .. versionadded:: 1.10.0
3749  
3750      `np.digitize` is  implemented in terms of `np.searchsorted`. This means
3751      that a binary search is used to bin the values, which scales much better
3752      for larger number of bins than the previous linear search. It also removes
3753      the requirement for the input array to be 1-dimensional.
3754  
3755      For monotonically _increasing_ `bins`, the following are equivalent::
3756  
3757          np.digitize(x, bins, right=True)
3758          np.searchsorted(bins, x, side='left')
3759  
3760      Note that as the order of the arguments are reversed, the side must be too.
3761      The `searchsorted` call is marginally faster, as it does not do any
3762      monotonicity checks. Perhaps more importantly, it supports all dtypes.
3763  
3764      Examples
3765      --------
3766      >>> x = np.array([0.2, 6.4, 3.0, 1.6])
3767      >>> bins = np.array([0.0, 1.0, 2.5, 4.0, 10.0])
3768      >>> inds = np.digitize(x, bins)
3769      >>> inds
3770      array([1, 4, 3, 2])
3771      >>> for n in range(x.size):
3772      ...   print(bins[inds[n]-1], "<=", x[n], "<", bins[inds[n]])
3773      ...
3774      0.0 <= 0.2 < 1.0
3775      4.0 <= 6.4 < 10.0
3776      2.5 <= 3.0 < 4.0
3777      1.0 <= 1.6 < 2.5
3778  
3779      >>> x = np.array([1.2, 10.0, 12.4, 15.5, 20.])
3780      >>> bins = np.array([0, 5, 10, 15, 20])
3781      >>> np.digitize(x,bins,right=True)
3782      array([1, 2, 3, 4, 4])
3783      >>> np.digitize(x,bins,right=False)
3784      array([1, 3, 3, 4, 5])
3785      zx may not be complexrz3bins must be monotonically increasing or decreasingrrr�N)�side)r�rr~r�r�r*r�r.r�r��searchsorted)r�rOr�monorQrbrbrcrI�s
3786  [
3787  "rI)NN)rmr�r])NNN)NNFr�)r�F)NNNN)F)Nr�)rA)NT)NNNNNN)NTFNNN)NNFF)NNNNN)NNFr�F)NNFr�)r�r�N)Nror�)��collections.abcr��	functoolsrXrPr�r4r~�numpy.core.numeric�core�numericr��
3788  numpy.corerrrrrrrr	r
3789  rrr
rrrrr�numpy.core.umathrrrrrrrrrrrr�numpy.core.fromnumericrr r!r"r#r$�numpy.core.numerictypesr%�numpy.core.overridesr&r'�numpy.core.function_baser(�numpy.lib.twodim_baser)�numpy.core.multiarrayr*r+r,r-r.r/r"r0r r1rZr��numpy.lib.histogramsr2r3�partial�array_function_dispatch�__all__�dictr%r�rCr�rBr:r�r�rHrGr�r7r�r6r�r9r�r=rr<rr(r>r/r?r6r@r@r8rJrDrNrErArZr��_CORE_DIMENSION_LISTr^�_ARGUMENT_LISTrcrfrjrqrvr|rFr�rJr�rKrRrQrPrOr�r�r�r�r�r�rUrSr�rNr�rLr�r�rMr�rr;r
r[rrr
3790  r�ryrrrvrrwr^rr�rr!rr*rTr0rVr6rWrJrXrNrYrPrIrbrbrbrc�<module>sNH8 $�������	������
3791  ��UY]
3792  ,��&F
3793  xd][
4_
3794  $4
3795  3
3796  ++
3797  
3798  
3799  
3800  "�n����^��
3801  c
3802  k
3803  g
3804  e!
3805  =
3806  
3807  P
3808  -N�U7����"����}�	�����
3809  �!&���
3810  �Wq@>9