_index_tricks_impl.py 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048
  1. import functools
  2. import math
  3. import sys
  4. from itertools import product
  5. import numpy as np
  6. import numpy._core.numeric as _nx
  7. import numpy.matrixlib as matrixlib
  8. from numpy._core import linspace, overrides
  9. from numpy._core.multiarray import ravel_multi_index, unravel_index
  10. from numpy._core.numeric import ScalarType, array
  11. from numpy._core.numerictypes import issubdtype
  12. from numpy._utils import set_module
  13. from numpy.lib._function_base_impl import diff
  14. array_function_dispatch = functools.partial(
  15. overrides.array_function_dispatch, module='numpy')
  16. __all__ = [
  17. 'ravel_multi_index', 'unravel_index', 'mgrid', 'ogrid', 'r_', 'c_',
  18. 's_', 'index_exp', 'ix_', 'ndenumerate', 'ndindex', 'fill_diagonal',
  19. 'diag_indices', 'diag_indices_from'
  20. ]
  21. def _ix__dispatcher(*args):
  22. return args
  23. @array_function_dispatch(_ix__dispatcher)
  24. def ix_(*args):
  25. """
  26. Construct an open mesh from multiple sequences.
  27. This function takes N 1-D sequences and returns N outputs with N
  28. dimensions each, such that the shape is 1 in all but one dimension
  29. and the dimension with the non-unit shape value cycles through all
  30. N dimensions.
  31. Using `ix_` one can quickly construct index arrays that will index
  32. the cross product. ``a[np.ix_([1,3],[2,5])]`` returns the array
  33. ``[[a[1,2] a[1,5]], [a[3,2] a[3,5]]]``.
  34. Parameters
  35. ----------
  36. args : 1-D sequences
  37. Each sequence should be of integer or boolean type.
  38. Boolean sequences will be interpreted as boolean masks for the
  39. corresponding dimension (equivalent to passing in
  40. ``np.nonzero(boolean_sequence)``).
  41. Returns
  42. -------
  43. out : tuple of ndarrays
  44. N arrays with N dimensions each, with N the number of input
  45. sequences. Together these arrays form an open mesh.
  46. See Also
  47. --------
  48. ogrid, mgrid, meshgrid
  49. Examples
  50. --------
  51. >>> import numpy as np
  52. >>> a = np.arange(10).reshape(2, 5)
  53. >>> a
  54. array([[0, 1, 2, 3, 4],
  55. [5, 6, 7, 8, 9]])
  56. >>> ixgrid = np.ix_([0, 1], [2, 4])
  57. >>> ixgrid
  58. (array([[0],
  59. [1]]), array([[2, 4]]))
  60. >>> ixgrid[0].shape, ixgrid[1].shape
  61. ((2, 1), (1, 2))
  62. >>> a[ixgrid]
  63. array([[2, 4],
  64. [7, 9]])
  65. >>> ixgrid = np.ix_([True, True], [2, 4])
  66. >>> a[ixgrid]
  67. array([[2, 4],
  68. [7, 9]])
  69. >>> ixgrid = np.ix_([True, True], [False, False, True, False, True])
  70. >>> a[ixgrid]
  71. array([[2, 4],
  72. [7, 9]])
  73. """
  74. out = []
  75. nd = len(args)
  76. for k, new in enumerate(args):
  77. if not isinstance(new, _nx.ndarray):
  78. new = np.asarray(new)
  79. if new.size == 0:
  80. # Explicitly type empty arrays to avoid float default
  81. new = new.astype(_nx.intp)
  82. if new.ndim != 1:
  83. raise ValueError("Cross index must be 1 dimensional")
  84. if issubdtype(new.dtype, _nx.bool):
  85. new, = new.nonzero()
  86. new = new.reshape((1,) * k + (new.size,) + (1,) * (nd - k - 1))
  87. out.append(new)
  88. return tuple(out)
  89. class nd_grid:
  90. """
  91. Construct a multi-dimensional "meshgrid".
  92. ``grid = nd_grid()`` creates an instance which will return a mesh-grid
  93. when indexed. The dimension and number of the output arrays are equal
  94. to the number of indexing dimensions. If the step length is not a
  95. complex number, then the stop is not inclusive.
  96. However, if the step length is a **complex number** (e.g. 5j), then the
  97. integer part of its magnitude is interpreted as specifying the
  98. number of points to create between the start and stop values, where
  99. the stop value **is inclusive**.
  100. If instantiated with an argument of ``sparse=True``, the mesh-grid is
  101. open (or not fleshed out) so that only one-dimension of each returned
  102. argument is greater than 1.
  103. Parameters
  104. ----------
  105. sparse : bool, optional
  106. Whether the grid is sparse or not. Default is False.
  107. Notes
  108. -----
  109. Two instances of `nd_grid` are made available in the NumPy namespace,
  110. `mgrid` and `ogrid`, approximately defined as::
  111. mgrid = nd_grid(sparse=False)
  112. ogrid = nd_grid(sparse=True)
  113. Users should use these pre-defined instances instead of using `nd_grid`
  114. directly.
  115. """
  116. __slots__ = ('sparse',)
  117. def __init__(self, sparse=False):
  118. self.sparse = sparse
  119. def __getitem__(self, key):
  120. try:
  121. size = []
  122. # Mimic the behavior of `np.arange` and use a data type
  123. # which is at least as large as `np.int_`
  124. num_list = [0]
  125. for k in range(len(key)):
  126. step = key[k].step
  127. start = key[k].start
  128. stop = key[k].stop
  129. if start is None:
  130. start = 0
  131. if step is None:
  132. step = 1
  133. if isinstance(step, (_nx.complexfloating, complex)):
  134. step = abs(step)
  135. size.append(int(step))
  136. else:
  137. size.append(
  138. math.ceil((stop - start) / step))
  139. num_list += [start, stop, step]
  140. typ = _nx.result_type(*num_list)
  141. if self.sparse:
  142. nn = [_nx.arange(_x, dtype=_t)
  143. for _x, _t in zip(size, (typ,) * len(size))]
  144. else:
  145. nn = _nx.indices(size, typ)
  146. for k, kk in enumerate(key):
  147. step = kk.step
  148. start = kk.start
  149. if start is None:
  150. start = 0
  151. if step is None:
  152. step = 1
  153. if isinstance(step, (_nx.complexfloating, complex)):
  154. step = int(abs(step))
  155. if step != 1:
  156. step = (kk.stop - start) / float(step - 1)
  157. nn[k] = (nn[k] * step + start)
  158. if self.sparse:
  159. slobj = [_nx.newaxis] * len(size)
  160. for k in range(len(size)):
  161. slobj[k] = slice(None, None)
  162. nn[k] = nn[k][tuple(slobj)]
  163. slobj[k] = _nx.newaxis
  164. return tuple(nn) # ogrid -> tuple of arrays
  165. return nn # mgrid -> ndarray
  166. except (IndexError, TypeError):
  167. step = key.step
  168. stop = key.stop
  169. start = key.start
  170. if start is None:
  171. start = 0
  172. if isinstance(step, (_nx.complexfloating, complex)):
  173. # Prevent the (potential) creation of integer arrays
  174. step_float = abs(step)
  175. step = length = int(step_float)
  176. if step != 1:
  177. step = (key.stop - start) / float(step - 1)
  178. typ = _nx.result_type(start, stop, step_float)
  179. return _nx.arange(0, length, 1, dtype=typ) * step + start
  180. else:
  181. return _nx.arange(start, stop, step)
  182. class MGridClass(nd_grid):
  183. """
  184. An instance which returns a dense multi-dimensional "meshgrid".
  185. An instance which returns a dense (or fleshed out) mesh-grid
  186. when indexed, so that each returned argument has the same shape.
  187. The dimensions and number of the output arrays are equal to the
  188. number of indexing dimensions. If the step length is not a complex
  189. number, then the stop is not inclusive.
  190. However, if the step length is a **complex number** (e.g. 5j), then
  191. the integer part of its magnitude is interpreted as specifying the
  192. number of points to create between the start and stop values, where
  193. the stop value **is inclusive**.
  194. Returns
  195. -------
  196. mesh-grid : ndarray
  197. A single array, containing a set of `ndarray`\\ s all of the same
  198. dimensions. stacked along the first axis.
  199. See Also
  200. --------
  201. ogrid : like `mgrid` but returns open (not fleshed out) mesh grids
  202. meshgrid: return coordinate matrices from coordinate vectors
  203. r_ : array concatenator
  204. :ref:`how-to-partition`
  205. Examples
  206. --------
  207. >>> import numpy as np
  208. >>> np.mgrid[0:5, 0:5]
  209. array([[[0, 0, 0, 0, 0],
  210. [1, 1, 1, 1, 1],
  211. [2, 2, 2, 2, 2],
  212. [3, 3, 3, 3, 3],
  213. [4, 4, 4, 4, 4]],
  214. [[0, 1, 2, 3, 4],
  215. [0, 1, 2, 3, 4],
  216. [0, 1, 2, 3, 4],
  217. [0, 1, 2, 3, 4],
  218. [0, 1, 2, 3, 4]]])
  219. >>> np.mgrid[-1:1:5j]
  220. array([-1. , -0.5, 0. , 0.5, 1. ])
  221. >>> np.mgrid[0:4].shape
  222. (4,)
  223. >>> np.mgrid[0:4, 0:5].shape
  224. (2, 4, 5)
  225. >>> np.mgrid[0:4, 0:5, 0:6].shape
  226. (3, 4, 5, 6)
  227. """
  228. __slots__ = ()
  229. def __init__(self):
  230. super().__init__(sparse=False)
  231. mgrid = MGridClass()
  232. class OGridClass(nd_grid):
  233. """
  234. An instance which returns an open multi-dimensional "meshgrid".
  235. An instance which returns an open (i.e. not fleshed out) mesh-grid
  236. when indexed, so that only one dimension of each returned array is
  237. greater than 1. The dimension and number of the output arrays are
  238. equal to the number of indexing dimensions. If the step length is
  239. not a complex number, then the stop is not inclusive.
  240. However, if the step length is a **complex number** (e.g. 5j), then
  241. the integer part of its magnitude is interpreted as specifying the
  242. number of points to create between the start and stop values, where
  243. the stop value **is inclusive**.
  244. Returns
  245. -------
  246. mesh-grid : ndarray or tuple of ndarrays
  247. If the input is a single slice, returns an array.
  248. If the input is multiple slices, returns a tuple of arrays, with
  249. only one dimension not equal to 1.
  250. See Also
  251. --------
  252. mgrid : like `ogrid` but returns dense (or fleshed out) mesh grids
  253. meshgrid: return coordinate matrices from coordinate vectors
  254. r_ : array concatenator
  255. :ref:`how-to-partition`
  256. Examples
  257. --------
  258. >>> from numpy import ogrid
  259. >>> ogrid[-1:1:5j]
  260. array([-1. , -0.5, 0. , 0.5, 1. ])
  261. >>> ogrid[0:5, 0:5]
  262. (array([[0],
  263. [1],
  264. [2],
  265. [3],
  266. [4]]),
  267. array([[0, 1, 2, 3, 4]]))
  268. """
  269. __slots__ = ()
  270. def __init__(self):
  271. super().__init__(sparse=True)
  272. ogrid = OGridClass()
  273. class AxisConcatenator:
  274. """
  275. Translates slice objects to concatenation along an axis.
  276. For detailed documentation on usage, see `r_`.
  277. """
  278. __slots__ = ('axis', 'matrix', 'ndmin', 'trans1d')
  279. # allow ma.mr_ to override this
  280. concatenate = staticmethod(_nx.concatenate)
  281. makemat = staticmethod(matrixlib.matrix)
  282. def __init__(self, axis=0, matrix=False, ndmin=1, trans1d=-1):
  283. self.axis = axis
  284. self.matrix = matrix
  285. self.trans1d = trans1d
  286. self.ndmin = ndmin
  287. def __getitem__(self, key):
  288. # handle matrix builder syntax
  289. if isinstance(key, str):
  290. frame = sys._getframe().f_back
  291. mymat = matrixlib.bmat(key, frame.f_globals, frame.f_locals)
  292. return mymat
  293. if not isinstance(key, tuple):
  294. key = (key,)
  295. # copy attributes, since they can be overridden in the first argument
  296. trans1d = self.trans1d
  297. ndmin = self.ndmin
  298. matrix = self.matrix
  299. axis = self.axis
  300. objs = []
  301. # dtypes or scalars for weak scalar handling in result_type
  302. result_type_objs = []
  303. for k, item in enumerate(key):
  304. scalar = False
  305. if isinstance(item, slice):
  306. step = item.step
  307. start = item.start
  308. stop = item.stop
  309. if start is None:
  310. start = 0
  311. if step is None:
  312. step = 1
  313. if isinstance(step, (_nx.complexfloating, complex)):
  314. size = int(abs(step))
  315. newobj = linspace(start, stop, num=size)
  316. else:
  317. newobj = _nx.arange(start, stop, step)
  318. if ndmin > 1:
  319. newobj = array(newobj, copy=None, ndmin=ndmin)
  320. if trans1d != -1:
  321. newobj = newobj.swapaxes(-1, trans1d)
  322. elif isinstance(item, str):
  323. if k != 0:
  324. raise ValueError("special directives must be the "
  325. "first entry.")
  326. if item in ('r', 'c'):
  327. matrix = True
  328. col = (item == 'c')
  329. continue
  330. if ',' in item:
  331. vec = item.split(',')
  332. try:
  333. axis, ndmin = [int(x) for x in vec[:2]]
  334. if len(vec) == 3:
  335. trans1d = int(vec[2])
  336. continue
  337. except Exception as e:
  338. raise ValueError(
  339. f"unknown special directive {item!r}"
  340. ) from e
  341. try:
  342. axis = int(item)
  343. continue
  344. except (ValueError, TypeError) as e:
  345. raise ValueError("unknown special directive") from e
  346. elif type(item) in ScalarType:
  347. scalar = True
  348. newobj = item
  349. else:
  350. item_ndim = np.ndim(item)
  351. newobj = array(item, copy=None, subok=True, ndmin=ndmin)
  352. if trans1d != -1 and item_ndim < ndmin:
  353. k2 = ndmin - item_ndim
  354. k1 = trans1d
  355. if k1 < 0:
  356. k1 += k2 + 1
  357. defaxes = list(range(ndmin))
  358. axes = defaxes[:k1] + defaxes[k2:] + defaxes[k1:k2]
  359. newobj = newobj.transpose(axes)
  360. objs.append(newobj)
  361. if scalar:
  362. result_type_objs.append(item)
  363. else:
  364. result_type_objs.append(newobj.dtype)
  365. # Ensure that scalars won't up-cast unless warranted, for 0, drops
  366. # through to error in concatenate.
  367. if len(result_type_objs) != 0:
  368. final_dtype = _nx.result_type(*result_type_objs)
  369. # concatenate could do cast, but that can be overridden:
  370. objs = [array(obj, copy=None, subok=True,
  371. ndmin=ndmin, dtype=final_dtype) for obj in objs]
  372. res = self.concatenate(tuple(objs), axis=axis)
  373. if matrix:
  374. oldndim = res.ndim
  375. res = self.makemat(res)
  376. if oldndim == 1 and col:
  377. res = res.T
  378. return res
  379. def __len__(self):
  380. return 0
  381. # separate classes are used here instead of just making r_ = concatenator(0),
  382. # etc. because otherwise we couldn't get the doc string to come out right
  383. # in help(r_)
  384. class RClass(AxisConcatenator):
  385. """
  386. Translates slice objects to concatenation along the first axis.
  387. This is a simple way to build up arrays quickly. There are two use cases.
  388. 1. If the index expression contains comma separated arrays, then stack
  389. them along their first axis.
  390. 2. If the index expression contains slice notation or scalars then create
  391. a 1-D array with a range indicated by the slice notation.
  392. If slice notation is used, the syntax ``start:stop:step`` is equivalent
  393. to ``np.arange(start, stop, step)`` inside of the brackets. However, if
  394. ``step`` is an imaginary number (i.e. 100j) then its integer portion is
  395. interpreted as a number-of-points desired and the start and stop are
  396. inclusive. In other words ``start:stop:stepj`` is interpreted as
  397. ``np.linspace(start, stop, step, endpoint=1)`` inside of the brackets.
  398. After expansion of slice notation, all comma separated sequences are
  399. concatenated together.
  400. Optional character strings placed as the first element of the index
  401. expression can be used to change the output. The strings 'r' or 'c' result
  402. in matrix output. If the result is 1-D and 'r' is specified a 1 x N (row)
  403. matrix is produced. If the result is 1-D and 'c' is specified, then
  404. an N x 1 (column) matrix is produced.
  405. If the result is 2-D then both provide the same matrix result.
  406. A string integer specifies which axis to stack multiple comma separated
  407. arrays along. A string of two comma-separated integers allows indication
  408. of the minimum number of dimensions to force each entry into as the
  409. second integer (the axis to concatenate along is still the first integer).
  410. A string with three comma-separated integers allows specification of the
  411. axis to concatenate along, the minimum number of dimensions to force the
  412. entries to, and which axis should contain the start of the arrays which
  413. are less than the specified number of dimensions. In other words the third
  414. integer allows you to specify where the 1's should be placed in the shape
  415. of the arrays that have their shapes upgraded. By default, they are placed
  416. in the front of the shape tuple. The third argument allows you to specify
  417. where the start of the array should be instead. Thus, a third argument of
  418. '0' would place the 1's at the end of the array shape. Negative integers
  419. specify where in the new shape tuple the last dimension of upgraded arrays
  420. should be placed, so the default is '-1'.
  421. Parameters
  422. ----------
  423. Not a function, so takes no parameters
  424. Returns
  425. -------
  426. A concatenated ndarray or matrix.
  427. See Also
  428. --------
  429. concatenate : Join a sequence of arrays along an existing axis.
  430. c_ : Translates slice objects to concatenation along the second axis.
  431. Examples
  432. --------
  433. >>> import numpy as np
  434. >>> np.r_[np.array([1,2,3]), 0, 0, np.array([4,5,6])]
  435. array([1, 2, 3, ..., 4, 5, 6])
  436. >>> np.r_[-1:1:6j, [0]*3, 5, 6]
  437. array([-1. , -0.6, -0.2, 0.2, 0.6, 1. , 0. , 0. , 0. , 5. , 6. ])
  438. String integers specify the axis to concatenate along or the minimum
  439. number of dimensions to force entries into.
  440. >>> a = np.array([[0, 1, 2], [3, 4, 5]])
  441. >>> np.r_['-1', a, a] # concatenate along last axis
  442. array([[0, 1, 2, 0, 1, 2],
  443. [3, 4, 5, 3, 4, 5]])
  444. >>> np.r_['0,2', [1,2,3], [4,5,6]] # concatenate along first axis, dim>=2
  445. array([[1, 2, 3],
  446. [4, 5, 6]])
  447. >>> np.r_['0,2,0', [1,2,3], [4,5,6]]
  448. array([[1],
  449. [2],
  450. [3],
  451. [4],
  452. [5],
  453. [6]])
  454. >>> np.r_['1,2,0', [1,2,3], [4,5,6]]
  455. array([[1, 4],
  456. [2, 5],
  457. [3, 6]])
  458. Using 'r' or 'c' as a first string argument creates a matrix.
  459. >>> np.r_['r',[1,2,3], [4,5,6]]
  460. matrix([[1, 2, 3, 4, 5, 6]])
  461. """
  462. __slots__ = ()
  463. def __init__(self):
  464. AxisConcatenator.__init__(self, 0)
  465. r_ = RClass()
  466. class CClass(AxisConcatenator):
  467. """
  468. Translates slice objects to concatenation along the second axis.
  469. This is short-hand for ``np.r_['-1,2,0', index expression]``, which is
  470. useful because of its common occurrence. In particular, arrays will be
  471. stacked along their last axis after being upgraded to at least 2-D with
  472. 1's post-pended to the shape (column vectors made out of 1-D arrays).
  473. See Also
  474. --------
  475. column_stack : Stack 1-D arrays as columns into a 2-D array.
  476. r_ : For more detailed documentation.
  477. Examples
  478. --------
  479. >>> import numpy as np
  480. >>> np.c_[np.array([1,2,3]), np.array([4,5,6])]
  481. array([[1, 4],
  482. [2, 5],
  483. [3, 6]])
  484. >>> np.c_[np.array([[1,2,3]]), 0, 0, np.array([[4,5,6]])]
  485. array([[1, 2, 3, ..., 4, 5, 6]])
  486. """
  487. __slots__ = ()
  488. def __init__(self):
  489. AxisConcatenator.__init__(self, -1, ndmin=2, trans1d=0)
  490. c_ = CClass()
  491. @set_module('numpy')
  492. class ndenumerate:
  493. """
  494. Multidimensional index iterator.
  495. Return an iterator yielding pairs of array coordinates and values.
  496. Parameters
  497. ----------
  498. arr : ndarray
  499. Input array.
  500. See Also
  501. --------
  502. ndindex, flatiter
  503. Examples
  504. --------
  505. >>> import numpy as np
  506. >>> a = np.array([[1, 2], [3, 4]])
  507. >>> for index, x in np.ndenumerate(a):
  508. ... print(index, x)
  509. (0, 0) 1
  510. (0, 1) 2
  511. (1, 0) 3
  512. (1, 1) 4
  513. """
  514. def __init__(self, arr):
  515. self.iter = np.asarray(arr).flat
  516. def __next__(self):
  517. """
  518. Standard iterator method, returns the index tuple and array value.
  519. Returns
  520. -------
  521. coords : tuple of ints
  522. The indices of the current iteration.
  523. val : scalar
  524. The array element of the current iteration.
  525. """
  526. return self.iter.coords, next(self.iter)
  527. def __iter__(self):
  528. return self
  529. @set_module('numpy')
  530. class ndindex:
  531. """
  532. An N-dimensional iterator object to index arrays.
  533. Given the shape of an array, an `ndindex` instance iterates over
  534. the N-dimensional index of the array. At each iteration a tuple
  535. of indices is returned, the last dimension is iterated over first.
  536. Parameters
  537. ----------
  538. shape : ints, or a single tuple of ints
  539. The size of each dimension of the array can be passed as
  540. individual parameters or as the elements of a tuple.
  541. See Also
  542. --------
  543. ndenumerate, flatiter
  544. Examples
  545. --------
  546. >>> import numpy as np
  547. Dimensions as individual arguments
  548. >>> for index in np.ndindex(3, 2, 1):
  549. ... print(index)
  550. (0, 0, 0)
  551. (0, 1, 0)
  552. (1, 0, 0)
  553. (1, 1, 0)
  554. (2, 0, 0)
  555. (2, 1, 0)
  556. Same dimensions - but in a tuple ``(3, 2, 1)``
  557. >>> for index in np.ndindex((3, 2, 1)):
  558. ... print(index)
  559. (0, 0, 0)
  560. (0, 1, 0)
  561. (1, 0, 0)
  562. (1, 1, 0)
  563. (2, 0, 0)
  564. (2, 1, 0)
  565. """
  566. def __init__(self, *shape):
  567. if len(shape) == 1 and isinstance(shape[0], tuple):
  568. shape = shape[0]
  569. if min(shape, default=0) < 0:
  570. raise ValueError("negative dimensions are not allowed")
  571. self._iter = product(*map(range, shape))
  572. def __iter__(self):
  573. return self
  574. def __next__(self):
  575. """
  576. Standard iterator method, updates the index and returns the index
  577. tuple.
  578. Returns
  579. -------
  580. val : tuple of ints
  581. Returns a tuple containing the indices of the current
  582. iteration.
  583. """
  584. return next(self._iter)
  585. # You can do all this with slice() plus a few special objects,
  586. # but there's a lot to remember. This version is simpler because
  587. # it uses the standard array indexing syntax.
  588. #
  589. # Written by Konrad Hinsen <hinsen@cnrs-orleans.fr>
  590. # last revision: 1999-7-23
  591. #
  592. # Cosmetic changes by T. Oliphant 2001
  593. #
  594. #
  595. class IndexExpression:
  596. """
  597. A nicer way to build up index tuples for arrays.
  598. .. note::
  599. Use one of the two predefined instances ``index_exp`` or `s_`
  600. rather than directly using `IndexExpression`.
  601. For any index combination, including slicing and axis insertion,
  602. ``a[indices]`` is the same as ``a[np.index_exp[indices]]`` for any
  603. array `a`. However, ``np.index_exp[indices]`` can be used anywhere
  604. in Python code and returns a tuple of slice objects that can be
  605. used in the construction of complex index expressions.
  606. Parameters
  607. ----------
  608. maketuple : bool
  609. If True, always returns a tuple.
  610. See Also
  611. --------
  612. s_ : Predefined instance without tuple conversion:
  613. `s_ = IndexExpression(maketuple=False)`.
  614. The ``index_exp`` is another predefined instance that
  615. always returns a tuple:
  616. `index_exp = IndexExpression(maketuple=True)`.
  617. Notes
  618. -----
  619. You can do all this with :class:`slice` plus a few special objects,
  620. but there's a lot to remember and this version is simpler because
  621. it uses the standard array indexing syntax.
  622. Examples
  623. --------
  624. >>> import numpy as np
  625. >>> np.s_[2::2]
  626. slice(2, None, 2)
  627. >>> np.index_exp[2::2]
  628. (slice(2, None, 2),)
  629. >>> np.array([0, 1, 2, 3, 4])[np.s_[2::2]]
  630. array([2, 4])
  631. """
  632. __slots__ = ('maketuple',)
  633. def __init__(self, maketuple):
  634. self.maketuple = maketuple
  635. def __getitem__(self, item):
  636. if self.maketuple and not isinstance(item, tuple):
  637. return (item,)
  638. else:
  639. return item
  640. index_exp = IndexExpression(maketuple=True)
  641. s_ = IndexExpression(maketuple=False)
  642. # End contribution from Konrad.
  643. # The following functions complement those in twodim_base, but are
  644. # applicable to N-dimensions.
  645. def _fill_diagonal_dispatcher(a, val, wrap=None):
  646. return (a,)
  647. @array_function_dispatch(_fill_diagonal_dispatcher)
  648. def fill_diagonal(a, val, wrap=False):
  649. """Fill the main diagonal of the given array of any dimensionality.
  650. For an array `a` with ``a.ndim >= 2``, the diagonal is the list of
  651. values ``a[i, ..., i]`` with indices ``i`` all identical. This function
  652. modifies the input array in-place without returning a value.
  653. Parameters
  654. ----------
  655. a : array, at least 2-D.
  656. Array whose diagonal is to be filled in-place.
  657. val : scalar or array_like
  658. Value(s) to write on the diagonal. If `val` is scalar, the value is
  659. written along the diagonal. If array-like, the flattened `val` is
  660. written along the diagonal, repeating if necessary to fill all
  661. diagonal entries.
  662. wrap : bool
  663. For tall matrices in NumPy version up to 1.6.2, the
  664. diagonal "wrapped" after N columns. You can have this behavior
  665. with this option. This affects only tall matrices.
  666. See also
  667. --------
  668. diag_indices, diag_indices_from
  669. Notes
  670. -----
  671. This functionality can be obtained via `diag_indices`, but internally
  672. this version uses a much faster implementation that never constructs the
  673. indices and uses simple slicing.
  674. Examples
  675. --------
  676. >>> import numpy as np
  677. >>> a = np.zeros((3, 3), int)
  678. >>> np.fill_diagonal(a, 5)
  679. >>> a
  680. array([[5, 0, 0],
  681. [0, 5, 0],
  682. [0, 0, 5]])
  683. The same function can operate on a 4-D array:
  684. >>> a = np.zeros((3, 3, 3, 3), int)
  685. >>> np.fill_diagonal(a, 4)
  686. We only show a few blocks for clarity:
  687. >>> a[0, 0]
  688. array([[4, 0, 0],
  689. [0, 0, 0],
  690. [0, 0, 0]])
  691. >>> a[1, 1]
  692. array([[0, 0, 0],
  693. [0, 4, 0],
  694. [0, 0, 0]])
  695. >>> a[2, 2]
  696. array([[0, 0, 0],
  697. [0, 0, 0],
  698. [0, 0, 4]])
  699. The wrap option affects only tall matrices:
  700. >>> # tall matrices no wrap
  701. >>> a = np.zeros((5, 3), int)
  702. >>> np.fill_diagonal(a, 4)
  703. >>> a
  704. array([[4, 0, 0],
  705. [0, 4, 0],
  706. [0, 0, 4],
  707. [0, 0, 0],
  708. [0, 0, 0]])
  709. >>> # tall matrices wrap
  710. >>> a = np.zeros((5, 3), int)
  711. >>> np.fill_diagonal(a, 4, wrap=True)
  712. >>> a
  713. array([[4, 0, 0],
  714. [0, 4, 0],
  715. [0, 0, 4],
  716. [0, 0, 0],
  717. [4, 0, 0]])
  718. >>> # wide matrices
  719. >>> a = np.zeros((3, 5), int)
  720. >>> np.fill_diagonal(a, 4, wrap=True)
  721. >>> a
  722. array([[4, 0, 0, 0, 0],
  723. [0, 4, 0, 0, 0],
  724. [0, 0, 4, 0, 0]])
  725. The anti-diagonal can be filled by reversing the order of elements
  726. using either `numpy.flipud` or `numpy.fliplr`.
  727. >>> a = np.zeros((3, 3), int);
  728. >>> np.fill_diagonal(np.fliplr(a), [1,2,3]) # Horizontal flip
  729. >>> a
  730. array([[0, 0, 1],
  731. [0, 2, 0],
  732. [3, 0, 0]])
  733. >>> np.fill_diagonal(np.flipud(a), [1,2,3]) # Vertical flip
  734. >>> a
  735. array([[0, 0, 3],
  736. [0, 2, 0],
  737. [1, 0, 0]])
  738. Note that the order in which the diagonal is filled varies depending
  739. on the flip function.
  740. """
  741. if a.ndim < 2:
  742. raise ValueError("array must be at least 2-d")
  743. end = None
  744. if a.ndim == 2:
  745. # Explicit, fast formula for the common case. For 2-d arrays, we
  746. # accept rectangular ones.
  747. step = a.shape[1] + 1
  748. # This is needed to don't have tall matrix have the diagonal wrap.
  749. if not wrap:
  750. end = a.shape[1] * a.shape[1]
  751. else:
  752. # For more than d=2, the strided formula is only valid for arrays with
  753. # all dimensions equal, so we check first.
  754. if not np.all(diff(a.shape) == 0):
  755. raise ValueError("All dimensions of input must be of equal length")
  756. step = 1 + (np.cumprod(a.shape[:-1])).sum()
  757. # Write the value out into the diagonal.
  758. a.flat[:end:step] = val
  759. @set_module('numpy')
  760. def diag_indices(n, ndim=2):
  761. """
  762. Return the indices to access the main diagonal of an array.
  763. This returns a tuple of indices that can be used to access the main
  764. diagonal of an array `a` with ``a.ndim >= 2`` dimensions and shape
  765. (n, n, ..., n). For ``a.ndim = 2`` this is the usual diagonal, for
  766. ``a.ndim > 2`` this is the set of indices to access ``a[i, i, ..., i]``
  767. for ``i = [0..n-1]``.
  768. Parameters
  769. ----------
  770. n : int
  771. The size, along each dimension, of the arrays for which the returned
  772. indices can be used.
  773. ndim : int, optional
  774. The number of dimensions.
  775. See Also
  776. --------
  777. diag_indices_from
  778. Examples
  779. --------
  780. >>> import numpy as np
  781. Create a set of indices to access the diagonal of a (4, 4) array:
  782. >>> di = np.diag_indices(4)
  783. >>> di
  784. (array([0, 1, 2, 3]), array([0, 1, 2, 3]))
  785. >>> a = np.arange(16).reshape(4, 4)
  786. >>> a
  787. array([[ 0, 1, 2, 3],
  788. [ 4, 5, 6, 7],
  789. [ 8, 9, 10, 11],
  790. [12, 13, 14, 15]])
  791. >>> a[di] = 100
  792. >>> a
  793. array([[100, 1, 2, 3],
  794. [ 4, 100, 6, 7],
  795. [ 8, 9, 100, 11],
  796. [ 12, 13, 14, 100]])
  797. Now, we create indices to manipulate a 3-D array:
  798. >>> d3 = np.diag_indices(2, 3)
  799. >>> d3
  800. (array([0, 1]), array([0, 1]), array([0, 1]))
  801. And use it to set the diagonal of an array of zeros to 1:
  802. >>> a = np.zeros((2, 2, 2), dtype=int)
  803. >>> a[d3] = 1
  804. >>> a
  805. array([[[1, 0],
  806. [0, 0]],
  807. [[0, 0],
  808. [0, 1]]])
  809. """
  810. idx = np.arange(n)
  811. return (idx,) * ndim
  812. def _diag_indices_from(arr):
  813. return (arr,)
  814. @array_function_dispatch(_diag_indices_from)
  815. def diag_indices_from(arr):
  816. """
  817. Return the indices to access the main diagonal of an n-dimensional array.
  818. See `diag_indices` for full details.
  819. Parameters
  820. ----------
  821. arr : array, at least 2-D
  822. See Also
  823. --------
  824. diag_indices
  825. Examples
  826. --------
  827. >>> import numpy as np
  828. Create a 4 by 4 array.
  829. >>> a = np.arange(16).reshape(4, 4)
  830. >>> a
  831. array([[ 0, 1, 2, 3],
  832. [ 4, 5, 6, 7],
  833. [ 8, 9, 10, 11],
  834. [12, 13, 14, 15]])
  835. Get the indices of the diagonal elements.
  836. >>> di = np.diag_indices_from(a)
  837. >>> di
  838. (array([0, 1, 2, 3]), array([0, 1, 2, 3]))
  839. >>> a[di]
  840. array([ 0, 5, 10, 15])
  841. This is simply syntactic sugar for diag_indices.
  842. >>> np.diag_indices(a.shape[0])
  843. (array([0, 1, 2, 3]), array([0, 1, 2, 3]))
  844. """
  845. if not arr.ndim >= 2:
  846. raise ValueError("input array must be at least 2-d")
  847. # For more than d=2, the strided formula is only valid for arrays with
  848. # all dimensions equal, so we check first.
  849. if not np.all(diff(arr.shape) == 0):
  850. raise ValueError("All dimensions of input must be of equal length")
  851. return diag_indices(arr.shape[0], arr.ndim)