Hypnogram#
- brainmaze_eeg.hypnogram.correct_hypnogram(df, time_threshold=60)#
Apply a series of corrections to hypnogram data.
This function applies multiple correction steps: fills gaps between same states, fills wake-REM gaps, fills non-REM gaps, fills sleep gaps, and corrects REM annotations.
- Parameters:
df (pd.DataFrame) – Hypnogram dataframe with ‘annotation’, ‘start’, ‘end’, and ‘duration’ columns.
time_threshold (int, optional) – Time threshold in seconds for gap filling. Default is 60.
- Returns:
Corrected hypnogram dataframe.
- Return type:
pd.DataFrame
- brainmaze_eeg.hypnogram.correct_rem(df, time_threshold=300, initial_state='AWAKE')#
Correct REM annotations that occur shortly after prolonged awake periods.
- Parameters:
df (pd.DataFrame) – Hypnogram dataframe with ‘annotation’, ‘start’, ‘end’, and ‘duration’ columns.
time_threshold (int, optional) – Minimum sustained awake duration in seconds. Default is 300 (5 minutes).
initial_state (str, optional) – Initial assumed state. Default is ‘AWAKE’.
- Returns:
Hypnogram with corrected REM annotations.
- Return type:
pd.DataFrame
- brainmaze_eeg.hypnogram.do_median_filtration(df)#
Apply median filtering to remove isolated 30-second stage annotations.
- Parameters:
df (pd.DataFrame) – Hypnogram dataframe with ‘annotation’ and ‘duration’ columns.
- Returns:
Filtered hypnogram dataframe.
- Return type:
pd.DataFrame
- brainmaze_eeg.hypnogram.fill_nonrem_voids(df, time_threshold=300, initial_state='AWAKE')#
Fill gaps between non-REM sleep stages (N2, N3) with ‘N’ annotations.
- Parameters:
df (pd.DataFrame) – Hypnogram dataframe with ‘annotation’, ‘start’, ‘end’, and ‘duration’ columns.
time_threshold (int, optional) – Maximum gap duration in seconds to fill. Default is 300 (5 minutes).
initial_state (str, optional) – Initial assumed state. Default is ‘AWAKE’.
- Returns:
Hypnogram with filled non-REM gaps.
- Return type:
pd.DataFrame
- brainmaze_eeg.hypnogram.fill_same_voids(df, time_threshold=300, initial_state='AWAKE')#
Fill temporal gaps between consecutive same-state annotations.
- Parameters:
df (pd.DataFrame) – Hypnogram dataframe with ‘annotation’, ‘start’, ‘end’, and ‘duration’ columns.
time_threshold (int, optional) – Maximum gap duration in seconds to fill. Default is 300 (5 minutes).
initial_state (str, optional) – Initial assumed state. Default is ‘AWAKE’.
- Returns:
Hypnogram with filled gaps.
- Return type:
pd.DataFrame
- brainmaze_eeg.hypnogram.fill_sleep_voids(df, time_threshold=300, initial_state='AWAKE')#
Fill gaps between any sleep states (non-AWAKE) with ‘SLP’ annotations.
- Parameters:
df (pd.DataFrame) – Hypnogram dataframe with ‘annotation’, ‘start’, ‘end’, and ‘duration’ columns.
time_threshold (int, optional) – Maximum gap duration in seconds to fill. Default is 300 (5 minutes).
initial_state (str, optional) – Initial assumed state. Default is ‘AWAKE’.
- Returns:
Hypnogram with filled sleep gaps.
- Return type:
pd.DataFrame
- brainmaze_eeg.hypnogram.fill_wakerem_voids(df, time_threshold=300, initial_state='AWAKE')#
Fill gaps between AWAKE and REM states with AWAKE annotations.
- Parameters:
df (pd.DataFrame) – Hypnogram dataframe with ‘annotation’, ‘start’, ‘end’, and ‘duration’ columns.
time_threshold (int, optional) – Maximum gap duration in seconds to fill. Default is 300 (5 minutes).
initial_state (str, optional) – Initial assumed state. Default is ‘AWAKE’.
- Returns:
Hypnogram with filled wake-REM gaps.
- Return type:
pd.DataFrame
- brainmaze_eeg.hypnogram.get_awakening_time(df, t_awake_threshold=90, t_sleep_threshold=10, awake_tag='AWAKE', sleep_cycle_tags=['REM', 'N2', 'N3'])#
Determine when the subject woke up based on hypnogram data.
- Parameters:
df (pd.DataFrame) – Hypnogram dataframe with ‘annotation’, ‘start’, ‘end’, and ‘duration’ columns.
t_awake_threshold (int, optional) – Minimum sustained awake time in minutes to be considered awakened. Default is 90.
t_sleep_threshold (int, optional) – Maximum sleep time in minutes allowed in the awakening window. Default is 10.
awake_tag (str, optional) – Tag for awake state. Default is ‘AWAKE’.
sleep_cycle_tags (list, optional) – List of tags indicating sleep states. Default is [‘REM’, ‘N2’, ‘N3’].
- Returns:
Timestamp when the subject woke up.
- Return type:
datetime
- brainmaze_eeg.hypnogram.get_fell_asleep_time(df, t_sleep_check=60, t_awake_threshold=10, awake_tag='AWAKE', sleep_cycle_tags=['REM', 'N1', 'N2', 'N3'])#
Determine when the subject fell asleep based on hypnogram data.
- Parameters:
df (pd.DataFrame) – Hypnogram dataframe with ‘annotation’, ‘start’, ‘end’, and ‘duration’ columns.
t_sleep_check (int, optional) – Time window in minutes to check for sustained sleep. Default is 60.
t_awake_threshold (int, optional) – Maximum awake time in minutes allowed within t_sleep_check window. Default is 10.
awake_tag (str, optional) – Tag for awake state. Default is ‘AWAKE’.
sleep_cycle_tags (list, optional) – List of tags indicating sleep states. Default is [‘REM’, ‘N1’, ‘N2’, ‘N3’].
- Returns:
Timestamp when the subject fell asleep.
- Return type:
datetime
- brainmaze_eeg.hypnogram.get_hypnogram_datarate(df)#
Calculate the data rate of a hypnogram.
- Parameters:
df (pd.DataFrame) – Hypnogram dataframe with ‘duration’, ‘start’, and ‘end’ columns.
- Returns:
Data rate as the ratio of total duration to time span.
- Return type:
float
- brainmaze_eeg.hypnogram.get_number_of_awakenings(df, awake_tag='AWAKE', n1_tag='N1', sleep_tags=['N2', 'N3', 'REM'])#
Count the number of awakenings after sleep onset.
- Parameters:
df (pd.DataFrame) – Hypnogram dataframe with ‘annotation’ column.
awake_tag (str, optional) – Tag for awake state. Default is ‘AWAKE’.
n1_tag (str, optional) – Tag for N1 sleep stage. Default is ‘N1’.
sleep_tags (list, optional) – List of tags for sleep states. Default is [‘N2’, ‘N3’, ‘REM’].
- Returns:
Number of awakenings.
- Return type:
int
- brainmaze_eeg.hypnogram.get_number_of_sleep_stages(df, tags='REM', delay=30)#
Count the number of sleep stage occurrences with minimum separation delay.
- Parameters:
df (pd.DataFrame) – Hypnogram dataframe with ‘annotation’, ‘start’, and ‘end’ columns.
tags (str or list, optional) – Sleep stage tag(s) to count. Default is ‘REM’.
delay (int, optional) – Minimum time in minutes between stage occurrences. Default is 30.
- Returns:
Number of sleep stage occurrences.
- Return type:
int
- brainmaze_eeg.hypnogram.get_rem_latency(df, rem_tag='REM', awake_tag='AWAKE')#
Calculate REM sleep latency (time from falling asleep or last awake to first REM).
- Parameters:
df (pd.DataFrame) – Hypnogram dataframe with ‘annotation’, ‘start’, and ‘end’ columns.
rem_tag (str, optional) – Tag for REM sleep state. Default is ‘REM’.
awake_tag (str, optional) – Tag for awake state. Default is ‘AWAKE’.
- Returns:
Dictionary with ‘last_awake’ and ‘fall_asleep’ latencies as timedelta objects.
- Return type:
dict
- brainmaze_eeg.hypnogram.get_stage_times(df, keys)#
Get total times for multiple sleep stages.
- Parameters:
df (pd.DataFrame) – Hypnogram dataframe with ‘annotation’ and ‘duration’ columns.
keys (list) – List of sleep stage tags.
- Returns:
List of total durations for each stage in seconds.
- Return type:
list
- brainmaze_eeg.hypnogram.get_stage_times_dataset(hypnograms: list, keys, verbose=True)#
Get stage times for a dataset of hypnograms.
- Parameters:
hypnograms (list) – List of hypnogram dataframes.
keys (list) – List of sleep stage tags.
verbose (bool, optional) – If True, show progress bar. Default is True.
- Returns:
Dataframe with stage times for each hypnogram.
- Return type:
pd.DataFrame
- brainmaze_eeg.hypnogram.get_time_by_key(df, key)#
Calculate total time for a specific sleep stage or combination of stages.
- Parameters:
df (pd.DataFrame) – Hypnogram dataframe with ‘annotation’ and ‘duration’ columns.
key (str or list) – Sleep stage tag(s) to sum durations for.
- Returns:
Total duration in seconds.
- Return type:
float
- brainmaze_eeg.hypnogram.get_transition_counts(hyp, states=['AWAKE', 'N1', 'N2', 'N3', 'REM'])#
Count transitions between sleep stages.
- Parameters:
hyp (pd.DataFrame) – Hypnogram dataframe with ‘annotation’ column.
states (list, optional) – List of sleep states to include. Default is [‘AWAKE’, ‘N1’, ‘N2’, ‘N3’, ‘REM’].
- Returns:
Matrix of transition counts where [i,j] is count of transitions from state i to state j.
- Return type:
np.ndarray
- brainmaze_eeg.hypnogram.get_transition_matrix(hyp, states=['AWAKE', 'N1', 'N2', 'N3', 'REM'])#
Calculate transition probability matrix between sleep stages.
- Parameters:
hyp (pd.DataFrame) – Hypnogram dataframe with ‘annotation’ column.
states (list, optional) – List of sleep states to include. Default is [‘AWAKE’, ‘N1’, ‘N2’, ‘N3’, ‘REM’].
- Returns:
Normalized transition probability matrix.
- Return type:
np.ndarray
- brainmaze_eeg.hypnogram.get_transition_matrix_dataset(hypnograms, states=['AWAKE', 'N1', 'N2', 'N3', 'REM'])#
Calculate mean and std of transition matrices across a dataset of hypnograms.
- Parameters:
hypnograms (list) – List of hypnogram dataframes.
states (list, optional) – List of sleep states to include. Default is [‘AWAKE’, ‘N1’, ‘N2’, ‘N3’, ‘REM’].
- Returns:
Mean transition matrix and standard deviation matrix.
- Return type:
tuple
- brainmaze_eeg.hypnogram.is_sleep_complete(df, awake_tag='AWAKE')#
Check if the sleep session is complete (starts and ends with awake state).
- Parameters:
df (pd.DataFrame) – Hypnogram dataframe with ‘annotation’ column.
awake_tag (str, optional) – Tag for awake state. Default is ‘AWAKE’.
- Returns:
True if sleep session starts and ends with awake state, False otherwise.
- Return type:
bool
- brainmaze_eeg.hypnogram.plot_hypnogram(orig_df, hypnogram_values=None, hypnogram_colors=None, fontsize=12, fig=None, night_start=22)#
Creates a Matplotlib figure of spectrogram from the annotations. Time must be in a time-zone aware format.
- Parameters:
orig_df (annotations)
hypnogram_values (dict) – dict of a y-axis values for each hypnogram state
hypnogram_colors (dict) – dict of color hex codes for each hypnogram state
fontsize (int) – Fontsize
fig (figure) – Already existing figure object.
night_start (int) – A hour when does the night begin
- brainmaze_eeg.hypnogram.print_sleep_score(score)#
Print a formatted summary of sleep metrics.
- Parameters:
score (dict) – Sleep score dictionary from score_night function.
- brainmaze_eeg.hypnogram.score_night(df, plot=False)#
Compute comprehensive sleep metrics for a night’s hypnogram.
- Parameters:
df (pd.DataFrame) – Hypnogram dataframe with ‘annotation’, ‘start’, ‘end’, and ‘duration’ columns.
plot (bool, optional) – If True, plot the hypnogram with sleep onset and awakening markers. Default is False.
- Returns:
Dictionary containing sleep metrics including:
sleep_complete: whether sleep session is complete
fell_asleep_time: time of sleep onset
rem_latency_fell_asleep: REM latency from sleep onset (seconds)
rem_latency_last_awake: REM latency from last awake (seconds)
awakening_time: time of final awakening
n_complete_sleep_cycles: number of complete sleep cycles
n_awakenings: number of awakenings
n1_sleep_time, n2_sleep_time, n3_sleep_time, rem_sleep_time, awake_sleep_time: durations in seconds for each stage
- Return type:
dict
- brainmaze_eeg.hypnogram.transition_matrix_to_change_matrix(m)#
Convert transition matrix to change matrix (excluding diagonal/same-state transitions).
- Parameters:
m (np.ndarray) – Transition probability matrix.
- Returns:
Change matrix with diagonal set to zero and rows renormalized.
- Return type:
np.ndarray
- brainmaze_eeg.hypnogram.valid_dataset_index_by_duration(hypnograms: list, filt_dict: dict)#
Filter hypnograms by minimum duration requirements for specific stages.
- Parameters:
hypnograms (list) – List of hypnogram dataframes.
filt_dict (dict) – Dictionary mapping stage names to minimum duration thresholds.
- Returns:
Indices of hypnograms meeting all duration requirements.
- Return type:
list