flatten-spectrum 0.1.0__py3-none-any.whl

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,132 @@
1
+ Metadata-Version: 2.4
2
+ Name: flatten-spectrum
3
+ Version: 0.1.0
4
+ Summary: FLAT: separate the aperiodic background from periodic peaks in EEG/MEG power spectra
5
+ Author: Tobias C. Haase, Steffen Gais
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/SteffenGais/FLAT
8
+ Project-URL: Documentation, https://github.com/SteffenGais/FLAT/blob/main/docs/method.md
9
+ Project-URL: Issues, https://github.com/SteffenGais/FLAT/issues
10
+ Keywords: EEG,MEG,power spectrum,aperiodic,1/f,oscillations
11
+ Requires-Python: >=3.10
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: numpy>=1.23
15
+ Provides-Extra: examples
16
+ Requires-Dist: scipy>=1.10; extra == "examples"
17
+ Requires-Dist: matplotlib>=3.7; extra == "examples"
18
+ Requires-Dist: mne>=1.6; extra == "examples"
19
+ Dynamic: license-file
20
+
21
+ # FLAT for Python
22
+
23
+ ## Installation
24
+
25
+ FLAT needs Python 3.10 or newer and NumPy. The examples also use SciPy,
26
+ Matplotlib and MNE.
27
+
28
+ With pip:
29
+
30
+ ```sh
31
+ pip install flatten-spectrum # FLAT only
32
+ pip install "flatten-spectrum[examples]" # FLAT and the packages for the examples
33
+ ```
34
+
35
+ With conda, create an environment and install with pip inside it:
36
+
37
+ ```sh
38
+ conda create -n flat python=3.12 pip
39
+ conda activate flat
40
+ pip install "flatten-spectrum[examples]"
41
+ ```
42
+
43
+ To install from a copy of this repository, run `pip install ".[examples]"` in
44
+ its main folder. You can also copy `flatten_spectrum.py` into your project; it
45
+ only needs NumPy.
46
+
47
+ ## Usage
48
+
49
+ ```python
50
+ from flatten_spectrum import flatten_spectrum
51
+
52
+ flattened, baseline, slope = flatten_spectrum(power, freqs)
53
+ flattened, baseline, slope = flatten_spectrum(power, freqs, notch_hz=[(47.5, 52.5)])
54
+ ```
55
+
56
+ Inputs:
57
+
58
+ - `power`: power spectral density in linear units (e.g. µV²/Hz), with
59
+ frequencies along the last axis. Leading axes (channels, conditions, ...)
60
+ are kept. Preferably from long windows with 1/32-octave cells (see below).
61
+ - `freqs`: frequencies in Hz, increasing.
62
+ - `notch_hz` (optional): frequency bands to exclude, as `(low, high)` pairs.
63
+ Default: none.
64
+
65
+ Outputs:
66
+
67
+ - `flattened`: the flattened spectrum, `power / baseline`. It is 1 at the
68
+ background level and shows periodic activity as peaks, together with the
69
+ noise of the estimate.
70
+ - `baseline`: the aperiodic background, in the units of `power`.
71
+ - `slope`: the slope of the baseline from 2 to 24 Hz in log-log coordinates,
72
+ one per spectrum (−2 for a 1/f² background). The aperiodic exponent of
73
+ specparam (FOOOF, fixed mode) corresponds to −slope.
74
+
75
+ Frequencies outside 0.3–45 Hz and inside notch bands are NaN in `flattened`
76
+ and `baseline`. Pass only the frequencies your recording measures reliably,
77
+ away from filter edges (see [method](https://github.com/SteffenGais/FLAT/blob/main/docs/method.md#reliable-frequency-range)):
78
+
79
+ ```python
80
+ keep = (freqs >= 1) & (freqs <= 40)
81
+ flattened, baseline, slope = flatten_spectrum(power[..., keep], freqs[keep])
82
+ ```
83
+
84
+ ## Recommended spectra
85
+
86
+ Compute the spectrum from windows as long as the recording allows while
87
+ still averaging about 30 of them, e.g. one 30-s Hann window per sleep epoch,
88
+ or 4-s windows with 50% overlap for one minute of data. Average the
89
+ periodograms in linear power, then average power within 1/32-octave cells:
90
+ low frequencies keep their full resolution, high frequencies become smooth
91
+ (see [method](https://github.com/SteffenGais/FLAT/blob/main/docs/method.md#input-spectra)).
92
+
93
+ ```python
94
+ import numpy as np
95
+ from scipy.signal import welch
96
+
97
+ freqs, power = welch(data, fs, nperseg=int(10 * fs)) # data: channels x samples, 10-s windows
98
+ cells = np.round(32 * np.log2(freqs[1:])).astype(int) # without the DC bin
99
+ _, first, counts = np.unique(cells, return_index=True, return_counts=True)
100
+ freqs = np.add.reduceat(freqs[1:], first) / counts
101
+ power = np.add.reduceat(power[..., 1:], first, axis=-1) / counts
102
+ ```
103
+
104
+ ## Examples
105
+
106
+ The examples in `examples/python` read any recording MNE can read, e.g.
107
+ BrainVision (`.vhdr`) or EDF. Downloads are stored in `examples/data`.
108
+
109
+ ```sh
110
+ cd examples/python
111
+ python eeg_example.py # 1 min of 64-channel resting EEG (1.3 MB download)
112
+ python eeg_example.py my_recording.vhdr O1 O2 # your own recording, two channels
113
+ python sleep_edf_example.py # one night of the Sleep-EDF database (50 MB download)
114
+ python sleep_example.py night.vhdr night.txt # your own sleep recording and scoring
115
+ ```
116
+
117
+ One or two channels are shown as line plots with their baseline, more
118
+ channels as waterfall plots of power and flattened power.
119
+
120
+ `sleep_example.py` needs a text file with one row per 30-s epoch, starting at
121
+ the first sample of the recording. Its first column holds the sleep stage:
122
+ 0 wake, 1–4 NREM stages 1–4, 5 REM. Other codes (e.g. 8 for movement time) are
123
+ skipped, and stages 3 and 4 are combined into N3.
124
+
125
+ In Python or Jupyter, the examples are functions with the optional arguments
126
+ `channels`, `frequency_range` and `notch_hz`. They return their results:
127
+
128
+ ```python
129
+ from sleep_example import sleep_example
130
+
131
+ result = sleep_example("night.vhdr", "night.txt", channels=["C3", "C4"])
132
+ ```
@@ -0,0 +1,6 @@
1
+ flatten_spectrum.py,sha256=LRggINlNkf5ZTDw4jFDsDo3tMxMB0jAes2Dy8XXpObg,6971
2
+ flatten_spectrum-0.1.0.dist-info/licenses/LICENSE,sha256=6vPq7HwATTANyaDjp2LP6XghZjeGE_9_k1mHiu4v_O0,1089
3
+ flatten_spectrum-0.1.0.dist-info/METADATA,sha256=FgTLqy3x9L09VotGQmZpgUxGGqYM1TQZUpXxqKyzdg8,5193
4
+ flatten_spectrum-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
5
+ flatten_spectrum-0.1.0.dist-info/top_level.txt,sha256=fuGwe3CZx7YJVxMdLiqztkYmlBG7TQ-4k7dNqR6_CTo,17
6
+ flatten_spectrum-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Tobias C. Haase and Steffen Gais
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 @@
1
+ flatten_spectrum
flatten_spectrum.py ADDED
@@ -0,0 +1,140 @@
1
+ """FLAT: Flattening spectra using the Local Aperiodic Trend."""
2
+
3
+ import numpy as np
4
+ from numpy.lib.stride_tricks import sliding_window_view
5
+
6
+
7
+ def flatten_spectrum(power, freqs, notch_hz=None):
8
+ """Return flattened power / baseline, aperiodic baseline, and 2–24 Hz slope.
9
+
10
+ Parameters
11
+ ----------
12
+ power : array_like, shape (..., n_frequencies)
13
+ Linear power or power spectral density; frequencies are the last axis.
14
+ An entirely NaN spectrum is allowed and returns entirely NaN outputs.
15
+ freqs : array_like, shape (n_frequencies,)
16
+ Finite, nonnegative, strictly increasing frequencies in Hz.
17
+ notch_hz : None, pair, or array_like of shape (n_bands, 2), optional
18
+ Excluded intervals in Hz, e.g. (32, 33). None (default) or [] means
19
+ no notch. Give the actual affected interval, not just its center.
20
+
21
+ Returns
22
+ -------
23
+ flattened, baseline : ndarray, same shape as power
24
+ Dimensionless power / baseline and baseline in the input power units.
25
+ Values outside 0.3–45 Hz and inside notch bands are NaN.
26
+ slope : ndarray, shape power.shape[:-1]
27
+ Signed least-squares slope of log10(baseline) versus log10(frequency),
28
+ with equal weight per log-frequency interval over 2–24 Hz. A 1/f**2
29
+ baseline has slope -2. NaN if this full interval is unavailable or
30
+ intersects a notch. For one input spectrum, this is a scalar array.
31
+
32
+ Notes
33
+ -----
34
+ The two-octave window and 1/32-octave grid are fixed method constants.
35
+ Supply averaged spectra from a reliable passband; FLAT does not detect
36
+ filters or reject artifacts. See docs/method.md for assumptions and limits.
37
+ """
38
+ power = np.asarray(power, dtype=float)
39
+ freqs = np.asarray(freqs, dtype=float)
40
+ if (freqs.ndim != 1 or freqs.size < 2 or not np.isfinite(freqs).all()
41
+ or np.any(freqs < 0) or np.any(np.diff(freqs) <= 0)):
42
+ raise ValueError("freqs must be finite, nonnegative, and strictly increasing.")
43
+ if power.ndim < 1 or power.shape[-1] != freqs.size or power.size == 0:
44
+ raise ValueError("The last power axis must match freqs; power must be nonempty.")
45
+
46
+ bands = np.asarray([] if notch_hz is None else notch_hz, dtype=float)
47
+ if bands.size:
48
+ bands = np.atleast_2d(bands)
49
+ if (bands.ndim != 2 or bands.shape[1] != 2 or not np.isfinite(bands).all()
50
+ or np.any(bands[:, 0] <= 0) or np.any(bands[:, 1] <= bands[:, 0])
51
+ or np.any(bands[1:, 0] <= bands[:-1, 1])):
52
+ raise ValueError("Notch bands must be positive, ordered, disjoint [low, high] pairs.")
53
+ else:
54
+ bands = np.empty((0, 2))
55
+
56
+ # Work only in the fixed EEG/MEG analysis range. DC is never logarithmed.
57
+ selected = (freqs >= 0.3) & (freqs <= 45)
58
+ f = freqs[selected]
59
+ if f.size < 2:
60
+ raise ValueError("At least two frequency bins are required within 0.3–45 Hz.")
61
+ x = np.log2(f)
62
+ grid = np.arange(x[0], x[-1] + 1e-9, 1 / 32)
63
+ if grid.size < 2:
64
+ raise ValueError("The analyzed frequency span must cover at least 1/32 octave.")
65
+ window = 65 # Two octaves: 64 intervals, 65 centered points.
66
+ half = window // 2
67
+ n_fit = min(half, grid.size) # Fit the outer one octave at each edge.
68
+ offsets = np.arange(-half, half + 1)
69
+ i, j = np.triu_indices(n_fit, 1)
70
+ edge_x = np.arange(n_fit)
71
+ masked = np.zeros(f.size, dtype=bool)
72
+ for low, high in bands:
73
+ masked |= (f >= low) & (f <= high)
74
+ if masked.any() and (masked[0] or masked[-1]):
75
+ raise ValueError("Each analyzed notch needs a frequency bin on both sides.")
76
+
77
+ rows = power.reshape(-1, freqs.size)
78
+ flattened = np.full_like(rows, np.nan)
79
+ baseline = np.full_like(rows, np.nan)
80
+ slopes = np.full(rows.shape[0], np.nan)
81
+ for r, spectrum in enumerate(rows):
82
+ if np.isnan(spectrum).all():
83
+ continue
84
+ p = spectrum[selected]
85
+ if not np.isfinite(p[~masked]).all() or np.any(p[~masked] <= 0):
86
+ raise ValueError("Analyzed power outside notches must be finite and positive.")
87
+
88
+ # Bridge excluded bins from unaffected neighbors in log-log coordinates.
89
+ # They support the baseline calculation but are never reported as data.
90
+ logp = np.interp(x, x[~masked], np.log10(p[~masked]))
91
+ y = np.interp(grid, x, logp)
92
+
93
+ # Robust linear continuation prevents shrinking-window bias at the edges.
94
+ # Theil–Sen slope = median of all pairwise slopes; intercept = median residual.
95
+ extensions = []
96
+ for edge, query in ((y[:n_fit], np.arange(-window, 0)),
97
+ (y[-n_fit:], np.arange(n_fit, n_fit + window))):
98
+ b = np.median((edge[j] - edge[i]) / (j - i))
99
+ a = np.median(edge - b * edge_x)
100
+ extensions.append(a + b * query)
101
+ y = np.concatenate((extensions[0], y, extensions[1]))
102
+
103
+ # First median-then-mean pass estimates a smooth local slope. NaN padding
104
+ # reproduces centered, shrinking windows at the far extrapolated ends.
105
+ neighborhoods = sliding_window_view(np.pad(y, half, constant_values=np.nan), window)
106
+ first = np.nanmedian(neighborhoods, axis=-1)
107
+ first = np.nanmean(sliding_window_view(
108
+ np.pad(first, half, constant_values=np.nan), window), axis=-1)
109
+ local_slope = np.gradient(first)
110
+
111
+ # Remove the local slope BEFORE taking the median: on a sloped spectrum,
112
+ # a positive peak can otherwise shift the median into a higher background.
113
+ detrended = neighborhoods - local_slope[:, None] * offsets
114
+ trend = np.nanmedian(detrended, axis=-1)
115
+ trend = np.nanmean(sliding_window_view(
116
+ np.pad(trend, half, constant_values=np.nan), window), axis=-1)
117
+ trend = trend[window:window + grid.size]
118
+
119
+ # Interpolate back. The final original bin may lie just beyond the grid;
120
+ # continue its last segment instead of silently clamping the endpoint.
121
+ logbase = np.interp(x, grid, trend)
122
+ beyond = x > grid[-1]
123
+ logbase[beyond] = trend[-1] + (x[beyond] - grid[-1]) * (
124
+ trend[-1] - trend[-2]) / (grid[-1] - grid[-2])
125
+ b = 10 ** logbase
126
+ b[masked] = np.nan
127
+ baseline[r, selected] = b
128
+ flattened[r, selected] = p / b
129
+
130
+ # Equal log-frequency weighting makes the summary independent of the
131
+ # density of linear FFT bins. Do not shorten an unavailable 2–24 Hz fit.
132
+ if f[0] <= 2 and f[-1] >= 24 and not any(
133
+ low <= 24 and high >= 2 for low, high in bands):
134
+ fit_x = np.linspace(1, np.log2(24), 116)
135
+ fit_y = np.interp(fit_x, x, logbase)
136
+ centered = fit_x - fit_x.mean()
137
+ slopes[r] = np.dot(centered, fit_y) / np.dot(centered, centered) / np.log10(2)
138
+
139
+ return (flattened.reshape(power.shape), baseline.reshape(power.shape),
140
+ slopes.reshape(power.shape[:-1]))