@@ -1801,16 +1801,42 @@ def main_sleep_bouts(data, report='major'):
18011801 # Compute the activity onset and off using the Roenneberg algorithm
18021802 activity_onset , activity_offset = Roenneberg_AoT (data )
18031803
1804- # Create empty dataframe to store all the sleep events
1805- sleep_events = pd .DataFrame ()
1806-
1804+ events = []
1805+ # For each sleep onset, find the next awakening and calculate the duration of the sleep episode
1806+ for sleep_onset in activity_offset :
1807+ # Find the next awakening after the sleep onset
1808+ following_awakening = activity_onset [activity_onset > sleep_onset ]
1809+
1810+ # If there is no awakening after the sleep onset, skip this sleep episode
1811+ if len (following_awakening ) == 0 :
1812+ continue
1813+
1814+ # Append the sleep episode to the events list
1815+ events .append ((sleep_onset , following_awakening [0 ], following_awakening [0 ] - sleep_onset ))
1816+
1817+ # Create a DataFrame from the events list with columns for start_time, stop_time, and duration
1818+ sleep_events = pd .DataFrame (events , columns = ['start_time' , 'stop_time' , 'duration' ])
1819+
1820+ # Date each episode is assigned to
1821+ sleep_events ['date' ] = sleep_events ['start_time' ].dt .date
1822+
1823+ # --- Deprecated (buggy) implementation, kept for reference ---
1824+ # Paired the two event arrays by position: activity_offset[i] as the sleep
1825+ # onset and activity_onset[i] as the matching wake. This assumes onset i
1826+ # always lines up with wake i, which fails in two ways:
1827+ # * If the recording starts or ends mid-sleep, activity_offset and
1828+ # activity_onset differ in length, and assigning them as DataFrame
1829+ # columns raises "Length of values (N) does not match length of
1830+ # index (M)".
1831+ # * Even at equal lengths, an onset can be paired with a wake that comes
1832+ # before it, producing negative or otherwise incorrect durations. # starts with a sleep episode (i.e. activity_offset < activity_onset)
18071833 # sleep_onset = activity_offset; sleep_offset = activity_onset
1808- sleep_events ['date' ] = activity_onset .date
1809- sleep_events ['start_time' ] = activity_offset
1810- sleep_events ['stop_time' ] = activity_onset
1834+ # sleep_events['date'] = activity_onset.date
1835+ # sleep_events['start_time'] = activity_offset
1836+ # sleep_events['stop_time'] = activity_onset
18111837
18121838 # Sleep/rest episode duration
1813- sleep_events ['duration' ] = sleep_events ['stop_time' ] - sleep_events ['start_time' ]
1839+ # sleep_events['duration'] = sleep_events['stop_time'] - sleep_events['start_time']
18141840
18151841 # Identify main sleep episode
18161842 main_sleep = sleep_events .loc [sleep_events .groupby ('date' )['duration' ].idxmax ()]
0 commit comments