Skip to content

signature_sparse

from tensorsig.classical.sparse import signature_sparse

Compute sparse path signature for paths with repeated points.

Uses Chen's identity to combine segment signatures, skipping zero increments (repeated points). For a path with M knots, computes the signature as the ordered tensor product of M-1 segment exponentials.

Parameters:

Name Type Description Default
path Tensor

Tensor of shape (batch, T, D_aug) representing batched paths. For a single path, pass path.unsqueeze(0) to add a batch dimension.

required
depth int

Maximum depth L for truncation (>=1).

required
eps float

Threshold for change detection. Default is 0.0.

0.0
lengths Tensor

Tensor of shape (batch,) with valid lengths in a padded batch.

Best practice (recommended): pad by repeating the last valid point of each path (see pad_paths_correctly). This padding produces zero increments on the tail, so it does not change the signature and you can usually leave lengths=None.

If you instead pad with zeros/any other values, you must pass lengths to ignore the padded tail (otherwise padding can introduce spurious increments and change the result).

Default is None.

None
return_levels bool

If True, return list of level tensors. If False, return flattened signature. Default is False.

False
stream bool

If True, return signatures at each step along the path. If False, return only the final signature. Default is False.

False

Returns:

Type Description
Tensor or list[Tensor]

If return_levels=False: Tensor of shape (batch, dim_sig) or (batch, T-1, dim_sig) (if stream=True).

If return_levels=True: List of tensors, either final signatures or streams depending on stream argument.

Examples:

>>> import torch
>>> from tensorsig.classical.sparse import signature_sparse
>>>
>>> # Path with repeats
>>> path = torch.tensor([
...     [[0.0, 0.0], [0.0, 0.0], [1.0, 1.0], [1.0, 1.0], [2.0, 0.0]]
... ])
>>> sig = signature_sparse(path, depth=2)
>>> sig.shape
torch.Size([1, 6])
>>> stream_sig = signature_sparse(path, depth=2, stream=True)
>>> stream_sig.shape
torch.Size([1, 4, 6])
Source code in src/tensorsig/classical/sparse_signature.py
def signature_sparse(
    path: Tensor,
    depth: int,
    eps: float = 0.0,
    lengths: Tensor | None = None,
    return_levels: bool = False,
    stream: bool = False,
) -> Tensor | list[Tensor]:
    """Compute sparse path signature for paths with repeated points.

    Uses Chen's identity to combine segment signatures, skipping zero
    increments (repeated points). For a path with M knots, computes the
    signature as the ordered tensor product of M-1 segment exponentials.

    Parameters
    ----------
    path : Tensor
        Tensor of shape ``(batch, T, D_aug)`` representing batched paths.
        For a single path, pass ``path.unsqueeze(0)`` to add a batch dimension.
    depth : int
        Maximum depth L for truncation (>=1).
    eps : float, optional
        Threshold for change detection. Default is 0.0.
    lengths : Tensor, optional
        Tensor of shape ``(batch,)`` with valid lengths in a padded batch.

        **Best practice (recommended)**: pad by repeating the last valid point
        of each path (see
        [`pad_paths_correctly`][tensorsig.classical.sparse.pad_paths_correctly]).
        This padding produces
        zero increments on the tail, so it does not change the signature and
        you can usually leave ``lengths=None``.

        If you instead pad with zeros/any other values, you must pass ``lengths``
        to ignore the padded tail (otherwise padding can introduce spurious
        increments and change the result).

        Default is None.
    return_levels : bool, optional
        If True, return list of level tensors. If False, return flattened
        signature. Default is False.
    stream : bool, optional
        If True, return signatures at each step along the path. If False,
        return only the final signature. Default is False.

    Returns
    -------
    Tensor or list[Tensor]
        If ``return_levels=False``: Tensor of shape
        ``(batch, dim_sig)`` or ``(batch, T-1, dim_sig)`` (if stream=True).

        If ``return_levels=True``: List of tensors, either final signatures
        or streams depending on ``stream`` argument.

    Examples
    --------
    >>> import torch
    >>> from tensorsig.classical.sparse import signature_sparse
    >>>
    >>> # Path with repeats
    >>> path = torch.tensor([
    ...     [[0.0, 0.0], [0.0, 0.0], [1.0, 1.0], [1.0, 1.0], [2.0, 0.0]]
    ... ])
    >>> sig = signature_sparse(path, depth=2)
    >>> sig.shape
    torch.Size([1, 6])
    >>> stream_sig = signature_sparse(path, depth=2, stream=True)
    >>> stream_sig.shape
    torch.Size([1, 4, 6])
    """
    if path.ndim != 3:
        msg = (
            f"Path must be of shape (batch, T, D_aug); got {path.shape}. "
            "Wrap a single path with path.unsqueeze(0)."
        )
        raise ValueError(msg)

    if depth < 1:
        raise ValueError("depth must be >= 1")

    # Compress path by removing repeated points
    compressed_path, knots, knot_counts = compress_path(path, eps=eps, lengths=lengths)
    width = path.shape[2]

    # Compute signature using the vectorized implementation
    # If stream=True, we need the streaming signature of the compressed path
    # to reconstruct the full stream.
    sig_result = _batch_signature(compressed_path, depth=depth, stream=stream)

    if stream:
        # Map compressed stream back to full path
        seq_len = path.shape[1]

        # sig_result is (batch, max_segments, sig_dim)
        # We need to expand to (batch, seq_len-1, sig_dim)
        sig_result = _expand_stream_signature(
            sig_result, knots, seq_len - 1, knot_counts
        )

    if return_levels:
        if stream:
            return _unflatten_stream_signature(sig_result, width=width, depth=depth)
        return _unflatten_signature(sig_result, width=width, depth=depth)
    else:
        return sig_result