_shape_base_impl.py 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289
  1. import functools
  2. import warnings
  3. import numpy as np
  4. import numpy._core.numeric as _nx
  5. from numpy._core import atleast_3d, overrides, vstack
  6. from numpy._core._multiarray_umath import _array_converter
  7. from numpy._core.fromnumeric import reshape, transpose
  8. from numpy._core.multiarray import normalize_axis_index
  9. from numpy._core.numeric import (
  10. array,
  11. asanyarray,
  12. asarray,
  13. normalize_axis_tuple,
  14. zeros,
  15. zeros_like,
  16. )
  17. from numpy._core.overrides import set_module
  18. from numpy._core.shape_base import _arrays_for_stack_dispatcher
  19. from numpy.lib._index_tricks_impl import ndindex
  20. from numpy.matrixlib.defmatrix import matrix # this raises all the right alarm bells
  21. __all__ = [
  22. 'column_stack', 'row_stack', 'dstack', 'array_split', 'split',
  23. 'hsplit', 'vsplit', 'dsplit', 'apply_over_axes', 'expand_dims',
  24. 'apply_along_axis', 'kron', 'tile', 'take_along_axis',
  25. 'put_along_axis'
  26. ]
  27. array_function_dispatch = functools.partial(
  28. overrides.array_function_dispatch, module='numpy')
  29. def _make_along_axis_idx(arr_shape, indices, axis):
  30. # compute dimensions to iterate over
  31. if not _nx.issubdtype(indices.dtype, _nx.integer):
  32. raise IndexError('`indices` must be an integer array')
  33. if len(arr_shape) != indices.ndim:
  34. raise ValueError(
  35. "`indices` and `arr` must have the same number of dimensions")
  36. shape_ones = (1,) * indices.ndim
  37. dest_dims = list(range(axis)) + [None] + list(range(axis + 1, indices.ndim))
  38. # build a fancy index, consisting of orthogonal aranges, with the
  39. # requested index inserted at the right location
  40. fancy_index = []
  41. for dim, n in zip(dest_dims, arr_shape):
  42. if dim is None:
  43. fancy_index.append(indices)
  44. else:
  45. ind_shape = shape_ones[:dim] + (-1,) + shape_ones[dim + 1:]
  46. fancy_index.append(_nx.arange(n).reshape(ind_shape))
  47. return tuple(fancy_index)
  48. def _take_along_axis_dispatcher(arr, indices, axis=None):
  49. return (arr, indices)
  50. @array_function_dispatch(_take_along_axis_dispatcher)
  51. def take_along_axis(arr, indices, axis=-1):
  52. """
  53. Take values from the input array by matching 1d index and data slices.
  54. This iterates over matching 1d slices oriented along the specified axis in
  55. the index and data arrays, and uses the former to look up values in the
  56. latter. These slices can be different lengths.
  57. Functions returning an index along an axis, like `argsort` and
  58. `argpartition`, produce suitable indices for this function.
  59. Parameters
  60. ----------
  61. arr : ndarray (Ni..., M, Nk...)
  62. Source array
  63. indices : ndarray (Ni..., J, Nk...)
  64. Indices to take along each 1d slice of ``arr``. This must match the
  65. dimension of ``arr``, but dimensions Ni and Nj only need to broadcast
  66. against ``arr``.
  67. axis : int or None, optional
  68. The axis to take 1d slices along. If axis is None, the input array is
  69. treated as if it had first been flattened to 1d, for consistency with
  70. `sort` and `argsort`.
  71. .. versionchanged:: 2.3
  72. The default value is now ``-1``.
  73. Returns
  74. -------
  75. out: ndarray (Ni..., J, Nk...)
  76. The indexed result.
  77. Notes
  78. -----
  79. This is equivalent to (but faster than) the following use of `ndindex` and
  80. `s_`, which sets each of ``ii`` and ``kk`` to a tuple of indices::
  81. Ni, M, Nk = a.shape[:axis], a.shape[axis], a.shape[axis+1:]
  82. J = indices.shape[axis] # Need not equal M
  83. out = np.empty(Ni + (J,) + Nk)
  84. for ii in ndindex(Ni):
  85. for kk in ndindex(Nk):
  86. a_1d = a [ii + s_[:,] + kk]
  87. indices_1d = indices[ii + s_[:,] + kk]
  88. out_1d = out [ii + s_[:,] + kk]
  89. for j in range(J):
  90. out_1d[j] = a_1d[indices_1d[j]]
  91. Equivalently, eliminating the inner loop, the last two lines would be::
  92. out_1d[:] = a_1d[indices_1d]
  93. See Also
  94. --------
  95. take : Take along an axis, using the same indices for every 1d slice
  96. put_along_axis :
  97. Put values into the destination array by matching 1d index and data slices
  98. Examples
  99. --------
  100. >>> import numpy as np
  101. For this sample array
  102. >>> a = np.array([[10, 30, 20], [60, 40, 50]])
  103. We can sort either by using sort directly, or argsort and this function
  104. >>> np.sort(a, axis=1)
  105. array([[10, 20, 30],
  106. [40, 50, 60]])
  107. >>> ai = np.argsort(a, axis=1)
  108. >>> ai
  109. array([[0, 2, 1],
  110. [1, 2, 0]])
  111. >>> np.take_along_axis(a, ai, axis=1)
  112. array([[10, 20, 30],
  113. [40, 50, 60]])
  114. The same works for max and min, if you maintain the trivial dimension
  115. with ``keepdims``:
  116. >>> np.max(a, axis=1, keepdims=True)
  117. array([[30],
  118. [60]])
  119. >>> ai = np.argmax(a, axis=1, keepdims=True)
  120. >>> ai
  121. array([[1],
  122. [0]])
  123. >>> np.take_along_axis(a, ai, axis=1)
  124. array([[30],
  125. [60]])
  126. If we want to get the max and min at the same time, we can stack the
  127. indices first
  128. >>> ai_min = np.argmin(a, axis=1, keepdims=True)
  129. >>> ai_max = np.argmax(a, axis=1, keepdims=True)
  130. >>> ai = np.concatenate([ai_min, ai_max], axis=1)
  131. >>> ai
  132. array([[0, 1],
  133. [1, 0]])
  134. >>> np.take_along_axis(a, ai, axis=1)
  135. array([[10, 30],
  136. [40, 60]])
  137. """
  138. # normalize inputs
  139. if axis is None:
  140. if indices.ndim != 1:
  141. raise ValueError(
  142. 'when axis=None, `indices` must have a single dimension.')
  143. arr = np.array(arr.flat)
  144. axis = 0
  145. else:
  146. axis = normalize_axis_index(axis, arr.ndim)
  147. # use the fancy index
  148. return arr[_make_along_axis_idx(arr.shape, indices, axis)]
  149. def _put_along_axis_dispatcher(arr, indices, values, axis):
  150. return (arr, indices, values)
  151. @array_function_dispatch(_put_along_axis_dispatcher)
  152. def put_along_axis(arr, indices, values, axis):
  153. """
  154. Put values into the destination array by matching 1d index and data slices.
  155. This iterates over matching 1d slices oriented along the specified axis in
  156. the index and data arrays, and uses the former to place values into the
  157. latter. These slices can be different lengths.
  158. Functions returning an index along an axis, like `argsort` and
  159. `argpartition`, produce suitable indices for this function.
  160. Parameters
  161. ----------
  162. arr : ndarray (Ni..., M, Nk...)
  163. Destination array.
  164. indices : ndarray (Ni..., J, Nk...)
  165. Indices to change along each 1d slice of `arr`. This must match the
  166. dimension of arr, but dimensions in Ni and Nj may be 1 to broadcast
  167. against `arr`.
  168. values : array_like (Ni..., J, Nk...)
  169. values to insert at those indices. Its shape and dimension are
  170. broadcast to match that of `indices`.
  171. axis : int
  172. The axis to take 1d slices along. If axis is None, the destination
  173. array is treated as if a flattened 1d view had been created of it.
  174. Notes
  175. -----
  176. This is equivalent to (but faster than) the following use of `ndindex` and
  177. `s_`, which sets each of ``ii`` and ``kk`` to a tuple of indices::
  178. Ni, M, Nk = a.shape[:axis], a.shape[axis], a.shape[axis+1:]
  179. J = indices.shape[axis] # Need not equal M
  180. for ii in ndindex(Ni):
  181. for kk in ndindex(Nk):
  182. a_1d = a [ii + s_[:,] + kk]
  183. indices_1d = indices[ii + s_[:,] + kk]
  184. values_1d = values [ii + s_[:,] + kk]
  185. for j in range(J):
  186. a_1d[indices_1d[j]] = values_1d[j]
  187. Equivalently, eliminating the inner loop, the last two lines would be::
  188. a_1d[indices_1d] = values_1d
  189. See Also
  190. --------
  191. take_along_axis :
  192. Take values from the input array by matching 1d index and data slices
  193. Examples
  194. --------
  195. >>> import numpy as np
  196. For this sample array
  197. >>> a = np.array([[10, 30, 20], [60, 40, 50]])
  198. We can replace the maximum values with:
  199. >>> ai = np.argmax(a, axis=1, keepdims=True)
  200. >>> ai
  201. array([[1],
  202. [0]])
  203. >>> np.put_along_axis(a, ai, 99, axis=1)
  204. >>> a
  205. array([[10, 99, 20],
  206. [99, 40, 50]])
  207. """
  208. # normalize inputs
  209. if axis is None:
  210. if indices.ndim != 1:
  211. raise ValueError(
  212. 'when axis=None, `indices` must have a single dimension.')
  213. arr = np.array(arr.flat)
  214. axis = 0
  215. else:
  216. axis = normalize_axis_index(axis, arr.ndim)
  217. # use the fancy index
  218. arr[_make_along_axis_idx(arr.shape, indices, axis)] = values
  219. def _apply_along_axis_dispatcher(func1d, axis, arr, *args, **kwargs):
  220. return (arr,)
  221. @array_function_dispatch(_apply_along_axis_dispatcher)
  222. def apply_along_axis(func1d, axis, arr, *args, **kwargs):
  223. """
  224. Apply a function to 1-D slices along the given axis.
  225. Execute `func1d(a, *args, **kwargs)` where `func1d` operates on 1-D arrays
  226. and `a` is a 1-D slice of `arr` along `axis`.
  227. This is equivalent to (but faster than) the following use of `ndindex` and
  228. `s_`, which sets each of ``ii``, ``jj``, and ``kk`` to a tuple of indices::
  229. Ni, Nk = a.shape[:axis], a.shape[axis+1:]
  230. for ii in ndindex(Ni):
  231. for kk in ndindex(Nk):
  232. f = func1d(arr[ii + s_[:,] + kk])
  233. Nj = f.shape
  234. for jj in ndindex(Nj):
  235. out[ii + jj + kk] = f[jj]
  236. Equivalently, eliminating the inner loop, this can be expressed as::
  237. Ni, Nk = a.shape[:axis], a.shape[axis+1:]
  238. for ii in ndindex(Ni):
  239. for kk in ndindex(Nk):
  240. out[ii + s_[...,] + kk] = func1d(arr[ii + s_[:,] + kk])
  241. Parameters
  242. ----------
  243. func1d : function (M,) -> (Nj...)
  244. This function should accept 1-D arrays. It is applied to 1-D
  245. slices of `arr` along the specified axis.
  246. axis : integer
  247. Axis along which `arr` is sliced.
  248. arr : ndarray (Ni..., M, Nk...)
  249. Input array.
  250. args : any
  251. Additional arguments to `func1d`.
  252. kwargs : any
  253. Additional named arguments to `func1d`.
  254. Returns
  255. -------
  256. out : ndarray (Ni..., Nj..., Nk...)
  257. The output array. The shape of `out` is identical to the shape of
  258. `arr`, except along the `axis` dimension. This axis is removed, and
  259. replaced with new dimensions equal to the shape of the return value
  260. of `func1d`. So if `func1d` returns a scalar `out` will have one
  261. fewer dimensions than `arr`.
  262. See Also
  263. --------
  264. apply_over_axes : Apply a function repeatedly over multiple axes.
  265. Examples
  266. --------
  267. >>> import numpy as np
  268. >>> def my_func(a):
  269. ... \"\"\"Average first and last element of a 1-D array\"\"\"
  270. ... return (a[0] + a[-1]) * 0.5
  271. >>> b = np.array([[1,2,3], [4,5,6], [7,8,9]])
  272. >>> np.apply_along_axis(my_func, 0, b)
  273. array([4., 5., 6.])
  274. >>> np.apply_along_axis(my_func, 1, b)
  275. array([2., 5., 8.])
  276. For a function that returns a 1D array, the number of dimensions in
  277. `outarr` is the same as `arr`.
  278. >>> b = np.array([[8,1,7], [4,3,9], [5,2,6]])
  279. >>> np.apply_along_axis(sorted, 1, b)
  280. array([[1, 7, 8],
  281. [3, 4, 9],
  282. [2, 5, 6]])
  283. For a function that returns a higher dimensional array, those dimensions
  284. are inserted in place of the `axis` dimension.
  285. >>> b = np.array([[1,2,3], [4,5,6], [7,8,9]])
  286. >>> np.apply_along_axis(np.diag, -1, b)
  287. array([[[1, 0, 0],
  288. [0, 2, 0],
  289. [0, 0, 3]],
  290. [[4, 0, 0],
  291. [0, 5, 0],
  292. [0, 0, 6]],
  293. [[7, 0, 0],
  294. [0, 8, 0],
  295. [0, 0, 9]]])
  296. """
  297. # handle negative axes
  298. conv = _array_converter(arr)
  299. arr = conv[0]
  300. nd = arr.ndim
  301. axis = normalize_axis_index(axis, nd)
  302. # arr, with the iteration axis at the end
  303. in_dims = list(range(nd))
  304. inarr_view = transpose(arr, in_dims[:axis] + in_dims[axis + 1:] + [axis])
  305. # compute indices for the iteration axes, and append a trailing ellipsis to
  306. # prevent 0d arrays decaying to scalars, which fixes gh-8642
  307. inds = ndindex(inarr_view.shape[:-1])
  308. inds = (ind + (Ellipsis,) for ind in inds)
  309. # invoke the function on the first item
  310. try:
  311. ind0 = next(inds)
  312. except StopIteration:
  313. raise ValueError(
  314. 'Cannot apply_along_axis when any iteration dimensions are 0'
  315. ) from None
  316. res = asanyarray(func1d(inarr_view[ind0], *args, **kwargs))
  317. # build a buffer for storing evaluations of func1d.
  318. # remove the requested axis, and add the new ones on the end.
  319. # laid out so that each write is contiguous.
  320. # for a tuple index inds, buff[inds] = func1d(inarr_view[inds])
  321. if not isinstance(res, matrix):
  322. buff = zeros_like(res, shape=inarr_view.shape[:-1] + res.shape)
  323. else:
  324. # Matrices are nasty with reshaping, so do not preserve them here.
  325. buff = zeros(inarr_view.shape[:-1] + res.shape, dtype=res.dtype)
  326. # permutation of axes such that out = buff.transpose(buff_permute)
  327. buff_dims = list(range(buff.ndim))
  328. buff_permute = (
  329. buff_dims[0 : axis] +
  330. buff_dims[buff.ndim - res.ndim : buff.ndim] +
  331. buff_dims[axis : buff.ndim - res.ndim]
  332. )
  333. # save the first result, then compute and save all remaining results
  334. buff[ind0] = res
  335. for ind in inds:
  336. buff[ind] = asanyarray(func1d(inarr_view[ind], *args, **kwargs))
  337. res = transpose(buff, buff_permute)
  338. return conv.wrap(res)
  339. def _apply_over_axes_dispatcher(func, a, axes):
  340. return (a,)
  341. @array_function_dispatch(_apply_over_axes_dispatcher)
  342. def apply_over_axes(func, a, axes):
  343. """
  344. Apply a function repeatedly over multiple axes.
  345. `func` is called as `res = func(a, axis)`, where `axis` is the first
  346. element of `axes`. The result `res` of the function call must have
  347. either the same dimensions as `a` or one less dimension. If `res`
  348. has one less dimension than `a`, a dimension is inserted before
  349. `axis`. The call to `func` is then repeated for each axis in `axes`,
  350. with `res` as the first argument.
  351. Parameters
  352. ----------
  353. func : function
  354. This function must take two arguments, `func(a, axis)`.
  355. a : array_like
  356. Input array.
  357. axes : array_like
  358. Axes over which `func` is applied; the elements must be integers.
  359. Returns
  360. -------
  361. apply_over_axis : ndarray
  362. The output array. The number of dimensions is the same as `a`,
  363. but the shape can be different. This depends on whether `func`
  364. changes the shape of its output with respect to its input.
  365. See Also
  366. --------
  367. apply_along_axis :
  368. Apply a function to 1-D slices of an array along the given axis.
  369. Notes
  370. -----
  371. This function is equivalent to tuple axis arguments to reorderable ufuncs
  372. with keepdims=True. Tuple axis arguments to ufuncs have been available since
  373. version 1.7.0.
  374. Examples
  375. --------
  376. >>> import numpy as np
  377. >>> a = np.arange(24).reshape(2,3,4)
  378. >>> a
  379. array([[[ 0, 1, 2, 3],
  380. [ 4, 5, 6, 7],
  381. [ 8, 9, 10, 11]],
  382. [[12, 13, 14, 15],
  383. [16, 17, 18, 19],
  384. [20, 21, 22, 23]]])
  385. Sum over axes 0 and 2. The result has same number of dimensions
  386. as the original array:
  387. >>> np.apply_over_axes(np.sum, a, [0,2])
  388. array([[[ 60],
  389. [ 92],
  390. [124]]])
  391. Tuple axis arguments to ufuncs are equivalent:
  392. >>> np.sum(a, axis=(0,2), keepdims=True)
  393. array([[[ 60],
  394. [ 92],
  395. [124]]])
  396. """
  397. val = asarray(a)
  398. N = a.ndim
  399. if array(axes).ndim == 0:
  400. axes = (axes,)
  401. for axis in axes:
  402. if axis < 0:
  403. axis = N + axis
  404. args = (val, axis)
  405. res = func(*args)
  406. if res.ndim == val.ndim:
  407. val = res
  408. else:
  409. res = expand_dims(res, axis)
  410. if res.ndim == val.ndim:
  411. val = res
  412. else:
  413. raise ValueError("function is not returning "
  414. "an array of the correct shape")
  415. return val
  416. def _expand_dims_dispatcher(a, axis):
  417. return (a,)
  418. @array_function_dispatch(_expand_dims_dispatcher)
  419. def expand_dims(a, axis):
  420. """
  421. Expand the shape of an array.
  422. Insert a new axis that will appear at the `axis` position in the expanded
  423. array shape.
  424. Parameters
  425. ----------
  426. a : array_like
  427. Input array.
  428. axis : int or tuple of ints
  429. Position in the expanded axes where the new axis (or axes) is placed.
  430. .. deprecated:: 1.13.0
  431. Passing an axis where ``axis > a.ndim`` will be treated as
  432. ``axis == a.ndim``, and passing ``axis < -a.ndim - 1`` will
  433. be treated as ``axis == 0``. This behavior is deprecated.
  434. Returns
  435. -------
  436. result : ndarray
  437. View of `a` with the number of dimensions increased.
  438. See Also
  439. --------
  440. squeeze : The inverse operation, removing singleton dimensions
  441. reshape : Insert, remove, and combine dimensions, and resize existing ones
  442. atleast_1d, atleast_2d, atleast_3d
  443. Examples
  444. --------
  445. >>> import numpy as np
  446. >>> x = np.array([1, 2])
  447. >>> x.shape
  448. (2,)
  449. The following is equivalent to ``x[np.newaxis, :]`` or ``x[np.newaxis]``:
  450. >>> y = np.expand_dims(x, axis=0)
  451. >>> y
  452. array([[1, 2]])
  453. >>> y.shape
  454. (1, 2)
  455. The following is equivalent to ``x[:, np.newaxis]``:
  456. >>> y = np.expand_dims(x, axis=1)
  457. >>> y
  458. array([[1],
  459. [2]])
  460. >>> y.shape
  461. (2, 1)
  462. ``axis`` may also be a tuple:
  463. >>> y = np.expand_dims(x, axis=(0, 1))
  464. >>> y
  465. array([[[1, 2]]])
  466. >>> y = np.expand_dims(x, axis=(2, 0))
  467. >>> y
  468. array([[[1],
  469. [2]]])
  470. Note that some examples may use ``None`` instead of ``np.newaxis``. These
  471. are the same objects:
  472. >>> np.newaxis is None
  473. True
  474. """
  475. if isinstance(a, matrix):
  476. a = asarray(a)
  477. else:
  478. a = asanyarray(a)
  479. if not isinstance(axis, (tuple, list)):
  480. axis = (axis,)
  481. out_ndim = len(axis) + a.ndim
  482. axis = normalize_axis_tuple(axis, out_ndim)
  483. shape_it = iter(a.shape)
  484. shape = [1 if ax in axis else next(shape_it) for ax in range(out_ndim)]
  485. return a.reshape(shape)
  486. # NOTE: Remove once deprecation period passes
  487. @set_module("numpy")
  488. def row_stack(tup, *, dtype=None, casting="same_kind"):
  489. # Deprecated in NumPy 2.0, 2023-08-18
  490. warnings.warn(
  491. "`row_stack` alias is deprecated. "
  492. "Use `np.vstack` directly.",
  493. DeprecationWarning,
  494. stacklevel=2
  495. )
  496. return vstack(tup, dtype=dtype, casting=casting)
  497. row_stack.__doc__ = vstack.__doc__
  498. def _column_stack_dispatcher(tup):
  499. return _arrays_for_stack_dispatcher(tup)
  500. @array_function_dispatch(_column_stack_dispatcher)
  501. def column_stack(tup):
  502. """
  503. Stack 1-D arrays as columns into a 2-D array.
  504. Take a sequence of 1-D arrays and stack them as columns
  505. to make a single 2-D array. 2-D arrays are stacked as-is,
  506. just like with `hstack`. 1-D arrays are turned into 2-D columns
  507. first.
  508. Parameters
  509. ----------
  510. tup : sequence of 1-D or 2-D arrays.
  511. Arrays to stack. All of them must have the same first dimension.
  512. Returns
  513. -------
  514. stacked : 2-D array
  515. The array formed by stacking the given arrays.
  516. See Also
  517. --------
  518. stack, hstack, vstack, concatenate
  519. Examples
  520. --------
  521. >>> import numpy as np
  522. >>> a = np.array((1,2,3))
  523. >>> b = np.array((4,5,6))
  524. >>> np.column_stack((a,b))
  525. array([[1, 4],
  526. [2, 5],
  527. [3, 6]])
  528. """
  529. arrays = []
  530. for v in tup:
  531. arr = asanyarray(v)
  532. if arr.ndim < 2:
  533. arr = array(arr, copy=None, subok=True, ndmin=2).T
  534. arrays.append(arr)
  535. return _nx.concatenate(arrays, 1)
  536. def _dstack_dispatcher(tup):
  537. return _arrays_for_stack_dispatcher(tup)
  538. @array_function_dispatch(_dstack_dispatcher)
  539. def dstack(tup):
  540. """
  541. Stack arrays in sequence depth wise (along third axis).
  542. This is equivalent to concatenation along the third axis after 2-D arrays
  543. of shape `(M,N)` have been reshaped to `(M,N,1)` and 1-D arrays of shape
  544. `(N,)` have been reshaped to `(1,N,1)`. Rebuilds arrays divided by
  545. `dsplit`.
  546. This function makes most sense for arrays with up to 3 dimensions. For
  547. instance, for pixel-data with a height (first axis), width (second axis),
  548. and r/g/b channels (third axis). The functions `concatenate`, `stack` and
  549. `block` provide more general stacking and concatenation operations.
  550. Parameters
  551. ----------
  552. tup : sequence of arrays
  553. The arrays must have the same shape along all but the third axis.
  554. 1-D or 2-D arrays must have the same shape.
  555. Returns
  556. -------
  557. stacked : ndarray
  558. The array formed by stacking the given arrays, will be at least 3-D.
  559. See Also
  560. --------
  561. concatenate : Join a sequence of arrays along an existing axis.
  562. stack : Join a sequence of arrays along a new axis.
  563. block : Assemble an nd-array from nested lists of blocks.
  564. vstack : Stack arrays in sequence vertically (row wise).
  565. hstack : Stack arrays in sequence horizontally (column wise).
  566. column_stack : Stack 1-D arrays as columns into a 2-D array.
  567. dsplit : Split array along third axis.
  568. Examples
  569. --------
  570. >>> import numpy as np
  571. >>> a = np.array((1,2,3))
  572. >>> b = np.array((4,5,6))
  573. >>> np.dstack((a,b))
  574. array([[[1, 4],
  575. [2, 5],
  576. [3, 6]]])
  577. >>> a = np.array([[1],[2],[3]])
  578. >>> b = np.array([[4],[5],[6]])
  579. >>> np.dstack((a,b))
  580. array([[[1, 4]],
  581. [[2, 5]],
  582. [[3, 6]]])
  583. """
  584. arrs = atleast_3d(*tup)
  585. if not isinstance(arrs, tuple):
  586. arrs = (arrs,)
  587. return _nx.concatenate(arrs, 2)
  588. def _array_split_dispatcher(ary, indices_or_sections, axis=None):
  589. return (ary, indices_or_sections)
  590. @array_function_dispatch(_array_split_dispatcher)
  591. def array_split(ary, indices_or_sections, axis=0):
  592. """
  593. Split an array into multiple sub-arrays.
  594. Please refer to the ``split`` documentation. The only difference
  595. between these functions is that ``array_split`` allows
  596. `indices_or_sections` to be an integer that does *not* equally
  597. divide the axis. For an array of length l that should be split
  598. into n sections, it returns l % n sub-arrays of size l//n + 1
  599. and the rest of size l//n.
  600. See Also
  601. --------
  602. split : Split array into multiple sub-arrays of equal size.
  603. Examples
  604. --------
  605. >>> import numpy as np
  606. >>> x = np.arange(8.0)
  607. >>> np.array_split(x, 3)
  608. [array([0., 1., 2.]), array([3., 4., 5.]), array([6., 7.])]
  609. >>> x = np.arange(9)
  610. >>> np.array_split(x, 4)
  611. [array([0, 1, 2]), array([3, 4]), array([5, 6]), array([7, 8])]
  612. """
  613. try:
  614. Ntotal = ary.shape[axis]
  615. except AttributeError:
  616. Ntotal = len(ary)
  617. try:
  618. # handle array case.
  619. Nsections = len(indices_or_sections) + 1
  620. div_points = [0] + list(indices_or_sections) + [Ntotal]
  621. except TypeError:
  622. # indices_or_sections is a scalar, not an array.
  623. Nsections = int(indices_or_sections)
  624. if Nsections <= 0:
  625. raise ValueError('number sections must be larger than 0.') from None
  626. Neach_section, extras = divmod(Ntotal, Nsections)
  627. section_sizes = ([0] +
  628. extras * [Neach_section + 1] +
  629. (Nsections - extras) * [Neach_section])
  630. div_points = _nx.array(section_sizes, dtype=_nx.intp).cumsum()
  631. sub_arys = []
  632. sary = _nx.swapaxes(ary, axis, 0)
  633. for i in range(Nsections):
  634. st = div_points[i]
  635. end = div_points[i + 1]
  636. sub_arys.append(_nx.swapaxes(sary[st:end], axis, 0))
  637. return sub_arys
  638. def _split_dispatcher(ary, indices_or_sections, axis=None):
  639. return (ary, indices_or_sections)
  640. @array_function_dispatch(_split_dispatcher)
  641. def split(ary, indices_or_sections, axis=0):
  642. """
  643. Split an array into multiple sub-arrays as views into `ary`.
  644. Parameters
  645. ----------
  646. ary : ndarray
  647. Array to be divided into sub-arrays.
  648. indices_or_sections : int or 1-D array
  649. If `indices_or_sections` is an integer, N, the array will be divided
  650. into N equal arrays along `axis`. If such a split is not possible,
  651. an error is raised.
  652. If `indices_or_sections` is a 1-D array of sorted integers, the entries
  653. indicate where along `axis` the array is split. For example,
  654. ``[2, 3]`` would, for ``axis=0``, result in
  655. - ary[:2]
  656. - ary[2:3]
  657. - ary[3:]
  658. If an index exceeds the dimension of the array along `axis`,
  659. an empty sub-array is returned correspondingly.
  660. axis : int, optional
  661. The axis along which to split, default is 0.
  662. Returns
  663. -------
  664. sub-arrays : list of ndarrays
  665. A list of sub-arrays as views into `ary`.
  666. Raises
  667. ------
  668. ValueError
  669. If `indices_or_sections` is given as an integer, but
  670. a split does not result in equal division.
  671. See Also
  672. --------
  673. array_split : Split an array into multiple sub-arrays of equal or
  674. near-equal size. Does not raise an exception if
  675. an equal division cannot be made.
  676. hsplit : Split array into multiple sub-arrays horizontally (column-wise).
  677. vsplit : Split array into multiple sub-arrays vertically (row wise).
  678. dsplit : Split array into multiple sub-arrays along the 3rd axis (depth).
  679. concatenate : Join a sequence of arrays along an existing axis.
  680. stack : Join a sequence of arrays along a new axis.
  681. hstack : Stack arrays in sequence horizontally (column wise).
  682. vstack : Stack arrays in sequence vertically (row wise).
  683. dstack : Stack arrays in sequence depth wise (along third dimension).
  684. Examples
  685. --------
  686. >>> import numpy as np
  687. >>> x = np.arange(9.0)
  688. >>> np.split(x, 3)
  689. [array([0., 1., 2.]), array([3., 4., 5.]), array([6., 7., 8.])]
  690. >>> x = np.arange(8.0)
  691. >>> np.split(x, [3, 5, 6, 10])
  692. [array([0., 1., 2.]),
  693. array([3., 4.]),
  694. array([5.]),
  695. array([6., 7.]),
  696. array([], dtype=float64)]
  697. """
  698. try:
  699. len(indices_or_sections)
  700. except TypeError:
  701. sections = indices_or_sections
  702. N = ary.shape[axis]
  703. if N % sections:
  704. raise ValueError(
  705. 'array split does not result in an equal division') from None
  706. return array_split(ary, indices_or_sections, axis)
  707. def _hvdsplit_dispatcher(ary, indices_or_sections):
  708. return (ary, indices_or_sections)
  709. @array_function_dispatch(_hvdsplit_dispatcher)
  710. def hsplit(ary, indices_or_sections):
  711. """
  712. Split an array into multiple sub-arrays horizontally (column-wise).
  713. Please refer to the `split` documentation. `hsplit` is equivalent
  714. to `split` with ``axis=1``, the array is always split along the second
  715. axis except for 1-D arrays, where it is split at ``axis=0``.
  716. See Also
  717. --------
  718. split : Split an array into multiple sub-arrays of equal size.
  719. Examples
  720. --------
  721. >>> import numpy as np
  722. >>> x = np.arange(16.0).reshape(4, 4)
  723. >>> x
  724. array([[ 0., 1., 2., 3.],
  725. [ 4., 5., 6., 7.],
  726. [ 8., 9., 10., 11.],
  727. [12., 13., 14., 15.]])
  728. >>> np.hsplit(x, 2)
  729. [array([[ 0., 1.],
  730. [ 4., 5.],
  731. [ 8., 9.],
  732. [12., 13.]]),
  733. array([[ 2., 3.],
  734. [ 6., 7.],
  735. [10., 11.],
  736. [14., 15.]])]
  737. >>> np.hsplit(x, np.array([3, 6]))
  738. [array([[ 0., 1., 2.],
  739. [ 4., 5., 6.],
  740. [ 8., 9., 10.],
  741. [12., 13., 14.]]),
  742. array([[ 3.],
  743. [ 7.],
  744. [11.],
  745. [15.]]),
  746. array([], shape=(4, 0), dtype=float64)]
  747. With a higher dimensional array the split is still along the second axis.
  748. >>> x = np.arange(8.0).reshape(2, 2, 2)
  749. >>> x
  750. array([[[0., 1.],
  751. [2., 3.]],
  752. [[4., 5.],
  753. [6., 7.]]])
  754. >>> np.hsplit(x, 2)
  755. [array([[[0., 1.]],
  756. [[4., 5.]]]),
  757. array([[[2., 3.]],
  758. [[6., 7.]]])]
  759. With a 1-D array, the split is along axis 0.
  760. >>> x = np.array([0, 1, 2, 3, 4, 5])
  761. >>> np.hsplit(x, 2)
  762. [array([0, 1, 2]), array([3, 4, 5])]
  763. """
  764. if _nx.ndim(ary) == 0:
  765. raise ValueError('hsplit only works on arrays of 1 or more dimensions')
  766. if ary.ndim > 1:
  767. return split(ary, indices_or_sections, 1)
  768. else:
  769. return split(ary, indices_or_sections, 0)
  770. @array_function_dispatch(_hvdsplit_dispatcher)
  771. def vsplit(ary, indices_or_sections):
  772. """
  773. Split an array into multiple sub-arrays vertically (row-wise).
  774. Please refer to the ``split`` documentation. ``vsplit`` is equivalent
  775. to ``split`` with `axis=0` (default), the array is always split along the
  776. first axis regardless of the array dimension.
  777. See Also
  778. --------
  779. split : Split an array into multiple sub-arrays of equal size.
  780. Examples
  781. --------
  782. >>> import numpy as np
  783. >>> x = np.arange(16.0).reshape(4, 4)
  784. >>> x
  785. array([[ 0., 1., 2., 3.],
  786. [ 4., 5., 6., 7.],
  787. [ 8., 9., 10., 11.],
  788. [12., 13., 14., 15.]])
  789. >>> np.vsplit(x, 2)
  790. [array([[0., 1., 2., 3.],
  791. [4., 5., 6., 7.]]),
  792. array([[ 8., 9., 10., 11.],
  793. [12., 13., 14., 15.]])]
  794. >>> np.vsplit(x, np.array([3, 6]))
  795. [array([[ 0., 1., 2., 3.],
  796. [ 4., 5., 6., 7.],
  797. [ 8., 9., 10., 11.]]),
  798. array([[12., 13., 14., 15.]]),
  799. array([], shape=(0, 4), dtype=float64)]
  800. With a higher dimensional array the split is still along the first axis.
  801. >>> x = np.arange(8.0).reshape(2, 2, 2)
  802. >>> x
  803. array([[[0., 1.],
  804. [2., 3.]],
  805. [[4., 5.],
  806. [6., 7.]]])
  807. >>> np.vsplit(x, 2)
  808. [array([[[0., 1.],
  809. [2., 3.]]]),
  810. array([[[4., 5.],
  811. [6., 7.]]])]
  812. """
  813. if _nx.ndim(ary) < 2:
  814. raise ValueError('vsplit only works on arrays of 2 or more dimensions')
  815. return split(ary, indices_or_sections, 0)
  816. @array_function_dispatch(_hvdsplit_dispatcher)
  817. def dsplit(ary, indices_or_sections):
  818. """
  819. Split array into multiple sub-arrays along the 3rd axis (depth).
  820. Please refer to the `split` documentation. `dsplit` is equivalent
  821. to `split` with ``axis=2``, the array is always split along the third
  822. axis provided the array dimension is greater than or equal to 3.
  823. See Also
  824. --------
  825. split : Split an array into multiple sub-arrays of equal size.
  826. Examples
  827. --------
  828. >>> import numpy as np
  829. >>> x = np.arange(16.0).reshape(2, 2, 4)
  830. >>> x
  831. array([[[ 0., 1., 2., 3.],
  832. [ 4., 5., 6., 7.]],
  833. [[ 8., 9., 10., 11.],
  834. [12., 13., 14., 15.]]])
  835. >>> np.dsplit(x, 2)
  836. [array([[[ 0., 1.],
  837. [ 4., 5.]],
  838. [[ 8., 9.],
  839. [12., 13.]]]), array([[[ 2., 3.],
  840. [ 6., 7.]],
  841. [[10., 11.],
  842. [14., 15.]]])]
  843. >>> np.dsplit(x, np.array([3, 6]))
  844. [array([[[ 0., 1., 2.],
  845. [ 4., 5., 6.]],
  846. [[ 8., 9., 10.],
  847. [12., 13., 14.]]]),
  848. array([[[ 3.],
  849. [ 7.]],
  850. [[11.],
  851. [15.]]]),
  852. array([], shape=(2, 2, 0), dtype=float64)]
  853. """
  854. if _nx.ndim(ary) < 3:
  855. raise ValueError('dsplit only works on arrays of 3 or more dimensions')
  856. return split(ary, indices_or_sections, 2)
  857. def get_array_wrap(*args):
  858. """Find the wrapper for the array with the highest priority.
  859. In case of ties, leftmost wins. If no wrapper is found, return None.
  860. .. deprecated:: 2.0
  861. """
  862. # Deprecated in NumPy 2.0, 2023-07-11
  863. warnings.warn(
  864. "`get_array_wrap` is deprecated. "
  865. "(deprecated in NumPy 2.0)",
  866. DeprecationWarning,
  867. stacklevel=2
  868. )
  869. wrappers = sorted((getattr(x, '__array_priority__', 0), -i,
  870. x.__array_wrap__) for i, x in enumerate(args)
  871. if hasattr(x, '__array_wrap__'))
  872. if wrappers:
  873. return wrappers[-1][-1]
  874. return None
  875. def _kron_dispatcher(a, b):
  876. return (a, b)
  877. @array_function_dispatch(_kron_dispatcher)
  878. def kron(a, b):
  879. """
  880. Kronecker product of two arrays.
  881. Computes the Kronecker product, a composite array made of blocks of the
  882. second array scaled by the first.
  883. Parameters
  884. ----------
  885. a, b : array_like
  886. Returns
  887. -------
  888. out : ndarray
  889. See Also
  890. --------
  891. outer : The outer product
  892. Notes
  893. -----
  894. The function assumes that the number of dimensions of `a` and `b`
  895. are the same, if necessary prepending the smallest with ones.
  896. If ``a.shape = (r0,r1,...,rN)`` and ``b.shape = (s0,s1,...,sN)``,
  897. the Kronecker product has shape ``(r0*s0, r1*s1, ..., rN*SN)``.
  898. The elements are products of elements from `a` and `b`, organized
  899. explicitly by::
  900. kron(a,b)[k0,k1,...,kN] = a[i0,i1,...,iN] * b[j0,j1,...,jN]
  901. where::
  902. kt = it * st + jt, t = 0,...,N
  903. In the common 2-D case (N=1), the block structure can be visualized::
  904. [[ a[0,0]*b, a[0,1]*b, ... , a[0,-1]*b ],
  905. [ ... ... ],
  906. [ a[-1,0]*b, a[-1,1]*b, ... , a[-1,-1]*b ]]
  907. Examples
  908. --------
  909. >>> import numpy as np
  910. >>> np.kron([1,10,100], [5,6,7])
  911. array([ 5, 6, 7, ..., 500, 600, 700])
  912. >>> np.kron([5,6,7], [1,10,100])
  913. array([ 5, 50, 500, ..., 7, 70, 700])
  914. >>> np.kron(np.eye(2), np.ones((2,2)))
  915. array([[1., 1., 0., 0.],
  916. [1., 1., 0., 0.],
  917. [0., 0., 1., 1.],
  918. [0., 0., 1., 1.]])
  919. >>> a = np.arange(100).reshape((2,5,2,5))
  920. >>> b = np.arange(24).reshape((2,3,4))
  921. >>> c = np.kron(a,b)
  922. >>> c.shape
  923. (2, 10, 6, 20)
  924. >>> I = (1,3,0,2)
  925. >>> J = (0,2,1)
  926. >>> J1 = (0,) + J # extend to ndim=4
  927. >>> S1 = (1,) + b.shape
  928. >>> K = tuple(np.array(I) * np.array(S1) + np.array(J1))
  929. >>> c[K] == a[I]*b[J]
  930. True
  931. """
  932. # Working:
  933. # 1. Equalise the shapes by prepending smaller array with 1s
  934. # 2. Expand shapes of both the arrays by adding new axes at
  935. # odd positions for 1st array and even positions for 2nd
  936. # 3. Compute the product of the modified array
  937. # 4. The inner most array elements now contain the rows of
  938. # the Kronecker product
  939. # 5. Reshape the result to kron's shape, which is same as
  940. # product of shapes of the two arrays.
  941. b = asanyarray(b)
  942. a = array(a, copy=None, subok=True, ndmin=b.ndim)
  943. is_any_mat = isinstance(a, matrix) or isinstance(b, matrix)
  944. ndb, nda = b.ndim, a.ndim
  945. nd = max(ndb, nda)
  946. if (nda == 0 or ndb == 0):
  947. return _nx.multiply(a, b)
  948. as_ = a.shape
  949. bs = b.shape
  950. if not a.flags.contiguous:
  951. a = reshape(a, as_)
  952. if not b.flags.contiguous:
  953. b = reshape(b, bs)
  954. # Equalise the shapes by prepending smaller one with 1s
  955. as_ = (1,) * max(0, ndb - nda) + as_
  956. bs = (1,) * max(0, nda - ndb) + bs
  957. # Insert empty dimensions
  958. a_arr = expand_dims(a, axis=tuple(range(ndb - nda)))
  959. b_arr = expand_dims(b, axis=tuple(range(nda - ndb)))
  960. # Compute the product
  961. a_arr = expand_dims(a_arr, axis=tuple(range(1, nd * 2, 2)))
  962. b_arr = expand_dims(b_arr, axis=tuple(range(0, nd * 2, 2)))
  963. # In case of `mat`, convert result to `array`
  964. result = _nx.multiply(a_arr, b_arr, subok=(not is_any_mat))
  965. # Reshape back
  966. result = result.reshape(_nx.multiply(as_, bs))
  967. return result if not is_any_mat else matrix(result, copy=False)
  968. def _tile_dispatcher(A, reps):
  969. return (A, reps)
  970. @array_function_dispatch(_tile_dispatcher)
  971. def tile(A, reps):
  972. """
  973. Construct an array by repeating A the number of times given by reps.
  974. If `reps` has length ``d``, the result will have dimension of
  975. ``max(d, A.ndim)``.
  976. If ``A.ndim < d``, `A` is promoted to be d-dimensional by prepending new
  977. axes. So a shape (3,) array is promoted to (1, 3) for 2-D replication,
  978. or shape (1, 1, 3) for 3-D replication. If this is not the desired
  979. behavior, promote `A` to d-dimensions manually before calling this
  980. function.
  981. If ``A.ndim > d``, `reps` is promoted to `A`.ndim by prepending 1's to it.
  982. Thus for an `A` of shape (2, 3, 4, 5), a `reps` of (2, 2) is treated as
  983. (1, 1, 2, 2).
  984. Note : Although tile may be used for broadcasting, it is strongly
  985. recommended to use numpy's broadcasting operations and functions.
  986. Parameters
  987. ----------
  988. A : array_like
  989. The input array.
  990. reps : array_like
  991. The number of repetitions of `A` along each axis.
  992. Returns
  993. -------
  994. c : ndarray
  995. The tiled output array.
  996. See Also
  997. --------
  998. repeat : Repeat elements of an array.
  999. broadcast_to : Broadcast an array to a new shape
  1000. Examples
  1001. --------
  1002. >>> import numpy as np
  1003. >>> a = np.array([0, 1, 2])
  1004. >>> np.tile(a, 2)
  1005. array([0, 1, 2, 0, 1, 2])
  1006. >>> np.tile(a, (2, 2))
  1007. array([[0, 1, 2, 0, 1, 2],
  1008. [0, 1, 2, 0, 1, 2]])
  1009. >>> np.tile(a, (2, 1, 2))
  1010. array([[[0, 1, 2, 0, 1, 2]],
  1011. [[0, 1, 2, 0, 1, 2]]])
  1012. >>> b = np.array([[1, 2], [3, 4]])
  1013. >>> np.tile(b, 2)
  1014. array([[1, 2, 1, 2],
  1015. [3, 4, 3, 4]])
  1016. >>> np.tile(b, (2, 1))
  1017. array([[1, 2],
  1018. [3, 4],
  1019. [1, 2],
  1020. [3, 4]])
  1021. >>> c = np.array([1,2,3,4])
  1022. >>> np.tile(c,(4,1))
  1023. array([[1, 2, 3, 4],
  1024. [1, 2, 3, 4],
  1025. [1, 2, 3, 4],
  1026. [1, 2, 3, 4]])
  1027. """
  1028. try:
  1029. tup = tuple(reps)
  1030. except TypeError:
  1031. tup = (reps,)
  1032. d = len(tup)
  1033. if all(x == 1 for x in tup) and isinstance(A, _nx.ndarray):
  1034. # Fixes the problem that the function does not make a copy if A is a
  1035. # numpy array and the repetitions are 1 in all dimensions
  1036. return _nx.array(A, copy=True, subok=True, ndmin=d)
  1037. else:
  1038. # Note that no copy of zero-sized arrays is made. However since they
  1039. # have no data there is no risk of an inadvertent overwrite.
  1040. c = _nx.array(A, copy=None, subok=True, ndmin=d)
  1041. if (d < c.ndim):
  1042. tup = (1,) * (c.ndim - d) + tup
  1043. shape_out = tuple(s * t for s, t in zip(c.shape, tup))
  1044. n = c.size
  1045. if n > 0:
  1046. for dim_in, nrep in zip(c.shape, tup):
  1047. if nrep != 1:
  1048. c = c.reshape(-1, n).repeat(nrep, 0)
  1049. n //= dim_in
  1050. return c.reshape(shape_out)