flatten-spectrum 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,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,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,77 @@
1
+ # FLAT
2
+
3
+ **Flattening spectra using the Local Aperiodic Trend** separates an EEG or MEG
4
+ power spectrum into its smooth aperiodic background, the *baseline*, and the
5
+ periodic activity on top of it. Dividing power by the baseline gives a
6
+ flattened spectrum in which oscillations stand out as peaks above 1.
7
+
8
+ ![Waterfall plots of 64-channel EEG before and after flattening](docs/eeg_example.png)
9
+
10
+ *One minute of 64-channel resting EEG with eyes closed, before (left) and after
11
+ flattening (right). Besides alpha, the flattened spectra show a beta peak
12
+ around 20 Hz that is hard to see in the power spectra. Channels run from
13
+ anterior (front) to posterior (back).*
14
+
15
+ ![Power spectra and flattened spectra per sleep stage](docs/sleep_example.png)
16
+
17
+ *One night of sleep EEG. Top: power spectra per sleep stage with their
18
+ baselines (dashed). Bottom: flattened spectra, showing alpha in wake and sleep
19
+ spindles in N2 and N3.*
20
+
21
+ ## Why FLAT
22
+
23
+ - **No settings.** There is no peak model, no model of the background and
24
+ nothing to tune, so every recording is processed in the same way.
25
+ - **Any smooth background.** The baseline is a local trend over two octaves.
26
+ It follows knees and bends without needing a model for them.
27
+ - **Robust to narrow peaks.** Medians taken after removing the local slope
28
+ keep narrow peaks from lifting the baseline, even on a steep background,
29
+ and a robust continuation keeps the full window at both ends of the range.
30
+ - **The full data.** The flattened spectrum shows every deviation from the
31
+ background, including noise, without thresholds or peak detection.
32
+ - **Works on any spectrum.** Welch, multitaper or wavelet spectra can be used
33
+ directly; neither the time series nor data beyond the analyzed range are
34
+ needed.
35
+ - **Fast, working in MATLAB and Python.**
36
+
37
+ The baseline slope from 2 to 24 Hz summarizes the background. For a power law
38
+ $1/f^\chi$ it equals $-\chi$, so it corresponds to −1 times the aperiodic
39
+ exponent of specparam (FOOOF) in its fixed mode. The
40
+ [method description](docs/method.md) explains the algorithm, the choice of its
41
+ fixed constants, its properties and its limits.
42
+
43
+ ## Getting started
44
+
45
+ Both implementations have the same interface:
46
+
47
+ ```matlab
48
+ [flattened, baseline, slope] = flatten_spectrum(power, freqs); % MATLAB
49
+ ```
50
+
51
+ ```python
52
+ flattened, baseline, slope = flatten_spectrum(power, freqs) # Python
53
+ ```
54
+
55
+ - [MATLAB: setup, usage and examples](README_matlab.md)
56
+ - [Python: installation, usage and examples](README_python.md)
57
+
58
+ The examples flatten your own recordings or download public data: one minute
59
+ of 64-channel resting EEG and one night of sleep EEG. Several more example
60
+ figures are in [examples/figures](examples/figures);
61
+ [examples/figures/MEG](examples/figures/MEG) holds waterfall plots of MEG
62
+ source spectra for all sleep stages as rotatable MATLAB figures.
63
+
64
+ ## Example data
65
+
66
+ The examples use data from [PhysioNet](https://physionet.org) (Goldberger et
67
+ al., 2000, *Circulation* 101:e215–e220), licensed under the Open Data Commons
68
+ Attribution License 1.0:
69
+
70
+ - [EEG Motor Movement/Imagery Dataset](https://physionet.org/content/eegmmidb/1.0.0/):
71
+ Schalk et al. (2004), *IEEE Trans Biomed Eng* 51:1034–1043.
72
+ - [Sleep-EDF Database Expanded](https://physionet.org/content/sleep-edfx/1.0.0/):
73
+ Kemp et al. (2000), *IEEE Trans Biomed Eng* 47:1185–1194.
74
+
75
+ ## License
76
+
77
+ [MIT](LICENSE), © 2026 Tobias C. Haase and Steffen Gais.
@@ -0,0 +1,112 @@
1
+ # FLAT for Python
2
+
3
+ ## Installation
4
+
5
+ FLAT needs Python 3.10 or newer and NumPy. The examples also use SciPy,
6
+ Matplotlib and MNE.
7
+
8
+ With pip:
9
+
10
+ ```sh
11
+ pip install flatten-spectrum # FLAT only
12
+ pip install "flatten-spectrum[examples]" # FLAT and the packages for the examples
13
+ ```
14
+
15
+ With conda, create an environment and install with pip inside it:
16
+
17
+ ```sh
18
+ conda create -n flat python=3.12 pip
19
+ conda activate flat
20
+ pip install "flatten-spectrum[examples]"
21
+ ```
22
+
23
+ To install from a copy of this repository, run `pip install ".[examples]"` in
24
+ its main folder. You can also copy `flatten_spectrum.py` into your project; it
25
+ only needs NumPy.
26
+
27
+ ## Usage
28
+
29
+ ```python
30
+ from flatten_spectrum import flatten_spectrum
31
+
32
+ flattened, baseline, slope = flatten_spectrum(power, freqs)
33
+ flattened, baseline, slope = flatten_spectrum(power, freqs, notch_hz=[(47.5, 52.5)])
34
+ ```
35
+
36
+ Inputs:
37
+
38
+ - `power`: power spectral density in linear units (e.g. µV²/Hz), with
39
+ frequencies along the last axis. Leading axes (channels, conditions, ...)
40
+ are kept. Preferably from long windows with 1/32-octave cells (see below).
41
+ - `freqs`: frequencies in Hz, increasing.
42
+ - `notch_hz` (optional): frequency bands to exclude, as `(low, high)` pairs.
43
+ Default: none.
44
+
45
+ Outputs:
46
+
47
+ - `flattened`: the flattened spectrum, `power / baseline`. It is 1 at the
48
+ background level and shows periodic activity as peaks, together with the
49
+ noise of the estimate.
50
+ - `baseline`: the aperiodic background, in the units of `power`.
51
+ - `slope`: the slope of the baseline from 2 to 24 Hz in log-log coordinates,
52
+ one per spectrum (−2 for a 1/f² background). The aperiodic exponent of
53
+ specparam (FOOOF, fixed mode) corresponds to −slope.
54
+
55
+ Frequencies outside 0.3–45 Hz and inside notch bands are NaN in `flattened`
56
+ and `baseline`. Pass only the frequencies your recording measures reliably,
57
+ away from filter edges (see [method](https://github.com/SteffenGais/FLAT/blob/main/docs/method.md#reliable-frequency-range)):
58
+
59
+ ```python
60
+ keep = (freqs >= 1) & (freqs <= 40)
61
+ flattened, baseline, slope = flatten_spectrum(power[..., keep], freqs[keep])
62
+ ```
63
+
64
+ ## Recommended spectra
65
+
66
+ Compute the spectrum from windows as long as the recording allows while
67
+ still averaging about 30 of them, e.g. one 30-s Hann window per sleep epoch,
68
+ or 4-s windows with 50% overlap for one minute of data. Average the
69
+ periodograms in linear power, then average power within 1/32-octave cells:
70
+ low frequencies keep their full resolution, high frequencies become smooth
71
+ (see [method](https://github.com/SteffenGais/FLAT/blob/main/docs/method.md#input-spectra)).
72
+
73
+ ```python
74
+ import numpy as np
75
+ from scipy.signal import welch
76
+
77
+ freqs, power = welch(data, fs, nperseg=int(10 * fs)) # data: channels x samples, 10-s windows
78
+ cells = np.round(32 * np.log2(freqs[1:])).astype(int) # without the DC bin
79
+ _, first, counts = np.unique(cells, return_index=True, return_counts=True)
80
+ freqs = np.add.reduceat(freqs[1:], first) / counts
81
+ power = np.add.reduceat(power[..., 1:], first, axis=-1) / counts
82
+ ```
83
+
84
+ ## Examples
85
+
86
+ The examples in `examples/python` read any recording MNE can read, e.g.
87
+ BrainVision (`.vhdr`) or EDF. Downloads are stored in `examples/data`.
88
+
89
+ ```sh
90
+ cd examples/python
91
+ python eeg_example.py # 1 min of 64-channel resting EEG (1.3 MB download)
92
+ python eeg_example.py my_recording.vhdr O1 O2 # your own recording, two channels
93
+ python sleep_edf_example.py # one night of the Sleep-EDF database (50 MB download)
94
+ python sleep_example.py night.vhdr night.txt # your own sleep recording and scoring
95
+ ```
96
+
97
+ One or two channels are shown as line plots with their baseline, more
98
+ channels as waterfall plots of power and flattened power.
99
+
100
+ `sleep_example.py` needs a text file with one row per 30-s epoch, starting at
101
+ the first sample of the recording. Its first column holds the sleep stage:
102
+ 0 wake, 1–4 NREM stages 1–4, 5 REM. Other codes (e.g. 8 for movement time) are
103
+ skipped, and stages 3 and 4 are combined into N3.
104
+
105
+ In Python or Jupyter, the examples are functions with the optional arguments
106
+ `channels`, `frequency_range` and `notch_hz`. They return their results:
107
+
108
+ ```python
109
+ from sleep_example import sleep_example
110
+
111
+ result = sleep_example("night.vhdr", "night.txt", channels=["C3", "C4"])
112
+ ```
@@ -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,10 @@
1
+ LICENSE
2
+ README.md
3
+ README_python.md
4
+ flatten_spectrum.py
5
+ pyproject.toml
6
+ flatten_spectrum.egg-info/PKG-INFO
7
+ flatten_spectrum.egg-info/SOURCES.txt
8
+ flatten_spectrum.egg-info/dependency_links.txt
9
+ flatten_spectrum.egg-info/requires.txt
10
+ flatten_spectrum.egg-info/top_level.txt
@@ -0,0 +1,6 @@
1
+ numpy>=1.23
2
+
3
+ [examples]
4
+ scipy>=1.10
5
+ matplotlib>=3.7
6
+ mne>=1.6
@@ -0,0 +1 @@
1
+ flatten_spectrum
@@ -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]))
@@ -0,0 +1,25 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "flatten-spectrum"
7
+ version = "0.1.0"
8
+ description = "FLAT: separate the aperiodic background from periodic peaks in EEG/MEG power spectra"
9
+ readme = "README_python.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ authors = [{name = "Tobias C. Haase"}, {name = "Steffen Gais"}]
13
+ keywords = ["EEG", "MEG", "power spectrum", "aperiodic", "1/f", "oscillations"]
14
+ dependencies = ["numpy>=1.23"]
15
+
16
+ [project.urls]
17
+ Homepage = "https://github.com/SteffenGais/FLAT"
18
+ Documentation = "https://github.com/SteffenGais/FLAT/blob/main/docs/method.md"
19
+ Issues = "https://github.com/SteffenGais/FLAT/issues"
20
+
21
+ [project.optional-dependencies]
22
+ examples = ["scipy>=1.10", "matplotlib>=3.7", "mne>=1.6"]
23
+
24
+ [tool.setuptools]
25
+ py-modules = ["flatten_spectrum"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+