Posts tagged phonocardiogram
BioAcousticSpectralNet: Classifying Cardiopulmonary Pathologies via Fractional-Order Phase-Space Attractors in PyTorch
Why do standard medical audio classifiers miss electromechanical cardiac pathology?
Conventional deep learning pipelines for stethoscope audio (phonocardiograms) convert 1D acoustic waveforms into 2D Short-Time Fourier Transform (STFT) or Mel-spectrogram images and feed them into standard vision backbones. While effective for speech recognition, linear spectrograms suffer from two fundamental physical limitations in clinical cardiology:
- Loss of Non-Linear Phase Geometry: Turbulent blood flow across stenotic or regurgitant heart valves generates deterministic chaotic dynamics whose phase trajectories are erased when taking the magnitude-squared power spectrum.
- Blindness to Electromechanical Coupling: Acoustic valve closure (Phonocardiogram, PCG) and sternal chest-wall recoil acceleration (Seismocardiogram, SCG) are physically coupled. Measuring acoustic intensity alone ignores the mechanical phase delay between myocardial contraction and acoustic emission.
To solve this, we introduce BioAcousticSpectralNet (BAS-Net)—a PyTorch architecture that replaces traditional spectrograms with a 3-channel topological tensor constructed from Takens’ Delay-Embedding Theorem, Grünwald–Letnikov Fractional Calculus, and Hilbert Phase Coherence.
Reconstructing Viscoelastic Phase-Space Attractors via Fractional Derivatives
By Floris Takens’ 1981 embedding theorem, the full state-space topology of a non-linear dynamical system can be reconstructed from a single scalar time series x(t) by plotting the signal against its time-delayed derivatives. However, biological myocardial tissue exhibits power-law viscoelastic damping rather than pure Newtonian viscosity. Standard integer-order derivatives (dx/dt) amplify high-frequency sensor noise, whereas a Grünwald–Letnikov fractional derivative of order α ∈ (0, 1) captures hereditary tissue memory smoothly:
Dαx[n] = (1 / Δtα) Σk=0..M−1 (−1)k Γ(α + 1) / [Γ(k + 1)Γ(α − k + 1)] · x[n − k]
Using α = 0.65 and a time-delay lag τ, BAS-Net projects synchronized PCG and SCG recordings onto a unified 64 × 64 × 3 phase-space tensor:
- Channel 0 (Acoustic Attractor Manifold): Log-compressed 2D occupancy density of (xPCG(t), DαxPCG(t − τ)).
- Channel 1 (Mechanical Recoil Manifold): Log-compressed 2D occupancy density of (xSCG(t), DαxSCG(t − τ)).
- Channel 2 (Cross-Modal Hilbert Phase-Locking Index): Instantaneous analytic phase coherence cos(φPCG(t) − φSCG(t)) extracted via the Hilbert transform and projected onto the joint attractor grid.
Implementing Fractional Takens Extraction & BAS-Net in PyTorch
Below is the core signal-processing and neural network architecture. Parallel 3 × 3 and 5 × 5 depthwise-separable convolutions capture both fine local limit-cycle splits (e.g., S3/S4 gallop harmonics) and global murmur trajectories, weighted dynamically by Squeeze-and-Excitation (SE) channel attention:
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from scipy.signal import butter, filtfilt, hilbert
def fractional_grunwald_letnikov_diff(
signal: np.ndarray, alpha: float = 0.65, dt: float = 1.0 / 2000.0, memory_len: int = 64
) -> np.ndarray:
weights = np.zeros(memory_len, dtype=np.float64)
weights[0] = 1.0
for k in range(1, memory_len):
weights[k] = weights[k - 1] * ((k - 1.0 - alpha) / k)
scale = dt ** (-alpha)
diff_sig = np.convolve(signal.astype(np.float64), weights, mode="same") * scale
return diff_sig.astype(np.float32)
def reconstruct_takens_attractor_tensor(
pcg_raw: np.ndarray,
scg_raw: np.ndarray,
fs: float = 2000.0,
tau_samples: int = 12,
alpha: float = 0.65,
grid_size: int = 64,
) -> np.ndarray:
nyq = 0.5 * fs
b_pcg, a_pcg = butter(4, [20.0 / nyq, min(450.0 / nyq, 0.99)], btype="band")
b_scg, a_scg = butter(4, [1.0 / nyq, min(100.0 / nyq, 0.99)], btype="band")
pcg_filt = filtfilt(b_pcg, a_pcg, pcg_raw).astype(np.float32)
scg_filt = filtfilt(b_scg, a_scg, scg_raw).astype(np.float32)
pcg_norm = (pcg_filt - np.mean(pcg_filt)) / (np.std(pcg_filt) + 1e-8)
scg_norm = (scg_filt - np.mean(scg_filt)) / (np.std(scg_filt) + 1e-8)
d_pcg = fractional_grunwald_letnikov_diff(pcg_norm, alpha=alpha, dt=1.0 / fs)
d_scg = fractional_grunwald_letnikov_diff(scg_norm, alpha=alpha, dt=1.0 / fs)
d_pcg = (d_pcg - np.mean(d_pcg)) / (np.std(d_pcg) + 1e-8)
d_scg = (d_scg - np.mean(d_scg)) / (np.std(d_scg) + 1e-8)
phi_pcg = np.angle(hilbert(pcg_norm))
phi_scg = np.angle(hilbert(scg_norm))
phase_coherence = np.cos(phi_pcg - phi_scg).astype(np.float32)
n = len(pcg_norm) - tau_samples
x0, y0 = np.clip(pcg_norm[tau_samples:], -3.5, 3.5), np.clip(d_pcg[:n], -3.5, 3.5)
x1, y1 = np.clip(scg_norm[tau_samples:], -3.5, 3.5), np.clip(d_scg[:n], -3.5, 3.5)
coh = phase_coherence[tau_samples:]
bins = np.linspace(-3.5, 3.5, grid_size + 1)
hist_pcg, _, _ = np.histogram2d(x0, y0, bins=[bins, bins])
hist_scg, _, _ = np.histogram2d(x1, y1, bins=[bins, bins])
hist_coh, _, _ = np.histogram2d(x0, y1, bins=[bins, bins], weights=coh)
ch0 = np.log1p(hist_pcg) / (np.max(np.log1p(hist_pcg)) + 1e-8)
ch1 = np.log1p(hist_scg) / (np.max(np.log1p(hist_scg)) + 1e-8)
ch2 = hist_coh / (np.max(np.abs(hist_coh)) + 1e-8)
return np.stack([ch0, ch1, ch2], axis=0).astype(np.float32)
class FractionalAttractorBlock(nn.Module):
def __init__(self, channels: int, reduction: int = 4) -> None:
super().__init__()
self.dw_conv3 = nn.Conv2d(channels, channels, 3, padding=1, groups=channels, bias=False)
self.dw_conv5 = nn.Conv2d(channels, channels, 5, padding=2, groups=channels, bias=False)
self.pw_fuse = nn.Conv2d(channels * 2, channels, 1, bias=False)
self.bn = nn.BatchNorm2d(channels)
hidden = max(channels // reduction, 8)
self.se = nn.Sequential(
nn.AdaptiveAvgPool2d(1),
nn.Conv2d(channels, hidden, 1),
nn.SiLU(inplace=True),
nn.Conv2d(hidden, channels, 1),
nn.Sigmoid(),
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
fused = F.silu(self.bn(self.pw_fuse(torch.cat([self.dw_conv3(x), self.dw_conv5(x)], dim=1))))
return x + fused * self.se(fused)
class BioAcousticSpectralNet(nn.Module):
def __init__(self, num_classes: int = 4, base_channels: int = 32) -> None:
super().__init__()
self.stem = nn.Sequential(
nn.Conv2d(3, base_channels, 3, padding=1, bias=False),
nn.BatchNorm2d(base_channels),
nn.SiLU(inplace=True),
)
self.stage1 = nn.Sequential(
FractionalAttractorBlock(base_channels),
nn.Conv2d(base_channels, base_channels * 2, 3, stride=2, padding=1, bias=False),
nn.BatchNorm2d(base_channels * 2),
nn.SiLU(inplace=True),
)
self.stage2 = nn.Sequential(
FractionalAttractorBlock(base_channels * 2),
nn.Conv2d(base_channels * 2, base_channels * 4, 3, stride=2, padding=1, bias=False),
nn.BatchNorm2d(base_channels * 4),
nn.SiLU(inplace=True),
)
self.stage3 = FractionalAttractorBlock(base_channels * 4)
self.pool = nn.AdaptiveAvgPool2d(1)
self.dropout = nn.Dropout(p=0.25)
self.classifier = nn.Linear(base_channels * 4, num_classes)
def forward(self, x: torch.Tensor) -> torch.Tensor:
h = self.stage3(self.stage2(self.stage1(self.stem(x))))
return self.classifier(self.dropout(self.pool(h).flatten(1)))
Clinical & Architectural Advantages Over Spectrogram Backbones
Because the phase-space manifold integrates over full cardiac cycles into a fixed 64 × 64 spatial grid regardless of recording duration, BAS-Net is inherently invariant to heart-rate variability (HRV) stretching that distorts fixed-width time-frequency spectrograms. Furthermore, using depthwise-separable convolutions keeps the entire model under 65,000 parameters—enabling real-time, low-power inference directly on edge microcontrollers and wearable digital stethoscopes.
Source Code: Download, inspect, and run the complete PyTorch implementation and synthetic cardiac waveform benchmark on GitHub: ratawil/BioAcousticSpectralNet