Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FIX: array_view construction for empty arrays #5106

Merged
merged 8 commits into from Oct 2, 2015
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
15 changes: 15 additions & 0 deletions lib/matplotlib/cbook.py
Expand Up @@ -2244,6 +2244,21 @@ def _reshape_2D(X):
return X


def ensure_3d(arr):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we want to make this a public function? We now have _check_1d(), _reshape_2D, and this new ensure_3d (notice the inconsistency with the case of "d/D").

Why don't we make this private, and make a new issue to unify the logic across these three functions later (if possible)?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would have thought that an underscore in the beginning means a function that is only called from within cbook, but clearly some underscored functions are called from elsewhere. What is the intended meaning?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

https://www.python.org/dev/peps/pep-0008/#id29

It means that it is to be treated as being for internal use only. This
gives developers the freedom to modify the API of such modules or functions
without warning or deprecation cycles. As noted later in PEP8, it is easier
to start with something as private and then make it public later, as
opposed to releasing it as public and then modifying it later.

On Mon, Sep 28, 2015 at 10:23 AM, Jouni K. Seppänen <
notifications@github.com> wrote:

In lib/matplotlib/cbook.py
#5106 (comment):

@@ -2244,6 +2244,21 @@ def _reshape_2D(X):
return X

+def ensure_3d(arr):

I would have thought that an underscore in the beginning means a function
that is only called from within cbook, but clearly some underscored
functions are called from elsewhere. What is the intended meaning?


Reply to this email directly or view it on GitHub
https://github.com/matplotlib/matplotlib/pull/5106/files#r40557282.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PEP8 doesn't really say what the boundaries of internal use are, but I guess here it means internal to matplotlib. Ok, I'll change this.

"""
Return a version of arr with ndim==3, with extra dimensions added
at the end of arr.shape as needed.
"""
arr = np.asanyarray(arr)
if arr.ndim == 1:
arr = arr[:, None, None]
elif arr.ndim == 2:
arr = arr[:, :, None]
elif arr.ndim > 3 or arr.ndim < 1:
raise ValueError("cannot convert arr to 3-dimensional")
return arr


def violin_stats(X, method, points=100):
'''
Returns a list of dictionaries of data which can be used to draw a series
Expand Down
6 changes: 2 additions & 4 deletions lib/matplotlib/collections.py
Expand Up @@ -80,9 +80,7 @@ class Collection(artist.Artist, cm.ScalarMappable):
# _offsets must be a Nx2 array!
_offsets.shape = (0, 2)
_transOffset = transforms.IdentityTransform()
_transforms = []


_transforms = np.empty((0, 3, 3))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since you've touched it, would you mind adding a #: style docstring for what _transforms is supposed to be - this will make reviewing (and editing) this part of the code easier in the future.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Where is this #: style documented?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think @pelson just means to add a normal comment explaining what the expected shape of _transfroms is and why?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see with git grep that there is a small number of #: comments in the code, but that's not a very easy thing to search. Does Sphinx do something special with them, or some other tool?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.


def __init__(self,
edgecolors=None,
Expand Down Expand Up @@ -1515,7 +1513,7 @@ def __init__(self, widths, heights, angles, units='points', **kwargs):
self._angles = np.asarray(angles).ravel() * (np.pi / 180.0)
self._units = units
self.set_transform(transforms.IdentityTransform())
self._transforms = []
self._transforms = np.empty((0, 3, 3))
self._paths = [mpath.Path.unit_circle()]

def _set_transforms(self):
Expand Down
5 changes: 3 additions & 2 deletions lib/matplotlib/path.py
Expand Up @@ -24,7 +24,7 @@
from numpy import ma

from matplotlib import _path
from matplotlib.cbook import simple_linear_interpolation, maxdict
from matplotlib.cbook import simple_linear_interpolation, maxdict, ensure_3d
from matplotlib import rcParams


Expand Down Expand Up @@ -988,7 +988,8 @@ def get_path_collection_extents(
if len(paths) == 0:
raise ValueError("No paths provided")
return Bbox.from_extents(*_path.get_path_collection_extents(
master_transform, paths, transforms, offsets, offset_transform))
master_transform, paths, ensure_3d(transforms),
offsets, offset_transform))


def get_paths_extents(paths, transforms=[]):
Expand Down
8 changes: 8 additions & 0 deletions lib/matplotlib/tests/test_cbook.py
Expand Up @@ -376,3 +376,11 @@ def test_step_fails():
np.arange(12))
assert_raises(ValueError, cbook._step_validation,
np.arange(12), np.arange(3))


def test_ensure_3d():
assert_array_equal([[[1]], [[2]], [[3]]],
cbook.ensure_3d([1, 2, 3]))
assert_array_equal([[[1], [2]], [[3], [4]]],
cbook.ensure_3d([[1, 2], [3, 4]]))
assert_raises(ValueError, cbook.ensure_3d, [[[[1]]]])
15 changes: 15 additions & 0 deletions lib/matplotlib/tests/test_transforms.py
Expand Up @@ -561,6 +561,21 @@ def test_nonsingular():
assert_array_equal(out, zero_expansion)


def test_invalid_arguments():
t = mtrans.Affine2D()
# There are two different exceptions, since the wrong number of
# dimensions is caught when constructing an array_view, and that
# raises a ValueError, and a wrong shape with a possible number
# of dimensions is caught by our CALL_CPP macro, which always
# raises the less precise RuntimeError.
assert_raises(ValueError, t.transform, 1)
assert_raises(ValueError, t.transform, [[[1]]])
assert_raises(RuntimeError, t.transform, [])
assert_raises(RuntimeError, t.transform, [1])
assert_raises(RuntimeError, t.transform, [[1]])
assert_raises(RuntimeError, t.transform, [[1, 2, 3]])


if __name__ == '__main__':
import nose
nose.runmodule(argv=['-s', '--with-doctest'], exit=False)
4 changes: 3 additions & 1 deletion lib/matplotlib/transforms.py
Expand Up @@ -48,6 +48,7 @@
from sets import Set as set

from .path import Path
from .cbook import ensure_3d

DEBUG = False
# we need this later, but this is very expensive to set up
Expand Down Expand Up @@ -666,7 +667,8 @@ def count_overlaps(self, bboxes):

bboxes is a sequence of :class:`BboxBase` objects
"""
return count_bboxes_overlapping_bbox(self, [np.array(x) for x in bboxes])
return count_bboxes_overlapping_bbox(
self, ensure_3d([np.array(x) for x in bboxes]))

def expanded(self, sw, sh):
"""
Expand Down
15 changes: 10 additions & 5 deletions src/_path_wrapper.cpp
Expand Up @@ -439,11 +439,16 @@ static PyObject *Py_affine_transform(PyObject *self, PyObject *args, PyObject *k
CALL_CPP("affine_transform", (affine_transform_2d(vertices, trans, result)));
return result.pyobj();
} catch (py::exception) {
numpy::array_view<double, 1> vertices(vertices_obj);
npy_intp dims[] = { vertices.dim(0) };
numpy::array_view<double, 1> result(dims);
CALL_CPP("affine_transform", (affine_transform_1d(vertices, trans, result)));
return result.pyobj();
PyErr_Clear();
try {
numpy::array_view<double, 1> vertices(vertices_obj);
npy_intp dims[] = { vertices.dim(0) };
numpy::array_view<double, 1> result(dims);
CALL_CPP("affine_transform", (affine_transform_1d(vertices, trans, result)));
return result.pyobj();
} catch (py::exception) {
return NULL;
}
}
}

Expand Down
19 changes: 12 additions & 7 deletions src/numpy_cpp.h
Expand Up @@ -443,13 +443,18 @@ class array_view : public detail::array_view_accessors<array_view, T, ND>
m_data = NULL;
m_shape = zeros;
m_strides = zeros;
} else if (PyArray_NDIM(tmp) != ND) {
PyErr_Format(PyExc_ValueError,
"Expected %d-dimensional array, got %d",
ND,
PyArray_NDIM(tmp));
Py_DECREF(tmp);
return 0;
if (PyArray_NDIM(tmp) == 0 && ND == 0) {
m_arr = tmp;
return 1;
}
}
if (PyArray_NDIM(tmp) != ND) {
PyErr_Format(PyExc_ValueError,
"Expected %d-dimensional array, got %d",
ND,
PyArray_NDIM(tmp));
Py_DECREF(tmp);
return 0;
}

/* Copy some of the data to the view object for faster access */
Expand Down