File size: 2,247 Bytes
27d7ce9 7bceef4 |
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 51 52 53 54 55 56 57 58 59 60 61 |
import numpy as np
from scipy.fft import rfft, rfftfreq
from scipy.signal import hilbert
from typing import Dict, Tuple
def analyze_cognitive_signal(
state_deltas: np.ndarray,
sampling_rate: float = 1.0 # Wir nehmen an, dass jeder "Step" eine Zeiteinheit ist
) -> Dict[str, float]:
"""
Führt eine fortgeschrittene Signalverarbeitungs-Analyse auf der Zeitreihe der
State Deltas durch, um den "kognitiven Frequenz-Fingerabdruck" zu extrahieren.
"""
if len(state_deltas) < 2:
return {}
# 1. Fourier-Analyse (FFT)
n = len(state_deltas)
yf = rfft(state_deltas - np.mean(state_deltas)) # Entferne DC-Offset
xf = rfftfreq(n, 1 / sampling_rate)
power_spectrum = np.abs(yf)**2
# 2. Extrahiere Metriken aus dem Spektrum
if len(power_spectrum) > 1:
# Dominante Frequenz (ohne die 0-Hz-Komponente)
dominant_freq_index = np.argmax(power_spectrum[1:]) + 1
dominant_frequency = xf[dominant_freq_index]
# Spektrale Entropie (Maß für die Komplexität/Rauschhaftigkeit)
prob_dist = power_spectrum / np.sum(power_spectrum)
prob_dist = prob_dist[prob_dist > 0] # Vermeide log(0)
spectral_entropy = -np.sum(prob_dist * np.log2(prob_dist))
else:
dominant_frequency = 0.0
spectral_entropy = 0.0
# 3. Hilbert-Transformation zur Phasen-Analyse (hier nur als Beispiel,
# da die Interpretation komplex ist und im UI schwer darstellbar)
# analytic_signal = hilbert(state_deltas)
# instantaneous_phase = np.unwrap(np.angle(analytic_signal))
# instantaneous_frequency = (np.diff(instantaneous_phase) / (2.0*np.pi) * sampling_rate)
return {
"dominant_frequency": float(dominant_frequency),
"spectral_entropy": float(spectral_entropy),
}
def get_power_spectrum_for_plotting(state_deltas: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
"""
Berechnet das Leistungsspektrum speziell für die Visualisierung.
"""
if len(state_deltas) < 2:
return np.array([]), np.array([])
n = len(state_deltas)
yf = rfft(state_deltas - np.mean(state_deltas))
xf = rfftfreq(n, 1.0)
power_spectrum = np.abs(yf)**2
return xf, power_spectrum |