skdh.sleep.Sleep#
- class skdh.sleep.Sleep(start_buffer=0, stop_buffer=0, internal_wear_temp_thresh=25.0, internal_wear_move_thresh=0.001, min_rest_block=30, max_activity_break=60, tso_min_thresh=0.1, tso_max_thresh=1.0, tso_perc=10, tso_factor=15.0, min_rest_period=None, nonwear_move_thresh=None, min_wear_time=0, min_day_hours=6, downsample=True, downsample_aa_filter=True, day_window=(12, 24), save_per_minute_results=False, add_active_time=0.0)#
Process raw accelerometer data from the wrist to determine various sleep metrics and endpoints.
- Parameters:
- start_bufferint, optional
Number of seconds to ignore at the beginning of a recording. Default is 0 seconds.
- stop_bufferint, optional
Number of seconds to ignore at the end of a recording. Default is 0 seconds.
- internal_wear_temp_threshfloat, optional
Internal wear calculation temperature threshold in celsius. Internal wear detection is performed if no wear is provided, and temperature values exist. Default is 25.0 C. Can be disabled by setting to 0.0
- internal_wear_move_threshfloat, optional
Internal wear calculation movement threshold in g. Internal wear detection is performed if no wear is provided, and temperature values are provided. Default is 0.001 g. Can be disabled by setting to 0.0
- min_rest_blockint, optional
Number of minutes required to consider a rest period valid. Default is 30 minutes.
- max_activity_breakint, optional
Number of minutes of activity allowed to interrupt the major rest period. Default is 60 minutes.
- tso_min_threshfloat, optional
Minimum allowed z-angle threshold for determining major rest period. Default is 0.1.
- tso_max_threshfloat, optional
Maximum allowed z-angle threshold for determining major rest period. Default is 1.0.
- tso_percint
The percentile to use when calculating the TSO threshold from daily data. Default is 10.
- tso_factorfloat
The factor to multiply the percentile value by co get the TSO threshold. Default is 15.0.
- min_rest_periodfloat, optional
Minimum length allowed for major rest period. Default is None
- nonwear_move_threshfloat, optional
Threshold for movement based non-wear. Default is None.
- min_wear_timefloat, optional
Used with nonwear_move_thresh. Wear time in minutes required for data to be considered valid. Default is 0
- min_day_hoursfloat, optional
Minimum number of hours required to consider a day useable. Default is 6 hours.
- downsamplebool, optional
Downsample to 20Hz. Default is True.
- downsample_aa_filterbool, optional
Apply an anti-aliasing filter before downsampling. Default is True. Uses the same IIR filter as
scipy.signal.decimate().- day_windowarray-like, optional
Two (2) element array-like of the base and period of the window to use for determining days. Default is (12, 24), which will look for days starting at 12 noon and lasting 24 hours. This should only be changed if the data coming in is from someone who sleeps during the day, in which case (0, 24) makes the most sense.
- add_active_timefloat, optional
Add active time to the accelerometer signal start and end when detecting the total sleep opportunity. This can occasionally be useful if less than 24 hrs of data are collected, as sleep-period skewed data can effect the sleep window cutoff, effecting the end results. Suggested is not adding more than 1.5 hours [5]. Default is 0.0 for no added data.
- save_per_minute_resultsbool, optional
Save minute-by-minute predictions of rest for each day. Default is False.
Methods
add_metrics(metrics)Add metrics to be computed
convert_timestamps(t)Convert a timestamp/array of timestamps to a datetime object
predict(time, accel, *[, temperature, fs, ...])Generate the sleep boundaries and endpoints for a time series signal.
save_results(results, file_name)Save the results of the processing pipeline to a csv file.
Notes
Sleep window detection is based off of methods in [1], [2].
The detection of sleep and wake states uses a heuristic model based on the algorithm described in [3].
The activity index feature is based on the index described in [4].
References
[1]van Hees V, Fang Z, Langford J, Assah F, Mohammad Mirkes A, da Silva I, Trenell M, White T, Wareham N, Brage S (2014). ‘Autocalibration of accelerometer data or free-living physical activity assessment using local gravity and temperature: an evaluation on four continents.’ Journal of Applied Physiology, 117(7), 738-744. doi: 10.1152/japplphysiol.00421.2014, https://www.physiology.org/doi/10.1152/japplphysiol.00421.2014
[2]van Hees V, Sabia S, Anderson K, Denton S, Oliver J, Catt M, Abell J, Kivimaki M, Trenell M, Singh-Maoux A (2015). ‘A Novel, Open Access Method to Assess Sleep Duration Using a Wrist-Worn Accelerometer.’ PloS One, 10(11). doi: 10.1371/journal.pone.0142533, https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0142533.
[3]Cole, R.J., Kripke, D.F., Gruen, W.’., Mullaney, D.J., & Gillin, J.C. (1992). Automatic sleep/wake identification from wrist activity. Sleep, 15 5, 461-9.
[4]Bai J, Di C, Xiao L, Evenson KR, LaCroix AZ, Crainiceanu CM, et al. (2016) An Activity Index for Raw Accelerometry Data and Its Comparison with Other Activity Metrics. PLoS ONE 11(8): e0160644. https://doi.org/10.1371/journal.pone.0160644
[5]V. T. van Hees et al., “Estimating sleep parameters using an accelerometer without sleep diary,” Scientific Reports, vol. 8, no. 1, Art. no. 1, Aug. 2018, doi: 10.1038/s41598-018-31266-z.
- add_metrics(metrics)#
Add metrics to be computed
- Parameters:
- metrics{Iterable, callable}
Either an iterable of EventMetric or BoutMetric references or an individual EventMetric/BoutMetric reference to be added to the list of metrics to be computed
Examples
>>> from skdh.sleep.endpoints import SleepEndpoint >>> class NewSleepMetric(SleepEndpoint): >>> def __init__(self): >>> super().__init__("metric name", __name__) # __name__ remains unchanged >>> def predict(self, **kwargs): >>> pass >>> >>> sleep = Sleep() >>> sleep.add_metrics(NewSleepMetric)
- predict(time, accel, *, temperature=None, fs=None, wear=None, day_ends={}, tz_name=None)#
Generate the sleep boundaries and endpoints for a time series signal.
- Parameters:
- timenumpy.ndarray
(N, ) array of unix timestamps, in seconds
- accelnumpy.ndarray
(N, 3) array of acceleration, in units of ‘g’
- temperaturenumpy.ndarray, optional
(N, ) array of temperature values, in celsius. Will be used for internal wear calculation if wear is not provided.
- fsfloat, optional
Sampling frequency in Hz for the acceleration and temperature values. If None, will be inferred from the timestamps
- wearnumpy.ndarray, optional
(P, 2) array of indices indicating where the device is worn. Optional.
- day_endsdict
Dictionary containing (N, 2) arrays of start and stop indices for individual days. Must have the key
- Other Parameters:
- tz_name{None, str}, optional
IANA time-zone name for the recording location if passing in time as UTC timestamps. Can be ignored if passing in naive timestamps.
- save_results(results, file_name)#
Save the results of the processing pipeline to a csv file. Will also save per minute rest/sleep predictions if save_per_minute_results was set to True. The file name for per minute results is the same as the sleep endpoints file with “_per_minute_predictions_day_<n>” added to the end.
- Parameters:
- resultsdict
Dictionary of results from the output of predict
- file_namestr
File name. Can be optionally formatted (see Notes)
Notes
Available format variables available:
date: todays date expressed in yyyymmdd format.
name: process name.
file: file name used in the pipeline, or “” if not found.