Thanks to visit codestin.com
Credit goes to github.com

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
21 changes: 11 additions & 10 deletions lib/matplotlib/colors.py
Original file line number Diff line number Diff line change
Expand Up @@ -715,16 +715,17 @@ def __call__(self, X, alpha=None, bytes=False):
if not xa.dtype.isnative:
xa = xa.byteswap().newbyteorder() # Native byteorder is faster.
if xa.dtype.kind == "f":
with np.errstate(invalid="ignore"):
xa *= self.N
# Negative values are out of range, but astype(int) would
# truncate them towards zero.
xa[xa < 0] = -1
# xa == 1 (== N after multiplication) is not out of range.
xa[xa == self.N] = self.N - 1
# Avoid converting large positive values to negative integers.
np.clip(xa, -1, self.N, out=xa)
xa = xa.astype(int)
xa *= self.N
# Negative values are out of range, but astype(int) would
# truncate them towards zero.
xa[xa < 0] = -1
# xa == 1 (== N after multiplication) is not out of range.
xa[xa == self.N] = self.N - 1
# Avoid converting large positive values to negative integers.
np.clip(xa, -1, self.N, out=xa)
with np.errstate(invalid="ignore"):
Copy link
Contributor

Choose a reason for hiding this comment

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

Is the errstate even still needed? AFAICT casting nan to int doesn't trigger an "invalid" error.

Copy link
Contributor Author

@greglucas greglucas Jan 13, 2023

Choose a reason for hiding this comment

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

I get one with it and get lots of failures in the pytest suite without ignoring.

python -c "import numpy; numpy.array([numpy.nan]).astype(int)"
<string>:1: RuntimeWarning: invalid value encountered in cast

# We need this cast for unsigned ints as well as floats
xa = xa.astype(int)
# Set the over-range indices before the under-range;
# otherwise the under-range values get converted to over-range.
xa[xa > self.N - 1] = self._i_over
Expand Down
7 changes: 7 additions & 0 deletions lib/matplotlib/tests/test_colors.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,13 @@ def test_create_lookup_table(N, result):
assert_array_almost_equal(mcolors._create_lookup_table(N, data), result)


@pytest.mark.parametrize("dtype", [np.uint8, int, np.float16, float])
def test_index_dtype(dtype):
# We use subtraction in the indexing, so need to verify that uint8 works
cm = mpl.colormaps["viridis"]
assert_array_equal(cm(dtype(0)), cm(0))


def test_resampled():
"""
GitHub issue #6025 pointed to incorrect ListedColormap.resampled;
Expand Down