Skip to content

Commit

Permalink
Allow comparison between Cell and numpy array or list of len = 1. (#4083
Browse files Browse the repository at this point in the history
)

* Allow comparison with numpy array or list of len = 1.

* Add test

* Add tests for numpy arrays of len=1

* Add bug fix descripation in latest.rst

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
  • Loading branch information
gcaria and pre-commit-ci[bot] committed Jul 23, 2021
1 parent 4850fda commit 149164e
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 2 deletions.
3 changes: 3 additions & 0 deletions docs/src/whatsnew/latest.rst
Expand Up @@ -60,6 +60,9 @@ This document explains the changes made to Iris for this release
🐛 Bugs Fixed
=============

#. `@gcaria`_ fixed :class:`~iris.coords.Cell` comparison with
0-dimensional arrays and 1-dimensional arrays with len=1. (:pull:`4083`)

#. `@gcaria`_ fixed :meth:`~iris.cube.Cube.cell_measure_dims` to also accept the
string name of a :class:`~iris.coords.CellMeasure`. (:pull:`3931`)

Expand Down
9 changes: 7 additions & 2 deletions lib/iris/coords.py
Expand Up @@ -809,7 +809,6 @@ def __init__(
attributes=None,
measure=None,
):

"""
Constructs a single cell measure.
Expand Down Expand Up @@ -1151,6 +1150,13 @@ def __common_cmp__(self, other, operator_method):
Non-Cell vs Cell comparison is used to define Constraint matching.
"""

if (isinstance(other, list) and len(other) == 1) or (
isinstance(other, np.ndarray) and other.shape == (1,)
):
other = other[0]
if isinstance(other, np.ndarray) and other.shape == ():
other = float(other)
if not (
isinstance(other, (int, float, np.number, Cell))
or hasattr(other, "timetuple")
Expand Down Expand Up @@ -1315,7 +1321,6 @@ def __init__(
coord_system=None,
climatological=False,
):

"""
Coordinate abstract base class. As of ``v3.0.0`` you **cannot** create an instance of :class:`Coord`.
Expand Down
20 changes: 20 additions & 0 deletions lib/iris/tests/unit/coords/test_Cell.py
Expand Up @@ -92,6 +92,26 @@ def test_datetime_unbounded_cell(self):
self.assertLess(cell, dt)
self.assertLessEqual(cell, dt)

def test_0D_numpy_array(self):
# Check that cell comparison works with 0D numpy arrays

cell = Cell(1.3)

self.assertGreater(np.array(1.5), cell)
self.assertLess(np.array(1.1), cell)
self.assertGreaterEqual(np.array(1.3), cell)
self.assertLessEqual(np.array(1.3), cell)

def test_len_1_numpy_array(self):
# Check that cell comparison works with numpy arrays of len=1

cell = Cell(1.3)

self.assertGreater(np.array([1.5]), cell)
self.assertLess(np.array([1.1]), cell)
self.assertGreaterEqual(np.array([1.3]), cell)
self.assertLessEqual(np.array([1.3]), cell)


class Test___eq__(tests.IrisTest):
def test_datetimelike(self):
Expand Down

0 comments on commit 149164e

Please sign in to comment.