Source code for composeui.core.colorscale

"""Color scales: a value's color between a low and a high, e.g. for a table's column."""

from __future__ import annotations

import decimal
import math
import numbers
import re
from typing import TYPE_CHECKING, Any, Optional

import attrs

if TYPE_CHECKING:
    from collections.abc import Iterable, Sequence

__all__ = ["ColorScale"]

_COLOR = re.compile(r"#[0-9a-fA-F]{6}")

#: matplotlib's viridis at 17 even stops: lighter as the value grows, also in grayscale and
#: with color blindness
_VIRIDIS = (
    "#440154", "#48186a", "#472d7b", "#424086", "#3b528b", "#33638d", "#2c728e", "#26828e",
    "#21918c", "#1fa088", "#28ae80", "#3fbc73", "#5ec962", "#84d44b", "#addc30", "#d8e219",
    "#fde725",
)  # fmt: skip
#: Kenneth Moreland's "Cool to Warm", ParaView's default, at 17 even stops: blue, gray at the
#: middle, red
_COOL_TO_WARM = (
    "#3b4cc0", "#4e68d8", "#6282ea", "#779af7", "#8db0fe", "#a3c2fe", "#b9d0f9", "#ccd9ed",
    "#dddcdc", "#ecd3c5", "#f5c4ac", "#f7b093", "#f4987a", "#eb7d62", "#dd5f4b", "#ca3b37",
    "#b40426",
)  # fmt: skip
#: the steps of the ticks, times a power of ten: each tick's text then has few digits
_TICK_STEPS = (1, 2, 5, 10)


def _to_colors(colors: Iterable[str]) -> tuple[str, ...]:
    return tuple(color.lower() for color in colors)


def _is_number(value: Any) -> bool:
    """Tell whether `value` takes a color: a real number or a `Decimal`, not a bool, not NaN."""
    if isinstance(value, bool) or not isinstance(value, (numbers.Real, decimal.Decimal)):
        return False
    return not math.isnan(value)


[docs] @attrs.frozen class ColorScale: """A scale of colors: the color of a value between `low` and `high`, e.g. a cell's. `colors` are the stops, evenly spaced from `low`'s color to `high`'s, as ``#rrggbb``; a value between two stops takes a color between theirs. A value below `low` takes `low`'s color, and a value above `high` takes `high`'s. None, NaN and text take none. Without `low` or `high`, the scale needs a range from elsewhere: a table gives it its column's, and `color` takes one. With `middle`, the first half of the stops covers `low` to `middle`, and the second half `middle` to `high`, e.g. a diverging scale's neutral color on zero. `sequential` and `diverging` build the usual scales. The colors are data: the same in every theme. """ def _check_colors(self, _attribute: attrs.Attribute[Any], colors: tuple[str, ...]) -> None: if len(colors) < 2: # noqa: PLR2004 (a color at each end) msg = f"Cannot build a ColorScale of {len(colors)} color: give 2 at least." raise ValueError(msg) for color in colors: if _COLOR.fullmatch(color) is None: msg = f"Cannot build a ColorScale with the color {color!r}: give it as #rrggbb." raise ValueError(msg) def _check_range(self, attribute: attrs.Attribute[Any], value: Optional[float]) -> None: if value is not None and not math.isfinite(value): msg = f"Cannot build a ColorScale with {attribute.name} {value}: give a finite one." raise ValueError(msg) #: the stops' colors, as #rrggbb, from `low`'s to `high`'s colors: tuple[str, ...] = attrs.field(converter=_to_colors, validator=_check_colors) #: the value of the first color; None: the lowest value colored low: Optional[float] = attrs.field(default=None, validator=_check_range) #: the value of the last color; None: the highest value colored high: Optional[float] = attrs.field(default=None, validator=_check_range) #: the value of the color halfway, e.g. 0; None: halfway between `low` and `high` middle: Optional[float] = attrs.field(default=None, validator=_check_range) def __attrs_post_init__(self) -> None: if self.low is not None and self.high is not None and self.low >= self.high: msg = f"Cannot build a ColorScale from {self.low} to {self.high}: low < high." raise ValueError(msg) if ( self.middle is not None and self.low is not None and self.high is not None and not self.low <= self.middle <= self.high ): msg = ( f"Cannot build a ColorScale with the middle {self.middle} outside " f"{self.low} to {self.high}." ) raise ValueError(msg)
[docs] @classmethod def sequential(cls, *, low: Optional[float] = None, high: Optional[float] = None) -> ColorScale: """Build viridis: dark blue for low values, to yellow for high ones.""" return cls(_VIRIDIS, low=low, high=high)
[docs] @classmethod def diverging( cls, *, middle: Optional[float] = 0.0, low: Optional[float] = None, high: Optional[float] = None, ) -> ColorScale: """Build ParaView's "Cool to Warm": blue below `middle`, gray on it, red above it.""" return cls(_COOL_TO_WARM, low=low, high=high, middle=middle)
[docs] def range( self, low: Optional[float] = None, high: Optional[float] = None ) -> tuple[float, float]: """Get the scale's `low` and `high`, each taken from the arguments when it has none. Raise `ValueError` when neither gives it, or for a low above the high. """ low = low if self.low is None else self.low high = high if self.high is None else self.high if low is None or high is None: msg = "Cannot color a value without a range: give the ColorScale a low and a high." raise ValueError(msg) if low > high: msg = f"Cannot color a value from {low} to {high}: low <= high." raise ValueError(msg) return low, high
[docs] def position( self, value: float, *, low: Optional[float] = None, high: Optional[float] = None ) -> float: """Get where `value` falls on the scale, from 0 (`low`) to 1 (`high`), clamped. `low` and `high` are the range of a scale without its own (see `range`). Values all equal (`low` == `high`) fall in the middle. """ low, high = self.range(low, high) return _position(value, low, high, self.middle)
[docs] def color( self, value: Any, *, low: Optional[float] = None, high: Optional[float] = None ) -> Optional[str]: """Get the color of `value`, as #rrggbb; None for None, NaN or text. `low` and `high` are the range of a scale without its own (see `range`). """ if not _is_number(value): return None return _color(self.colors, self.position(float(value), low=low, high=high))
[docs] def colors_of( self, values: Iterable[Any], *, low: Optional[float] = None, high: Optional[float] = None ) -> list[Optional[str]]: """Get the color of each value, as `color` does: with NumPy for an array of numbers.""" low, high = self.range(low, high) array = _number_array(values) if array is None: return [self.color(value, low=low, high=high) for value in values] return _array_colors(self.colors, array, low, high, self.middle)
[docs] def table(self, count: int) -> list[str]: """Get `count` colors evenly spaced from the first to the last, e.g. for a lookup table.""" if count < 2: # noqa: PLR2004 (a color at each end) msg = f"Cannot make a table of {count} color: ask for 2 at least." raise ValueError(msg) return [_color(self.colors, index / (count - 1)) for index in range(count)]
[docs] @staticmethod def ticks(low: float, high: float, count: int = 5) -> list[float]: """Get about `count` round values from `low` to `high`, e.g. for a legend's ticks. They are a step apart, a step of 1, 2 or 5 times a power of ten. """ if not (math.isfinite(low) and math.isfinite(high)) or low > high: msg = f"Cannot place ticks from {low} to {high}." raise ValueError(msg) if low == high: return [low] # halves: the width of finite ends can be past the largest float rough = (high / 2 - low / 2) / max(count, 1) * 2 if rough == 0: # ends a few subnormals apart return [low, high] power = 10.0 ** math.floor(math.log10(rough)) def span(step: float) -> tuple[int, int]: return math.ceil(low / step - 1e-9), math.floor(high / step + 1e-9) # the step giving the count closest to `count`, the larger one between two as close step = min( (step * power for step in reversed(_TICK_STEPS)), key=lambda step: abs(span(step)[1] - span(step)[0] + 1 - count), ) digits = max(0, -math.floor(math.log10(step))) first, last = span(step) return [round(index * step, digits) + 0.0 for index in range(first, last + 1)]
def _position(value: float, low: float, high: float, middle: Optional[float]) -> float: """Get where `value` falls from `low` (0) to `high` (1), `middle` at 0.5 when given. A value past an end is taken at that end. The differences are of halves: the width of finite ends can be past the largest float. """ value = min(max(value, low), high) if middle is None: return 0.5 if high <= low else (value / 2 - low / 2) / (high / 2 - low / 2) if value < middle: # so low < middle return 0.5 * (value / 2 - low / 2) / (middle / 2 - low / 2) if value > middle: # so middle < high return 0.5 + 0.5 * (value / 2 - middle / 2) / (high / 2 - middle / 2) return 0.5 def _rgb(color: str) -> tuple[int, int, int]: return int(color[1:3], 16), int(color[3:5], 16), int(color[5:7], 16) def _color(colors: Sequence[str], position: float) -> str: """Get the color at `position`, from 0 to 1, between the two stops around it.""" scaled = position * (len(colors) - 1) index = min(int(scaled), len(colors) - 2) fraction = scaled - index start, stop = _rgb(colors[index]), _rgb(colors[index + 1]) red, green, blue = (round(a + (b - a) * fraction) for a, b in zip(start, stop)) return f"#{red:02x}{green:02x}{blue:02x}" def _number_array(values: Iterable[Any]) -> Any: """Get `values` as a NumPy array of numbers, or None: not an array of numbers, no NumPy.""" try: import numpy as np # noqa: PLC0415 (optional: the scale needs no NumPy) except ImportError: # pragma: no cover (NumPy is in every test environment) return None if not isinstance(values, np.ndarray) or values.dtype.kind not in "iuf": return None return values.astype(float) def _array_colors( colors: Sequence[str], values: Any, low: float, high: float, middle: Optional[float] ) -> list[Optional[str]]: """Get the colors of an array of numbers as `_color` and `_position` do, value by value.""" import numpy as np # noqa: PLC0415 (optional: the scale needs no NumPy) values = np.clip(values, low, high) with np.errstate(divide="ignore", invalid="ignore"): # in the branches not taken if middle is None: positions = ( np.full(values.shape, 0.5) if high <= low else (values / 2 - low / 2) / (high / 2 - low / 2) ) else: below = 0.5 * (values / 2 - low / 2) / (middle / 2 - low / 2) above = 0.5 + 0.5 * (values / 2 - middle / 2) / (high / 2 - middle / 2) positions = np.where(values < middle, below, np.where(values > middle, above, 0.5)) scaled = positions * (len(colors) - 1) index = np.minimum(np.floor(np.nan_to_num(scaled)).astype(int), len(colors) - 2) fraction = scaled - index stops = np.array([_rgb(color) for color in colors], dtype=float) start, stop = stops[index], stops[index + 1] rgb = np.rint(start + (stop - start) * fraction[..., None]) is_number = ~np.isnan(values) return [ f"#{int(red):02x}{int(green):02x}{int(blue):02x}" if keep else None for (red, green, blue), keep in zip(rgb.tolist(), is_number.tolist()) ]