CNN-VAD / vad /fir_filter.py
abhishek-sehgal's picture
Add the code to run the spaces
6a9b2e3
import numpy as np
class FIR:
"""
FIR (Finite Impulse Response) filter implementation
Converted from C implementation in FIRFilter.c
"""
def __init__(self, step_size):
"""Initialize the FIR filter"""
self.N = step_size
self.input_buffer = np.zeros(2 * step_size, dtype=float)
def check_range(input_val):
"""Limit the value to the range [-1.0, 1.0]"""
if input_val > 1.0:
return 1.0
elif input_val < -1.0:
return -1.0
else:
return input_val
def init_fir(step_size):
"""Create a new FIR filter instance"""
return FIR(step_size)
def process_fir_filter(fir, input_signal, filter_coefficients):
"""
Process input through the FIR filter
Args:
fir: FIR filter instance
input_signal: Input signal array
filter_coefficients: Filter coefficients array
Returns:
output_signal: Filtered output signal
"""
# Create output array
output = np.zeros(fir.N, dtype=float)
# Update input buffer
fir.input_buffer[: fir.N] = fir.input_buffer[fir.N :]
fir.input_buffer[fir.N :] = input_signal
# Apply FIR filter
for i in range(fir.N):
temp = 0.0
for j in range(len(filter_coefficients)):
idx = fir.N + (i - j)
if idx >= 0 and idx < 2 * fir.N: # Ensure index is in bounds
temp += fir.input_buffer[idx] * filter_coefficients[j]
output[i] = check_range(temp)
return output
def destroy_fir(fir):
"""
Clean up resources (not necessary in Python due to garbage collection)
Included for API compatibility with C code
"""
# In Python, memory management is automatic
pass