Skip to content

Kernels

This page documents 6 public symbols. Each entry includes its purpose, import path, full API docstring, and the maintained example that exercises it.

Conceptual guide

gaussian_kernel

Compute Gaussian kernel weights.

Property Value
Type function
Import from pygwrx.core import gaussian_kernel
Signature gaussian_kernel(distances: 'np.ndarray', bandwidth: 'float') -> 'np.ndarray'
Maintained example examples/core/01_kernels.py

gaussian_kernel

gaussian_kernel(
    distances: ndarray, bandwidth: float
) -> np.ndarray

Compute Gaussian kernel weights.

Parameters:

Name Type Description Default
distances ndarray

Non-negative distances from a regression location.

required
bandwidth float

Positive bandwidth controlling the rate of weight decay.

required

Returns:

Name Type Description
ndarray ndarray

Floating-point weights in the interval [0, 1]. Values may underflow to exactly zero for extremely large normalized distances.

Notes

The kernel is defined as:

w(d) = exp(-0.5 * (d / bandwidth) ** 2)
Source code in src/pygwrx/core/kernels.py
def gaussian_kernel(distances: np.ndarray, bandwidth: float) -> np.ndarray:
    """Compute Gaussian kernel weights.

    Args:
        distances: Non-negative distances from a regression location.
        bandwidth: Positive bandwidth controlling the rate of weight decay.

    Returns:
        ndarray: Floating-point weights in the interval [0, 1]. Values may underflow
            to exactly zero for extremely large normalized distances.

    Notes:
        The kernel is defined as:

            w(d) = exp(-0.5 * (d / bandwidth) ** 2)
    """
    distances_arr, bandwidth_value = _validate_kernel_inputs(
        distances,
        bandwidth,
    )
    normalized_distances = distances_arr / bandwidth_value
    return np.exp(-0.5 * normalized_distances**2)

bisquare_kernel

Compute bi-square (quartic) kernel weights.

Property Value
Type function
Import from pygwrx.core import bisquare_kernel
Signature bisquare_kernel(distances: 'np.ndarray', bandwidth: 'float') -> 'np.ndarray'
Maintained example examples/core/01_kernels.py

bisquare_kernel

bisquare_kernel(
    distances: ndarray, bandwidth: float
) -> np.ndarray

Compute bi-square (quartic) kernel weights.

Parameters:

Name Type Description Default
distances ndarray

Non-negative distances from a regression location.

required
bandwidth float

Positive bandwidth. Observations at or beyond the bandwidth receive zero weight.

required

Returns:

Name Type Description
ndarray ndarray

Floating-point weights in the interval [0, 1].

Notes

The kernel is defined as:

w(d) = (1 - (d / bandwidth) ** 2) ** 2,  if d < bandwidth
w(d) = 0,                                if d >= bandwidth
Source code in src/pygwrx/core/kernels.py
def bisquare_kernel(distances: np.ndarray, bandwidth: float) -> np.ndarray:
    """Compute bi-square (quartic) kernel weights.

    Args:
        distances: Non-negative distances from a regression location.
        bandwidth: Positive bandwidth. Observations at or beyond the bandwidth receive
            zero weight.

    Returns:
        ndarray: Floating-point weights in the interval [0, 1].

    Notes:
        The kernel is defined as:

            w(d) = (1 - (d / bandwidth) ** 2) ** 2,  if d < bandwidth
            w(d) = 0,                                if d >= bandwidth
    """
    distances_arr, bandwidth_value = _validate_kernel_inputs(
        distances,
        bandwidth,
    )

    weights = np.zeros_like(distances_arr, dtype=float)
    mask = distances_arr < bandwidth_value
    normalized_distances = distances_arr[mask] / bandwidth_value
    weights[mask] = (1.0 - normalized_distances**2) ** 2
    return weights

exponential_kernel

Compute exponential kernel weights.

Property Value
Type function
Import from pygwrx.core import exponential_kernel
Signature exponential_kernel(distances: 'np.ndarray', bandwidth: 'float') -> 'np.ndarray'
Maintained example examples/core/01_kernels.py

exponential_kernel

exponential_kernel(
    distances: ndarray, bandwidth: float
) -> np.ndarray

Compute exponential kernel weights.

The exponential kernel decreases more sharply near the origin than the Gaussian kernel, while retaining a heavier tail at large distances.

Parameters:

Name Type Description Default
distances ndarray

Non-negative distances from a regression location.

required
bandwidth float

Positive bandwidth controlling the rate of weight decay.

required

Returns:

Name Type Description
ndarray ndarray

Floating-point weights in the interval [0, 1]. Values may underflow to exactly zero for extremely large normalized distances.

Notes

The kernel is defined as:

w(d) = exp(-d / bandwidth)
Source code in src/pygwrx/core/kernels.py
def exponential_kernel(distances: np.ndarray, bandwidth: float) -> np.ndarray:
    """Compute exponential kernel weights.

    The exponential kernel decreases more sharply near the origin than the
    Gaussian kernel, while retaining a heavier tail at large distances.

    Args:
        distances: Non-negative distances from a regression location.
        bandwidth: Positive bandwidth controlling the rate of weight decay.

    Returns:
        ndarray: Floating-point weights in the interval [0, 1]. Values may underflow
            to exactly zero for extremely large normalized distances.

    Notes:
        The kernel is defined as:

            w(d) = exp(-d / bandwidth)
    """
    distances_arr, bandwidth_value = _validate_kernel_inputs(
        distances,
        bandwidth,
    )
    return np.exp(-distances_arr / bandwidth_value)

tricube_kernel

Compute tri-cube kernel weights.

Property Value
Type function
Import from pygwrx.core import tricube_kernel
Signature tricube_kernel(distances: 'np.ndarray', bandwidth: 'float') -> 'np.ndarray'
Maintained example examples/core/01_kernels.py

tricube_kernel

tricube_kernel(
    distances: ndarray, bandwidth: float
) -> np.ndarray

Compute tri-cube kernel weights.

Parameters:

Name Type Description Default
distances ndarray

Non-negative distances from a regression location.

required
bandwidth float

Positive bandwidth. Observations at or beyond the bandwidth receive zero weight.

required

Returns:

Name Type Description
ndarray ndarray

Floating-point weights in the interval [0, 1].

Notes

The kernel is defined as:

w(d) = (1 - (d / bandwidth) ** 3) ** 3,  if d < bandwidth
w(d) = 0,                                if d >= bandwidth
Source code in src/pygwrx/core/kernels.py
def tricube_kernel(distances: np.ndarray, bandwidth: float) -> np.ndarray:
    """Compute tri-cube kernel weights.

    Args:
        distances: Non-negative distances from a regression location.
        bandwidth: Positive bandwidth. Observations at or beyond the bandwidth receive
            zero weight.

    Returns:
        ndarray: Floating-point weights in the interval [0, 1].

    Notes:
        The kernel is defined as:

            w(d) = (1 - (d / bandwidth) ** 3) ** 3,  if d < bandwidth
            w(d) = 0,                                if d >= bandwidth
    """
    distances_arr, bandwidth_value = _validate_kernel_inputs(
        distances,
        bandwidth,
    )

    weights = np.zeros_like(distances_arr, dtype=float)
    mask = distances_arr < bandwidth_value
    normalized_distances = distances_arr[mask] / bandwidth_value
    weights[mask] = (1.0 - normalized_distances**3) ** 3
    return weights

boxcar_kernel

Compute boxcar (uniform) kernel weights.

Property Value
Type function
Import from pygwrx.core import boxcar_kernel
Signature boxcar_kernel(distances: 'np.ndarray', bandwidth: 'float') -> 'np.ndarray'
Maintained example examples/core/01_kernels.py

boxcar_kernel

boxcar_kernel(
    distances: ndarray, bandwidth: float
) -> np.ndarray

Compute boxcar (uniform) kernel weights.

Parameters:

Name Type Description Default
distances ndarray

Non-negative distances from a regression location.

required
bandwidth float

Positive bandwidth. Observations within or exactly on the bandwidth boundary receive unit weight.

required

Returns:

Name Type Description
ndarray ndarray

Floating-point weights containing only 0 and 1.

Notes

The kernel is defined as:

w(d) = 1,  if d <= bandwidth
w(d) = 0,  if d > bandwidth
Source code in src/pygwrx/core/kernels.py
def boxcar_kernel(distances: np.ndarray, bandwidth: float) -> np.ndarray:
    """Compute boxcar (uniform) kernel weights.

    Args:
        distances: Non-negative distances from a regression location.
        bandwidth: Positive bandwidth. Observations within or exactly on the bandwidth
            boundary receive unit weight.

    Returns:
        ndarray: Floating-point weights containing only 0 and 1.

    Notes:
        The kernel is defined as:

            w(d) = 1,  if d <= bandwidth
            w(d) = 0,  if d > bandwidth
    """
    distances_arr, bandwidth_value = _validate_kernel_inputs(
        distances,
        bandwidth,
    )
    return (distances_arr <= bandwidth_value).astype(float)

get_kernel_function

Return a built-in kernel by name or validate a custom callable.

Property Value
Type function
Import from pygwrx.core import get_kernel_function
Signature get_kernel_function(kernel: 'KernelLike') -> 'KernelCallable'
Maintained example examples/core/01_kernels.py

get_kernel_function

get_kernel_function(kernel: KernelLike) -> KernelCallable

Return a built-in kernel by name or validate a custom callable.

Parameters:

Name Type Description Default
kernel KernelLike

Built-in kernel name or a callable with the signature kernel(distances, bandwidth) -> weights.

required

Returns:

Name Type Description
callable KernelCallable

Kernel function.

Raises:

Type Description
TypeError

If kernel is neither a string nor a callable.

ValueError

If a string kernel name is unknown or empty.

Source code in src/pygwrx/core/kernels.py
def get_kernel_function(kernel: KernelLike) -> KernelCallable:
    """Return a built-in kernel by name or validate a custom callable.

    Args:
        kernel: Built-in kernel name or a callable with the signature
            ``kernel(distances, bandwidth) -> weights``.

    Returns:
        callable: Kernel function.

    Raises:
        TypeError: If ``kernel`` is neither a string nor a callable.
        ValueError: If a string kernel name is unknown or empty.
    """
    if callable(kernel):
        return kernel

    if not isinstance(kernel, str):
        raise TypeError(
            "kernel must be a string name or callable; " f"got {type(kernel).__name__}."
        )

    kernel_name = kernel.strip().lower()
    if not kernel_name:
        raise ValueError("kernel name cannot be empty.")

    try:
        return KERNEL_FUNCTIONS[kernel_name]
    except KeyError as exc:
        available = ", ".join(sorted(KERNEL_FUNCTIONS))
        raise ValueError(
            f"Unknown kernel: {kernel!r}. Available kernels: {available}."
        ) from exc

Runnable examples used on this page

examples/core/01_kernels.py
# SPDX-FileCopyrightText: 2026 Jinghao Hu
# SPDX-License-Identifier: MIT

"""Evaluate every public kernel and resolve kernels by name or callable."""

# Allow this script to run directly from any working directory.
import sys
from pathlib import Path

_PROJECT_ROOT = Path(__file__).resolve().parents[2]
_EXAMPLES_ROOT = _PROJECT_ROOT / "examples"
_SRC_ROOT = _PROJECT_ROOT / "src"
for _path in (_SRC_ROOT, _EXAMPLES_ROOT):
    if str(_path) not in sys.path:
        sys.path.insert(0, str(_path))

import numpy as np

from pygwrx.core import (
    bisquare_kernel,
    boxcar_kernel,
    exponential_kernel,
    gaussian_kernel,
    get_kernel_function,
    tricube_kernel,
)

distances = np.array([0.0, 0.5, 1.0, 2.0])
for kernel in (
    gaussian_kernel,
    bisquare_kernel,
    exponential_kernel,
    tricube_kernel,
    boxcar_kernel,
):
    print(kernel.__name__, kernel(distances, bandwidth=1.5))
print("resolved=", get_kernel_function("bisquare").__name__)
print("callable_passthrough=", get_kernel_function(gaussian_kernel) is gaussian_kernel)