1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
U
P±dHã@sêdZddlZddlmZddlmZmZdddgZGdd    „d    ƒZ    d
d „Z
d#dd„Z d$dddœdd„Z ee ƒd%d d dœdd„ƒZ dd„Zd&dd„Zeeddd'dd„ƒZdd„Zedƒdd„ƒZddœd d!„Zeeddd dœd"d„ƒZdS)(z¢
Utilities that manipulate strides to achieve desirable effects.
 
An explanation of strides can be found in the "ndarray.rst" file in the
NumPy reference guide.
 
éN)Únormalize_axis_tuple)Úarray_function_dispatchÚ
set_moduleÚ broadcast_toÚbroadcast_arraysÚbroadcast_shapesc@seZdZdZddd„ZdS)Ú
DummyArrayz„Dummy object that just exists to hang __array_interface__ dictionaries
    and possibly keep alive a reference to a base array.
    NcCs||_||_dS©N)Ú__array_interface__Úbase)ÚselfÚ    interfacer ©rúNd:\z\workplace\vscode\pyvenv\venv\Lib\site-packages\numpy/lib/stride_tricks.pyÚ__init__szDummyArray.__init__)N)Ú__name__Ú
__module__Ú __qualname__Ú__doc__rrrrrrsrcCs4t|ƒt|ƒk    r0|jt|ƒd}|jr0| |¡|S)N)Útype)rÚviewZ__array_finalize__)Zoriginal_arrayZ    new_arrayrrrÚ_maybe_view_as_subclasss
 
rFTcCs~tj|d|d}t|jƒ}|dk    r.t|ƒ|d<|dk    rBt|ƒ|d<t t||d¡}|j|_t||ƒ}|j    j
rz|szd|j    _
|S)a
    Create a view into the array with the given shape and strides.
 
    .. warning:: This function has to be used with extreme care, see notes.
 
    Parameters
    ----------
    x : ndarray
        Array to create a new.
    shape : sequence of int, optional
        The shape of the new array. Defaults to ``x.shape``.
    strides : sequence of int, optional
        The strides of the new array. Defaults to ``x.strides``.
    subok : bool, optional
        .. versionadded:: 1.10
 
        If True, subclasses are preserved.
    writeable : bool, optional
        .. versionadded:: 1.12
 
        If set to False, the returned array will always be readonly.
        Otherwise it will be writable if the original array was. It
        is advisable to set this to False if possible (see Notes).
 
    Returns
    -------
    view : ndarray
 
    See also
    --------
    broadcast_to : broadcast an array to a given shape.
    reshape : reshape an array.
    lib.stride_tricks.sliding_window_view :
        userfriendly and safe function for the creation of sliding window views.
 
    Notes
    -----
    ``as_strided`` creates a view into the array given the exact strides
    and shape. This means it manipulates the internal data structure of
    ndarray and, if done incorrectly, the array elements can point to
    invalid memory and can corrupt results or crash your program.
    It is advisable to always use the original ``x.strides`` when
    calculating new strides to avoid reliance on a contiguous memory
    layout.
 
    Furthermore, arrays created with this function often contain self
    overlapping memory, so that two elements are identical.
    Vectorized write operations on such arrays will typically be
    unpredictable. They may even give different results for small, large,
    or transposed arrays.
 
    Since writing to these arrays has to be tested and done with great
    care, you may want to use ``writeable=False`` to avoid accidental write
    operations.
 
    For these reasons it is advisable to avoid ``as_strided`` when
    possible.
    F©ÚcopyÚsubokNÚshapeÚstrides)r ) ÚnpÚarrayÚdictr
ÚtupleZasarrayrÚdtyperÚflagsÚ    writeable)Úxrrrr#r rrrrrÚ
as_strided&s<
 
 r%)rr#cCs|fSr    r)r$Ú window_shapeÚaxisrr#rrrÚ_sliding_window_view_dispatchervsr(c sLt |¡rt|ƒn|f}tjˆd|d‰t |¡}t |dk¡rHtdƒ‚|dkrŒttˆjƒƒ}t|ƒt|ƒkrÊtdt|ƒ›dˆj›dƒ‚n>t    |ˆjd    d
}t|ƒt|ƒkrÊtd t|ƒ›d t|ƒ›d ƒ‚ˆj
t‡fdd„|Dƒƒ}t ˆj ƒ}t ||ƒD]2\}}    |||    krtdƒ‚|||    d8<qút|ƒ|}
tˆ||
||dS)a¥
    Create a sliding window view into the array with the given window shape.
 
    Also known as rolling or moving window, the window slides across all
    dimensions of the array and extracts subsets of the array at all window
    positions.
    
    .. versionadded:: 1.20.0
 
    Parameters
    ----------
    x : array_like
        Array to create the sliding window view from.
    window_shape : int or tuple of int
        Size of window over each axis that takes part in the sliding window.
        If `axis` is not present, must have same length as the number of input
        array dimensions. Single integers `i` are treated as if they were the
        tuple `(i,)`.
    axis : int or tuple of int, optional
        Axis or axes along which the sliding window is applied.
        By default, the sliding window is applied to all axes and
        `window_shape[i]` will refer to axis `i` of `x`.
        If `axis` is given as a `tuple of int`, `window_shape[i]` will refer to
        the axis `axis[i]` of `x`.
        Single integers `i` are treated as if they were the tuple `(i,)`.
    subok : bool, optional
        If True, sub-classes will be passed-through, otherwise the returned
        array will be forced to be a base-class array (default).
    writeable : bool, optional
        When true, allow writing to the returned view. The default is false,
        as this should be used with caution: the returned view contains the
        same memory location multiple times, so writing to one location will
        cause others to change.
 
    Returns
    -------
    view : ndarray
        Sliding window view of the array. The sliding window dimensions are
        inserted at the end, and the original dimensions are trimmed as
        required by the size of the sliding window.
        That is, ``view.shape = x_shape_trimmed + window_shape``, where
        ``x_shape_trimmed`` is ``x.shape`` with every entry reduced by one less
        than the corresponding window size.
 
    See Also
    --------
    lib.stride_tricks.as_strided: A lower-level and less safe routine for
        creating arbitrary views from custom shape and strides.
    broadcast_to: broadcast an array to a given shape.
 
    Notes
    -----
    For many applications using a sliding window view can be convenient, but
    potentially very slow. Often specialized solutions exist, for example:
 
    - `scipy.signal.fftconvolve`
 
    - filtering functions in `scipy.ndimage`
 
    - moving window functions provided by
      `bottleneck <https://github.com/pydata/bottleneck>`_.
 
    As a rough estimate, a sliding window approach with an input size of `N`
    and a window size of `W` will scale as `O(N*W)` where frequently a special
    algorithm can achieve `O(N)`. That means that the sliding window variant
    for a window size of 100 can be a 100 times slower than a more specialized
    version.
 
    Nevertheless, for small window sizes, when no custom algorithm exists, or
    as a prototyping and developing tool, this function can be a good solution.
 
    Examples
    --------
    >>> x = np.arange(6)
    >>> x.shape
    (6,)
    >>> v = sliding_window_view(x, 3)
    >>> v.shape
    (4, 3)
    >>> v
    array([[0, 1, 2],
           [1, 2, 3],
           [2, 3, 4],
           [3, 4, 5]])
 
    This also works in more dimensions, e.g.
 
    >>> i, j = np.ogrid[:3, :4]
    >>> x = 10*i + j
    >>> x.shape
    (3, 4)
    >>> x
    array([[ 0,  1,  2,  3],
           [10, 11, 12, 13],
           [20, 21, 22, 23]])
    >>> shape = (2,2)
    >>> v = sliding_window_view(x, shape)
    >>> v.shape
    (2, 3, 2, 2)
    >>> v
    array([[[[ 0,  1],
             [10, 11]],
            [[ 1,  2],
             [11, 12]],
            [[ 2,  3],
             [12, 13]]],
           [[[10, 11],
             [20, 21]],
            [[11, 12],
             [21, 22]],
            [[12, 13],
             [22, 23]]]])
 
    The axis can be specified explicitly:
 
    >>> v = sliding_window_view(x, 3, 0)
    >>> v.shape
    (1, 4, 3)
    >>> v
    array([[[ 0, 10, 20],
            [ 1, 11, 21],
            [ 2, 12, 22],
            [ 3, 13, 23]]])
 
    The same axis can be used several times. In that case, every use reduces
    the corresponding original dimension:
 
    >>> v = sliding_window_view(x, (2, 3), (1, 1))
    >>> v.shape
    (3, 1, 2, 3)
    >>> v
    array([[[[ 0,  1,  2],
             [ 1,  2,  3]]],
           [[[10, 11, 12],
             [11, 12, 13]]],
           [[[20, 21, 22],
             [21, 22, 23]]]])
 
    Combining with stepped slicing (`::step`), this can be used to take sliding
    views which skip elements:
 
    >>> x = np.arange(7)
    >>> sliding_window_view(x, 5)[:, ::2]
    array([[0, 2, 4],
           [1, 3, 5],
           [2, 4, 6]])
 
    or views which move by multiple elements
 
    >>> x = np.arange(7)
    >>> sliding_window_view(x, 3)[::2, :]
    array([[0, 1, 2],
           [2, 3, 4],
           [4, 5, 6]])
 
    A common application of `sliding_window_view` is the calculation of running
    statistics. The simplest example is the
    `moving average <https://en.wikipedia.org/wiki/Moving_average>`_:
 
    >>> x = np.arange(6)
    >>> x.shape
    (6,)
    >>> v = sliding_window_view(x, 3)
    >>> v.shape
    (4, 3)
    >>> v
    array([[0, 1, 2],
           [1, 2, 3],
           [2, 3, 4],
           [3, 4, 5]])
    >>> moving_average = v.mean(axis=-1)
    >>> moving_average
    array([1., 2., 3., 4.])
 
    Note that a sliding window approach is often **not** optimal (see Notes).
    Frrz-`window_shape` cannot contain negative valuesNzOSince axis is `None`, must provide window_shape for all dimensions of `x`; got z' window_shape elements and `x.ndim` is Ú.T)Zallow_duplicatez8Must provide matching length window_shape and axis; got z window_shape elements and z axes elements.c3s|]}ˆj|VqdSr    )r)Ú.0Úax©r$rrÚ    <genexpr>Fsz&sliding_window_view.<locals>.<genexpr>z4window shape cannot be larger than input array shapeé)rrrr#)rÚiterabler rÚanyÚ
ValueErrorÚrangeÚndimÚlenrrÚlistrÚzipr%) r$r&r'rr#Zwindow_shape_arrayZ out_stridesZx_shape_trimmedr+ZdimZ    out_shaperr,rÚsliding_window_view{s:5ÿ
þ
 
ÿ ÿr7c    Cs¾t |¡rt|ƒn|f}tj|d|d}|s:|jr:tdƒ‚tdd„|DƒƒrTtdƒ‚g}tj|fddd    g|d
g|d d }||jd }W5QRXt    ||ƒ}|sº|j
j rºd|j
_ d|j
_ |S)NFrz/cannot broadcast a non-scalar to a scalar arraycss|]}|dkVqdS)rNr)r*Úsizerrrr-Ysz _broadcast_to.<locals>.<genexpr>z4all elements of broadcast shape must be non-negativeZ multi_indexZrefs_okZ zerosize_okÚreadonlyÚC)r"Zop_flagsZ    itershapeÚorderrT)rr/r rrr1r0ZnditerZitviewsrr"Z_writeable_no_warnr#Z_warn_on_write)rrrr9ÚextrasÚitÚ    broadcastÚresultrrrÚ _broadcast_toTs*
 þ
 r@cCs|fSr    r©rrrrrrÚ_broadcast_to_dispatcherksrBÚnumpy)ÚmodulecCst|||ddS)aaBroadcast an array to a new shape.
 
    Parameters
    ----------
    array : array_like
        The array to broadcast.
    shape : tuple or int
        The shape of the desired array. A single integer ``i`` is interpreted
        as ``(i,)``.
    subok : bool, optional
        If True, then sub-classes will be passed-through, otherwise
        the returned array will be forced to be a base-class array (default).
 
    Returns
    -------
    broadcast : array
        A readonly view on the original array with the given shape. It is
        typically not contiguous. Furthermore, more than one element of a
        broadcasted array may refer to a single memory location.
 
    Raises
    ------
    ValueError
        If the array is not compatible with the new shape according to NumPy's
        broadcasting rules.
 
    See Also
    --------
    broadcast
    broadcast_arrays
    broadcast_shapes
 
    Notes
    -----
    .. versionadded:: 1.10.0
 
    Examples
    --------
    >>> x = np.array([1, 2, 3])
    >>> np.broadcast_to(x, (3, 3))
    array([[1, 2, 3],
           [1, 2, 3],
           [1, 2, 3]])
    T©rr9©r@rArrrros.cGsVtj|dd…Ž}tdt|ƒdƒD],}td|jƒ}tj|f|||d…žŽ}q"|jS)ztReturns the shape of the arrays that would result from broadcasting the
    supplied arrays against each other.
    Né ér)rr>r2r4rr)ÚargsÚbÚposrrrÚ_broadcast_shape s
 rLcGsdd„|Dƒ}t|ŽS)aç
    Broadcast the input shapes into a single shape.
 
    :ref:`Learn more about broadcasting here <basics.broadcasting>`.
 
    .. versionadded:: 1.20.0
 
    Parameters
    ----------
    `*args` : tuples of ints, or ints
        The shapes to be broadcast against each other.
 
    Returns
    -------
    tuple
        Broadcasted shape.
 
    Raises
    ------
    ValueError
        If the shapes are not compatible and cannot be broadcast according
        to NumPy's broadcasting rules.
 
    See Also
    --------
    broadcast
    broadcast_arrays
    broadcast_to
 
    Examples
    --------
    >>> np.broadcast_shapes((1, 2), (3, 1), (3, 2))
    (3, 2)
 
    >>> np.broadcast_shapes((6, 7), (5, 6, 1), (7,), (5, 1, 7))
    (5, 6, 7)
    cSsg|]}tj|gd‘qS))r!)rÚempty)r*r$rrrÚ
<listcomp>Øsz$broadcast_shapes.<locals>.<listcomp>)rL)rIZarraysrrrr±s'©rcGs|Sr    r©rrIrrrÚ_broadcast_arrays_dispatcherÜsrQcsH‡fdd„|Dƒ}t|މt‡fdd„|Dƒƒr4|S‡‡fdd„|DƒS)a=
    Broadcast any number of arrays against each other.
 
    Parameters
    ----------
    `*args` : array_likes
        The arrays to broadcast.
 
    subok : bool, optional
        If True, then sub-classes will be passed-through, otherwise
        the returned arrays will be forced to be a base-class array (default).
 
    Returns
    -------
    broadcasted : list of arrays
        These arrays are views on the original arrays.  They are typically
        not contiguous.  Furthermore, more than one element of a
        broadcasted array may refer to a single memory location. If you need
        to write to the arrays, make copies first. While you can set the
        ``writable`` flag True, writing to a single output value may end up
        changing more than one location in the output array.
 
        .. deprecated:: 1.17
            The output is currently marked so that if written to, a deprecation
            warning will be emitted. A future version will set the
            ``writable`` flag False so writing to it will raise an error.
 
    See Also
    --------
    broadcast
    broadcast_to
    broadcast_shapes
 
    Examples
    --------
    >>> x = np.array([[1,2,3]])
    >>> y = np.array([[4],[5]])
    >>> np.broadcast_arrays(x, y)
    [array([[1, 2, 3],
           [1, 2, 3]]), array([[4, 4, 4],
           [5, 5, 5]])]
 
    Here is a useful idiom for getting contiguous copies instead of
    non-contiguous views.
 
    >>> [np.array(a) for a in np.broadcast_arrays(x, y)]
    [array([[1, 2, 3],
           [1, 2, 3]]), array([[4, 4, 4],
           [5, 5, 5]])]
 
    csg|]}tj|dˆd‘qS)Fr)rr)r*Ú_mrOrrrNsz$broadcast_arrays.<locals>.<listcomp>c3s|]}|jˆkVqdSr    ©r©r*rrSrrr-sz#broadcast_arrays.<locals>.<genexpr>csg|]}t|ˆˆdd‘qS)FrErFrT©rrrrrN"sÿ)rLÚallrPrrUrràs: ÿ)NNFT)N)N)N)F)rrCrZnumpy.core.numericrZnumpy.core.overridesrrÚ__all__rrr%r(r7r@rBrrLrrQrrrrrÚ<module>s6 
 
 
Pÿ ÿY
 
 0
*