\n",
" \n",
"Note: An inertial measurement unit (IMU) is a sensor that measures a body's acceleration (using accelerometers) and angular rate (using gyroscopes). In medical and psychological applications IMUs are commonly used for activity monitoring, movement analysis, and many more.\n",
" \n",
"
"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Setup and Helper Functions"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from pathlib import Path\n",
"\n",
"import pandas as pd\n",
"import numpy as np\n",
"\n",
"from fau_colors import cmaps\n",
"import biopsykit as bp\n",
"\n",
"import matplotlib.pyplot as plt\n",
"import seaborn as sns\n",
"\n",
"%matplotlib widget\n",
"%load_ext autoreload\n",
"%autoreload 2"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"plt.close(\"all\")\n",
"\n",
"palette = sns.color_palette(cmaps.faculties)\n",
"sns.set_theme(context=\"notebook\", style=\"ticks\", font=\"sans-serif\", palette=palette)\n",
"\n",
"plt.rcParams[\"figure.figsize\"] = (8, 4)\n",
"plt.rcParams[\"pdf.fonttype\"] = 42\n",
"plt.rcParams[\"mathtext.default\"] = \"regular\"\n",
"\n",
"palette"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def display_dict_structure(dict_to_display):\n",
" _display_dict_recursive(dict_to_display)\n",
"\n",
"\n",
"def _display_dict_recursive(dict_to_display):\n",
" if isinstance(dict_to_display, dict):\n",
" display(dict_to_display.keys())\n",
" _display_dict_recursive(list(dict_to_display.values())[0])\n",
" else:\n",
" display(\"Dataframe shape: {}\".format(dict_to_display.shape))\n",
" display(dict_to_display.head())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Load Dataset"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Example dataset\n",
"data, fs = bp.example_data.get_sleep_imu_example()\n",
"\n",
"### Alternatively: Load your own dataset\n",
"# data, fs = bp.io.nilspod.load_dataset_nilspod(\"\") # or any other way to load a file containing IMU data"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"data.head()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Plot IMU Data"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"fig, ax = bp.sleep.plotting.sleep_imu_plot(data, downsample_factor=5 * fs)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Compute Sleep Endpoints"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The Sleep Processing Pipeline (which is performed in [sleep_processing_pipeline.predict_pipeline_acceleration()](https://biopsykit.readthedocs.io/en/latest/api/biopsykit.sleep.sleep_processing_pipeline.sleep_processing_pipeline.html#biopsykit.sleep.sleep_processing_pipeline.sleep_processing_pipeline.predict_pipeline_acceleration) consists of the following steps:\n",
"\n",
"1. **Activity Count Conversion**: Convert (3-axis) raw acceleration data into activity counts. Most sleep/wake detection algorithms use activity counts (as typically provided by Actigraphs) as input data. \n",
"1. **Wear Detection**: Detect wear and non-wear periods. Afterwards, cut data to longest continuous wear block. \n",
"1. **Rest Periods**: Detect rest periods, i.e., periods with large physical inactivity. The longest continuous rest period (*Major Rest Period*) is used to determine the *Bed Interval*, i.e., the period spent in bed. \n",
"1. **Sleep/Wake Detection**: Apply sleep/wake detection to classify phases of sleep and wake. \n",
"1. **Sleep Endpoint Computation**: Compute Sleep Endpoints from sleep/wake detection results and bed interval. The following sleep endpoints are supported:\n",
" * `date`: Date of the sleep recording. \n",
" **Note**: By convention, this field will return the *previous* day if the Bed Interval started *after* 12 a.m., i.e. the subject went to bed after midnight. By this convention, one always night always spans *two days*.\n",
" * `sleep_onset`: Sleep Onset, i.e., time of falling asleep (when *first* sleep phase started), in absolute time\n",
" * `wake_onset`: Wake Onset, i.e., time of awakening (*last* sleep phase ended), in absolute time\n",
" * `total_sleep_duration`: Total duration spent sleeping, i.e., the duration between *Sleep Onset* and *Wake Onset*, in minutes\n",
" * `net_sleep_duration`: Net duration spent sleeping, in minutes\n",
" * `bed_interval_start`: Bed Interval Start, i.e., time when subject went to bed, in absolute time\n",
" * `bed_interval_end`: Bed Interval End, i.e., time when subject left bed, in absolute time\n",
" * `sleep_efficiency`: Ratio of `net_sleep_duration`, i.e., the time actually spent sleeping and `total_sleep_duration`, i.e., the total time between *Sleep Onset* and *Wake Onset*, in percent\n",
" * `sleep_onset_latency`: Sleep Onset Latency, i.e., time in bed needed to fall asleep (difference between *Sleep Onset* and *Bed Interval Start*), in minutes\n",
" * `getup_latency`: Getup Latency, i.e., time in bed after awakening until getting up (difference between *Bed Interval End* and *Wake Onset*), in minutes\n",
" * `wake_after_sleep_onset`: Wake After Sleep Onset (WASO), i.e., total duration awake after falling asleep (after *Sleep Onset* and before *Wake Onset*), in minutes\n",
" * `sleep_bouts`: List with start and end times of sleep bouts\n",
" * `wake_bouts`: List with start and end times of wake bouts\n",
" * `number_wake_bouts`: Total number of wake bouts\n",
" "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The results are stored in a dictionary:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"sleep_results = bp.sleep.sleep_processing_pipeline.predict_pipeline_acceleration(\n",
" data, sampling_rate=fs, epoch_length=60\n",
")\n",
"sleep_endpoints = sleep_results[\"sleep_endpoints\"]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"sleep_endpoints.keys()"
]
},
{
"cell_type": "markdown",
"metadata": {
"tags": []
},
"source": [
"## Plot IMU Data with Sleep Endpoints"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Cut Data to Wear Period"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"For nicer visualization the IMU data are cut to the longest wear period before plotting:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"wear_detection = bp.signals.imu.wear_detection.WearDetection(sampling_rate=fs)\n",
"data = wear_detection.cut_to_wear_block(data, sleep_results[\"major_wear_block\"])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"df = bp.sleep.sleep_endpoints.endpoints_as_df(sleep_endpoints)\n",
"df"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note: See Documentation for [wear_detection.WearDetection()](https://biopsykit.readthedocs.io/en/latest/api/biopsykit.signals.imu.wear_detection.html#biopsykit.signals.imu.wear_detection.WearDetection) and [sleep_endpoints.endpoints_as_df()](https://biopsykit.readthedocs.io/en/latest/api/biopsykit.sleep.sleep_endpoints.html#biopsykit.sleep.sleep_endpoints.endpoints_as_df) for further information of the used functions."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Plot Sleep Data"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"tags": [
"nbsphinx-thumbnail"
]
},
"outputs": [],
"source": [
"fig, ax = bp.sleep.plotting.sleep_imu_plot(data, sleep_endpoints=sleep_endpoints, downsample_factor=5 * fs)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note: See Documentation for [sleep.plotting.sleep_imu_plot()](https://biopsykit.readthedocs.io/en/latest/api/biopsykit.sleep.plotting.html#biopsykit.sleep.plotting.sleep_imu_plot) for further information of the used functions."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Export Sleep Endpoints"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# bp.io.sleep.save_sleep_endpoints(\"../example_data/sleep_endpoints.csv\", df)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note: See Documentation for [save_sleep_endpoints()](https://biopsykit.readthedocs.io/en/latest/api/biopsykit.io.sleep.html#biopsykit.io.sleep.save_sleep_endpoints) for further information of the used functions."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "biopsykit",
"language": "python",
"name": "biopsykit"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.13"
}
},
"nbformat": 4,
"nbformat_minor": 4
}