[Numpy-tickets] [NumPy] #358: Reshape makes unnecessary copies
NumPy
numpy-tickets at scipy.net
Fri Oct 20 01:54:51 CDT 2006
#358: Reshape makes unnecessary copies
---------------------+------------------------------------------------------
Reporter: peridot | Owner: somebody
Type: defect | Status: new
Priority: normal | Milestone:
Component: Other | Version:
Severity: normal | Keywords:
---------------------+------------------------------------------------------
Reshape's rule for detecting when it can return a view is too
conservative. This results in unnecessary copying of data, and it
restricts the utility of assigning to the shape attribute (which never
copies). Consider the following session:
{{{
In [3]: from numpy import *
In [4]: z = zeros((4,4))[:,1]
In [5]: z
Out[5]: array([ 0., 0., 0., 0.])
In [6]: r = z.reshape((2,2))
In [7]: r[0]=1
In [8]: z
Out[8]: array([ 0., 0., 0., 0.])
}}}
The elements of z are not contiguous, but they are a linear array spaced
by 4*sizeof(float); there's no reason this can't be reshaped with a view.
Attached is a patch that recognizes all situations where a view can be
returned. It passes all tests in numpy, and a few of my own devising
(although it could use a more thorough and organized test suite). The new
code is only called when a copy would have been made under the current
rules, so it should not affect the speed of "easy" reshapes. It does
correctly handle the easy reshapes, so the code could perhaps be
simplified by removing some special-case detection.
--
Ticket URL: <http://projects.scipy.org/scipy/numpy/ticket/358>
NumPy <http://projects.scipy.org/scipy/numpy>
The fundamental package needed for scientific computing with Python.
More information about the Numpy-tickets
mailing list