wristpy.processing.analytics¶
Calculate sleep onset and wake up times.
Functions
|
Compute the physical activity categories based on the specific activity metric. |
|
Add dunder methods based on the fields defined in the class. |
|
This function will synchronize and filter the SPT or SIB windows. |
|
This function will filter the sleep windows based on the nonwear measurement. |
Classes
|
Sleep Detection algorithm based on the GGIR method. |
|
Dataclass to store sleep parameters used to compute sleep metrics. |
|
Dataclass to store sleep window information. |
|
Represent a union type |
- class wristpy.processing.analytics.GgirSleepDetection(anglez: Measurement)[source]¶
Bases:
objectSleep Detection algorithm based on the GGIR method.
This class implements the GGIR method for sleep detection. The method uses the angle-z data to find periods of sleep. It returns a list of SleepWindow objects.
- anglez¶
The angle-z data, calculated from the calibrated accelerometer data.
- Type:
- _calculate_sib_periods(anglez_data: Measurement, threshold_degrees: int = 5) Measurement[source]¶
Find the sustained inactivity bouts.
This function finds the absolute difference of the anglez data over 5s windows. We then find the 5-minute windows where all the differences are below a threshold (defaults to 5 degrees).
- Parameters:
anglez_data – the raw anglez data, calculated from calibrated acceleration.
threshold_degrees – the threshold, in degrees, for inactivity.
- Returns:
A Measurement instance with values set to 1 indicating identified SIB windows, and corresponding time stamps.
References
- van Hees, V. T. et al. A Novel, Open Access Method to Assess Sleep
Duration Using a Wrist-Worn Accelerometer. PLoS One 10, e0142533 (2015). https://doi.org/10.1371/journal.pone.0142533.
- _compute_abs_diff_mean_anglez(anglez_data: Measurement, window_size_seconds: int = 5) Measurement[source]¶
Helper function to compute the absolute difference of averaged anglez data.
- Parameters:
anglez_data – the raw anglez data.
window_size_seconds – the window size in seconds to average the anglez data.
- Returns:
A Measurement instance with the absolute difference of the anglez data. Note that the length of the returned Measurement instance will be one less than the input anglez_data, this is because np.diff returns an array that is diff_size shorter than the input, where diff_size is the size of the difference step.
- _find_onset_wakeup_times(spt_periods: List[Tuple[datetime, datetime]], sib_periods: List[Tuple[datetime, datetime]]) List[SleepWindow][source]¶
Find the sleep onset and wake up times.
This function is implemented as follows: First, we use the spt_window as a guider for potential sleep. Then we find overlapping sustained inactivity bouts (sib_periods == 1). Sleep onset is defined as the start of the first sib_period that overlaps with a specific spt_window. Sleep wakeup is the end of the last SIB that overlaps with a spt window.
- Parameters:
spt_periods – the sleep period guider windows, this is computed from the _find_periods method, it is a list of tuples of start and end times of the periods.
sib_periods – the sustained inactivity bouts, this is computed from the _find_periods method, it is a list of tuples of start and end times of the periods.
- Returns:
A SleepWindow instance with sleep onset and wake up times. If there is no overlap between spt_windows and sib_periods, the onset and wakeup lists will be empty.
- _spt_window(anglez_data: Measurement, threshold: float = 0.2) Measurement[source]¶
Implement Heuristic distribution of z angle (HDCZA) for SPT window detection.
This function finds the absolute difference of the anglez data over 5s windows. We find the 5-minute rolling median of that difference. Next, we find when that 5-minute median is above a specified threshold, taken as the new default value from the GGIR implementation of the HDCZA algorithm. This represents non-sleep candidates. The logical not of this is the sleep candidate. We then find long blocks (30 minutes) when the threshold criteria is met. Any gaps in SPT windows that are less than 60 minutes are filled.
- Parameters:
anglez_data – the raw anglez data, calculated from calibrated acceleration.
threshold – the threshold for the distribution of z angle, chosen as 0.2 based on new GGIR default.
- Returns:
A Measurement instance with values set to 1 indicating identified SPT windows and corresponding time stamps.
References
- van Hees, V.T., et al. Estimating sleep parameters using an
accelerometer without sleep diary. Sci Rep 8, 12975 (2018). https://doi.org/10.1038/s41598-018-31266-z.
- run_sleep_detection() SleepParameters[source]¶
Run the GGIR sleep detection.
This algorithm uses the angle-z data to first find potential sleep periods (SPT windows) and then find sustained inactivity bouts (SIB periods). The sleep onset and wake up times are then calculated based on the overlap between the SPT windows and SIB periods.
Currently, the spt and sib window lengths are hardcoded to 5 seconds and 5 mintues, respectively to adhere to the published algorithm implementation.
- Returns:
sleep_windows
spt_window
sib_periods
- Return type:
A SleepParameters instance containing the underlying sleep parameters
- class wristpy.processing.analytics.SleepParameters(sleep_windows: List[SleepWindow], spt_windows: Measurement, sib_periods: Measurement)[source]¶
Bases:
objectDataclass to store sleep parameters used to compute sleep metrics.
- sleep_windows¶
a list of SleepWindow objects, each representing a sleep period with an onset and wakeup time.
- Type:
- spt_windows¶
a Measurement object with the sleep period guider windows.
- sib_periods¶
a Measurement object with the sustained inactivity bouts.
- sib_periods: Measurement¶
- sleep_windows: List[SleepWindow]¶
- spt_windows: Measurement¶
- class wristpy.processing.analytics.SleepWindow(onset: datetime | List, wakeup: datetime | List)[source]¶
Bases:
objectDataclass to store sleep window information.
- onset¶
the predicted start time of the sleep window.
- Type:
datetime.datetime | List
- wakeup¶
the predicted end time of the sleep window.
- Type:
datetime.datetime | List
- wristpy.processing.analytics._fill_false_blocks(boolean_array: ndarray, gap_block: int) ndarray[source]¶
Helper function to fill gaps in any window that are less than gap_blocks.
We find the first non-zero in the boolean_array, if there are none , we return the initial array. We then iterate over the array and count every zero between ones (skipping the leading zeros), if that value is less than the gap_block, we fill in with ones.
- Parameters:
boolean_array – A generic boolean array, typically the SPT window.
gap_block – the length of the gap that needs to be filled.
- Returns:
A booelan numpy array where true, typically, indicates the SPT windows.
- wristpy.processing.analytics._find_periods(window_measurement: Measurement, bucket_duration: timedelta) List[Tuple[datetime, datetime]][source]¶
Find periods where window_measurement is equal to 1.
Measurement timestamps label bucket starts. Each active run is returned as a half-open interval [start, end), from the first active bucket’s start to the last active bucket’s nominal end, including the final observation.
- Parameters:
window_measurement – the Measurement instance, intended to be either the spt_window or sib_period.
bucket_duration – the duration of each bucket.
- Returns:
A list of tuples, where each tuple contains the start and end times of a period. An isolated active bucket spans one full bucket duration. The list is sorted by time; all-inactive measurements return no periods.
- wristpy.processing.analytics._sleep_windows_as_measurement(ref_measurement_time: Series, sleep_windows: Iterable[SleepWindow]) Measurement[source]¶
Helper function to convert list of sleep windows to a Measurement instance.
The temporal resolution of the output Measurement instance matches the reference measurement.
- Parameters:
ref_measurement_time – Reference polars Series with time stamps from a reference Measurement.
sleep_windows – The list of sleep windows, where the entries are instances of the SleepWindow class.
- Returns:
A new Measurement instance with the sleep values, as a booleans.
- wristpy.processing.analytics.compute_physical_activty_categories(activity_metric_epoch1: Measurement, thresholds: Tuple[float, float, float] = (0.0563, 0.1916, 0.6958), name: str | None = None) Measurement[source]¶
Compute the physical activity categories based on the specific activity metric.
This function uses the activity_metric_epoch1 data (5s aggregated data) to compute four physical activity levels: inactive, light, moderate, and vigorous.
Default values are specifically for ENMO data, taken from the Hildebrand 2014 study, and is best suited for children aged 7 - 11 years.
- Parameters:
activity_metric_epoch1 – The specific activity metric epoch1 data, as physical activity data should be computed on aggregated data.
thresholds – The threshold values for the physical activity categories. The default values are: (light_threshold, moderate_threshold, vigorous_threshold).
name – The name of the Measurement object
- Returns:
A Measurement instance with the physical activity categories. Categories are Inactive, Light, Moderate, Vigorous. The temporal resolution is the same as activity_metric_epoch1.
- Raises:
ValueError – If the threshold values are not poisitive, unique and in ascending
order. –
References
- Hildebrand, M., et al. Age group comparability of raw accelerometer output
from wrist- and hip-worn monitors. Medicine and Science in Sports and Exercise, 46(9), 1816-1824 (2014). https://doi.org/10.1249/mss.0000000000000289.
- wristpy.processing.analytics.sleep_bouts_cleanup(sleep_parameter: Measurement, nonwear_measurement: Measurement, time_reference_measurement: Measurement, epoch_length: float) Measurement[source]¶
This function will synchronize and filter the SPT or SIB windows.
The time sychrnoization is based on the time_reference_measurement, while the filtering is based on the nonwear_measurement.
- Parameters:
sleep_parameter – The sleep parameter measurement data, which contains either the SPT or SIB windows.
nonwear_measurement – The nonwear measurement data used for reference time stamps and to remove overlaps with periods of sleep.
time_reference_measurement – The time reference measurement data used for reference time stamps.
epoch_length – The epoch length in seconds, used for resampling the data.
- Returns:
A Measurement object with the cleaned SPT or SIB data.
- wristpy.processing.analytics.sleep_cleanup(sleep_windows: Iterable[SleepWindow], nonwear_measurement: Measurement, adaptive: bool | None = None, nonwear_sleep_buffer: int = 0) Tuple[Measurement, Measurement][source]¶
This function will filter the sleep windows based on the nonwear measurement.
The SleepWindows are first converted to a Measurement object with the same timestamps as the reference measurement. Then any overlap with nonwear is removed, and finally any blocks of sleep that are less than 15 minutes long are removed.
An adaptive second pass can also be performed, where we look ahead a specified number of samples after the end of each nonwear run, and if we find sleep within that buffer, we absorb the nonwear run into sleep. This is to account for some cases where we were finding initial sleep phases to cause false-positives in the non-wear detection.
- Parameters:
sleep_windows – Iterable of sleep windows (onset/wakeup pairs).
nonwear_measurement – The nonwear measurement data used for reference time stamps and to remove overlaps with periods of sleep.
adaptive – Whether to perform the second pass of absorbing nonwear runs into sleep when sleep follows nonwear within the configured buffer. Defaults to None, which is equivalent to False.
nonwear_sleep_buffer – The number of samples to look ahead when performing adaptive cleanup. Defaults to 0, which only includes the first sample after a nonwear run. Must be non-negative.
- Returns:
A tuple containing the cleaned sleep Measurement and the nonwear Measurement. If adaptive cleanup is enabled, the returned nonwear data excludes runs absorbed into sleep; otherwise the original nonwear Measurement is returned.
- Raises:
ValueError – If nonwear_sleep_buffer is negative.