_stride_tricks_impl.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. """
  2. Utilities that manipulate strides to achieve desirable effects.
  3. An explanation of strides can be found in the :ref:`arrays.ndarray`.
  4. """
  5. import numpy as np
  6. from numpy._core.numeric import normalize_axis_tuple
  7. from numpy._core.overrides import array_function_dispatch, set_module
  8. __all__ = ['broadcast_to', 'broadcast_arrays', 'broadcast_shapes']
  9. class DummyArray:
  10. """Dummy object that just exists to hang __array_interface__ dictionaries
  11. and possibly keep alive a reference to a base array.
  12. """
  13. def __init__(self, interface, base=None):
  14. self.__array_interface__ = interface
  15. self.base = base
  16. def _maybe_view_as_subclass(original_array, new_array):
  17. if type(original_array) is not type(new_array):
  18. # if input was an ndarray subclass and subclasses were OK,
  19. # then view the result as that subclass.
  20. new_array = new_array.view(type=type(original_array))
  21. # Since we have done something akin to a view from original_array, we
  22. # should let the subclass finalize (if it has it implemented, i.e., is
  23. # not None).
  24. if new_array.__array_finalize__:
  25. new_array.__array_finalize__(original_array)
  26. return new_array
  27. @set_module("numpy.lib.stride_tricks")
  28. def as_strided(x, shape=None, strides=None, subok=False, writeable=True):
  29. """
  30. Create a view into the array with the given shape and strides.
  31. .. warning:: This function has to be used with extreme care, see notes.
  32. Parameters
  33. ----------
  34. x : ndarray
  35. Array to create a new.
  36. shape : sequence of int, optional
  37. The shape of the new array. Defaults to ``x.shape``.
  38. strides : sequence of int, optional
  39. The strides of the new array. Defaults to ``x.strides``.
  40. subok : bool, optional
  41. If True, subclasses are preserved.
  42. writeable : bool, optional
  43. If set to False, the returned array will always be readonly.
  44. Otherwise it will be writable if the original array was. It
  45. is advisable to set this to False if possible (see Notes).
  46. Returns
  47. -------
  48. view : ndarray
  49. See also
  50. --------
  51. broadcast_to : broadcast an array to a given shape.
  52. reshape : reshape an array.
  53. lib.stride_tricks.sliding_window_view :
  54. userfriendly and safe function for a creation of sliding window views.
  55. Notes
  56. -----
  57. ``as_strided`` creates a view into the array given the exact strides
  58. and shape. This means it manipulates the internal data structure of
  59. ndarray and, if done incorrectly, the array elements can point to
  60. invalid memory and can corrupt results or crash your program.
  61. It is advisable to always use the original ``x.strides`` when
  62. calculating new strides to avoid reliance on a contiguous memory
  63. layout.
  64. Furthermore, arrays created with this function often contain self
  65. overlapping memory, so that two elements are identical.
  66. Vectorized write operations on such arrays will typically be
  67. unpredictable. They may even give different results for small, large,
  68. or transposed arrays.
  69. Since writing to these arrays has to be tested and done with great
  70. care, you may want to use ``writeable=False`` to avoid accidental write
  71. operations.
  72. For these reasons it is advisable to avoid ``as_strided`` when
  73. possible.
  74. """
  75. # first convert input to array, possibly keeping subclass
  76. x = np.array(x, copy=None, subok=subok)
  77. interface = dict(x.__array_interface__)
  78. if shape is not None:
  79. interface['shape'] = tuple(shape)
  80. if strides is not None:
  81. interface['strides'] = tuple(strides)
  82. array = np.asarray(DummyArray(interface, base=x))
  83. # The route via `__interface__` does not preserve structured
  84. # dtypes. Since dtype should remain unchanged, we set it explicitly.
  85. array.dtype = x.dtype
  86. view = _maybe_view_as_subclass(x, array)
  87. if view.flags.writeable and not writeable:
  88. view.flags.writeable = False
  89. return view
  90. def _sliding_window_view_dispatcher(x, window_shape, axis=None, *,
  91. subok=None, writeable=None):
  92. return (x,)
  93. @array_function_dispatch(
  94. _sliding_window_view_dispatcher, module="numpy.lib.stride_tricks"
  95. )
  96. def sliding_window_view(x, window_shape, axis=None, *,
  97. subok=False, writeable=False):
  98. """
  99. Create a sliding window view into the array with the given window shape.
  100. Also known as rolling or moving window, the window slides across all
  101. dimensions of the array and extracts subsets of the array at all window
  102. positions.
  103. .. versionadded:: 1.20.0
  104. Parameters
  105. ----------
  106. x : array_like
  107. Array to create the sliding window view from.
  108. window_shape : int or tuple of int
  109. Size of window over each axis that takes part in the sliding window.
  110. If `axis` is not present, must have same length as the number of input
  111. array dimensions. Single integers `i` are treated as if they were the
  112. tuple `(i,)`.
  113. axis : int or tuple of int, optional
  114. Axis or axes along which the sliding window is applied.
  115. By default, the sliding window is applied to all axes and
  116. `window_shape[i]` will refer to axis `i` of `x`.
  117. If `axis` is given as a `tuple of int`, `window_shape[i]` will refer to
  118. the axis `axis[i]` of `x`.
  119. Single integers `i` are treated as if they were the tuple `(i,)`.
  120. subok : bool, optional
  121. If True, sub-classes will be passed-through, otherwise the returned
  122. array will be forced to be a base-class array (default).
  123. writeable : bool, optional
  124. When true, allow writing to the returned view. The default is false,
  125. as this should be used with caution: the returned view contains the
  126. same memory location multiple times, so writing to one location will
  127. cause others to change.
  128. Returns
  129. -------
  130. view : ndarray
  131. Sliding window view of the array. The sliding window dimensions are
  132. inserted at the end, and the original dimensions are trimmed as
  133. required by the size of the sliding window.
  134. That is, ``view.shape = x_shape_trimmed + window_shape``, where
  135. ``x_shape_trimmed`` is ``x.shape`` with every entry reduced by one less
  136. than the corresponding window size.
  137. See Also
  138. --------
  139. lib.stride_tricks.as_strided: A lower-level and less safe routine for
  140. creating arbitrary views from custom shape and strides.
  141. broadcast_to: broadcast an array to a given shape.
  142. Notes
  143. -----
  144. For many applications using a sliding window view can be convenient, but
  145. potentially very slow. Often specialized solutions exist, for example:
  146. - `scipy.signal.fftconvolve`
  147. - filtering functions in `scipy.ndimage`
  148. - moving window functions provided by
  149. `bottleneck <https://github.com/pydata/bottleneck>`_.
  150. As a rough estimate, a sliding window approach with an input size of `N`
  151. and a window size of `W` will scale as `O(N*W)` where frequently a special
  152. algorithm can achieve `O(N)`. That means that the sliding window variant
  153. for a window size of 100 can be a 100 times slower than a more specialized
  154. version.
  155. Nevertheless, for small window sizes, when no custom algorithm exists, or
  156. as a prototyping and developing tool, this function can be a good solution.
  157. Examples
  158. --------
  159. >>> import numpy as np
  160. >>> from numpy.lib.stride_tricks import sliding_window_view
  161. >>> x = np.arange(6)
  162. >>> x.shape
  163. (6,)
  164. >>> v = sliding_window_view(x, 3)
  165. >>> v.shape
  166. (4, 3)
  167. >>> v
  168. array([[0, 1, 2],
  169. [1, 2, 3],
  170. [2, 3, 4],
  171. [3, 4, 5]])
  172. This also works in more dimensions, e.g.
  173. >>> i, j = np.ogrid[:3, :4]
  174. >>> x = 10*i + j
  175. >>> x.shape
  176. (3, 4)
  177. >>> x
  178. array([[ 0, 1, 2, 3],
  179. [10, 11, 12, 13],
  180. [20, 21, 22, 23]])
  181. >>> shape = (2,2)
  182. >>> v = sliding_window_view(x, shape)
  183. >>> v.shape
  184. (2, 3, 2, 2)
  185. >>> v
  186. array([[[[ 0, 1],
  187. [10, 11]],
  188. [[ 1, 2],
  189. [11, 12]],
  190. [[ 2, 3],
  191. [12, 13]]],
  192. [[[10, 11],
  193. [20, 21]],
  194. [[11, 12],
  195. [21, 22]],
  196. [[12, 13],
  197. [22, 23]]]])
  198. The axis can be specified explicitly:
  199. >>> v = sliding_window_view(x, 3, 0)
  200. >>> v.shape
  201. (1, 4, 3)
  202. >>> v
  203. array([[[ 0, 10, 20],
  204. [ 1, 11, 21],
  205. [ 2, 12, 22],
  206. [ 3, 13, 23]]])
  207. The same axis can be used several times. In that case, every use reduces
  208. the corresponding original dimension:
  209. >>> v = sliding_window_view(x, (2, 3), (1, 1))
  210. >>> v.shape
  211. (3, 1, 2, 3)
  212. >>> v
  213. array([[[[ 0, 1, 2],
  214. [ 1, 2, 3]]],
  215. [[[10, 11, 12],
  216. [11, 12, 13]]],
  217. [[[20, 21, 22],
  218. [21, 22, 23]]]])
  219. Combining with stepped slicing (`::step`), this can be used to take sliding
  220. views which skip elements:
  221. >>> x = np.arange(7)
  222. >>> sliding_window_view(x, 5)[:, ::2]
  223. array([[0, 2, 4],
  224. [1, 3, 5],
  225. [2, 4, 6]])
  226. or views which move by multiple elements
  227. >>> x = np.arange(7)
  228. >>> sliding_window_view(x, 3)[::2, :]
  229. array([[0, 1, 2],
  230. [2, 3, 4],
  231. [4, 5, 6]])
  232. A common application of `sliding_window_view` is the calculation of running
  233. statistics. The simplest example is the
  234. `moving average <https://en.wikipedia.org/wiki/Moving_average>`_:
  235. >>> x = np.arange(6)
  236. >>> x.shape
  237. (6,)
  238. >>> v = sliding_window_view(x, 3)
  239. >>> v.shape
  240. (4, 3)
  241. >>> v
  242. array([[0, 1, 2],
  243. [1, 2, 3],
  244. [2, 3, 4],
  245. [3, 4, 5]])
  246. >>> moving_average = v.mean(axis=-1)
  247. >>> moving_average
  248. array([1., 2., 3., 4.])
  249. Note that a sliding window approach is often **not** optimal (see Notes).
  250. """
  251. window_shape = (tuple(window_shape)
  252. if np.iterable(window_shape)
  253. else (window_shape,))
  254. # first convert input to array, possibly keeping subclass
  255. x = np.array(x, copy=None, subok=subok)
  256. window_shape_array = np.array(window_shape)
  257. if np.any(window_shape_array < 0):
  258. raise ValueError('`window_shape` cannot contain negative values')
  259. if axis is None:
  260. axis = tuple(range(x.ndim))
  261. if len(window_shape) != len(axis):
  262. raise ValueError(f'Since axis is `None`, must provide '
  263. f'window_shape for all dimensions of `x`; '
  264. f'got {len(window_shape)} window_shape elements '
  265. f'and `x.ndim` is {x.ndim}.')
  266. else:
  267. axis = normalize_axis_tuple(axis, x.ndim, allow_duplicate=True)
  268. if len(window_shape) != len(axis):
  269. raise ValueError(f'Must provide matching length window_shape and '
  270. f'axis; got {len(window_shape)} window_shape '
  271. f'elements and {len(axis)} axes elements.')
  272. out_strides = x.strides + tuple(x.strides[ax] for ax in axis)
  273. # note: same axis can be windowed repeatedly
  274. x_shape_trimmed = list(x.shape)
  275. for ax, dim in zip(axis, window_shape):
  276. if x_shape_trimmed[ax] < dim:
  277. raise ValueError(
  278. 'window shape cannot be larger than input array shape')
  279. x_shape_trimmed[ax] -= dim - 1
  280. out_shape = tuple(x_shape_trimmed) + window_shape
  281. return as_strided(x, strides=out_strides, shape=out_shape,
  282. subok=subok, writeable=writeable)
  283. def _broadcast_to(array, shape, subok, readonly):
  284. shape = tuple(shape) if np.iterable(shape) else (shape,)
  285. array = np.array(array, copy=None, subok=subok)
  286. if not shape and array.shape:
  287. raise ValueError('cannot broadcast a non-scalar to a scalar array')
  288. if any(size < 0 for size in shape):
  289. raise ValueError('all elements of broadcast shape must be non-'
  290. 'negative')
  291. extras = []
  292. it = np.nditer(
  293. (array,), flags=['multi_index', 'refs_ok', 'zerosize_ok'] + extras,
  294. op_flags=['readonly'], itershape=shape, order='C')
  295. with it:
  296. # never really has writebackifcopy semantics
  297. broadcast = it.itviews[0]
  298. result = _maybe_view_as_subclass(array, broadcast)
  299. # In a future version this will go away
  300. if not readonly and array.flags._writeable_no_warn:
  301. result.flags.writeable = True
  302. result.flags._warn_on_write = True
  303. return result
  304. def _broadcast_to_dispatcher(array, shape, subok=None):
  305. return (array,)
  306. @array_function_dispatch(_broadcast_to_dispatcher, module='numpy')
  307. def broadcast_to(array, shape, subok=False):
  308. """Broadcast an array to a new shape.
  309. Parameters
  310. ----------
  311. array : array_like
  312. The array to broadcast.
  313. shape : tuple or int
  314. The shape of the desired array. A single integer ``i`` is interpreted
  315. as ``(i,)``.
  316. subok : bool, optional
  317. If True, then sub-classes will be passed-through, otherwise
  318. the returned array will be forced to be a base-class array (default).
  319. Returns
  320. -------
  321. broadcast : array
  322. A readonly view on the original array with the given shape. It is
  323. typically not contiguous. Furthermore, more than one element of a
  324. broadcasted array may refer to a single memory location.
  325. Raises
  326. ------
  327. ValueError
  328. If the array is not compatible with the new shape according to NumPy's
  329. broadcasting rules.
  330. See Also
  331. --------
  332. broadcast
  333. broadcast_arrays
  334. broadcast_shapes
  335. Examples
  336. --------
  337. >>> import numpy as np
  338. >>> x = np.array([1, 2, 3])
  339. >>> np.broadcast_to(x, (3, 3))
  340. array([[1, 2, 3],
  341. [1, 2, 3],
  342. [1, 2, 3]])
  343. """
  344. return _broadcast_to(array, shape, subok=subok, readonly=True)
  345. def _broadcast_shape(*args):
  346. """Returns the shape of the arrays that would result from broadcasting the
  347. supplied arrays against each other.
  348. """
  349. # use the old-iterator because np.nditer does not handle size 0 arrays
  350. # consistently
  351. b = np.broadcast(*args[:32])
  352. # unfortunately, it cannot handle 32 or more arguments directly
  353. for pos in range(32, len(args), 31):
  354. # ironically, np.broadcast does not properly handle np.broadcast
  355. # objects (it treats them as scalars)
  356. # use broadcasting to avoid allocating the full array
  357. b = broadcast_to(0, b.shape)
  358. b = np.broadcast(b, *args[pos:(pos + 31)])
  359. return b.shape
  360. _size0_dtype = np.dtype([])
  361. @set_module('numpy')
  362. def broadcast_shapes(*args):
  363. """
  364. Broadcast the input shapes into a single shape.
  365. :ref:`Learn more about broadcasting here <basics.broadcasting>`.
  366. .. versionadded:: 1.20.0
  367. Parameters
  368. ----------
  369. *args : tuples of ints, or ints
  370. The shapes to be broadcast against each other.
  371. Returns
  372. -------
  373. tuple
  374. Broadcasted shape.
  375. Raises
  376. ------
  377. ValueError
  378. If the shapes are not compatible and cannot be broadcast according
  379. to NumPy's broadcasting rules.
  380. See Also
  381. --------
  382. broadcast
  383. broadcast_arrays
  384. broadcast_to
  385. Examples
  386. --------
  387. >>> import numpy as np
  388. >>> np.broadcast_shapes((1, 2), (3, 1), (3, 2))
  389. (3, 2)
  390. >>> np.broadcast_shapes((6, 7), (5, 6, 1), (7,), (5, 1, 7))
  391. (5, 6, 7)
  392. """
  393. arrays = [np.empty(x, dtype=_size0_dtype) for x in args]
  394. return _broadcast_shape(*arrays)
  395. def _broadcast_arrays_dispatcher(*args, subok=None):
  396. return args
  397. @array_function_dispatch(_broadcast_arrays_dispatcher, module='numpy')
  398. def broadcast_arrays(*args, subok=False):
  399. """
  400. Broadcast any number of arrays against each other.
  401. Parameters
  402. ----------
  403. *args : array_likes
  404. The arrays to broadcast.
  405. subok : bool, optional
  406. If True, then sub-classes will be passed-through, otherwise
  407. the returned arrays will be forced to be a base-class array (default).
  408. Returns
  409. -------
  410. broadcasted : tuple of arrays
  411. These arrays are views on the original arrays. They are typically
  412. not contiguous. Furthermore, more than one element of a
  413. broadcasted array may refer to a single memory location. If you need
  414. to write to the arrays, make copies first. While you can set the
  415. ``writable`` flag True, writing to a single output value may end up
  416. changing more than one location in the output array.
  417. .. deprecated:: 1.17
  418. The output is currently marked so that if written to, a deprecation
  419. warning will be emitted. A future version will set the
  420. ``writable`` flag False so writing to it will raise an error.
  421. See Also
  422. --------
  423. broadcast
  424. broadcast_to
  425. broadcast_shapes
  426. Examples
  427. --------
  428. >>> import numpy as np
  429. >>> x = np.array([[1,2,3]])
  430. >>> y = np.array([[4],[5]])
  431. >>> np.broadcast_arrays(x, y)
  432. (array([[1, 2, 3],
  433. [1, 2, 3]]),
  434. array([[4, 4, 4],
  435. [5, 5, 5]]))
  436. Here is a useful idiom for getting contiguous copies instead of
  437. non-contiguous views.
  438. >>> [np.array(a) for a in np.broadcast_arrays(x, y)]
  439. [array([[1, 2, 3],
  440. [1, 2, 3]]),
  441. array([[4, 4, 4],
  442. [5, 5, 5]])]
  443. """
  444. # nditer is not used here to avoid the limit of 32 arrays.
  445. # Otherwise, something like the following one-liner would suffice:
  446. # return np.nditer(args, flags=['multi_index', 'zerosize_ok'],
  447. # order='C').itviews
  448. args = [np.array(_m, copy=None, subok=subok) for _m in args]
  449. shape = _broadcast_shape(*args)
  450. result = [array if array.shape == shape
  451. else _broadcast_to(array, shape, subok=subok, readonly=False)
  452. for array in args]
  453. return tuple(result)