Skip to content

base

base #

What a distance function is: extract features, compare them pairwise.

Every metric implements two vectorized steps — extract turns values into numeric features, pairwise turns two feature sets into a matrix of distances — and inherits the scalar __call__, the full matrix and coverage (how well captures cover each point) from them.

Missing data has one rule, applied here: an absent value extracts as nan features, so every pair involving it has nan distance. A combination drops its nan terms, and is itself nan only when no term survives; select_sessions never offers a candidate whose distance is nan.

COVERAGE_CHUNK = 4096 module-attribute #

How many points coverage scores at once, bounding its distance matrix.

DistanceFunction #

Bases: ABC

A statistical distance between two values along one dimension.

Source code in capturegraph-recipes/capturegraph_recipes/scheduling/distance/base.py
class DistanceFunction[T](ABC):
    """A statistical distance between two values along one dimension."""

    @abstractmethod
    def extract(self, values: cg.Array) -> np.ndarray:
        """The numeric features of each value, one row each (``nan`` when absent)."""
        ...

    @abstractmethod
    def pairwise(self, features_a: np.ndarray, features_b: np.ndarray) -> np.ndarray:
        """The ``len(a) × len(b)`` distances between two extracted feature sets."""
        ...

    def __call__(self, a: T, b: T) -> float:
        """The distance between two values (``nan`` when they cannot be compared)."""
        return float(self.matrix(cg.Array([a]), cg.Array([b]))[0, 0])

    def matrix(self, values_a: cg.Array, values_b: cg.Array | None = None) -> np.ndarray:
        """The pairwise distances between two value sets (``values_a`` against itself)."""
        features_a = self.extract(values_a)
        features_b = features_a if values_b is None else self.extract(values_b)
        return self.pairwise(features_a, features_b)

    def coverage(
        self,
        points: cg.Array | np.ndarray,
        captures: cg.Array | np.ndarray,
        weights: np.ndarray | None = None,
    ) -> np.ndarray:
        """How well ``captures`` cover each point: the best weighted Gaussian of a distance.

        A point's score is ``max(weight · exp(-d² / 2))`` over every capture,
        ``d`` the distance in sigmas — a best rather than a sum, so a burst of
        captures in one place covers it no more than one capture does.

        ```python
        sun = cgr.scheduling.distance.solar(sigma_deg=4.0)
        need = 1.0 - sun.coverage(coming_suns, photographed_suns)
        ```

        Args:
            points: The values to score — or their features, already extracted.
            captures: The captured values — or their features.
            weights: How much each capture counts, 0–1; every capture fully when omitted.

        Returns:
            One 0–1 score per point; 0 where no capture can be compared with it.
        """
        point_features = self._features(points)
        capture_features = self._features(captures)
        weight = np.ones(len(capture_features)) if weights is None else np.asarray(weights)
        capture_features, weight = _distinct(capture_features, weight)
        scores = np.zeros(len(point_features), dtype=np.float64)
        if not len(capture_features):
            return scores
        for begin in range(0, len(point_features), COVERAGE_CHUNK):
            separation = self.pairwise(
                point_features[begin : begin + COVERAGE_CHUNK],
                capture_features,
            )
            covered = weight[None, :] * np.exp(-0.5 * separation**2)
            scores[begin : begin + COVERAGE_CHUNK] = np.nan_to_num(covered).max(axis=1)
        return scores

    def _features(self, values: cg.Array | np.ndarray) -> np.ndarray:
        """``values`` as features: an array of values is extracted, an ndarray already is one."""
        return values if isinstance(values, np.ndarray) else self.extract(values)

    def defined(self, values: cg.Array) -> np.ndarray:
        """Which values this metric can compare at all, as a boolean mask."""
        return np.array([not np.isnan(self(value, value)) for value in values], dtype=bool)

__call__(a, b) #

The distance between two values (nan when they cannot be compared).

Source code in capturegraph-recipes/capturegraph_recipes/scheduling/distance/base.py
def __call__(self, a: T, b: T) -> float:
    """The distance between two values (``nan`` when they cannot be compared)."""
    return float(self.matrix(cg.Array([a]), cg.Array([b]))[0, 0])

coverage(points, captures, weights=None) #

How well captures cover each point: the best weighted Gaussian of a distance.

A point's score is max(weight · exp(-d² / 2)) over every capture, d the distance in sigmas — a best rather than a sum, so a burst of captures in one place covers it no more than one capture does.

sun = cgr.scheduling.distance.solar(sigma_deg=4.0)
need = 1.0 - sun.coverage(coming_suns, photographed_suns)

Parameters:

Name Type Description Default
points Array | ndarray

The values to score — or their features, already extracted.

required
captures Array | ndarray

The captured values — or their features.

required
weights ndarray | None

How much each capture counts, 0–1; every capture fully when omitted.

None

Returns:

Type Description
ndarray

One 0–1 score per point; 0 where no capture can be compared with it.

Source code in capturegraph-recipes/capturegraph_recipes/scheduling/distance/base.py
def coverage(
    self,
    points: cg.Array | np.ndarray,
    captures: cg.Array | np.ndarray,
    weights: np.ndarray | None = None,
) -> np.ndarray:
    """How well ``captures`` cover each point: the best weighted Gaussian of a distance.

    A point's score is ``max(weight · exp(-d² / 2))`` over every capture,
    ``d`` the distance in sigmas — a best rather than a sum, so a burst of
    captures in one place covers it no more than one capture does.

    ```python
    sun = cgr.scheduling.distance.solar(sigma_deg=4.0)
    need = 1.0 - sun.coverage(coming_suns, photographed_suns)
    ```

    Args:
        points: The values to score — or their features, already extracted.
        captures: The captured values — or their features.
        weights: How much each capture counts, 0–1; every capture fully when omitted.

    Returns:
        One 0–1 score per point; 0 where no capture can be compared with it.
    """
    point_features = self._features(points)
    capture_features = self._features(captures)
    weight = np.ones(len(capture_features)) if weights is None else np.asarray(weights)
    capture_features, weight = _distinct(capture_features, weight)
    scores = np.zeros(len(point_features), dtype=np.float64)
    if not len(capture_features):
        return scores
    for begin in range(0, len(point_features), COVERAGE_CHUNK):
        separation = self.pairwise(
            point_features[begin : begin + COVERAGE_CHUNK],
            capture_features,
        )
        covered = weight[None, :] * np.exp(-0.5 * separation**2)
        scores[begin : begin + COVERAGE_CHUNK] = np.nan_to_num(covered).max(axis=1)
    return scores

defined(values) #

Which values this metric can compare at all, as a boolean mask.

Source code in capturegraph-recipes/capturegraph_recipes/scheduling/distance/base.py
def defined(self, values: cg.Array) -> np.ndarray:
    """Which values this metric can compare at all, as a boolean mask."""
    return np.array([not np.isnan(self(value, value)) for value in values], dtype=bool)

extract(values) abstractmethod #

The numeric features of each value, one row each (nan when absent).

Source code in capturegraph-recipes/capturegraph_recipes/scheduling/distance/base.py
@abstractmethod
def extract(self, values: cg.Array) -> np.ndarray:
    """The numeric features of each value, one row each (``nan`` when absent)."""
    ...

matrix(values_a, values_b=None) #

The pairwise distances between two value sets (values_a against itself).

Source code in capturegraph-recipes/capturegraph_recipes/scheduling/distance/base.py
def matrix(self, values_a: cg.Array, values_b: cg.Array | None = None) -> np.ndarray:
    """The pairwise distances between two value sets (``values_a`` against itself)."""
    features_a = self.extract(values_a)
    features_b = features_a if values_b is None else self.extract(values_b)
    return self.pairwise(features_a, features_b)

pairwise(features_a, features_b) abstractmethod #

The len(a) × len(b) distances between two extracted feature sets.

Source code in capturegraph-recipes/capturegraph_recipes/scheduling/distance/base.py
@abstractmethod
def pairwise(self, features_a: np.ndarray, features_b: np.ndarray) -> np.ndarray:
    """The ``len(a) × len(b)`` distances between two extracted feature sets."""
    ...

as_distance(function) #

function as a [DistanceFunction][], wrapping a plain callable as one.

Parameters:

Name Type Description Default
function Callable[[T, T], float]

A metric, or a plain (a, b) -> float callable.

required

Returns:

Type Description
DistanceFunction[T]

The metric itself, or the callable wrapped to evaluate pair by pair.

Source code in capturegraph-recipes/capturegraph_recipes/scheduling/distance/base.py
def as_distance[T](function: Callable[[T, T], float]) -> DistanceFunction[T]:
    """``function`` as a [DistanceFunction][], wrapping a plain callable as one.

    Args:
        function: A metric, or a plain ``(a, b) -> float`` callable.

    Returns:
        The metric itself, or the callable wrapped to evaluate pair by pair.
    """
    if isinstance(function, DistanceFunction):
        return function
    return _CallableDistance(function)

field(row, name) #

row.name, else row[name] on a mapping, else None (absent).

Parameters:

Name Type Description Default
row object

A session — a cg.Struct, a plain dict, or an absent value.

required
name str

The attribute (or key) to read.

required

Returns:

Type Description
object

The attribute's value, or None when the row does not carry it.

Source code in capturegraph-recipes/capturegraph_recipes/scheduling/distance/base.py
def field(row: object, name: str) -> object:
    """``row.name``, else ``row[name]`` on a mapping, else ``None`` (absent).

    Args:
        row: A session — a ``cg.Struct``, a plain ``dict``, or an absent value.
        name: The attribute (or key) to read.

    Returns:
        The attribute's value, or ``None`` when the row does not carry it.
    """
    try:
        return getattr(row, name)
    except AttributeError:
        return row.get(name) if isinstance(row, Mapping) else None

numeric(values, *fields) #

Each value's fields as a row of floats — the value itself when none are named.

Parameters:

Name Type Description Default
values Array

The values to read.

required
fields str

The field names to read from each value, in column order.

()

Returns:

Type Description
ndarray

A len(values) × max(len(fields), 1) array; an absent value or field

ndarray

reads nan.

Source code in capturegraph-recipes/capturegraph_recipes/scheduling/distance/base.py
def numeric(values: cg.Array, *fields: str) -> np.ndarray:
    """Each value's ``fields`` as a row of floats — the value itself when none are named.

    Args:
        values: The values to read.
        fields: The field names to read from each value, in column order.

    Returns:
        A ``len(values) × max(len(fields), 1)`` array; an absent value or field
        reads ``nan``.
    """
    rows = [
        [_number(field(value, name)) for name in fields] if fields else [_number(value)]
        for value in values
    ]
    return np.array(rows, dtype=np.float64).reshape(len(values), len(fields) or 1)