Implementing a Savitzky-Golay filter from scratch in pure Python is a bit involved but certainly doable. Here’s a concise implementation that you can use for your real-time speed data filtering.
The Savitzky-Golay filter performs polynomial fitting over a window and smooths the data by polynomials. Here's how you can implement it and use it in your existing code.
First, let's define the Savitzky-Golay filter in its entirety:
def savitzky_golay(y, window_size, order, deriv=0, rate=1):
from math import factorial
try:
window_size = np.abs(np.int(window_size))
order = np.abs(np.int(order))
except ValueError as msg:
raise ValueError("window_size and order have to be of type int")
if window_size % 2 != 1 or window_size < 1:
raise TypeError("window_size size must be a positive odd number")
if window_size < order + 2:
raise TypeError("window_size is too small for the polynomials order")
half_window = (window_size - 1) // 2
b = np.mat([[k**i for i in range(order + 1)] for k in range(-half_window, half_window + 1)])
m = np.linalg.pinv(b).A[deriv] * rate**deriv * factorial(deriv)
firstvals = y[0] - np.abs(y[1:half_window+1][::-1] - y[0])
lastvals = y[-1] + np.abs(y[-half_window-1:-1][::-1] - y[-1])
y = np.concatenate((firstvals, y, lastvals))
return np.convolve(m[::-1], y, mode='valid')
# Example usage
window_size = 5 # Needs to be an odd number
order = 2
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
filtered_data = savitzky_golay(np.array(data), window_size, order)
print(filtered_data)
To integrate this into your existing live data filtering:
class SavitzkyGolayFilter:
def __init__(self, window_size, order):
self.window_size = window_size
self.order = order
self.data = []
def set_initial_value(self, initial_value):
self.data.append(initial_value)
if len(self.data) == 1:
self.data = [initial_value] * self.window_size # Initialize with initial value
def get_filtered_value(self, new_value):
self.data.append(new_value)
if len(self.data) >= self.window_size:
return savitzky_golay(np.array(self.data[-self.window_size:]), self.window_size, self.order)[-1]
else:
return new_value
# Usage in your live data filter
filter = SavitzkyGolayFilter(window_size=5, order=2) # Initialize with desired parameters
if m_idx <= 1:
filter.set_initial_value(m_speed)
m_speed_filtered = filter.get_filtered_value(m_speed)
else:
arr_speed.append(m_speed_filtered)
Make sure to adjust the window_size and order parameters to fit your needs. Keep in mind this is a simplified implementation, and real-time processing might need additional considerations for performance and edge case handling.
Note: While this example uses NumPy for matrix operations, this is as minimal as possible, avoiding other external dependencies. If you strictly want no external libraries, implementing matrix inversion and convolution from scratch is required, but it is recommended to leverage existing optimized libraries such as NumPy for these purposes.