shape_base.py 38 KB

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