twodim_base.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059
  1. """ Basic functions for manipulating 2d arrays
  2. """
  3. import functools
  4. from numpy.core.numeric import (
  5. asanyarray, arange, zeros, greater_equal, multiply, ones,
  6. asarray, where, int8, int16, int32, int64, intp, empty, promote_types,
  7. diagonal, nonzero, indices
  8. )
  9. from numpy.core.overrides import set_array_function_like_doc, set_module
  10. from numpy.core import overrides
  11. from numpy.core import iinfo
  12. from numpy.lib.stride_tricks import broadcast_to
  13. __all__ = [
  14. 'diag', 'diagflat', 'eye', 'fliplr', 'flipud', 'tri', 'triu',
  15. 'tril', 'vander', 'histogram2d', 'mask_indices', 'tril_indices',
  16. 'tril_indices_from', 'triu_indices', 'triu_indices_from', ]
  17. array_function_dispatch = functools.partial(
  18. overrides.array_function_dispatch, module='numpy')
  19. i1 = iinfo(int8)
  20. i2 = iinfo(int16)
  21. i4 = iinfo(int32)
  22. def _min_int(low, high):
  23. """ get small int that fits the range """
  24. if high <= i1.max and low >= i1.min:
  25. return int8
  26. if high <= i2.max and low >= i2.min:
  27. return int16
  28. if high <= i4.max and low >= i4.min:
  29. return int32
  30. return int64
  31. def _flip_dispatcher(m):
  32. return (m,)
  33. @array_function_dispatch(_flip_dispatcher)
  34. def fliplr(m):
  35. """
  36. Reverse the order of elements along axis 1 (left/right).
  37. For a 2-D array, this flips the entries in each row in the left/right
  38. direction. Columns are preserved, but appear in a different order than
  39. before.
  40. Parameters
  41. ----------
  42. m : array_like
  43. Input array, must be at least 2-D.
  44. Returns
  45. -------
  46. f : ndarray
  47. A view of `m` with the columns reversed. Since a view
  48. is returned, this operation is :math:`\\mathcal O(1)`.
  49. See Also
  50. --------
  51. flipud : Flip array in the up/down direction.
  52. flip : Flip array in one or more dimesions.
  53. rot90 : Rotate array counterclockwise.
  54. Notes
  55. -----
  56. Equivalent to ``m[:,::-1]`` or ``np.flip(m, axis=1)``.
  57. Requires the array to be at least 2-D.
  58. Examples
  59. --------
  60. >>> A = np.diag([1.,2.,3.])
  61. >>> A
  62. array([[1., 0., 0.],
  63. [0., 2., 0.],
  64. [0., 0., 3.]])
  65. >>> np.fliplr(A)
  66. array([[0., 0., 1.],
  67. [0., 2., 0.],
  68. [3., 0., 0.]])
  69. >>> A = np.random.randn(2,3,5)
  70. >>> np.all(np.fliplr(A) == A[:,::-1,...])
  71. True
  72. """
  73. m = asanyarray(m)
  74. if m.ndim < 2:
  75. raise ValueError("Input must be >= 2-d.")
  76. return m[:, ::-1]
  77. @array_function_dispatch(_flip_dispatcher)
  78. def flipud(m):
  79. """
  80. Reverse the order of elements along axis 0 (up/down).
  81. For a 2-D array, this flips the entries in each column in the up/down
  82. direction. Rows are preserved, but appear in a different order than before.
  83. Parameters
  84. ----------
  85. m : array_like
  86. Input array.
  87. Returns
  88. -------
  89. out : array_like
  90. A view of `m` with the rows reversed. Since a view is
  91. returned, this operation is :math:`\\mathcal O(1)`.
  92. See Also
  93. --------
  94. fliplr : Flip array in the left/right direction.
  95. flip : Flip array in one or more dimesions.
  96. rot90 : Rotate array counterclockwise.
  97. Notes
  98. -----
  99. Equivalent to ``m[::-1, ...]`` or ``np.flip(m, axis=0)``.
  100. Requires the array to be at least 1-D.
  101. Examples
  102. --------
  103. >>> A = np.diag([1.0, 2, 3])
  104. >>> A
  105. array([[1., 0., 0.],
  106. [0., 2., 0.],
  107. [0., 0., 3.]])
  108. >>> np.flipud(A)
  109. array([[0., 0., 3.],
  110. [0., 2., 0.],
  111. [1., 0., 0.]])
  112. >>> A = np.random.randn(2,3,5)
  113. >>> np.all(np.flipud(A) == A[::-1,...])
  114. True
  115. >>> np.flipud([1,2])
  116. array([2, 1])
  117. """
  118. m = asanyarray(m)
  119. if m.ndim < 1:
  120. raise ValueError("Input must be >= 1-d.")
  121. return m[::-1, ...]
  122. def _eye_dispatcher(N, M=None, k=None, dtype=None, order=None, *, like=None):
  123. return (like,)
  124. @set_array_function_like_doc
  125. @set_module('numpy')
  126. def eye(N, M=None, k=0, dtype=float, order='C', *, like=None):
  127. """
  128. Return a 2-D array with ones on the diagonal and zeros elsewhere.
  129. Parameters
  130. ----------
  131. N : int
  132. Number of rows in the output.
  133. M : int, optional
  134. Number of columns in the output. If None, defaults to `N`.
  135. k : int, optional
  136. Index of the diagonal: 0 (the default) refers to the main diagonal,
  137. a positive value refers to an upper diagonal, and a negative value
  138. to a lower diagonal.
  139. dtype : data-type, optional
  140. Data-type of the returned array.
  141. order : {'C', 'F'}, optional
  142. Whether the output should be stored in row-major (C-style) or
  143. column-major (Fortran-style) order in memory.
  144. .. versionadded:: 1.14.0
  145. ${ARRAY_FUNCTION_LIKE}
  146. .. versionadded:: 1.20.0
  147. Returns
  148. -------
  149. I : ndarray of shape (N,M)
  150. An array where all elements are equal to zero, except for the `k`-th
  151. diagonal, whose values are equal to one.
  152. See Also
  153. --------
  154. identity : (almost) equivalent function
  155. diag : diagonal 2-D array from a 1-D array specified by the user.
  156. Examples
  157. --------
  158. >>> np.eye(2, dtype=int)
  159. array([[1, 0],
  160. [0, 1]])
  161. >>> np.eye(3, k=1)
  162. array([[0., 1., 0.],
  163. [0., 0., 1.],
  164. [0., 0., 0.]])
  165. """
  166. if like is not None:
  167. return _eye_with_like(N, M=M, k=k, dtype=dtype, order=order, like=like)
  168. if M is None:
  169. M = N
  170. m = zeros((N, M), dtype=dtype, order=order)
  171. if k >= M:
  172. return m
  173. if k >= 0:
  174. i = k
  175. else:
  176. i = (-k) * M
  177. m[:M-k].flat[i::M+1] = 1
  178. return m
  179. _eye_with_like = array_function_dispatch(
  180. _eye_dispatcher
  181. )(eye)
  182. def _diag_dispatcher(v, k=None):
  183. return (v,)
  184. @array_function_dispatch(_diag_dispatcher)
  185. def diag(v, k=0):
  186. """
  187. Extract a diagonal or construct a diagonal array.
  188. See the more detailed documentation for ``numpy.diagonal`` if you use this
  189. function to extract a diagonal and wish to write to the resulting array;
  190. whether it returns a copy or a view depends on what version of numpy you
  191. are using.
  192. Parameters
  193. ----------
  194. v : array_like
  195. If `v` is a 2-D array, return a copy of its `k`-th diagonal.
  196. If `v` is a 1-D array, return a 2-D array with `v` on the `k`-th
  197. diagonal.
  198. k : int, optional
  199. Diagonal in question. The default is 0. Use `k>0` for diagonals
  200. above the main diagonal, and `k<0` for diagonals below the main
  201. diagonal.
  202. Returns
  203. -------
  204. out : ndarray
  205. The extracted diagonal or constructed diagonal array.
  206. See Also
  207. --------
  208. diagonal : Return specified diagonals.
  209. diagflat : Create a 2-D array with the flattened input as a diagonal.
  210. trace : Sum along diagonals.
  211. triu : Upper triangle of an array.
  212. tril : Lower triangle of an array.
  213. Examples
  214. --------
  215. >>> x = np.arange(9).reshape((3,3))
  216. >>> x
  217. array([[0, 1, 2],
  218. [3, 4, 5],
  219. [6, 7, 8]])
  220. >>> np.diag(x)
  221. array([0, 4, 8])
  222. >>> np.diag(x, k=1)
  223. array([1, 5])
  224. >>> np.diag(x, k=-1)
  225. array([3, 7])
  226. >>> np.diag(np.diag(x))
  227. array([[0, 0, 0],
  228. [0, 4, 0],
  229. [0, 0, 8]])
  230. """
  231. v = asanyarray(v)
  232. s = v.shape
  233. if len(s) == 1:
  234. n = s[0]+abs(k)
  235. res = zeros((n, n), v.dtype)
  236. if k >= 0:
  237. i = k
  238. else:
  239. i = (-k) * n
  240. res[:n-k].flat[i::n+1] = v
  241. return res
  242. elif len(s) == 2:
  243. return diagonal(v, k)
  244. else:
  245. raise ValueError("Input must be 1- or 2-d.")
  246. @array_function_dispatch(_diag_dispatcher)
  247. def diagflat(v, k=0):
  248. """
  249. Create a two-dimensional array with the flattened input as a diagonal.
  250. Parameters
  251. ----------
  252. v : array_like
  253. Input data, which is flattened and set as the `k`-th
  254. diagonal of the output.
  255. k : int, optional
  256. Diagonal to set; 0, the default, corresponds to the "main" diagonal,
  257. a positive (negative) `k` giving the number of the diagonal above
  258. (below) the main.
  259. Returns
  260. -------
  261. out : ndarray
  262. The 2-D output array.
  263. See Also
  264. --------
  265. diag : MATLAB work-alike for 1-D and 2-D arrays.
  266. diagonal : Return specified diagonals.
  267. trace : Sum along diagonals.
  268. Examples
  269. --------
  270. >>> np.diagflat([[1,2], [3,4]])
  271. array([[1, 0, 0, 0],
  272. [0, 2, 0, 0],
  273. [0, 0, 3, 0],
  274. [0, 0, 0, 4]])
  275. >>> np.diagflat([1,2], 1)
  276. array([[0, 1, 0],
  277. [0, 0, 2],
  278. [0, 0, 0]])
  279. """
  280. try:
  281. wrap = v.__array_wrap__
  282. except AttributeError:
  283. wrap = None
  284. v = asarray(v).ravel()
  285. s = len(v)
  286. n = s + abs(k)
  287. res = zeros((n, n), v.dtype)
  288. if (k >= 0):
  289. i = arange(0, n-k, dtype=intp)
  290. fi = i+k+i*n
  291. else:
  292. i = arange(0, n+k, dtype=intp)
  293. fi = i+(i-k)*n
  294. res.flat[fi] = v
  295. if not wrap:
  296. return res
  297. return wrap(res)
  298. def _tri_dispatcher(N, M=None, k=None, dtype=None, *, like=None):
  299. return (like,)
  300. @set_array_function_like_doc
  301. @set_module('numpy')
  302. def tri(N, M=None, k=0, dtype=float, *, like=None):
  303. """
  304. An array with ones at and below the given diagonal and zeros elsewhere.
  305. Parameters
  306. ----------
  307. N : int
  308. Number of rows in the array.
  309. M : int, optional
  310. Number of columns in the array.
  311. By default, `M` is taken equal to `N`.
  312. k : int, optional
  313. The sub-diagonal at and below which the array is filled.
  314. `k` = 0 is the main diagonal, while `k` < 0 is below it,
  315. and `k` > 0 is above. The default is 0.
  316. dtype : dtype, optional
  317. Data type of the returned array. The default is float.
  318. ${ARRAY_FUNCTION_LIKE}
  319. .. versionadded:: 1.20.0
  320. Returns
  321. -------
  322. tri : ndarray of shape (N, M)
  323. Array with its lower triangle filled with ones and zero elsewhere;
  324. in other words ``T[i,j] == 1`` for ``j <= i + k``, 0 otherwise.
  325. Examples
  326. --------
  327. >>> np.tri(3, 5, 2, dtype=int)
  328. array([[1, 1, 1, 0, 0],
  329. [1, 1, 1, 1, 0],
  330. [1, 1, 1, 1, 1]])
  331. >>> np.tri(3, 5, -1)
  332. array([[0., 0., 0., 0., 0.],
  333. [1., 0., 0., 0., 0.],
  334. [1., 1., 0., 0., 0.]])
  335. """
  336. if like is not None:
  337. return _tri_with_like(N, M=M, k=k, dtype=dtype, like=like)
  338. if M is None:
  339. M = N
  340. m = greater_equal.outer(arange(N, dtype=_min_int(0, N)),
  341. arange(-k, M-k, dtype=_min_int(-k, M - k)))
  342. # Avoid making a copy if the requested type is already bool
  343. m = m.astype(dtype, copy=False)
  344. return m
  345. _tri_with_like = array_function_dispatch(
  346. _tri_dispatcher
  347. )(tri)
  348. def _trilu_dispatcher(m, k=None):
  349. return (m,)
  350. @array_function_dispatch(_trilu_dispatcher)
  351. def tril(m, k=0):
  352. """
  353. Lower triangle of an array.
  354. Return a copy of an array with elements above the `k`-th diagonal zeroed.
  355. Parameters
  356. ----------
  357. m : array_like, shape (M, N)
  358. Input array.
  359. k : int, optional
  360. Diagonal above which to zero elements. `k = 0` (the default) is the
  361. main diagonal, `k < 0` is below it and `k > 0` is above.
  362. Returns
  363. -------
  364. tril : ndarray, shape (M, N)
  365. Lower triangle of `m`, of same shape and data-type as `m`.
  366. See Also
  367. --------
  368. triu : same thing, only for the upper triangle
  369. Examples
  370. --------
  371. >>> np.tril([[1,2,3],[4,5,6],[7,8,9],[10,11,12]], -1)
  372. array([[ 0, 0, 0],
  373. [ 4, 0, 0],
  374. [ 7, 8, 0],
  375. [10, 11, 12]])
  376. """
  377. m = asanyarray(m)
  378. mask = tri(*m.shape[-2:], k=k, dtype=bool)
  379. return where(mask, m, zeros(1, m.dtype))
  380. @array_function_dispatch(_trilu_dispatcher)
  381. def triu(m, k=0):
  382. """
  383. Upper triangle of an array.
  384. Return a copy of an array with the elements below the `k`-th diagonal
  385. zeroed.
  386. Please refer to the documentation for `tril` for further details.
  387. See Also
  388. --------
  389. tril : lower triangle of an array
  390. Examples
  391. --------
  392. >>> np.triu([[1,2,3],[4,5,6],[7,8,9],[10,11,12]], -1)
  393. array([[ 1, 2, 3],
  394. [ 4, 5, 6],
  395. [ 0, 8, 9],
  396. [ 0, 0, 12]])
  397. """
  398. m = asanyarray(m)
  399. mask = tri(*m.shape[-2:], k=k-1, dtype=bool)
  400. return where(mask, zeros(1, m.dtype), m)
  401. def _vander_dispatcher(x, N=None, increasing=None):
  402. return (x,)
  403. # Originally borrowed from John Hunter and matplotlib
  404. @array_function_dispatch(_vander_dispatcher)
  405. def vander(x, N=None, increasing=False):
  406. """
  407. Generate a Vandermonde matrix.
  408. The columns of the output matrix are powers of the input vector. The
  409. order of the powers is determined by the `increasing` boolean argument.
  410. Specifically, when `increasing` is False, the `i`-th output column is
  411. the input vector raised element-wise to the power of ``N - i - 1``. Such
  412. a matrix with a geometric progression in each row is named for Alexandre-
  413. Theophile Vandermonde.
  414. Parameters
  415. ----------
  416. x : array_like
  417. 1-D input array.
  418. N : int, optional
  419. Number of columns in the output. If `N` is not specified, a square
  420. array is returned (``N = len(x)``).
  421. increasing : bool, optional
  422. Order of the powers of the columns. If True, the powers increase
  423. from left to right, if False (the default) they are reversed.
  424. .. versionadded:: 1.9.0
  425. Returns
  426. -------
  427. out : ndarray
  428. Vandermonde matrix. If `increasing` is False, the first column is
  429. ``x^(N-1)``, the second ``x^(N-2)`` and so forth. If `increasing` is
  430. True, the columns are ``x^0, x^1, ..., x^(N-1)``.
  431. See Also
  432. --------
  433. polynomial.polynomial.polyvander
  434. Examples
  435. --------
  436. >>> x = np.array([1, 2, 3, 5])
  437. >>> N = 3
  438. >>> np.vander(x, N)
  439. array([[ 1, 1, 1],
  440. [ 4, 2, 1],
  441. [ 9, 3, 1],
  442. [25, 5, 1]])
  443. >>> np.column_stack([x**(N-1-i) for i in range(N)])
  444. array([[ 1, 1, 1],
  445. [ 4, 2, 1],
  446. [ 9, 3, 1],
  447. [25, 5, 1]])
  448. >>> x = np.array([1, 2, 3, 5])
  449. >>> np.vander(x)
  450. array([[ 1, 1, 1, 1],
  451. [ 8, 4, 2, 1],
  452. [ 27, 9, 3, 1],
  453. [125, 25, 5, 1]])
  454. >>> np.vander(x, increasing=True)
  455. array([[ 1, 1, 1, 1],
  456. [ 1, 2, 4, 8],
  457. [ 1, 3, 9, 27],
  458. [ 1, 5, 25, 125]])
  459. The determinant of a square Vandermonde matrix is the product
  460. of the differences between the values of the input vector:
  461. >>> np.linalg.det(np.vander(x))
  462. 48.000000000000043 # may vary
  463. >>> (5-3)*(5-2)*(5-1)*(3-2)*(3-1)*(2-1)
  464. 48
  465. """
  466. x = asarray(x)
  467. if x.ndim != 1:
  468. raise ValueError("x must be a one-dimensional array or sequence.")
  469. if N is None:
  470. N = len(x)
  471. v = empty((len(x), N), dtype=promote_types(x.dtype, int))
  472. tmp = v[:, ::-1] if not increasing else v
  473. if N > 0:
  474. tmp[:, 0] = 1
  475. if N > 1:
  476. tmp[:, 1:] = x[:, None]
  477. multiply.accumulate(tmp[:, 1:], out=tmp[:, 1:], axis=1)
  478. return v
  479. def _histogram2d_dispatcher(x, y, bins=None, range=None, normed=None,
  480. weights=None, density=None):
  481. yield x
  482. yield y
  483. # This terrible logic is adapted from the checks in histogram2d
  484. try:
  485. N = len(bins)
  486. except TypeError:
  487. N = 1
  488. if N == 2:
  489. yield from bins # bins=[x, y]
  490. else:
  491. yield bins
  492. yield weights
  493. @array_function_dispatch(_histogram2d_dispatcher)
  494. def histogram2d(x, y, bins=10, range=None, normed=None, weights=None,
  495. density=None):
  496. """
  497. Compute the bi-dimensional histogram of two data samples.
  498. Parameters
  499. ----------
  500. x : array_like, shape (N,)
  501. An array containing the x coordinates of the points to be
  502. histogrammed.
  503. y : array_like, shape (N,)
  504. An array containing the y coordinates of the points to be
  505. histogrammed.
  506. bins : int or array_like or [int, int] or [array, array], optional
  507. The bin specification:
  508. * If int, the number of bins for the two dimensions (nx=ny=bins).
  509. * If array_like, the bin edges for the two dimensions
  510. (x_edges=y_edges=bins).
  511. * If [int, int], the number of bins in each dimension
  512. (nx, ny = bins).
  513. * If [array, array], the bin edges in each dimension
  514. (x_edges, y_edges = bins).
  515. * A combination [int, array] or [array, int], where int
  516. is the number of bins and array is the bin edges.
  517. range : array_like, shape(2,2), optional
  518. The leftmost and rightmost edges of the bins along each dimension
  519. (if not specified explicitly in the `bins` parameters):
  520. ``[[xmin, xmax], [ymin, ymax]]``. All values outside of this range
  521. will be considered outliers and not tallied in the histogram.
  522. density : bool, optional
  523. If False, the default, returns the number of samples in each bin.
  524. If True, returns the probability *density* function at the bin,
  525. ``bin_count / sample_count / bin_area``.
  526. normed : bool, optional
  527. An alias for the density argument that behaves identically. To avoid
  528. confusion with the broken normed argument to `histogram`, `density`
  529. should be preferred.
  530. weights : array_like, shape(N,), optional
  531. An array of values ``w_i`` weighing each sample ``(x_i, y_i)``.
  532. Weights are normalized to 1 if `normed` is True. If `normed` is
  533. False, the values of the returned histogram are equal to the sum of
  534. the weights belonging to the samples falling into each bin.
  535. Returns
  536. -------
  537. H : ndarray, shape(nx, ny)
  538. The bi-dimensional histogram of samples `x` and `y`. Values in `x`
  539. are histogrammed along the first dimension and values in `y` are
  540. histogrammed along the second dimension.
  541. xedges : ndarray, shape(nx+1,)
  542. The bin edges along the first dimension.
  543. yedges : ndarray, shape(ny+1,)
  544. The bin edges along the second dimension.
  545. See Also
  546. --------
  547. histogram : 1D histogram
  548. histogramdd : Multidimensional histogram
  549. Notes
  550. -----
  551. When `normed` is True, then the returned histogram is the sample
  552. density, defined such that the sum over bins of the product
  553. ``bin_value * bin_area`` is 1.
  554. Please note that the histogram does not follow the Cartesian convention
  555. where `x` values are on the abscissa and `y` values on the ordinate
  556. axis. Rather, `x` is histogrammed along the first dimension of the
  557. array (vertical), and `y` along the second dimension of the array
  558. (horizontal). This ensures compatibility with `histogramdd`.
  559. Examples
  560. --------
  561. >>> from matplotlib.image import NonUniformImage
  562. >>> import matplotlib.pyplot as plt
  563. Construct a 2-D histogram with variable bin width. First define the bin
  564. edges:
  565. >>> xedges = [0, 1, 3, 5]
  566. >>> yedges = [0, 2, 3, 4, 6]
  567. Next we create a histogram H with random bin content:
  568. >>> x = np.random.normal(2, 1, 100)
  569. >>> y = np.random.normal(1, 1, 100)
  570. >>> H, xedges, yedges = np.histogram2d(x, y, bins=(xedges, yedges))
  571. >>> # Histogram does not follow Cartesian convention (see Notes),
  572. >>> # therefore transpose H for visualization purposes.
  573. >>> H = H.T
  574. :func:`imshow <matplotlib.pyplot.imshow>` can only display square bins:
  575. >>> fig = plt.figure(figsize=(7, 3))
  576. >>> ax = fig.add_subplot(131, title='imshow: square bins')
  577. >>> plt.imshow(H, interpolation='nearest', origin='lower',
  578. ... extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]])
  579. <matplotlib.image.AxesImage object at 0x...>
  580. :func:`pcolormesh <matplotlib.pyplot.pcolormesh>` can display actual edges:
  581. >>> ax = fig.add_subplot(132, title='pcolormesh: actual edges',
  582. ... aspect='equal')
  583. >>> X, Y = np.meshgrid(xedges, yedges)
  584. >>> ax.pcolormesh(X, Y, H)
  585. <matplotlib.collections.QuadMesh object at 0x...>
  586. :class:`NonUniformImage <matplotlib.image.NonUniformImage>` can be used to
  587. display actual bin edges with interpolation:
  588. >>> ax = fig.add_subplot(133, title='NonUniformImage: interpolated',
  589. ... aspect='equal', xlim=xedges[[0, -1]], ylim=yedges[[0, -1]])
  590. >>> im = NonUniformImage(ax, interpolation='bilinear')
  591. >>> xcenters = (xedges[:-1] + xedges[1:]) / 2
  592. >>> ycenters = (yedges[:-1] + yedges[1:]) / 2
  593. >>> im.set_data(xcenters, ycenters, H)
  594. >>> ax.images.append(im)
  595. >>> plt.show()
  596. """
  597. from numpy import histogramdd
  598. try:
  599. N = len(bins)
  600. except TypeError:
  601. N = 1
  602. if N != 1 and N != 2:
  603. xedges = yedges = asarray(bins)
  604. bins = [xedges, yedges]
  605. hist, edges = histogramdd([x, y], bins, range, normed, weights, density)
  606. return hist, edges[0], edges[1]
  607. @set_module('numpy')
  608. def mask_indices(n, mask_func, k=0):
  609. """
  610. Return the indices to access (n, n) arrays, given a masking function.
  611. Assume `mask_func` is a function that, for a square array a of size
  612. ``(n, n)`` with a possible offset argument `k`, when called as
  613. ``mask_func(a, k)`` returns a new array with zeros in certain locations
  614. (functions like `triu` or `tril` do precisely this). Then this function
  615. returns the indices where the non-zero values would be located.
  616. Parameters
  617. ----------
  618. n : int
  619. The returned indices will be valid to access arrays of shape (n, n).
  620. mask_func : callable
  621. A function whose call signature is similar to that of `triu`, `tril`.
  622. That is, ``mask_func(x, k)`` returns a boolean array, shaped like `x`.
  623. `k` is an optional argument to the function.
  624. k : scalar
  625. An optional argument which is passed through to `mask_func`. Functions
  626. like `triu`, `tril` take a second argument that is interpreted as an
  627. offset.
  628. Returns
  629. -------
  630. indices : tuple of arrays.
  631. The `n` arrays of indices corresponding to the locations where
  632. ``mask_func(np.ones((n, n)), k)`` is True.
  633. See Also
  634. --------
  635. triu, tril, triu_indices, tril_indices
  636. Notes
  637. -----
  638. .. versionadded:: 1.4.0
  639. Examples
  640. --------
  641. These are the indices that would allow you to access the upper triangular
  642. part of any 3x3 array:
  643. >>> iu = np.mask_indices(3, np.triu)
  644. For example, if `a` is a 3x3 array:
  645. >>> a = np.arange(9).reshape(3, 3)
  646. >>> a
  647. array([[0, 1, 2],
  648. [3, 4, 5],
  649. [6, 7, 8]])
  650. >>> a[iu]
  651. array([0, 1, 2, 4, 5, 8])
  652. An offset can be passed also to the masking function. This gets us the
  653. indices starting on the first diagonal right of the main one:
  654. >>> iu1 = np.mask_indices(3, np.triu, 1)
  655. with which we now extract only three elements:
  656. >>> a[iu1]
  657. array([1, 2, 5])
  658. """
  659. m = ones((n, n), int)
  660. a = mask_func(m, k)
  661. return nonzero(a != 0)
  662. @set_module('numpy')
  663. def tril_indices(n, k=0, m=None):
  664. """
  665. Return the indices for the lower-triangle of an (n, m) array.
  666. Parameters
  667. ----------
  668. n : int
  669. The row dimension of the arrays for which the returned
  670. indices will be valid.
  671. k : int, optional
  672. Diagonal offset (see `tril` for details).
  673. m : int, optional
  674. .. versionadded:: 1.9.0
  675. The column dimension of the arrays for which the returned
  676. arrays will be valid.
  677. By default `m` is taken equal to `n`.
  678. Returns
  679. -------
  680. inds : tuple of arrays
  681. The indices for the triangle. The returned tuple contains two arrays,
  682. each with the indices along one dimension of the array.
  683. See also
  684. --------
  685. triu_indices : similar function, for upper-triangular.
  686. mask_indices : generic function accepting an arbitrary mask function.
  687. tril, triu
  688. Notes
  689. -----
  690. .. versionadded:: 1.4.0
  691. Examples
  692. --------
  693. Compute two different sets of indices to access 4x4 arrays, one for the
  694. lower triangular part starting at the main diagonal, and one starting two
  695. diagonals further right:
  696. >>> il1 = np.tril_indices(4)
  697. >>> il2 = np.tril_indices(4, 2)
  698. Here is how they can be used with a sample array:
  699. >>> a = np.arange(16).reshape(4, 4)
  700. >>> a
  701. array([[ 0, 1, 2, 3],
  702. [ 4, 5, 6, 7],
  703. [ 8, 9, 10, 11],
  704. [12, 13, 14, 15]])
  705. Both for indexing:
  706. >>> a[il1]
  707. array([ 0, 4, 5, ..., 13, 14, 15])
  708. And for assigning values:
  709. >>> a[il1] = -1
  710. >>> a
  711. array([[-1, 1, 2, 3],
  712. [-1, -1, 6, 7],
  713. [-1, -1, -1, 11],
  714. [-1, -1, -1, -1]])
  715. These cover almost the whole array (two diagonals right of the main one):
  716. >>> a[il2] = -10
  717. >>> a
  718. array([[-10, -10, -10, 3],
  719. [-10, -10, -10, -10],
  720. [-10, -10, -10, -10],
  721. [-10, -10, -10, -10]])
  722. """
  723. tri_ = tri(n, m, k=k, dtype=bool)
  724. return tuple(broadcast_to(inds, tri_.shape)[tri_]
  725. for inds in indices(tri_.shape, sparse=True))
  726. def _trilu_indices_form_dispatcher(arr, k=None):
  727. return (arr,)
  728. @array_function_dispatch(_trilu_indices_form_dispatcher)
  729. def tril_indices_from(arr, k=0):
  730. """
  731. Return the indices for the lower-triangle of arr.
  732. See `tril_indices` for full details.
  733. Parameters
  734. ----------
  735. arr : array_like
  736. The indices will be valid for square arrays whose dimensions are
  737. the same as arr.
  738. k : int, optional
  739. Diagonal offset (see `tril` for details).
  740. See Also
  741. --------
  742. tril_indices, tril
  743. Notes
  744. -----
  745. .. versionadded:: 1.4.0
  746. """
  747. if arr.ndim != 2:
  748. raise ValueError("input array must be 2-d")
  749. return tril_indices(arr.shape[-2], k=k, m=arr.shape[-1])
  750. @set_module('numpy')
  751. def triu_indices(n, k=0, m=None):
  752. """
  753. Return the indices for the upper-triangle of an (n, m) array.
  754. Parameters
  755. ----------
  756. n : int
  757. The size of the arrays for which the returned indices will
  758. be valid.
  759. k : int, optional
  760. Diagonal offset (see `triu` for details).
  761. m : int, optional
  762. .. versionadded:: 1.9.0
  763. The column dimension of the arrays for which the returned
  764. arrays will be valid.
  765. By default `m` is taken equal to `n`.
  766. Returns
  767. -------
  768. inds : tuple, shape(2) of ndarrays, shape(`n`)
  769. The indices for the triangle. The returned tuple contains two arrays,
  770. each with the indices along one dimension of the array. Can be used
  771. to slice a ndarray of shape(`n`, `n`).
  772. See also
  773. --------
  774. tril_indices : similar function, for lower-triangular.
  775. mask_indices : generic function accepting an arbitrary mask function.
  776. triu, tril
  777. Notes
  778. -----
  779. .. versionadded:: 1.4.0
  780. Examples
  781. --------
  782. Compute two different sets of indices to access 4x4 arrays, one for the
  783. upper triangular part starting at the main diagonal, and one starting two
  784. diagonals further right:
  785. >>> iu1 = np.triu_indices(4)
  786. >>> iu2 = np.triu_indices(4, 2)
  787. Here is how they can be used with a sample array:
  788. >>> a = np.arange(16).reshape(4, 4)
  789. >>> a
  790. array([[ 0, 1, 2, 3],
  791. [ 4, 5, 6, 7],
  792. [ 8, 9, 10, 11],
  793. [12, 13, 14, 15]])
  794. Both for indexing:
  795. >>> a[iu1]
  796. array([ 0, 1, 2, ..., 10, 11, 15])
  797. And for assigning values:
  798. >>> a[iu1] = -1
  799. >>> a
  800. array([[-1, -1, -1, -1],
  801. [ 4, -1, -1, -1],
  802. [ 8, 9, -1, -1],
  803. [12, 13, 14, -1]])
  804. These cover only a small part of the whole array (two diagonals right
  805. of the main one):
  806. >>> a[iu2] = -10
  807. >>> a
  808. array([[ -1, -1, -10, -10],
  809. [ 4, -1, -1, -10],
  810. [ 8, 9, -1, -1],
  811. [ 12, 13, 14, -1]])
  812. """
  813. tri_ = ~tri(n, m, k=k - 1, dtype=bool)
  814. return tuple(broadcast_to(inds, tri_.shape)[tri_]
  815. for inds in indices(tri_.shape, sparse=True))
  816. @array_function_dispatch(_trilu_indices_form_dispatcher)
  817. def triu_indices_from(arr, k=0):
  818. """
  819. Return the indices for the upper-triangle of arr.
  820. See `triu_indices` for full details.
  821. Parameters
  822. ----------
  823. arr : ndarray, shape(N, N)
  824. The indices will be valid for square arrays.
  825. k : int, optional
  826. Diagonal offset (see `triu` for details).
  827. Returns
  828. -------
  829. triu_indices_from : tuple, shape(2) of ndarray, shape(N)
  830. Indices for the upper-triangle of `arr`.
  831. See Also
  832. --------
  833. triu_indices, triu
  834. Notes
  835. -----
  836. .. versionadded:: 1.4.0
  837. """
  838. if arr.ndim != 2:
  839. raise ValueError("input array must be 2-d")
  840. return triu_indices(arr.shape[-2], k=k, m=arr.shape[-1])