Skip to content

OffsetCode

from tensorsig.offset_coded_signatures.codes import OffsetCode

A separable offset code A: U_R -> W.

The matrix has shape (window, dimension) and acts identically on every signal channel. Temporal degrees are present only when the code carries a certified Pascal/Newton filtration.

Bind an arbitrary matrix as an ungraded matrix code.

Source code in src/tensorsig/offset_coded_signatures/codes.py
def __init__(self, matrix: Tensor) -> None:
    """Bind an arbitrary matrix as an ungraded matrix code."""
    _floating_matrix(matrix, "matrix", 2)
    owned = _owned_matrix(matrix)
    object.__setattr__(self, "_matrix", owned)
    object.__setattr__(self, "_family", "matrix")
    object.__setattr__(self, "_temporal_degrees", None)
    object.__setattr__(self, "_pascal_factor", None)
    object.__setattr__(self, "_pascal_raw", False)
    self.__post_init__()

family property

family: _CodeFamily

Construction family and associated semantic guarantees.

matrix property

matrix: Tensor

Code matrix; fixed matrices are returned as defensive copies.

temporal_degrees property

temporal_degrees: tuple[int, ...] | None

Certified Pascal/Newton filtration degrees, when available.

pascal classmethod

pascal(window: int, dimension: int, *, orthonormal: bool = True, device: device | str | None = None, dtype: dtype | None = None) -> 'OffsetCode'

Return a certified Pascal/Newton offset code.

Source code in src/tensorsig/offset_coded_signatures/codes.py
@classmethod
def pascal(
    cls,
    window: int,
    dimension: int,
    *,
    orthonormal: bool = True,
    device: torch.device | str | None = None,
    dtype: torch.dtype | None = None,
) -> "OffsetCode":
    """Return a certified Pascal/Newton offset code."""
    _positive_integer(window, "window")
    _positive_integer(dimension, "dimension")
    if not isinstance(orthonormal, bool):
        raise TypeError("orthonormal must be a boolean.")
    if dimension > window:
        raise ValueError("dimension must not exceed window.")
    matrix, factor = _pascal_matrix(
        window,
        dimension,
        orthonormal=orthonormal,
        device=device,
        dtype=dtype,
    )
    return cls._certified(
        matrix,
        family="pascal",
        temporal_degrees=tuple(range(dimension)),
        pascal_factor=factor,
        pascal_raw=not orthonormal,
    )

constant classmethod

constant(window: int, *, device: device | str | None = None, dtype: dtype | None = None) -> 'OffsetCode'

Return the degree-zero Pascal code that forgets relative offsets.

Source code in src/tensorsig/offset_coded_signatures/codes.py
@classmethod
def constant(
    cls,
    window: int,
    *,
    device: torch.device | str | None = None,
    dtype: torch.dtype | None = None,
) -> "OffsetCode":
    """Return the degree-zero Pascal code that forgets relative offsets."""
    _positive_integer(window, "window")
    dtype = torch.get_default_dtype() if dtype is None else dtype
    if not dtype.is_floating_point:
        raise ValueError("dtype must be floating-point.")
    return cls._certified(
        torch.ones(window, 1, device=device, dtype=dtype),
        family="pascal",
        temporal_degrees=(0,),
        pascal_factor=torch.ones(1, 1, dtype=torch.float64),
        pascal_raw=True,
    )

identity classmethod

identity(window: int, *, device: device | str | None = None, dtype: dtype | None = None) -> 'OffsetCode'

Return full physical offset retention.

Source code in src/tensorsig/offset_coded_signatures/codes.py
@classmethod
def identity(
    cls,
    window: int,
    *,
    device: torch.device | str | None = None,
    dtype: torch.dtype | None = None,
) -> "OffsetCode":
    """Return full physical offset retention."""
    _positive_integer(window, "window")
    dtype = torch.get_default_dtype() if dtype is None else dtype
    if not dtype.is_floating_point:
        raise ValueError("dtype must be floating-point.")
    return cls._certified(
        torch.eye(window, device=device, dtype=dtype),
        family="identity",
    )

structured classmethod

structured(window: int, dimension: int, *, kind: str = 'dct', include_constant: bool = True, center: bool = False, normalize: bool = False, positive_count: int | None = None, seed: int = 0, device: device | str | None = None, dtype: dtype | None = None) -> 'OffsetCode'

Return a fixed structured code without inferred Newton grading.

Source code in src/tensorsig/offset_coded_signatures/codes.py
@classmethod
def structured(
    cls,
    window: int,
    dimension: int,
    *,
    kind: str = "dct",
    include_constant: bool = True,
    center: bool = False,
    normalize: bool = False,
    positive_count: int | None = None,
    seed: int = 0,
    device: torch.device | str | None = None,
    dtype: torch.dtype | None = None,
) -> "OffsetCode":
    """Return a fixed structured code without inferred Newton grading."""
    _positive_integer(window, "window")
    _positive_integer(dimension, "dimension")
    if not isinstance(kind, str):
        raise TypeError("kind must be a string.")
    for name, value in (
        ("include_constant", include_constant),
        ("center", center),
        ("normalize", normalize),
    ):
        if not isinstance(value, bool):
            raise TypeError(f"{name} must be a boolean.")
    if not isinstance(seed, int) or isinstance(seed, bool):
        raise TypeError("seed must be an integer.")
    if positive_count is not None and (
        not isinstance(positive_count, int) or isinstance(positive_count, bool)
    ):
        raise TypeError("positive_count must be an integer or None.")
    if window < 1 or dimension < 1 or dimension > window:
        raise ValueError(
            "window and dimension must satisfy 1 <= dimension <= window."
        )
    if kind not in _STRUCTURED_KINDS:
        choices = ", ".join(sorted(_STRUCTURED_KINDS))
        raise ValueError(f"kind must be one of: {choices}.")
    dtype = _output_dtype(dtype)
    nonconstant = dimension - int(include_constant)
    if nonconstant < 0:
        raise ValueError("dimension is too small for a constant column.")
    if kind == "constant" and dimension != 1:
        raise ValueError("constant codes have dimension one.")
    columns = []
    if include_constant:
        columns.append(torch.ones(window, 1, dtype=dtype))
    structured = _structured_columns(
        kind,
        window,
        nonconstant,
        include_constant=include_constant,
        positive_count=positive_count,
        seed=seed,
        dtype=dtype,
    )
    if center:
        structured = _center_columns(structured)
    if normalize:
        structured = _normalize_columns(structured)
    if structured.shape[1]:
        columns.append(structured)
    matrix = torch.cat(columns, dim=1).to(device=device)
    return cls._certified(matrix, family="structured")

shift_operator

shift_operator(stride: int = 1) -> Tensor

Return the exact backward rebase for a sliding-window update.

If A is this code's matrix, the returned operator L satisfies A[stride:] @ L == A[:-stride] up to storage-dtype rounding. Thus a surviving letter formerly at offset r + stride is relabelled to offset r. Codes without this finite shift closure are rejected.

Source code in src/tensorsig/offset_coded_signatures/codes.py
def shift_operator(self, stride: int = 1) -> Tensor:
    """Return the exact backward rebase for a sliding-window update.

    If ``A`` is this code's matrix, the returned operator ``L`` satisfies
    ``A[stride:] @ L == A[:-stride]`` up to storage-dtype rounding. Thus a
    surviving letter formerly at offset ``r + stride`` is relabelled to
    offset ``r``. Codes without this finite shift closure are rejected.
    """
    if self._pascal_factor is None:
        return _exact_shift_operator(self._matrix, stride).clone()
    _positive_integer(stride, "stride")
    if stride >= self.window:
        raise ValueError("stride must be smaller than the code window.")
    return self._pascal_shift_operator(-stride).to(
        device=self._matrix.device, dtype=self._matrix.dtype
    )

to

to(device: device | str | None = None, dtype: dtype | None = None) -> 'OffsetCode'

Return the same semantic code on another device or dtype.

Source code in src/tensorsig/offset_coded_signatures/codes.py
def to(
    self,
    device: torch.device | str | None = None,
    dtype: torch.dtype | None = None,
) -> "OffsetCode":
    """Return the same semantic code on another device or dtype."""
    matrix = self._matrix.to(device=device, dtype=dtype)
    return OffsetCode._certified(
        matrix,
        self.family,
        self.temporal_degrees,
        pascal_factor=self._pascal_factor,
        pascal_raw=self._pascal_raw,
    )

as_alphabet_map

as_alphabet_map(channels: int) -> 'AlphabetMap'

Return the channel-equivariant A tensor I alphabet map.

Source code in src/tensorsig/offset_coded_signatures/codes.py
def as_alphabet_map(self, channels: int) -> "AlphabetMap":
    """Return the channel-equivariant ``A tensor I`` alphabet map."""
    _positive_integer(channels, "channels")
    eye = torch.eye(channels, device=self._matrix.device, dtype=self._matrix.dtype)
    matrix = self._matrix[:, None, None, :] * eye[None, :, :, None]
    return AlphabetMap(
        matrix.reshape(self.window, channels, channels * self.dimension)
    )