Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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.overrides import array_function_dispatch 

10 

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

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 

37def as_strided(x, shape=None, strides=None, subok=False, writeable=True): 

38 """ 

39 Create a view into the array with the given shape and strides. 

40 

41 .. warning:: This function has to be used with extreme care, see notes. 

42 

43 Parameters 

44 ---------- 

45 x : ndarray 

46 Array to create a new. 

47 shape : sequence of int, optional 

48 The shape of the new array. Defaults to ``x.shape``. 

49 strides : sequence of int, optional 

50 The strides of the new array. Defaults to ``x.strides``. 

51 subok : bool, optional 

52 .. versionadded:: 1.10 

53 

54 If True, subclasses are preserved. 

55 writeable : bool, optional 

56 .. versionadded:: 1.12 

57 

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

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

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

61 

62 Returns 

63 ------- 

64 view : ndarray 

65 

66 See also 

67 -------- 

68 broadcast_to: broadcast an array to a given shape. 

69 reshape : reshape an array. 

70 

71 Notes 

72 ----- 

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

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

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

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

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

78 calculating new strides to avoid reliance on a contiguous memory 

79 layout. 

80 

81 Furthermore, arrays created with this function often contain self 

82 overlapping memory, so that two elements are identical. 

83 Vectorized write operations on such arrays will typically be 

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

85 or transposed arrays. 

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=False, 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 _broadcast_to(array, shape, subok, readonly): 

115 shape = tuple(shape) if np.iterable(shape) else (shape,) 

116 array = np.array(array, copy=False, subok=subok) 

117 if not shape and array.shape: 

118 raise ValueError('cannot broadcast a non-scalar to a scalar array') 

119 if any(size < 0 for size in shape): 

120 raise ValueError('all elements of broadcast shape must be non-' 

121 'negative') 

122 extras = [] 

123 it = np.nditer( 

124 (array,), flags=['multi_index', 'refs_ok', 'zerosize_ok'] + extras, 

125 op_flags=['readonly'], itershape=shape, order='C') 

126 with it: 

127 # never really has writebackifcopy semantics 

128 broadcast = it.itviews[0] 

129 result = _maybe_view_as_subclass(array, broadcast) 

130 # In a future version this will go away 

131 if not readonly and array.flags._writeable_no_warn: 

132 result.flags.writeable = True 

133 result.flags._warn_on_write = True 

134 return result 

135 

136 

137def _broadcast_to_dispatcher(array, shape, subok=None): 

138 return (array,) 

139 

140 

141@array_function_dispatch(_broadcast_to_dispatcher, module='numpy') 

142def broadcast_to(array, shape, subok=False): 

143 """Broadcast an array to a new shape. 

144 

145 Parameters 

146 ---------- 

147 array : array_like 

148 The array to broadcast. 

149 shape : tuple 

150 The shape of the desired array. 

151 subok : bool, optional 

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

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

154 

155 Returns 

156 ------- 

157 broadcast : array 

158 A readonly view on the original array with the given shape. It is 

159 typically not contiguous. Furthermore, more than one element of a 

160 broadcasted array may refer to a single memory location. 

161 

162 Raises 

163 ------ 

164 ValueError 

165 If the array is not compatible with the new shape according to NumPy's 

166 broadcasting rules. 

167 

168 Notes 

169 ----- 

170 .. versionadded:: 1.10.0 

171 

172 Examples 

173 -------- 

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

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

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

177 [1, 2, 3], 

178 [1, 2, 3]]) 

179 """ 

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

181 

182 

183def _broadcast_shape(*args): 

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

185 supplied arrays against each other. 

186 """ 

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

188 # consistently 

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

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

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

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

193 # objects (it treats them as scalars) 

194 # use broadcasting to avoid allocating the full array 

195 b = broadcast_to(0, b.shape) 

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

197 return b.shape 

198 

199 

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

201 return args 

202 

203 

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

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

206 """ 

207 Broadcast any number of arrays against each other. 

208 

209 Parameters 

210 ---------- 

211 `*args` : array_likes 

212 The arrays to broadcast. 

213 

214 subok : bool, optional 

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

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

217 

218 Returns 

219 ------- 

220 broadcasted : list of arrays 

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

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

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

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

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

226 changing more than one location in the output array. 

227 

228 .. deprecated:: 1.17 

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

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

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

232 

233 Examples 

234 -------- 

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

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

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

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

239 [1, 2, 3]]), array([[4, 4, 4], 

240 [5, 5, 5]])] 

241 

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

243 non-contiguous views. 

244 

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

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

247 [1, 2, 3]]), array([[4, 4, 4], 

248 [5, 5, 5]])] 

249 

250 """ 

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

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

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

254 # order='C').itviews 

255 

256 args = [np.array(_m, copy=False, subok=subok) for _m in args] 

257 

258 shape = _broadcast_shape(*args) 

259 

260 if all(array.shape == shape for array in args): 

261 # Common case where nothing needs to be broadcasted. 

262 return args 

263 

264 return [_broadcast_to(array, shape, subok=subok, readonly=False) 

265 for array in args]