Skip to content

causal_fir

from tensorsig.augmentations import causal_fir

Apply a causal finite-impulse-response filter bank.

Parameters:

Name Type Description Default
path Tensor

Path points with shape (batch, length, in_channels).

required
weight Tensor

Filter weights with shape (num_filters, in_channels, max_lag + 1). weight[..., 0] multiplies the current point and weight[..., lag] multiplies the point at that causal lag.

required
bias Tensor

Per-filter bias with shape (num_filters,).

None
padding ('repeat', 'zero')

Values before the first point either repeat that point or are zero.

"repeat"

Returns:

Type Description
Tensor

Filtered points with shape (batch, length, num_filters).

Source code in src/tensorsig/augmentations/__init__.py
def causal_fir(
    path: Tensor,
    weight: Tensor,
    bias: Tensor | None = None,
    *,
    padding: str = "repeat",
) -> Tensor:
    """Apply a causal finite-impulse-response filter bank.

    Parameters
    ----------
    path : Tensor
        Path points with shape ``(batch, length, in_channels)``.
    weight : Tensor
        Filter weights with shape ``(num_filters, in_channels, max_lag + 1)``.
        ``weight[..., 0]`` multiplies the current point and ``weight[..., lag]``
        multiplies the point at that causal lag.
    bias : Tensor, optional
        Per-filter bias with shape ``(num_filters,)``.
    padding : {"repeat", "zero"}, optional
        Values before the first point either repeat that point or are zero.

    Returns
    -------
    Tensor
        Filtered points with shape ``(batch, length, num_filters)``.
    """
    _, _, in_channels = _validate_sequence(path)
    if weight.ndim != 3:
        raise ValueError(
            "weight must have shape (num_filters, in_channels, max_lag + 1)."
        )
    num_filters, weight_channels, kernel_width = weight.shape
    if num_filters < 1:
        raise ValueError("weight must contain at least one filter.")
    if weight_channels != in_channels:
        raise ValueError(
            f"Expected weight.shape[1] == {in_channels}, got {weight_channels}."
        )
    if kernel_width < 1:
        raise ValueError("weight must contain at least one lag coefficient.")
    if bias is not None and tuple(bias.shape) != (num_filters,):
        raise ValueError(f"bias must have shape ({num_filters},).")

    padding = _normalize_padding(padding)
    max_lag = kernel_width - 1
    channel_first = path.movedim(1, 2)
    if max_lag:
        if padding == "zero":
            channel_first = F.pad(channel_first, (max_lag, 0))
        else:
            channel_first = F.pad(channel_first, (max_lag, 0), mode="replicate")

    kernel = weight.to(device=path.device, dtype=path.dtype).flip(-1)
    filter_bias = (
        None if bias is None else bias.to(device=path.device, dtype=path.dtype)
    )
    return F.conv1d(channel_first, kernel, bias=filter_bias).movedim(1, 2)