"""Heatmap of image players over their picture.
@domain viz
@see [[knowledge/architecture/viz]]
@tested-by [[tests/viz/test_image.py]]
"""
from collections.abc import Sequence
from typing import TYPE_CHECKING, Any, cast
from ..domain.conversation import ImagePart
from ..domain.players import PlayerSpan
from ..masking.image import decode_image
from .colors import SHAP_BLUE_RGB, SHAP_RED_RGB
from .style import _import_pyplot, apply_attribution_theme
if TYPE_CHECKING:
from matplotlib.figure import Figure
_MAX_ALPHA = 0.6 # value fills stay translucent so the picture shows through
_MAX_LABELS = 12 # finer grids would bury the picture under cell names
[docs]
def plot_image_players(
image: ImagePart, spans: Sequence[PlayerSpan], values: Sequence[float]
) -> "Figure":
"""Draw ``image`` with each player's ``region`` shaded by its signed value.
Raises:
ValueError: If ``spans`` and ``values`` differ in length.
"""
if len(spans) != len(values):
msg = "spans and values must have the same length"
raise ValueError(msg)
apply_attribution_theme()
pyplot = _import_pyplot()
pixels = decode_image(image.data())
height, width = pixels.shape[:2]
figure, axis = pyplot.subplots(figsize=(6.0, 6.0 * height / max(width, 1)))
vmax = max((abs(v) for v in values), default=0.0)
draw_image_players(axis, image, list(zip(spans, values, strict=True)), vmax)
figure.tight_layout()
return cast("Figure", figure)
[docs]
def draw_image_players(
axis: Any, image: ImagePart, players: list[tuple[PlayerSpan, float]], vmax: float
) -> None:
"""Show ``image`` on ``axis`` and shade every region on the ``vmax`` scale.
Opacity grows with ``|value| / vmax``, so a player near zero leaves its pixels
as they are; cell names are drawn only for up to ``_MAX_LABELS`` players.
"""
rectangle = _import_pyplot().Rectangle
axis.imshow(decode_image(image.data()))
labelled = len(players) <= _MAX_LABELS
for span, value in players:
strength = min(1.0, abs(value) / vmax) if vmax > 0 else 0.0
fill = (*(SHAP_RED_RGB if value >= 0 else SHAP_BLUE_RGB), _MAX_ALPHA * strength)
for left, top, right, bottom in span.region or ():
axis.add_patch(
rectangle(
(left, top),
right - left,
bottom - top,
facecolor=fill,
edgecolor=(1.0, 1.0, 1.0, 0.5),
linewidth=0.4,
label="player",
)
)
if labelled and span.region:
left, top, right, bottom = span.region[0]
axis.text(
(left + right) / 2,
(top + bottom) / 2,
span.display_label,
ha="center",
va="center",
fontsize=8,
)
axis.set_xticks([])
axis.set_yticks([])