index_tricks.py 30 KB

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