6.5 KiB
6.5 KiB
In [ ]:
# FIR Filter anlegen
from scipy import signal
from scipy.fft import fft, fftfreq
import numpy as np
import matplotlib.pyplot as plt
from ipywidgets import interact
def fir_filter(taps, input): # taps, input sind 1d Eingabelisten mit Koeffizienten und Samples
fir=[] # Ausgabeliste anlegen
for j in range(0, len(input) - len(taps)): # Erste Samples (Koeffizientenzahl) zählen nicht zur Filterantwort
fir_i=0
for i in range (len(taps)): # Durch Koeffizienten durchiterieren
taps_i = taps[i] # taps_i ist Laufvariable
fir_i += taps_i*input[j+i] # fir_i ist Laufvariable für Filterergebnis - jeweiliger Koeffizient wird mit dem i-ten Input-Sample der reduzierten Liste j multipliziert
fir.append(fir_i) # hänge Ergebnis an Ergebnisliste an
return fir
[0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0]
In [ ]:
# Chirp Generator
n=3000 #Sampleanzahl
fs=20000 #Samplingrate
f0=100 #Startfrequenz
f1=1000 #Stopfrequenz
t1=n/fs #Chirpdauer (Samples/Samplingrate)
t_chrip = np.linspace(0, t1, n) #Array mit Anzahl der Samples anlegen für Zeitachse
y_chrip = np.round(signal.chirp(t_chrip, f0=f0, f1=f1, t1=t1, method='linear')*(2**15-1)).astype(int) #Chirp erstellen, auf Ganzzahlen runden, auf 16 Bit Integer skalieren
# Erste 4 Samples wegschneiden
cutsamps = 45
y_chrip = y_chrip[cutsamps:]
t_chrip = t_chrip[cutsamps:]
# Doppelt so langes Signal mit abwechselnd Original- und invertierten Werten - Struktur für Symmetrie und 2-Kanal-Systeme
y_chrip_interleaved = np.empty((2*y_chrip.size), dtype=y_chrip.dtype)pa
y_chrip_interleaved[0::2] = y_chrip
y_chrip_interleaved[1::2] = -1*y_chrip[::-1]
# Chirp in Header-Datei schreiben, welche über PCM eingelesen werden kann
file_str= f"#define CHIRP_DATA_SAMPLE_RATE {int(fs)}\n"\
"#define CHIRP_DATA_LEN"f" {y_chrip.size}" "\n"\
"#define CHIRP_DATA_INTERLEAVED_LEN"f" {y_chrip_interleaved.size}" "\n"\
"#define CHIRP_DATA {" + ",".join(y_chrip.astype(str)) +"}\n"\
"#define CHIRP_DATA_INTERLEAVED_INVERTED {" + ",".join(y_chrip_interleaved.astype(str)) +"}" "\n"
with open("pcm_chirp/include/chirp_data.h", "w") as f:
f.write(file_str)In [ ]:
# ScyPyFIR Filter anlegenIn [ ]:
# Vergleich und Plot
%matplotlib widget
b=signal.firwin(20, 100, fs=fs)
y_lfiltered = signal.lfilter(b, [1.0], y_chrip)
yf=fft(y_lfiltered)
xf = fftfreq(n, t1/n)[:n//2]
cols = 1
rows = 3
fig = plt.figure(1)
ax1 = fig.add_subplot(rows, cols, 1)
line1, = ax1.plot([0], ".-", label = "chrip")
ax2 = fig.add_subplot(rows, cols, 2)
line2, = ax2.plot([0], label="chrip filtered signal.lfilter")
ax3 = fig.add_subplot(rows, cols, 3)
line3, = ax3.plot([0], label="own fir implementation")
def update(numtaps = 40, f_cut=100):
# Calculate the filter coefficients for given paramters
b=signal.firwin(numtaps, f_cut, fs=fs)
print(f"Filter coeffs for {numtaps} tabs and {f_cut}Hz cutoff are:\n", b)
bits=16
if min(b)<0:
bits=bits-1
print(f"Filter coeffs converted to Q1.{bits}bit int are :\n",
", ".join(
np.array(np.array(np.round(b*(2**(bits)-1)), dtype=np.int32), dtype=str)
)
)
# plot the chirp
line1.set_data(range(len(y_chrip)), y_chrip)
ax1.set_xlim(0, len(y_chrip))
ax1.set_ylim(min(y_chrip), max(y_chrip))
# Apply the coefficents with scipy function
y_lfiltered = signal.lfilter(b, [1.0], y_chrip)
line2.set_data(range(len(y_lfiltered)), y_lfiltered)
ax2.set_xlim(0, len(y_lfiltered))
ax2.set_ylim(min(y_lfiltered), max(y_lfiltered))
# yf=2.0/n*np.abs(fft(y_chrip[:n//2]))
# xf = fftfreq(n, t1/n)[:n//2]
data = simple_fir(b, y_chrip)
line3.set_data(range(len(data)), data)
ax3.set_xlim(0, len(data))
ax3.set_ylim(min(data), max(data))
fig.canvas.draw_idle()
# save coefficients to file
with open("pcm_data_processing/include/coefficients.h", "w") as f:
f.write(
"#define NUMTAPS " + str(numtaps) + "\n" +
"#define COEFFICIENTS {" + ",".join(np.array(np.array(np.round(b*(2**(bits)-1)), dtype=np.int32), dtype=str)) +"}" "\n"
)
plt.tight_layout()
interact(update, numtaps=(0, 100,2), f_cut=(100,5000))