bgA ~dZddlZddlZddlZddlZddlZddlmZgdZ ej ej dZ e Z dZdZd Zd Zd Zd Zd ZdZdZeeeeeeeedZdZdZdZdZdZddZe eddZ ddZe ed dZ ddZ!e e!d dZ"dS)!z Histogram-related functions N) overrides) histogram histogramddhistogram_bin_edgesnumpy)modulecjt||S)aPeak-to-peak value of x. This implementation avoids the problem of signed integer arrays having a peak-to-peak value that cannot be represented with the array's data type. This function returns an unsigned value for signed integer arrays. )_unsigned_subtractmaxmin)xs K/opt/cloudlinux/venv/lib64/python3.11/site-packages/numpy/lib/histograms.py_ptprs$ aeeggquuww / //cV~t|tj|jz S)a~ Square root histogram bin estimator. Bin width is inversely proportional to the data size. Used by many programs for its simplicity. Parameters ---------- x : array_like Input data that is to be histogrammed, trimmed to range. May not be empty. Returns ------- h : An estimate of the optimal bin width for the given data. )rnpsqrtsizer ranges r_hist_bin_sqrtr s""  77RWQV__ $$rc\~t|tj|jdzz S)a Sturges histogram bin estimator. A very simplistic estimator based on the assumption of normality of the data. This estimator has poor performance for non-normal data, which becomes especially obvious for large data sets. The estimate depends only on size of the data. Parameters ---------- x : array_like Input data that is to be histogrammed, trimmed to range. May not be empty. Returns ------- h : An estimate of the optimal bin width for the given data. ?)rrlog2rrs r_hist_bin_sturgesr5s'&  77bgafoo+ ,,rc>~t|d|jdzzz S)aI Rice histogram bin estimator. Another simple estimator with no normality assumption. It has better performance for large data than Sturges, but tends to overestimate the number of bins. The number of bins is proportional to the cube root of data size (asymptotically optimal). The estimate depends only on size of the data. Parameters ---------- x : array_like Input data that is to be histogrammed, trimmed to range. May not be empty. Returns ------- h : An estimate of the optimal bin width for the given data. @UUUUUU?)rrrs r_hist_bin_ricerLs$(  77cAFw// 00rch~dtjdzz|jz dztj|zS)a Scott histogram bin estimator. The binwidth is proportional to the standard deviation of the data and inversely proportional to the cube root of data size (asymptotically optimal). Parameters ---------- x : array_like Input data that is to be histogrammed, trimmed to range. May not be empty. Returns ------- h : An estimate of the optimal bin width for the given data. g8@?r)rpirstdrs r_hist_bin_scottr$ds1$  25#:  &) 4rvayy @@rcRjtdksdkrdSfd}tdtt j}t td|dz|}||krtj dtd|z S) a6 Histogram bin estimator based on minimizing the estimated integrated squared error (ISE). The number of bins is chosen by minimizing the estimated ISE against the unknown true distribution. The ISE is estimated using cross-validation and can be regarded as a generalization of Scott's rule. https://en.wikipedia.org/wiki/Histogram#Scott.27s_normal_reference_rule This paper by Stone appears to be the origination of this rule. http://digitalassets.lib.berkeley.edu/sdtr/ucb/text/34.pdf Parameters ---------- x : array_like Input data that is to be histogrammed, trimmed to range. May not be empty. range : (float, float) The lower and upper range of the bins. Returns ------- h : An estimate of the optimal bin width for the given data. rc|z }tj|dz }ddz||zz |z S)N)binsrrr&)rrdot)nbinshhp_knptp_xrr s rjhatz_hist_bin_stone..jhatsO U]l15666q9A=QUcggcll**b00rd)keyz/The number of bins estimated may be suboptimal. stacklevel) rrr intrrr _rangewarningswarnRuntimeWarning)r rr0nbins_upper_boundr+r.r/s`` @@r_hist_bin_stoner<zs0 A GGEAvv!q11111111 CRWQZZ11 q+a/00d ; ; ;E !!! G$ 4 4 4 4 5=rc~|jdkrtjd|jdz z|jdz|jdzzz }tj|}|dkr|tj|z }tj|||tj|d|tj|}t|dtj|jztjdtj ||z zzz SdS)a Doane's histogram bin estimator. Improved version of Sturges' formula which works better for non-normal data. See stats.stackexchange.com/questions/55134/doanes-formula-for-histogram-binning Parameters ---------- x : array_like Input data that is to be histogrammed, trimmed to range. May not be empty. Returns ------- h : An estimate of the optimal bin width for the given data. r)g@rr3g) rrrr#mean true_dividepowerrrabsolute)r rsg1sigmatempg1s r_hist_bin_doanerFs$ vzzgcQVaZ(QVc\afqj,IJKKq  3;;rwqzz>D N4 - - - HT1d # # #B77cBGAFOO3$&GC"+b//C2G,G$H$HIJ J 3rcj~tjtj|ddg}d|z|jdzzS)a= The Freedman-Diaconis histogram bin estimator. The Freedman-Diaconis rule uses interquartile range (IQR) to estimate binwidth. It is considered a variation of the Scott rule with more robustness as the IQR is less affected by outliers than the standard deviation. However, the IQR depends on fewer points than the standard deviation, so it is less accurate, especially for long tailed distributions. If the IQR is 0, this function returns 0 for the bin width. Binwidth is inversely proportional to the cube root of data size (asymptotically optimal). Parameters ---------- x : array_like Input data that is to be histogrammed, trimmed to range. May not be empty. Returns ------- h : An estimate of the optimal bin width for the given data. KrgUUUUUUտ)rsubtract percentiler)r riqrs r _hist_bin_fdrMs92  +r}QR11 2C 9qv*- --rclt||}t||}~|rt||S|S)a Histogram bin estimator that uses the minimum width of the Freedman-Diaconis and Sturges estimators if the FD bin width is non-zero. If the bin width from the FD estimator is 0, the Sturges estimator is used. The FD estimator is usually the most robust method, but its width estimate tends to be too large for small `x` and bad for data with limited variance. The Sturges estimator is quite good for small (<1000) datasets and is the default in the R language. This method gives good off-the-shelf behaviour. .. versionchanged:: 1.15.0 If there is limited variance the IQR can be 0, which results in the FD bin width being 0 too. This is not a valid bin width, so ``np.histogram_bin_edges`` chooses 1 bin instead, which may not be optimal. If the IQR is 0, it's unlikely any variance-based estimators will be of use, so we revert to the Sturges estimator, which only uses the size of the dataset in its calculation. Parameters ---------- x : array_like Input data that is to be histogrammed, trimmed to range. May not be empty. Returns ------- h : An estimate of the optimal bin width for the given data. See Also -------- _hist_bin_fd, _hist_bin_sturges )rMrr )r rfd_bw sturges_bws r_hist_bin_autorQsFD E " "E"1e,,J  5*%%%r)stoneautodoanefdricescottrsturgesctj|}|jtjkr^t jd|jtjtd| tj}|Gtj|}|j |j krtd| }| }||fS)z: Check a and weights have matching shapes, and ravel both z1Converting input from {} to {} for compatibility.r3r4Nz(weights should have the same shape as a.) rasarraydtypebool_r8r9formatuint8r:astypeshape ValueErrorravel)aweightss r_ravel_and_check_weightsres 1 A w"( Ivagrx00$ 4 4 4 4 HHRX  *W%% =AG # #:<< <--//  A g:rc|f|\}}||krtdtj|rtj|s#td||n|jdkrd\}}ns||}}tj|rtj|s#td||||kr |dz }|dz}||fS)z^ Determine the outer bin edges to use, from either the data or the range argument Nz/max must be larger than min in range parameter.z(supplied range of [{}, {}] is not finiter)rr&z,autodetected range of [{}, {}] is not finiter!)rarisfiniter]rr r )rcr first_edge last_edges r_get_outer_edgesrj0s5   % I  ! !ACC C J'' ZBK ,B,B Z:AA*iXXZZ Z Z 1 $ II !I  J'' ^BK ,B,B ^>EEjR[\\^^ ^Y#% O y  rc tjtjtjtjtjtjtjtjtj tj i}tj ||} ||j }tj ||d|S#t$rtj |||cYSwxYw)z Subtract two values where a >= b, and produce an unsigned result This is needed when finding the difference between the upper and lower bound of an int16 histogram unsafe)castingr[r[)rbyteubyteshortushortintcuintcint_uintlonglong ulonglong result_typetyperJKeyError)rcbsigned_to_unsigneddts rr r Ns  ")   R\  1  B=  ( {1a<<<< +++{1ar******+s B,,!CCcd}d}t|tr|}|tvr"td||t dt ||\}}|6||k} | ||kz} tj | s|| }|j dkrd}n((.. dG 6Q;;LL(1!j)5LMME !"27+=i+T+TW\+\#]#]^^  ! !   K#>$//LL K K KBDDIJ K K !  GHH H 0E : : II !  Jt$$ 6)CRC.9QRR=0 1 1 ECEE E E ;<<<>*i;; =2: . . 7~h66HK   q"vv&& qvw''  rc |||fSN)rcr(rrds r_histogram_bin_edges_dispatcherrs tW r cVt||\}}t||||\}}|S)aY Function to calculate only the edges of the bins used by the `histogram` function. Parameters ---------- a : array_like Input data. The histogram is computed over the flattened array. bins : int or sequence of scalars or str, optional If `bins` is an int, it defines the number of equal-width bins in the given range (10, by default). If `bins` is a sequence, it defines the bin edges, including the rightmost edge, allowing for non-uniform bin widths. If `bins` is a string from the list below, `histogram_bin_edges` will use the method chosen to calculate the optimal bin width and consequently the number of bins (see `Notes` for more detail on the estimators) from the data that falls within the requested range. While the bin width will be optimal for the actual data in the range, the number of bins will be computed to fill the entire range, including the empty portions. For visualisation, using the 'auto' option is suggested. Weighted data is not supported for automated bin size selection. 'auto' Maximum of the 'sturges' and 'fd' estimators. Provides good all around performance. 'fd' (Freedman Diaconis Estimator) Robust (resilient to outliers) estimator that takes into account data variability and data size. 'doane' An improved version of Sturges' estimator that works better with non-normal datasets. 'scott' Less robust estimator that takes into account data variability and data size. 'stone' Estimator based on leave-one-out cross-validation estimate of the integrated squared error. Can be regarded as a generalization of Scott's rule. 'rice' Estimator does not take variability into account, only data size. Commonly overestimates number of bins required. 'sturges' R's default method, only accounts for data size. Only optimal for gaussian data and underestimates number of bins for large non-gaussian datasets. 'sqrt' Square root (of data size) estimator, used by Excel and other programs for its speed and simplicity. range : (float, float), optional The lower and upper range of the bins. If not provided, range is simply ``(a.min(), a.max())``. Values outside the range are ignored. The first element of the range must be less than or equal to the second. `range` affects the automatic bin computation as well. While bin width is computed to be optimal based on the actual data within `range`, the bin count will fill the entire range including portions containing no data. weights : array_like, optional An array of weights, of the same shape as `a`. Each value in `a` only contributes its associated weight towards the bin count (instead of 1). This is currently not used by any of the bin estimators, but may be in the future. Returns ------- bin_edges : array of dtype float The edges to pass into `histogram` See Also -------- histogram Notes ----- The methods to estimate the optimal number of bins are well founded in literature, and are inspired by the choices R provides for histogram visualisation. Note that having the number of bins proportional to :math:`n^{1/3}` is asymptotically optimal, which is why it appears in most estimators. These are simply plug-in methods that give good starting points for number of bins. In the equations below, :math:`h` is the binwidth and :math:`n_h` is the number of bins. All estimators that compute bin counts are recast to bin width using the `ptp` of the data. The final bin count is obtained from ``np.round(np.ceil(range / h))``. The final bin width is often less than what is returned by the estimators below. 'auto' (maximum of the 'sturges' and 'fd' estimators) A compromise to get a good value. For small datasets the Sturges value will usually be chosen, while larger datasets will usually default to FD. Avoids the overly conservative behaviour of FD and Sturges for small and large datasets respectively. Switchover point is usually :math:`a.size \approx 1000`. 'fd' (Freedman Diaconis Estimator) .. math:: h = 2 \frac{IQR}{n^{1/3}} The binwidth is proportional to the interquartile range (IQR) and inversely proportional to cube root of a.size. Can be too conservative for small datasets, but is quite good for large datasets. The IQR is very robust to outliers. 'scott' .. math:: h = \sigma \sqrt[3]{\frac{24 \sqrt{\pi}}{n}} The binwidth is proportional to the standard deviation of the data and inversely proportional to cube root of ``x.size``. Can be too conservative for small datasets, but is quite good for large datasets. The standard deviation is not very robust to outliers. Values are very similar to the Freedman-Diaconis estimator in the absence of outliers. 'rice' .. math:: n_h = 2n^{1/3} The number of bins is only proportional to cube root of ``a.size``. It tends to overestimate the number of bins and it does not take into account data variability. 'sturges' .. math:: n_h = \log _{2}(n) + 1 The number of bins is the base 2 log of ``a.size``. This estimator assumes normality of data and is too conservative for larger, non-normal datasets. This is the default method in R's ``hist`` method. 'doane' .. math:: n_h = 1 + \log_{2}(n) + \log_{2}\left(1 + \frac{|g_1|}{\sigma_{g_1}}\right) g_1 = mean\left[\left(\frac{x - \mu}{\sigma}\right)^3\right] \sigma_{g_1} = \sqrt{\frac{6(n - 2)}{(n + 1)(n + 3)}} An improved version of Sturges' formula that produces better estimates for non-normal datasets. This estimator attempts to account for the skew of the data. 'sqrt' .. math:: n_h = \sqrt n The simplest and fastest estimator. Only takes into account the data size. Examples -------- >>> arr = np.array([0, 0, 0, 1, 2, 3, 3, 4, 5]) >>> np.histogram_bin_edges(arr, bins='auto', range=(0, 1)) array([0. , 0.25, 0.5 , 0.75, 1. ]) >>> np.histogram_bin_edges(arr, bins=2) array([0. , 2.5, 5. ]) For consistency with histogram, an array of pre-computed bins is passed through unmodified: >>> np.histogram_bin_edges(arr, [1, 2]) array([1, 2]) This function allows one set of bins to be computed, and reused across multiple histograms: >>> shared_bins = np.histogram_bin_edges(arr, bins='auto') >>> shared_bins array([0., 1., 2., 3., 4., 5.]) >>> group_id = np.array([0, 1, 1, 0, 1, 1, 0, 1, 1]) >>> hist_0, _ = np.histogram(arr[group_id == 0], bins=shared_bins) >>> hist_1, _ = np.histogram(arr[group_id == 1], bins=shared_bins) >>> hist_0; hist_1 array([1, 1, 0, 1, 0]) array([2, 0, 1, 1, 2]) Which gives more easily comparable results than using separate bins for each histogram: >>> hist_0, bins_0 = np.histogram(arr[group_id == 0], bins='auto') >>> hist_1, bins_1 = np.histogram(arr[group_id == 1], bins='auto') >>> hist_0; hist_1 array([1, 1, 1]) array([2, 1, 1, 2]) >>> bins_0; bins_1 array([0., 1., 2., 3.]) array([0. , 1.25, 2.5 , 3.75, 5. ]) )rer)rcr(rrdr_s rrrs5L*!W55JAw!!T5'::LIq rc |||fSrr)rcr(rdensityrds r_histogram_dispatcherrs tW rc"t||\}}t||||\}}|tjtj}n|j}d}|dupBtj|jtjptj|jt} || r|\} } } tj| |} | t| | z }tdt||D]}||||z}|d}n ||||z}|| k}||| kz}tj |s||}|||}||jd}t|| |z}|tj}||| kxxdzcc<|||k}||xxdzcc<|||dzk|| dz kz}||xxdz cc<|jdkrV| xjtj||j| z c_| xjtj||j| z c_j| tj||| |z } n>> np.histogram([1, 2, 1], bins=[0, 1, 2, 3]) (array([0, 2, 1]), array([0, 1, 2, 3])) >>> np.histogram(np.arange(4), bins=np.arange(5), density=True) (array([0.25, 0.25, 0.25, 0.25]), array([0, 1, 2, 3, 4])) >>> np.histogram([[1, 2, 1], [1, 0, 1]], bins=[0,1,2,3]) (array([1, 4, 1]), array([0, 1, 2, 3])) >>> a = np.arange(5) >>> hist, bin_edges = np.histogram(a, density=True) >>> hist array([0.5, 0. , 0.5, 0. , 0. , 0.5, 0. , 0.5, 0. , 0.5]) >>> hist.sum() 2.4999999999999996 >>> np.sum(hist * np.diff(bin_edges)) 1.0 .. versionadded:: 1.11.0 Automated Bin Selection Methods example, using 2 peak random data with 2000 points: >>> import matplotlib.pyplot as plt >>> rng = np.random.RandomState(10) # deterministic random data >>> a = np.hstack((rng.normal(size=1000), ... rng.normal(loc=5, scale=2, size=1000))) >>> _ = plt.hist(a, bins='auto') # arguments are passed to np.histogram >>> plt.title("Histogram with 'auto' bins") Text(0.5, 1.0, "Histogram with 'auto' bins") >>> plt.show() NirF)copyr&c)rd minlengthrn)rerrr[intpcan_castdoublecomplexzerosr r7lenrrr_kindrealbincountimagr`sortrargsortrcumsumdiffarrayrsum)rcr(rrrdr uniform_binsntypeBLOCKsimple_weightsrhrirr.normitmp_atmp_wr f_indicesindices decrement incrementcum_nsazero sorting_indexswcw bin_indexdbs rrrsrH*!W55JAw,QeWEEI|!!  E 4 , GM29-- , GM7++ N/;+ I| H\5 ) )0JGGG 3q665))+ G+ GAa%iLE!e) ,Z'D Ui' (D>((.. (d $!$KE LLuL==E+5*==DI&&rw//G G|+ , , , 1 , , , ' 22I I   ! #   9Wq[#99#|a'779I I   ! #   zS  "+guz0<>>>>"+guz0<>>>>R[%+79999?GU+ G\%00 ?As1vvu-- A AWQq5y\**1"i@@@ A8AU+++DAs1vvu-- ' '!AeG) !E' * " 5 1 1 =)=)^T299;;$7884RCC I& GENN' Xbgi((% 0 0tAEEGG|Y&& i<rc#Kt|dr|Vn|Ed{Vtjt5|Ed{Vdddn #1swxYwY|VdS)Nr`)hasattr contextlibsuppressr)sampler(rrrds r_histogramdd_dispatcherrxsvw   Y ' ' MMMMMs AAAc j\}}n:#ttf$r&tjjj\}}YnwxYwtj|tj}|dgz|dgz}|tj|} t|} | |krtdn#t$r ||gz}YnwxYw|d|z}n"t||krtdt|D]} tj || dkr|| dkr"td | tdd| f|| \} } tj|| } n5#t$r(}td | |d}~wwxYwtj| | | dz| <ntj || dkrttj|| | <tj| dd | ddkr"td | n"td | t| dz|| <tj| || <t)fd t|D}t|D]4} dd| f| d k}|| |xxdzcc<5tj||}tj||| }||}|t4d}|t7dd fz}||}|rq|}t|D]H} tj|t<}|| dz || <||| |z }I||z}|j|dz krt?d|fS)ab Compute the multidimensional histogram of some data. Parameters ---------- sample : (N, D) array, or (N, D) array_like The data to be histogrammed. Note the unusual interpretation of sample when an array_like: * When an array, each row is a coordinate in a D-dimensional space - such as ``histogramdd(np.array([p1, p2, p3]))``. * When an array_like, each element is the list of values for single coordinate - such as ``histogramdd((X, Y, Z))``. The first form should be preferred. bins : sequence or int, optional The bin specification: * A sequence of arrays describing the monotonically increasing bin edges along each dimension. * The number of bins for each dimension (nx, ny, ... =bins) * The number of bins for all dimensions (nx=ny=...=bins). range : sequence, optional A sequence of length D, each an optional (lower, upper) tuple giving the outer bin edges to be used if the edges are not given explicitly in `bins`. An entry of None in the sequence results in the minimum and maximum values being used for the corresponding dimension. The default, None, is equivalent to passing a tuple of D None values. density : bool, optional If False, the default, returns the number of samples in each bin. If True, returns the probability *density* function at the bin, ``bin_count / sample_count / bin_volume``. weights : (N,) array_like, optional An array of values `w_i` weighing each sample `(x_i, y_i, z_i, ...)`. Weights are normalized to 1 if density is True. If density is False, the values of the returned histogram are equal to the sum of the weights belonging to the samples falling into each bin. Returns ------- H : ndarray The multidimensional histogram of sample x. See density and weights for the different possible semantics. edges : list A list of D arrays describing the bin edges for each dimension. See Also -------- histogram: 1-D histogram histogram2d: 2-D histogram Examples -------- >>> r = np.random.randn(100,3) >>> H, edges = np.histogramdd(r, bins = (5, 8, 4)) >>> H.shape, edges[0].size, edges[1].size, edges[2].size ((5, 8, 4), 6, 9, 5) NzEThe dimension of bins must be equal to the dimension of the sample x.rz0range argument must have one entry per dimensionrr&z,`bins[{}]` must be positive, when an integerz,`bins[{}]` must be an integer, when a scalarrz:`bins[{}]` must be monotonically increasing, when an arrayz'`bins[{}]` must be a scalar or 1d arrayc3fK|]+}tj|dd|fdV,dS)Nr)side)rr).0redgesrs r zhistogramdd..sZ  a&A,W===r)rsafe)rmr)zInternal Shape Error) r`AttributeErrorrar atleast_2dTemptyrrZrrr7rr]rjrrrrrtupleravel_multi_indexrprodreshaper_rsliceronesr6 RuntimeError)rr(rrrdNDnbindedgesMrsminsmaxr.rNcounton_edgexyhistcoresr`rs` @rrrsD|11 J 'v&&(|111 8Arw  D tfHE vXF*W%% II 66   $x  }!  UqKLLLAYY&& 747  q Aw{{ BII!LLNNN)&1+uQx@@JD$ N47++   ?FFqII  {4q1u55E!HH WT!W   " "z$q'**E!HveAhssmeAhqrrl233  PVAYY    9@@CCEE EeAh--!#QGE!H%%q FAYY  !!!Q$<58B</q 'a fd + +B ;r7diikk : : :D <<  D ;;uf; - -D eArll_ D :D HHJJ 3 3AGAsOOEAw{E!H&)++E222DD   dQh##%%$ "$$ $ ;s9 4AA $B00CC2F  F?#F::F?)NNN)rNN)NNNN)rNNN)#__doc__r functoolsrr8rr numpy.corer__all__partialarray_function_dispatchrr7rrrrr$r<rFrMrQrrerjr rrrrrrrrrrrrs| = = =+)+ %g777 000%%%*---.1110AAA,'''T   F...<)))X!0- /)- /-"355*!!!<===4[[[|   899GGG:9GV9= .//NNN0/NbDH$(011jjj21jjjr