twodim_base.py 32 KB

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