neural-emd 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,8 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ .venv/
4
+ dist/
5
+ build/
6
+ *.egg-info/
7
+ .pytest_cache/
8
+ checkpoints/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Aous Abdo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,151 @@
1
+ Metadata-Version: 2.5
2
+ Name: neural-emd
3
+ Version: 0.1.0
4
+ Summary: Neural Empirical Mode Decomposition: a differentiable, learned replacement for EMD sifting, in PyTorch
5
+ Project-URL: Homepage, https://github.com/aousabdo/neural-emd
6
+ Project-URL: Issues, https://github.com/aousabdo/neural-emd/issues
7
+ Author: Aous Abdo
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: decomposition,emd,empirical-mode-decomposition,hilbert-huang,pytorch,signal-processing,time-series
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
19
+ Classifier: Topic :: Scientific/Engineering :: Information Analysis
20
+ Requires-Python: >=3.11
21
+ Requires-Dist: numpy>=1.24
22
+ Requires-Dist: scipy>=1.11
23
+ Requires-Dist: torch>=2.0
24
+ Provides-Extra: baselines
25
+ Requires-Dist: emd-signal>=1.5; extra == 'baselines'
26
+ Requires-Dist: vmdpy>=0.2; extra == 'baselines'
27
+ Provides-Extra: dev
28
+ Requires-Dist: emd-signal>=1.5; extra == 'dev'
29
+ Requires-Dist: pytest>=7.0; extra == 'dev'
30
+ Requires-Dist: vmdpy>=0.2; extra == 'dev'
31
+ Description-Content-Type: text/markdown
32
+
33
+ # neural-emd
34
+
35
+ **N-EMD: Neural Empirical Mode Decomposition.** A differentiable replacement for the
36
+ iterative sifting in Empirical Mode Decomposition (EMD), written in PyTorch.
37
+
38
+ Classical EMD splits a signal into intrinsic mode functions (IMFs) by repeated
39
+ envelope fitting. It works without assumptions about the signal, but it is not
40
+ differentiable, the number of IMFs is whatever the sifting produces, and it is prone
41
+ to mode mixing. N-EMD learns the decomposition instead:
42
+
43
+ 1. take the signal's spectrum (rFFT),
44
+ 2. a small 1-D CNN reads magnitude and phase and predicts *K* filter responses,
45
+ 3. a softmax across the *K* filters turns them into a partition of unity,
46
+ 4. each filter is applied to the spectrum and inverted back to the time domain.
47
+
48
+ That construction gives three guarantees by design, not by training:
49
+
50
+ - **Exact reconstruction.** The IMFs always sum back to the input.
51
+ - **Band-limited IMFs.** Every filter is non-negative, so each IMF is a bandpass of the input.
52
+ - **No energy inflation.** The IMFs' total energy can never exceed the signal's.
53
+
54
+ Training only has to make the filters sharp, ordered by frequency and orthogonal.
55
+ Because the whole pipeline is differentiable, N-EMD can sit inside a larger model and
56
+ be trained end to end with a downstream loss.
57
+
58
+ ## Install
59
+
60
+ ```bash
61
+ pip install neural-emd # the library: torch, numpy, scipy
62
+ pip install "neural-emd[baselines]" # adds classical EMD / EEMD / VMD for comparison
63
+ ```
64
+
65
+ The import name is `nemd`. Python 3.11 or newer.
66
+
67
+ ## Quick start
68
+
69
+ [`examples/quickstart.py`](examples/quickstart.py) fits N-EMD to a single noisy signal
70
+ made of three AM-FM tones (50, 15 and 3 Hz) and compares it with classical EMD:
71
+
72
+ ```python
73
+ import numpy as np
74
+ import torch
75
+
76
+ from nemd.classical import ClassicalEMD
77
+ from nemd.train import overfit_single_signal
78
+ from nemd.utils import generate_synthetic_signal, mode_mixing_index, reconstruction_error
79
+
80
+ t, x, truth = generate_synthetic_signal(
81
+ n_samples=1000,
82
+ components=[
83
+ {"f0": 50.0, "f_mod": 2.0, "a_mod": 0.5},
84
+ {"f0": 15.0, "f_mod": 0.5, "a_mod": 0.3},
85
+ {"f0": 3.0, "f_mod": 0.1, "a_mod": 0.2},
86
+ ],
87
+ noise_std=0.05,
88
+ seed=42,
89
+ )
90
+
91
+ out = overfit_single_signal(torch.tensor(x, dtype=torch.float32),
92
+ num_imfs=3, num_steps=1500, fs=1000.0, verbose=False)
93
+ imfs = out["imfs"].detach().numpy() # (3, 1000)
94
+ ```
95
+
96
+ Output on a laptop CPU (about 30 seconds):
97
+
98
+ ```
99
+ N-EMD IMF dominant frequencies (Hz): [58.0, 16.0, 3.0]
100
+ N-EMD reconstruction error: 1.96e-07
101
+ N-EMD mode-mixing index: 0.241
102
+ EMD mode-mixing index: 0.236 (6 IMFs)
103
+ EMD first 3 IMF dominant frequencies (Hz): [58.0, 42.0, 15.0]
104
+ ```
105
+
106
+ N-EMD returns exactly the three components asked for, one per tone, and reconstructs
107
+ the signal to float precision. Classical EMD splits the same signal into six IMFs,
108
+ including a spurious 42 Hz mode.
109
+
110
+ ## Training on a dataset
111
+
112
+ For signals from one family, train a model once and reuse it rather than fitting
113
+ each signal:
114
+
115
+ ```python
116
+ from nemd.train import TrainConfig, train
117
+
118
+ result = train(TrainConfig(num_imfs=3, signal_length=1024, sample_rate=1000.0, num_epochs=100))
119
+ model = result["model"] # nemd.model.NEMD
120
+ imfs, residual, meta = model(batch) # batch: (B, T) tensor -> imfs: (B, K, T)
121
+ ```
122
+
123
+ `train` generates synthetic training data by default. Pass `dataset_fn` to train on
124
+ your own signals. Best and final weights are saved to `TrainConfig.save_dir`.
125
+
126
+ ## What's in the package
127
+
128
+ | Module | Contents |
129
+ |---|---|
130
+ | `nemd.model` | `NEMD`, the filter-bank model; `NEMDSifting`, the earlier iterative variant kept for ablations |
131
+ | `nemd.losses` | Filter sharpness, frequency ordering, orthogonality, balance and the combined `NEMDLoss` |
132
+ | `nemd.train` | `TrainConfig`, `train`, `overfit_single_signal` |
133
+ | `nemd.utils` | Synthetic AM-FM, chirp and nonstationary signal generators; reconstruction error, orthogonality index, mode-mixing index, IF tracking error |
134
+ | `nemd.classical` | Thin wrappers for EMD, EEMD (PyEMD) and VMD (vmdpy), with the `[baselines]` extra |
135
+
136
+ ## Status
137
+
138
+ Research code, alpha. The API may change before 1.0. A paper describing the method
139
+ and its evaluation is in preparation. Until then, please cite this repository if you
140
+ use it.
141
+
142
+ ## Development
143
+
144
+ ```bash
145
+ pip install -e ".[dev]"
146
+ pytest
147
+ ```
148
+
149
+ ## License
150
+
151
+ MIT. Copyright (c) 2026 Aous Abdo.
@@ -0,0 +1,119 @@
1
+ # neural-emd
2
+
3
+ **N-EMD: Neural Empirical Mode Decomposition.** A differentiable replacement for the
4
+ iterative sifting in Empirical Mode Decomposition (EMD), written in PyTorch.
5
+
6
+ Classical EMD splits a signal into intrinsic mode functions (IMFs) by repeated
7
+ envelope fitting. It works without assumptions about the signal, but it is not
8
+ differentiable, the number of IMFs is whatever the sifting produces, and it is prone
9
+ to mode mixing. N-EMD learns the decomposition instead:
10
+
11
+ 1. take the signal's spectrum (rFFT),
12
+ 2. a small 1-D CNN reads magnitude and phase and predicts *K* filter responses,
13
+ 3. a softmax across the *K* filters turns them into a partition of unity,
14
+ 4. each filter is applied to the spectrum and inverted back to the time domain.
15
+
16
+ That construction gives three guarantees by design, not by training:
17
+
18
+ - **Exact reconstruction.** The IMFs always sum back to the input.
19
+ - **Band-limited IMFs.** Every filter is non-negative, so each IMF is a bandpass of the input.
20
+ - **No energy inflation.** The IMFs' total energy can never exceed the signal's.
21
+
22
+ Training only has to make the filters sharp, ordered by frequency and orthogonal.
23
+ Because the whole pipeline is differentiable, N-EMD can sit inside a larger model and
24
+ be trained end to end with a downstream loss.
25
+
26
+ ## Install
27
+
28
+ ```bash
29
+ pip install neural-emd # the library: torch, numpy, scipy
30
+ pip install "neural-emd[baselines]" # adds classical EMD / EEMD / VMD for comparison
31
+ ```
32
+
33
+ The import name is `nemd`. Python 3.11 or newer.
34
+
35
+ ## Quick start
36
+
37
+ [`examples/quickstart.py`](examples/quickstart.py) fits N-EMD to a single noisy signal
38
+ made of three AM-FM tones (50, 15 and 3 Hz) and compares it with classical EMD:
39
+
40
+ ```python
41
+ import numpy as np
42
+ import torch
43
+
44
+ from nemd.classical import ClassicalEMD
45
+ from nemd.train import overfit_single_signal
46
+ from nemd.utils import generate_synthetic_signal, mode_mixing_index, reconstruction_error
47
+
48
+ t, x, truth = generate_synthetic_signal(
49
+ n_samples=1000,
50
+ components=[
51
+ {"f0": 50.0, "f_mod": 2.0, "a_mod": 0.5},
52
+ {"f0": 15.0, "f_mod": 0.5, "a_mod": 0.3},
53
+ {"f0": 3.0, "f_mod": 0.1, "a_mod": 0.2},
54
+ ],
55
+ noise_std=0.05,
56
+ seed=42,
57
+ )
58
+
59
+ out = overfit_single_signal(torch.tensor(x, dtype=torch.float32),
60
+ num_imfs=3, num_steps=1500, fs=1000.0, verbose=False)
61
+ imfs = out["imfs"].detach().numpy() # (3, 1000)
62
+ ```
63
+
64
+ Output on a laptop CPU (about 30 seconds):
65
+
66
+ ```
67
+ N-EMD IMF dominant frequencies (Hz): [58.0, 16.0, 3.0]
68
+ N-EMD reconstruction error: 1.96e-07
69
+ N-EMD mode-mixing index: 0.241
70
+ EMD mode-mixing index: 0.236 (6 IMFs)
71
+ EMD first 3 IMF dominant frequencies (Hz): [58.0, 42.0, 15.0]
72
+ ```
73
+
74
+ N-EMD returns exactly the three components asked for, one per tone, and reconstructs
75
+ the signal to float precision. Classical EMD splits the same signal into six IMFs,
76
+ including a spurious 42 Hz mode.
77
+
78
+ ## Training on a dataset
79
+
80
+ For signals from one family, train a model once and reuse it rather than fitting
81
+ each signal:
82
+
83
+ ```python
84
+ from nemd.train import TrainConfig, train
85
+
86
+ result = train(TrainConfig(num_imfs=3, signal_length=1024, sample_rate=1000.0, num_epochs=100))
87
+ model = result["model"] # nemd.model.NEMD
88
+ imfs, residual, meta = model(batch) # batch: (B, T) tensor -> imfs: (B, K, T)
89
+ ```
90
+
91
+ `train` generates synthetic training data by default. Pass `dataset_fn` to train on
92
+ your own signals. Best and final weights are saved to `TrainConfig.save_dir`.
93
+
94
+ ## What's in the package
95
+
96
+ | Module | Contents |
97
+ |---|---|
98
+ | `nemd.model` | `NEMD`, the filter-bank model; `NEMDSifting`, the earlier iterative variant kept for ablations |
99
+ | `nemd.losses` | Filter sharpness, frequency ordering, orthogonality, balance and the combined `NEMDLoss` |
100
+ | `nemd.train` | `TrainConfig`, `train`, `overfit_single_signal` |
101
+ | `nemd.utils` | Synthetic AM-FM, chirp and nonstationary signal generators; reconstruction error, orthogonality index, mode-mixing index, IF tracking error |
102
+ | `nemd.classical` | Thin wrappers for EMD, EEMD (PyEMD) and VMD (vmdpy), with the `[baselines]` extra |
103
+
104
+ ## Status
105
+
106
+ Research code, alpha. The API may change before 1.0. A paper describing the method
107
+ and its evaluation is in preparation. Until then, please cite this repository if you
108
+ use it.
109
+
110
+ ## Development
111
+
112
+ ```bash
113
+ pip install -e ".[dev]"
114
+ pytest
115
+ ```
116
+
117
+ ## License
118
+
119
+ MIT. Copyright (c) 2026 Aous Abdo.
@@ -0,0 +1,3 @@
1
+ """N-EMD: Neural Empirical Mode Decomposition."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,149 @@
1
+ """Classical EMD / EEMD / VMD baselines for comparison.
2
+
3
+ Thin wrappers around established libraries (EMD-signal, vmdpy) that expose
4
+ a uniform interface for benchmarking against N-EMD.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import numpy as np
10
+ from numpy.typing import NDArray
11
+
12
+
13
+ class ClassicalEMD:
14
+ """Wrapper around PyEMD's EMD implementation.
15
+
16
+ Parameters
17
+ ----------
18
+ max_imfs : int or None
19
+ Maximum number of IMFs to extract. *None* = library default.
20
+ spline_kind : str
21
+ Spline type for envelope fitting (``"cubic"``).
22
+ """
23
+
24
+ def __init__(
25
+ self,
26
+ max_imfs: int | None = None,
27
+ spline_kind: str = "cubic",
28
+ ) -> None:
29
+ self.max_imfs = max_imfs
30
+ self.spline_kind = spline_kind
31
+
32
+ def decompose(
33
+ self, signal: NDArray[np.float64], t: NDArray[np.float64] | None = None,
34
+ ) -> NDArray[np.float64]:
35
+ """Run standard EMD and return IMFs (last row is the residual).
36
+
37
+ Parameters
38
+ ----------
39
+ signal : array of shape (N,)
40
+ t : array of shape (N,) or None
41
+ Time vector. If *None*, uses integer indices.
42
+
43
+ Returns
44
+ -------
45
+ imfs : array of shape (K, N)
46
+ Rows are IMFs from highest to lowest frequency; the last row
47
+ is the residual (monotonic trend).
48
+ """
49
+ from PyEMD import EMD as _EMD
50
+
51
+ emd = _EMD(spline_kind=self.spline_kind)
52
+ if self.max_imfs is not None:
53
+ emd.MAX_ITERATION = 2000
54
+ if t is None:
55
+ t = np.arange(len(signal), dtype=np.float64)
56
+ imfs = emd.emd(signal.astype(np.float64), t)
57
+ if self.max_imfs is not None and imfs.shape[0] > self.max_imfs:
58
+ # Merge excess IMFs into residual
59
+ residual = np.sum(imfs[self.max_imfs - 1 :], axis=0)
60
+ imfs = np.vstack([imfs[: self.max_imfs - 1], residual[np.newaxis, :]])
61
+ return imfs
62
+
63
+
64
+ class EnsembleEMD:
65
+ """Wrapper around PyEMD's EEMD implementation.
66
+
67
+ Parameters
68
+ ----------
69
+ n_trials : int
70
+ Number of noise-assisted trials.
71
+ noise_width : float
72
+ Standard deviation of the added white noise.
73
+ max_imfs : int or None
74
+ Maximum number of IMFs.
75
+ """
76
+
77
+ def __init__(
78
+ self,
79
+ n_trials: int = 100,
80
+ noise_width: float = 0.05,
81
+ max_imfs: int | None = None,
82
+ ) -> None:
83
+ self.n_trials = n_trials
84
+ self.noise_width = noise_width
85
+ self.max_imfs = max_imfs
86
+
87
+ def decompose(
88
+ self, signal: NDArray[np.float64], t: NDArray[np.float64] | None = None,
89
+ ) -> NDArray[np.float64]:
90
+ """Run EEMD and return IMFs."""
91
+ from PyEMD import EEMD as _EEMD
92
+
93
+ eemd = _EEMD(trials=self.n_trials, noise_width=self.noise_width)
94
+ if t is None:
95
+ t = np.arange(len(signal), dtype=np.float64)
96
+ imfs = eemd.eemd(signal.astype(np.float64), t)
97
+ if self.max_imfs is not None and imfs.shape[0] > self.max_imfs:
98
+ residual = np.sum(imfs[self.max_imfs - 1 :], axis=0)
99
+ imfs = np.vstack([imfs[: self.max_imfs - 1], residual[np.newaxis, :]])
100
+ return imfs
101
+
102
+
103
+ class VMD:
104
+ """Wrapper around vmdpy's VMD implementation.
105
+
106
+ Parameters
107
+ ----------
108
+ n_modes : int
109
+ Number of modes (K) to extract.
110
+ alpha : float
111
+ Bandwidth constraint parameter.
112
+ tau : float
113
+ Noise-tolerance (time-step of dual ascent).
114
+ tol : float
115
+ Convergence tolerance.
116
+ """
117
+
118
+ def __init__(
119
+ self,
120
+ n_modes: int = 3,
121
+ alpha: float = 2000.0,
122
+ tau: float = 0.0,
123
+ tol: float = 1e-7,
124
+ ) -> None:
125
+ self.n_modes = n_modes
126
+ self.alpha = alpha
127
+ self.tau = tau
128
+ self.tol = tol
129
+
130
+ def decompose(
131
+ self, signal: NDArray[np.float64], t: NDArray[np.float64] | None = None,
132
+ ) -> NDArray[np.float64]:
133
+ """Run VMD and return modes.
134
+
135
+ Note: VMD does not produce a monotonic residual — the returned
136
+ modes sum to the original signal by construction.
137
+ """
138
+ from vmdpy import VMD as _VMD
139
+
140
+ u, _, _ = _VMD(
141
+ signal.astype(np.float64),
142
+ self.alpha,
143
+ self.tau,
144
+ self.n_modes,
145
+ 0, # DC — no imposed DC
146
+ 1, # init — uniform center frequencies
147
+ self.tol,
148
+ )
149
+ return np.array(u)
@@ -0,0 +1,249 @@
1
+ """Differentiable signal-processing building blocks for N-EMD.
2
+
3
+ All operations accept and return PyTorch tensors and support batched inputs
4
+ of shape ``(B, N)`` or unbatched ``(N,)``. Gradients flow through every
5
+ operation so they can be used inside a training loop.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import torch
11
+ import torch.nn.functional as F
12
+ import numpy as np
13
+
14
+
15
+ # ---------------------------------------------------------------------------
16
+ # Differentiable Hilbert transform
17
+ # ---------------------------------------------------------------------------
18
+
19
+ def hilbert_transform(x: torch.Tensor) -> torch.Tensor:
20
+ """Compute the analytic signal via the Hilbert transform (FFT-based).
21
+
22
+ Given a real signal x(t), the analytic signal is::
23
+
24
+ z(t) = x(t) + j * H[x](t)
25
+
26
+ where H is the Hilbert transform.
27
+
28
+ Parameters
29
+ ----------
30
+ x : Tensor of shape ``(..., N)``
31
+ Real-valued input signal(s).
32
+
33
+ Returns
34
+ -------
35
+ analytic : complex Tensor of shape ``(..., N)``
36
+ The analytic signal.
37
+ """
38
+ N = x.shape[-1]
39
+ X = torch.fft.fft(x, dim=-1)
40
+
41
+ # Build the frequency-domain multiplier h:
42
+ # h[0] = 1, h[N/2] = 1 (if N even), h[1..N/2-1] = 2, rest = 0
43
+ h = torch.zeros(N, device=x.device, dtype=x.dtype)
44
+ h[0] = 1.0
45
+ if N % 2 == 0:
46
+ h[N // 2] = 1.0
47
+ h[1 : N // 2] = 2.0
48
+ else:
49
+ h[1 : (N + 1) // 2] = 2.0
50
+
51
+ return torch.fft.ifft(X * h, dim=-1)
52
+
53
+
54
+ def instantaneous_amplitude(x: torch.Tensor) -> torch.Tensor:
55
+ """Instantaneous amplitude (envelope) via the analytic signal.
56
+
57
+ Parameters
58
+ ----------
59
+ x : Tensor of shape ``(..., N)``
60
+
61
+ Returns
62
+ -------
63
+ env : Tensor of shape ``(..., N)``
64
+ """
65
+ z = hilbert_transform(x)
66
+ return z.abs()
67
+
68
+
69
+ def instantaneous_phase(x: torch.Tensor) -> torch.Tensor:
70
+ """Instantaneous phase via the analytic signal (unwrapped).
71
+
72
+ Parameters
73
+ ----------
74
+ x : Tensor of shape ``(..., N)``
75
+
76
+ Returns
77
+ -------
78
+ phase : Tensor of shape ``(..., N)``
79
+ Unwrapped instantaneous phase in radians.
80
+ """
81
+ z = hilbert_transform(x)
82
+ phase = torch.atan2(z.imag, z.real)
83
+ return _unwrap_phase(phase)
84
+
85
+
86
+ def instantaneous_frequency(
87
+ x: torch.Tensor, fs: float = 1.0
88
+ ) -> torch.Tensor:
89
+ """Instantaneous frequency via differentiation of unwrapped phase.
90
+
91
+ Parameters
92
+ ----------
93
+ x : Tensor of shape ``(..., N)``
94
+ fs : float
95
+ Sampling frequency.
96
+
97
+ Returns
98
+ -------
99
+ freq : Tensor of shape ``(..., N-1)``
100
+ Instantaneous frequency at midpoints.
101
+ """
102
+ phase = instantaneous_phase(x)
103
+ # Central-difference style: diff gives phase increments
104
+ dphase = torch.diff(phase, dim=-1)
105
+ return dphase * fs / (2.0 * np.pi)
106
+
107
+
108
+ def _unwrap_phase(phase: torch.Tensor) -> torch.Tensor:
109
+ """Differentiable phase unwrapping.
110
+
111
+ Adjusts phase jumps greater than pi to produce a continuous phase signal.
112
+ """
113
+ dp = torch.diff(phase, dim=-1)
114
+ # Wrap differences to [-pi, pi]
115
+ dp_wrapped = (dp + np.pi) % (2 * np.pi) - np.pi
116
+ # Fix the edge case where dp_wrapped == -pi and dp > 0
117
+ dp_wrapped = torch.where(
118
+ (dp_wrapped == -np.pi) & (dp > 0),
119
+ torch.tensor(np.pi, device=phase.device, dtype=phase.dtype),
120
+ dp_wrapped,
121
+ )
122
+ correction = torch.cumsum(dp_wrapped - dp, dim=-1)
123
+ # Prepend zeros for the first sample
124
+ zeros = torch.zeros(
125
+ *phase.shape[:-1], 1, device=phase.device, dtype=phase.dtype
126
+ )
127
+ return phase + torch.cat([zeros, correction], dim=-1)
128
+
129
+
130
+ # ---------------------------------------------------------------------------
131
+ # Differentiable envelope estimation
132
+ # ---------------------------------------------------------------------------
133
+
134
+ def envelope_mean(x: torch.Tensor, window_size: int = 51) -> torch.Tensor:
135
+ """Estimate the mean envelope via a smoothing filter.
136
+
137
+ Uses a simple moving average as a differentiable alternative to cubic
138
+ spline envelope fitting. The filter is applied with reflection padding
139
+ to reduce boundary effects.
140
+
141
+ Parameters
142
+ ----------
143
+ x : Tensor of shape ``(..., N)``
144
+ window_size : int
145
+ Smoothing window (must be odd).
146
+
147
+ Returns
148
+ -------
149
+ mean_env : Tensor of shape ``(..., N)``
150
+ """
151
+ if window_size % 2 == 0:
152
+ window_size += 1
153
+
154
+ # Ensure 3-D for conv1d: (B, 1, N)
155
+ orig_shape = x.shape
156
+ if x.dim() == 1:
157
+ x = x.unsqueeze(0)
158
+ if x.dim() == 2:
159
+ x = x.unsqueeze(1) # (B, 1, N)
160
+
161
+ pad = window_size // 2
162
+ x_padded = F.pad(x, (pad, pad), mode="reflect")
163
+
164
+ kernel = torch.ones(1, 1, window_size, device=x.device, dtype=x.dtype) / window_size
165
+ mean_env = F.conv1d(x_padded, kernel)
166
+
167
+ # Restore original shape
168
+ mean_env = mean_env.squeeze(1)
169
+ if len(orig_shape) == 1:
170
+ mean_env = mean_env.squeeze(0)
171
+ return mean_env
172
+
173
+
174
+ def upper_lower_envelopes(
175
+ x: torch.Tensor, window_size: int = 51
176
+ ) -> tuple[torch.Tensor, torch.Tensor]:
177
+ """Estimate upper and lower envelopes via max/min pooling + smoothing.
178
+
179
+ A differentiable approximation: we use max-pool to get local maxima
180
+ envelope and negated-max-pool for local minima envelope, followed by
181
+ smoothing.
182
+
183
+ Parameters
184
+ ----------
185
+ x : Tensor of shape ``(..., N)``
186
+ window_size : int
187
+
188
+ Returns
189
+ -------
190
+ upper, lower : Tensors of shape ``(..., N)``
191
+ """
192
+ if window_size % 2 == 0:
193
+ window_size += 1
194
+
195
+ orig_shape = x.shape
196
+ if x.dim() == 1:
197
+ x = x.unsqueeze(0)
198
+ # (B, N) -> (B, 1, N) for pooling
199
+ x3 = x.unsqueeze(1)
200
+
201
+ pad = window_size // 2
202
+ x_padded = F.pad(x3, (pad, pad), mode="reflect")
203
+
204
+ upper = F.max_pool1d(x_padded, kernel_size=window_size, stride=1)
205
+ lower = -F.max_pool1d(-x_padded, kernel_size=window_size, stride=1)
206
+
207
+ upper = upper.squeeze(1)
208
+ lower = lower.squeeze(1)
209
+
210
+ # Smooth the envelopes
211
+ upper = envelope_mean(upper, window_size=window_size)
212
+ lower = envelope_mean(lower, window_size=window_size)
213
+
214
+ if len(orig_shape) == 1:
215
+ upper = upper.squeeze(0)
216
+ lower = lower.squeeze(0)
217
+ return upper, lower
218
+
219
+
220
+ # ---------------------------------------------------------------------------
221
+ # Bandwidth / narrow-band measure
222
+ # ---------------------------------------------------------------------------
223
+
224
+ def spectral_bandwidth(x: torch.Tensor, fs: float = 1.0) -> torch.Tensor:
225
+ """Spectral bandwidth of a signal (RMS deviation from spectral centroid).
226
+
227
+ A narrow-band (mono-component) signal has low spectral bandwidth.
228
+
229
+ Parameters
230
+ ----------
231
+ x : Tensor of shape ``(..., N)``
232
+ fs : float
233
+ Sampling frequency.
234
+
235
+ Returns
236
+ -------
237
+ bw : Tensor of shape ``(...,)``
238
+ Spectral bandwidth in Hz.
239
+ """
240
+ N = x.shape[-1]
241
+ X = torch.fft.rfft(x, dim=-1)
242
+ psd = (X.real ** 2 + X.imag ** 2) # power spectral density
243
+
244
+ freqs = torch.linspace(0, fs / 2, psd.shape[-1], device=x.device, dtype=x.dtype)
245
+
246
+ total_power = psd.sum(dim=-1, keepdim=True).clamp(min=1e-12)
247
+ centroid = (psd * freqs).sum(dim=-1, keepdim=True) / total_power
248
+ bw_sq = (psd * (freqs - centroid) ** 2).sum(dim=-1) / total_power.squeeze(-1)
249
+ return bw_sq.sqrt()