wristpy.processing.analytics

Calculate sleep onset and wake up times.

Functions

compute_physical_activty_categories(...[, ...])

Compute the physical activity categories based on the specific activity metric.

dataclass([cls, init, repr, eq, order, ...])

Add dunder methods based on the fields defined in the class.

sleep_bouts_cleanup(sleep_parameter, ...)

This function will synchronize and filter the SPT and SIB windows.

sleep_cleanup(sleep_windows, nonwear_measurement)

This function will filter the sleep windows based on the nonwear measurement.

Classes

GgirSleepDetection(anglez)

Sleep Detection algorithm based on the GGIR method.

SleepParameters(sleep_windows, spt_windows, ...)

Dataclass to store sleep parameters used to compute sleep metrics.

SleepWindow(onset, wakeup)

Dataclass to store sleep window information.

class wristpy.processing.analytics.GgirSleepDetection(anglez: Measurement)[source]

Bases: object

Sleep 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:

models.Measurement

_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.

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: object

Dataclass 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:

List[wristpy.processing.analytics.SleepWindow]

spt_windows

a Measurement object with the sleep period guider windows.

Type:

wristpy.core.models.Measurement

sib_periods

a Measurement object with the sustained inactivity bouts.

Type:

wristpy.core.models.Measurement

sib_periods: Measurement
sleep_windows: List[SleepWindow]
spt_windows: Measurement
class wristpy.processing.analytics.SleepWindow(onset: datetime | List, wakeup: datetime | List)[source]

Bases: object

Dataclass 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

onset: datetime | List
wakeup: 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) List[Tuple[datetime, datetime]][source]

Find periods where window_measurement is equal to 1.

This is a helper function to return the periods in the format of List [start_of_period, end_of_period], it is used in the GGIRSleepDetection class.

Parameters:

window_measurement – the Measurement instance, intended to be either the spt_window or sib_period.

Returns:

A list of tuples, where each tuple contains the start and end times of a period. For isolated ones the function returns the same start and end time. The list is sorted by time.

wristpy.processing.analytics._sleep_windows_as_measurement(ref_measurement_time: Series, sleep_windows: List[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 and 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 and 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 tuple of two Measurement instances with the cleaned SPT and SIB data.

wristpy.processing.analytics.sleep_cleanup(sleep_windows: List[SleepWindow], nonwear_measurement: 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.

Parameters:
  • sleep_windows – List of the sleep windows (Onset/Wake pairs).

  • nonwear_measurement – The nonwear measurement data used for reference time stamps and to remove overlaps with periods of sleep.

Returns:

A Measurement instance with the cleaned sleep data.