_histograms_impl.py 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085
  1. """
  2. Histogram-related functions
  3. """
  4. import contextlib
  5. import functools
  6. import operator
  7. import warnings
  8. import numpy as np
  9. from numpy._core import overrides
  10. __all__ = ['histogram', 'histogramdd', 'histogram_bin_edges']
  11. array_function_dispatch = functools.partial(
  12. overrides.array_function_dispatch, module='numpy')
  13. # range is a keyword argument to many functions, so save the builtin so they can
  14. # use it.
  15. _range = range
  16. def _ptp(x):
  17. """Peak-to-peak value of x.
  18. This implementation avoids the problem of signed integer arrays having a
  19. peak-to-peak value that cannot be represented with the array's data type.
  20. This function returns an unsigned value for signed integer arrays.
  21. """
  22. return _unsigned_subtract(x.max(), x.min())
  23. def _hist_bin_sqrt(x, range):
  24. """
  25. Square root histogram bin estimator.
  26. Bin width is inversely proportional to the data size. Used by many
  27. programs for its simplicity.
  28. Parameters
  29. ----------
  30. x : array_like
  31. Input data that is to be histogrammed, trimmed to range. May not
  32. be empty.
  33. Returns
  34. -------
  35. h : An estimate of the optimal bin width for the given data.
  36. """
  37. del range # unused
  38. return _ptp(x) / np.sqrt(x.size)
  39. def _hist_bin_sturges(x, range):
  40. """
  41. Sturges histogram bin estimator.
  42. A very simplistic estimator based on the assumption of normality of
  43. the data. This estimator has poor performance for non-normal data,
  44. which becomes especially obvious for large data sets. The estimate
  45. depends only on size of the data.
  46. Parameters
  47. ----------
  48. x : array_like
  49. Input data that is to be histogrammed, trimmed to range. May not
  50. be empty.
  51. Returns
  52. -------
  53. h : An estimate of the optimal bin width for the given data.
  54. """
  55. del range # unused
  56. return _ptp(x) / (np.log2(x.size) + 1.0)
  57. def _hist_bin_rice(x, range):
  58. """
  59. Rice histogram bin estimator.
  60. Another simple estimator with no normality assumption. It has better
  61. performance for large data than Sturges, but tends to overestimate
  62. the number of bins. The number of bins is proportional to the cube
  63. root of data size (asymptotically optimal). The estimate depends
  64. only on size of the data.
  65. Parameters
  66. ----------
  67. x : array_like
  68. Input data that is to be histogrammed, trimmed to range. May not
  69. be empty.
  70. Returns
  71. -------
  72. h : An estimate of the optimal bin width for the given data.
  73. """
  74. del range # unused
  75. return _ptp(x) / (2.0 * x.size ** (1.0 / 3))
  76. def _hist_bin_scott(x, range):
  77. """
  78. Scott histogram bin estimator.
  79. The binwidth is proportional to the standard deviation of the data
  80. and inversely proportional to the cube root of data size
  81. (asymptotically optimal).
  82. Parameters
  83. ----------
  84. x : array_like
  85. Input data that is to be histogrammed, trimmed to range. May not
  86. be empty.
  87. Returns
  88. -------
  89. h : An estimate of the optimal bin width for the given data.
  90. """
  91. del range # unused
  92. return (24.0 * np.pi**0.5 / x.size)**(1.0 / 3.0) * np.std(x)
  93. def _hist_bin_stone(x, range):
  94. """
  95. Histogram bin estimator based on minimizing the estimated integrated squared error (ISE).
  96. The number of bins is chosen by minimizing the estimated ISE against the unknown
  97. true distribution. The ISE is estimated using cross-validation and can be regarded
  98. as a generalization of Scott's rule.
  99. https://en.wikipedia.org/wiki/Histogram#Scott.27s_normal_reference_rule
  100. This paper by Stone appears to be the origination of this rule.
  101. https://digitalassets.lib.berkeley.edu/sdtr/ucb/text/34.pdf
  102. Parameters
  103. ----------
  104. x : array_like
  105. Input data that is to be histogrammed, trimmed to range. May not
  106. be empty.
  107. range : (float, float)
  108. The lower and upper range of the bins.
  109. Returns
  110. -------
  111. h : An estimate of the optimal bin width for the given data.
  112. """ # noqa: E501
  113. n = x.size
  114. ptp_x = _ptp(x)
  115. if n <= 1 or ptp_x == 0:
  116. return 0
  117. def jhat(nbins):
  118. hh = ptp_x / nbins
  119. p_k = np.histogram(x, bins=nbins, range=range)[0] / n
  120. return (2 - (n + 1) * p_k.dot(p_k)) / hh
  121. nbins_upper_bound = max(100, int(np.sqrt(n)))
  122. nbins = min(_range(1, nbins_upper_bound + 1), key=jhat)
  123. if nbins == nbins_upper_bound:
  124. warnings.warn("The number of bins estimated may be suboptimal.",
  125. RuntimeWarning, stacklevel=3)
  126. return ptp_x / nbins
  127. def _hist_bin_doane(x, range):
  128. """
  129. Doane's histogram bin estimator.
  130. Improved version of Sturges' formula which works better for
  131. non-normal data. See
  132. stats.stackexchange.com/questions/55134/doanes-formula-for-histogram-binning
  133. Parameters
  134. ----------
  135. x : array_like
  136. Input data that is to be histogrammed, trimmed to range. May not
  137. be empty.
  138. Returns
  139. -------
  140. h : An estimate of the optimal bin width for the given data.
  141. """
  142. del range # unused
  143. if x.size > 2:
  144. sg1 = np.sqrt(6.0 * (x.size - 2) / ((x.size + 1.0) * (x.size + 3)))
  145. sigma = np.std(x)
  146. if sigma > 0.0:
  147. # These three operations add up to
  148. # g1 = np.mean(((x - np.mean(x)) / sigma)**3)
  149. # but use only one temp array instead of three
  150. temp = x - np.mean(x)
  151. np.true_divide(temp, sigma, temp)
  152. np.power(temp, 3, temp)
  153. g1 = np.mean(temp)
  154. return _ptp(x) / (1.0 + np.log2(x.size) +
  155. np.log2(1.0 + np.absolute(g1) / sg1))
  156. return 0.0
  157. def _hist_bin_fd(x, range):
  158. """
  159. The Freedman-Diaconis histogram bin estimator.
  160. The Freedman-Diaconis rule uses interquartile range (IQR) to
  161. estimate binwidth. It is considered a variation of the Scott rule
  162. with more robustness as the IQR is less affected by outliers than
  163. the standard deviation. However, the IQR depends on fewer points
  164. than the standard deviation, so it is less accurate, especially for
  165. long tailed distributions.
  166. If the IQR is 0, this function returns 0 for the bin width.
  167. Binwidth is inversely proportional to the cube root of data size
  168. (asymptotically optimal).
  169. Parameters
  170. ----------
  171. x : array_like
  172. Input data that is to be histogrammed, trimmed to range. May not
  173. be empty.
  174. Returns
  175. -------
  176. h : An estimate of the optimal bin width for the given data.
  177. """
  178. del range # unused
  179. iqr = np.subtract(*np.percentile(x, [75, 25]))
  180. return 2.0 * iqr * x.size ** (-1.0 / 3.0)
  181. def _hist_bin_auto(x, range):
  182. """
  183. Histogram bin estimator that uses the minimum width of a relaxed
  184. Freedman-Diaconis and Sturges estimators if the FD bin width does
  185. not result in a large number of bins. The relaxed Freedman-Diaconis estimator
  186. limits the bin width to half the sqrt estimated to avoid small bins.
  187. The FD estimator is usually the most robust method, but its width
  188. estimate tends to be too large for small `x` and bad for data with limited
  189. variance. The Sturges estimator is quite good for small (<1000) datasets
  190. and is the default in the R language. This method gives good off-the-shelf
  191. behaviour.
  192. Parameters
  193. ----------
  194. x : array_like
  195. Input data that is to be histogrammed, trimmed to range. May not
  196. be empty.
  197. range : Tuple with range for the histogram
  198. Returns
  199. -------
  200. h : An estimate of the optimal bin width for the given data.
  201. See Also
  202. --------
  203. _hist_bin_fd, _hist_bin_sturges
  204. """
  205. fd_bw = _hist_bin_fd(x, range)
  206. sturges_bw = _hist_bin_sturges(x, range)
  207. sqrt_bw = _hist_bin_sqrt(x, range)
  208. # heuristic to limit the maximal number of bins
  209. fd_bw_corrected = max(fd_bw, sqrt_bw / 2)
  210. return min(fd_bw_corrected, sturges_bw)
  211. # Private dict initialized at module load time
  212. _hist_bin_selectors = {'stone': _hist_bin_stone,
  213. 'auto': _hist_bin_auto,
  214. 'doane': _hist_bin_doane,
  215. 'fd': _hist_bin_fd,
  216. 'rice': _hist_bin_rice,
  217. 'scott': _hist_bin_scott,
  218. 'sqrt': _hist_bin_sqrt,
  219. 'sturges': _hist_bin_sturges}
  220. def _ravel_and_check_weights(a, weights):
  221. """ Check a and weights have matching shapes, and ravel both """
  222. a = np.asarray(a)
  223. # Ensure that the array is a "subtractable" dtype
  224. if a.dtype == np.bool:
  225. msg = f"Converting input from {a.dtype} to {np.uint8} for compatibility."
  226. warnings.warn(msg, RuntimeWarning, stacklevel=3)
  227. a = a.astype(np.uint8)
  228. if weights is not None:
  229. weights = np.asarray(weights)
  230. if weights.shape != a.shape:
  231. raise ValueError(
  232. 'weights should have the same shape as a.')
  233. weights = weights.ravel()
  234. a = a.ravel()
  235. return a, weights
  236. def _get_outer_edges(a, range):
  237. """
  238. Determine the outer bin edges to use, from either the data or the range
  239. argument
  240. """
  241. if range is not None:
  242. first_edge, last_edge = range
  243. if first_edge > last_edge:
  244. raise ValueError(
  245. 'max must be larger than min in range parameter.')
  246. if not (np.isfinite(first_edge) and np.isfinite(last_edge)):
  247. raise ValueError(
  248. f"supplied range of [{first_edge}, {last_edge}] is not finite")
  249. elif a.size == 0:
  250. # handle empty arrays. Can't determine range, so use 0-1.
  251. first_edge, last_edge = 0, 1
  252. else:
  253. first_edge, last_edge = a.min(), a.max()
  254. if not (np.isfinite(first_edge) and np.isfinite(last_edge)):
  255. raise ValueError(
  256. f"autodetected range of [{first_edge}, {last_edge}] is not finite")
  257. # expand empty range to avoid divide by zero
  258. if first_edge == last_edge:
  259. first_edge = first_edge - 0.5
  260. last_edge = last_edge + 0.5
  261. return first_edge, last_edge
  262. def _unsigned_subtract(a, b):
  263. """
  264. Subtract two values where a >= b, and produce an unsigned result
  265. This is needed when finding the difference between the upper and lower
  266. bound of an int16 histogram
  267. """
  268. # coerce to a single type
  269. signed_to_unsigned = {
  270. np.byte: np.ubyte,
  271. np.short: np.ushort,
  272. np.intc: np.uintc,
  273. np.int_: np.uint,
  274. np.longlong: np.ulonglong
  275. }
  276. dt = np.result_type(a, b)
  277. try:
  278. unsigned_dt = signed_to_unsigned[dt.type]
  279. except KeyError:
  280. return np.subtract(a, b, dtype=dt)
  281. else:
  282. # we know the inputs are integers, and we are deliberately casting
  283. # signed to unsigned. The input may be negative python integers so
  284. # ensure we pass in arrays with the initial dtype (related to NEP 50).
  285. return np.subtract(np.asarray(a, dtype=dt), np.asarray(b, dtype=dt),
  286. casting='unsafe', dtype=unsigned_dt)
  287. def _get_bin_edges(a, bins, range, weights):
  288. """
  289. Computes the bins used internally by `histogram`.
  290. Parameters
  291. ==========
  292. a : ndarray
  293. Ravelled data array
  294. bins, range
  295. Forwarded arguments from `histogram`.
  296. weights : ndarray, optional
  297. Ravelled weights array, or None
  298. Returns
  299. =======
  300. bin_edges : ndarray
  301. Array of bin edges
  302. uniform_bins : (Number, Number, int):
  303. The upper bound, lowerbound, and number of bins, used in the optimized
  304. implementation of `histogram` that works on uniform bins.
  305. """
  306. # parse the overloaded bins argument
  307. n_equal_bins = None
  308. bin_edges = None
  309. if isinstance(bins, str):
  310. bin_name = bins
  311. # if `bins` is a string for an automatic method,
  312. # this will replace it with the number of bins calculated
  313. if bin_name not in _hist_bin_selectors:
  314. raise ValueError(
  315. f"{bin_name!r} is not a valid estimator for `bins`")
  316. if weights is not None:
  317. raise TypeError("Automated estimation of the number of "
  318. "bins is not supported for weighted data")
  319. first_edge, last_edge = _get_outer_edges(a, range)
  320. # truncate the range if needed
  321. if range is not None:
  322. keep = (a >= first_edge)
  323. keep &= (a <= last_edge)
  324. if not np.logical_and.reduce(keep):
  325. a = a[keep]
  326. if a.size == 0:
  327. n_equal_bins = 1
  328. else:
  329. # Do not call selectors on empty arrays
  330. width = _hist_bin_selectors[bin_name](a, (first_edge, last_edge))
  331. if width:
  332. if np.issubdtype(a.dtype, np.integer) and width < 1:
  333. width = 1
  334. delta = _unsigned_subtract(last_edge, first_edge)
  335. n_equal_bins = int(np.ceil(delta / width))
  336. else:
  337. # Width can be zero for some estimators, e.g. FD when
  338. # the IQR of the data is zero.
  339. n_equal_bins = 1
  340. elif np.ndim(bins) == 0:
  341. try:
  342. n_equal_bins = operator.index(bins)
  343. except TypeError as e:
  344. raise TypeError(
  345. '`bins` must be an integer, a string, or an array') from e
  346. if n_equal_bins < 1:
  347. raise ValueError('`bins` must be positive, when an integer')
  348. first_edge, last_edge = _get_outer_edges(a, range)
  349. elif np.ndim(bins) == 1:
  350. bin_edges = np.asarray(bins)
  351. if np.any(bin_edges[:-1] > bin_edges[1:]):
  352. raise ValueError(
  353. '`bins` must increase monotonically, when an array')
  354. else:
  355. raise ValueError('`bins` must be 1d, when an array')
  356. if n_equal_bins is not None:
  357. # gh-10322 means that type resolution rules are dependent on array
  358. # shapes. To avoid this causing problems, we pick a type now and stick
  359. # with it throughout.
  360. bin_type = np.result_type(first_edge, last_edge, a)
  361. if np.issubdtype(bin_type, np.integer):
  362. bin_type = np.result_type(bin_type, float)
  363. # bin edges must be computed
  364. bin_edges = np.linspace(
  365. first_edge, last_edge, n_equal_bins + 1,
  366. endpoint=True, dtype=bin_type)
  367. if np.any(bin_edges[:-1] >= bin_edges[1:]):
  368. raise ValueError(
  369. f'Too many bins for data range. Cannot create {n_equal_bins} '
  370. f'finite-sized bins.')
  371. return bin_edges, (first_edge, last_edge, n_equal_bins)
  372. else:
  373. return bin_edges, None
  374. def _search_sorted_inclusive(a, v):
  375. """
  376. Like `searchsorted`, but where the last item in `v` is placed on the right.
  377. In the context of a histogram, this makes the last bin edge inclusive
  378. """
  379. return np.concatenate((
  380. a.searchsorted(v[:-1], 'left'),
  381. a.searchsorted(v[-1:], 'right')
  382. ))
  383. def _histogram_bin_edges_dispatcher(a, bins=None, range=None, weights=None):
  384. return (a, bins, weights)
  385. @array_function_dispatch(_histogram_bin_edges_dispatcher)
  386. def histogram_bin_edges(a, bins=10, range=None, weights=None):
  387. r"""
  388. Function to calculate only the edges of the bins used by the `histogram`
  389. function.
  390. Parameters
  391. ----------
  392. a : array_like
  393. Input data. The histogram is computed over the flattened array.
  394. bins : int or sequence of scalars or str, optional
  395. If `bins` is an int, it defines the number of equal-width
  396. bins in the given range (10, by default). If `bins` is a
  397. sequence, it defines the bin edges, including the rightmost
  398. edge, allowing for non-uniform bin widths.
  399. If `bins` is a string from the list below, `histogram_bin_edges` will
  400. use the method chosen to calculate the optimal bin width and
  401. consequently the number of bins (see the Notes section for more detail
  402. on the estimators) from the data that falls within the requested range.
  403. While the bin width will be optimal for the actual data
  404. in the range, the number of bins will be computed to fill the
  405. entire range, including the empty portions. For visualisation,
  406. using the 'auto' option is suggested. Weighted data is not
  407. supported for automated bin size selection.
  408. 'auto'
  409. Minimum bin width between the 'sturges' and 'fd' estimators.
  410. Provides good all-around performance.
  411. 'fd' (Freedman Diaconis Estimator)
  412. Robust (resilient to outliers) estimator that takes into
  413. account data variability and data size.
  414. 'doane'
  415. An improved version of Sturges' estimator that works better
  416. with non-normal datasets.
  417. 'scott'
  418. Less robust estimator that takes into account data variability
  419. and data size.
  420. 'stone'
  421. Estimator based on leave-one-out cross-validation estimate of
  422. the integrated squared error. Can be regarded as a generalization
  423. of Scott's rule.
  424. 'rice'
  425. Estimator does not take variability into account, only data
  426. size. Commonly overestimates number of bins required.
  427. 'sturges'
  428. R's default method, only accounts for data size. Only
  429. optimal for gaussian data and underestimates number of bins
  430. for large non-gaussian datasets.
  431. 'sqrt'
  432. Square root (of data size) estimator, used by Excel and
  433. other programs for its speed and simplicity.
  434. range : (float, float), optional
  435. The lower and upper range of the bins. If not provided, range
  436. is simply ``(a.min(), a.max())``. Values outside the range are
  437. ignored. The first element of the range must be less than or
  438. equal to the second. `range` affects the automatic bin
  439. computation as well. While bin width is computed to be optimal
  440. based on the actual data within `range`, the bin count will fill
  441. the entire range including portions containing no data.
  442. weights : array_like, optional
  443. An array of weights, of the same shape as `a`. Each value in
  444. `a` only contributes its associated weight towards the bin count
  445. (instead of 1). This is currently not used by any of the bin estimators,
  446. but may be in the future.
  447. Returns
  448. -------
  449. bin_edges : array of dtype float
  450. The edges to pass into `histogram`
  451. See Also
  452. --------
  453. histogram
  454. Notes
  455. -----
  456. The methods to estimate the optimal number of bins are well founded
  457. in literature, and are inspired by the choices R provides for
  458. histogram visualisation. Note that having the number of bins
  459. proportional to :math:`n^{1/3}` is asymptotically optimal, which is
  460. why it appears in most estimators. These are simply plug-in methods
  461. that give good starting points for number of bins. In the equations
  462. below, :math:`h` is the binwidth and :math:`n_h` is the number of
  463. bins. All estimators that compute bin counts are recast to bin width
  464. using the `ptp` of the data. The final bin count is obtained from
  465. ``np.round(np.ceil(range / h))``. The final bin width is often less
  466. than what is returned by the estimators below.
  467. 'auto' (minimum bin width of the 'sturges' and 'fd' estimators)
  468. A compromise to get a good value. For small datasets the Sturges
  469. value will usually be chosen, while larger datasets will usually
  470. default to FD. Avoids the overly conservative behaviour of FD
  471. and Sturges for small and large datasets respectively.
  472. Switchover point is usually :math:`a.size \approx 1000`.
  473. 'fd' (Freedman Diaconis Estimator)
  474. .. math:: h = 2 \frac{IQR}{n^{1/3}}
  475. The binwidth is proportional to the interquartile range (IQR)
  476. and inversely proportional to cube root of a.size. Can be too
  477. conservative for small datasets, but is quite good for large
  478. datasets. The IQR is very robust to outliers.
  479. 'scott'
  480. .. math:: h = \sigma \sqrt[3]{\frac{24 \sqrt{\pi}}{n}}
  481. The binwidth is proportional to the standard deviation of the
  482. data and inversely proportional to cube root of ``x.size``. Can
  483. be too conservative for small datasets, but is quite good for
  484. large datasets. The standard deviation is not very robust to
  485. outliers. Values are very similar to the Freedman-Diaconis
  486. estimator in the absence of outliers.
  487. 'rice'
  488. .. math:: n_h = 2n^{1/3}
  489. The number of bins is only proportional to cube root of
  490. ``a.size``. It tends to overestimate the number of bins and it
  491. does not take into account data variability.
  492. 'sturges'
  493. .. math:: n_h = \log _{2}(n) + 1
  494. The number of bins is the base 2 log of ``a.size``. This
  495. estimator assumes normality of data and is too conservative for
  496. larger, non-normal datasets. This is the default method in R's
  497. ``hist`` method.
  498. 'doane'
  499. .. math:: n_h = 1 + \log_{2}(n) +
  500. \log_{2}\left(1 + \frac{|g_1|}{\sigma_{g_1}}\right)
  501. g_1 = mean\left[\left(\frac{x - \mu}{\sigma}\right)^3\right]
  502. \sigma_{g_1} = \sqrt{\frac{6(n - 2)}{(n + 1)(n + 3)}}
  503. An improved version of Sturges' formula that produces better
  504. estimates for non-normal datasets. This estimator attempts to
  505. account for the skew of the data.
  506. 'sqrt'
  507. .. math:: n_h = \sqrt n
  508. The simplest and fastest estimator. Only takes into account the
  509. data size.
  510. Additionally, if the data is of integer dtype, then the binwidth will never
  511. be less than 1.
  512. Examples
  513. --------
  514. >>> import numpy as np
  515. >>> arr = np.array([0, 0, 0, 1, 2, 3, 3, 4, 5])
  516. >>> np.histogram_bin_edges(arr, bins='auto', range=(0, 1))
  517. array([0. , 0.25, 0.5 , 0.75, 1. ])
  518. >>> np.histogram_bin_edges(arr, bins=2)
  519. array([0. , 2.5, 5. ])
  520. For consistency with histogram, an array of pre-computed bins is
  521. passed through unmodified:
  522. >>> np.histogram_bin_edges(arr, [1, 2])
  523. array([1, 2])
  524. This function allows one set of bins to be computed, and reused across
  525. multiple histograms:
  526. >>> shared_bins = np.histogram_bin_edges(arr, bins='auto')
  527. >>> shared_bins
  528. array([0., 1., 2., 3., 4., 5.])
  529. >>> group_id = np.array([0, 1, 1, 0, 1, 1, 0, 1, 1])
  530. >>> hist_0, _ = np.histogram(arr[group_id == 0], bins=shared_bins)
  531. >>> hist_1, _ = np.histogram(arr[group_id == 1], bins=shared_bins)
  532. >>> hist_0; hist_1
  533. array([1, 1, 0, 1, 0])
  534. array([2, 0, 1, 1, 2])
  535. Which gives more easily comparable results than using separate bins for
  536. each histogram:
  537. >>> hist_0, bins_0 = np.histogram(arr[group_id == 0], bins='auto')
  538. >>> hist_1, bins_1 = np.histogram(arr[group_id == 1], bins='auto')
  539. >>> hist_0; hist_1
  540. array([1, 1, 1])
  541. array([2, 1, 1, 2])
  542. >>> bins_0; bins_1
  543. array([0., 1., 2., 3.])
  544. array([0. , 1.25, 2.5 , 3.75, 5. ])
  545. """
  546. a, weights = _ravel_and_check_weights(a, weights)
  547. bin_edges, _ = _get_bin_edges(a, bins, range, weights)
  548. return bin_edges
  549. def _histogram_dispatcher(
  550. a, bins=None, range=None, density=None, weights=None):
  551. return (a, bins, weights)
  552. @array_function_dispatch(_histogram_dispatcher)
  553. def histogram(a, bins=10, range=None, density=None, weights=None):
  554. r"""
  555. Compute the histogram of a dataset.
  556. Parameters
  557. ----------
  558. a : array_like
  559. Input data. The histogram is computed over the flattened array.
  560. bins : int or sequence of scalars or str, optional
  561. If `bins` is an int, it defines the number of equal-width
  562. bins in the given range (10, by default). If `bins` is a
  563. sequence, it defines a monotonically increasing array of bin edges,
  564. including the rightmost edge, allowing for non-uniform bin widths.
  565. If `bins` is a string, it defines the method used to calculate the
  566. optimal bin width, as defined by `histogram_bin_edges`.
  567. range : (float, float), optional
  568. The lower and upper range of the bins. If not provided, range
  569. is simply ``(a.min(), a.max())``. Values outside the range are
  570. ignored. The first element of the range must be less than or
  571. equal to the second. `range` affects the automatic bin
  572. computation as well. While bin width is computed to be optimal
  573. based on the actual data within `range`, the bin count will fill
  574. the entire range including portions containing no data.
  575. weights : array_like, optional
  576. An array of weights, of the same shape as `a`. Each value in
  577. `a` only contributes its associated weight towards the bin count
  578. (instead of 1). If `density` is True, the weights are
  579. normalized, so that the integral of the density over the range
  580. remains 1.
  581. Please note that the ``dtype`` of `weights` will also become the
  582. ``dtype`` of the returned accumulator (`hist`), so it must be
  583. large enough to hold accumulated values as well.
  584. density : bool, optional
  585. If ``False``, the result will contain the number of samples in
  586. each bin. If ``True``, the result is the value of the
  587. probability *density* function at the bin, normalized such that
  588. the *integral* over the range is 1. Note that the sum of the
  589. histogram values will not be equal to 1 unless bins of unity
  590. width are chosen; it is not a probability *mass* function.
  591. Returns
  592. -------
  593. hist : array
  594. The values of the histogram. See `density` and `weights` for a
  595. description of the possible semantics. If `weights` are given,
  596. ``hist.dtype`` will be taken from `weights`.
  597. bin_edges : array of dtype float
  598. Return the bin edges ``(length(hist)+1)``.
  599. See Also
  600. --------
  601. histogramdd, bincount, searchsorted, digitize, histogram_bin_edges
  602. Notes
  603. -----
  604. All but the last (righthand-most) bin is half-open. In other words,
  605. if `bins` is::
  606. [1, 2, 3, 4]
  607. then the first bin is ``[1, 2)`` (including 1, but excluding 2) and
  608. the second ``[2, 3)``. The last bin, however, is ``[3, 4]``, which
  609. *includes* 4.
  610. Examples
  611. --------
  612. >>> import numpy as np
  613. >>> np.histogram([1, 2, 1], bins=[0, 1, 2, 3])
  614. (array([0, 2, 1]), array([0, 1, 2, 3]))
  615. >>> np.histogram(np.arange(4), bins=np.arange(5), density=True)
  616. (array([0.25, 0.25, 0.25, 0.25]), array([0, 1, 2, 3, 4]))
  617. >>> np.histogram([[1, 2, 1], [1, 0, 1]], bins=[0,1,2,3])
  618. (array([1, 4, 1]), array([0, 1, 2, 3]))
  619. >>> a = np.arange(5)
  620. >>> hist, bin_edges = np.histogram(a, density=True)
  621. >>> hist
  622. array([0.5, 0. , 0.5, 0. , 0. , 0.5, 0. , 0.5, 0. , 0.5])
  623. >>> hist.sum()
  624. 2.4999999999999996
  625. >>> np.sum(hist * np.diff(bin_edges))
  626. 1.0
  627. Automated Bin Selection Methods example, using 2 peak random data
  628. with 2000 points.
  629. .. plot::
  630. :include-source:
  631. import matplotlib.pyplot as plt
  632. import numpy as np
  633. rng = np.random.RandomState(10) # deterministic random data
  634. a = np.hstack((rng.normal(size=1000),
  635. rng.normal(loc=5, scale=2, size=1000)))
  636. plt.hist(a, bins='auto') # arguments are passed to np.histogram
  637. plt.title("Histogram with 'auto' bins")
  638. plt.show()
  639. """
  640. a, weights = _ravel_and_check_weights(a, weights)
  641. bin_edges, uniform_bins = _get_bin_edges(a, bins, range, weights)
  642. # Histogram is an integer or a float array depending on the weights.
  643. if weights is None:
  644. ntype = np.dtype(np.intp)
  645. else:
  646. ntype = weights.dtype
  647. # We set a block size, as this allows us to iterate over chunks when
  648. # computing histograms, to minimize memory usage.
  649. BLOCK = 65536
  650. # The fast path uses bincount, but that only works for certain types
  651. # of weight
  652. simple_weights = (
  653. weights is None or
  654. np.can_cast(weights.dtype, np.double) or
  655. np.can_cast(weights.dtype, complex)
  656. )
  657. if uniform_bins is not None and simple_weights:
  658. # Fast algorithm for equal bins
  659. # We now convert values of a to bin indices, under the assumption of
  660. # equal bin widths (which is valid here).
  661. first_edge, last_edge, n_equal_bins = uniform_bins
  662. # Initialize empty histogram
  663. n = np.zeros(n_equal_bins, ntype)
  664. # Pre-compute histogram scaling factor
  665. norm_numerator = n_equal_bins
  666. norm_denom = _unsigned_subtract(last_edge, first_edge)
  667. # We iterate over blocks here for two reasons: the first is that for
  668. # large arrays, it is actually faster (for example for a 10^8 array it
  669. # is 2x as fast) and it results in a memory footprint 3x lower in the
  670. # limit of large arrays.
  671. for i in _range(0, len(a), BLOCK):
  672. tmp_a = a[i:i + BLOCK]
  673. if weights is None:
  674. tmp_w = None
  675. else:
  676. tmp_w = weights[i:i + BLOCK]
  677. # Only include values in the right range
  678. keep = (tmp_a >= first_edge)
  679. keep &= (tmp_a <= last_edge)
  680. if not np.logical_and.reduce(keep):
  681. tmp_a = tmp_a[keep]
  682. if tmp_w is not None:
  683. tmp_w = tmp_w[keep]
  684. # This cast ensures no type promotions occur below, which gh-10322
  685. # make unpredictable. Getting it wrong leads to precision errors
  686. # like gh-8123.
  687. tmp_a = tmp_a.astype(bin_edges.dtype, copy=False)
  688. # Compute the bin indices, and for values that lie exactly on
  689. # last_edge we need to subtract one
  690. f_indices = ((_unsigned_subtract(tmp_a, first_edge) / norm_denom)
  691. * norm_numerator)
  692. indices = f_indices.astype(np.intp)
  693. indices[indices == n_equal_bins] -= 1
  694. # The index computation is not guaranteed to give exactly
  695. # consistent results within ~1 ULP of the bin edges.
  696. decrement = tmp_a < bin_edges[indices]
  697. indices[decrement] -= 1
  698. # The last bin includes the right edge. The other bins do not.
  699. increment = ((tmp_a >= bin_edges[indices + 1])
  700. & (indices != n_equal_bins - 1))
  701. indices[increment] += 1
  702. # We now compute the histogram using bincount
  703. if ntype.kind == 'c':
  704. n.real += np.bincount(indices, weights=tmp_w.real,
  705. minlength=n_equal_bins)
  706. n.imag += np.bincount(indices, weights=tmp_w.imag,
  707. minlength=n_equal_bins)
  708. else:
  709. n += np.bincount(indices, weights=tmp_w,
  710. minlength=n_equal_bins).astype(ntype)
  711. else:
  712. # Compute via cumulative histogram
  713. cum_n = np.zeros(bin_edges.shape, ntype)
  714. if weights is None:
  715. for i in _range(0, len(a), BLOCK):
  716. sa = np.sort(a[i:i + BLOCK])
  717. cum_n += _search_sorted_inclusive(sa, bin_edges)
  718. else:
  719. zero = np.zeros(1, dtype=ntype)
  720. for i in _range(0, len(a), BLOCK):
  721. tmp_a = a[i:i + BLOCK]
  722. tmp_w = weights[i:i + BLOCK]
  723. sorting_index = np.argsort(tmp_a)
  724. sa = tmp_a[sorting_index]
  725. sw = tmp_w[sorting_index]
  726. cw = np.concatenate((zero, sw.cumsum()))
  727. bin_index = _search_sorted_inclusive(sa, bin_edges)
  728. cum_n += cw[bin_index]
  729. n = np.diff(cum_n)
  730. if density:
  731. db = np.array(np.diff(bin_edges), float)
  732. return n / db / n.sum(), bin_edges
  733. return n, bin_edges
  734. def _histogramdd_dispatcher(sample, bins=None, range=None, density=None,
  735. weights=None):
  736. if hasattr(sample, 'shape'): # same condition as used in histogramdd
  737. yield sample
  738. else:
  739. yield from sample
  740. with contextlib.suppress(TypeError):
  741. yield from bins
  742. yield weights
  743. @array_function_dispatch(_histogramdd_dispatcher)
  744. def histogramdd(sample, bins=10, range=None, density=None, weights=None):
  745. """
  746. Compute the multidimensional histogram of some data.
  747. Parameters
  748. ----------
  749. sample : (N, D) array, or (N, D) array_like
  750. The data to be histogrammed.
  751. Note the unusual interpretation of sample when an array_like:
  752. * When an array, each row is a coordinate in a D-dimensional space -
  753. such as ``histogramdd(np.array([p1, p2, p3]))``.
  754. * When an array_like, each element is the list of values for single
  755. coordinate - such as ``histogramdd((X, Y, Z))``.
  756. The first form should be preferred.
  757. bins : sequence or int, optional
  758. The bin specification:
  759. * A sequence of arrays describing the monotonically increasing bin
  760. edges along each dimension.
  761. * The number of bins for each dimension (nx, ny, ... =bins)
  762. * The number of bins for all dimensions (nx=ny=...=bins).
  763. range : sequence, optional
  764. A sequence of length D, each an optional (lower, upper) tuple giving
  765. the outer bin edges to be used if the edges are not given explicitly in
  766. `bins`.
  767. An entry of None in the sequence results in the minimum and maximum
  768. values being used for the corresponding dimension.
  769. The default, None, is equivalent to passing a tuple of D None values.
  770. density : bool, optional
  771. If False, the default, returns the number of samples in each bin.
  772. If True, returns the probability *density* function at the bin,
  773. ``bin_count / sample_count / bin_volume``.
  774. weights : (N,) array_like, optional
  775. An array of values `w_i` weighing each sample `(x_i, y_i, z_i, ...)`.
  776. Weights are normalized to 1 if density is True. If density is False,
  777. the values of the returned histogram are equal to the sum of the
  778. weights belonging to the samples falling into each bin.
  779. Returns
  780. -------
  781. H : ndarray
  782. The multidimensional histogram of sample x. See density and weights
  783. for the different possible semantics.
  784. edges : tuple of ndarrays
  785. A tuple of D arrays describing the bin edges for each dimension.
  786. See Also
  787. --------
  788. histogram: 1-D histogram
  789. histogram2d: 2-D histogram
  790. Examples
  791. --------
  792. >>> import numpy as np
  793. >>> rng = np.random.default_rng()
  794. >>> r = rng.normal(size=(100,3))
  795. >>> H, edges = np.histogramdd(r, bins = (5, 8, 4))
  796. >>> H.shape, edges[0].size, edges[1].size, edges[2].size
  797. ((5, 8, 4), 6, 9, 5)
  798. """
  799. try:
  800. # Sample is an ND-array.
  801. N, D = sample.shape
  802. except (AttributeError, ValueError):
  803. # Sample is a sequence of 1D arrays.
  804. sample = np.atleast_2d(sample).T
  805. N, D = sample.shape
  806. nbin = np.empty(D, np.intp)
  807. edges = D * [None]
  808. dedges = D * [None]
  809. if weights is not None:
  810. weights = np.asarray(weights)
  811. try:
  812. M = len(bins)
  813. if M != D:
  814. raise ValueError(
  815. 'The dimension of bins must be equal to the dimension of the '
  816. 'sample x.')
  817. except TypeError:
  818. # bins is an integer
  819. bins = D * [bins]
  820. # normalize the range argument
  821. if range is None:
  822. range = (None,) * D
  823. elif len(range) != D:
  824. raise ValueError('range argument must have one entry per dimension')
  825. # Create edge arrays
  826. for i in _range(D):
  827. if np.ndim(bins[i]) == 0:
  828. if bins[i] < 1:
  829. raise ValueError(
  830. f'`bins[{i}]` must be positive, when an integer')
  831. smin, smax = _get_outer_edges(sample[:, i], range[i])
  832. try:
  833. n = operator.index(bins[i])
  834. except TypeError as e:
  835. raise TypeError(
  836. f"`bins[{i}]` must be an integer, when a scalar"
  837. ) from e
  838. edges[i] = np.linspace(smin, smax, n + 1)
  839. elif np.ndim(bins[i]) == 1:
  840. edges[i] = np.asarray(bins[i])
  841. if np.any(edges[i][:-1] > edges[i][1:]):
  842. raise ValueError(
  843. f'`bins[{i}]` must be monotonically increasing, when an array')
  844. else:
  845. raise ValueError(
  846. f'`bins[{i}]` must be a scalar or 1d array')
  847. nbin[i] = len(edges[i]) + 1 # includes an outlier on each end
  848. dedges[i] = np.diff(edges[i])
  849. # Compute the bin number each sample falls into.
  850. Ncount = tuple(
  851. # avoid np.digitize to work around gh-11022
  852. np.searchsorted(edges[i], sample[:, i], side='right')
  853. for i in _range(D)
  854. )
  855. # Using digitize, values that fall on an edge are put in the right bin.
  856. # For the rightmost bin, we want values equal to the right edge to be
  857. # counted in the last bin, and not as an outlier.
  858. for i in _range(D):
  859. # Find which points are on the rightmost edge.
  860. on_edge = (sample[:, i] == edges[i][-1])
  861. # Shift these points one bin to the left.
  862. Ncount[i][on_edge] -= 1
  863. # Compute the sample indices in the flattened histogram matrix.
  864. # This raises an error if the array is too large.
  865. xy = np.ravel_multi_index(Ncount, nbin)
  866. # Compute the number of repetitions in xy and assign it to the
  867. # flattened histmat.
  868. hist = np.bincount(xy, weights, minlength=nbin.prod())
  869. # Shape into a proper matrix
  870. hist = hist.reshape(nbin)
  871. # This preserves the (bad) behavior observed in gh-7845, for now.
  872. hist = hist.astype(float, casting='safe')
  873. # Remove outliers (indices 0 and -1 for each dimension).
  874. core = D * (slice(1, -1),)
  875. hist = hist[core]
  876. if density:
  877. # calculate the probability density function
  878. s = hist.sum()
  879. for i in _range(D):
  880. shape = np.ones(D, int)
  881. shape[i] = nbin[i] - 2
  882. hist = hist / dedges[i].reshape(shape)
  883. hist /= s
  884. if (hist.shape != nbin - 2).any():
  885. raise RuntimeError(
  886. "Internal Shape Error")
  887. return hist, edges