_twodim_base_impl.py 33 KB

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