-
Notifications
You must be signed in to change notification settings - Fork 348
Description
The .into_shape() method works in some cases, but compared to NumPy's reshape() has the following limitations:
- It only works for arrays with contiguous memory layout.
- The result depends on the layout of the data in memory. (Calling
.into_shape()on an array with Fortran memory layout will give a different result from calling.into_shape()on the logically equivalent array with C memory layout.) - All of the new axis lengths need to be known. (NumPy has the nice ability to use
-1to indicate that an axis length should be inferred.)
I'd like to add a method or methods to resolve at least limitations 1 and 2.
In order to handle arrays without contiguous memory layout, the data needs to be cloned in some cases. If the input array owns its data, this is simple – just return a new owned array. However, if the input array is an ArrayView, then you need to return something like Cow. If the input array is an ArrayViewMut, you need some way to return a mutable view with the correct shape but make sure that any changes to that view are copied back to the original underlying data.
A prototype of one approach is at jturner314/ndarray@0157df8. This introduces a few new types, including ArrayViewTemp which handles the temporary array if the input is an ArrayView, and ArrayViewMutTemp, which handles the case where the input is an ArrayViewMut (using Drop to make sure the data is written from the temporary array back to the original underlying data).
It's worth noting that this type of problem (needing a temporary array in some cases) also occurs for operations other than reshaping. For example, I'm working on a similar approach for ndarray-linalg to convert arrays/views to Fortran layout to pass to LAPACK. If something like ArrayViewTemp and ArrayViewMutTemp get added to ndarray, I can reuse those types in ndarray-linalg for the changing-layout problem.
What do you think?
Edit: After thinking about this a little more, I realized:
- Instead of wrapping arrays in
ArrayViewTempandArrayViewMutTempenums, it would be cleaner to create new reprs for theStype parameter inArrayBasethat implementData/DataMut. - It might be possible for
drop_hookinArrayViewMutTempReprto own the view of the original data so that theviewfield andDotype parameter could be removed.