Skip to content

SignaturePlan

from tensorsig.offset_coded_signatures.plans import SignaturePlan

Bases: _CompiledPlan

A code-bound local signature coordinate plan.

word_indices property

word_indices: tuple[Tensor, ...]

Return zero-based channel-major words for chronological levels.

temporal_indices property

temporal_indices: tuple[Tensor, ...]

Return zero-based temporal letters for chronological levels.

channel_indices property

channel_indices: tuple[Tensor, ...]

Return zero-based channel letters for chronological levels.

state_count property

state_count: int | None

Unique prefix states, including the empty word, used by evaluation.

evaluate

evaluate(windows: Tensor) -> Tensor

Evaluate the compiled coordinates on increment windows.

Source code in src/tensorsig/offset_coded_signatures/plans.py
def evaluate(self, windows: Tensor) -> Tensor:
    """Evaluate the compiled coordinates on increment windows."""
    return self._evaluate(windows, self._matrix_tensor())

contract

contract(windows: Tensor, weight: Tensor) -> Tensor

Contract features with (outputs, features) weights.

Source code in src/tensorsig/offset_coded_signatures/plans.py
def contract(self, windows: Tensor, weight: Tensor) -> Tensor:
    """Contract features with ``(outputs, features)`` weights."""
    if weight.ndim != 2 or weight.shape[1] != self.feature_count:
        raise ValueError(f"weight must have shape (outputs, {self.feature_count}).")
    features = self.evaluate(windows)
    return features @ weight.to(device=features.device, dtype=features.dtype).T

reconstruct

reconstruct(features: Tensor) -> tuple[Tensor, ...]

Reconstruct dense coded tensor levels from a lossless plan.

Source code in src/tensorsig/offset_coded_signatures/plans.py
def reconstruct(self, features: Tensor) -> tuple[Tensor, ...]:
    """Reconstruct dense coded tensor levels from a lossless plan."""
    self._validate_features(features)
    if self.coordinates == "dense":
        return tuple(
            features[..., feature_slice].reshape(
                *features.shape[:-1],
                *([self.output_dimension] * depth),
            )
            for depth, feature_slice in zip(
                self.depths,
                self.level_slices,
                strict=True,
            )
        )
    if not self.is_lossless:
        raise ValueError("Only lossless chronological plans have a decoder.")
    levels = []
    for depth, feature_slice, level in zip(
        self.depths,
        self.level_slices,
        self._levels,
        strict=True,
    ):
        if (
            self.certification == "structural"
            and level.feature_count == level.ambient_dimension
        ):
            values = features[..., feature_slice]
        else:
            if level.ambient_dimension > torch.iinfo(torch.long).max:
                raise OverflowError(
                    "Dense reconstruction exceeds int64 indexing; use reconstruct_words instead."
                )
            indices = torch.arange(level.ambient_dimension, dtype=torch.long)
            words = torch.stack(
                [
                    (indices // self.output_dimension**power)
                    % self.output_dimension
                    for power in reversed(range(depth))
                ],
                dim=1,
            )
            values = self.reconstruct_words(features, words)
        levels.append(
            values.reshape(*features.shape[:-1], *([self.output_dimension] * depth))
        )
    return tuple(levels)

reconstruct_words

reconstruct_words(features: Tensor, words: Tensor) -> Tensor

Recover requested ordinary signature coordinates at one depth.

words has shape (Q, m) and uses the zero-based channel-major letters of word_indices. Results have shape (..., Q) in request order, including duplicates. Retained words can be looked up on lossy plans; decoding omitted words requires a complete chart at depth m.

Source code in src/tensorsig/offset_coded_signatures/plans.py
def reconstruct_words(self, features: Tensor, words: Tensor) -> Tensor:
    """Recover requested ordinary signature coordinates at one depth.

    ``words`` has shape ``(Q, m)`` and uses the zero-based channel-major
    letters of ``word_indices``. Results have shape ``(..., Q)`` in request
    order, including duplicates. Retained words can be looked up on lossy
    plans; decoding omitted words requires a complete chart at depth ``m``.
    """
    self._validate_features(features)
    if (
        not isinstance(words, Tensor)
        or words.ndim != 2
        or words.dtype
        not in {
            torch.uint8,
            torch.int8,
            torch.int16,
            torch.int32,
            torch.int64,
        }
    ):
        raise ValueError("words must be a two-dimensional integer tensor.")
    depth = words.shape[1]
    if depth not in self.depths:
        raise ValueError("The requested word depth must be present in the plan.")
    words = words.detach().to(device="cpu", dtype=torch.long)
    if torch.any(words < 0) or torch.any(words >= self.output_dimension):
        raise ValueError("Word letters must lie in the plan's alphabet.")
    if not len(words):
        return features[..., :0]
    position = self.depths.index(depth)
    source = features[..., self.level_slices[position]]
    if self.coordinates == "chronological":
        level = self._levels[position]
        lookup = {word: index for index, word in enumerate(level.words)}
        targets = tuple(map(tuple, words.tolist()))
        if all(word in lookup for word in targets):
            indices = torch.tensor(
                [lookup[word] for word in targets], device=features.device
            )
            return source.index_select(-1, indices)
        if not level.is_lossless:
            raise ValueError(
                "Decoding omitted words requires a complete chart at the requested depth."
            )
        if self.certification == "structural":
            decoder = self._decoder_cache.get(depth)
            if decoder is None:
                assert isinstance(self.mapping, OffsetCode)
                decoder = _PascalDecoder(self.mapping, level.letters)
                self._decoder_cache[depth] = decoder
            assert isinstance(decoder, _PascalDecoder)
            return decoder.decode(source, words)
    if self.output_dimension**depth > torch.iinfo(torch.long).max:
        raise OverflowError("Ambient word indices exceed int64 storage.")
    indices = torch.zeros(len(words), dtype=torch.long)
    for letter in words.T:
        indices = indices * self.output_dimension + letter
    if self.coordinates == "dense":
        return source.index_select(-1, indices.to(device=features.device))
    basis = self._levels[position]
    if basis.reconstruction_matrix is None:
        cached = self._decoder_cache.get(depth)
        if cached is None:
            assert isinstance(self.mapping, OffsetCode)
            cached = _build_chronological_level(
                self.mapping._runtime_matrix(), channels=self.channels, depth=depth
            )
            self._decoder_cache[depth] = cached
        assert isinstance(cached, _ChronologicalLevel)
        basis = cached
    assert basis.reconstruction_matrix is not None
    decoder_rows = basis.reconstruction_matrix.index_select(
        0, indices.to(basis.reconstruction_matrix.device)
    )
    return source @ decoder_rows.to(device=features.device, dtype=features.dtype).T