U C^ @sTdZddlmZmZmZddlZddlZddlZddlZddl Z ddl m Z ddl mZdddgZejejd d ZeZd d Zd dZddZddZddZddZddZddZddZeeeeeeeedZddZd d!Zd"d#Z d$d%Z!d&d'Z"d2d(d)Z#ee#d3d+dZ$d4d,d-Z%ee%d5d.dZ&d6d/d0Z'ee'd7d1dZ(dS)8z Histogram-related functions )divisionabsolute_importprint_functionN) basestring) overrides histogram histogramddhistogram_bin_edgesnumpy)modulecCst||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)xr7/tmp/pip-install-6_kvzl1k/numpy/numpy/lib/histograms.py_ptpsrcCs~t|t|jS)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. )rnpsqrtsizerrangerrr_hist_bin_sqrt#srcCs~t|t|jdS)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. ?)rrlog2rrrrr_hist_bin_sturges8srcCs~t|d|jdS)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?)rrrrrr_hist_bin_riceOsrcCs$~dtjd|jdt|S)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)rpirstdrrrr_hist_bin_scottgsr"cs~jtdksdkr"dSfdd}tdtt}ttd|d|d}||krvtj dt dd |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. rcs:|}tj|dd}dd|||S)N)binsrrr#)rrdot)nbinshhZp_knZptp_xrrrrjhatsz_hist_bin_stone..jhatd)keyz/The number of bins estimated may be suboptimal. stacklevel) rrr intrrr_rangewarningswarnRuntimeWarning)rrr+Znbins_upper_boundr'rr)r_hist_bin_stone}sr6cCs~|jdkrtd|jd|jd|jd}t|}|dkr|t|}t|||t|d|t|}t|dt|jtdt ||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@rr.g) rrrr!ZmeanZ true_dividepowerrrZabsolute)rrZsg1sigmatempZg1rrr_hist_bin_doanes (  r:cCs*~tjt|ddg}d||jdS)aB 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. KrgUUUUUUտ)rsubtractZ percentiler)rrZiqrrrr _hist_bin_fdsr>cCs,t||}t||}~|r$t||S|SdS)a 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)r>rr)rrZfd_bwZ sturges_bwrrr_hist_bin_autos "   r?)ZstoneautoZdoanefdZriceZscottrZsturgescCs|t|}|jtjkr>tjd|jtjtdd| tj}|dk rlt|}|j |j krdt d| }| }||fS)z: Check a and weights have matching shapes, and ravel both z1Converting input from {} to {} for compatibility.r.r/Nz(weights should have the same shape as a.) rasarraydtypeZbool_r3r4formatZuint8r5astypeshape ValueErrorZravel)aweightsrrr_ravel_and_check_weightss&     rJcCs|dk rF|\}}||kr tdt|r4t|std||nJ|jdkrZd\}}n6||}}t|rt|std||||kr|d}|d}||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)rGrisfiniterDrrr )rHr first_edge last_edgerrr_get_outer_edges3s*    rNc Cstjtjtjtjtjtjtjtjtj tj i}t ||}z||j }Wn$t k rjtj|||dYSXtj||d|dSdS)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 rCZunsafe)castingrCN)rbyteZubyteshortZushortZintcZuintcint_ZuintZlonglongZ ulonglong result_typetypeKeyErrorr=)rHbZsigned_to_unsigneddtrrrr Qs"  r c Csd}d}t|tr|}|tkr,td||dk r>> 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. ]) )rJrk)rHr$rrIrh_rrrr sFcCs |||fSrrr)rHr$rnormedrIdensityrrr_histogram_dispatchersrxc Cst||\}}t||||\}}|dkr6ttj}n|j}d} |dkpdt|jtjpdt|jt} |dk r| r|\} } } t| |}| t | | }t dt || D]T}|||| }|dkrd}n|||| }|| k}||| kM}tj |s||}|dk r||}|j|jdd}t || |}|tj}||| kd8<|||k}||d8<|||dk|| dk@}||d7<|jdkr|jtj||j| d7_|jtj||j| d7_q|tj||| d|7}qnt|j|}|dkrZt dt || D]*}t|||| }|t||7}q,ntjd|d }t dt || D]h}|||| }|||| }t|}||}||}t||f}t||}|||7}qxt|}|dk r|dk rtjd td d d}|r@tt|t}||||fS|r~tjd tj d d tt|t}||||fS|dk rtjdtd d ||fSdS)a 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 a monotonically increasing array of 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") Text(0.5, 1.0, "Histogram with 'auto' bins") >>> plt.show() NirF)copyr#c)rI minlengthrOzhThe normed argument is ignored when density is provided. In future passing both will result in an error.r.r/a@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.zePassing normed=False is deprecated, and has no effect. Consider passing the density argument instead.)!rJrkrrCZintpZcan_castdoublecomplexzerosr r2lenr]r^rEkindrealbincountimagrFsortrqZargsortrnZcumsumdiffr3r4DeprecationWarningarrayresumZVisibleDeprecationWarning) rHr$rrvrIrwrhZ uniform_binsZntypeZBLOCKZsimple_weightsrLrMrgr*ZnormiZtmp_aZtmp_wriZ f_indicesindicesZ decrement incrementZcum_nsaZzeroZ sorting_indexswZcwZ bin_indexdbrrrrsq                     c csFt|dr|Vn |EdHtt|EdHW5QRX|VdS)NrF)hasattr contextlibsuppressr\)sampler$rrvrIrwrrr_histogramdd_dispatchers    rc s4zj\}}Wn.ttfk r<tjj\}}YnXt|t}|dg|dg} |dk rpt|}zt |} | |krtdWnt k r||g}YnX|dkrd|}nt ||krtdt |D]} t || dkrJ|| dkrtd | tdd| f|| \} } t| | || d| <nlt || dkrt|| | <t| dd| ddkrtd | ntd | t | d|| <t| | | <qtfd d t |D}t |D]6} dd| f| dk}|| |d8<qt||}tj|||d }||}|jtdd}|tddf}||}|dkr|dkrd}n|dkr|}nt d|r|}t |D]4} t|t}|| d|| <|| | |}q||}|j|dkr,td|fS)a9 Compute the multidimensional histogram of some data. Parameters ---------- sample : (N, D) array, or (D, N) 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 ``histogramgramdd(np.array([p1, p2, p3]))``. * When an array_like, each element is the list of values for single coordinate - such as ``histogramgramdd((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``. normed : bool, optional An alias for the density argument that behaves identically. To avoid confusion with the broken normed argument to `histogram`, `density` should be preferred. 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 normed is True. If normed 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 normed 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) NzFThe dimension of bins must be equal to the dimension of the sample x.rrz0range argument must have one entry per dimensionrr#z,`bins[{}]` must be positive, when an integerrYz:`bins[{}]` must be monotonically increasing, when an arrayz'`bins[{}]` must be a scalar or 1d arrayc3s.|]&}tj|dd|fddVqdS)Nrm)Zside)rro).0redgesrrr ,szhistogramdd..)r{safe)rPFz*Cannot specify both 'normed' and 'density'r%zInternal Shape Error)rFAttributeErrorrGrZ atleast_2dTemptyr1rBrr\r2r`rDrNrfrcrtupleZravel_multi_indexrprodZreshaperEreslicerZones RuntimeError)rr$rrvrIrwNDZnbinZdedgesMrZsminZsmaxZNcountZon_edgeZxyhistcoresrFrrrrsG       (        )NNN)rtNN)NNNNN)rtNNNN)NNNNN)rtNNNN))__doc__ __future__rrrr functoolsrar3r rZnumpy.compat.py3krZ numpy.corer__all__partialZarray_function_dispatchrr2rrrrr"r6r:r>r?r[rJrNr rkrqrsr rxrrrrrrrsx    *#, ^  K  ~