Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.10/site-packages/numpy/lib/_stride_tricks_impl.py: 25%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

92 statements  

1""" 

2Utilities that manipulate strides to achieve desirable effects. 

3 

4An explanation of strides can be found in the :ref:`arrays.ndarray`. 

5 

6""" 

7import numpy as np 

8from numpy._core.numeric import normalize_axis_tuple 

9from numpy._core.overrides import array_function_dispatch, set_module 

10 

11__all__ = ['broadcast_to', 'broadcast_arrays', 'broadcast_shapes'] 

12 

13 

14class DummyArray: 

15 """Dummy object that just exists to hang __array_interface__ dictionaries 

16 and possibly keep alive a reference to a base array. 

17 """ 

18 

19 def __init__(self, interface, base=None): 

20 self.__array_interface__ = interface 

21 self.base = base 

22 

23 

24def _maybe_view_as_subclass(original_array, new_array): 

25 if type(original_array) is not type(new_array): 

26 # if input was an ndarray subclass and subclasses were OK, 

27 # then view the result as that subclass. 

28 new_array = new_array.view(type=type(original_array)) 

29 # Since we have done something akin to a view from original_array, we 

30 # should let the subclass finalize (if it has it implemented, i.e., is 

31 # not None). 

32 if new_array.__array_finalize__: 

33 new_array.__array_finalize__(original_array) 

34 return new_array 

35 

36 

37@set_module("numpy.lib.stride_tricks") 

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 If True, subclasses are preserved. 

54 writeable : bool, optional 

55 If set to False, the returned array will always be readonly. 

56 Otherwise it will be writable if the original array was. It 

57 is advisable to set this to False if possible (see Notes). 

58 

59 Returns 

60 ------- 

61 view : ndarray 

62 

63 See also 

64 -------- 

65 broadcast_to : broadcast an array to a given shape. 

66 reshape : reshape an array. 

67 lib.stride_tricks.sliding_window_view : 

68 userfriendly and safe function for a creation of sliding window views. 

69 

70 Notes 

71 ----- 

72 ``as_strided`` creates a view into the array given the exact strides 

73 and shape. This means it manipulates the internal data structure of 

74 ndarray and, if done incorrectly, the array elements can point to 

75 invalid memory and can corrupt results or crash your program. 

76 It is advisable to always use the original ``x.strides`` when 

77 calculating new strides to avoid reliance on a contiguous memory 

78 layout. 

79 

80 Furthermore, arrays created with this function often contain self 

81 overlapping memory, so that two elements are identical. 

82 Vectorized write operations on such arrays will typically be 

83 unpredictable. They may even give different results for small, large, 

84 or transposed arrays. 

85 

86 Since writing to these arrays has to be tested and done with great 

87 care, you may want to use ``writeable=False`` to avoid accidental write 

88 operations. 

89 

90 For these reasons it is advisable to avoid ``as_strided`` when 

91 possible. 

92 """ 

93 # first convert input to array, possibly keeping subclass 

94 x = np.array(x, copy=None, subok=subok) 

95 interface = dict(x.__array_interface__) 

96 if shape is not None: 

97 interface['shape'] = tuple(shape) 

98 if strides is not None: 

99 interface['strides'] = tuple(strides) 

100 

101 array = np.asarray(DummyArray(interface, base=x)) 

102 # The route via `__interface__` does not preserve structured 

103 # dtypes. Since dtype should remain unchanged, we set it explicitly. 

104 array.dtype = x.dtype 

105 

106 view = _maybe_view_as_subclass(x, array) 

107 

108 if view.flags.writeable and not writeable: 

109 view.flags.writeable = False 

110 

111 return view 

112 

113 

114def _sliding_window_view_dispatcher(x, window_shape, axis=None, *, 

115 subok=None, writeable=None): 

116 return (x,) 

117 

118 

119@array_function_dispatch( 

120 _sliding_window_view_dispatcher, module="numpy.lib.stride_tricks" 

121) 

122def sliding_window_view(x, window_shape, axis=None, *, 

123 subok=False, writeable=False): 

124 """ 

125 Create a sliding window view into the array with the given window shape. 

126 

127 Also known as rolling or moving window, the window slides across all 

128 dimensions of the array and extracts subsets of the array at all window 

129 positions. 

130 

131 .. versionadded:: 1.20.0 

132 

133 Parameters 

134 ---------- 

135 x : array_like 

136 Array to create the sliding window view from. 

137 window_shape : int or tuple of int 

138 Size of window over each axis that takes part in the sliding window. 

139 If `axis` is not present, must have same length as the number of input 

140 array dimensions. Single integers `i` are treated as if they were the 

141 tuple `(i,)`. 

142 axis : int or tuple of int, optional 

143 Axis or axes along which the sliding window is applied. 

144 By default, the sliding window is applied to all axes and 

145 `window_shape[i]` will refer to axis `i` of `x`. 

146 If `axis` is given as a `tuple of int`, `window_shape[i]` will refer to 

147 the axis `axis[i]` of `x`. 

148 Single integers `i` are treated as if they were the tuple `(i,)`. 

149 subok : bool, optional 

150 If True, sub-classes will be passed-through, otherwise the returned 

151 array will be forced to be a base-class array (default). 

152 writeable : bool, optional 

153 When true, allow writing to the returned view. The default is false, 

154 as this should be used with caution: the returned view contains the 

155 same memory location multiple times, so writing to one location will 

156 cause others to change. 

157 

158 Returns 

159 ------- 

160 view : ndarray 

161 Sliding window view of the array. The sliding window dimensions are 

162 inserted at the end, and the original dimensions are trimmed as 

163 required by the size of the sliding window. 

164 That is, ``view.shape = x_shape_trimmed + window_shape``, where 

165 ``x_shape_trimmed`` is ``x.shape`` with every entry reduced by one less 

166 than the corresponding window size. 

167 

168 See Also 

169 -------- 

170 lib.stride_tricks.as_strided: A lower-level and less safe routine for 

171 creating arbitrary views from custom shape and strides. 

172 broadcast_to: broadcast an array to a given shape. 

173 

174 Notes 

175 ----- 

176 For many applications using a sliding window view can be convenient, but 

177 potentially very slow. Often specialized solutions exist, for example: 

178 

179 - `scipy.signal.fftconvolve` 

180 

181 - filtering functions in `scipy.ndimage` 

182 

183 - moving window functions provided by 

184 `bottleneck <https://github.com/pydata/bottleneck>`_. 

185 

186 As a rough estimate, a sliding window approach with an input size of `N` 

187 and a window size of `W` will scale as `O(N*W)` where frequently a special 

188 algorithm can achieve `O(N)`. That means that the sliding window variant 

189 for a window size of 100 can be a 100 times slower than a more specialized 

190 version. 

191 

192 Nevertheless, for small window sizes, when no custom algorithm exists, or 

193 as a prototyping and developing tool, this function can be a good solution. 

194 

195 Examples 

196 -------- 

197 >>> import numpy as np 

198 >>> from numpy.lib.stride_tricks import sliding_window_view 

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=None, 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=None, 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 Examples 

402 -------- 

403 >>> import numpy as np 

404 >>> x = np.array([1, 2, 3]) 

405 >>> np.broadcast_to(x, (3, 3)) 

406 array([[1, 2, 3], 

407 [1, 2, 3], 

408 [1, 2, 3]]) 

409 """ 

410 return _broadcast_to(array, shape, subok=subok, readonly=True) 

411 

412 

413def _broadcast_shape(*args): 

414 """Returns the shape of the arrays that would result from broadcasting the 

415 supplied arrays against each other. 

416 """ 

417 # use the old-iterator because np.nditer does not handle size 0 arrays 

418 # consistently 

419 b = np.broadcast(*args[:32]) 

420 # unfortunately, it cannot handle 32 or more arguments directly 

421 for pos in range(32, len(args), 31): 

422 # ironically, np.broadcast does not properly handle np.broadcast 

423 # objects (it treats them as scalars) 

424 # use broadcasting to avoid allocating the full array 

425 b = broadcast_to(0, b.shape) 

426 b = np.broadcast(b, *args[pos:(pos + 31)]) 

427 return b.shape 

428 

429 

430_size0_dtype = np.dtype([]) 

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 >>> import numpy as np 

467 >>> np.broadcast_shapes((1, 2), (3, 1), (3, 2)) 

468 (3, 2) 

469 

470 >>> np.broadcast_shapes((6, 7), (5, 6, 1), (7,), (5, 1, 7)) 

471 (5, 6, 7) 

472 """ 

473 arrays = [np.empty(x, dtype=_size0_dtype) for x in args] 

474 return _broadcast_shape(*arrays) 

475 

476 

477def _broadcast_arrays_dispatcher(*args, subok=None): 

478 return args 

479 

480 

481@array_function_dispatch(_broadcast_arrays_dispatcher, module='numpy') 

482def broadcast_arrays(*args, subok=False): 

483 """ 

484 Broadcast any number of arrays against each other. 

485 

486 Parameters 

487 ---------- 

488 *args : array_likes 

489 The arrays to broadcast. 

490 

491 subok : bool, optional 

492 If True, then sub-classes will be passed-through, otherwise 

493 the returned arrays will be forced to be a base-class array (default). 

494 

495 Returns 

496 ------- 

497 broadcasted : tuple of arrays 

498 These arrays are views on the original arrays. They are typically 

499 not contiguous. Furthermore, more than one element of a 

500 broadcasted array may refer to a single memory location. If you need 

501 to write to the arrays, make copies first. While you can set the 

502 ``writable`` flag True, writing to a single output value may end up 

503 changing more than one location in the output array. 

504 

505 .. deprecated:: 1.17 

506 The output is currently marked so that if written to, a deprecation 

507 warning will be emitted. A future version will set the 

508 ``writable`` flag False so writing to it will raise an error. 

509 

510 See Also 

511 -------- 

512 broadcast 

513 broadcast_to 

514 broadcast_shapes 

515 

516 Examples 

517 -------- 

518 >>> import numpy as np 

519 >>> x = np.array([[1,2,3]]) 

520 >>> y = np.array([[4],[5]]) 

521 >>> np.broadcast_arrays(x, y) 

522 (array([[1, 2, 3], 

523 [1, 2, 3]]), 

524 array([[4, 4, 4], 

525 [5, 5, 5]])) 

526 

527 Here is a useful idiom for getting contiguous copies instead of 

528 non-contiguous views. 

529 

530 >>> [np.array(a) for a in np.broadcast_arrays(x, y)] 

531 [array([[1, 2, 3], 

532 [1, 2, 3]]), 

533 array([[4, 4, 4], 

534 [5, 5, 5]])] 

535 

536 """ 

537 # nditer is not used here to avoid the limit of 32 arrays. 

538 # Otherwise, something like the following one-liner would suffice: 

539 # return np.nditer(args, flags=['multi_index', 'zerosize_ok'], 

540 # order='C').itviews 

541 

542 args = [np.array(_m, copy=None, subok=subok) for _m in args] 

543 

544 shape = _broadcast_shape(*args) 

545 

546 result = [array if array.shape == shape 

547 else _broadcast_to(array, shape, subok=subok, readonly=False) 

548 for array in args] 

549 return tuple(result)