Skip to content

Value Mapping

Value mappings turn data values into visual properties, such as colors, line widths or opacities. Discrete mappings map single values; continuous mappings map number ranges; a rule-based mapping calls a function. Import is_missing, the discrete and the continuous mapping classes from mesqual.visualizations.value_mapping_system. These classes stay in their modules: BaseMapping in mesqual.visualizations.value_mapping_system.base, SegmentedContinuousInputMappingBase in mesqual.visualizations.value_mapping_system.continuous, RuleBasedMapping in mesqual.visualizations.value_mapping_system.rule.

base

BaseMapping

Bases: ABC

Base class of the value mappings: a call maps one input value to one output.

Source code in src/mesqual/visualizations/value_mapping_system/base.py
23
24
25
26
27
28
class BaseMapping(ABC):
    """Base class of the value mappings: a call maps one input value to one output."""

    @abstractmethod
    def __call__(self, value: Any) -> Any:
        """Return the output for `value`."""

__call__ abstractmethod

__call__(value: Any) -> Any

Return the output for value.

Source code in src/mesqual/visualizations/value_mapping_system/base.py
26
27
28
@abstractmethod
def __call__(self, value: Any) -> Any:
    """Return the output for `value`."""

is_missing

is_missing(value: Any) -> bool

Return True if value is a missing value.

Missing values are the scalars that pandas counts as missing: None, NaN, pd.NA, pd.NaT and np.datetime64("NaT", "ns"). A list, tuple or array is not a missing value, also when it holds missing values.

Parameters:

Name Type Description Default
value Any

Value to check.

required

Returns:

Type Description
bool

True if value is a missing scalar.

Source code in src/mesqual/visualizations/value_mapping_system/base.py
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
def is_missing(value: Any) -> bool:
    """Return True if `value` is a missing value.

    Missing values are the scalars that pandas counts as missing: `None`,
    `NaN`, `pd.NA`, `pd.NaT` and `np.datetime64("NaT", "ns")`. A list, tuple or array
    is not a missing value, also when it holds missing values.

    Args:
        value: Value to check.

    Returns:
        True if `value` is a missing scalar.
    """
    return pd.api.types.is_scalar(value) and bool(pd.isna(value))

discrete

DiscreteInputMapping

Bases: BaseMapping

Maps discrete input values to outputs, such as colors or line widths.

A call returns the output for one value:

  1. A missing value (None, NaN, pd.NA, pd.NaT; see is_missing) gets default_output.
  2. A value in mapping gets its output.
  3. Another value gets the next palette output, if a palette is given. The mapping stores this assignment, so the value keeps its output for the life of the mapping object.
  4. Without a palette, another value gets default_output.

A missing value gets default_output only when the mapping is called with it; Series.map(mapping, na_action="ignore"), for example, does not call it.

The palette leaves out the outputs of the fixed entries, so an assigned output does not repeat a fixed one; if that leaves no outputs, the palette uses all given outputs. The palette starts again from its first output when it runs out.

Parameters:

Name Type Description Default
mapping Mapping[Any, Any] | None

Fixed output per input value. The mapping copies it and does not change it.

None
palette Iterable[Any] | None

Outputs for values without a fixed output, in assignment order. None or no outputs: these values get default_output.

None
default_output Any

Output for missing values and for values without an output when there is no palette.

None

Raises:

Type Description
ValueError

If a key of mapping is a missing value. Use default_output for missing values.

Source code in src/mesqual/visualizations/value_mapping_system/discrete.py
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
class DiscreteInputMapping(BaseMapping):
    """Maps discrete input values to outputs, such as colors or line widths.

    A call returns the output for one value:

    1. A missing value (`None`, `NaN`, `pd.NA`, `pd.NaT`; see `is_missing`) gets
       `default_output`.
    2. A value in `mapping` gets its output.
    3. Another value gets the next palette output, if a palette is given. The
       mapping stores this assignment, so the value keeps its output for the life
       of the mapping object.
    4. Without a palette, another value gets `default_output`.

    A missing value gets `default_output` only when the mapping is called with it;
    `Series.map(mapping, na_action="ignore")`, for example, does not call it.

    The palette leaves out the outputs of the fixed entries, so an assigned output
    does not repeat a fixed one; if that leaves no outputs, the palette uses all
    given outputs. The palette starts again from its first output when it runs out.

    Args:
        mapping: Fixed output per input value. The mapping copies it and does
            not change it.
        palette: Outputs for values without a fixed output, in assignment order.
            `None` or no outputs: these values get `default_output`.
        default_output: Output for missing values and for values without an
            output when there is no palette.

    Raises:
        ValueError: If a key of `mapping` is a missing value. Use
            `default_output` for missing values.
    """

    def __init__(
        self,
        mapping: Mapping[Any, Any] | None = None,
        palette: Iterable[Any] | None = None,
        default_output: Any = None,
    ):
        self._mapping = {} if mapping is None else dict(mapping)
        self._check_no_missing_keys()
        self._palette = self._working_palette(palette, list(self._mapping.values()))
        self._default_output = default_output
        self._n_assigned = 0
        self._default_used = False

    @property
    def mapping(self) -> dict:
        """Output per input value: the fixed entries first, also the ones never
        mapped, then the palette assignments in the order of first use."""
        return self._mapping

    @property
    def default_output(self) -> Any:
        """Output for missing values and for values without an output."""
        return self._default_output

    @property
    def default_used(self) -> bool:
        """True once a call fell back to `default_output`: a missing value, or a
        value without an output when there is no palette."""
        return self._default_used

    def __call__(self, value: Any) -> Any:
        if is_missing(value):
            return self._use_default()
        if value in self._mapping:
            return self._mapping[value]
        if self._palette:
            return self._assign(value)
        return self._use_default()

    def _check_no_missing_keys(self) -> None:
        missing = [key for key in self._mapping if is_missing(key)]
        if missing:
            raise ValueError(
                f'Mapping keys {missing} are missing values and are never looked up. '
                'Use default_output for missing values.'
            )

    @staticmethod
    def _working_palette(palette: Iterable[Any] | None, fixed_outputs: list) -> list:
        given = [] if palette is None else list(palette)
        free = [output for output in given if output not in fixed_outputs]
        return free or given

    def _use_default(self) -> Any:
        self._default_used = True
        return self._default_output

    def _assign(self, value: Any) -> Any:
        output = self._palette[self._n_assigned % len(self._palette)]
        self._n_assigned += 1
        self._mapping[value] = output
        return output

mapping property

mapping: dict

Output per input value: the fixed entries first, also the ones never mapped, then the palette assignments in the order of first use.

default_output property

default_output: Any

Output for missing values and for values without an output.

default_used property

default_used: bool

True once a call fell back to default_output: a missing value, or a value without an output when there is no palette.

DiscreteColorMapping

Bases: DiscreteInputMapping

Maps discrete input values to CSS colors.

Examples:

Fixed colors for two fuels, palette colors for the others. The mapping keeps its assignments, so one mapping gives the same colors in many frames, and a legend shows all colors that the frames used:

>>> import folium
>>> from mesqual.visualizations.folium_viz_system.legends import DiscreteColorLegend
>>> colors = DiscreteColorMapping(
...     mapping={'solar': '#ffcc00', 'wind': '#3399ff'},
...     palette=['#1f77b4', '#ff7f0e', '#2ca02c'],
...     default_output='#cccccc',
... )
>>> pd.Series(['solar', 'gas', None]).map(colors).tolist()
['#ffcc00', '#1f77b4', '#cccccc']
>>> pd.Series(['coal', 'gas']).map(colors).tolist()
['#ff7f0e', '#1f77b4']
>>> list(colors.mapping)
['solar', 'wind', 'gas', 'coal']
>>> legend = DiscreteColorLegend(colors, title='Fuel').add_to(folium.Map())
Source code in src/mesqual/visualizations/value_mapping_system/discrete.py
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
class DiscreteColorMapping(DiscreteInputMapping):
    """Maps discrete input values to CSS colors.

    Examples:
        Fixed colors for two fuels, palette colors for the others. The mapping keeps
        its assignments, so one mapping gives the same colors in many frames, and a
        legend shows all colors that the frames used:

        >>> import folium
        >>> from mesqual.visualizations.folium_viz_system.legends import DiscreteColorLegend
        >>> colors = DiscreteColorMapping(
        ...     mapping={'solar': '#ffcc00', 'wind': '#3399ff'},
        ...     palette=['#1f77b4', '#ff7f0e', '#2ca02c'],
        ...     default_output='#cccccc',
        ... )
        >>> pd.Series(['solar', 'gas', None]).map(colors).tolist()
        ['#ffcc00', '#1f77b4', '#cccccc']
        >>> pd.Series(['coal', 'gas']).map(colors).tolist()
        ['#ff7f0e', '#1f77b4']
        >>> list(colors.mapping)
        ['solar', 'wind', 'gas', 'coal']
        >>> legend = DiscreteColorLegend(colors, title='Fuel').add_to(folium.Map())
    """

DiscreteLineDashPatternMapping

Bases: DiscreteInputMapping

Maps discrete input values to SVG dash patterns, such as "5,5".

Source code in src/mesqual/visualizations/value_mapping_system/discrete.py
129
130
class DiscreteLineDashPatternMapping(DiscreteInputMapping):
    """Maps discrete input values to SVG dash patterns, such as `"5,5"`."""

DiscreteLineWidthMapping

Bases: DiscreteInputMapping

Maps discrete input values to line widths in px.

Source code in src/mesqual/visualizations/value_mapping_system/discrete.py
133
134
class DiscreteLineWidthMapping(DiscreteInputMapping):
    """Maps discrete input values to line widths in px."""

DiscreteIconMapping

Bases: DiscreteInputMapping

Maps discrete input values to icons.

Source code in src/mesqual/visualizations/value_mapping_system/discrete.py
137
138
class DiscreteIconMapping(DiscreteInputMapping):
    """Maps discrete input values to icons."""

continuous

SegmentedContinuousInputMappingBase

Bases: BaseMapping

Base class of the segmented continuous mappings, with the call rules.

Use a subclass, such as SegmentedContinuousColorscale or SegmentedContinuousLineWidthMapping, or subclass it for a new output type. Each segment is a closed input range (start, end) with an output:

  • One output, such as 5.0 or "#ff0000": every value in the segment gets it.
  • A list of outputs: the outputs sit at equal steps from start to end, and a value between two of them gets the linear interpolation.

A call returns the output for one value:

  1. A missing value (see is_missing) gets default_output.
  2. A value that float() cannot convert gets default_output.
  3. A value below the first segment or above the last segment gets the output at that edge.
  4. A value in a gap between two segments gets default_output.
  5. A numeric output is clipped to min_output_value and max_output_value, also a numeric default_output: with default_output=0.5 and min_output_value=2, a missing value gives 2.

Parameters:

Name Type Description Default
segments dict[tuple[float | int, float | int], Any]

Output per input range (start, end). The mapping sorts the segments by range.

required
default_output Any

Output for missing values and for values without an output.

None
min_output_value float | int

Lower bound of numeric outputs. None: no bound.

None
max_output_value float | int

Upper bound of numeric outputs. None: no bound.

None

Raises:

Type Description
ValueError

If segments is empty, two segments overlap, or a segment has end <= start.

Source code in src/mesqual/visualizations/value_mapping_system/continuous.py
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
class SegmentedContinuousInputMappingBase(BaseMapping):
    """Base class of the segmented continuous mappings, with the call rules.

    Use a subclass, such as `SegmentedContinuousColorscale` or
    `SegmentedContinuousLineWidthMapping`, or subclass it for a new output type.
    Each segment is a closed input range `(start, end)` with an output:

    - One output, such as `5.0` or `"#ff0000"`: every value in the segment
      gets it.
    - A list of outputs: the outputs sit at equal steps from `start` to `end`,
      and a value between two of them gets the linear interpolation.

    A call returns the output for one value:

    1. A missing value (see `is_missing`) gets `default_output`.
    2. A value that `float()` cannot convert gets `default_output`.
    3. A value below the first segment or above the last segment gets the output
       at that edge.
    4. A value in a gap between two segments gets `default_output`.
    5. A numeric output is clipped to `min_output_value` and `max_output_value`,
       also a numeric `default_output`: with `default_output=0.5` and
       `min_output_value=2`, a missing value gives 2.

    Args:
        segments: Output per input range `(start, end)`. The mapping sorts the
            segments by range.
        default_output: Output for missing values and for values without an output.
        min_output_value: Lower bound of numeric outputs. `None`: no bound.
        max_output_value: Upper bound of numeric outputs. `None`: no bound.

    Raises:
        ValueError: If `segments` is empty, two segments overlap, or a segment
            has `end <= start`.
    """

    def __init__(
        self,
        segments: dict[tuple[float | int, float | int], Any],
        default_output: Any = None,
        min_output_value: float | int = None,
        max_output_value: float | int = None,
    ):
        self._default_output = default_output
        self._min_output_value = min_output_value
        self._max_output_value = max_output_value
        self._segments = dict(sorted(segments.items()))
        self._validate_segments()
        ranges = list(self._segments)
        self._input_value_range = (float(ranges[0][0]), float(ranges[-1][1]))

    @property
    def default_output(self) -> Any:
        """Output for missing values and for values without an output."""
        return self._default_output

    def __call__(self, value: float):
        if is_missing(value):
            result = self._default_output
        else:
            try:
                result = self._compute_output(float(value))
            except (ValueError, TypeError):
                result = self._default_output

        # in case of numeric output
        if isinstance(result, (float, int)):
            if self._min_output_value:
                result = max(result, self._min_output_value)
            if self._max_output_value:
                result = min(result, self._max_output_value)
        return result

    @staticmethod
    def _get_low_high_from_values(values, trim_percentile) -> tuple[float, float]:
        arr = np.asarray(values)
        arr = arr[~pd.isna(arr)].astype(float)
        if arr.size == 0:
            raise ValueError('Cannot autoscale: the values are empty or all missing.')
        if trim_percentile:
            # A percentile next to an infinite value is NaN; _widened_finite_range raises for it.
            with np.errstate(invalid='ignore'):
                low, high = (float(v) for v in np.percentile(arr, trim_percentile))
        else:
            low, high = float(np.min(arr)), float(np.max(arr))
        return low, high

    @staticmethod
    def _widened_finite_range(low: float, high: float) -> tuple[float, float]:
        """Return `(low, high)`, widened if it is one value. Raise `ValueError` if a bound or the width is not finite."""
        if low == high:
            half_width = abs(low) * 0.1 or 1.0
            low, high = low - half_width, high + half_width
        if not np.isfinite([low, high, high - low]).all():
            raise ValueError(
                f'Cannot autoscale: the range ({low}, {high}) or its width is not finite. '
                'An infinite or very large value in the range causes this.'
            )
        return low, high

    @property
    def segments(self) -> dict[tuple[float | int, float | int], Any]:
        """Output per input range `(start, end)`, sorted by range."""
        return self._segments

    def _validate_segments(self):
        if not self._segments:
            raise ValueError('A continuous mapping needs at least one segment.')
        prev_end = -float('inf')
        for (start, end), _ in self._segments.items():
            if start < prev_end:
                raise ValueError(f'Overlapping segments: ({start}, {end})')
            if end <= start:
                raise ValueError(f'Invalid segment: ({start}, {end})')
            prev_end = end

    def _compute_output(self, value: float):
        clipped_value = np.clip(value, self.min_input_value, self.max_input_value)
        for (start, end), output in self._segments.items():
            if start <= clipped_value <= end:
                if isinstance(output, list):  # continuous output --> interpolate
                    return self._interpolate(clipped_value, start, end, output)
                return output
        return self._default_output

    def _interpolate(self, value: float, start: float, end: float, outputs: list[float]) -> float:
        if len(outputs) == 1:
            return outputs[0]
        pos = (value - start) / (end - start)
        idx = pos * (len(outputs) - 1)
        idx_low, idx_high = int(np.floor(idx)), int(np.ceil(idx))
        if idx_low == idx_high:
            return outputs[idx_low]
        frac = idx - idx_low
        return outputs[idx_low] + frac * (outputs[idx_high] - outputs[idx_low])

    @property
    def min_input_value(self) -> float:
        """Start of the first segment."""
        return self._input_value_range[0]

    @property
    def max_input_value(self) -> float:
        """End of the last segment."""
        return self._input_value_range[1]

    @property
    def input_value_range(self) -> tuple[float, float]:
        """Start of the first segment and end of the last segment."""
        return self._input_value_range

default_output property

default_output: Any

Output for missing values and for values without an output.

segments property

segments: dict[tuple[float | int, float | int], Any]

Output per input range (start, end), sorted by range.

min_input_value property

min_input_value: float

Start of the first segment.

max_input_value property

max_input_value: float

End of the last segment.

input_value_range property

input_value_range: tuple[float, float]

Start of the first segment and end of the last segment.

SegmentedContinuousColorscale

Bases: SegmentedContinuousInputMappingBase

Maps numbers to CSS colors, segment by segment.

The output of a segment is a list of colors, one color string, or the name of a matplotlib colormap, such as "viridis". A string that is a colormap name is a colormap, also when it is a color too, such as "gray"; any other string is one color. A colormap name gives 100 colors of the colormap. A call returns a hex color, interpolated in RGBA within the segment, or default_output. The rules of a call are in SegmentedContinuousInputMappingBase.

Parameters:

Name Type Description Default
segments dict[tuple[float | int, float | int], Any]

Colors per input range (start, end). The mapping does not change the given dict.

required
default_output Any

Color for missing values and for values without a color.

None

Raises:

Type Description
ValueError

If a string is neither a colormap name nor a color, segments is empty, two segments overlap, or a segment has end <= start.

Examples:

A diverging scale for prices, gray for missing prices. A value outside all segments gets the edge color, here the last color of YlOrRd:

>>> from mesqual.visualizations.value_mapping_system import SegmentedContinuousColorscale
>>> prices = SegmentedContinuousColorscale(
...     segments={(-50, 0): ['#2166ac', '#f7f7f7'], (0, 200): 'YlOrRd'},
...     default_output='#cccccc',
... )
>>> prices(-50), prices(500), prices(None)
('#2166ac', '#800026', '#cccccc')
Source code in src/mesqual/visualizations/value_mapping_system/continuous.py
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
class SegmentedContinuousColorscale(SegmentedContinuousInputMappingBase):
    """Maps numbers to CSS colors, segment by segment.

    The output of a segment is a list of colors, one color string, or the name of
    a matplotlib colormap, such as `"viridis"`. A string that is a colormap name
    is a colormap, also when it is a color too, such as `"gray"`; any other
    string is one color. A colormap name gives 100 colors of the colormap. A call
    returns a hex color, interpolated in RGBA within the segment, or
    `default_output`. The rules of a call are in
    `SegmentedContinuousInputMappingBase`.

    Args:
        segments: Colors per input range `(start, end)`. The mapping does not
            change the given dict.
        default_output: Color for missing values and for values without a color.

    Raises:
        ValueError: If a string is neither a colormap name nor a color,
            `segments` is empty, two segments overlap, or a segment has
            `end <= start`.

    Examples:
        A diverging scale for prices, gray for missing prices. A value outside all
        segments gets the edge color, here the last color of YlOrRd:

        >>> from mesqual.visualizations.value_mapping_system import SegmentedContinuousColorscale
        >>> prices = SegmentedContinuousColorscale(
        ...     segments={(-50, 0): ['#2166ac', '#f7f7f7'], (0, 200): 'YlOrRd'},
        ...     default_output='#cccccc',
        ... )
        >>> prices(-50), prices(500), prices(None)
        ('#2166ac', '#800026', '#cccccc')
    """

    def __init__(
        self,
        segments: dict[tuple[float | int, float | int], Any],
        default_output: Any = None,
    ):

        super().__init__(
            segments=self._convert_recognized_colorscale_strings_to_list_of_colors(segments),
            default_output=default_output,
        )

    @staticmethod
    def _convert_recognized_colorscale_strings_to_list_of_colors(segments: dict) -> dict:
        return {
            key: SegmentedContinuousColorscale._string_to_colors(val) if isinstance(val, str) else val
            for key, val in segments.items()
        }

    @staticmethod
    def _string_to_colors(name: str) -> list[str]:
        if name in matplotlib.colormaps:
            cmap = matplotlib.colormaps[name]
            return [colors.to_hex(cmap(i)) for i in np.linspace(0, 1, 100)]
        if colors.is_color_like(name):
            return [name]
        raise ValueError(f"'{name}' is neither a valid colormap nor a valid color string.")

    @classmethod
    def single_segment_autoscale_factory_from_array(
        cls,
        values: np.ndarray | list,
        colorscale: list[str] | str = 'viridis',
        trim_percentile: tuple[float, float] = None,
        continuous_midpoint: int | float = None,
        default_output: Any = None,
    ) -> 'SegmentedContinuousColorscale':
        """Return a colorscale with one segment from the range of `values`.

        Args:
            values: Values that set the range. Missing values are ignored. If
                the range is one value after the midpoint step, such as for a
                constant array without a midpoint or equal to the midpoint, it
                grows by 10 % of the value on each side, or by 1 for the value 0.
            colorscale: Colors, one color, or a matplotlib colormap name.
            trim_percentile: Lower and upper percentile of `values` for the range,
                such as `(5, 95)`, so outliers do not stretch the scale. `None`:
                the minimum and maximum.
            continuous_midpoint: Value at the middle of the scale. The range grows
                to the same distance on both sides of it, for a diverging
                colorscale. `None`: no midpoint.
            default_output: Color for missing values and for values without a color.

        Returns:
            Colorscale with one segment.

        Raises:
            ValueError: If `values` is empty, all values are missing, or the
                range or its width is not finite, from an infinite value in
                the range or a value near the float limit.
        """
        low, high = cls._get_low_high_from_values(values, trim_percentile)

        if continuous_midpoint is not None:
            dist_low = abs(low - continuous_midpoint)
            dist_high = abs(high - continuous_midpoint)
            max_dist = max(dist_low, dist_high)
            low = continuous_midpoint - max_dist
            high = continuous_midpoint + max_dist

        low, high = cls._widened_finite_range(low, high)
        segments = {(low, high): colorscale}
        return cls(segments=segments, default_output=default_output)

    def _interpolate(self, value: float, start: float, end: float, outputs: list[str]) -> str:
        rgba_colors = list(map(colors.to_rgba, outputs))
        positions = np.linspace(0, 1, len(rgba_colors))

        def color_fn(v: float) -> str:
            t = (np.clip(v, start, end) - start) / (end - start)
            r, g, b, a = np.transpose([np.interp(t, positions, channel) for channel in np.transpose(rgba_colors)])
            return colors.to_hex((r, g, b, a))

        return color_fn(value)

    def to_normalized_colorscale(self, num_reference_points_per_segment: int = 10) -> List[Tuple[float, str]]:
        """Return the colorscale as a plotly colorscale.

        The positions run from 0 at `min_input_value` to 1 at `max_input_value`.
        Each segment gets `num_reference_points_per_segment` points. The end of
        a segment moves by 1e-9 before the next segment, so a color step at a
        segment boundary stays sharp.

        Args:
            num_reference_points_per_segment: Number of points per segment,
                with its start and end.

        Returns:
            `(position, color)` pairs sorted by position.

        Raises:
            ValueError: If `num_reference_points_per_segment` is less than 2.
        """
        if num_reference_points_per_segment < 2:
            raise ValueError('num_reference_points_per_segment must be >= 2')
        total_range = self.max_input_value - self.min_input_value
        segment_items = list(self.segments.items())
        raw_scale: List[Tuple[float, str]] = []
        for idx, ((start, end), _) in enumerate(segment_items):
            norm_start = (start - self.min_input_value) / total_range
            norm_end = (end - self.min_input_value) / total_range
            if idx < len(segment_items) - 1:
                norm_end -= 1e-9
            positions = np.linspace(norm_start, norm_end, num_reference_points_per_segment)
            for pos in positions:
                value = self.min_input_value + pos * total_range
                raw_scale.append((round(pos, 10), self(value)))
        final_pos = (self.max_input_value - self.min_input_value) / total_range
        raw_scale.append((round(final_pos, 10), self(self.max_input_value)))
        seen = set()
        normalized_scale: List[Tuple[float, str]] = []
        for pos, color in sorted(raw_scale, key=lambda x: x[0]):
            if pos in seen:
                continue
            seen.add(pos)
            normalized_scale.append((pos, color))
        return normalized_scale

single_segment_autoscale_factory_from_array classmethod

single_segment_autoscale_factory_from_array(values: ndarray | list, colorscale: list[str] | str = 'viridis', trim_percentile: tuple[float, float] = None, continuous_midpoint: int | float = None, default_output: Any = None) -> SegmentedContinuousColorscale

Return a colorscale with one segment from the range of values.

Parameters:

Name Type Description Default
values ndarray | list

Values that set the range. Missing values are ignored. If the range is one value after the midpoint step, such as for a constant array without a midpoint or equal to the midpoint, it grows by 10 % of the value on each side, or by 1 for the value 0.

required
colorscale list[str] | str

Colors, one color, or a matplotlib colormap name.

'viridis'
trim_percentile tuple[float, float]

Lower and upper percentile of values for the range, such as (5, 95), so outliers do not stretch the scale. None: the minimum and maximum.

None
continuous_midpoint int | float

Value at the middle of the scale. The range grows to the same distance on both sides of it, for a diverging colorscale. None: no midpoint.

None
default_output Any

Color for missing values and for values without a color.

None

Returns:

Type Description
SegmentedContinuousColorscale

Colorscale with one segment.

Raises:

Type Description
ValueError

If values is empty, all values are missing, or the range or its width is not finite, from an infinite value in the range or a value near the float limit.

Source code in src/mesqual/visualizations/value_mapping_system/continuous.py
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
@classmethod
def single_segment_autoscale_factory_from_array(
    cls,
    values: np.ndarray | list,
    colorscale: list[str] | str = 'viridis',
    trim_percentile: tuple[float, float] = None,
    continuous_midpoint: int | float = None,
    default_output: Any = None,
) -> 'SegmentedContinuousColorscale':
    """Return a colorscale with one segment from the range of `values`.

    Args:
        values: Values that set the range. Missing values are ignored. If
            the range is one value after the midpoint step, such as for a
            constant array without a midpoint or equal to the midpoint, it
            grows by 10 % of the value on each side, or by 1 for the value 0.
        colorscale: Colors, one color, or a matplotlib colormap name.
        trim_percentile: Lower and upper percentile of `values` for the range,
            such as `(5, 95)`, so outliers do not stretch the scale. `None`:
            the minimum and maximum.
        continuous_midpoint: Value at the middle of the scale. The range grows
            to the same distance on both sides of it, for a diverging
            colorscale. `None`: no midpoint.
        default_output: Color for missing values and for values without a color.

    Returns:
        Colorscale with one segment.

    Raises:
        ValueError: If `values` is empty, all values are missing, or the
            range or its width is not finite, from an infinite value in
            the range or a value near the float limit.
    """
    low, high = cls._get_low_high_from_values(values, trim_percentile)

    if continuous_midpoint is not None:
        dist_low = abs(low - continuous_midpoint)
        dist_high = abs(high - continuous_midpoint)
        max_dist = max(dist_low, dist_high)
        low = continuous_midpoint - max_dist
        high = continuous_midpoint + max_dist

    low, high = cls._widened_finite_range(low, high)
    segments = {(low, high): colorscale}
    return cls(segments=segments, default_output=default_output)

to_normalized_colorscale

to_normalized_colorscale(num_reference_points_per_segment: int = 10) -> list[tuple[float, str]]

Return the colorscale as a plotly colorscale.

The positions run from 0 at min_input_value to 1 at max_input_value. Each segment gets num_reference_points_per_segment points. The end of a segment moves by 1e-9 before the next segment, so a color step at a segment boundary stays sharp.

Parameters:

Name Type Description Default
num_reference_points_per_segment int

Number of points per segment, with its start and end.

10

Returns:

Type Description
list[tuple[float, str]]

(position, color) pairs sorted by position.

Raises:

Type Description
ValueError

If num_reference_points_per_segment is less than 2.

Source code in src/mesqual/visualizations/value_mapping_system/continuous.py
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
def to_normalized_colorscale(self, num_reference_points_per_segment: int = 10) -> List[Tuple[float, str]]:
    """Return the colorscale as a plotly colorscale.

    The positions run from 0 at `min_input_value` to 1 at `max_input_value`.
    Each segment gets `num_reference_points_per_segment` points. The end of
    a segment moves by 1e-9 before the next segment, so a color step at a
    segment boundary stays sharp.

    Args:
        num_reference_points_per_segment: Number of points per segment,
            with its start and end.

    Returns:
        `(position, color)` pairs sorted by position.

    Raises:
        ValueError: If `num_reference_points_per_segment` is less than 2.
    """
    if num_reference_points_per_segment < 2:
        raise ValueError('num_reference_points_per_segment must be >= 2')
    total_range = self.max_input_value - self.min_input_value
    segment_items = list(self.segments.items())
    raw_scale: List[Tuple[float, str]] = []
    for idx, ((start, end), _) in enumerate(segment_items):
        norm_start = (start - self.min_input_value) / total_range
        norm_end = (end - self.min_input_value) / total_range
        if idx < len(segment_items) - 1:
            norm_end -= 1e-9
        positions = np.linspace(norm_start, norm_end, num_reference_points_per_segment)
        for pos in positions:
            value = self.min_input_value + pos * total_range
            raw_scale.append((round(pos, 10), self(value)))
    final_pos = (self.max_input_value - self.min_input_value) / total_range
    raw_scale.append((round(final_pos, 10), self(self.max_input_value)))
    seen = set()
    normalized_scale: List[Tuple[float, str]] = []
    for pos, color in sorted(raw_scale, key=lambda x: x[0]):
        if pos in seen:
            continue
        seen.add(pos)
        normalized_scale.append((pos, color))
    return normalized_scale

SegmentedContinuousInputToContinuousOutputMapping

Bases: SegmentedContinuousInputMappingBase

Maps numbers to numbers, segment by segment.

The output of a segment is one number, or a list of numbers to interpolate. The rules of a call and the arguments are in SegmentedContinuousInputMappingBase.

Examples:

Widths from 1 to 5 for values from 0 to 100, width 0.5 for missing values:

>>> widths = SegmentedContinuousInputToContinuousOutputMapping(segments={(0, 100): [1.0, 5.0]}, default_output=0.5)
>>> print(widths(50), widths(250), widths(None))
3.0 5.0 0.5
Source code in src/mesqual/visualizations/value_mapping_system/continuous.py
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
class SegmentedContinuousInputToContinuousOutputMapping(SegmentedContinuousInputMappingBase):
    """Maps numbers to numbers, segment by segment.

    The output of a segment is one number, or a list of numbers to interpolate.
    The rules of a call and the arguments are in
    `SegmentedContinuousInputMappingBase`.

    Examples:
        Widths from 1 to 5 for values from 0 to 100, width 0.5 for missing values:

        >>> widths = SegmentedContinuousInputToContinuousOutputMapping(segments={(0, 100): [1.0, 5.0]}, default_output=0.5)
        >>> print(widths(50), widths(250), widths(None))
        3.0 5.0 0.5
    """

    @classmethod
    def single_segment_autoscale_factory_from_array(
        cls,
        values: np.ndarray | list,
        output_range: tuple[int | float, int | float],
        trim_percentile: tuple[float, float] = None,
        default_output: Any = None,
    ) -> 'SegmentedContinuousInputToContinuousOutputMapping':
        """Return a mapping with one segment from the range of `values`.

        Args:
            values: Values that set the range. Missing values are ignored. If
                the range is one value, such as for a constant array, it grows
                by 10 % of the value on each side, or by 1 for the value 0.
            output_range: Output at the start and at the end of the range.
            trim_percentile: Lower and upper percentile of `values` for the range,
                such as `(5, 95)`, so outliers do not stretch the scale. `None`:
                the minimum and maximum.
            default_output: Output for missing values and for values without an output.

        Returns:
            Mapping with one segment.

        Raises:
            ValueError: If `values` is empty, all values are missing, or the
                range or its width is not finite, from an infinite value in
                the range or a value near the float limit.
        """
        low, high = cls._widened_finite_range(*cls._get_low_high_from_values(values, trim_percentile))
        segments = {(low, high): [output_range[0], output_range[1]]}
        return cls(segments=segments, default_output=default_output)

single_segment_autoscale_factory_from_array classmethod

single_segment_autoscale_factory_from_array(values: ndarray | list, output_range: tuple[int | float, int | float], trim_percentile: tuple[float, float] = None, default_output: Any = None) -> SegmentedContinuousInputToContinuousOutputMapping

Return a mapping with one segment from the range of values.

Parameters:

Name Type Description Default
values ndarray | list

Values that set the range. Missing values are ignored. If the range is one value, such as for a constant array, it grows by 10 % of the value on each side, or by 1 for the value 0.

required
output_range tuple[int | float, int | float]

Output at the start and at the end of the range.

required
trim_percentile tuple[float, float]

Lower and upper percentile of values for the range, such as (5, 95), so outliers do not stretch the scale. None: the minimum and maximum.

None
default_output Any

Output for missing values and for values without an output.

None

Returns:

Type Description
SegmentedContinuousInputToContinuousOutputMapping

Mapping with one segment.

Raises:

Type Description
ValueError

If values is empty, all values are missing, or the range or its width is not finite, from an infinite value in the range or a value near the float limit.

Source code in src/mesqual/visualizations/value_mapping_system/continuous.py
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
@classmethod
def single_segment_autoscale_factory_from_array(
    cls,
    values: np.ndarray | list,
    output_range: tuple[int | float, int | float],
    trim_percentile: tuple[float, float] = None,
    default_output: Any = None,
) -> 'SegmentedContinuousInputToContinuousOutputMapping':
    """Return a mapping with one segment from the range of `values`.

    Args:
        values: Values that set the range. Missing values are ignored. If
            the range is one value, such as for a constant array, it grows
            by 10 % of the value on each side, or by 1 for the value 0.
        output_range: Output at the start and at the end of the range.
        trim_percentile: Lower and upper percentile of `values` for the range,
            such as `(5, 95)`, so outliers do not stretch the scale. `None`:
            the minimum and maximum.
        default_output: Output for missing values and for values without an output.

    Returns:
        Mapping with one segment.

    Raises:
        ValueError: If `values` is empty, all values are missing, or the
            range or its width is not finite, from an infinite value in
            the range or a value near the float limit.
    """
    low, high = cls._widened_finite_range(*cls._get_low_high_from_values(values, trim_percentile))
    segments = {(low, high): [output_range[0], output_range[1]]}
    return cls(segments=segments, default_output=default_output)

SegmentedContinuousLineWidthMapping

Bases: SegmentedContinuousInputToContinuousOutputMapping

Maps numbers to line widths in px.

Examples:

Width 1 for small flows, 2 to 6 for large flows:

>>> widths = SegmentedContinuousLineWidthMapping(
...     segments={(0, 500): 1.0, (500, 2000): [2.0, 6.0]},
...     default_output=0.5,
... )
>>> print(widths(250), widths(1250), widths(5000), widths(None))
1.0 4.0 6.0 0.5
Source code in src/mesqual/visualizations/value_mapping_system/continuous.py
372
373
374
375
376
377
378
379
380
381
382
383
384
class SegmentedContinuousLineWidthMapping(SegmentedContinuousInputToContinuousOutputMapping):
    """Maps numbers to line widths in px.

    Examples:
        Width 1 for small flows, 2 to 6 for large flows:

        >>> widths = SegmentedContinuousLineWidthMapping(
        ...     segments={(0, 500): 1.0, (500, 2000): [2.0, 6.0]},
        ...     default_output=0.5,
        ... )
        >>> print(widths(250), widths(1250), widths(5000), widths(None))
        1.0 4.0 6.0 0.5
    """

SegmentedContinuousOpacityMapping

Bases: SegmentedContinuousInputToContinuousOutputMapping

Maps numbers to opacities from 0 to 1.

Examples:

Opacity from 0.2 to 1 for values from 0 to 100, hidden for missing values:

>>> opacity = SegmentedContinuousOpacityMapping(segments={(0, 100): [0.2, 1.0]}, default_output=0.0)
>>> print(opacity(0), opacity(250), opacity(float('nan')))
0.2 1.0 0.0
Source code in src/mesqual/visualizations/value_mapping_system/continuous.py
387
388
389
390
391
392
393
394
395
396
class SegmentedContinuousOpacityMapping(SegmentedContinuousInputToContinuousOutputMapping):
    """Maps numbers to opacities from 0 to 1.

    Examples:
        Opacity from 0.2 to 1 for values from 0 to 100, hidden for missing values:

        >>> opacity = SegmentedContinuousOpacityMapping(segments={(0, 100): [0.2, 1.0]}, default_output=0.0)
        >>> print(opacity(0), opacity(250), opacity(float('nan')))
        0.2 1.0 0.0
    """

rule

RuleBasedMapping

Bases: BaseMapping

Maps values with a function.

A call returns mapping_rule(value). The rule handles missing values itself, for example with is_missing.

Parameters:

Name Type Description Default
mapping_rule Callable[[Any], Any]

Function that returns the output for one value.

required

Examples:

Red for negative values, green for others, gray for missing values:

>>> from mesqual.visualizations.value_mapping_system import is_missing
>>> def sign_color(value: float) -> str:
...     if is_missing(value):
...         return '#cccccc'
...     return '#d62728' if value < 0 else '#2ca02c'
>>> colors = RuleBasedMapping(sign_color)
>>> colors(-3), colors(None)
('#d62728', '#cccccc')
Source code in src/mesqual/visualizations/value_mapping_system/rule.py
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class RuleBasedMapping(BaseMapping):
    """Maps values with a function.

    A call returns `mapping_rule(value)`. The rule handles missing values
    itself, for example with `is_missing`.

    Args:
        mapping_rule: Function that returns the output for one value.

    Examples:
        Red for negative values, green for others, gray for missing values:

        >>> from mesqual.visualizations.value_mapping_system import is_missing
        >>> def sign_color(value: float) -> str:
        ...     if is_missing(value):
        ...         return '#cccccc'
        ...     return '#d62728' if value < 0 else '#2ca02c'
        >>> colors = RuleBasedMapping(sign_color)
        >>> colors(-3), colors(None)
        ('#d62728', '#cccccc')
    """

    def __init__(self, mapping_rule: Callable[[Any], Any]):
        self.rule = mapping_rule

    def __call__(self, value: Any) -> Any:
        return self.rule(value)