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

Skip to content

Commit 29147f2

Browse files
committed
Simplify handling of out-of-bound values Colormap.__call__.
Mostly, we don't need to manually handle/clip out of bounds float values if we compute the masks early enough (note that these masks are always computed at some point anyways, so there's no cost of doing that a bit earlier).
1 parent 99d39bd commit 29147f2

File tree

1 file changed

+7
-12
lines changed

1 file changed

+7
-12
lines changed

lib/matplotlib/colors.py

Lines changed: 7 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -708,28 +708,23 @@ def __call__(self, X, alpha=None, bytes=False):
708708

709709
# Take the bad mask from a masked array, or in all other cases defer
710710
# np.isnan() to after we have converted to an array.
711-
mask_bad = X.mask if np.ma.is_masked(X) else None
712711
xa = np.array(X, copy=True)
713-
if mask_bad is None:
714-
mask_bad = np.isnan(xa)
715712
if not xa.dtype.isnative:
716713
xa = xa.byteswap().newbyteorder() # Native byteorder is faster.
717714
if xa.dtype.kind == "f":
718715
xa *= self.N
719-
# Negative values are out of range, but astype(int) would
720-
# truncate them towards zero.
721-
xa[xa < 0] = -1
722716
# xa == 1 (== N after multiplication) is not out of range.
723717
xa[xa == self.N] = self.N - 1
724-
# Avoid converting large positive values to negative integers.
725-
np.clip(xa, -1, self.N, out=xa)
718+
# Pre-compute the masks before casting to int (which can truncate
719+
# negative values to zero or wrap large floats to negative ints).
720+
mask_under = xa < 0
721+
mask_over = xa > self.N - 1
722+
mask_bad = X.mask if np.ma.is_masked(X) else np.isnan(xa)
726723
with np.errstate(invalid="ignore"):
727724
# We need this cast for unsigned ints as well as floats
728725
xa = xa.astype(int)
729-
# Set the over-range indices before the under-range;
730-
# otherwise the under-range values get converted to over-range.
731-
xa[xa > self.N - 1] = self._i_over
732-
xa[xa < 0] = self._i_under
726+
xa[mask_under] = self._i_under
727+
xa[mask_over] = self._i_over
733728
xa[mask_bad] = self._i_bad
734729

735730
lut = self._lut

0 commit comments

Comments
 (0)