_index_tricks_impl.py 31 KB

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