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

Skip to content

Creation of the Norm Protocol #30149

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
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
2 changes: 1 addition & 1 deletion lib/matplotlib/colorizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ def norm(self):

@norm.setter
def norm(self, norm):
_api.check_isinstance((colors.Normalize, str, None), norm=norm)
_api.check_isinstance((colors.Norm, str, None), norm=norm)
if norm is None:
norm = colors.Normalize()
elif isinstance(norm, str):
Expand Down
14 changes: 7 additions & 7 deletions lib/matplotlib/colorizer.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,12 @@ class Colorizer:
def __init__(
self,
cmap: str | colors.Colormap | None = ...,
norm: str | colors.Normalize | None = ...,
norm: str | colors.Norm | None = ...,
) -> None: ...
@property
def norm(self) -> colors.Normalize: ...
def norm(self) -> colors.Norm: ...
@norm.setter
def norm(self, norm: colors.Normalize | str | None) -> None: ...
def norm(self, norm: colors.Norm | str | None) -> None: ...
def to_rgba(
self,
x: np.ndarray,
Expand Down Expand Up @@ -63,18 +63,18 @@ class _ColorizerInterface:
def get_cmap(self) -> colors.Colormap: ...
def set_cmap(self, cmap: str | colors.Colormap) -> None: ...
@property
def norm(self) -> colors.Normalize: ...
def norm(self) -> colors.Norm: ...
@norm.setter
def norm(self, norm: colors.Normalize | str | None) -> None: ...
def set_norm(self, norm: colors.Normalize | str | None) -> None: ...
def norm(self, norm: colors.Norm | str | None) -> None: ...
def set_norm(self, norm: colors.Norm | str | None) -> None: ...
def autoscale(self) -> None: ...
def autoscale_None(self) -> None: ...


class _ScalarMappable(_ColorizerInterface):
def __init__(
self,
norm: colors.Normalize | None = ...,
norm: colors.Norm | None = ...,
cmap: str | colors.Colormap | None = ...,
*,
colorizer: Colorizer | None = ...,
Expand Down
81 changes: 81 additions & 0 deletions lib/matplotlib/colors.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@

import base64
from collections.abc import Sequence, Mapping
from typing import Protocol, runtime_checkable
import functools
import importlib
import inspect
Expand Down Expand Up @@ -2257,6 +2258,86 @@
self._isinit = True


@runtime_checkable
class Norm(Protocol):

callbacks: cbook.CallbackRegistry

@property
def vmin(self):
"""Lower limit of the input data interval; maps to 0."""
...

Check warning on line 2269 in lib/matplotlib/colors.py

View check run for this annotation

Codecov / codecov/patch

lib/matplotlib/colors.py#L2269

Added line #L2269 was not covered by tests


@property
def vmax(self):
"""Upper limit of the input data interval; maps to 1."""
...

Check warning on line 2275 in lib/matplotlib/colors.py

View check run for this annotation

Codecov / codecov/patch

lib/matplotlib/colors.py#L2275

Added line #L2275 was not covered by tests

@property
def clip(self):
"""
Determines the behavior for mapping values outside the range ``[vmin, vmax]``.

See the *clip* parameter in `.Normalize`.
"""
...

Check warning on line 2284 in lib/matplotlib/colors.py

View check run for this annotation

Codecov / codecov/patch

lib/matplotlib/colors.py#L2284

Added line #L2284 was not covered by tests

def _changed(self):
"""
Call this whenever the norm is changed to notify all the
callback listeners to the 'changed' signal.
"""
...

Check warning on line 2291 in lib/matplotlib/colors.py

View check run for this annotation

Codecov / codecov/patch

lib/matplotlib/colors.py#L2291

Added line #L2291 was not covered by tests


def __call__(self, value, clip=None):
"""
Normalize the data and return the normalized data.

Parameters
----------
value
Data to normalize.
clip : bool, optional
See the description of the parameter *clip* in `.Normalize`.

If ``None``, defaults to ``self.clip`` (which defaults to
``False``).

Notes
-----
If not already initialized, ``self.vmin`` and ``self.vmax`` are
initialized using ``self.autoscale_None(value)``.
"""
...

Check warning on line 2313 in lib/matplotlib/colors.py

View check run for this annotation

Codecov / codecov/patch

lib/matplotlib/colors.py#L2313

Added line #L2313 was not covered by tests

def inverse(self, value):
"""
Maps the normalized value (i.e., index in the colormap) back to image
data value.

Parameters
----------
value
Normalized value.
"""
...

Check warning on line 2325 in lib/matplotlib/colors.py

View check run for this annotation

Codecov / codecov/patch

lib/matplotlib/colors.py#L2325

Added line #L2325 was not covered by tests


def autoscale(self, A):
"""Set *vmin*, *vmax* to min, max of *A*."""
...

Check warning on line 2330 in lib/matplotlib/colors.py

View check run for this annotation

Codecov / codecov/patch

lib/matplotlib/colors.py#L2330

Added line #L2330 was not covered by tests

def autoscale_None(self, A):
"""If *vmin* or *vmax* are not set, use the min/max of *A* to set them."""
...

Check warning on line 2334 in lib/matplotlib/colors.py

View check run for this annotation

Codecov / codecov/patch

lib/matplotlib/colors.py#L2334

Added line #L2334 was not covered by tests

def scaled(self):
"""Return whether *vmin* and *vmax* are both set."""
...

Check warning on line 2338 in lib/matplotlib/colors.py

View check run for this annotation

Codecov / codecov/patch

lib/matplotlib/colors.py#L2338

Added line #L2338 was not covered by tests


class Normalize:
"""
A class which, when called, maps values within the interval
Expand Down
27 changes: 26 additions & 1 deletion lib/matplotlib/colors.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence
from matplotlib import cbook, scale
import re

from typing import Any, Literal, overload
from typing import Any, Literal, overload, Protocol, runtime_checkable
from .typing import ColorType

import numpy as np
Expand Down Expand Up @@ -249,6 +249,31 @@ class BivarColormapFromImage(BivarColormap):
origin: Sequence[float] = ..., name: str = ...
) -> None: ...

@runtime_checkable
class Norm(Protocol):
callbacks: cbook.CallbackRegistry
@property
def vmin(self) -> float | tuple[float] | None: ...
@property
def vmax(self) -> float | tuple[float] | None: ...
@property
def clip(self) -> bool | tuple[bool]: ...
@overload
def __call__(self, value: float, clip: bool | None = ...) -> float: ...
@overload
def __call__(self, value: np.ndarray, clip: bool | None = ...) -> np.ma.MaskedArray: ...
@overload
def __call__(self, value: ArrayLike, clip: bool | None | list = ...) -> ArrayLike: ...
@overload
def inverse(self, value: float) -> float: ...
@overload
def inverse(self, value: np.ndarray) -> np.ma.MaskedArray: ...
@overload
def inverse(self, value: ArrayLike) -> ArrayLike: ...
def autoscale(self, A: ArrayLike) -> None: ...
def autoscale_None(self, A: ArrayLike) -> None: ...
def scaled(self) -> bool: ...

class Normalize:
callbacks: cbook.CallbackRegistry
def __init__(
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
52 changes: 51 additions & 1 deletion lib/matplotlib/tests/test_colors.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from PIL import Image
import pytest
import base64
import platform

from numpy.testing import assert_array_equal, assert_array_almost_equal

Expand All @@ -19,7 +20,7 @@
import matplotlib.pyplot as plt
import matplotlib.scale as mscale
from matplotlib.rcsetup import cycler
from matplotlib.testing.decorators import image_comparison, check_figures_equal
from matplotlib.testing.decorators import (image_comparison, check_figures_equal)
from matplotlib.colors import is_color_like, to_rgba_array, ListedColormap


Expand Down Expand Up @@ -1829,3 +1830,52 @@
cmap([value for value, _ in value_color_tuples]),
to_rgba_array([color for _, color in value_color_tuples]),
)


@image_comparison(['test_norm_protocol.png'], remove_text=True,
tol=0 if platform.machine() == 'x86_64' else 0.05)
def test_norm_protocol():
class CustomHalfNorm:
def __init__(self):
self.callbacks = mpl.cbook.CallbackRegistry(signals=["changed"])

@property
def vmin(self):
return 0

@property
def vmax(self):
return 1

@property
def clip(self):
return False

def _changed(self):
self.callbacks.process('changed')

def __call__(self, value, clip=None):
return value/2

def inverse(self, value):
return value

Check warning on line 1861 in lib/matplotlib/tests/test_colors.py

View check run for this annotation

Codecov / codecov/patch

lib/matplotlib/tests/test_colors.py#L1861

Added line #L1861 was not covered by tests


def autoscale(self, A):
pass

Check warning on line 1865 in lib/matplotlib/tests/test_colors.py

View check run for this annotation

Codecov / codecov/patch

lib/matplotlib/tests/test_colors.py#L1865

Added line #L1865 was not covered by tests

def autoscale_None(self, A):
pass

def scaled(self):
return True

fig, axes = plt.subplots(2,2)

r = np.linspace(-1, 3, 16*16).reshape((16,16))
norm = CustomHalfNorm()
colorizer = mpl.colorizer.Colorizer(cmap='viridis', norm=norm)
c = axes[0,0].imshow(r, colorizer=colorizer)
axes[0,1].pcolor(r, colorizer=colorizer)
axes[1,0].contour(r, colorizer=colorizer)
axes[1,1].contourf(r, colorizer=colorizer)
Loading