twodim_base.py 31 KB

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