Skip to content

Commit

Permalink
Merge pull request #6837 from anntzer/fix-integer-normalization
Browse files Browse the repository at this point in the history
FIX: Normalize(<signed integer array>).

closes #6825
  • Loading branch information
tacaswell committed Aug 1, 2016
1 parent 875e539 commit 7e938fa
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 4 deletions.
12 changes: 8 additions & 4 deletions lib/matplotlib/colors.py
Expand Up @@ -811,8 +811,9 @@ def process_value(value):
if is_scalar:
value = [value]
dtype = np.min_scalar_type(value)
dtype = (np.float32 if dtype.itemsize <= 2
else np.promote_types(dtype, float))
if np.issubdtype(dtype, np.integer) or dtype.type is np.bool_:
# bool_/int8/int16 -> float32; int32/int64 -> float64
dtype = np.promote_types(dtype, np.float32)
result = np.ma.array(value, dtype=dtype, copy=True)
return result, is_scalar

Expand All @@ -830,7 +831,9 @@ def __call__(self, value, clip=None):
result, is_scalar = self.process_value(value)

self.autoscale_None(result)
vmin, vmax = self.vmin, self.vmax
# Convert at least to float, without losing precision.
(vmin,), _ = self.process_value(self.vmin)
(vmax,), _ = self.process_value(self.vmax)
if vmin == vmax:
result.fill(0) # Or should it be all masked? Or 0.5?
elif vmin > vmax:
Expand All @@ -854,7 +857,8 @@ def __call__(self, value, clip=None):
def inverse(self, value):
if not self.scaled():
raise ValueError("Not invertible until scaled")
vmin, vmax = self.vmin, self.vmax
(vmin,), _ = self.process_value(self.vmin)
(vmax,), _ = self.process_value(self.vmax)

if cbook.iterable(value):
val = ma.asarray(value)
Expand Down
6 changes: 6 additions & 0 deletions lib/matplotlib/tests/test_colors.py
Expand Up @@ -193,6 +193,12 @@ def test_Normalize():
_scalar_tester(norm, vals)
_mask_tester(norm, vals)

# Handle integer input correctly (don't overflow when computing max-min,
# i.e. 127-(-128) here).
vals = np.array([-128, 127], dtype=np.int8)
norm = mcolors.Normalize(vals.min(), vals.max())
assert_array_equal(np.asarray(norm(vals)), [0, 1])

# Don't lose precision on longdoubles (float128 on Linux):
# for array inputs...
vals = np.array([1.2345678901, 9.8765432109], dtype=np.longdouble)
Expand Down

0 comments on commit 7e938fa

Please sign in to comment.