MCPcopy Create free account
hub / github.com/numpy/numpy / get_data_variation

Method get_data_variation

numpy/core/tests/test_casting_unittests.py:198–255  ·  view source on GitHub ↗

Returns a copy of arr1 that may be non-contiguous or unaligned, and a matching array for arr2 (although not a copy).

(self, arr1, arr2, aligned=True, contig=True)

Source from the content-addressed store, hash-verified

196 return arr1, arr2, values
197
198 def get_data_variation(self, arr1, arr2, aligned=True, contig=True):
199 """
200 Returns a copy of arr1 that may be non-contiguous or unaligned, and a
201 matching array for arr2 (although not a copy).
202 """
203 if contig:
204 stride1 = arr1.dtype.itemsize
205 stride2 = arr2.dtype.itemsize
206 elif aligned:
207 stride1 = 2 * arr1.dtype.itemsize
208 stride2 = 2 * arr2.dtype.itemsize
209 else:
210 stride1 = arr1.dtype.itemsize + 1
211 stride2 = arr2.dtype.itemsize + 1
212
213 max_size1 = len(arr1) * 3 * arr1.dtype.itemsize + 1
214 max_size2 = len(arr2) * 3 * arr2.dtype.itemsize + 1
215 from_bytes = np.zeros(max_size1, dtype=np.uint8)
216 to_bytes = np.zeros(max_size2, dtype=np.uint8)
217
218 # Sanity check that the above is large enough:
219 assert stride1 * len(arr1) <= from_bytes.nbytes
220 assert stride2 * len(arr2) <= to_bytes.nbytes
221
222 if aligned:
223 new1 = as_strided(from_bytes[:-1].view(arr1.dtype),
224 arr1.shape, (stride1,))
225 new2 = as_strided(to_bytes[:-1].view(arr2.dtype),
226 arr2.shape, (stride2,))
227 else:
228 new1 = as_strided(from_bytes[1:].view(arr1.dtype),
229 arr1.shape, (stride1,))
230 new2 = as_strided(to_bytes[1:].view(arr2.dtype),
231 arr2.shape, (stride2,))
232
233 new1[...] = arr1
234
235 if not contig:
236 # Ensure we did not overwrite bytes that should not be written:
237 offset = arr1.dtype.itemsize if aligned else 0
238 buf = from_bytes[offset::stride1].tobytes()
239 assert buf.count(b"\0") == len(buf)
240
241 if contig:
242 assert new1.flags.c_contiguous
243 assert new2.flags.c_contiguous
244 else:
245 assert not new1.flags.c_contiguous
246 assert not new2.flags.c_contiguous
247
248 if aligned:
249 assert new1.flags.aligned
250 assert new2.flags.aligned
251 else:
252 assert not new1.flags.aligned or new1.dtype.alignment == 1
253 assert not new2.flags.aligned or new2.dtype.alignment == 1
254
255 return new1, new2

Callers 4

test_numeric_to_timesMethod · 0.95
test_time_to_timeMethod · 0.95

Calls 4

as_stridedFunction · 0.90
viewMethod · 0.45
tobytesMethod · 0.45
countMethod · 0.45

Tested by

no test coverage detected