-
Notifications
You must be signed in to change notification settings - Fork 3
/
one_euro_filter.py
50 lines (39 loc) · 1.43 KB
/
one_euro_filter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import numpy as np
from time import time
def smoothing_factor(t_e, cutoff):
r = 2 * np.pi * cutoff * t_e
return r / (r + 1)
def exponential_smoothing(a, x, x_prev):
return a * x + (1 - a) * x_prev
class OneEuroFilter:
def __init__(self, x0, dx0=0.0, min_cutoff=1.0, beta=0.0,
d_cutoff=1.0):
"""Initialize the one euro filter."""
# The parameters.
self.data_shape = x0.shape
self.min_cutoff = np.full(x0.shape, min_cutoff)
self.beta = np.full(x0.shape, beta)
self.d_cutoff = np.full(x0.shape, d_cutoff)
# Previous values.
self.x_prev = x0.astype(np.float)
self.dx_prev = np.full(x0.shape, dx0)
self.t_prev = time()
def __call__(self, x):
"""Compute the filtered signal."""
assert x.shape == self.data_shape
t = time()
t_e = t - self.t_prev
t_e = np.full(x.shape, t_e)
# The filtered derivative of the signal.
a_d = smoothing_factor(t_e, self.d_cutoff)
dx = (x - self.x_prev) / t_e
dx_hat = exponential_smoothing(a_d, dx, self.dx_prev)
# The filtered signal.
cutoff = self.min_cutoff + self.beta * np.abs(dx_hat)
a = smoothing_factor(t_e, cutoff)
x_hat = exponential_smoothing(a, x, self.x_prev)
# Memorize the previous values.
self.x_prev = x_hat
self.dx_prev = dx_hat
self.t_prev = t
return x_hat