From d661960b3489c83485a3aa83e909e2ee603e7422 Mon Sep 17 00:00:00 2001 From: David Warde-Farley Date: Thu, 25 Oct 2012 15:32:25 -0400 Subject: BUG: copy.(deep)copy should preserve F-contiguity Currently, copy.deepcopy() on certain objects in scikit-learn results in the copied object being broken, as underlying methods depend on members being F-contiguous. I can think of no reason that F-contiguous arrays should not remain F-contiguous through a copy.copy/copy.deepcopy, therefore this alters the methods to use NPY_KEEPORDER when allocating the copy. --- numpy/core/src/multiarray/methods.c | 16 +++++++++++++--- numpy/core/tests/test_regression.py | 9 ++++++++- 2 files changed, 21 insertions(+), 4 deletions(-) (limited to 'numpy') diff --git a/numpy/core/src/multiarray/methods.c b/numpy/core/src/multiarray/methods.c index 18ff1ec51..e5e21c98d 100644 --- a/numpy/core/src/multiarray/methods.c +++ b/numpy/core/src/multiarray/methods.c @@ -1027,6 +1027,16 @@ array_copy(PyArrayObject *self, PyObject *args, PyObject *kwds) return PyArray_NewCopy(self, order); } +/* Separate from array_copy to make __copy__ preserve Fortran contiguity. */ +static PyObject * +array_copy_keeporder(PyArrayObject *self, PyObject *args, PyObject *kwds) +{ + if (!PyArg_ParseTuple(args, "")) { + return NULL; + } + return PyArray_NewCopy(self, NPY_KEEPORDER); +} + #include static PyObject * array_resize(PyArrayObject *self, PyObject *args, PyObject *kwds) @@ -1291,7 +1301,7 @@ array_deepcopy(PyArrayObject *self, PyObject *args) if (!PyArg_ParseTuple(args, "O", &visit)) { return NULL; } - ret = (PyArrayObject *)PyArray_Copy(self); + ret = (PyArrayObject *)PyArray_NewCopy(self, NPY_KEEPORDER); if (PyDataType_REFCHK(PyArray_DESCR(self))) { copy = PyImport_ImportModule("copy"); if (copy == NULL) { @@ -2160,8 +2170,8 @@ NPY_NO_EXPORT PyMethodDef array_methods[] = { /* for the copy module */ {"__copy__", - (PyCFunction)array_copy, - METH_VARARGS | METH_KEYWORDS, NULL}, + (PyCFunction)array_copy_keeporder, + METH_VARARGS, NULL}, {"__deepcopy__", (PyCFunction)array_deepcopy, METH_VARARGS, NULL}, diff --git a/numpy/core/tests/test_regression.py b/numpy/core/tests/test_regression.py index bb0bf029b..fcbb75ba2 100644 --- a/numpy/core/tests/test_regression.py +++ b/numpy/core/tests/test_regression.py @@ -1903,7 +1903,14 @@ class TestRegression(TestCase): count = np.count_nonzero(arr) assert_equal(count, 0) - + def test_copymodule_preserves_f_contiguity(self): + a = np.empty((2, 2), order='F') + b = copy.copy(a) + c = copy.deepcopy(a) + assert_(b.flags.fortran) + assert_(b.flags.f_contiguous) + assert_(c.flags.fortran) + assert_(c.flags.f_contiguous) if __name__ == "__main__": -- cgit v1.2.1