Files
Masterarbeit_Simulation/ANR_high_level.ipynb
T

531 KiB

In [ ]:
#Funktionen und Abhängigkeiten

import time
import os
from ipywidgets import interact
from scipy import signal
from scipy.signal import savgol_filter
from scipy.stats import pearsonr
import numpy as np
import matplotlib.pyplot as plt
import soundfile as sf
import pandas as pd
import csv

# Soundfile laden
def load_wav(filename):
    y, fs = sf.read(filename, dtype='float32')
    return fs, y.T

# Sensitivätskurve Mikrofon laden (normiert auf 1000 Hz)
def load_transfer_function(filename):
    df = pd.read_csv(filename, skiprows=3, header=None, dtype=float, sep=";")
    frequencies = df.iloc[:, 0]
    gain = df.iloc[:, 1]
    return frequencies, gain

# Transferfunktion für frequenzabhängige Veränderung von Signal anlegen
def apply_transfer_function_freq(signal, fs, frequencies, gain_dB):
    # Signal in Frequenzbereich fouriertransformieren, Frequenzbins berechnen, linearen Gain berechnen
    N = len(signal)
    freq_signal = np.fft.rfft(signal)
    freq_bins = np.fft.rfftfreq(N, d=1/fs)
    gain_linear = 10 ** (gain_dB / 20.0)    
    # Gain Werte interpolieren auf die tatsächlichen Frequenzbins
    # Phasenshift für die Verzögerung berechnen
    # Signalfrequenzen modifizieren. 
    # Signal wieder zurück in Zeitbereich
    gain_interp = np.interp(freq_bins, frequencies, gain_linear)
    modified_freq_signal = freq_signal * gain_interp
    modified_signal = np.fft.irfft(modified_freq_signal, n=N)
    return modified_signal

# High-Level ANR Algorithmmus - nicht deterministisch, daher nicht gleiche Ergebnisse wie in C
def anr_function(input, ref_noise, coefficients, mu, adaption_step = 1):
    coefficient_matrix = np.zeros((len(input), coefficients), dtype=np.float32)
    output=np.zeros(input.shape[0], dtype=np.float32)
    filter = np.zeros(coefficients, dtype=np.float32)
    adaption_step = 10
    
    for j in range(0, len(input) - len(filter)): 
        accumulator=0
        for i in range(coefficients):
            noise=ref_noise[j+i]
            accumulator+=filter[i] * noise
        output[j] = input[j] - accumulator
        corrector = mu * output[j]
        if (j % adaption_step) != 4:
            for k in range(coefficients):
                filter[k] += corrector*ref_noise[j+k]
        coefficient_matrix[j, :] = filter[:]
    return output, coefficient_matrix

# Low-Level ANR Algorithmmus (wie in C)
def anr_function_c(input, ref_noise, coefficients, mu, adaption_step = 1):
    counter = 0
    sample_count = len(input)
    filter_line = np.zeros(coefficients)
    sample_line = np.zeros(coefficients)
    output = np.zeros(sample_count)
    coeffient_matrix = np.zeros((sample_count, coefficients))
    adaption_step = 1
    
    for n in range(sample_count):
        # Reference Noise Signal in Sample Line
        sample_line = np.roll(sample_line, 1)
        sample_line[0] = ref_noise[n]
        # apply_fir_filter: Akkumulator berechnen
        accumulator = np.dot(filter_line, sample_line)
        # update_output: Output/Error berechnen
        error = input[n] - accumulator
        output[n] = error
        # update_filter_coeffcients: Filterkoeffizienten adaptieren
        # Reduced-update Codeblock
        #if (n % adaption_step) == 0:     # bei Rate x/adatpion_step:  if (n % adaption_step) < x:
        # Error-driven Codeblock
        #if (abs(error)*ref_noise[n]) > 0:  # nur adaptieren wenn Fehler über Schwellwert
        #    counter += 1
        # filter_line += mu * error * sample_line
        filter_line += mu * error * sample_line
        # Filterkoeffizienten expoertieren
        coeffient_matrix[n, :] = filter_line
    #print(f"Anpassungen: {counter}")
    return output, coeffient_matrix
    


In [ ]:
#Plots für Simple Usecases

SIMULATION = False
AUDIO = False
PLOT = False
COMPLEX = False

plot = 'sine_1'

# Chirp Generator
n=2000 #Sampleanzahl
fs=20000 #Samplingrate
f0=100 #Startfrequenz
f1=1000 #Stopfrequenz
t1=n/fs #Chirpdauer (Samples/Samplingrate)
if plot == 'sine_1':
    f_disturber=2000 #Störfrequenz
else:
    f_disturber=500 #Störfrequenz

signal_amplitude=0.5
disturber_amplitude=0.25

# Parameter setzen
coefficients = 16
step_size = 0.01
noise_delay = 0.000
indices = [0, coefficients // 2, coefficients - 1]

t = np.linspace(0, t1, n)

# Zielsignal anlegen
desired_signal = signal.chirp(t, f0=f0, f1=f1, t1=t1, method='linear')*signal_amplitude

# Störsignal anlegen
if plot == 'sine_1' or plot == 'sine_2':
    noise_signal = np.sin(2*np.pi*f_disturber*t) * disturber_amplitude
else:
    noise_signal = np.random.normal(0, 1, n) * disturber_amplitude

# Sensitivätskurve Mikrofon laden (normiert auf 1000 Hz)
frequency_r11, gain_r11 = load_transfer_function('./transfer_functions/R11_normalized.csv')
frequency_vpu, gain_vpu = load_transfer_function('./transfer_functions/VPU17BA01_normlized.csv')

if COMPLEX == True:
    desired_signal_r11 = apply_transfer_function_freq(desired_signal, fs, frequency_r11, gain_r11)
    noise_signal_r11 = apply_transfer_function_freq(noise_signal, fs, frequency_r11, gain_r11)
    noise_signal_vpu = apply_transfer_function_freq(noise_signal, fs, frequency_vpu, gain_vpu)
else:
    desired_signal_r11 = desired_signal
    noise_signal_r11 = noise_signal
    noise_signal_vpu = noise_signal

# Noise Delay bedeutet, dass das Corruption Noise Signal im Corrupted Signal verzögert ist (zum Reference Noise Signal)
if noise_delay != 0:
    # Delay von ms in Samples umrechnen, 0-Array erzeugen
    delay_samples = int(noise_delay * fs)
    noise_signal_r11_delayed = np.zeros_like(noise_signal_r11)
    # Schneided die Delay Samples vom ursprünglichen Array ab und schreibt sie nach entsprechend vielen Nullen ins neue Array
    noise_signal_r11_delayed[delay_samples:] = noise_signal_r11[:-delay_samples]
    # Corrupted Signal mit verzögertem Noise
    corrupted_signal = desired_signal_r11 + noise_signal_r11_delayed
else:
    corrupted_signal = desired_signal_r11 + noise_signal_r11

# Zeitachse anlegen, ANR Algorithmus ausführen
t = np.linspace(0, len(corrupted_signal), len(corrupted_signal))/1000
output, coefficient_matrix = anr_function_c(corrupted_signal, noise_signal_vpu, coefficients, step_size, adaption_step=1)

# Koeffizientenmatrix und Vergleich um Koeffizientenanzahl kürzen, um Tail zu vermeiden, 2.te Zeitachse anlegen
coefficient_matrix = coefficient_matrix[:-coefficients]
error_signal = (output - desired_signal_r11)[:-coefficients]
t2 = np.linspace(0, len(error_signal), len(error_signal))/20000

# SNR davor/danach in dB berechnen, SNR Ratio berechnen, 
snr_before = 10 * np.log10(np.trapz(desired_signal_r11**2, t) / np.trapz(noise_signal_r11**2, t))
snr_after = 10 * np.log10(np.trapz(desired_signal_r11**2, t) / np.trapz(error_signal**2, t2))
delta_snr = round(snr_after - snr_before, 2)

if SIMULATION == True:
    # Soundfiles zu 16 Bit skalieren und als .txt speichern für DSP Simulation
    dsp_desired_signal_r11 = desired_signal_r11*(2**(15)-1)
    dsp_noise_signal_r11 = noise_signal_r11*(2**(15)-1)
    dsp_noise_signal_vpu = noise_signal_vpu*(2**(15)-1)
    dsp_corrupted_signal = corrupted_signal*(2**(15)-1)
    python_output = output*(2**(15)-1)
    np.savetxt('simulation_data/simple_dsp_desired_signal_r11.txt', dsp_desired_signal_r11, fmt='%d')
    np.savetxt('simulation_data/simple_dsp_noise_signal_r11.txt', dsp_noise_signal_r11, fmt='%d')
    np.savetxt('simulation_data/simple_dsp_noise_signal_vpu.txt', dsp_noise_signal_vpu, fmt='%d', delimiter="\n")
    np.savetxt('simulation_data/simple_dsp_corrupted_signal.txt', dsp_corrupted_signal, fmt='%d', delimiter="\n")
    np.savetxt('filter_output/simple_python_output.txt', python_output, fmt='%d', delimiter="\n")
    np.savetxt('filter_output/simple_python_filter_coefficients.txt', coefficient_matrix, fmt='%.4f', delimiter=",")

# Plots des Filterprozesses
figure1, (ax0, ax1, ax2, ax3) = plt.subplots(4, 1, figsize=(15, 12), sharex=True, sharey=True)
ax0.set_ylim(-1, 1)
ax0.plot(t, desired_signal, c='deepskyblue', label='Desired signal')
ax1.plot(t, corrupted_signal, c='royalblue', label='Corrupted signal')
ax2.plot(t, noise_signal, c='chocolate', label='Reference noise signal')
ax3.plot(t, output, c='green', label=f'SNR Gain = {delta_snr} dB')

ax0.text(0.5, -0.3, '(a) Desired signal',
         transform=ax0.transAxes,
         fontsize=25,
         fontweight='normal',
         ha='center',
         va='bottom')

ax1.text(0.5, -0.3, '(b) Corrupted signal',
         transform=ax1.transAxes,
         fontsize=25,
         fontweight='normal',
         ha='center',
         va='bottom')

ax2.text(0.5, -0.3, '(c) Reference noise signal',
         transform=ax2.transAxes,
         fontsize=25,
         fontweight='normal',
         ha='center',
         va='bottom')

ax3.text(0.5, -0.5, f'(d) Filter output (SNR Gain = {delta_snr} dB)',
         transform=ax3.transAxes,
         fontsize=25,
         fontweight='normal',
         ha='center',
         va='bottom')

ax3.set_xlabel('time(s)', x=0.05)
ax0.set_ylabel('Amplitude')
ax1.set_ylabel('Amplitude')
ax2.set_ylabel('Amplitude')
ax3.set_ylabel('Amplitude')

# Plots der Filterperfomanz
figure2, (ax4, ax5) = plt.subplots(2, 1, figsize=(15, 7), sharex=True)
ax4.set_ylim(-1, 1)
ax4.plot(t2, error_signal, c='purple', label='Error (Desired signal - Filter output)')
for i in indices:
    ax5.plot(t2, coefficient_matrix[:,i], label=f'Coefficient {i+1}')

ax4.text(0.5, -0.3, '(a) Error signal',
         transform=ax4.transAxes,
         fontsize=25,
         fontweight='normal',
         ha='center',
         va='bottom')

ax5.text(0.5, -0.5, '(b) Coefficient values (1st, 8th, 16th)',
         transform=ax5.transAxes,
         fontsize=25,
         fontweight='normal',
         ha='center',
         va='bottom')

ax5.set_xlabel('time(s)', x=0.05)
ax4.set_ylabel('Amplitude')
ax5.set_ylabel('Coeffcient value')

#Grids direkt auf Subplots anwenden
ax0.grid(True, linestyle='--', alpha=0.4)
ax1.grid(True, linestyle='--', alpha=0.4)
ax2.grid(True, linestyle='--', alpha=0.4)
ax3.grid(True, linestyle='--', alpha=0.4)
ax4.grid(True, linestyle='--', alpha=0.4)
ax5.grid(True, linestyle='--', alpha=0.4)

#Spines direkt auf Subplots anwenden
ax0.spines['top'].set_visible(False)
ax1.spines['top'].set_visible(False)
ax2.spines['top'].set_visible(False)
ax3.spines['top'].set_visible(False)
ax4.spines['top'].set_visible(False)
ax5.spines['top'].set_visible(False)
ax0.spines['right'].set_visible(False)
ax1.spines['right'].set_visible(False)
ax2.spines['right'].set_visible(False)
ax3.spines['right'].set_visible(False)
ax4.spines['right'].set_visible(False)
ax5.spines['right'].set_visible(False)

# Schriftgrößen für LaTeX-Dokument
plt.rcParams.update({
    "text.usetex": True,
    "font.family": "serif",
    'font.size': 16,          # Standardtext
    'axes.labelsize': 30,     # Achsenbeschriftungen
    'xtick.labelsize': 25,    # Tick-Beschriftungen
    'ytick.labelsize': 25,
    'legend.fontsize': 15     # Legende
})

figure1.tight_layout()
figure2.tight_layout()
if PLOT == True:
    figure1.savefig(f'plots/fig_plot_1_{plot}', dpi=600)
    figure2.savefig(f'plots/fig_plot_2_{plot}', dpi=600)
plt.show()
In [ ]:
#Plots für intermediate/komplexen Usecases

from pandas import Series

COMPLEX= True
SIMULATION = False
AUDIO = False
PLOT = False
SERIES = False

# Chirp Generator
n=2000 #Sampleanzahl
fs=20000 #Samplingrate
f0=100 #Startfrequenz
f1=1000 #Stopfrequenz
t1=n/fs #Chirpdauer (Samples/Samplingrate)
f_disturber=2000 #Störfrequenz

# Parameter setzen
coefficients = 45
step_size = 0.01
noise_delay = 0.002
indices = [0, coefficients // 2, coefficients - 1]

# .wav File laden, Tonspuren den Signalen zuordnen, Corrputed Target Signal erstellen, Reduced Noise Signal erstellen
fs, data_1 = load_wav(f'./audio_data/Nutzsignal/male.wav')
fs, data_2 = load_wav(f'./audio_data/Störsignal/breathing.wav')

# Sensitivätskurve Mikrofon laden (normiert auf 1000 Hz)
frequency_r11, gain_r11 = load_transfer_function('./transfer_functions/R11_normalized.csv')
frequency_vpu, gain_vpu = load_transfer_function('./transfer_functions/VPU17BA01_normlized.csv')

# Signale laden und zuordnen
desired_signal = data_1
noise_signal = data_2
if COMPLEX == True:
    desired_signal_r11 = apply_transfer_function_freq(desired_signal, fs, frequency_r11, gain_r11)
    noise_signal_r11 = apply_transfer_function_freq(noise_signal, fs, frequency_r11, gain_r11)
    noise_signal_vpu = apply_transfer_function_freq(noise_signal, fs, frequency_vpu, gain_vpu)
else:
    desired_signal_r11 = desired_signal
    noise_signal_r11 = noise_signal
    noise_signal_vpu = noise_signal

# Noise Delay bedeutet, dass das Corruption Noise Signal im Corrupted Signal verzögert ist (zum Reference Noise Signal)
if noise_delay != 0:
    # Delay von ms in Samples umrechnen, 0-Array erzeugen
    delay_samples = int(noise_delay * fs)
    noise_signal_r11_delayed = np.zeros_like(noise_signal_r11)
    # Schneided die Delay Samples vom ursprünglichen Array ab und schreibt sie nach entsprechend vielen Nullen ins neue Array
    noise_signal_r11_delayed[delay_samples:] = noise_signal_r11[:-delay_samples]
    # Corrupted Signal mit verzögertem Noise
    corrupted_signal = desired_signal_r11 + noise_signal_r11_delayed
else:
    corrupted_signal = desired_signal_r11 + noise_signal_r11

# Zeitachse anlegen, ANR Algorithmus ausführen
t = np.linspace(0, len(corrupted_signal), len(corrupted_signal))/20000

if SERIES == True:
    for i in range(16, coefficients+2, 2):
        output, coefficient_matrix = anr_function_c(corrupted_signal, noise_signal_vpu, i, step_size, adaption_step=1)

        # Koeffizientenmatrix und Vergleich um Koeffizientenanzahl kürzen, um Tail zu vermeiden, 2.te Zeitachse anlegen
        coefficient_matrix = coefficient_matrix[:-coefficients]
        error_signal = (output - desired_signal_r11)[:-coefficients]
        t2 = np.linspace(0, len(error_signal), len(error_signal))/20000

        # SNR davor/danach in dB berechnen, SNR Ratio berechnen, 
        snr_before = 10 * np.log10(np.trapz(desired_signal_r11**2, t) / np.trapz(noise_signal_r11**2, t))
        snr_after = 10 * np.log10(np.trapz(desired_signal_r11**2, t) / np.trapz(error_signal**2, t2))
        delta_snr = round(snr_after - snr_before, 2)

        with open('snr_evaluation/male+breathing', 'a', newline='') as f:
            writer = csv.writer(f)
            writer.writerow([i, delta_snr])
else:
        output, coefficient_matrix = anr_function_c(corrupted_signal, noise_signal_vpu, coefficients, step_size, adaption_step=1)

# Koeffizientenmatrix und Vergleich um Koeffizientenanzahl kürzen, um Tail zu vermeiden, 2.te Zeitachse anlegen
coefficient_matrix = coefficient_matrix[:-coefficients]
error_signal = (output - desired_signal_r11)[:-coefficients]
t2 = np.linspace(0, len(error_signal), len(error_signal))/20000

# SNR davor/danach in dB berechnen, SNR Ratio berechnen, 
snr_before = 10 * np.log10(np.trapz(desired_signal_r11**2, t) / np.trapz(noise_signal_r11**2, t))
snr_after = 10 * np.log10(np.trapz(desired_signal_r11**2, t) / np.trapz(error_signal**2, t2))
delta_snr = round(snr_after - snr_before, 2)

if AUDIO == True:
    # Audiodateien zum Vergleich abspeichern
    sf.write('corrupted_signal.wav', corrupted_signal, fs)
    sf.write('filter_output.wav', output, fs)

if SIMULATION == True:
    # Soundfiles zu 16 Bit skalieren und als .txt speichern für DSP Simulation
    dsp_desired_signal_r11 = desired_signal_r11*(2**(15)-1)
    dsp_noise_signal_r11 = noise_signal_r11*(2**(15)-1)
    dsp_noise_signal_vpu = noise_signal_vpu*(2**(15)-1)
    dsp_corrupted_signal = corrupted_signal*(2**(15)-1)
    python_output = output*(2**(15)-1)
    python_coefficient_matrix = coefficient_matrix*(2**(15)-1)
    np.savetxt('simulation_data/complex_dsp_desired_signal_r11.txt', dsp_desired_signal_r11, fmt='%d')
    np.savetxt('simulation_data/complex_dsp_noise_signal_r11.txt', dsp_noise_signal_r11, fmt='%d')
    np.savetxt('simulation_data/complex_dsp_noise_signal_vpu.txt', dsp_noise_signal_vpu, fmt='%d', delimiter="\n")
    np.savetxt('simulation_data/complex_dsp_corrupted_signal.txt', dsp_corrupted_signal, fmt='%d', delimiter="\n")
    np.savetxt('filter_output/complex_python_output.txt', python_output, fmt='%d', delimiter="\n")
    np.savetxt('filter_output/complex_python_filter_coefficients.txt', python_coefficient_matrix, fmt='%d', delimiter=",")

# Plots des Filterprozesses
figure1, (ax0, ax1, ax2, ax3) = plt.subplots(4, 1, figsize=(15, 12), sharex=True, sharey=True)
ax0.set_ylim(-1, 1)
ax0.plot(t, desired_signal, c='deepskyblue', label='Desired signal')
ax1.plot(t, corrupted_signal, c='royalblue', label='Corrupted signal')
ax2.plot(t, noise_signal_vpu, c='chocolate', label='Reference noise signal')
ax3.plot(t, output, c='green', label=f'SNR Gain = {delta_snr} dB')

ax0.text(0.5, -0.3, '(a) Desired signal',
         transform=ax0.transAxes,
         fontsize=25,
         fontweight='normal',
         ha='center',
         va='bottom')

ax1.text(0.5, -0.3, '(b) Corrupted signal',
         transform=ax1.transAxes,
         fontsize=25,
         fontweight='normal',
         ha='center',
         va='bottom')

ax2.text(0.5, -0.3, '(c) Reference noise signal',
         transform=ax2.transAxes,
         fontsize=25,
         fontweight='normal',
         ha='center',
         va='bottom')

ax3.text(0.5, -0.5, f'(d) Filter output (SNR Gain = {delta_snr} dB)',
         transform=ax3.transAxes,
         fontsize=25,
         fontweight='normal',
         ha='center',
         va='bottom')

ax3.set_xlabel('time(s)', x=0.05)
ax0.set_ylabel('Amplitude')
ax1.set_ylabel('Amplitude')
ax2.set_ylabel('Amplitude')
ax3.set_ylabel('Amplitude')

# Plots der Filterperfomanz
figure2, (ax4, ax5) = plt.subplots(2, 1, figsize=(15, 7), sharex=True)
ax4.set_ylim(-1, 1)
ax4.plot(t2, error_signal, c='purple', label='Error (Desired signal - Filter output)')
for i in indices:
    ax5.plot(t2, coefficient_matrix[:,i], label=f'Coefficient {i+1}')

ax4.text(0.5, -0.3, '(a) Error signal',
         transform=ax4.transAxes,
         fontsize=25,
         fontweight='normal',
         ha='center',
         va='bottom')

ax5.text(0.5, -0.5, '(b) Coefficient values (1st, 8th, 16th)',
         transform=ax5.transAxes,
         fontsize=25,
         fontweight='normal',
         ha='center',
         va='bottom')

ax5.set_xlabel('time(s)', x=0.05)
ax4.set_ylabel('Amplitude')
ax5.set_ylabel('Coeffcient value')

# Plot Sensitivitätskurve
figure3, (ax6, ax7) = plt.subplots(2, 1, figsize=(15, 7), sharex=True)
ax6.set_ylim(min(gain_r11), max(gain_r11))
ax7.set_ylim(min(gain_vpu), max(gain_vpu))
ax6.plot(frequency_r11, gain_r11, c='indianred', label='Sensitivity Curve (Primary sensor)' )
ax7.plot(frequency_vpu, gain_vpu, c='orangered', label='Sensitivity Curve (Secondary sensor)')

ax6.text(0.5, -0.3, '(a) Sensitivity Curve (Primary sensor)',
         transform=ax6.transAxes,
         fontsize=25,
         fontweight='normal',
         ha='center',
         va='bottom')
ax7.text(0.5, -0.5, '(b) Sensitivity Curve (Secondary sensor)',
         transform=ax7.transAxes,
         fontsize=25,
         fontweight='normal',
         ha='center',
         va='bottom')

ax7.set_xlabel('Frequency (Hz)', x=0.1)
ax6.set_ylabel('Gain (dB)')
ax7.set_ylabel('Gain (dB)')

# Plot für Störsignalvergleich
figure4, (ax8, ax9, ax10) = plt.subplots(3, 1, figsize=(15, 10), sharex=True, sharey=True)
ax8.set_ylim(1.0, -1.0)
ax8.plot(t, noise_signal, c='orange', label='Noise signal')
ax9.plot(t, noise_signal_r11, c='darkorange', label='Corruption noise signal (Primary sensor)')
ax10.plot(t, noise_signal_vpu, c='peru', label='Reference noise signal (Secondary sensor)')

ax8.text(0.5, -0.3, '(a) Noise signal',
         transform=ax8.transAxes,
         fontsize=25,
         fontweight='normal',
         ha='center',
         va='bottom')

ax9.text(0.5, -0.3, '(b) Corruption noise signal (Primary sensor)',
         transform=ax9.transAxes,
         fontsize=25,
         fontweight='normal',
         ha='center',
         va='bottom')

ax10.text(0.5, -0.5, '(c) Reference noise signal (Secondary sensor)',
         transform=ax10.transAxes,
         fontsize=25,
         fontweight='normal',
         ha='center',
         va='bottom')

ax10.set_xlabel('time(s)', x=0.05)
ax8.set_ylabel('Amplitude')
ax9.set_ylabel('Amplitude')
ax10.set_ylabel('Amplitude')

#Grids direkt auf Subplots anwenden
ax0.grid(True, linestyle='--', alpha=0.4)
ax1.grid(True, linestyle='--', alpha=0.4)
ax2.grid(True, linestyle='--', alpha=0.4)
ax3.grid(True, linestyle='--', alpha=0.4)
ax4.grid(True, linestyle='--', alpha=0.4)
ax5.grid(True, linestyle='--', alpha=0.4)
ax6.grid(True, linestyle='--', alpha=0.4)
ax7.grid(True, linestyle='--', alpha=0.4)
ax8.grid(True, linestyle='--', alpha=0.4)
ax9.grid(True, linestyle='--', alpha=0.4)
ax10.grid(True, linestyle='--', alpha=0.4)

#Spines direkt auf Subplots anwenden
ax0.spines['top'].set_visible(False)
ax1.spines['top'].set_visible(False)
ax2.spines['top'].set_visible(False)
ax3.spines['top'].set_visible(False)
ax4.spines['top'].set_visible(False)
ax5.spines['top'].set_visible(False)
ax6.spines['top'].set_visible(False)
ax7.spines['top'].set_visible(False)
ax8.spines['top'].set_visible(False)
ax9.spines['top'].set_visible(False)
ax10.spines['top'].set_visible(False)
ax0.spines['right'].set_visible(False)
ax1.spines['right'].set_visible(False)
ax2.spines['right'].set_visible(False)
ax3.spines['right'].set_visible(False)
ax4.spines['right'].set_visible(False)
ax5.spines['right'].set_visible(False)
ax6.spines['right'].set_visible(False)
ax7.spines['right'].set_visible(False)
ax8.spines['right'].set_visible(False)
ax9.spines['right'].set_visible(False)
ax10.spines['right'].set_visible(False)

# Schriftgrößen für LaTeX-Dokument
plt.rcParams.update({
    "text.usetex": True,
    "font.family": "serif",
    'font.size': 16,          # Standardtext
    'axes.labelsize': 30,     # Achsenbeschriftungen
    'xtick.labelsize': 25,    # Tick-Beschriftungen
    'ytick.labelsize': 25,
    'legend.fontsize': 15     # Legende
})

figure1.tight_layout()
figure2.tight_layout()
figure3.tight_layout()
figure4.tight_layout()
if PLOT == True:
    if COMPLEX == True:
        figure1.savefig(f'plots/fig_plot_1_wav_complex', dpi=600)
        figure2.savefig(f'plots/fig_plot_2_wav_complex', dpi=600)
        figure3.savefig(f'plots/fig_plot_3_wav_complex', dpi=600)
        figure4.savefig(f'plots/fig_plot_4_wav_complex', dpi=600)
    else:
        figure1.savefig(f'plots/fig_plot_1_wav', dpi=600)
        figure2.savefig(f'plots/fig_plot_2_wav', dpi=600)
plt.show()
C:\Users\phangl\AppData\Local\Temp\ipykernel_37188\3939203997.py:86: DeprecationWarning: `trapz` is deprecated. Use `trapezoid` instead, or one of the numerical integration functions in `scipy.integrate`.
  snr_before = 10 * np.log10(np.trapz(desired_signal_r11**2, t) / np.trapz(noise_signal_r11**2, t))
C:\Users\phangl\AppData\Local\Temp\ipykernel_37188\3939203997.py:87: DeprecationWarning: `trapz` is deprecated. Use `trapezoid` instead, or one of the numerical integration functions in `scipy.integrate`.
  snr_after = 10 * np.log10(np.trapz(desired_signal_r11**2, t) / np.trapz(error_signal**2, t2))
In [ ]:
#Plots für SNR Vergleich

PLOT = False

# Daten aus .csv laden
data_male_breathing = np.loadtxt('snr_evaluation/male+breathing', delimiter=",")
data_male_chewing = np.loadtxt('snr_evaluation/male+chewing', delimiter=",")
data_male_scratching = np.loadtxt('snr_evaluation/male+scratching', delimiter=",")
data_male_drinking = np.loadtxt('snr_evaluation/male+drinking', delimiter=",")
data_male_coughing = np.loadtxt('snr_evaluation/male+coughing', delimiter=",")


# Daten laden
x = data_male_breathing[:, 0]
male_breathing = savgol_filter(data_male_breathing[:, 1], 10, 3)
male_chewing = savgol_filter(data_male_chewing[:, 1], 10, 3)
male_scratching = savgol_filter(data_male_scratching[:, 1], 10, 3)
male_drinking = savgol_filter(data_male_drinking[:, 1], 10, 3)
male_coughing = savgol_filter(data_male_coughing[:, 1], 10, 3)

# Alle Kurven in ein Array stapeln
all_curves = np.vstack([
    male_breathing,
    male_chewing,
    male_scratching,
    male_drinking,
    male_coughing
])

# Punktweiser Mittelwert
mean_gain = np.mean(all_curves, axis=0)

# Plot
plt.figure(figsize=(15, 7))
plt.plot(x, male_breathing, linestyle='-',  linewidth=1.5, alpha=0.7, label='Breathing Noise')
plt.plot(x, male_chewing, linestyle='--', linewidth=1.5, alpha=0.7, label='Chewing Noise')
plt.plot(x, male_scratching, linestyle='-.', linewidth=1.5, alpha=0.7, label='Scratching Noise')
plt.plot(x, male_drinking, linestyle=':',  linewidth=1.5, alpha=0.7, label='Drinking Noise')
plt.plot(x, male_coughing, linestyle=(0, (3, 1, 1, 1)), linewidth=1.5, alpha=0.7, label='Coughing Noise')
plt.plot(x, mean_gain, linestyle='--', color='red', linewidth=2.5, label='Mean SNR-Gain')

plt.rcParams.update({
    "text.usetex": True,
    "font.family": "serif",
    'font.size': 16,          # Standardtext
    'axes.labelsize': 30,     # Achsenbeschriftungen
    'xtick.labelsize': 25,    # Tick-Beschriftungen
    'ytick.labelsize': 25,
    'legend.fontsize': 25     # Legende
})

plt.xlabel("Filter length")
plt.ylabel("SNR-Gain (dB)")
plt.grid(True, linestyle='--', alpha=0.4)
#Spines auf ganzen Plot anwenden
plt.gca().spines['top'].set_visible(False)
plt.gca().spines['right'].set_visible(False)
plt.legend(frameon=False, loc='upper left')
plt.tight_layout()
if PLOT == True:
    plt.savefig(f'plots/fig_snr_comparison', dpi=600)
plt.show()
In [ ]:
#Plots der Störsignale

PLOT = True

fs, data_1 = load_wav(f'./audio_data/Störsignal/breathing.wav')
fs, data_2 = load_wav(f'./audio_data/Störsignal/coughing.wav')
fs, data_3 = load_wav(f'./audio_data/Störsignal/scratching.wav')
fs, data_4 = load_wav(f'./audio_data/Störsignal/drinking.wav')
fs, data_5 = load_wav(f'./audio_data/Störsignal/chewing.wav')

t = np.linspace(0, len(data_1), len(data_1))/20000

figure1, (ax1, ax2, ax3, ax4, ax5) = plt.subplots(5, 1, figsize=(15, 15), sharex=True, sharey=True)
ax1.set_ylim(1.0, -1.0)
ax1.plot(t, data_1, c='darkorange', label='Breathing Noise')
ax2.plot(t, data_2, c='indianred', label='Coughing Noise')
ax3.plot(t, data_3, c='deepskyblue', label='Scratching Noise')
ax4.plot(t, data_4, c='forestgreen', label='Drinking Noise')
ax5.plot(t, data_5, c='darkorchid', label='Chewing Noise')

ax1.text(0.5, -0.3, '(a) Breathing Noise',
         transform=ax1.transAxes,
         fontsize=25,
         fontweight='normal',
         ha='center',
         va='bottom')

ax2.text(0.5, -0.3, '(b) Coughing Noise',
         transform=ax2.transAxes,
         fontsize=25,
         fontweight='normal',
         ha='center',
         va='bottom')

ax3.text(0.5, -0.3, '(c) Scratching Noise',
         transform=ax3.transAxes,
         fontsize=25,
         fontweight='normal',
         ha='center',
         va='bottom')

ax4.text(0.5, -0.3, '(d) Drinking Noise',
         transform=ax4.transAxes,
         fontsize=25,
         fontweight='normal',
         ha='center',
         va='bottom')

ax5.text(0.5, -0.5, '(e) Chewing Noise',
         transform=ax5.transAxes,
         fontsize=25,
         fontweight='normal',
         ha='center',
         va='bottom')

ax5.set_xlabel("time (s)", x=0.05)
ax1.set_ylabel("Amplitude")
ax2.set_ylabel("Amplitude")
ax3.set_ylabel("Amplitude")
ax4.set_ylabel("Amplitude")
ax5.set_ylabel("Amplitude")
#ax5.xaxis.set_label_coords(0.5, -0.4)

ax1.grid(True, linestyle='--', alpha=0.4)
ax2.grid(True, linestyle='--', alpha=0.4)
ax3.grid(True, linestyle='--', alpha=0.4)
ax4.grid(True, linestyle='--', alpha=0.4)
ax5.grid(True, linestyle='--', alpha=0.4)

#Spines direkt auf Subplots anwenden
ax1.spines['top'].set_visible(False)
ax2.spines['top'].set_visible(False)
ax3.spines['top'].set_visible(False)
ax4.spines['top'].set_visible(False)
ax5.spines['top'].set_visible(False)
ax1.spines['right'].set_visible(False)
ax2.spines['right'].set_visible(False)
ax3.spines['right'].set_visible(False)
ax4.spines['right'].set_visible(False)
ax5.spines['right'].set_visible(False)

# Schriftgrößen für LaTeX-Dokument
plt.rcParams.update({
    "text.usetex": True,
    "font.family": "serif",
    'font.size': 16,          # Standardtext
    'axes.labelsize': 30,     # Achsenbeschriftungen
    'xtick.labelsize': 25,    # Tick-Beschriftungen
    'ytick.labelsize': 25,
    'legend.fontsize': 15     # Legende
})

figure1.tight_layout()
if PLOT == True:
    plt.savefig(f'plots/fig_noise_signals', dpi=600)
figure1.show()
In [ ]:
# Filterlänge und Update-Schritte Vergleich

import numpy as np
import matplotlib.pyplot as plt

PLOT = False

# Filterlänge
N = np.arange(1, 128)
# Verschiedene Updateschritte
U_values = [1, 0.5, 0.25]

C_total_1 = N + (6*N + 8)*U_values[0] + 34
C_total_2 = N + (6*N + 8)*U_values[1] + 34
C_total_3 = N + (6*N + 8)*U_values[2] + 34

plt.figure(figsize=(15, 7))
plt.plot(N, C_total_1, linestyle='-',  linewidth=1.5, alpha=0.7, label=f'1/U = {U_values[0]}')
plt.plot(N, C_total_2, linestyle='--', linewidth=1.5, alpha=0.7, label=f'1/U = {U_values[1]}')
plt.plot(N, C_total_3, linestyle='-.', linewidth=1.5, alpha=0.7, label=f'1/U = {U_values[2]}')

plt.rcParams.update({
    "text.usetex": True,
    "font.family": "serif",
    'font.size': 16,          # Standardtext
    'axes.labelsize': 30,     # Achsenbeschriftungen
    'xtick.labelsize': 25,    # Tick-Beschriftungen
    'ytick.labelsize': 25,
    'legend.fontsize': 25     # Legende
})

plt.xlabel("Filter length")
plt.ylabel("Cycles/Sample")
plt.grid(True, linestyle='--', alpha=0.4)
#Spines auf ganzen Plot anwenden
plt.gca().spines['top'].set_visible(False)
plt.gca().spines['right'].set_visible(False)
plt.legend(frameon=False, loc='lower right')
plt.tight_layout()
if PLOT == True:
    plt.savefig(f'plots/fig_c_total', dpi=600)
plt.show()
In [ ]:
# Vergleich Output High/Low-Level

PLOT = False
COMPLEX = True

if COMPLEX == True:
    python_output = np.loadtxt('filter_output/complex_python_output.txt', delimiter=",")/(2**(15)-1)
    dsp_output = np.loadtxt('filter_output/complex_dsp_output.txt', delimiter=",")[:-1]/(2**(15)-1)
else:
    python_output = np.loadtxt('filter_output/simple_python_output.txt', delimiter=",")/(2**(15)-1)
    dsp_output = np.loadtxt('filter_output/simple_dsp_output.txt', delimiter=",")[:-1]/(2**(15)-1)

diff = python_output - dsp_output

if COMPLEX == True:
    t = np.linspace(0, 200000, 200000)/20000
else:
    t = np.linspace(0, 2000, 2000)/200

figure1, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize=(15, 9), sharex=True, sharey=True)
ax1.set_ylim(1.0, -1.0)
ax1.plot(t, python_output, linestyle='-', c='deepskyblue',  linewidth=1, alpha=1, label='High Level Simulation')
ax2.plot(t, dsp_output, linestyle='-', c='indianred', linewidth=1, alpha=1, label='Low Level Simulation')
ax3.plot(t, python_output, linestyle='-', c='deepskyblue',  linewidth=1, alpha=1)
ax3.plot(t, dsp_output, linestyle='-', c='indianred', linewidth=1, alpha=0.7)
ax3.plot(t, diff, linestyle='-', c='green', linewidth=2, alpha=0.7, label=f'Error Amplitude')

figure2, ax4 = plt.subplots(1, 1, figsize=(15, 7))
ax4.hist(diff, bins=100, density=True, color='green',edgecolor='black', alpha=0.7)
ax4.set_yscale('log')

mean = np.mean(diff)
std = np.std(diff)
ax4.axvline(mean, linestyle='-', linewidth=3, label='Mean')
ax4.axvline(mean + std, linestyle='--', linewidth=2, label='+1 Sigma')
ax4.axvline(mean - std, linestyle='--', linewidth=2, label='-1 Sigma')


plt.rcParams.update({
    "text.usetex": True,
    "font.family": "serif",
    'font.size': 16,          # Standardtext
    'axes.labelsize': 30,     # Achsenbeschriftungen
    'xtick.labelsize': 25,    # Tick-Beschriftungen
    'ytick.labelsize': 25,
    'legend.fontsize': 25     # Legende
})

ax1.text(0.5, -0.3, '(a) High Level Simulation',
         transform=ax1.transAxes,
         fontsize=25,
         fontweight='normal',
         ha='center',
         va='bottom')

ax2.text(0.5, -0.3, '(b) Low Level Simulation',
         transform=ax2.transAxes,
         fontsize=25,
         fontweight='normal',
         ha='center',
         va='bottom')

ax3.text(0.5, -0.5, f'(c) Comparision High/Low Level Simulation',
         transform=ax3.transAxes,
         fontsize=25,
         fontweight='normal',
         ha='center',
         va='bottom')

ax3.set_xlabel("time (s)", x=0.05)
ax1.set_ylabel("Amplitude")
ax2.set_ylabel("Amplitude")
ax3.set_ylabel("Amplitude")
ax3.set_ylabel("Amplitude")

ax4.set_xlabel("Error Amplitude")
ax4.set_ylabel("Samples")

ax1.grid(True, linestyle='--', alpha=0.4)
ax2.grid(True, linestyle='--', alpha=0.4)
ax3.grid(True, linestyle='--', alpha=0.4)
ax4.grid(True, linestyle='--', alpha=0.4)

#Spines direkt auf Subplots anwenden
ax1.spines['top'].set_visible(False)
ax2.spines['top'].set_visible(False)
ax3.spines['top'].set_visible(False)
ax4.spines['top'].set_visible(False)
ax1.spines['right'].set_visible(False)
ax2.spines['right'].set_visible(False)
ax3.spines['right'].set_visible(False)
ax4.spines['right'].set_visible(False)
ax3.legend(frameon=False, loc='upper right')
ax4.legend(frameon=False, loc='upper right')

figure1.tight_layout()
figure2.tight_layout()
if PLOT == True:
    figure1.savefig(f'plots/fig_high_low_comparison', dpi=600)
    figure2.savefig(f'plots/fig_high_low_comparison_hist', dpi=600)
figure1.show()
figure2.show()
In [ ]:
#Single Reduced Update Plot

import matplotlib.ticker as mtick
from scipy.interpolate import make_interp_spline

PLOT = False

# Daten aus .csv laden
update_rate_breathing = np.loadtxt('update_rate_evaluation/update_rate_breathing.csv', delimiter=";", skiprows=1)

# Daten laden
x = update_rate_breathing[:, 0]
update_gain_breathing = update_rate_breathing[:, 2]
update_cycles_breathing = update_rate_breathing[:, 4]
update_load_breathing = update_rate_breathing[:, 5]
update_cycles_breathing_new = update_rate_breathing[:, 7]
update_load_breathing_new = update_rate_breathing[:, 8]

# Sortieren
idx = np.argsort(x)
x = x[idx]
update_gain_breathing = update_gain_breathing[idx]
update_cycles_breathing = update_cycles_breathing[idx]
update_load_breathing = update_load_breathing[idx]
update_cycles_breathing_new = update_cycles_breathing_new[idx]
update_load_breathing_new = update_load_breathing_new[idx]

# Smoothing
x_smooth = np.linspace(x.min(), x.max(), 300)

update_gain_smooth = make_interp_spline(x, update_gain_breathing)(x_smooth)
update_cycles_smooth = make_interp_spline(x, update_cycles_breathing)(x_smooth)
update_load_smooth = make_interp_spline(x, update_load_breathing)(x_smooth)
update_cycles_smooth_new = make_interp_spline(x, update_cycles_breathing_new)(x_smooth)
update_load_smooth_new = make_interp_spline(x, update_load_breathing_new)(x_smooth)

diff_smooth = np.abs(update_gain_smooth - update_cycles_smooth)
idx_max = np.argmax(diff_smooth)
x_max = x_smooth[idx_max]
y1_max = update_gain_smooth[idx_max]
y2_max = update_cycles_smooth[idx_max]

# Plot
figure1, ax1 = plt.subplots(figsize=(15, 7))
ax1.plot(x_smooth, update_gain_smooth, linestyle='--', color='indianred', linewidth=2, alpha=0.9, label='SNR-Gain')
ax1.plot(x_smooth, update_cycles_smooth, linestyle='-.', color='skyblue', linewidth=2, alpha=0.9, label='Cycles/Sample')
ax1.plot(x_smooth, update_load_smooth, linestyle=':', color='forestgreen', linewidth=2, alpha=0.9, label='DSP Load')
ax1.plot([x_max, x_max], [y1_max, y2_max], color='black', linestyle=':', linewidth=2)

ax1.scatter(x, update_gain_breathing, color='indianred', s=40)
ax1.scatter(x, update_cycles_breathing, color='skyblue', s=40)
ax1.scatter(x, update_load_breathing, color='forestgreen', s=40)

# Plot
figure2, ax2 = plt.subplots(figsize=(15, 7))
ax2.plot(x_smooth, update_gain_smooth, linestyle='--', color='indianred', linewidth=2, alpha=0.9, label='SNR-Gain')
ax2.plot(x_smooth, update_cycles_smooth, linestyle='-.', color='skyblue', linewidth=2, alpha=0.3)
ax2.plot(x_smooth, update_load_smooth, linestyle=':', color='forestgreen', linewidth=2, alpha=0.3)
ax2.plot(x_smooth, update_cycles_smooth_new, linestyle='-', color='skyblue', linewidth=2, alpha=0.9, label='Cycles/Sample (New)')
ax2.plot(x_smooth, update_load_smooth_new, linestyle='-', color='forestgreen', linewidth=2, alpha=0.9, label='DSP Load (New)')

ax2.scatter(x, update_gain_breathing, color='indianred', s=40)
ax2.scatter(x, update_cycles_breathing, color='skyblue', s=40, alpha=0.3)
ax2.scatter(x, update_load_breathing, color='forestgreen', s=40, alpha=0.3)
ax2.scatter(x, update_cycles_breathing_new, color='skyblue', s=40)
ax2.scatter(x, update_load_breathing_new, color='forestgreen', s=40)

ax1.text(x_max, (y1_max + y2_max)/2+0.1,
         f'Max. offset at update rate {x_max:.2f}',
         fontsize=20,
         ha='left')

plt.rcParams.update({
    "text.usetex": True,
    "font.family": "serif",
    'font.size': 16,          # Standardtext
    'axes.labelsize': 30,     # Achsenbeschriftungen
    'xtick.labelsize': 25,    # Tick-Beschriftungen
    'ytick.labelsize': 25,
    'legend.fontsize': 25     # Legende
})


ax1.set_xlabel("Update Rate")
ax1.set_ylabel("Relative Performance")
ax2.set_xlabel("Update Rate")
ax2.set_ylabel("Relative Performance")
ax1.grid(True, linestyle='-.', alpha=0.4)
ax2.grid(True, linestyle='-.', alpha=0.4)
#Spines auf ganzen Plot anwenden
ax1.yaxis.set_major_formatter(mtick.PercentFormatter(1.0))
ax2.yaxis.set_major_formatter(mtick.PercentFormatter(1.0))
ax1.spines['top'].set_visible(False)
ax1.spines['right'].set_visible(False)
ax2.spines['top'].set_visible(False)
ax2.spines['right'].set_visible(False)
ax1.invert_xaxis()
ax2.invert_xaxis()
ax1.legend(frameon=False, loc='upper right')
ax2.legend(frameon=False, loc='upper right')
figure1.tight_layout()
figure2.tight_layout()
if PLOT == True:
    figure1.savefig(f'plots/fig_snr_update_rate', dpi=600)
    figure2.savefig(f'plots/fig_snr_update_rate_new', dpi=600)
figure1.show()
figure2.show()
In [ ]:
#Multi Reduced Update Plot

import matplotlib.ticker as mtick
from scipy.interpolate import make_interp_spline

PLOT = False

# Daten aus .csv laden
update_rate_breathing = np.loadtxt('update_rate_evaluation/update_rate_breathing.csv', delimiter=";", skiprows=1)
update_rate_chewing = np.loadtxt('update_rate_evaluation/update_rate_chewing.csv', delimiter=";", skiprows=1)
update_rate_coughing = np.loadtxt('update_rate_evaluation/update_rate_coughing.csv', delimiter=";", skiprows=1)
update_rate_drinking = np.loadtxt('update_rate_evaluation/update_rate_drinking.csv', delimiter=";", skiprows=1)
update_rate_scratching = np.loadtxt('update_rate_evaluation/update_rate_scratching.csv', delimiter=";", skiprows=1)

# Daten laden
x = update_rate_breathing[:, 0]
update_gain_breathing = update_rate_breathing[:, 2]
update_cycles_breathing = update_rate_breathing[:, 4]
update_load_breathing = update_rate_breathing[:, 5]
update_gain_chewing = update_rate_chewing[:, 2]
update_cycles_chewing = update_rate_chewing[:, 4]
update_load_chewing = update_rate_chewing[:, 5]
update_gain_coughing = update_rate_coughing[:, 2]
update_cycles_coughing = update_rate_coughing[:, 4]
update_load_coughing = update_rate_coughing[:, 5]
update_gain_drinking = update_rate_drinking[:, 2]
update_cycles_drinking = update_rate_drinking[:, 4]
update_load_drinking = update_rate_drinking[:, 5]
update_gain_scratching = update_rate_scratching[:, 2]
update_cycles_scratching = update_rate_scratching[:, 4]  
update_load_scratching = update_rate_scratching[:, 5] 

# Sortieren
idx = np.argsort(x)
x = x[idx]
update_gain_breathing = update_gain_breathing[idx]
update_cycles_breathing = update_cycles_breathing[idx]
update_load_breathing = update_load_breathing[idx]
update_gain_chewing = update_gain_chewing[idx]
update_cycles_chewing = update_cycles_chewing[idx]
update_load_chewing = update_load_chewing[idx]
update_gain_coughing = update_gain_coughing[idx]
update_cycles_coughing = update_cycles_coughing[idx]
update_load_coughing = update_load_coughing[idx]
update_gain_drinking = update_gain_drinking[idx]
update_cycles_drinking = update_cycles_drinking[idx]
update_load_drinking = update_load_drinking[idx]
update_gain_scratching = update_gain_scratching[idx]
update_cycles_scratching = update_cycles_scratching[idx]
update_load_scratching = update_load_scratching[idx]

# Smoothing
x_smooth = np.linspace(x.min(), x.max(), 300)

gain_smooth_breathing = make_interp_spline(x, update_gain_breathing)(x_smooth)
cycles_smooth_breathing = make_interp_spline(x, update_cycles_breathing)(x_smooth)
load_smooth_breathing = make_interp_spline(x, update_load_breathing)(x_smooth)
gain_smooth_chewing = make_interp_spline(x, update_gain_chewing)(x_smooth)
cycles_smooth_chewing = make_interp_spline(x, update_cycles_chewing)(x_smooth)
load_smooth_chewing = make_interp_spline(x, update_load_chewing)(x_smooth)
gain_smooth_coughing = make_interp_spline(x, update_gain_coughing)(x_smooth)
cycles_smooth_coughing = make_interp_spline(x, update_cycles_coughing)(x_smooth)
load_smooth_coughing = make_interp_spline(x, update_load_coughing)(x_smooth)
gain_smooth_drinking = make_interp_spline(x, update_gain_drinking)(x_smooth)
cycles_smooth_drinking = make_interp_spline(x, update_cycles_drinking)(x_smooth)
load_smooth_drinking = make_interp_spline(x, update_load_drinking)(x_smooth)
gain_smooth_scratching = make_interp_spline(x, update_gain_scratching)(x_smooth)
cycles_smooth_scratching = make_interp_spline(x, update_cycles_scratching)(x_smooth)
load_smooth_scratching = make_interp_spline(x, update_load_scratching)(x_smooth)

diff_smooth_breathing = gain_smooth_breathing - cycles_smooth_breathing
diff_smooth_chewing = gain_smooth_chewing - cycles_smooth_chewing
diff_smooth_coughing = gain_smooth_coughing - cycles_smooth_coughing
diff_smooth_drinking = gain_smooth_drinking - cycles_smooth_drinking
diff_smooth_scratching = gain_smooth_scratching - cycles_smooth_scratching

# Alle Kurven in ein Array stapeln
stack_difference = np.vstack([
    diff_smooth_breathing,
    diff_smooth_chewing,
    diff_smooth_coughing,
    diff_smooth_drinking,
    diff_smooth_scratching
])

# Alle Kurven in ein Array stapeln
stack_load = np.vstack([
    load_smooth_breathing,
    load_smooth_chewing,
    load_smooth_coughing,
    load_smooth_drinking,
    load_smooth_scratching
])

# Punktweiser Mittelwert
mean_gain = np.mean(stack_difference, axis=0)
mean_load = np.mean(stack_load, axis=0)   

idx_max_gain = np.argmax(mean_gain)
x_max_gain = x_smooth[idx_max_gain]
y_max_gain = mean_gain[idx_max_gain]
x_max_load = x_smooth[idx_max_gain]
y_max_load = mean_load[idx_max_gain]


# Plot
figure1, ax1 = plt.subplots(figsize=(15, 7))
ax1.plot(x_smooth, diff_smooth_breathing, linestyle='--', color='indianred', linewidth=1.5, alpha=0.7, label='Breathing Noise')
ax1.plot(x_smooth, diff_smooth_chewing, linestyle='-.', color='skyblue', linewidth=1.5, alpha=0.7, label='Chewing Noise')
ax1.plot(x_smooth, diff_smooth_coughing, linestyle=':', color='forestgreen', linewidth=1.5, alpha=0.7, label='Coughing Noise')
ax1.plot(x_smooth, diff_smooth_drinking, linestyle='--', color='darkorange', linewidth=1.5, alpha=0.7, label='Drinking Noise')
ax1.plot(x_smooth, diff_smooth_scratching, linestyle='-.', color='darkorchid', linewidth=1.5, alpha=0.7, label='Scratching Noise')
ax1.plot(x_smooth, mean_gain, linestyle='--', color='red', linewidth=2.5, alpha=1, label='Mean Performance Gain')
ax1.plot([x_max_gain, x_max_gain], [y_max_gain, 0], color='black', linestyle=':', linewidth=2)

ax1.text(x_max_gain+0.38, y_max_gain+0.03,
         f'{y_max_gain*100:.1f} \% mean performance gain at update rate {x_max_gain:.2f}',
         fontsize=20,
         ha='left')

figure2, ax2 = plt.subplots(figsize=(15, 7))
ax2.plot(x_smooth, load_smooth_breathing, linestyle='--', color='indianred', linewidth=1.5, alpha=0.7, label='Breathing Noise')
ax2.plot(x_smooth, load_smooth_chewing, linestyle='-.', color='skyblue', linewidth=1.5, alpha=0.7, label='Chewing Noise')
ax2.plot(x_smooth, load_smooth_coughing, linestyle=':', color='forestgreen', linewidth=1.5, alpha=0.7, label='Coughing Noise')
ax2.plot(x_smooth, load_smooth_drinking, linestyle='--', color='darkorange', linewidth=1.5, alpha=0.7, label='Drinking Noise')
ax2.plot(x_smooth, load_smooth_scratching, linestyle='-.', color='darkorchid', linewidth=1.5, alpha=0.7, label='Scratching Noise')
ax2.plot(x_smooth, mean_load, linestyle='--', color='blue', linewidth=2.5, alpha=1, label='Mean DSP Load')
ax2.plot([x_max_load, x_max_load], [y_max_load, 0], color='black', linestyle=':', linewidth=2)

ax2.text(x_max_load+0.32, y_max_load-0.04,
         f'{y_max_load*100:.1f} \% mean DSP load at update rate {x_max_load:.2f}',
         fontsize=20,
         ha='left')

plt.rcParams.update({
    "text.usetex": True,
    "font.family": "serif",
    'font.size': 16,          # Standardtext
    'axes.labelsize': 30,     # Achsenbeschriftungen
    'xtick.labelsize': 25,    # Tick-Beschriftungen
    'ytick.labelsize': 25,
    'legend.fontsize': 25     # Legende
})

ax1.set_xlabel("Update Rate")
ax2.set_xlabel("Update Rate")
ax1.set_ylabel("Performance Gain")
ax2.set_ylabel("DSP Load")
ax1.grid(True, linestyle='-.', alpha=0.4)
ax2.grid(True, linestyle='-.', alpha=0.4)
ax1.set_ylim(0, 1)
ax2.set_ylim(0, 0.7)
#Spines auf ganzen Plot anwenden
ax1.yaxis.set_major_formatter(mtick.PercentFormatter(1.0))
ax2.yaxis.set_major_formatter(mtick.PercentFormatter(1.0))
ax1.spines['top'].set_visible(False)
ax2.spines['top'].set_visible(False)
ax1.spines['right'].set_visible(False)
ax2.spines['right'].set_visible(False)
ax1.legend(frameon=False, loc='upper right')
ax2.legend(frameon=False, loc='upper right')
ax1.invert_xaxis()
ax2.invert_xaxis()
figure1.tight_layout()
figure2.tight_layout()
if PLOT == True:
    figure1.savefig(f'plots/fig_gain_update_rate', dpi=600)
    figure2.savefig(f'plots/fig_load_update_rate', dpi=600)
figure1.show()
figure2.show()




In [ ]:
#Single Error Threshold Plot

import matplotlib.ticker as mtick
from scipy.interpolate import make_interp_spline

PLOT = False

# Daten aus .csv laden
data_error_threshold = np.loadtxt('threshold_evaluation/error_threshold_breathing.csv', delimiter=";", skiprows=1)

# Daten laden
x = data_error_threshold[:, 0]
error_gain = data_error_threshold[:, 2]
error_cycles = data_error_threshold[:, 6]
error_load = data_error_threshold[:, 7]
error_cycles_new = data_error_threshold[:, 9]
error_load_new = data_error_threshold[:, 10]

# Sortieren
idx = np.argsort(x)
x = x[idx]
error_gain = error_gain[idx]
error_cycles = error_cycles[idx]
error_load = error_load[idx]
error_cycles_new = error_cycles_new[idx]
error_load_new = error_load_new[idx]
# Smoothing
x_smooth = np.linspace(x.min(), x.max(), 300)

gain_smooth = make_interp_spline(x, error_gain)(x_smooth)
cycles_smooth = make_interp_spline(x, error_cycles)(x_smooth)
load_smooth = make_interp_spline(x, error_load)(x_smooth)
cycles_smooth_new = make_interp_spline(x, error_cycles_new)(x_smooth)
load_smooth_new = make_interp_spline(x, error_load_new)(x_smooth)

diff_smooth = np.abs(gain_smooth - cycles_smooth)
idx_max = np.argmax(diff_smooth)
x_max = x_smooth[idx_max]
y1_max = gain_smooth[idx_max]
y2_max = cycles_smooth[idx_max]

# Plot
figure1, ax1 = plt.subplots(figsize=(15, 7))
ax1.plot(x_smooth, gain_smooth, linestyle='--', color='indianred', linewidth=2, alpha=0.9, label='SNR-Gain')
ax1.plot(x_smooth, cycles_smooth, linestyle='-.', color='skyblue', linewidth=2, alpha=0.9, label='Cycles/Sample')
ax1.plot(x_smooth, load_smooth, linestyle=':', color='forestgreen', linewidth=2, alpha=0.9, label='DSP Load')
ax1.plot([x_max, x_max], [y1_max, y2_max], color='black', linestyle=':', linewidth=2)

ax1.scatter(x, error_gain, color='indianred', s=40)
ax1.scatter(x, error_cycles, color='skyblue', s=40)
ax1.scatter(x, error_load, color='forestgreen', s=40)

figure2, ax2 = plt.subplots(figsize=(15, 7))
ax2.plot(x_smooth, gain_smooth, linestyle='--', color='indianred', linewidth=2, alpha=0.9, label='SNR-Gain')
ax2.plot(x_smooth, cycles_smooth, linestyle='-.', color='skyblue', linewidth=2, alpha=0.3)
ax2.plot(x_smooth, load_smooth, linestyle=':', color='forestgreen', linewidth=2, alpha=0.3)
ax2.plot(x_smooth, cycles_smooth_new, linestyle='-', color='skyblue', linewidth=2, alpha=0.9, label='Cycles/Sample (New)')
ax2.plot(x_smooth, load_smooth_new, linestyle='-', color='forestgreen', linewidth=2, alpha=0.9, label='DSP Load (New)')


ax2.scatter(x, error_gain, color='indianred', s=40)
ax2.scatter(x, error_cycles, color='skyblue', s=40, alpha=0.3)
ax2.scatter(x, error_load, color='forestgreen', s=40, alpha=0.3)
ax2.scatter(x, error_cycles_new, color='skyblue', s=40,)
ax2.scatter(x, error_load_new, color='forestgreen', s=40)

ax1.text(x_max, (y1_max + y2_max)/2+0.21,
         f'Max. offset at threshold {x_max:.2f}',
         fontsize=20,
         ha='left')

plt.rcParams.update({
    "text.usetex": True,
    "font.family": "serif",
    'font.size': 16,          # Standardtext
    'axes.labelsize': 30,     # Achsenbeschriftungen
    'xtick.labelsize': 25,    # Tick-Beschriftungen
    'ytick.labelsize': 25,
    'legend.fontsize': 25     # Legende
})

ax1.set_xlabel("Error Threshold")
ax1.set_ylabel("Relative Performance")
ax2.set_xlabel("Error Threshold")
ax2.set_ylabel("Relative Performance")
ax1.grid(True, linestyle='-.', alpha=0.4)
ax2.grid(True, linestyle='-.', alpha=0.4)
#Spines auf ganzen Plot anwenden
ax1.yaxis.set_major_formatter(mtick.PercentFormatter(1.0))
ax2.yaxis.set_major_formatter(mtick.PercentFormatter(1.0))
ax1.spines['top'].set_visible(False)
ax1.spines['right'].set_visible(False)
ax2.spines['top'].set_visible(False)
ax2.spines['right'].set_visible(False)
ax1.legend(frameon=False, loc='upper right')
ax2.legend(frameon=False, loc='upper right')
figure1.tight_layout()
figure2.tight_layout()
if PLOT == True:
    figure1.savefig(f'plots/fig_snr_error_threshold', dpi=600)
    figure2.savefig(f'plots/fig_snr_error_threshold_new', dpi=600)
figure1.show()
figure2.show()
In [ ]:
#Multi Error Threshold Plot

import matplotlib.ticker as mtick
from scipy.interpolate import make_interp_spline

PLOT = False

# Daten aus .csv laden
error_threshold_breathing = np.loadtxt('threshold_evaluation/error_threshold_breathing.csv', delimiter=";", skiprows=1)
error_threshold_chewing = np.loadtxt('threshold_evaluation/error_threshold_chewing.csv', delimiter=";", skiprows=1)
error_threshold_coughing = np.loadtxt('threshold_evaluation/error_threshold_coughing.csv', delimiter=";", skiprows=1)
error_threshold_drinking = np.loadtxt('threshold_evaluation/error_threshold_drinking.csv', delimiter=";", skiprows=1)
error_threshold_scratching = np.loadtxt('threshold_evaluation/error_threshold_scratching.csv', delimiter=";", skiprows=1)

# Daten laden
x = error_threshold_breathing[:, 0]
error_gain_breathing = error_threshold_breathing[:, 2]
error_cycles_breathing = error_threshold_breathing[:, 6]
error_load_breathing = error_threshold_breathing[:, 7]
error_gain_chewing = error_threshold_chewing[:, 2]
error_cycles_chewing = error_threshold_chewing[:, 6]
error_load_chewing = error_threshold_chewing[:, 7]
error_gain_coughing = error_threshold_coughing[:, 2]
error_cycles_coughing = error_threshold_coughing[:, 6]
error_load_coughing = error_threshold_coughing[:, 7]
error_gain_drinking = error_threshold_drinking[:, 2]
error_cycles_drinking = error_threshold_drinking[:, 6]
error_load_drinking = error_threshold_drinking[:, 7]
error_gain_scratching = error_threshold_scratching[:, 2]
error_cycles_scratching = error_threshold_scratching[:, 6]  
error_load_scratching = error_threshold_scratching[:, 7] 

# Sortieren
idx = np.argsort(x)
x = x[idx]
error_gain_breathing = error_gain_breathing[idx]
error_cycles_breathing = error_cycles_breathing[idx]
error_load_breathing = error_load_breathing[idx]
error_gain_chewing = error_gain_chewing[idx]
error_cycles_chewing = error_cycles_chewing[idx]
error_load_chewing = error_load_chewing[idx]
error_gain_coughing = error_gain_coughing[idx]
error_cycles_coughing = error_cycles_coughing[idx]
error_load_coughing = error_load_coughing[idx]
error_gain_drinking = error_gain_drinking[idx]
error_cycles_drinking = error_cycles_drinking[idx]
error_load_drinking = error_load_drinking[idx]
error_gain_scratching = error_gain_scratching[idx]
error_cycles_scratching = error_cycles_scratching[idx]
error_load_scratching = error_load_scratching[idx]

# Smoothing
x_smooth = np.linspace(x.min(), x.max(), 300)

gain_smooth_breathing = make_interp_spline(x, error_gain_breathing)(x_smooth)
cycles_smooth_breathing = make_interp_spline(x, error_cycles_breathing)(x_smooth)
load_smooth_breathing = make_interp_spline(x, error_load_breathing)(x_smooth)
gain_smooth_chewing = make_interp_spline(x, error_gain_chewing)(x_smooth)
cycles_smooth_chewing = make_interp_spline(x, error_cycles_chewing)(x_smooth)
load_smooth_chewing = make_interp_spline(x, error_load_chewing)(x_smooth)
gain_smooth_coughing = make_interp_spline(x, error_gain_coughing)(x_smooth)
cycles_smooth_coughing = make_interp_spline(x, error_cycles_coughing)(x_smooth)
load_smooth_coughing = make_interp_spline(x, error_load_coughing)(x_smooth)
gain_smooth_drinking = make_interp_spline(x, error_gain_drinking)(x_smooth)
cycles_smooth_drinking = make_interp_spline(x, error_cycles_drinking)(x_smooth)
load_smooth_drinking = make_interp_spline(x, error_load_drinking)(x_smooth)
gain_smooth_scratching = make_interp_spline(x, error_gain_scratching)(x_smooth)
cycles_smooth_scratching = make_interp_spline(x, error_cycles_scratching)(x_smooth)
load_smooth_scratching = make_interp_spline(x, error_load_scratching)(x_smooth)

diff_smooth_breathing = gain_smooth_breathing - cycles_smooth_breathing
diff_smooth_chewing = gain_smooth_chewing - cycles_smooth_chewing
diff_smooth_coughing = gain_smooth_coughing - cycles_smooth_coughing
diff_smooth_drinking = gain_smooth_drinking - cycles_smooth_drinking
diff_smooth_scratching = gain_smooth_scratching - cycles_smooth_scratching

# Alle Kurven in ein Array stapeln
stack_difference = np.vstack([
    diff_smooth_breathing,
    diff_smooth_chewing,
    diff_smooth_coughing,
    diff_smooth_drinking,
    diff_smooth_scratching
])

# Alle Kurven in ein Array stapeln
stack_load = np.vstack([
    load_smooth_breathing,
    load_smooth_chewing,
    load_smooth_coughing,
    load_smooth_drinking,
    load_smooth_scratching
])

# Punktweiser Mittelwert
mean_gain = np.mean(stack_difference, axis=0)
mean_load = np.mean(stack_load, axis=0)   

idx_max_gain = np.argmax(mean_gain)
x_max_gain = x_smooth[idx_max_gain]
y_max_gain = mean_gain[idx_max_gain]
x_max_load = x_smooth[idx_max_gain]
y_max_load = mean_load[idx_max_gain]


# Plot
figure1, ax1 = plt.subplots(figsize=(15, 7))
ax1.plot(x_smooth, diff_smooth_breathing, linestyle='--', color='indianred', linewidth=1.5, alpha=0.7, label='Breathing Noise')
ax1.plot(x_smooth, diff_smooth_chewing, linestyle='-.', color='skyblue', linewidth=1.5, alpha=0.7, label='Chewing Noise')
ax1.plot(x_smooth, diff_smooth_coughing, linestyle=':', color='forestgreen', linewidth=1.5, alpha=0.7, label='Coughing Noise')
ax1.plot(x_smooth, diff_smooth_drinking, linestyle='--', color='darkorange', linewidth=1.5, alpha=0.7, label='Drinking Noise')
ax1.plot(x_smooth, diff_smooth_scratching, linestyle='-.', color='darkorchid', linewidth=1.5, alpha=0.7, label='Scratching Noise')
ax1.plot(x_smooth, mean_gain, linestyle='--', color='red', linewidth=2.5, alpha=1, label='Mean Performance Gain')
ax1.plot([x_max_gain, x_max_gain], [y_max_gain, 0], color='black', linestyle=':', linewidth=2)

ax1.text(x_max_gain, y_max_gain+0.01,
         f'{y_max_gain*100:.1f} \% mean performance gain at error threshold {x_max_gain:.2f}',
         fontsize=20,
         ha='left')

figure2, ax2 = plt.subplots(figsize=(15, 7))
ax2.plot(x_smooth, load_smooth_breathing, linestyle='--', color='indianred', linewidth=1.5, alpha=0.7, label='Breathing Noise')
ax2.plot(x_smooth, load_smooth_chewing, linestyle='-.', color='skyblue', linewidth=1.5, alpha=0.7, label='Chewing Noise')
ax2.plot(x_smooth, load_smooth_coughing, linestyle=':', color='forestgreen', linewidth=1.5, alpha=0.7, label='Coughing Noise')
ax2.plot(x_smooth, load_smooth_drinking, linestyle='--', color='darkorange', linewidth=1.5, alpha=0.7, label='Drinking Noise')
ax2.plot(x_smooth, load_smooth_scratching, linestyle='-.', color='darkorchid', linewidth=1.5, alpha=0.7, label='Scratching Noise')
ax2.plot(x_smooth, mean_load, linestyle='--', color='blue', linewidth=2.5, alpha=1, label='Mean DSP Load')
ax2.plot([x_max_load, x_max_load], [y_max_load, 0], color='black', linestyle=':', linewidth=2)

ax2.text(x_max_load, y_max_load+0.01,
         f'{y_max_load*100:.1f} \% mean DSP load at error threshold {x_max_load:.2f}',
         fontsize=20,
         ha='left')

plt.rcParams.update({
    "text.usetex": True,
    "font.family": "serif",
    'font.size': 16,          # Standardtext
    'axes.labelsize': 30,     # Achsenbeschriftungen
    'xtick.labelsize': 25,    # Tick-Beschriftungen
    'ytick.labelsize': 25,
    'legend.fontsize': 25     # Legende
})

ax1.set_xlabel("Error Threshold")
ax2.set_xlabel("Error Threshold")
ax1.set_ylabel("Performance Gain")
ax2.set_ylabel("DSP Load")
ax1.grid(True, linestyle='-.', alpha=0.4)
ax2.grid(True, linestyle='-.', alpha=0.4)
ax1.set_ylim(0, 1)
ax2.set_ylim(0, 0.7)
#Spines auf ganzen Plot anwenden
ax1.yaxis.set_major_formatter(mtick.PercentFormatter(1.0))
ax2.yaxis.set_major_formatter(mtick.PercentFormatter(1.0))
ax1.spines['top'].set_visible(False)
ax2.spines['top'].set_visible(False)
ax1.spines['right'].set_visible(False)
ax2.spines['right'].set_visible(False)
ax1.legend(frameon=False, loc='upper right')
ax2.legend(frameon=False, loc='upper right')
figure1.tight_layout()
figure2.tight_layout()
if PLOT == True:
    figure1.savefig(f'plots/fig_gain_error_threshold', dpi=600)
    figure2.savefig(f'plots/fig_load_error_threshold', dpi=600)
figure1.show()
figure2.show()