Skip to content

Commit

Permalink
add implementation of digital filter (#15)
Browse files Browse the repository at this point in the history
  • Loading branch information
SamProell committed Aug 18, 2024
1 parent f1a6f4b commit 37c1f29
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
*.mp4
*.task
*.tflite

# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
Expand Down
35 changes: 35 additions & 0 deletions src/yarppg/digital_filter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
"""Provides tools for applying digital filters in a real-time application."""

from typing import Sequence

import numpy as np
import scipy.signal


class DigitalFilter:
"""Live digital filter processing one sample at a time.
Args:
b: numerator coefficients obtained from scipy.
a: denominator coefficients obtained from scipy.
xi: first signal value used to initialize the filter state.
"""

def __init__(self, b: np.ndarray, a: np.ndarray, xi: float = 0):
self.b = b
self.a = a
self.reset(xi)

def process(self, x: float) -> float:
"""Process incoming data and update filter state."""
y, self.zi = scipy.signal.lfilter(self.b, self.a, [x], zi=self.zi)
return y[0]

def process_signal(self, x: Sequence[float]) -> np.ndarray:
"""Process an entire signal at once (SciPy's lfilter with current state)."""
y, self.zi = scipy.signal.lfilter(self.b, self.a, x, zi=self.zi)
return y

def reset(self, xi: float = 0):
"""Reset filter state to initial value."""
self.zi = scipy.signal.lfiltic(self.b, self.a, [xi], xi)

0 comments on commit 37c1f29

Please sign in to comment.