Skip to main content

This package provides a toolbox of functions to compute key metrics about nocturnal sleep from already processed wrist-worn actigraphy data.

Project description

noctsleepy

A Python package for computing nocturnal sleep metrics from processed actigraphy data.

Build codecov Ruff stability-stable MIT License pages

Overview

noctsleepy is a Python-based toolbox for computing comprehensive sleep metrics from processed actigraphy data. Sleep metrics are computed from a user-defined nocturnal window, thus the impact of naps/secondary sleep can be removed if needed. The package handles timezone-aware processing, including proper daylight saving time (DST) transitions, and computes both individual night metrics and summary statistics across multiple nights.

Key Features

  • Comprehensive Sleep Metrics: Computes sleep duration, time in bed, sleep efficiency, wake after sleep onset (WASO), number of awakenings, sleep onset/wakeup times, and sleep midpoints.
  • DST-Aware Processing: Properly handles daylight saving time transitions using IANA timezone database, ensuring accurate sleep timing metrics during time changes.
  • Summary Statistics: Automatically computes mean and standard deviation for all requested metrics.
  • Flexible Nocturnal Windows: Users can define custom start and end times for the nocturnal interval.
  • Non-wear Filtering: Filters out nights with excessive non-wear time based on user-defined thresholds.

Installation

Install the noctsleepy package from PyPI via:

pip install noctsleepy

Quick Start

noctsleepy provides two flexible interfaces: a command-line tool for direct execution and an importable Python library.

Using noctsleepy through the command-line:

Basic usage:

noctsleepy /path/to/data.csv america/new_york

Custom parameters:

noctsleepy /path/to/data.csv europe/london \
  --night-start 22:00 \
  --night-end 07:00 \
  --nw-threshold 0.3 \
  --metrics sleep_duration \
  --metrics sleep_timing

For a full list of command line arguments:

noctsleepy --help

Using noctsleepy through a Python script or notebook:

import noctsleepy
import pathlib
import datetime

# Define input file path
input_path = pathlib.Path('/path/to/your/data.csv')

# Compute all sleep metrics
sleep_metrics = noctsleepy.compute_sleep_metrics(
    input_data=input_path,
    timezone='America/New_York'
)

# Compute custom pipeline
custom_metrics = noctsleepy.compute_sleep_metrics(    
    input_data=input_path,
    timezone='America/Toronto',
    night_start=datetime.time(22, 0),
    night_end=datetime.time(6, 0),
    nw_threshold=0.15,
    selected_metrics=['sleep_continuity', 'sleep_timing']
)

# Access computed metrics
sleep_duration = sleep_metrics.sleep_duration
sleep_onset = sleep_metrics.sleep_onset
sleep_efficiency = sleep_metrics.sleep_efficiency

Input Data Requirements

noctsleepy requires processed actigraphy data with the following columns:

  • time: Timestamps for each data point, it should be a singular sampling rate.
  • sib_periods: Boolean indicating sustained inactivity bouts (sleep detection).
  • spt_periods: Boolean indicating sleep period time windows.
  • nonwear_status: Boolean indicating non-wear periods.

The input data should ideally be processed with wristpy or have a compatible output format. Supported input formats include CSV and Parquet files.

Computed Sleep Metrics

All metrics are computed only during the defined nocturnal window, any sleep that occurs outside of this window is ignored.

Sleep Duration Metrics

  • sleep_duration: Total sleep time in minutes (sum of sustained inactivity bouts within sleep period time).
  • time_in_bed: Total time in bed in minutes (duration of sleep period time windows).

Sleep Continuity Metrics

  • sleep_efficiency: Ratio of total sleep time to time in bed, as a percentage.
  • waso: Wake After Sleep Onset, in minutes.
  • num_awakenings: Number of awakening episodes during the sleep period.
  • waso_30: Number of nights with WASO exceeding 30 minutes (normalized to 30-day protocol).

Sleep Timing Metrics

  • sleep_onset: Time when the first sleep period starts (HH:MM format).
  • sleep_wakeup: Time when the last sleep period ends (HH:MM format).
  • sleep_midpoint: Midpoint of the sleep period (HH:MM format).
  • weekday_midpoint: Average sleep midpoint on weekdays (Monday-Friday).
  • weekend_midpoint: Average sleep midpoint on weekends (Saturday-Sunday).
  • social_jetlag: Absolute difference between weekend and weekday midpoints, in hours.

Summary Statistics

For each metric, noctsleepy automatically computes:

  • Mean: Average value across all valid nights
  • Standard Deviation: Measure of variability across nights
    • Duration metrics use standard statistics
    • Time-based metrics use circular statistics to properly handle times crossing midnight

Handling Timezones and Daylight Saving Time

noctsleepy requires users to specify a timezone-aware location using IANA timezone database names (e.g., America/New_York, Europe/London). The package properly handles DST transitions:

Wall-Clock vs. Anatomical Clock

  • Wall-clock metrics (sleep onset, wakeup, midpoint): Reported based on the local time displayed on a clock
  • Anatomical clock metrics (sleep duration, time in bed, WASO, sleep efficiency): Account for actual elapsed time, including DST changes.

Example: During a "fall back" DST transition, if someone sleeps from 10:00 PM to 6:00 AM (wall-clock time), their sleep duration will reflect the additional hour gained during the transition (9 hours of actual sleep), while the onset/wakeup times show the wall-clock times (10:00 PM and 6:00 AM).

Supported Timezones

noctsleepy supports timezones across many regions, including:

  • North America: us_eastern, us_central, us_mountain, us_pacific, us_alaska, us_hawaii, canada_eastern, mexico_central, etc.
  • Europe: europe_london, europe_paris, europe_berlin, europe_rome, europe_moscow, etc.
  • Asia: asia_tokyo, asia_shanghai, asia_kolkata, asia_singapore, asia_dubai, etc.
  • South America: brazil_eastern, argentina, chile, colombia, etc.
  • Africa: africa_cairo, africa_johannesburg, africa_nairobi, africa_lagos, etc.
  • Oceania: australia_sydney, australia_melbourne, new_zealand, pacific_fiji, etc.

For a complete list of supported timezones, run:

noctsleepy compute-metrics --help

Output Format

Results are automatically saved as a JSON file in the same directory as the input file, containing both per night statistics and summary statistics.

Support

For questions, bug reports, or feature requests, please open an issue on GitHub.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

noctsleepy-0.1.1.tar.gz (314.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

noctsleepy-0.1.1-py3-none-any.whl (27.6 kB view details)

Uploaded Python 3

File details

Details for the file noctsleepy-0.1.1.tar.gz.

File metadata

  • Download URL: noctsleepy-0.1.1.tar.gz
  • Upload date:
  • Size: 314.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.26 {"installer":{"name":"uv","version":"0.9.26","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for noctsleepy-0.1.1.tar.gz
Algorithm Hash digest
SHA256 4e4e087ff5ed9b99f6d8beac5d90873dda0f3fae2b2978b9c5d4b9b21fa79368
MD5 4b3af5c9c094b469607384e1b63f918b
BLAKE2b-256 4d0184ea89138a659d9e8e742c425aa390805e115e030ad4312edd4ef1a5315d

See more details on using hashes here.

File details

Details for the file noctsleepy-0.1.1-py3-none-any.whl.

File metadata

  • Download URL: noctsleepy-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 27.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.26 {"installer":{"name":"uv","version":"0.9.26","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for noctsleepy-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 62fa4f9d8e4c633979b967c0689a8ef1a35fb7354717d6542464533808f8d3c5
MD5 1c9e33f86b563eba61eb553c7f79798f
BLAKE2b-256 a3d8b88d3f0ebd3cadaba4cfff41e0f781bdddc3bef94da21c05403d18572be0

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page