hbutils.algorithm.linear

This module provides utilities for creating multi-staged linear gradient mappings based on float numbers.

The main functionality allows users to define piecewise linear functions through a sequence of control points, either with automatic x-spacing or custom x-coordinates. This is useful for creating custom interpolation functions, gradient mappings, and other piecewise linear transformations.

The module exports a single function linear_map() that creates callable piecewise linear mapping functions.

linear_map

hbutils.algorithm.linear.linear_map(points: Sequence[float] | Sequence[Tuple[float, float]]) Callable[[float], float][source]

Create a multiple-staged linear gradient calculation function based on control points.

This function generates a piecewise linear mapping function from a sequence of control points. The points can be specified in two ways:

  1. Simple sequence of y-values: x-values are automatically distributed evenly from 0 to 1

  2. Sequence of (x, y) tuples: explicit x and y coordinates for each control point

Parameters:

points (Union[Sequence[float], Sequence[Tuple[float, float]]]) – Points for this linear mapping. If the sequence consists of float numbers, it will be seen as the simple linear mapping with x-values automatically distributed from 0 to 1. If the elements are binary tuples (contains 2 float numbers), it means the x-range is assigned explicitly.

Returns:

A callable function for linear mapping that takes a float x-value and returns the interpolated y-value.

Return type:

Callable[[float], float]

Raises:
  • AssertionError – If points sequence is empty or if x-values are not in strictly increasing order.

  • ValueError – If the input x-value to the returned function is outside the valid range.

Examples::
  • Simple Linear Mapping

>>> from hbutils.algorithm import linear_map
>>>
>>> f = linear_map((0, 1, 0.5))
>>> f(0)
0.0
>>> f(0.25)
0.5
>>> f(1 / 3)
0.6666666666666666
>>> f(0.5)
1.0
>>> f(2 / 3)
0.8333333333333334
>>> f(0.75)
0.75
>>> f(1)
0.5
  • Complex Linear Mapping (x values are customized)

>>> f = linear_map(((-0.2, 0), (0.7, 1), (1.1, 0.5)))
>>> f(-0.2)
0.0
>>> f(0)
0.22222222222222227
>>> f(0.25)
0.5000000000000001
>>> f(1 / 3)
0.5925925925925927
>>> f(0.5)
0.7777777777777778
>>> f(2 / 3)
0.9629629629629631
>>> f(0.7)
1.0
>>> f(0.75)
0.9375
>>> f(0.8)
0.875
>>> f(1)
0.625
>>> f(1.1)
0.5