Source code for gpype.backend.transform.fft

from __future__ import annotations

import numpy as np
from scipy.signal import get_window

from ...common._private import channels
from ...common._private.naming import node_label
from ...common.constants import Constants
from ..core.io_node import IONode

#: Default input port identifier
PORT_IN = Constants.Defaults.PORT_IN
#: Default output port identifier
PORT_OUT = Constants.Defaults.PORT_OUT


[docs] class FFT(IONode): """Fast Fourier Transform node for frequency domain analysis. Performs windowed FFT on input data with configurable window size, overlap, and window functions. Uses rolling buffer for continuous processing and proper amplitude scaling for spectral analysis. A channel's unit is unchanged: the output is a one-sided amplitude spectrum, in the same unit as the input signal, not a power spectral density, so no unit conversion applies (D-BATCH-43). """ #: Applied when the author does not choose. Declared rather than #: left as a literal in the constructor body, so the catalog can #: publish it without building an FFT to find out. DEFAULT_WINDOW_FUNCTION: str = "boxcar" DEFAULT_OVERLAP: float = 0.5 # Type annotation for the rolling buffer _buf: np.ndarray
[docs] class Configuration(IONode.Configuration): """Configuration class for FFT parameters."""
[docs] class Keys(IONode.Configuration.Keys): """Configuration key constants for the FFT.""" #: Window size configuration key WINDOW_SIZE = "window_size" #: Window function configuration key WINDOW_FUNCTION = "window_function" #: Overlap configuration key OVERLAP = "overlap" #: Buffer length, defaulting to the window size. Accepted #: through kwargs and stored, so it is declared here rather #: than travelling in the configuration undocumented. FRAME_SIZE = "frame_size"
[docs] def __init__( self, window_size: int, window_function: str = None, overlap: float = None, **kwargs, ): """Initialize FFT transform node. Args: window_size (int): Size of the FFT window in samples. Must be > 1. window_function (str, optional): Name of the window function to apply. Defaults to 'boxcar' (rectangular window). overlap (float, optional): Overlap ratio between consecutive windows, ranging from 0.0 to 1.0. Defaults to 0.5. **kwargs: Additional configuration parameters passed to IONode. Raises: ValueError: If window_size is None, not an integer, or <= 1. ValueError: If overlap is not a float or outside [0, 1] range. """ # Validate window size parameter if window_size is None: raise ValueError("window_size must not be None.") if type(window_size) is not int: raise ValueError("window_size must be integer.") if window_size <= 1: raise ValueError("window_size must be greater than 1.") frame_size = window_size # Accepted so a serialized document round-trips, refused when it # disagrees: the window is (window_size, 1) and the buffer # (frame_size, channels), so any other value fails to broadcast # on the first step() -- a long way from where it was written. supplied = kwargs.pop(Constants.Keys.FRAME_SIZE, frame_size) if supplied != frame_size: raise ValueError( f"frame_size is derived from window_size and must be " f"{frame_size}, not {supplied}. Set window_size instead." ) # Set default window function if not provided if window_function is None: window_function = self.DEFAULT_WINDOW_FUNCTION # Set default overlap if not provided if overlap is None: overlap = self.DEFAULT_OVERLAP # Validate overlap parameter if type(overlap) is not float: raise ValueError("overlap must be float.") if overlap < 0 or overlap > 1: raise ValueError("overlap must be between 0 and 1.") # Calculate step size for overlapping windows # Step size determines how many samples to advance between windows self._step_size = int(np.round(window_size * (1 - overlap))) # Recalculate the actual overlap from the integer step size. The # step advances by the non-overlapping part, so the overlap is # what remains; storing the step ratio would invert the value and # a stored configuration would not round-trip. overlap = 1.0 - self._step_size / window_size # Calculate decimation factor for processing decimation_factor = self._step_size # Derived from window_size and overlap; accepted and checked # for the same reason as frame_size above. supplied = kwargs.pop( self.Configuration.Keys.DECIMATION_FACTOR, decimation_factor ) if supplied != decimation_factor: raise ValueError( f"decimation_factor is derived from window_size and " f"overlap and must be {decimation_factor}, not " f"{supplied}. Set overlap instead." ) # Initialize parent IONode with windowing configuration super().__init__( window_size=window_size, frame_size=frame_size, decimation_factor=decimation_factor, window_function=window_function, overlap=overlap, **kwargs, ) # Initialize internal state variables self._buf = None # Rolling input buffer for windowing self._w = None # Precomputed window function weights self._since_last = 0 # Samples since the last window was emitted
[docs] def setup( self, data: dict[str, np.ndarray], port_context_in: dict[str, dict] ) -> dict[str, dict]: """Set up the FFT node and initialize windowing components. Args: data (dict): Initial data dictionary for port configuration. port_context_in (dict): Input port context information. Returns: dict: Output port context with updated frame size for FFT output. Raises: ValueError: If input frame size is not 1. """ # Call parent setup to get base output context port_context_out = super().setup(data, port_context_in) # The hop between windows is counted in SAMPLES, and a cycle # carries frame_size_in of them. # # This used to demand frame_size_in == 1, because the hop was # applied through ioiocore's is_decimation_step(), which counts # cycles -- the two coincide only at one sample per cycle. The # buffer now ingests every row of a frame and the hop is counted # in samples, so any frame size works. # # One shape genuinely cannot be served: a frame longer than the # hop would cross more than one window boundary in a single # cycle, and only one spectrum can be emitted per cycle. frame_size_in = port_context_in[PORT_IN][Constants.Keys.FRAME_SIZE] if frame_size_in is None: raise ValueError( "FFT needs a frame size in the input context; got none." ) if frame_size_in > self._step_size: raise ValueError( f"FFT advances {self._step_size} samples between windows " f"but a frame carries {frame_size_in}, so a cycle would " f"cross more than one window. Reduce the source's " f"frame_size to {self._step_size} or less, or lower " f"overlap so the step is at least {frame_size_in}." ) self._since_last = 0 # Get configuration parameters frame_size_out = self.config[Constants.Keys.FRAME_SIZE] channel_count = port_context_out[PORT_OUT][ Constants.Keys.CHANNEL_COUNT ] # Initialize rolling buffer for windowing # Shape: (window_size, channel_count) self._buf = np.zeros(shape=(frame_size_out, channel_count)) self._frame_size = frame_size_out sampling_rate = port_context_in[PORT_IN][Constants.Keys.SAMPLING_RATE] frame_rate = sampling_rate / self._step_size # Update the output context. A step emits one row per frequency # bin of the one-sided spectrum, not one row per windowed sample, # so the declared frame size has to be the bin count or every # downstream node sizes its buffers wrongly. bin_count = frame_size_out // 2 + 1 port_context_out[PORT_OUT][Constants.Keys.FRAME_SIZE] = bin_count port_context_out[PORT_OUT][Constants.Keys.FRAME_RATE] = frame_rate # Get window function configuration window_function = self.config[self.Configuration.Keys.WINDOW_FUNCTION] window_size = self.config[self.Configuration.Keys.WINDOW_SIZE] # Create and normalize window function w = get_window(window_function, window_size) w = w / np.sum(w) # Normalize to preserve signal power # Reshape for broadcasting with multi-channel data self._w = w[:, np.newaxis] # Shape: (window_size, 1) # A row is now a frequency bin, not a sample: a marker or gap # naming an input sample would name a meaningless bin # (D-BATCH-86). warning = channels.drop_grid( port_context_out[PORT_OUT], node_label(self) ) if warning: self.log(warning, type=Constants.LogTypes.WARNING) return port_context_out
[docs] def step(self, data: dict[str, np.ndarray]) -> dict[str, np.ndarray]: """Process one frame of data and compute FFT when ready. Args: data (dict): Dictionary containing input data arrays with shape (1, channel_count) for each frame. Returns: dict or None: Dictionary containing FFT amplitude spectrum when decimation step is reached, None otherwise. Output shape is (frequency_bins, channel_count) where frequency_bins is (window_size // 2 + 1). """ # Ingest every row of the frame, oldest first, so the window # sees the signal that actually arrived. Taking only the last row # -- which is what this did while frames were single samples -- # silently decimates the window's content by the frame size. block = data[PORT_IN] rows = block.shape[0] window = self._buf.shape[0] if rows >= window: self._buf[:] = block[-window:] elif rows: self._buf[:-rows] = self._buf[rows:] self._buf[-rows:] = block # Emit once the window has advanced by a whole hop, counted in # samples rather than in cycles. self._since_last += rows if self._since_last < self._step_size: return None self._since_last -= self._step_size # Apply window function to the buffered data # Broadcasting: (window_size, channels) * (window_size, 1) windowed = self._buf * self._w # Compute real FFT (optimized for real-valued signals) # Transpose for FFT: (channels, window_size) -> (channels, freq_bins) fft = np.fft.rfft(windowed.T, axis=1) # Get window size for scaling calculations N = self._frame_size # Create scaling array for proper amplitude normalization scale_arr = np.ones((fft.shape[1],)) scale_arr[1:-1] = 2.0 # Scale non-DC/Nyquist frequencies by 2 scale_arr[0] = 1.0 # DC component (0 Hz) scaled by 1 # Handle Nyquist frequency (only exists for even N) if N % 2 == 0: scale_arr[-1] = 1.0 # Nyquist bin scaled by 1 # Calculate magnitude spectrum # Normalize by window sum to preserve signal power magnitude = np.abs(fft) / np.sum(self._w) # Apply proper amplitude scaling for single-sided spectrum. # scale_arr already carries the factor of two that accounts for the # negative frequencies; a second one here would double every bin. amplitude = magnitude * scale_arr[np.newaxis, :] # Return transposed result: (frequency_bins, channels) return {PORT_OUT: amplitude.T}