Pairwise Distance Base#

base #

CLASS DESCRIPTION
PairwiseDistance

Abstract base class for computing pairwise distances between samples.

PairwiseDistanceRegistry

Registry for pairwise distance classes.

FUNCTION DESCRIPTION
initialize_distance_fn

Initialize a distance from an instance or registry name.

Classes#

PairwiseDistance(reduce: Literal['mean', 'sum', 'none', None] = None, compute_mode: Literal['donot_use_mm_for_euclid_dist', 'use_mm_for_euclid_dist', 'use_mm_for_euclid_dist_if_necessary'] | None = 'donot_use_mm_for_euclid_dist', normalize: bool = False) #

Bases: Module

Abstract base class for computing pairwise distances between samples.

Provides a unified interface for different distance metrics used in spectral methods and manifold learning. All distance implementations should inherit from this class and implement the forward_step method.

PARAMETER DESCRIPTION
reduce

Reduction method for the computed distances.

  • "mean": Average distance across specified dimensions
  • "sum": Sum distances across specified dimensions
  • "none" or None: Return full distance matrix without reduction

TYPE: Literal["mean", "sum", "none", None], optional, by default None DEFAULT: None

compute_mode

Computation strategy for Euclidean distances.

  • "donot_use_mm_for_euclid_dist": Use element-wise operations
  • "use_mm_for_euclid_dist": Force matrix multiplication approach
  • "use_mm_for_euclid_dist_if_necessary": Adaptive selection based on data
  • None: Not applicable (used by non-Euclidean distance metrics)

TYPE: str | None, optional, by default "donot_use_mm_for_euclid_dist" DEFAULT: 'donot_use_mm_for_euclid_dist'

normalize

Whether to normalize distances to unit scale.

TYPE: bool, optional, by default False DEFAULT: False

Examples:

Creating a custom distance metric:

>>> import torch
>>> from spectre.pairwise_distance import PairwiseDistance
>>>
>>> class ManhattanDistance(PairwiseDistance):
...     def forward_step(self, X):
...         return torch.cdist(X, X, p=1)
>>>
>>> X = torch.randn(50, 3)
>>> distance_fn = ManhattanDistance()
>>> distances = distance_fn(X)

Using existing distance implementations:

>>> from spectre.pairwise_distance import PairwiseDistanceEuclidean
>>> euclidean = PairwiseDistanceEuclidean(normalize=True)
METHOD DESCRIPTION
forward_step

Compute pairwise distances between samples.

forward

Compute pairwise distances with automatic parameter handling.

Source code in spectre/pairwise_distance/base.py
def __init__(
    self,
    reduce: Literal["mean", "sum", "none", None] = None,
    compute_mode: Literal[
        "donot_use_mm_for_euclid_dist",
        "use_mm_for_euclid_dist",
        "use_mm_for_euclid_dist_if_necessary",
    ]
    | None = "donot_use_mm_for_euclid_dist",
    normalize: bool = False,
) -> None:
    super().__init__()

    avail_reduce = ["mean", "sum", "none", None]
    if reduce not in avail_reduce:
        raise ValueError(f"Expected `reduce` to be {avail_reduce}, got {reduce}.")
    self.reduce = reduce

    if compute_mode is not None:
        avail_compute_mode = [
            "donot_use_mm_for_euclid_dist",
            "use_mm_for_euclid_dist",
            "use_mm_for_euclid_dist_if_necessary",
        ]
        if compute_mode not in avail_compute_mode:
            raise ValueError(
                f"Expected `compute_mode` to be {avail_compute_mode}, got "
                f"{compute_mode}."
            )
    self.compute_mode = compute_mode

    if not isinstance(normalize, bool):
        raise TypeError(
            f"Parameter `normalize` must be a boolean, got {type(normalize)}."
        )
    self.normalize = normalize
Functions#
forward_step(X: torch.Tensor, **kwargs) -> torch.Tensor abstractmethod #

Compute pairwise distances between samples.

This method must be implemented by subclasses to define their specific distance computation logic. The signature allows flexibility for different distance metrics that require varying parameters.

PARAMETER DESCRIPTION
X

Input data matrix.

TYPE: torch.Tensor of shape (n_samples, n_features)

**kwargs

Additional keyword arguments specific to the distance metric.

  • Y: torch.Tensor (for Euclidean distances)
  • M_inv: torch.Tensor (for Mahalanobis distances)

TYPE: dict DEFAULT: {}

RETURNS DESCRIPTION
Tensor

Pairwise distance matrix. Shape depends on the specific metric and input parameters.

Examples:

Euclidean distance with second tensor:

>>> forward_step(X, Y=Y)

Mahalanobis distance with inverse covariance:

>>> forward_step(X, M_inv=M_inv)

Covariance distance (no additional parameters):

>>> forward_step(X)
Source code in spectre/pairwise_distance/base.py
@abstractmethod
def forward_step(self, X: torch.Tensor, **kwargs) -> torch.Tensor:
    """
    Compute pairwise distances between samples.

    This method must be implemented by subclasses to define their specific
    distance computation logic. The signature allows flexibility for different
    distance metrics that require varying parameters.

    Parameters
    ----------
    X : torch.Tensor of shape (n_samples, n_features)
        Input data matrix.

    **kwargs : dict
        Additional keyword arguments specific to the distance metric.

        - Y: torch.Tensor (for Euclidean distances)
        - M_inv: torch.Tensor (for Mahalanobis distances)

    Returns
    -------
    torch.Tensor
        Pairwise distance matrix. Shape depends on the specific metric and input
        parameters.

    Examples
    --------
    Euclidean distance with second tensor:
    >>> forward_step(X, Y=Y)

    Mahalanobis distance with inverse covariance:
    >>> forward_step(X, M_inv=M_inv)

    Covariance distance (no additional parameters):
    >>> forward_step(X)
    """
    raise NotImplementedError()
forward(X: torch.Tensor, **kwargs) -> torch.Tensor #

Compute pairwise distances with automatic parameter handling.

This method provides a unified interface for all distance metrics while allowing flexible parameter passing. Derived classes handle their own parameter extraction from kwargs.

PARAMETER DESCRIPTION
X

Input data matrix.

TYPE: torch.Tensor of shape (n_samples, n_features)

**kwargs

Additional keyword arguments passed to forward_step. Used for metric-specific parameters like Y, M_inv, etc.

TYPE: dict DEFAULT: {}

RETURNS DESCRIPTION
Tensor

Distance matrix as computed by the specific metric implementation.

Examples:

>>> # Euclidean distance
>>> euclidean_dist = euclidean_module(X, Y, normalize=True)
>>>
>>> # Mahalanobis distance
>>> mahalanobis_dist = mahalanobis_module(X, M_inv=M_inv, reduce="mean")
>>>
>>> # Covariance distance
>>> cov_dist = covariance_module(X, cov_k_neighbor=8)
Source code in spectre/pairwise_distance/base.py
def forward(self, X: torch.Tensor, **kwargs) -> torch.Tensor:
    """
    Compute pairwise distances with automatic parameter handling.

    This method provides a unified interface for all distance metrics while
    allowing flexible parameter passing. Derived classes handle their own
    parameter extraction from kwargs.

    Parameters
    ----------
    X : torch.Tensor of shape (n_samples, n_features)
        Input data matrix.

    **kwargs : dict
        Additional keyword arguments passed to `forward_step`. Used for
        metric-specific parameters like `Y`, `M_inv`, etc.

    Returns
    -------
    torch.Tensor
        Distance matrix as computed by the specific metric implementation.

    Examples
    --------
    >>> # Euclidean distance
    >>> euclidean_dist = euclidean_module(X, Y, normalize=True)
    >>>
    >>> # Mahalanobis distance
    >>> mahalanobis_dist = mahalanobis_module(X, M_inv=M_inv, reduce="mean")
    >>>
    >>> # Covariance distance
    >>> cov_dist = covariance_module(X, cov_k_neighbor=8)
    """
    return self.forward_step(X, **kwargs)

PairwiseDistanceRegistry #

Bases: Registry

Registry for pairwise distance classes.

Functions#

initialize_distance_fn(distance_fn: PairwiseDistance | str | None, distance_kwargs: dict[str, Any] | None = None) -> PairwiseDistance #

Initialize a distance from an instance or registry name.

Arguments

distance_fn : PairwiseDistance | str | None Distance instance or name of registered distance. distance_kwargs : dict[str, Any] | None Keyword arguments passed to distance constructor (only for string names).

RETURNS DESCRIPTION
PairwiseDistance

Initialized distance instance.

RAISES DESCRIPTION
ValueError

If distance_fn is None.

TypeError

If distance_fn is not a PairwiseDistance instance or string.

Source code in spectre/pairwise_distance/base.py
def initialize_distance_fn(
    distance_fn: PairwiseDistance | str | None,
    distance_kwargs: dict[str, Any] | None = None,
) -> PairwiseDistance:
    """
    Initialize a distance from an instance or registry name.

    Arguments
    ---------
    distance_fn : PairwiseDistance | str | None
        Distance instance or name of registered distance.
    distance_kwargs : dict[str, Any] | None
        Keyword arguments passed to distance constructor (only for string names).

    Returns
    -------
    PairwiseDistance
        Initialized distance instance.

    Raises
    ------
    ValueError
        If `distance_fn` is None.
    TypeError
        If `distance_fn` is not a PairwiseDistance instance or string.
    """
    return _initialize_from_registry(
        PairwiseDistanceRegistry, distance_fn, distance_kwargs, param_name="distance_fn"
    )