shape_base.py 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274
  1. import functools
  2. import numpy.core.numeric as _nx
  3. from numpy.core.numeric import asarray, zeros, array, asanyarray
  4. from numpy.core.fromnumeric import reshape, transpose
  5. from numpy.core.multiarray import normalize_axis_index
  6. from numpy.core import overrides
  7. from numpy.core import vstack, atleast_3d
  8. from numpy.core.numeric import normalize_axis_tuple
  9. from numpy.core.shape_base import _arrays_for_stack_dispatcher
  10. from numpy.lib.index_tricks import ndindex
  11. from numpy.matrixlib.defmatrix import matrix # this raises all the right alarm bells
  12. __all__ = [
  13. 'column_stack', 'row_stack', 'dstack', 'array_split', 'split',
  14. 'hsplit', 'vsplit', 'dsplit', 'apply_over_axes', 'expand_dims',
  15. 'apply_along_axis', 'kron', 'tile', 'get_array_wrap', 'take_along_axis',
  16. 'put_along_axis'
  17. ]
  18. array_function_dispatch = functools.partial(
  19. overrides.array_function_dispatch, module='numpy')
  20. def _make_along_axis_idx(arr_shape, indices, axis):
  21. # compute dimensions to iterate over
  22. if not _nx.issubdtype(indices.dtype, _nx.integer):
  23. raise IndexError('`indices` must be an integer array')
  24. if len(arr_shape) != indices.ndim:
  25. raise ValueError(
  26. "`indices` and `arr` must have the same number of dimensions")
  27. shape_ones = (1,) * indices.ndim
  28. dest_dims = list(range(axis)) + [None] + list(range(axis+1, indices.ndim))
  29. # build a fancy index, consisting of orthogonal aranges, with the
  30. # requested index inserted at the right location
  31. fancy_index = []
  32. for dim, n in zip(dest_dims, arr_shape):
  33. if dim is None:
  34. fancy_index.append(indices)
  35. else:
  36. ind_shape = shape_ones[:dim] + (-1,) + shape_ones[dim+1:]
  37. fancy_index.append(_nx.arange(n).reshape(ind_shape))
  38. return tuple(fancy_index)
  39. def _take_along_axis_dispatcher(arr, indices, axis):
  40. return (arr, indices)
  41. @array_function_dispatch(_take_along_axis_dispatcher)
  42. def take_along_axis(arr, indices, axis):
  43. """
  44. Take values from the input array by matching 1d index and data slices.
  45. This iterates over matching 1d slices oriented along the specified axis in
  46. the index and data arrays, and uses the former to look up values in the
  47. latter. These slices can be different lengths.
  48. Functions returning an index along an axis, like `argsort` and
  49. `argpartition`, produce suitable indices for this function.
  50. .. versionadded:: 1.15.0
  51. Parameters
  52. ----------
  53. arr : ndarray (Ni..., M, Nk...)
  54. Source array
  55. indices : ndarray (Ni..., J, Nk...)
  56. Indices to take along each 1d slice of `arr`. This must match the
  57. dimension of arr, but dimensions Ni and Nj only need to broadcast
  58. against `arr`.
  59. axis : int
  60. The axis to take 1d slices along. If axis is None, the input array is
  61. treated as if it had first been flattened to 1d, for consistency with
  62. `sort` and `argsort`.
  63. Returns
  64. -------
  65. out: ndarray (Ni..., J, Nk...)
  66. The indexed result.
  67. Notes
  68. -----
  69. This is equivalent to (but faster than) the following use of `ndindex` and
  70. `s_`, which sets each of ``ii`` and ``kk`` to a tuple of indices::
  71. Ni, M, Nk = a.shape[:axis], a.shape[axis], a.shape[axis+1:]
  72. J = indices.shape[axis] # Need not equal M
  73. out = np.empty(Ni + (J,) + Nk)
  74. for ii in ndindex(Ni):
  75. for kk in ndindex(Nk):
  76. a_1d = a [ii + s_[:,] + kk]
  77. indices_1d = indices[ii + s_[:,] + kk]
  78. out_1d = out [ii + s_[:,] + kk]
  79. for j in range(J):
  80. out_1d[j] = a_1d[indices_1d[j]]
  81. Equivalently, eliminating the inner loop, the last two lines would be::
  82. out_1d[:] = a_1d[indices_1d]
  83. See Also
  84. --------
  85. take : Take along an axis, using the same indices for every 1d slice
  86. put_along_axis :
  87. Put values into the destination array by matching 1d index and data slices
  88. Examples
  89. --------
  90. For this sample array
  91. >>> a = np.array([[10, 30, 20], [60, 40, 50]])
  92. We can sort either by using sort directly, or argsort and this function
  93. >>> np.sort(a, axis=1)
  94. array([[10, 20, 30],
  95. [40, 50, 60]])
  96. >>> ai = np.argsort(a, axis=1)
  97. >>> ai
  98. array([[0, 2, 1],
  99. [1, 2, 0]])
  100. >>> np.take_along_axis(a, ai, axis=1)
  101. array([[10, 20, 30],
  102. [40, 50, 60]])
  103. The same works for max and min, if you maintain the trivial dimension
  104. with ``keepdims``:
  105. >>> np.max(a, axis=1, keepdims=True)
  106. array([[30],
  107. [60]])
  108. >>> ai = np.argmax(a, axis=1, keepdims=True)
  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.argmin(a, axis=1, keepdims=True)
  118. >>> ai_max = np.argmax(a, axis=1, keepdims=True)
  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.argmax(a, axis=1, keepdims=True)
  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:
  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. arrays = []
  511. for v in tup:
  512. arr = asanyarray(v)
  513. if arr.ndim < 2:
  514. arr = array(arr, copy=False, subok=True, ndmin=2).T
  515. arrays.append(arr)
  516. return _nx.concatenate(arrays, 1)
  517. def _dstack_dispatcher(tup):
  518. return _arrays_for_stack_dispatcher(tup)
  519. @array_function_dispatch(_dstack_dispatcher)
  520. def dstack(tup):
  521. """
  522. Stack arrays in sequence depth wise (along third axis).
  523. This is equivalent to concatenation along the third axis after 2-D arrays
  524. of shape `(M,N)` have been reshaped to `(M,N,1)` and 1-D arrays of shape
  525. `(N,)` have been reshaped to `(1,N,1)`. Rebuilds arrays divided by
  526. `dsplit`.
  527. This function makes most sense for arrays with up to 3 dimensions. For
  528. instance, for pixel-data with a height (first axis), width (second axis),
  529. and r/g/b channels (third axis). The functions `concatenate`, `stack` and
  530. `block` provide more general stacking and concatenation operations.
  531. Parameters
  532. ----------
  533. tup : sequence of arrays
  534. The arrays must have the same shape along all but the third axis.
  535. 1-D or 2-D arrays must have the same shape.
  536. Returns
  537. -------
  538. stacked : ndarray
  539. The array formed by stacking the given arrays, will be at least 3-D.
  540. See Also
  541. --------
  542. concatenate : Join a sequence of arrays along an existing axis.
  543. stack : Join a sequence of arrays along a new axis.
  544. block : Assemble an nd-array from nested lists of blocks.
  545. vstack : Stack arrays in sequence vertically (row wise).
  546. hstack : Stack arrays in sequence horizontally (column wise).
  547. column_stack : Stack 1-D arrays as columns into a 2-D array.
  548. dsplit : Split array along third axis.
  549. Examples
  550. --------
  551. >>> a = np.array((1,2,3))
  552. >>> b = np.array((2,3,4))
  553. >>> np.dstack((a,b))
  554. array([[[1, 2],
  555. [2, 3],
  556. [3, 4]]])
  557. >>> a = np.array([[1],[2],[3]])
  558. >>> b = np.array([[2],[3],[4]])
  559. >>> np.dstack((a,b))
  560. array([[[1, 2]],
  561. [[2, 3]],
  562. [[3, 4]]])
  563. """
  564. arrs = atleast_3d(*tup)
  565. if not isinstance(arrs, list):
  566. arrs = [arrs]
  567. return _nx.concatenate(arrs, 2)
  568. def _replace_zero_by_x_arrays(sub_arys):
  569. for i in range(len(sub_arys)):
  570. if _nx.ndim(sub_arys[i]) == 0:
  571. sub_arys[i] = _nx.empty(0, dtype=sub_arys[i].dtype)
  572. elif _nx.sometrue(_nx.equal(_nx.shape(sub_arys[i]), 0)):
  573. sub_arys[i] = _nx.empty(0, dtype=sub_arys[i].dtype)
  574. return sub_arys
  575. def _array_split_dispatcher(ary, indices_or_sections, axis=None):
  576. return (ary, indices_or_sections)
  577. @array_function_dispatch(_array_split_dispatcher)
  578. def array_split(ary, indices_or_sections, axis=0):
  579. """
  580. Split an array into multiple sub-arrays.
  581. Please refer to the ``split`` documentation. The only difference
  582. between these functions is that ``array_split`` allows
  583. `indices_or_sections` to be an integer that does *not* equally
  584. divide the axis. For an array of length l that should be split
  585. into n sections, it returns l % n sub-arrays of size l//n + 1
  586. and the rest of size l//n.
  587. See Also
  588. --------
  589. split : Split array into multiple sub-arrays of equal size.
  590. Examples
  591. --------
  592. >>> x = np.arange(8.0)
  593. >>> np.array_split(x, 3)
  594. [array([0., 1., 2.]), array([3., 4., 5.]), array([6., 7.])]
  595. >>> x = np.arange(9)
  596. >>> np.array_split(x, 4)
  597. [array([0, 1, 2]), array([3, 4]), array([5, 6]), array([7, 8])]
  598. """
  599. try:
  600. Ntotal = ary.shape[axis]
  601. except AttributeError:
  602. Ntotal = len(ary)
  603. try:
  604. # handle array case.
  605. Nsections = len(indices_or_sections) + 1
  606. div_points = [0] + list(indices_or_sections) + [Ntotal]
  607. except TypeError:
  608. # indices_or_sections is a scalar, not an array.
  609. Nsections = int(indices_or_sections)
  610. if Nsections <= 0:
  611. raise ValueError('number sections must be larger than 0.') from None
  612. Neach_section, extras = divmod(Ntotal, Nsections)
  613. section_sizes = ([0] +
  614. extras * [Neach_section+1] +
  615. (Nsections-extras) * [Neach_section])
  616. div_points = _nx.array(section_sizes, dtype=_nx.intp).cumsum()
  617. sub_arys = []
  618. sary = _nx.swapaxes(ary, axis, 0)
  619. for i in range(Nsections):
  620. st = div_points[i]
  621. end = div_points[i + 1]
  622. sub_arys.append(_nx.swapaxes(sary[st:end], axis, 0))
  623. return sub_arys
  624. def _split_dispatcher(ary, indices_or_sections, axis=None):
  625. return (ary, indices_or_sections)
  626. @array_function_dispatch(_split_dispatcher)
  627. def split(ary, indices_or_sections, axis=0):
  628. """
  629. Split an array into multiple sub-arrays as views into `ary`.
  630. Parameters
  631. ----------
  632. ary : ndarray
  633. Array to be divided into sub-arrays.
  634. indices_or_sections : int or 1-D array
  635. If `indices_or_sections` is an integer, N, the array will be divided
  636. into N equal arrays along `axis`. If such a split is not possible,
  637. an error is raised.
  638. If `indices_or_sections` is a 1-D array of sorted integers, the entries
  639. indicate where along `axis` the array is split. For example,
  640. ``[2, 3]`` would, for ``axis=0``, result in
  641. - ary[:2]
  642. - ary[2:3]
  643. - ary[3:]
  644. If an index exceeds the dimension of the array along `axis`,
  645. an empty sub-array is returned correspondingly.
  646. axis : int, optional
  647. The axis along which to split, default is 0.
  648. Returns
  649. -------
  650. sub-arrays : list of ndarrays
  651. A list of sub-arrays as views into `ary`.
  652. Raises
  653. ------
  654. ValueError
  655. If `indices_or_sections` is given as an integer, but
  656. a split does not result in equal division.
  657. See Also
  658. --------
  659. array_split : Split an array into multiple sub-arrays of equal or
  660. near-equal size. Does not raise an exception if
  661. an equal division cannot be made.
  662. hsplit : Split array into multiple sub-arrays horizontally (column-wise).
  663. vsplit : Split array into multiple sub-arrays vertically (row wise).
  664. dsplit : Split array into multiple sub-arrays along the 3rd axis (depth).
  665. concatenate : Join a sequence of arrays along an existing axis.
  666. stack : Join a sequence of arrays along a new axis.
  667. hstack : Stack arrays in sequence horizontally (column wise).
  668. vstack : Stack arrays in sequence vertically (row wise).
  669. dstack : Stack arrays in sequence depth wise (along third dimension).
  670. Examples
  671. --------
  672. >>> x = np.arange(9.0)
  673. >>> np.split(x, 3)
  674. [array([0., 1., 2.]), array([3., 4., 5.]), array([6., 7., 8.])]
  675. >>> x = np.arange(8.0)
  676. >>> np.split(x, [3, 5, 6, 10])
  677. [array([0., 1., 2.]),
  678. array([3., 4.]),
  679. array([5.]),
  680. array([6., 7.]),
  681. array([], dtype=float64)]
  682. """
  683. try:
  684. len(indices_or_sections)
  685. except TypeError:
  686. sections = indices_or_sections
  687. N = ary.shape[axis]
  688. if N % sections:
  689. raise ValueError(
  690. 'array split does not result in an equal division') from None
  691. return array_split(ary, indices_or_sections, axis)
  692. def _hvdsplit_dispatcher(ary, indices_or_sections):
  693. return (ary, indices_or_sections)
  694. @array_function_dispatch(_hvdsplit_dispatcher)
  695. def hsplit(ary, indices_or_sections):
  696. """
  697. Split an array into multiple sub-arrays horizontally (column-wise).
  698. Please refer to the `split` documentation. `hsplit` is equivalent
  699. to `split` with ``axis=1``, the array is always split along the second
  700. axis except for 1-D arrays, where it is split at ``axis=0``.
  701. See Also
  702. --------
  703. split : Split an array into multiple sub-arrays of equal size.
  704. Examples
  705. --------
  706. >>> x = np.arange(16.0).reshape(4, 4)
  707. >>> x
  708. array([[ 0., 1., 2., 3.],
  709. [ 4., 5., 6., 7.],
  710. [ 8., 9., 10., 11.],
  711. [12., 13., 14., 15.]])
  712. >>> np.hsplit(x, 2)
  713. [array([[ 0., 1.],
  714. [ 4., 5.],
  715. [ 8., 9.],
  716. [12., 13.]]),
  717. array([[ 2., 3.],
  718. [ 6., 7.],
  719. [10., 11.],
  720. [14., 15.]])]
  721. >>> np.hsplit(x, np.array([3, 6]))
  722. [array([[ 0., 1., 2.],
  723. [ 4., 5., 6.],
  724. [ 8., 9., 10.],
  725. [12., 13., 14.]]),
  726. array([[ 3.],
  727. [ 7.],
  728. [11.],
  729. [15.]]),
  730. array([], shape=(4, 0), dtype=float64)]
  731. With a higher dimensional array the split is still along the second axis.
  732. >>> x = np.arange(8.0).reshape(2, 2, 2)
  733. >>> x
  734. array([[[0., 1.],
  735. [2., 3.]],
  736. [[4., 5.],
  737. [6., 7.]]])
  738. >>> np.hsplit(x, 2)
  739. [array([[[0., 1.]],
  740. [[4., 5.]]]),
  741. array([[[2., 3.]],
  742. [[6., 7.]]])]
  743. With a 1-D array, the split is along axis 0.
  744. >>> x = np.array([0, 1, 2, 3, 4, 5])
  745. >>> np.hsplit(x, 2)
  746. [array([0, 1, 2]), array([3, 4, 5])]
  747. """
  748. if _nx.ndim(ary) == 0:
  749. raise ValueError('hsplit only works on arrays of 1 or more dimensions')
  750. if ary.ndim > 1:
  751. return split(ary, indices_or_sections, 1)
  752. else:
  753. return split(ary, indices_or_sections, 0)
  754. @array_function_dispatch(_hvdsplit_dispatcher)
  755. def vsplit(ary, indices_or_sections):
  756. """
  757. Split an array into multiple sub-arrays vertically (row-wise).
  758. Please refer to the ``split`` documentation. ``vsplit`` is equivalent
  759. to ``split`` with `axis=0` (default), the array is always split along the
  760. first axis regardless of the array dimension.
  761. See Also
  762. --------
  763. split : Split an array into multiple sub-arrays of equal size.
  764. Examples
  765. --------
  766. >>> x = np.arange(16.0).reshape(4, 4)
  767. >>> x
  768. array([[ 0., 1., 2., 3.],
  769. [ 4., 5., 6., 7.],
  770. [ 8., 9., 10., 11.],
  771. [12., 13., 14., 15.]])
  772. >>> np.vsplit(x, 2)
  773. [array([[0., 1., 2., 3.],
  774. [4., 5., 6., 7.]]), array([[ 8., 9., 10., 11.],
  775. [12., 13., 14., 15.]])]
  776. >>> np.vsplit(x, np.array([3, 6]))
  777. [array([[ 0., 1., 2., 3.],
  778. [ 4., 5., 6., 7.],
  779. [ 8., 9., 10., 11.]]), array([[12., 13., 14., 15.]]), array([], shape=(0, 4), dtype=float64)]
  780. With a higher dimensional array the split is still along the first axis.
  781. >>> x = np.arange(8.0).reshape(2, 2, 2)
  782. >>> x
  783. array([[[0., 1.],
  784. [2., 3.]],
  785. [[4., 5.],
  786. [6., 7.]]])
  787. >>> np.vsplit(x, 2)
  788. [array([[[0., 1.],
  789. [2., 3.]]]), array([[[4., 5.],
  790. [6., 7.]]])]
  791. """
  792. if _nx.ndim(ary) < 2:
  793. raise ValueError('vsplit only works on arrays of 2 or more dimensions')
  794. return split(ary, indices_or_sections, 0)
  795. @array_function_dispatch(_hvdsplit_dispatcher)
  796. def dsplit(ary, indices_or_sections):
  797. """
  798. Split array into multiple sub-arrays along the 3rd axis (depth).
  799. Please refer to the `split` documentation. `dsplit` is equivalent
  800. to `split` with ``axis=2``, the array is always split along the third
  801. axis provided the array dimension is greater than or equal to 3.
  802. See Also
  803. --------
  804. split : Split an array into multiple sub-arrays of equal size.
  805. Examples
  806. --------
  807. >>> x = np.arange(16.0).reshape(2, 2, 4)
  808. >>> x
  809. array([[[ 0., 1., 2., 3.],
  810. [ 4., 5., 6., 7.]],
  811. [[ 8., 9., 10., 11.],
  812. [12., 13., 14., 15.]]])
  813. >>> np.dsplit(x, 2)
  814. [array([[[ 0., 1.],
  815. [ 4., 5.]],
  816. [[ 8., 9.],
  817. [12., 13.]]]), array([[[ 2., 3.],
  818. [ 6., 7.]],
  819. [[10., 11.],
  820. [14., 15.]]])]
  821. >>> np.dsplit(x, np.array([3, 6]))
  822. [array([[[ 0., 1., 2.],
  823. [ 4., 5., 6.]],
  824. [[ 8., 9., 10.],
  825. [12., 13., 14.]]]),
  826. array([[[ 3.],
  827. [ 7.]],
  828. [[11.],
  829. [15.]]]),
  830. array([], shape=(2, 2, 0), dtype=float64)]
  831. """
  832. if _nx.ndim(ary) < 3:
  833. raise ValueError('dsplit only works on arrays of 3 or more dimensions')
  834. return split(ary, indices_or_sections, 2)
  835. def get_array_prepare(*args):
  836. """Find the wrapper for the array with the highest priority.
  837. In case of ties, leftmost wins. If no wrapper is found, return None
  838. """
  839. wrappers = sorted((getattr(x, '__array_priority__', 0), -i,
  840. x.__array_prepare__) for i, x in enumerate(args)
  841. if hasattr(x, '__array_prepare__'))
  842. if wrappers:
  843. return wrappers[-1][-1]
  844. return None
  845. def get_array_wrap(*args):
  846. """Find the wrapper for the array with the highest priority.
  847. In case of ties, leftmost wins. If no wrapper is found, return None
  848. """
  849. wrappers = sorted((getattr(x, '__array_priority__', 0), -i,
  850. x.__array_wrap__) for i, x in enumerate(args)
  851. if hasattr(x, '__array_wrap__'))
  852. if wrappers:
  853. return wrappers[-1][-1]
  854. return None
  855. def _kron_dispatcher(a, b):
  856. return (a, b)
  857. @array_function_dispatch(_kron_dispatcher)
  858. def kron(a, b):
  859. """
  860. Kronecker product of two arrays.
  861. Computes the Kronecker product, a composite array made of blocks of the
  862. second array scaled by the first.
  863. Parameters
  864. ----------
  865. a, b : array_like
  866. Returns
  867. -------
  868. out : ndarray
  869. See Also
  870. --------
  871. outer : The outer product
  872. Notes
  873. -----
  874. The function assumes that the number of dimensions of `a` and `b`
  875. are the same, if necessary prepending the smallest with ones.
  876. If ``a.shape = (r0,r1,..,rN)`` and ``b.shape = (s0,s1,...,sN)``,
  877. the Kronecker product has shape ``(r0*s0, r1*s1, ..., rN*SN)``.
  878. The elements are products of elements from `a` and `b`, organized
  879. explicitly by::
  880. kron(a,b)[k0,k1,...,kN] = a[i0,i1,...,iN] * b[j0,j1,...,jN]
  881. where::
  882. kt = it * st + jt, t = 0,...,N
  883. In the common 2-D case (N=1), the block structure can be visualized::
  884. [[ a[0,0]*b, a[0,1]*b, ... , a[0,-1]*b ],
  885. [ ... ... ],
  886. [ a[-1,0]*b, a[-1,1]*b, ... , a[-1,-1]*b ]]
  887. Examples
  888. --------
  889. >>> np.kron([1,10,100], [5,6,7])
  890. array([ 5, 6, 7, ..., 500, 600, 700])
  891. >>> np.kron([5,6,7], [1,10,100])
  892. array([ 5, 50, 500, ..., 7, 70, 700])
  893. >>> np.kron(np.eye(2), np.ones((2,2)))
  894. array([[1., 1., 0., 0.],
  895. [1., 1., 0., 0.],
  896. [0., 0., 1., 1.],
  897. [0., 0., 1., 1.]])
  898. >>> a = np.arange(100).reshape((2,5,2,5))
  899. >>> b = np.arange(24).reshape((2,3,4))
  900. >>> c = np.kron(a,b)
  901. >>> c.shape
  902. (2, 10, 6, 20)
  903. >>> I = (1,3,0,2)
  904. >>> J = (0,2,1)
  905. >>> J1 = (0,) + J # extend to ndim=4
  906. >>> S1 = (1,) + b.shape
  907. >>> K = tuple(np.array(I) * np.array(S1) + np.array(J1))
  908. >>> c[K] == a[I]*b[J]
  909. True
  910. """
  911. # Working:
  912. # 1. Equalise the shapes by prepending smaller array with 1s
  913. # 2. Expand shapes of both the arrays by adding new axes at
  914. # odd positions for 1st array and even positions for 2nd
  915. # 3. Compute the product of the modified array
  916. # 4. The inner most array elements now contain the rows of
  917. # the Kronecker product
  918. # 5. Reshape the result to kron's shape, which is same as
  919. # product of shapes of the two arrays.
  920. b = asanyarray(b)
  921. a = array(a, copy=False, subok=True, ndmin=b.ndim)
  922. is_any_mat = isinstance(a, matrix) or isinstance(b, matrix)
  923. ndb, nda = b.ndim, a.ndim
  924. nd = max(ndb, nda)
  925. if (nda == 0 or ndb == 0):
  926. return _nx.multiply(a, b)
  927. as_ = a.shape
  928. bs = b.shape
  929. if not a.flags.contiguous:
  930. a = reshape(a, as_)
  931. if not b.flags.contiguous:
  932. b = reshape(b, bs)
  933. # Equalise the shapes by prepending smaller one with 1s
  934. as_ = (1,)*max(0, ndb-nda) + as_
  935. bs = (1,)*max(0, nda-ndb) + bs
  936. # Insert empty dimensions
  937. a_arr = expand_dims(a, axis=tuple(range(ndb-nda)))
  938. b_arr = expand_dims(b, axis=tuple(range(nda-ndb)))
  939. # Compute the product
  940. a_arr = expand_dims(a_arr, axis=tuple(range(1, nd*2, 2)))
  941. b_arr = expand_dims(b_arr, axis=tuple(range(0, nd*2, 2)))
  942. # In case of `mat`, convert result to `array`
  943. result = _nx.multiply(a_arr, b_arr, subok=(not is_any_mat))
  944. # Reshape back
  945. result = result.reshape(_nx.multiply(as_, bs))
  946. return result if not is_any_mat else matrix(result, copy=False)
  947. def _tile_dispatcher(A, reps):
  948. return (A, reps)
  949. @array_function_dispatch(_tile_dispatcher)
  950. def tile(A, reps):
  951. """
  952. Construct an array by repeating A the number of times given by reps.
  953. If `reps` has length ``d``, the result will have dimension of
  954. ``max(d, A.ndim)``.
  955. If ``A.ndim < d``, `A` is promoted to be d-dimensional by prepending new
  956. axes. So a shape (3,) array is promoted to (1, 3) for 2-D replication,
  957. or shape (1, 1, 3) for 3-D replication. If this is not the desired
  958. behavior, promote `A` to d-dimensions manually before calling this
  959. function.
  960. If ``A.ndim > d``, `reps` is promoted to `A`.ndim by pre-pending 1's to it.
  961. Thus for an `A` of shape (2, 3, 4, 5), a `reps` of (2, 2) is treated as
  962. (1, 1, 2, 2).
  963. Note : Although tile may be used for broadcasting, it is strongly
  964. recommended to use numpy's broadcasting operations and functions.
  965. Parameters
  966. ----------
  967. A : array_like
  968. The input array.
  969. reps : array_like
  970. The number of repetitions of `A` along each axis.
  971. Returns
  972. -------
  973. c : ndarray
  974. The tiled output array.
  975. See Also
  976. --------
  977. repeat : Repeat elements of an array.
  978. broadcast_to : Broadcast an array to a new shape
  979. Examples
  980. --------
  981. >>> a = np.array([0, 1, 2])
  982. >>> np.tile(a, 2)
  983. array([0, 1, 2, 0, 1, 2])
  984. >>> np.tile(a, (2, 2))
  985. array([[0, 1, 2, 0, 1, 2],
  986. [0, 1, 2, 0, 1, 2]])
  987. >>> np.tile(a, (2, 1, 2))
  988. array([[[0, 1, 2, 0, 1, 2]],
  989. [[0, 1, 2, 0, 1, 2]]])
  990. >>> b = np.array([[1, 2], [3, 4]])
  991. >>> np.tile(b, 2)
  992. array([[1, 2, 1, 2],
  993. [3, 4, 3, 4]])
  994. >>> np.tile(b, (2, 1))
  995. array([[1, 2],
  996. [3, 4],
  997. [1, 2],
  998. [3, 4]])
  999. >>> c = np.array([1,2,3,4])
  1000. >>> np.tile(c,(4,1))
  1001. array([[1, 2, 3, 4],
  1002. [1, 2, 3, 4],
  1003. [1, 2, 3, 4],
  1004. [1, 2, 3, 4]])
  1005. """
  1006. try:
  1007. tup = tuple(reps)
  1008. except TypeError:
  1009. tup = (reps,)
  1010. d = len(tup)
  1011. if all(x == 1 for x in tup) and isinstance(A, _nx.ndarray):
  1012. # Fixes the problem that the function does not make a copy if A is a
  1013. # numpy array and the repetitions are 1 in all dimensions
  1014. return _nx.array(A, copy=True, subok=True, ndmin=d)
  1015. else:
  1016. # Note that no copy of zero-sized arrays is made. However since they
  1017. # have no data there is no risk of an inadvertent overwrite.
  1018. c = _nx.array(A, copy=False, subok=True, ndmin=d)
  1019. if (d < c.ndim):
  1020. tup = (1,)*(c.ndim-d) + tup
  1021. shape_out = tuple(s*t for s, t in zip(c.shape, tup))
  1022. n = c.size
  1023. if n > 0:
  1024. for dim_in, nrep in zip(c.shape, tup):
  1025. if nrep != 1:
  1026. c = c.reshape(-1, n).repeat(nrep, 0)
  1027. n //= dim_in
  1028. return c.reshape(shape_out)