ó 2ÄÈ[c@`sTdZddlmZmZmZddlZddlZddlZddl m Z dddgZ e Z d„Zd „Zd „Zd „Zd „Zd „Zd„Zied6ed6ed6ed6ed6ed6ed6Zd„Zd„Zd„Zd„Zd„Zdddd„Zdddddd„Zdddddd„ZdS(s Histogram-related functions i(tdivisiontabsolute_importtprint_functionN(t basestringt histogramt histogramddthistogram_bin_edgescC`s|jƒtj|jƒS(s~ 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. (tptptnptsqrttsize(tx((s3/tmp/pip-build-fiC0ax/numpy/numpy/lib/histograms.pyt_hist_bin_sqrtscC`s|jƒtj|jƒdS(s 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. gð?(RRtlog2R (R ((s3/tmp/pip-build-fiC0ax/numpy/numpy/lib/histograms.pyt_hist_bin_sturges'scC`s|jƒd|jdS(sI 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. g@gð?igUUUUUUÕ?(RR (R ((s3/tmp/pip-build-fiC0ax/numpy/numpy/lib/histograms.pyt_hist_bin_rice=scC`s'dtjd|jdtj|ƒS(s² 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@gà?gð?g@gUUUUUUÕ?(RtpiR tstd(R ((s3/tmp/pip-build-fiC0ax/numpy/numpy/lib/histograms.pyt_hist_bin_scottTscC`så|jdkrátjd|jd|jd|jdƒ}tj|ƒ}|dkrá|tj|ƒ}tj|||ƒtj|d|ƒtj|ƒ}|jƒdtj|jƒtjdtj |ƒ|ƒSndS(s¼ 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. ig@gð?ig( R RR Rtmeant true_dividetpowerRR tabsolute(R tsg1tsigmattemptg1((s3/tmp/pip-build-fiC0ax/numpy/numpy/lib/histograms.pyt_hist_bin_doaneis0 #cC`s4tjtj|ddgƒŒ}d||jdS(sB 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 1 for the number of bins. 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. iKig@gð¿g@gUUUUUUÕ¿(Rtsubtractt percentileR (R tiqr((s3/tmp/pip-build-fiC0ax/numpy/numpy/lib/histograms.pyt _hist_bin_fd‹s!cC`s3t|ƒ}t|ƒ}|r+t||ƒS|SdS(sä Histogram bin estimator that uses the minimum width of the Freedman-Diaconis and Sturges estimators if the FD bandwidth is non zero and the Sturges estimator if the FD bandwidth is 0. 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 N(RRtmin(R tfd_bwt sturges_bw((s3/tmp/pip-build-fiC0ax/numpy/numpy/lib/histograms.pyt_hist_bin_auto¨s "   tautotdoanetfdtricetscottR tsturgescC`sptj|ƒ}|dk rZtj|ƒ}|j|jkrKtdƒ‚n|jƒ}n|jƒ}||fS(s: Check a and weights have matching shapes, and ravel both s(weights should have the same shape as a.N(RtasarraytNonetshapet ValueErrortravel(tatweights((s3/tmp/pip-build-fiC0ax/numpy/numpy/lib/histograms.pyt_ravel_and_check_weightsÜs   cC`s |dk ro|\}}||kr3tdƒ‚ntj|ƒoNtj|ƒsßtdj||ƒƒ‚qßnp|jdkrd\}}nR|jƒ|jƒ}}tj|ƒoÁtj|ƒsßtdj||ƒƒ‚n||kr|d}|d}n||fS( s^ Determine the outer bin edges to use, from either the data or the range argument s/max must be larger than min in range parameter.s(supplied range of [{}, {}] is not finiteiis,autodetected range of [{}, {}] is not finitegà?N(ii(R+R-RtisfinitetformatR R tmax(R/tranget first_edget last_edge((s3/tmp/pip-build-fiC0ax/numpy/numpy/lib/histograms.pyt_get_outer_edgesés$       cC`s±itjtj6tjtj6tjtj6tjtj6tj tj 6}tj ||ƒ}y||j }Wn$t k rtj||d|ƒSXtj||ddd|ƒSdS(s¶ 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 tdtypetcastingtunsafeN(Rtubytetbytetushorttshorttuintctintctuinttint_t ulonglongtlonglongt result_typettypetKeyErrorR(R/tbtsigned_to_unsignedtdt((s3/tmp/pip-build-fiC0ax/numpy/numpy/lib/histograms.pyt_unsigned_subtracts     c C`s†d }d }t|tƒr|}|tkrEtdj|ƒƒ‚n|d k r`tdƒ‚nt||ƒ\}}|d k r¿||k} | ||kM} tj j | ƒs¿|| }q¿n|j dkr×d}qõt||ƒ} | rt tj t||ƒ| ƒƒ}qõd}nÚtj|ƒdkr–ytj|ƒ}Wntk rbtdƒ‚nX|dkr~tdƒ‚nt||ƒ\}}n_tj|ƒdkrétj|ƒ}tj|d |dkƒrõtdƒ‚qõn td ƒ‚|d k rxtj|||ƒ} tj| tjƒr@tj| tƒ} ntj|||dd td | ƒ}||||ffS|d fSd S( s Computes the bins used internally by `histogram`. Parameters ========== a : ndarray Ravelled data array bins, range Forwarded arguments from `histogram`. weights : ndarray, optional Ravelled weights array, or None Returns ======= bin_edges : ndarray Array of bin edges uniform_bins : (Number, Number, int): The upper bound, lowerbound, and number of bins, used in the optimized implementation of `histogram` that works on uniform bins. s({!r} is not a valid estimator for `bins`sMAutomated estimation of the number of bins is not supported for weighted dataiis0`bins` must be an integer, a string, or an arrays(`bins` must be positive, when an integeriÿÿÿÿs1`bins` must increase monotonically, when an arrays `bins` must be 1d, when an arraytendpointR9N(R+t isinstanceRt_hist_bin_selectorsR-R3t TypeErrorR8Rt logical_andtreduceR tinttceilRLtndimtoperatortindexR*tanyRFt issubdtypetintegertfloattlinspacetTrue( R/tbinsR5R0t n_equal_binst bin_edgestbin_nameR6R7tkeeptwidthtbin_type((s3/tmp/pip-build-fiC0ax/numpy/numpy/lib/histograms.pyt_get_bin_edges!sZ     %      cC`s3tj|j|d dƒ|j|ddƒfƒS(s  Like `searchsorted`, but where the last item in `v` is placed on the right. In the context of a histogram, this makes the last bin edge inclusive iÿÿÿÿtlefttright(Rt concatenatet searchsorted(R/tv((s3/tmp/pip-build-fiC0ax/numpy/numpy/lib/histograms.pyt_search_sorted_inclusivesi cC`s4t||ƒ\}}t||||ƒ\}}|S(s 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 that takes into account data variability and data size. '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))``. '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}(1 + \frac{|g_1|}{\sigma_{g_1}}) g_1 = mean[(\frac{x - \mu}{\sigma})^3] \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; hist1 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. ]) (R1Re(R/R^R5R0R`t_((s3/tmp/pip-build-fiC0ax/numpy/numpy/lib/histograms.pyR‹s½c C`sít||ƒ\}}t||||ƒ\}}|dkrQtjtjƒ}n |j}d} |dkp–tj|jtjƒp–tj|jtƒ} |dk r½| r½|\} } } tj | |ƒ}| t | | ƒ}xt dt |ƒ| ƒD]¾}|||| !}|dkr$d}n|||| !}|| k}||| kM}tj j|ƒs‰||}|dk r‰||}q‰n|j|jdtƒ}t || ƒ|}|jtjƒ}||| kcd8<|||k}||cd8<|||dk|| dk@}||cd7<|jdkrŽ|jtj|d|jd| ƒ7_|jtj|d|jd| ƒ7_qø|tj|d|d| ƒj|ƒ7}qøWn8tj |j|ƒ}|dkr1xt dt |ƒ| ƒD]3}tj|||| !ƒ}|t||ƒ7}q÷Wnµtj dd|ƒ}xt dt |ƒ| ƒD]ƒ}|||| !}|||| !}tj|ƒ}||}||}tj||jƒfƒ}t||ƒ}|||7}q_Wtj|ƒ}|dk r/|dk r&tjd td d ƒnd}n|rhtjtj|ƒt ƒ}|||j!ƒ|fS|rºtjd tj"d d ƒtjtj|ƒt ƒ}|||j!ƒ|fS|dk rßtjd td d ƒn||fSdS(s¾ Compute the histogram of a set of data. 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. .. versionadded:: 1.11.0 If `bins` is a string, it defines the method used to calculate the optimal bin width, as defined by `histogram_bin_edges`. 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. normed : bool, optional .. deprecated:: 1.6.0 This is equivalent to the `density` argument, but produces incorrect results for unequal bin widths. It should not be used. .. versionchanged:: 1.15.0 DeprecationWarnings are actually emitted. 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). If `density` is True, the weights are normalized, so that the integral of the density over the range remains 1. density : bool, optional If ``False``, the result will contain the number of samples in each bin. If ``True``, the result is the value of the probability *density* function at the bin, normalized such that the *integral* over the range is 1. Note that the sum of the histogram values will not be equal to 1 unless bins of unity width are chosen; it is not a probability *mass* function. Overrides the ``normed`` keyword if given. Returns ------- hist : array The values of the histogram. See `density` and `weights` for a description of the possible semantics. bin_edges : array of dtype float Return the bin edges ``(length(hist)+1)``. See Also -------- histogramdd, bincount, searchsorted, digitize, histogram_bin_edges Notes ----- All but the last (righthand-most) bin is half-open. In other words, if `bins` is:: [1, 2, 3, 4] then the first bin is ``[1, 2)`` (including 1, but excluding 2) and the second ``[2, 3)``. The last bin, however, is ``[3, 4]``, which *includes* 4. Examples -------- >>> 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") >>> plt.show() iitcopyitcR0t minlengthR9shThe normed argument is ignored when density is provided. In future passing both will result in an error.t stacklevelis@Passing `normed=True` on non-uniform bins has always been broken, and computes neither the probability density function nor the probability mass function. The result is only correct if the bins are uniform, when density=True will produce the same result anyway. The argument will be removed in a future version of numpy.sePassing normed=False is deprecated, and has no effect. Consider passing the density argument instead.N(#R1ReR+RR9tintptcan_casttdoubletcomplextzerosRLt_rangetlenRQRRtastypetFalsetkindtrealtbincounttimagR,tsortRktargsortRhtcumsumtdifftwarningstwarntDeprecationWarningtarrayR[tsumtVisibleDeprecationWarning( R/R^R5tnormedR0tdensityR`t uniform_binstntypetBLOCKtsimple_weightsR6R7R_tntnormtittmp_attmp_wRbt f_indicestindicest decrementt incrementtcum_ntsatzerot sorting_indextswtcwt bin_indextdb((s3/tmp/pip-build-fiC0ax/numpy/numpy/lib/histograms.pyRMs˜o                c`sGyˆj\}}Wn8ttfk rMtjˆƒj‰ˆj\}}nXtj|tƒ}|dg‰|dg} |dk r˜tj |ƒ}ny+t |ƒ} | |krÂtdƒ‚nWnt k rã||g}nX|dkrýd|}n!t |ƒ|krtdƒ‚nxVt |ƒD]H} tj || ƒdkr¿|| dkrrtdj| ƒƒ‚ntˆdd…| f|| ƒ\} } tj| | || dƒˆ| } ˆdd…| fˆ| dk}|| |cd8>> 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) sFThe dimension of bins must be equal to the dimension of the sample x.s0range argument must have one entry per dimensioniis,`bins[{}]` must be positive, when an integerNiÿÿÿÿs:`bins[{}]` must be monotonically increasing, when an arrays'`bins[{}]` must be a scalar or 1d arrayc3`s;|]1}tjˆ|ˆdd…|fddƒVqdS(NtsideRg(RRi(t.0R(tedgestsample(s3/tmp/pip-build-fiC0ax/numpy/numpy/lib/histograms.pys ÄsRoR:tsafes*Cannot specify both 'normed' and 'density'isInternal Shape Error(N(R,tAttributeErrorR-Rt atleast_2dtTtemptyRSR+R*RwRPRvRUR3R8R\RXRttupletravel_multi_indexR|tprodtreshapeRxR[tsliceRyR†tonest RuntimeError(R¢R^R5RˆR0R‰tNtDtnbintdedgestMRtsmintsmaxtNcountton_edgetxythisttcoretsR,((R¡R¢s3/tmp/pip-build-fiC0ax/numpy/numpy/lib/histograms.pyRIs†E        )$%$          (t__doc__t __future__RRRRVR‚tnumpyRtnumpy.compat.py3kRt__all__R5RvR RRRRRR#ROR1R8RLReRkR+RRR(((s3/tmp/pip-build-fiC0ax/numpy/numpy/lib/histograms.pyts>        "  +     ^   û