Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions lib/matplotlib/contour.py
Original file line number Diff line number Diff line change
Expand Up @@ -1542,6 +1542,8 @@ def _check_xyz(self, args, kwargs):

if z.ndim != 2:
raise TypeError("Input z must be a 2D array.")
elif z.shape[0] < 2 or z.shape[1] < 2:
raise TypeError("Input z must be at least a 2x2 array.")
else:
Ny, Nx = z.shape

Expand Down Expand Up @@ -1590,6 +1592,8 @@ def _initialize_x_y(self, z):
"""
if z.ndim != 2:
raise TypeError("Input must be a 2D array.")
elif z.shape[0] < 2 or z.shape[1] < 2:
raise TypeError("Input z must be at least a 2x2 array.")
else:
Ny, Nx = z.shape
if self.origin is None: # Not for image-matching.
Expand Down
91 changes: 61 additions & 30 deletions lib/matplotlib/tests/test_contour.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,9 @@ def test_contour_shape_mismatch_1():
fig = plt.figure()
ax = fig.add_subplot(111)

try:
with pytest.raises(TypeError) as excinfo:
ax.contour(x, y, z)
except TypeError as exc:
assert exc.args[0] == 'Length of x must be number of columns in z.'
excinfo.match(r'Length of x must be number of columns in z.')


def test_contour_shape_mismatch_2():
Expand All @@ -61,10 +60,9 @@ def test_contour_shape_mismatch_2():
fig = plt.figure()
ax = fig.add_subplot(111)

try:
with pytest.raises(TypeError) as excinfo:
ax.contour(x, y, z)
except TypeError as exc:
assert exc.args[0] == 'Length of y must be number of rows in z.'
excinfo.match(r'Length of y must be number of rows in z.')


def test_contour_shape_mismatch_3():
Expand All @@ -77,15 +75,13 @@ def test_contour_shape_mismatch_3():
fig = plt.figure()
ax = fig.add_subplot(111)

try:
with pytest.raises(TypeError) as excinfo:
ax.contour(xg, y, z)
except TypeError as exc:
assert exc.args[0] == 'Number of dimensions of x and y should match.'
excinfo.match(r'Number of dimensions of x and y should match.')

try:
with pytest.raises(TypeError) as excinfo:
ax.contour(x, yg, z)
except TypeError as exc:
assert exc.args[0] == 'Number of dimensions of x and y should match.'
excinfo.match(r'Number of dimensions of x and y should match.')


def test_contour_shape_mismatch_4():
Expand All @@ -97,21 +93,15 @@ def test_contour_shape_mismatch_4():
fig = plt.figure()
ax = fig.add_subplot(111)

try:
with pytest.raises(TypeError) as excinfo:
ax.contour(b, g, z)
except TypeError as exc:
assert re.match(
r'Shape of x does not match that of z: ' +
r'found \(9L?, 9L?\) instead of \(9L?, 10L?\)\.',
exc.args[0]) is not None, exc.args[0]
excinfo.match(r'Shape of x does not match that of z: found \(9L?, 9L?\) ' +
r'instead of \(9L?, 10L?\)')

try:
with pytest.raises(TypeError) as excinfo:
ax.contour(g, b, z)
except TypeError as exc:
assert re.match(
r'Shape of y does not match that of z: ' +
r'found \(9L?, 9L?\) instead of \(9L?, 10L?\)\.',
exc.args[0]) is not None, exc.args[0]
excinfo.match(r'Shape of y does not match that of z: found \(9L?, 9L?\) ' +
r'instead of \(9L?, 10L?\)')


def test_contour_shape_invalid_1():
Expand All @@ -123,10 +113,9 @@ def test_contour_shape_invalid_1():
fig = plt.figure()
ax = fig.add_subplot(111)

try:
with pytest.raises(TypeError) as excinfo:
ax.contour(x, y, z)
except TypeError as exc:
assert exc.args[0] == 'Inputs x and y must be 1D or 2D.'
excinfo.match(r'Inputs x and y must be 1D or 2D.')


def test_contour_shape_invalid_2():
Expand All @@ -138,10 +127,9 @@ def test_contour_shape_invalid_2():
fig = plt.figure()
ax = fig.add_subplot(111)

try:
with pytest.raises(TypeError) as excinfo:
ax.contour(x, y, z)
except TypeError as exc:
assert exc.args[0] == 'Input z must be a 2D array.'
excinfo.match(r'Input z must be a 2D array.')


@image_comparison(baseline_images=['contour_manual_labels'])
Expand Down Expand Up @@ -309,3 +297,46 @@ def test_contourf_symmetric_locator():
locator = plt.MaxNLocator(nbins=4, symmetric=True)
cs = plt.contourf(z, locator=locator)
assert_array_almost_equal(cs.levels, np.linspace(-12, 12, 5))


def test_contour_1x1_array():

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This test might need a cleanup decorator, because while the plt.contour() calls all fail, figures and axes are still produced prior to throwing the error.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

master does not need or use the cleanup decorator any more; it's all in the py.test fixture.

# github issue 8197
with pytest.raises(TypeError) as excinfo:
plt.contour([[0]])
excinfo.match(r'Input z must be at least a 2x2 array.')

with pytest.raises(TypeError) as excinfo:
plt.contour([0], [0], [[0]])
excinfo.match(r'Input z must be at least a 2x2 array.')


def test_internal_cpp_api():
# Following github issue 8197.
import matplotlib._contour as _contour

with pytest.raises(TypeError) as excinfo:
qcg = _contour.QuadContourGenerator()
excinfo.match(r'function takes exactly 6 arguments \(0 given\)')

with pytest.raises(ValueError) as excinfo:
qcg = _contour.QuadContourGenerator(1, 2, 3, 4, 5, 6)
excinfo.match(r'Expected 2-dimensional array, got 0')

with pytest.raises(ValueError) as excinfo:
qcg = _contour.QuadContourGenerator([[0]], [[0]], [[]], None, True, 0)
excinfo.match(r'x, y and z must all be 2D arrays with the same dimensions')

with pytest.raises(ValueError) as excinfo:
qcg = _contour.QuadContourGenerator([[0]], [[0]], [[0]], None, True, 0)
excinfo.match(r'x, y and z must all be at least 2x2 arrays')

arr = [[0, 1], [2, 3]]
with pytest.raises(ValueError) as excinfo:
qcg = _contour.QuadContourGenerator(arr, arr, arr, [[0]], True, 0)
excinfo.match(r'If mask is set it must be a 2D array with the same ' +
r'dimensions as x.')

qcg = _contour.QuadContourGenerator(arr, arr, arr, None, True, 0)
with pytest.raises(ValueError) as excinfo:
qcg.create_filled_contour(1, 0)
excinfo.match(r'filled contour levels must be increasing')
75 changes: 75 additions & 0 deletions lib/matplotlib/tests/test_triangulation.py
Original file line number Diff line number Diff line change
Expand Up @@ -1048,3 +1048,78 @@ def test_tricontourf_decreasing_levels():
plt.figure()
with pytest.raises(ValueError):
plt.tricontourf(x, y, z, [1.0, 0.0])


def test_internal_cpp_api():
# Following github issue 8197.
import matplotlib._tri as _tri

# C++ Triangulation.
with pytest.raises(TypeError) as excinfo:
triang = _tri.Triangulation()
excinfo.match(r'function takes exactly 7 arguments \(0 given\)')

with pytest.raises(ValueError) as excinfo:
triang = _tri.Triangulation([], [1], [[]], None, None, None, False)
excinfo.match(r'x and y must be 1D arrays of the same length')

x = [0, 1, 1]
y = [0, 0, 1]
with pytest.raises(ValueError) as excinfo:
triang = _tri.Triangulation(x, y, [[0, 1]], None, None, None, False)
excinfo.match(r'triangles must be a 2D array of shape \(\?,3\)')

tris = [[0, 1, 2]]
with pytest.raises(ValueError) as excinfo:
triang = _tri.Triangulation(x, y, tris, [0, 1], None, None, False)
excinfo.match(r'mask must be a 1D array with the same length as the ' +
r'triangles array')

with pytest.raises(ValueError) as excinfo:
triang = _tri.Triangulation(x, y, tris, None, [[1]], None, False)
excinfo.match(r'edges must be a 2D array with shape \(\?,2\)')

with pytest.raises(ValueError) as excinfo:
triang = _tri.Triangulation(x, y, tris, None, None, [[-1]], False)
excinfo.match(r'neighbors must be a 2D array with the same shape as the ' +
r'triangles array')

triang = _tri.Triangulation(x, y, tris, None, None, None, False)

with pytest.raises(ValueError) as excinfo:
triang.calculate_plane_coefficients([])
excinfo.match(r'z array must have same length as triangulation x and y ' +
r'arrays')

with pytest.raises(ValueError) as excinfo:
triang.set_mask([0, 1])
excinfo.match(r'mask must be a 1D array with the same length as the ' +
r'triangles array')

# C++ TriContourGenerator.
with pytest.raises(TypeError) as excinfo:
tcg = _tri.TriContourGenerator()
excinfo.match(r'function takes exactly 2 arguments \(0 given\)')

with pytest.raises(ValueError) as excinfo:
tcg = _tri.TriContourGenerator(triang, [1])
excinfo.match(r'z must be a 1D array with the same length as the x and ' +
r'y arrays')

z = [0, 1, 2]
tcg = _tri.TriContourGenerator(triang, z)

with pytest.raises(ValueError) as excinfo:
tcg.create_filled_contour(1, 0)
excinfo.match(r'filled contour levels must be increasing')

# C++ TrapezoidMapTriFinder.
with pytest.raises(TypeError) as excinfo:
trifinder = _tri.TrapezoidMapTriFinder()
excinfo.match(r'function takes exactly 1 argument \(0 given\)')

trifinder = _tri.TrapezoidMapTriFinder(triang)

with pytest.raises(ValueError) as excinfo:
trifinder.find_many([0], [0, 1])
excinfo.match(r'x and y must be array_like with same shape')
10 changes: 10 additions & 0 deletions lib/matplotlib/tri/_tri_wrapper.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -53,31 +53,36 @@ static int PyTriangulation_init(PyTriangulation* self, PyObject* args, PyObject*
if (x.empty() || y.empty() || x.dim(0) != y.dim(0)) {
PyErr_SetString(PyExc_ValueError,
"x and y must be 1D arrays of the same length");
return -1;
}

// triangles.
if (triangles.empty() || triangles.dim(1) != 3) {
PyErr_SetString(PyExc_ValueError,
"triangles must be a 2D array of shape (?,3)");
return -1;
}

// Optional mask.
if (!mask.empty() && mask.dim(0) != triangles.dim(0)) {
PyErr_SetString(PyExc_ValueError,
"mask must be a 1D array with the same length as the triangles array");
return -1;
}

// Optional edges.
if (!edges.empty() && edges.dim(1) != 2) {
PyErr_SetString(PyExc_ValueError,
"edges must be a 2D array with shape (?,2)");
return -1;
}

// Optional neighbors.
if (!neighbors.empty() && (neighbors.dim(0) != triangles.dim(0) ||
neighbors.dim(1) != triangles.dim(1))) {
PyErr_SetString(PyExc_ValueError,
"neighbors must be a 2D array with the same shape as the triangles array");
return -1;
}

CALL_CPP_INIT("Triangulation",
Expand Down Expand Up @@ -109,6 +114,7 @@ static PyObject* PyTriangulation_calculate_plane_coefficients(PyTriangulation* s
if (z.empty() || z.dim(0) != self->ptr->get_npoints()) {
PyErr_SetString(PyExc_ValueError,
"z array must have same length as triangulation x and y arrays");
return NULL;
}

Triangulation::TwoCoordinateArray result;
Expand Down Expand Up @@ -167,6 +173,7 @@ static PyObject* PyTriangulation_set_mask(PyTriangulation* self, PyObject* args,
if (!mask.empty() && mask.dim(0) != self->ptr->get_ntri()) {
PyErr_SetString(PyExc_ValueError,
"mask must be a 1D array with the same length as the triangles array");
return NULL;
}

CALL_CPP("set_mask", (self->ptr->set_mask(mask)));
Expand Down Expand Up @@ -251,6 +258,7 @@ static int PyTriContourGenerator_init(PyTriContourGenerator* self, PyObject* arg
if (z.empty() || z.dim(0) != triangulation.get_npoints()) {
PyErr_SetString(PyExc_ValueError,
"z must be a 1D array with the same length as the x and y arrays");
return -1;
}

CALL_CPP_INIT("TriContourGenerator",
Expand Down Expand Up @@ -299,6 +307,7 @@ static PyObject* PyTriContourGenerator_create_filled_contour(PyTriContourGenerat
{
PyErr_SetString(PyExc_ValueError,
"filled contour levels must be increasing");
return NULL;
}

PyObject* result;
Expand Down Expand Up @@ -407,6 +416,7 @@ static PyObject* PyTrapezoidMapTriFinder_find_many(PyTrapezoidMapTriFinder* self
if (x.empty() || y.empty() || x.dim(0) != y.dim(0)) {
PyErr_SetString(PyExc_ValueError,
"x and y must be array_like with same shape");
return NULL;
}

TrapezoidMapTriFinder::TriIndexArray result;
Expand Down
9 changes: 9 additions & 0 deletions src/_contour_wrapper.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,20 @@ static int PyQuadContourGenerator_init(PyQuadContourGenerator* self, PyObject* a
y.dim(1) != x.dim(1) || z.dim(1) != x.dim(1)) {
PyErr_SetString(PyExc_ValueError,
"x, y and z must all be 2D arrays with the same dimensions");
return -1;
}

if (z.dim(0) < 2 || z.dim(1) < 2) {
PyErr_SetString(PyExc_ValueError,
"x, y and z must all be at least 2x2 arrays");
return -1;
}

// Mask array is optional, if set must be same size as other arrays.
if (!mask.empty() && (mask.dim(0) != x.dim(0) || mask.dim(1) != x.dim(1))) {
PyErr_SetString(PyExc_ValueError,
"If mask is set it must be a 2D array with the same dimensions as x.");
return -1;
}

CALL_CPP_INIT("QuadContourGenerator",
Expand Down Expand Up @@ -101,6 +109,7 @@ static PyObject* PyQuadContourGenerator_create_filled_contour(PyQuadContourGener
{
PyErr_SetString(PyExc_ValueError,
"filled contour levels must be increasing");
return NULL;
}

PyObject* result;
Expand Down