_binned_statistic.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619
  1. from __future__ import division, print_function, absolute_import
  2. import numpy as np
  3. from scipy._lib.six import callable, xrange
  4. from scipy._lib._numpy_compat import suppress_warnings
  5. from collections import namedtuple
  6. __all__ = ['binned_statistic',
  7. 'binned_statistic_2d',
  8. 'binned_statistic_dd']
  9. BinnedStatisticResult = namedtuple('BinnedStatisticResult',
  10. ('statistic', 'bin_edges', 'binnumber'))
  11. def binned_statistic(x, values, statistic='mean',
  12. bins=10, range=None):
  13. """
  14. Compute a binned statistic for one or more sets of data.
  15. This is a generalization of a histogram function. A histogram divides
  16. the space into bins, and returns the count of the number of points in
  17. each bin. This function allows the computation of the sum, mean, median,
  18. or other statistic of the values (or set of values) within each bin.
  19. Parameters
  20. ----------
  21. x : (N,) array_like
  22. A sequence of values to be binned.
  23. values : (N,) array_like or list of (N,) array_like
  24. The data on which the statistic will be computed. This must be
  25. the same shape as `x`, or a set of sequences - each the same shape as
  26. `x`. If `values` is a set of sequences, the statistic will be computed
  27. on each independently.
  28. statistic : string or callable, optional
  29. The statistic to compute (default is 'mean').
  30. The following statistics are available:
  31. * 'mean' : compute the mean of values for points within each bin.
  32. Empty bins will be represented by NaN.
  33. * 'median' : compute the median of values for points within each
  34. bin. Empty bins will be represented by NaN.
  35. * 'count' : compute the count of points within each bin. This is
  36. identical to an unweighted histogram. `values` array is not
  37. referenced.
  38. * 'sum' : compute the sum of values for points within each bin.
  39. This is identical to a weighted histogram.
  40. * 'min' : compute the minimum of values for points within each bin.
  41. Empty bins will be represented by NaN.
  42. * 'max' : compute the maximum of values for point within each bin.
  43. Empty bins will be represented by NaN.
  44. * function : a user-defined function which takes a 1D array of
  45. values, and outputs a single numerical statistic. This function
  46. will be called on the values in each bin. Empty bins will be
  47. represented by function([]), or NaN if this returns an error.
  48. bins : int or sequence of scalars, optional
  49. If `bins` is an int, it defines the number of equal-width bins in the
  50. given range (10 by default). If `bins` is a sequence, it defines the
  51. bin edges, including the rightmost edge, allowing for non-uniform bin
  52. widths. Values in `x` that are smaller than lowest bin edge are
  53. assigned to bin number 0, values beyond the highest bin are assigned to
  54. ``bins[-1]``. If the bin edges are specified, the number of bins will
  55. be, (nx = len(bins)-1).
  56. range : (float, float) or [(float, float)], optional
  57. The lower and upper range of the bins. If not provided, range
  58. is simply ``(x.min(), x.max())``. Values outside the range are
  59. ignored.
  60. Returns
  61. -------
  62. statistic : array
  63. The values of the selected statistic in each bin.
  64. bin_edges : array of dtype float
  65. Return the bin edges ``(length(statistic)+1)``.
  66. binnumber: 1-D ndarray of ints
  67. Indices of the bins (corresponding to `bin_edges`) in which each value
  68. of `x` belongs. Same length as `values`. A binnumber of `i` means the
  69. corresponding value is between (bin_edges[i-1], bin_edges[i]).
  70. See Also
  71. --------
  72. numpy.digitize, numpy.histogram, binned_statistic_2d, binned_statistic_dd
  73. Notes
  74. -----
  75. All but the last (righthand-most) bin is half-open. In other words, if
  76. `bins` is ``[1, 2, 3, 4]``, then the first bin is ``[1, 2)`` (including 1,
  77. but excluding 2) and the second ``[2, 3)``. The last bin, however, is
  78. ``[3, 4]``, which *includes* 4.
  79. .. versionadded:: 0.11.0
  80. Examples
  81. --------
  82. >>> from scipy import stats
  83. >>> import matplotlib.pyplot as plt
  84. First some basic examples:
  85. Create two evenly spaced bins in the range of the given sample, and sum the
  86. corresponding values in each of those bins:
  87. >>> values = [1.0, 1.0, 2.0, 1.5, 3.0]
  88. >>> stats.binned_statistic([1, 1, 2, 5, 7], values, 'sum', bins=2)
  89. (array([ 4. , 4.5]), array([ 1., 4., 7.]), array([1, 1, 1, 2, 2]))
  90. Multiple arrays of values can also be passed. The statistic is calculated
  91. on each set independently:
  92. >>> values = [[1.0, 1.0, 2.0, 1.5, 3.0], [2.0, 2.0, 4.0, 3.0, 6.0]]
  93. >>> stats.binned_statistic([1, 1, 2, 5, 7], values, 'sum', bins=2)
  94. (array([[ 4. , 4.5], [ 8. , 9. ]]), array([ 1., 4., 7.]),
  95. array([1, 1, 1, 2, 2]))
  96. >>> stats.binned_statistic([1, 2, 1, 2, 4], np.arange(5), statistic='mean',
  97. ... bins=3)
  98. (array([ 1., 2., 4.]), array([ 1., 2., 3., 4.]),
  99. array([1, 2, 1, 2, 3]))
  100. As a second example, we now generate some random data of sailing boat speed
  101. as a function of wind speed, and then determine how fast our boat is for
  102. certain wind speeds:
  103. >>> windspeed = 8 * np.random.rand(500)
  104. >>> boatspeed = .3 * windspeed**.5 + .2 * np.random.rand(500)
  105. >>> bin_means, bin_edges, binnumber = stats.binned_statistic(windspeed,
  106. ... boatspeed, statistic='median', bins=[1,2,3,4,5,6,7])
  107. >>> plt.figure()
  108. >>> plt.plot(windspeed, boatspeed, 'b.', label='raw data')
  109. >>> plt.hlines(bin_means, bin_edges[:-1], bin_edges[1:], colors='g', lw=5,
  110. ... label='binned statistic of data')
  111. >>> plt.legend()
  112. Now we can use ``binnumber`` to select all datapoints with a windspeed
  113. below 1:
  114. >>> low_boatspeed = boatspeed[binnumber == 0]
  115. As a final example, we will use ``bin_edges`` and ``binnumber`` to make a
  116. plot of a distribution that shows the mean and distribution around that
  117. mean per bin, on top of a regular histogram and the probability
  118. distribution function:
  119. >>> x = np.linspace(0, 5, num=500)
  120. >>> x_pdf = stats.maxwell.pdf(x)
  121. >>> samples = stats.maxwell.rvs(size=10000)
  122. >>> bin_means, bin_edges, binnumber = stats.binned_statistic(x, x_pdf,
  123. ... statistic='mean', bins=25)
  124. >>> bin_width = (bin_edges[1] - bin_edges[0])
  125. >>> bin_centers = bin_edges[1:] - bin_width/2
  126. >>> plt.figure()
  127. >>> plt.hist(samples, bins=50, density=True, histtype='stepfilled',
  128. ... alpha=0.2, label='histogram of data')
  129. >>> plt.plot(x, x_pdf, 'r-', label='analytical pdf')
  130. >>> plt.hlines(bin_means, bin_edges[:-1], bin_edges[1:], colors='g', lw=2,
  131. ... label='binned statistic of data')
  132. >>> plt.plot((binnumber - 0.5) * bin_width, x_pdf, 'g.', alpha=0.5)
  133. >>> plt.legend(fontsize=10)
  134. >>> plt.show()
  135. """
  136. try:
  137. N = len(bins)
  138. except TypeError:
  139. N = 1
  140. if N != 1:
  141. bins = [np.asarray(bins, float)]
  142. if range is not None:
  143. if len(range) == 2:
  144. range = [range]
  145. medians, edges, binnumbers = binned_statistic_dd(
  146. [x], values, statistic, bins, range)
  147. return BinnedStatisticResult(medians, edges[0], binnumbers)
  148. BinnedStatistic2dResult = namedtuple('BinnedStatistic2dResult',
  149. ('statistic', 'x_edge', 'y_edge',
  150. 'binnumber'))
  151. def binned_statistic_2d(x, y, values, statistic='mean',
  152. bins=10, range=None, expand_binnumbers=False):
  153. """
  154. Compute a bidimensional binned statistic for one or more sets of data.
  155. This is a generalization of a histogram2d function. A histogram divides
  156. the space into bins, and returns the count of the number of points in
  157. each bin. This function allows the computation of the sum, mean, median,
  158. or other statistic of the values (or set of values) within each bin.
  159. Parameters
  160. ----------
  161. x : (N,) array_like
  162. A sequence of values to be binned along the first dimension.
  163. y : (N,) array_like
  164. A sequence of values to be binned along the second dimension.
  165. values : (N,) array_like or list of (N,) array_like
  166. The data on which the statistic will be computed. This must be
  167. the same shape as `x`, or a list of sequences - each with the same
  168. shape as `x`. If `values` is such a list, the statistic will be
  169. computed on each independently.
  170. statistic : string or callable, optional
  171. The statistic to compute (default is 'mean').
  172. The following statistics are available:
  173. * 'mean' : compute the mean of values for points within each bin.
  174. Empty bins will be represented by NaN.
  175. * 'median' : compute the median of values for points within each
  176. bin. Empty bins will be represented by NaN.
  177. * 'count' : compute the count of points within each bin. This is
  178. identical to an unweighted histogram. `values` array is not
  179. referenced.
  180. * 'sum' : compute the sum of values for points within each bin.
  181. This is identical to a weighted histogram.
  182. * 'min' : compute the minimum of values for points within each bin.
  183. Empty bins will be represented by NaN.
  184. * 'max' : compute the maximum of values for point within each bin.
  185. Empty bins will be represented by NaN.
  186. * function : a user-defined function which takes a 1D array of
  187. values, and outputs a single numerical statistic. This function
  188. will be called on the values in each bin. Empty bins will be
  189. represented by function([]), or NaN if this returns an error.
  190. bins : int or [int, int] or array_like or [array, array], optional
  191. The bin specification:
  192. * the number of bins for the two dimensions (nx = ny = bins),
  193. * the number of bins in each dimension (nx, ny = bins),
  194. * the bin edges for the two dimensions (x_edge = y_edge = bins),
  195. * the bin edges in each dimension (x_edge, y_edge = bins).
  196. If the bin edges are specified, the number of bins will be,
  197. (nx = len(x_edge)-1, ny = len(y_edge)-1).
  198. range : (2,2) array_like, optional
  199. The leftmost and rightmost edges of the bins along each dimension
  200. (if not specified explicitly in the `bins` parameters):
  201. [[xmin, xmax], [ymin, ymax]]. All values outside of this range will be
  202. considered outliers and not tallied in the histogram.
  203. expand_binnumbers : bool, optional
  204. 'False' (default): the returned `binnumber` is a shape (N,) array of
  205. linearized bin indices.
  206. 'True': the returned `binnumber` is 'unraveled' into a shape (2,N)
  207. ndarray, where each row gives the bin numbers in the corresponding
  208. dimension.
  209. See the `binnumber` returned value, and the `Examples` section.
  210. .. versionadded:: 0.17.0
  211. Returns
  212. -------
  213. statistic : (nx, ny) ndarray
  214. The values of the selected statistic in each two-dimensional bin.
  215. x_edge : (nx + 1) ndarray
  216. The bin edges along the first dimension.
  217. y_edge : (ny + 1) ndarray
  218. The bin edges along the second dimension.
  219. binnumber : (N,) array of ints or (2,N) ndarray of ints
  220. This assigns to each element of `sample` an integer that represents the
  221. bin in which this observation falls. The representation depends on the
  222. `expand_binnumbers` argument. See `Notes` for details.
  223. See Also
  224. --------
  225. numpy.digitize, numpy.histogram2d, binned_statistic, binned_statistic_dd
  226. Notes
  227. -----
  228. Binedges:
  229. All but the last (righthand-most) bin is half-open. In other words, if
  230. `bins` is ``[1, 2, 3, 4]``, then the first bin is ``[1, 2)`` (including 1,
  231. but excluding 2) and the second ``[2, 3)``. The last bin, however, is
  232. ``[3, 4]``, which *includes* 4.
  233. `binnumber`:
  234. This returned argument assigns to each element of `sample` an integer that
  235. represents the bin in which it belongs. The representation depends on the
  236. `expand_binnumbers` argument. If 'False' (default): The returned
  237. `binnumber` is a shape (N,) array of linearized indices mapping each
  238. element of `sample` to its corresponding bin (using row-major ordering).
  239. If 'True': The returned `binnumber` is a shape (2,N) ndarray where
  240. each row indicates bin placements for each dimension respectively. In each
  241. dimension, a binnumber of `i` means the corresponding value is between
  242. (D_edge[i-1], D_edge[i]), where 'D' is either 'x' or 'y'.
  243. .. versionadded:: 0.11.0
  244. Examples
  245. --------
  246. >>> from scipy import stats
  247. Calculate the counts with explicit bin-edges:
  248. >>> x = [0.1, 0.1, 0.1, 0.6]
  249. >>> y = [2.1, 2.6, 2.1, 2.1]
  250. >>> binx = [0.0, 0.5, 1.0]
  251. >>> biny = [2.0, 2.5, 3.0]
  252. >>> ret = stats.binned_statistic_2d(x, y, None, 'count', bins=[binx,biny])
  253. >>> ret.statistic
  254. array([[ 2., 1.],
  255. [ 1., 0.]])
  256. The bin in which each sample is placed is given by the `binnumber`
  257. returned parameter. By default, these are the linearized bin indices:
  258. >>> ret.binnumber
  259. array([5, 6, 5, 9])
  260. The bin indices can also be expanded into separate entries for each
  261. dimension using the `expand_binnumbers` parameter:
  262. >>> ret = stats.binned_statistic_2d(x, y, None, 'count', bins=[binx,biny],
  263. ... expand_binnumbers=True)
  264. >>> ret.binnumber
  265. array([[1, 1, 1, 2],
  266. [1, 2, 1, 1]])
  267. Which shows that the first three elements belong in the xbin 1, and the
  268. fourth into xbin 2; and so on for y.
  269. """
  270. # This code is based on np.histogram2d
  271. try:
  272. N = len(bins)
  273. except TypeError:
  274. N = 1
  275. if N != 1 and N != 2:
  276. xedges = yedges = np.asarray(bins, float)
  277. bins = [xedges, yedges]
  278. medians, edges, binnumbers = binned_statistic_dd(
  279. [x, y], values, statistic, bins, range,
  280. expand_binnumbers=expand_binnumbers)
  281. return BinnedStatistic2dResult(medians, edges[0], edges[1], binnumbers)
  282. BinnedStatisticddResult = namedtuple('BinnedStatisticddResult',
  283. ('statistic', 'bin_edges',
  284. 'binnumber'))
  285. def binned_statistic_dd(sample, values, statistic='mean',
  286. bins=10, range=None, expand_binnumbers=False):
  287. """
  288. Compute a multidimensional binned statistic for a set of data.
  289. This is a generalization of a histogramdd function. A histogram divides
  290. the space into bins, and returns the count of the number of points in
  291. each bin. This function allows the computation of the sum, mean, median,
  292. or other statistic of the values within each bin.
  293. Parameters
  294. ----------
  295. sample : array_like
  296. Data to histogram passed as a sequence of D arrays of length N, or
  297. as an (N,D) array.
  298. values : (N,) array_like or list of (N,) array_like
  299. The data on which the statistic will be computed. This must be
  300. the same shape as `sample`, or a list of sequences - each with the
  301. same shape as `sample`. If `values` is such a list, the statistic
  302. will be computed on each independently.
  303. statistic : string or callable, optional
  304. The statistic to compute (default is 'mean').
  305. The following statistics are available:
  306. * 'mean' : compute the mean of values for points within each bin.
  307. Empty bins will be represented by NaN.
  308. * 'median' : compute the median of values for points within each
  309. bin. Empty bins will be represented by NaN.
  310. * 'count' : compute the count of points within each bin. This is
  311. identical to an unweighted histogram. `values` array is not
  312. referenced.
  313. * 'sum' : compute the sum of values for points within each bin.
  314. This is identical to a weighted histogram.
  315. * 'min' : compute the minimum of values for points within each bin.
  316. Empty bins will be represented by NaN.
  317. * 'max' : compute the maximum of values for point within each bin.
  318. Empty bins will be represented by NaN.
  319. * function : a user-defined function which takes a 1D array of
  320. values, and outputs a single numerical statistic. This function
  321. will be called on the values in each bin. Empty bins will be
  322. represented by function([]), or NaN if this returns an error.
  323. bins : sequence or int, optional
  324. The bin specification must be in one of the following forms:
  325. * A sequence of arrays describing the bin edges along each dimension.
  326. * The number of bins for each dimension (nx, ny, ... = bins).
  327. * The number of bins for all dimensions (nx = ny = ... = bins).
  328. range : sequence, optional
  329. A sequence of lower and upper bin edges to be used if the edges are
  330. not given explicitly in `bins`. Defaults to the minimum and maximum
  331. values along each dimension.
  332. expand_binnumbers : bool, optional
  333. 'False' (default): the returned `binnumber` is a shape (N,) array of
  334. linearized bin indices.
  335. 'True': the returned `binnumber` is 'unraveled' into a shape (D,N)
  336. ndarray, where each row gives the bin numbers in the corresponding
  337. dimension.
  338. See the `binnumber` returned value, and the `Examples` section of
  339. `binned_statistic_2d`.
  340. .. versionadded:: 0.17.0
  341. Returns
  342. -------
  343. statistic : ndarray, shape(nx1, nx2, nx3,...)
  344. The values of the selected statistic in each two-dimensional bin.
  345. bin_edges : list of ndarrays
  346. A list of D arrays describing the (nxi + 1) bin edges for each
  347. dimension.
  348. binnumber : (N,) array of ints or (D,N) ndarray of ints
  349. This assigns to each element of `sample` an integer that represents the
  350. bin in which this observation falls. The representation depends on the
  351. `expand_binnumbers` argument. See `Notes` for details.
  352. See Also
  353. --------
  354. numpy.digitize, numpy.histogramdd, binned_statistic, binned_statistic_2d
  355. Notes
  356. -----
  357. Binedges:
  358. All but the last (righthand-most) bin is half-open in each dimension. In
  359. other words, if `bins` is ``[1, 2, 3, 4]``, then the first bin is
  360. ``[1, 2)`` (including 1, but excluding 2) and the second ``[2, 3)``. The
  361. last bin, however, is ``[3, 4]``, which *includes* 4.
  362. `binnumber`:
  363. This returned argument assigns to each element of `sample` an integer that
  364. represents the bin in which it belongs. The representation depends on the
  365. `expand_binnumbers` argument. If 'False' (default): The returned
  366. `binnumber` is a shape (N,) array of linearized indices mapping each
  367. element of `sample` to its corresponding bin (using row-major ordering).
  368. If 'True': The returned `binnumber` is a shape (D,N) ndarray where
  369. each row indicates bin placements for each dimension respectively. In each
  370. dimension, a binnumber of `i` means the corresponding value is between
  371. (bin_edges[D][i-1], bin_edges[D][i]), for each dimension 'D'.
  372. .. versionadded:: 0.11.0
  373. """
  374. known_stats = ['mean', 'median', 'count', 'sum', 'std','min','max']
  375. if not callable(statistic) and statistic not in known_stats:
  376. raise ValueError('invalid statistic %r' % (statistic,))
  377. # `Ndim` is the number of dimensions (e.g. `2` for `binned_statistic_2d`)
  378. # `Dlen` is the length of elements along each dimension.
  379. # This code is based on np.histogramdd
  380. try:
  381. # `sample` is an ND-array.
  382. Dlen, Ndim = sample.shape
  383. except (AttributeError, ValueError):
  384. # `sample` is a sequence of 1D arrays.
  385. sample = np.atleast_2d(sample).T
  386. Dlen, Ndim = sample.shape
  387. # Store initial shape of `values` to preserve it in the output
  388. values = np.asarray(values)
  389. input_shape = list(values.shape)
  390. # Make sure that `values` is 2D to iterate over rows
  391. values = np.atleast_2d(values)
  392. Vdim, Vlen = values.shape
  393. # Make sure `values` match `sample`
  394. if(statistic != 'count' and Vlen != Dlen):
  395. raise AttributeError('The number of `values` elements must match the '
  396. 'length of each `sample` dimension.')
  397. nbin = np.empty(Ndim, int) # Number of bins in each dimension
  398. edges = Ndim * [None] # Bin edges for each dim (will be 2D array)
  399. dedges = Ndim * [None] # Spacing between edges (will be 2D array)
  400. try:
  401. M = len(bins)
  402. if M != Ndim:
  403. raise AttributeError('The dimension of bins must be equal '
  404. 'to the dimension of the sample x.')
  405. except TypeError:
  406. bins = Ndim * [bins]
  407. # Select range for each dimension
  408. # Used only if number of bins is given.
  409. if range is None:
  410. smin = np.atleast_1d(np.array(sample.min(axis=0), float))
  411. smax = np.atleast_1d(np.array(sample.max(axis=0), float))
  412. else:
  413. smin = np.zeros(Ndim)
  414. smax = np.zeros(Ndim)
  415. for i in xrange(Ndim):
  416. smin[i], smax[i] = range[i]
  417. # Make sure the bins have a finite width.
  418. for i in xrange(len(smin)):
  419. if smin[i] == smax[i]:
  420. smin[i] = smin[i] - .5
  421. smax[i] = smax[i] + .5
  422. # Create edge arrays
  423. for i in xrange(Ndim):
  424. if np.isscalar(bins[i]):
  425. nbin[i] = bins[i] + 2 # +2 for outlier bins
  426. edges[i] = np.linspace(smin[i], smax[i], nbin[i] - 1)
  427. else:
  428. edges[i] = np.asarray(bins[i], float)
  429. nbin[i] = len(edges[i]) + 1 # +1 for outlier bins
  430. dedges[i] = np.diff(edges[i])
  431. nbin = np.asarray(nbin)
  432. # Compute the bin number each sample falls into, in each dimension
  433. sampBin = [
  434. np.digitize(sample[:, i], edges[i])
  435. for i in xrange(Ndim)
  436. ]
  437. # Using `digitize`, values that fall on an edge are put in the right bin.
  438. # For the rightmost bin, we want values equal to the right
  439. # edge to be counted in the last bin, and not as an outlier.
  440. for i in xrange(Ndim):
  441. # Find the rounding precision
  442. decimal = int(-np.log10(dedges[i].min())) + 6
  443. # Find which points are on the rightmost edge.
  444. on_edge = np.where(np.around(sample[:, i], decimal) ==
  445. np.around(edges[i][-1], decimal))[0]
  446. # Shift these points one bin to the left.
  447. sampBin[i][on_edge] -= 1
  448. # Compute the sample indices in the flattened statistic matrix.
  449. binnumbers = np.ravel_multi_index(sampBin, nbin)
  450. result = np.empty([Vdim, nbin.prod()], float)
  451. if statistic == 'mean':
  452. result.fill(np.nan)
  453. flatcount = np.bincount(binnumbers, None)
  454. a = flatcount.nonzero()
  455. for vv in xrange(Vdim):
  456. flatsum = np.bincount(binnumbers, values[vv])
  457. result[vv, a] = flatsum[a] / flatcount[a]
  458. elif statistic == 'std':
  459. result.fill(0)
  460. flatcount = np.bincount(binnumbers, None)
  461. a = flatcount.nonzero()
  462. for vv in xrange(Vdim):
  463. flatsum = np.bincount(binnumbers, values[vv])
  464. flatsum2 = np.bincount(binnumbers, values[vv] ** 2)
  465. result[vv, a] = np.sqrt(flatsum2[a] / flatcount[a] -
  466. (flatsum[a] / flatcount[a]) ** 2)
  467. elif statistic == 'count':
  468. result.fill(0)
  469. flatcount = np.bincount(binnumbers, None)
  470. a = np.arange(len(flatcount))
  471. result[:, a] = flatcount[np.newaxis, :]
  472. elif statistic == 'sum':
  473. result.fill(0)
  474. for vv in xrange(Vdim):
  475. flatsum = np.bincount(binnumbers, values[vv])
  476. a = np.arange(len(flatsum))
  477. result[vv, a] = flatsum
  478. elif statistic == 'median':
  479. result.fill(np.nan)
  480. for i in np.unique(binnumbers):
  481. for vv in xrange(Vdim):
  482. result[vv, i] = np.median(values[vv, binnumbers == i])
  483. elif statistic == 'min':
  484. result.fill(np.nan)
  485. for i in np.unique(binnumbers):
  486. for vv in xrange(Vdim):
  487. result[vv, i] = np.min(values[vv, binnumbers == i])
  488. elif statistic == 'max':
  489. result.fill(np.nan)
  490. for i in np.unique(binnumbers):
  491. for vv in xrange(Vdim):
  492. result[vv, i] = np.max(values[vv, binnumbers == i])
  493. elif callable(statistic):
  494. with np.errstate(invalid='ignore'), suppress_warnings() as sup:
  495. sup.filter(RuntimeWarning)
  496. try:
  497. null = statistic([])
  498. except Exception:
  499. null = np.nan
  500. result.fill(null)
  501. for i in np.unique(binnumbers):
  502. for vv in xrange(Vdim):
  503. result[vv, i] = statistic(values[vv, binnumbers == i])
  504. # Shape into a proper matrix
  505. result = result.reshape(np.append(Vdim, nbin))
  506. # Remove outliers (indices 0 and -1 for each bin-dimension).
  507. core = tuple([slice(None)] + Ndim * [slice(1, -1)])
  508. result = result[core]
  509. # Unravel binnumbers into an ndarray, each row the bins for each dimension
  510. if(expand_binnumbers and Ndim > 1):
  511. binnumbers = np.asarray(np.unravel_index(binnumbers, nbin))
  512. if np.any(result.shape[1:] != nbin - 2):
  513. raise RuntimeError('Internal Shape Error')
  514. # Reshape to have output (`reulst`) match input (`values`) shape
  515. result = result.reshape(input_shape[:-1] + list(nbin-2))
  516. return BinnedStatisticddResult(result, edges, binnumbers)