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