Return a zero-copy view of this array's memory with a different data type. The array's contents are not modified in any way. Args: dtype: The desired data type. If ``dtype`` has the same byte size as the array's ``dtype``, the result is an array with the
(self, dtype)
| 4331 | return a |
| 4332 | |
| 4333 | def view(self, dtype): |
| 4334 | """Return a zero-copy view of this array's memory with a different data type. |
| 4335 | The array's contents are not modified in any way. |
| 4336 | |
| 4337 | Args: |
| 4338 | dtype: The desired data type. |
| 4339 | |
| 4340 | If ``dtype`` has the same byte size as the array's ``dtype``, the result is an array with |
| 4341 | the same shape and strides and the new ``dtype``. |
| 4342 | |
| 4343 | This method can also be used to convert between vector, matrix, and scalar types, |
| 4344 | in which case the resulting shape and strides are adjusted as needed. |
| 4345 | |
| 4346 | Example: |
| 4347 | Simple views (same dtype size):: |
| 4348 | |
| 4349 | # view an array of signed integers as unsigned integers |
| 4350 | ai = wp.ones(10, dtype=wp.int32) |
| 4351 | au = ai.view(wp.uint32) |
| 4352 | |
| 4353 | # view an array of vec4 as quat or mat22 |
| 4354 | av = wp.ones(10, dtype=wp.vec4) |
| 4355 | aq = av.view(wp.quat) |
| 4356 | am = av.view(wp.mat22) |
| 4357 | |
| 4358 | # view 4-byte vectors as a single unsigned integer |
| 4359 | rgba = wp.ones(10, dtype=wp.vec4ub) |
| 4360 | color = rgba.view(wp.uint32) |
| 4361 | |
| 4362 | Vector/matrix to scalar views:: |
| 4363 | |
| 4364 | av = wp.ones(10, dtype=wp.vec4) |
| 4365 | am = wp.ones(10, dtype=wp.mat33) |
| 4366 | avf = av.view(float) # shape (10, 4) |
| 4367 | amf = am.view(float) # shape (10, 3, 3) |
| 4368 | |
| 4369 | Scalar to vector/matrix views:: |
| 4370 | |
| 4371 | avf = wp.ones((10, 4), dtype=float) |
| 4372 | amf = wp.ones((10, 3, 3), dtype=float) |
| 4373 | av = avf.view(wp.vec4) # shape (10,) |
| 4374 | am = amf.view(wp.mat33) # shape (10,) |
| 4375 | """ |
| 4376 | if type_size_in_bytes(dtype) == type_size_in_bytes(self.dtype): |
| 4377 | # a simple "reinterpret cast" |
| 4378 | result_shape = self.shape |
| 4379 | result_strides = self.strides |
| 4380 | elif type_is_scalar(dtype) and hasattr(self.dtype, "_wp_scalar_type_"): |
| 4381 | # cast from vec/mat type to scalar type |
| 4382 | if type_size_in_bytes(dtype) == type_size_in_bytes(self.dtype._wp_scalar_type_): |
| 4383 | result_shape = (*self.shape, *self.dtype._shape_) |
| 4384 | result_strides = (*self.strides, *strides_from_shape(self.dtype._shape_, self.dtype._wp_scalar_type_)) |
| 4385 | else: |
| 4386 | raise TypeError("Incompatible scalar type sizes") |
| 4387 | elif type_is_scalar(self.dtype) and hasattr(dtype, "_wp_scalar_type_"): |
| 4388 | # cast from scalar type to vec/mat type |
| 4389 | if type_size_in_bytes(self.dtype) == type_size_in_bytes(dtype._wp_scalar_type_): |
| 4390 | # ensure that the shape and strides are compatible with the requested vec/mat type |