ezmsg.sigproc.filter#
Core IIR/FIR filtering infrastructure with BA and SOS coefficient support.
Functions
- filtergen(axis, coefs, coef_type)[source]#
Filter data using the provided coefficients.
- Returns:
- Parameters:
- Return type:
Classes
- class BaseFilterByDesignTransformerUnit(*args, settings=None, **kwargs)[source]#
Bases:
BaseTransformerUnit[SettingsType,AxisArray,AxisArray,FilterByDesignTransformer],Generic[SettingsType,TransformerType]- Parameters:
settings (Settings | None)
- class Filter(*args, settings=None, **kwargs)[source]#
Bases:
BaseTransformerUnit[FilterSettings,AxisArray,AxisArray,FilterTransformer]- Parameters:
settings (Settings | None)
- SETTINGS#
alias of
FilterSettings
- class FilterBaseSettings(axis: str | None = None, coef_type: str = 'ba', use_fast_sosfilt: bool = True, use_mlx_metal: bool = True, mlx_metal_chunk_sizes: tuple[int, ...]=(512, ), thread_min_bytes: int = 1048576, fir_fft_min_taps: int = 64, min_phase: MinPhaseMode = <MinPhaseMode.NONE: 'No kernel modification'>, compensate_delay: bool = False, startup: StartupMode = <StartupMode.CONSTANT: "Constant pre-history at the first sample's value">, startup_max_dur: float | None = 1.0)[source]#
Bases:
Settings- Parameters:
- axis: str | None = None#
Deprecated since version 3.8.
Scheduled for removal in 4.0. The dimension messages accumulate along now comes from
stream_dim; seeezmsg.sigproc.util.deprecation.
- use_fast_sosfilt: bool = True#
If True (default), numpy SOS filtering calls scipy’s Cython kernel directly instead of going through
scipy.signal.sosfilt.Output is bit-identical – same kernel, same dtype promotion, same order of operations – so this is purely a latency optimization. It removes scipy’s fixed ~12-18 us of per-call validation and bookkeeping, which is invisible on offline-sized chunks but dominant online: measured 59.9% of the call at 16 channels x 30 samples, 51.0% at 32x30, 16.6% at 256x30, 4.1% at 256x128.
The fast path depends on a private scipy entry point. It is verified against the public function once per process, and falls back automatically if the private kernel is missing or disagrees. Set False to force the public path.
- use_mlx_metal: bool = True#
If True (default), SOS filtering on MLX inputs runs on the GPU via the bundled Metal kernel (
sosfilt_mlx_metal) instead of round-tripping through scipy. Set to False to fall back to the scipy path (bit-exact with numpy at the cost of CPU round-trips and ~5-8x slowdown).
- mlx_metal_chunk_sizes: tuple[int, ...] = (512,)#
Allowable compile-time chunk sizes for SOS Metal kernels. The smallest size that fits the remaining samples is selected on each launch; otherwise the largest size is repeated. Specializations compile lazily on first use. Values must be in
[1, 512].
- thread_min_bytes: int = 1048576#
Chunk size (bytes) at or above which scipy IIR filtering is split across threads on a non-sample axis. Channels are independent recurrences, so the result is bit-identical to the single-threaded call.
Only large chunks benefit: scipy’s filters are single-threaded C loops, and below ~1 MB the dispatch cost makes threading a net loss (measured 0.23x at 30 samples x 256 channels, 4.5x at 8192). The default keeps online-sized chunks single-threaded while letting offline blocks use the cores. Set to 0 to disable threading entirely.
- fir_fft_min_taps: int = 64#
Tap count at or above which a numpy FIR filter is applied by FFT convolution instead of scipy.ndimage’s C-level correlation.
Neither wins everywhere. Measured on 256 channels (best FFT vs ndimage), the FFT is 1.3-6.8x faster at 129-513 taps while ndimage is 1.6-3.0x faster at 17-33 taps, with the crossover near 64 taps.
The two differ in more than speed, and the difference matters if you rely on an offline run reproducing an online one exactly:
The time-domain path is chunk-size invariant – filtering in chunks of 250, chunks of 333, or one shot gives bit-identical output.
The FFT path is not. The transform length depends on the chunk length, so a different chunking gives a different rounding: measured 2.6e-07 relative in float32 (~7e-16 in float64).
Both match scipy’s
lfilterto roundoff, so this is about reproducibility across chunkings rather than accuracy. Set this very high to force the time-domain path everywhere and keep FIR output chunk-invariant.
- min_phase: MinPhaseMode = 'No kernel modification'#
If not NONE, convert the designed FIR taps to minimum phase (see
min_phase_kernel()), trading the linear-phase delay of(n_taps - 1) / 2samples for a much shorter, frequency-dependent one.HILBERT and HOMOMORPHIC return a half-length kernel whose magnitude response is the square root of the designed one – e.g. 40 dB of stopband attenuation becomes about 20 dB. Use HOMOMORPHICFULL when the filter must keep its design response.
Only FIR designs with
coef_type="ba"can be converted; any other combination raisesValueErrorrather than ignoring the setting.
- compensate_delay: bool = False#
If True, subtract the FIR filter’s delay (see
kernel_delay()) from the stream axis offset of each output message, so samples are stamped with the time of the content they carry. The samples still arrive late; only their timestamps move.The delay is exact for linear-phase filters and the envelope delay at the passband peak otherwise (e.g. after
min_phase). IIR and SOS filters have no single delay and raiseValueError. The delay is logged at info level whether or not it is compensated.
- startup: StartupMode = "Constant pre-history at the first sample's value"#
What the filter assumes about the signal before the first sample, at start and after every reset.
CONSTANT (default): a constant pre-history at the first sample’s value. Removes the step transient from a DC offset, but oscillating content still takes the filter’s full settling time to come through. This is what SciPy documents (
lfilter_zi * x[0]) and what online EEG tools do; prefer it for band-pass filters.FIRST_CHUNK: build the state from a synthetic pre-history, the odd reflection of the first samples about the first one (as
scipy.signal.filtfilt()pads), so the filter starts as if it had been running on a signal that joins the real one in value and slope. The pad is taken from the first message alone, so no latency is added, but the output depends on how long that message is: a short first chunk primes little.BUFFERED: like FIRST_CHUNK, but output is withheld (zero-length messages are emitted) until enough samples have arrived for the full pad, then everything held is released in one message stamped with the first held sample’s time. The output does not depend on chunking.
The pad length is inferred from the filter:
taps - 1for an FIR, and for an IIR the samples its slowest pole takes to decay to 1e-3. It is capped bystartup_max_dur. Requires a LinearAxis on the stream dimension.The reflection matches the signal’s value and slope at the first sample, so it removes the start-up transient of offsets and drifts. It helps a pass-band oscillation only if the stream starts near the oscillation’s mean: started away from it, the reflection carries a DC step of
2 * (x[0] - mean)and the transient can be longer than with CONSTANT.
- startup_max_dur: float | None = 1.0#
Upper limit, in seconds, on the start-up pad (see
startup); None for no limit. Bounds the latency of BUFFERED start-up for narrow-band IIR filters, whose settling time can be long.
- __init__(axis=None, coef_type='ba', use_fast_sosfilt=True, use_mlx_metal=True, mlx_metal_chunk_sizes=(512,), thread_min_bytes=1048576, fir_fft_min_taps=64, min_phase=MinPhaseMode.NONE, compensate_delay=False, startup=StartupMode.CONSTANT, startup_max_dur=1.0)#
- class FilterByDesignTransformer(*args, **kwargs)[source]#
Bases:
BaseStatefulTransformer[SettingsType,AxisArray,AxisArray,FilterByDesignState],ABC,Generic[SettingsType,FilterCoefsType]Abstract base class for filter design transformers.
- property delay_samples: float | None#
FIR delay of the designed filter in samples; None before it is designed, or if it is IIR or SOS.
- class FilterSettings(axis: str | None = None, coef_type: str = 'ba', use_fast_sosfilt: bool = True, use_mlx_metal: bool = True, mlx_metal_chunk_sizes: tuple[int, ...]=(512, ), thread_min_bytes: int = 1048576, fir_fft_min_taps: int = 64, min_phase: MinPhaseMode = <MinPhaseMode.NONE: 'No kernel modification'>, compensate_delay: bool = False, startup: StartupMode = <StartupMode.CONSTANT: "Constant pre-history at the first sample's value">, startup_max_dur: float | None = 1.0, coefs: FilterCoefficients | None = None)[source]#
Bases:
FilterBaseSettings- Parameters:
axis (str | None)
coef_type (str)
use_fast_sosfilt (bool)
use_mlx_metal (bool)
thread_min_bytes (int)
fir_fft_min_taps (int)
min_phase (MinPhaseMode)
compensate_delay (bool)
startup (StartupMode)
startup_max_dur (float | None)
coefs (FilterCoefficients | None)
- coefs: FilterCoefficients | None = None#
The pre-calculated filter coefficients.
- __init__(axis=None, coef_type='ba', use_fast_sosfilt=True, use_mlx_metal=True, mlx_metal_chunk_sizes=(512,), thread_min_bytes=1048576, fir_fft_min_taps=64, min_phase=MinPhaseMode.NONE, compensate_delay=False, startup=StartupMode.CONSTANT, startup_max_dur=1.0, coefs=None)#
- Parameters:
axis (str | None)
coef_type (str)
use_fast_sosfilt (bool)
use_mlx_metal (bool)
thread_min_bytes (int)
fir_fft_min_taps (int)
min_phase (MinPhaseMode)
compensate_delay (bool)
startup (StartupMode)
startup_max_dur (float | None)
coefs (FilterCoefficients | None)
- Return type:
None
- class FilterTransformer(*args, **kwargs)[source]#
Bases:
BaseStatefulTransformer[FilterSettings,AxisArray,AxisArray,FilterState]Filter data using the provided coefficients.
- property delay_samples: float | None#
FIR delay in samples (see
FilterBaseSettings.compensate_delay); None before the first message after a coefficient change, and for IIR or SOS filters.
- update_coefficients(coefs, coef_type=None)[source]#
Update filter coefficients.
If the new coefficients have the same length as the current ones, only the coefficients are updated. If the lengths differ, the filter state is also reset to handle the new filter order.
- Parameters:
coefs (FilterCoefficients | tuple[NDArray, NDArray] | NDArray) – New filter coefficients
coef_type (str | None)
- Return type:
None