yasa.Hypnogram.from_integers#
- classmethod Hypnogram.from_integers(values, mapping={-2: 'Uns', -1: 'Art', 0: 'W', 1: 'N1', 2: 'N2', 3: 'N3', 4: 'R'}, n_stages=5, *, freq='30s', start=None, tz=None, scorer=None, proba=None)[source]#
Create a
Hypnogramfrom an integer-encoded hypnogram array.This is a convenience constructor for users migrating from the legacy integer-based API (e.g.
[0, 1, 2, 3, 4]for Wake, N1, N2, N3, REM). Internally, it callsyasa.hypno_int_to_strto convert integers to strings before creating theHypnogram.Added in version 0.7.0.
- Parameters:
- valuesarray_like
A 1D array of integer sleep stage values, e.g.
np.array([0, 1, 1, 2, 3, 4]).- mappingdict
A dictionary mapping integer values to stage string labels. The default mapping is:
{0: "W", 1: "N1", 2: "N2", 3: "N3", 4: "R", -1: "Art", -2: "Uns"}
Override this to support non-standard integer encodings.
- n_stagesint
Whether
valuescomes from a 2, 3, 4 or 5-stage hypnogram. Default is 5.- freqstr
Frequency resolution of the hypnogram. Default is
"30s".- startstr or datetime, optional
Optional start datetime of the hypnogram (e.g.
"2022-12-15 22:30:00").- scorerstr, optional
Optional scorer name.
- proba
pandas.DataFrame, optional Optional dataframe of per-epoch stage probabilities.
- Returns:
Examples
Convert a legacy integer hypnogram to a
Hypnogramobject:>>> import numpy as np >>> from yasa import Hypnogram >>> int_hypno = np.array([0, 0, 1, 2, 3, 2, 4, 4, 0]) >>> hyp = Hypnogram.from_integers(int_hypno) >>> hyp <Hypnogram | 9 epochs x 30s (4.50 minutes), 5 unique stages> - Use `.hypno` to get the string values as a pandas.Series - Use `.as_int()` to get the integer values as a pandas.Series - Use `.plot_hypnogram()` to plot the hypnogram See the online documentation for more details.
>>> hyp.hypno Epoch 0 WAKE 1 WAKE 2 N1 3 N2 4 N3 5 N2 6 REM 7 REM 8 WAKE Name: Stage, dtype: category Categories (7, str): ['WAKE', 'N1', 'N2', 'N3', 'REM', 'ART', 'UNS']
Typical usage when loading a hypnogram from a plain-text file:
>>> import numpy as np >>> from yasa import Hypnogram >>> int_hypno = np.loadtxt("path/to/hypnogram.txt").astype(int) >>> hyp = Hypnogram.from_integers( ... int_hypno, freq="30s", start="2022-12-15 22:30:00" ... )
Use a custom mapping to handle non-standard integer encodings:
>>> # Hypnogram encoded as: 1=WAKE, 2=REM, 3=N1, 4=N2, 5=N3 >>> custom_mapping = {1: "W", 2: "R", 3: "N1", 4: "N2", 5: "N3"} >>> hyp = Hypnogram.from_integers([1, 3, 4, 5, 2], mapping=custom_mapping)