Skip to main content

FLAT for Python

Installation

FLAT needs Python 3.10 or newer and NumPy. The examples also use SciPy, Matplotlib and MNE.

With pip:

pip install flatten-spectrum               # FLAT only
pip install "flatten-spectrum[examples]"   # FLAT and the packages for the examples

With conda, create an environment and install with pip inside it:

conda create -n flat python=3.12 pip
conda activate flat
pip install "flatten-spectrum[examples]"

To install from a copy of this repository, run pip install ".[examples]" in its main folder. You can also copy flatten_spectrum.py into your project; it only needs NumPy.

Usage

from flatten_spectrum import flatten_spectrum

flattened, baseline, slope = flatten_spectrum(power, freqs)
flattened, baseline, slope = flatten_spectrum(power, freqs, notch_hz=[(47.5, 52.5)])

Inputs:

  • power: power spectral density in linear units (e.g. µV²/Hz), with frequencies along the last axis. Leading axes (channels, conditions, ...) are kept. Preferably from long windows with 1/32-octave cells (see below).
  • freqs: frequencies in Hz, increasing.
  • notch_hz (optional): frequency bands to exclude, as (low, high) pairs. Default: none.

Outputs:

  • flattened: the flattened spectrum, power / baseline. It is 1 at the background level and shows periodic activity as peaks, together with the noise of the estimate.
  • baseline: the aperiodic background, in the units of power.
  • slope: the slope of the baseline from 2 to 24 Hz in log-log coordinates, one per spectrum (−2 for a 1/f² background). The aperiodic exponent of specparam (FOOOF, fixed mode) corresponds to −slope.

Frequencies outside 0.3–45 Hz and inside notch bands are NaN in flattened and baseline. Pass only the frequencies your recording measures reliably, away from filter edges (see method):

keep = (freqs >= 1) & (freqs <= 40)
flattened, baseline, slope = flatten_spectrum(power[..., keep], freqs[keep])

Compute the spectrum from windows as long as the recording allows while still averaging about 30 of them, e.g. one 30-s Hann window per sleep epoch, or 4-s windows with 50% overlap for one minute of data. Average the periodograms in linear power, then average power within 1/32-octave cells: low frequencies keep their full resolution, high frequencies become smooth (see method).

import numpy as np
from scipy.signal import welch

freqs, power = welch(data, fs, nperseg=int(10 * fs))   # data: channels x samples, 10-s windows
cells = np.round(32 * np.log2(freqs[1:])).astype(int)  # without the DC bin
_, first, counts = np.unique(cells, return_index=True, return_counts=True)
freqs = np.add.reduceat(freqs[1:], first) / counts
power = np.add.reduceat(power[..., 1:], first, axis=-1) / counts

Examples

The examples in examples/python read any recording MNE can read, e.g. BrainVision (.vhdr) or EDF. Downloads are stored in examples/data.

cd examples/python
python eeg_example.py                           # 1 min of 64-channel resting EEG (1.3 MB download)
python eeg_example.py my_recording.vhdr O1 O2   # your own recording, two channels
python sleep_edf_example.py                     # one night of the Sleep-EDF database (50 MB download)
python sleep_example.py night.vhdr night.txt    # your own sleep recording and scoring

One or two channels are shown as line plots with their baseline, more channels as waterfall plots of power and flattened power.

sleep_example.py needs a text file with one row per 30-s epoch, starting at the first sample of the recording. Its first column holds the sleep stage: 0 wake, 1–4 NREM stages 1–4, 5 REM. Other codes (e.g. 8 for movement time) are skipped, and stages 3 and 4 are combined into N3.

In Python or Jupyter, the examples are functions with the optional arguments channels, frequency_range and notch_hz. They return their results:

from sleep_example import sleep_example

result = sleep_example("night.vhdr", "night.txt", channels=["C3", "C4"])

Metadata

Release files for flatten-spectrum 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for flatten-spectrum 0.1.0
File Size Uploaded Provenance Actions
flatten_spectrum-0.1.0.tar.gz 8.2 kB Without provenance Details for flatten_spectrum-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for flatten-spectrum 0.1.0
File Interpreter ABI Platform Actions
flatten_spectrum-0.1.0-py3-none-any.whl Python 3 none any Details for flatten_spectrum-0.1.0-py3-none-any.whl

Total release size: 15.2 kB

Release files / flatten_spectrum-0.1.0.tar.gz

Download URL flatten_spectrum-0.1.0.tar.gz
Size 8.2 kB
Tags Source
SHA-256 checksum
How to use checksums
a5cfc8947adcd02fc9a7cfcdcb81f19e5dce821bfe79e54c9fdc5e11aef67b32
BLAKE2b-256 checksum
How to use checksums
9511f5b1db2d029fe60915a6479c3ad01273b1f1324622835f8691a6804eaf4a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.15

Release files / flatten_spectrum-0.1.0-py3-none-any.whl

Download URL flatten_spectrum-0.1.0-py3-none-any.whl
Size 7.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
7d26501a359c3cafa2872da0e573908acd70ea0c6755d04a24123ea115e7175d
BLAKE2b-256 checksum
How to use checksums
d0f8f86cf06df4eaa77e7f81e72631261b5bb84bb31584f7f9aeb7d80118b93b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.15

Security for flatten-spectrum 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page